blob: 1e33f1ed10fc753b19fb3ee30089678cf3565dbf [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);
Simon Pilgrim011381d2015-06-13 14:08:15 +0000258 SDValue visitBSWAP(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000265 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
Simon Pilgrime0541992015-05-21 10:05:03 +0000272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000274 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000279 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000282 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
301 SDValue visitSTORE(SDNode *N);
302 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304 SDValue visitBUILD_VECTOR(SDNode *N);
305 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000307 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +0000308 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000309 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000310 SDValue visitMLOAD(SDNode *N);
311 SDValue visitMSTORE(SDNode *N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000312 SDValue visitMGATHER(SDNode *N);
313 SDValue visitMSCATTER(SDNode *N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +0000314 SDValue visitFP_TO_FP16(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000315
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +0000316 SDValue visitFADDForFMACombine(SDNode *N);
317 SDValue visitFSUBForFMACombine(SDNode *N);
318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000319 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000321
Matt Arsenault985b9de2014-03-17 18:58:01 +0000322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000328 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000329 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000331 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000332
333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
334 SDValue &CC) const;
335 bool isOneUseSetCC(SDValue N) const;
336
Scott Michelcf0da6c2009-02-17 22:15:04 +0000337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000338 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000340 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000341 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000342 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000343 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000344 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000345 SDValue BuildReciprocalEstimate(SDValue Op);
346 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000347 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000349 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350 bool DemandHighBits = true);
351 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000352 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353 SDValue InnerPos, SDValue InnerNeg,
354 unsigned PosOpcode, unsigned NegOpcode,
355 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000356 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000357 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000358 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000359 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000360 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000361 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000362
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000363 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000364
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000365 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000366 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000367 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000368 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000369
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000370 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000371 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000372
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000373 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000375 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000376
Sanjay Patel37c41c12015-01-22 18:21:26 +0000377 /// Holds a pointer to an LSBaseSDNode as well as information on where it
378 /// is located in a sequence of memory operations connected by a chain.
379 struct MemOpLink {
380 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382 // Ptr to the mem node.
383 LSBaseSDNode *MemNode;
384 // Offset from the base ptr.
385 int64_t OffsetFromBase;
386 // What is the sequence number of this mem node.
387 // Lowest mem operand in the DAG starts at zero.
388 unsigned SequenceNum;
389 };
390
391 /// This is a helper function for MergeConsecutiveStores. When the source
392 /// elements of the consecutive stores are all constants or all extracted
393 /// vector elements, try to merge them into one larger store.
394 /// \return True if a merged store was created.
395 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000396 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000397 bool IsConstantSrc, bool UseVector);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +0000398
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000399 /// Merge consecutive store operations into a wide store.
400 /// This optimization uses wide integers or vectors when possible.
401 /// \return True if some memory operations were changed.
402 bool MergeConsecutiveStores(StoreSDNode *N);
403
Adam Nemet67483892014-03-04 23:28:31 +0000404 /// \brief Try to transform a truncation where C is a constant:
405 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
406 ///
407 /// \p N needs to be a truncation and its first operand an AND. Other
408 /// requirements are checked by the function (e.g. that trunc is
409 /// single-use) and if missed an empty SDValue is returned.
410 SDValue distributeTruncateThroughAnd(SDNode *N);
411
Chris Lattner4041ab62010-04-15 04:48:01 +0000412 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000413 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000414 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
415 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000416 auto *F = DAG.getMachineFunction().getFunction();
417 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
418 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000419 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000420
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000421 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000422 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000423
Chris Lattner4041ab62010-04-15 04:48:01 +0000424 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000425
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000426 /// Returns a type large enough to hold any valid shift amount - before type
427 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000428 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000429 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
430 if (LHSTy.isVector())
431 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000432 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
433 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000434 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000435
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000436 /// This method returns true if we are running before type legalization or
437 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000438 bool isTypeLegal(const EVT &VT) {
439 if (!LegalTypes) return true;
440 return TLI.isTypeLegal(VT);
441 }
Matt Arsenault758659232013-05-18 00:21:46 +0000442
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000443 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000444 EVT getSetCCResultType(EVT VT) const {
445 return TLI.getSetCCResultType(*DAG.getContext(), VT);
446 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000447 };
448}
449
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000450
451namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000452/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000453/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000454class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000455 DAGCombiner &DC;
456public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000457 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000458 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000459
Craig Topper7b883b32014-03-08 06:31:39 +0000460 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000461 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000462 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000463};
464}
465
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000466//===----------------------------------------------------------------------===//
467// TargetLowering::DAGCombinerInfo implementation
468//===----------------------------------------------------------------------===//
469
470void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000471 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000472}
473
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000474void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000475 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000476}
477
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000478SDValue TargetLowering::DAGCombinerInfo::
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +0000479CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
Evan Chengfd81c732009-03-28 05:57:29 +0000480 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000481}
482
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000483SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000484CombineTo(SDNode *N, SDValue Res, bool AddTo) {
485 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000486}
487
488
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000489SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000490CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
491 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000492}
493
Dan Gohmane58ab792009-01-29 01:59:02 +0000494void TargetLowering::DAGCombinerInfo::
495CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
496 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
497}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000498
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000499//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000500// Helper Functions
501//===----------------------------------------------------------------------===//
502
Chandler Carruth18066972014-08-02 10:02:07 +0000503void DAGCombiner::deleteAndRecombine(SDNode *N) {
504 removeFromWorklist(N);
505
506 // If the operands of this node are only used by the node, they will now be
507 // dead. Make sure to re-visit them and recursively delete dead nodes.
508 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000509 // For an operand generating multiple values, one of the values may
510 // become dead allowing further simplification (e.g. split index
511 // arithmetic from an indexed load).
512 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000513 AddToWorklist(Op.getNode());
514
515 DAG.DeleteNode(N);
516}
517
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000518/// Return 1 if we can compute the negated form of the specified expression for
519/// the same cost as the expression itself, or 2 if we can compute the negated
520/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000521static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000522 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000523 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000524 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000525 // fneg is removable even if it has multiple uses.
526 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527
Chris Lattnere49c9742007-05-14 22:04:50 +0000528 // Don't allow anything with multiple uses.
529 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000530
Chris Lattner46980832007-05-25 02:19:06 +0000531 // Don't recurse exponentially.
532 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000533
Chris Lattnere49c9742007-05-14 22:04:50 +0000534 switch (Op.getOpcode()) {
535 default: return false;
536 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000537 // Don't invert constant FP values after legalize. The negated constant
538 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000539 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 case ISD::FADD:
541 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000542 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000543
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000544 // After operation legalization, it might not be legal to create new FSUBs.
545 if (LegalOperations &&
546 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
547 return 0;
548
Craig Topper03f39772012-09-09 22:58:45 +0000549 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000550 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
551 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000552 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000553 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000554 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000556 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000558 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559
Bill Wendling6fbf5492009-01-30 23:10:18 +0000560 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000561 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Chris Lattnere49c9742007-05-14 22:04:50 +0000563 case ISD::FMUL:
564 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000565 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000566
Bill Wendling6fbf5492009-01-30 23:10:18 +0000567 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000568 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
569 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000570 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000571
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000572 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000573 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574
Chris Lattnere49c9742007-05-14 22:04:50 +0000575 case ISD::FP_EXTEND:
576 case ISD::FP_ROUND:
577 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000578 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000579 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000580 }
581}
582
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000583/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000584static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000586 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 // fneg is removable even if it has multiple uses.
588 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589
Chris Lattnere49c9742007-05-14 22:04:50 +0000590 // Don't allow anything with multiple uses.
591 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000592
Chris Lattner46980832007-05-25 02:19:06 +0000593 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000594 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000595 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000596 case ISD::ConstantFP: {
597 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
598 V.changeSign();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000599 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
Dale Johannesen446b9002007-08-31 23:34:27 +0000600 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000601 case ISD::FADD:
602 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000603 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000604
Bill Wendling6fbf5492009-01-30 23:10:18 +0000605 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000606 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000607 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000608 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000609 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000610 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000611 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000612 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000613 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000614 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000615 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000616 Op.getOperand(0));
617 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000618 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000619 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000620
Bill Wendling6fbf5492009-01-30 23:10:18 +0000621 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000622 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Andrea Di Biagioeb331342015-06-05 10:29:55 +0000623 if (N0CFP->isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000624 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000625
Bill Wendling6fbf5492009-01-30 23:10:18 +0000626 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000627 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000628 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000629
Chris Lattnere49c9742007-05-14 22:04:50 +0000630 case ISD::FMUL:
631 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000632 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000633
Bill Wendling6fbf5492009-01-30 23:10:18 +0000634 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000635 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000636 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000637 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000638 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000639 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000640 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000641
Bill Wendling6fbf5492009-01-30 23:10:18 +0000642 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000643 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000644 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000645 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000646 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000647
Chris Lattnere49c9742007-05-14 22:04:50 +0000648 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000649 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000650 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000651 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000652 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000653 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000654 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000655 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000656 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000657 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000658 }
659}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000660
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000661// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000662// that selects between the target values used for true and false, making it
663// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
664// the appropriate nodes based on the type of node we are checking. This
665// simplifies life a bit for the callers.
666bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
667 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000668 if (N.getOpcode() == ISD::SETCC) {
669 LHS = N.getOperand(0);
670 RHS = N.getOperand(1);
671 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000672 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000673 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000674
675 if (N.getOpcode() != ISD::SELECT_CC ||
676 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
677 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
678 return false;
679
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000680 if (TLI.getBooleanContents(N.getValueType()) ==
681 TargetLowering::UndefinedBooleanContent)
682 return false;
683
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000684 LHS = N.getOperand(0);
685 RHS = N.getOperand(1);
686 CC = N.getOperand(4);
687 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000688}
689
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000690/// Return true if this is a SetCC-equivalent operation with only one use.
691/// If this is true, it allows the users to invert the operation for free when
692/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000693bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000694 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000695 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000696 return true;
697 return false;
698}
699
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000700/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000701/// elements are all the same constant or undefined.
702static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
703 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
704 if (!C)
705 return false;
706
707 APInt SplatUndef;
708 unsigned SplatBitSize;
709 bool HasAnyUndefs;
710 EVT EltVT = N->getValueType(0).getVectorElementType();
711 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
712 HasAnyUndefs) &&
713 EltVT.getSizeInBits() >= SplatBitSize);
714}
715
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000716// \brief Returns the SDNode if it is a constant integer BuildVector
717// or constant integer.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000718static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
719 if (isa<ConstantSDNode>(N))
720 return N.getNode();
721 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
722 return N.getNode();
723 return nullptr;
724}
725
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000726// \brief Returns the SDNode if it is a constant float BuildVector
727// or constant float.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000728static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
729 if (isa<ConstantFPSDNode>(N))
730 return N.getNode();
731 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
732 return N.getNode();
733 return nullptr;
734}
735
Matt Arsenault985b9de2014-03-17 18:58:01 +0000736// \brief Returns the SDNode if it is a constant splat BuildVector or constant
737// int.
738static ConstantSDNode *isConstOrConstSplat(SDValue N) {
739 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
740 return CN;
741
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000742 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000743 BitVector UndefElements;
744 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000745
746 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000747 // FIXME: We blindly ignore splats which include undef which is overly
748 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000749 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000750 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000751 return CN;
752 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000753
754 return nullptr;
755}
756
Matt Arsenault6cc00422014-08-16 10:14:19 +0000757// \brief Returns the SDNode if it is a constant splat BuildVector or constant
758// float.
759static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
760 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
761 return CN;
762
763 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
764 BitVector UndefElements;
765 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
766
Matt Arsenault965de302014-09-02 18:33:51 +0000767 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000768 return CN;
769 }
770
771 return nullptr;
772}
773
Andrew Trickef9de2a2013-05-25 02:42:55 +0000774SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000775 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000776 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000777 if (N0.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000778 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
779 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000780 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000781 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
Matthias Braunf50ab432015-01-13 22:17:46 +0000782 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
783 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000784 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000785 if (N0.hasOneUse()) {
786 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
787 // use
788 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
789 if (!OpNode.getNode())
790 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000791 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000792 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000793 }
794 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000795 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000796
Juergen Ributzka68402822014-01-13 21:49:25 +0000797 if (N1.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000798 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
799 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000800 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000801 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
Matthias Braunf50ab432015-01-13 22:17:46 +0000802 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
803 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000804 }
805 if (N1.hasOneUse()) {
806 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
807 // use
808 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
809 if (!OpNode.getNode())
810 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000811 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000812 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
813 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000814 }
815 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000817 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000818}
819
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000820SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
821 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000822 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
823 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000824 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000825 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000826 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000827 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000828 dbgs() << " and " << NumTo-1 << " other values\n");
829 for (unsigned i = 0, e = NumTo; i != e; ++i)
830 assert((!To[i].getNode() ||
831 N->getValueType(i) == To[i].getValueType()) &&
832 "Cannot combine value to value of different type!");
833
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000834 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000835 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000836 if (AddTo) {
837 // Push the new nodes and any users onto the worklist
838 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000839 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000840 AddToWorklist(To[i].getNode());
841 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000842 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000843 }
844 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000845
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000846 // Finally, if the node is now dead, remove it from the graph. The node
847 // may not be dead if the replacement process recursively simplified to
848 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000849 if (N->use_empty())
850 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000851 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000852}
853
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000854void DAGCombiner::
855CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000856 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000857 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000858 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000859 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000860
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000861 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000862 AddToWorklist(TLO.New.getNode());
863 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000864
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000865 // Finally, if the node is now dead, remove it from the graph. The node
866 // may not be dead if the replacement process recursively simplified to
867 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000868 if (TLO.Old.getNode()->use_empty())
869 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000870}
871
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000872/// Check the specified integer node value to see if it can be simplified or if
873/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000874bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000876 APInt KnownZero, KnownOne;
877 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
878 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000879
Dan Gohmane58ab792009-01-29 01:59:02 +0000880 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000881 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000882
Dan Gohmane58ab792009-01-29 01:59:02 +0000883 // Replace the old value with the new one.
884 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000885 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000886 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000887 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000888 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000889 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000890
Dan Gohmane58ab792009-01-29 01:59:02 +0000891 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000892 return true;
893}
894
Evan Cheng0abb54d2010-04-24 04:43:44 +0000895void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000896 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000897 EVT VT = Load->getValueType(0);
898 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000899
Evan Cheng0abb54d2010-04-24 04:43:44 +0000900 DEBUG(dbgs() << "\nReplacing.9 ";
901 Load->dump(&DAG);
902 dbgs() << "\nWith: ";
903 Trunc.getNode()->dump(&DAG);
904 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000905 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000906 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
907 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000908 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000909 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000910}
911
912SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
913 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000914 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000915 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000916 EVT MemVT = LD->getMemoryVT();
917 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000918 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
919 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000920 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000922 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000923 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000924 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000925 }
926
Evan Chenge19aa5c2010-04-19 19:29:22 +0000927 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000928 switch (Opc) {
929 default: break;
930 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000931 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000932 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000933 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000934 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000935 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000937 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000938 case ISD::Constant: {
939 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000940 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000941 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000942 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000943 }
944
945 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000946 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000947 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000948}
949
Evan Cheng0abb54d2010-04-24 04:43:44 +0000950SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000951 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
952 return SDValue();
953 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000954 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000955 bool Replace = false;
956 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000957 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000958 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000959 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000960
961 if (Replace)
962 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
963 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000964 DAG.getValueType(OldVT));
965}
966
Evan Cheng0abb54d2010-04-24 04:43:44 +0000967SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000968 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000969 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000970 bool Replace = false;
971 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000972 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000973 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000974 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000975
976 if (Replace)
977 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
978 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000979}
980
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000981/// Promote the specified integer binary operation if the target indicates it is
982/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
983/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000984SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
985 if (!LegalOperations)
986 return SDValue();
987
988 EVT VT = Op.getValueType();
989 if (VT.isVector() || !VT.isInteger())
990 return SDValue();
991
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000992 // If operation type is 'undesirable', e.g. i16 on x86, consider
993 // promoting it.
994 unsigned Opc = Op.getOpcode();
995 if (TLI.isTypeDesirableForOp(Opc, VT))
996 return SDValue();
997
Evan Chengaf56fac2010-04-16 06:14:10 +0000998 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000999 // Consult target whether it is a good idea to promote this operation and
1000 // what's the right type to promote it to.
1001 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +00001002 assert(PVT != VT && "Don't know what type to promote to!");
1003
Evan Cheng0abb54d2010-04-24 04:43:44 +00001004 bool Replace0 = false;
1005 SDValue N0 = Op.getOperand(0);
1006 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +00001007 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +00001008 return SDValue();
1009
Evan Cheng0abb54d2010-04-24 04:43:44 +00001010 bool Replace1 = false;
1011 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +00001012 SDValue NN1;
1013 if (N0 == N1)
1014 NN1 = NN0;
1015 else {
1016 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +00001017 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +00001018 return SDValue();
1019 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001020
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001021 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001022 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001023 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001024
1025 if (Replace0)
1026 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1027 if (Replace1)
1028 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001029
Evan Chenge8136902010-04-27 19:48:13 +00001030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001032 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001033 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001034 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001035 }
1036 return SDValue();
1037}
1038
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001039/// Promote the specified integer shift operation if the target indicates it is
1040/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1041/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001042SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1043 if (!LegalOperations)
1044 return SDValue();
1045
1046 EVT VT = Op.getValueType();
1047 if (VT.isVector() || !VT.isInteger())
1048 return SDValue();
1049
1050 // If operation type is 'undesirable', e.g. i16 on x86, consider
1051 // promoting it.
1052 unsigned Opc = Op.getOpcode();
1053 if (TLI.isTypeDesirableForOp(Opc, VT))
1054 return SDValue();
1055
1056 EVT PVT = VT;
1057 // Consult target whether it is a good idea to promote this operation and
1058 // what's the right type to promote it to.
1059 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1060 assert(PVT != VT && "Don't know what type to promote to!");
1061
Evan Cheng0abb54d2010-04-24 04:43:44 +00001062 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001063 SDValue N0 = Op.getOperand(0);
1064 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001065 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001066 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001067 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001068 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001069 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001070 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001071 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001072
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001073 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001074 if (Replace)
1075 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001076
Evan Chenge8136902010-04-27 19:48:13 +00001077 DEBUG(dbgs() << "\nPromoting ";
1078 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001079 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001080 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001081 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001082 }
1083 return SDValue();
1084}
1085
Evan Chenge19aa5c2010-04-19 19:29:22 +00001086SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1087 if (!LegalOperations)
1088 return SDValue();
1089
1090 EVT VT = Op.getValueType();
1091 if (VT.isVector() || !VT.isInteger())
1092 return SDValue();
1093
1094 // If operation type is 'undesirable', e.g. i16 on x86, consider
1095 // promoting it.
1096 unsigned Opc = Op.getOpcode();
1097 if (TLI.isTypeDesirableForOp(Opc, VT))
1098 return SDValue();
1099
1100 EVT PVT = VT;
1101 // Consult target whether it is a good idea to promote this operation and
1102 // what's the right type to promote it to.
1103 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1104 assert(PVT != VT && "Don't know what type to promote to!");
1105 // fold (aext (aext x)) -> (aext x)
1106 // fold (aext (zext x)) -> (zext x)
1107 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001108 DEBUG(dbgs() << "\nPromoting ";
1109 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001110 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001111 }
1112 return SDValue();
1113}
1114
1115bool DAGCombiner::PromoteLoad(SDValue Op) {
1116 if (!LegalOperations)
1117 return false;
1118
1119 EVT VT = Op.getValueType();
1120 if (VT.isVector() || !VT.isInteger())
1121 return false;
1122
1123 // If operation type is 'undesirable', e.g. i16 on x86, consider
1124 // promoting it.
1125 unsigned Opc = Op.getOpcode();
1126 if (TLI.isTypeDesirableForOp(Opc, VT))
1127 return false;
1128
1129 EVT PVT = VT;
1130 // Consult target whether it is a good idea to promote this operation and
1131 // what's the right type to promote it to.
1132 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1133 assert(PVT != VT && "Don't know what type to promote to!");
1134
Andrew Trickef9de2a2013-05-25 02:42:55 +00001135 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001136 SDNode *N = Op.getNode();
1137 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001138 EVT MemVT = LD->getMemoryVT();
1139 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001140 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1141 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001142 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001143 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001144 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001145 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001146 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1147
Evan Cheng0abb54d2010-04-24 04:43:44 +00001148 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001149 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001150 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001151 Result.getNode()->dump(&DAG);
1152 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001153 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001154 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1155 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001156 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001157 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001158 return true;
1159 }
1160 return false;
1161}
1162
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001163/// \brief Recursively delete a node which has no uses and any operands for
1164/// which it is the only use.
1165///
1166/// Note that this both deletes the nodes and removes them from the worklist.
1167/// It also adds any nodes who have had a user deleted to the worklist as they
1168/// may now have only one use and subject to other combines.
1169bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1170 if (!N->use_empty())
1171 return false;
1172
1173 SmallSetVector<SDNode *, 16> Nodes;
1174 Nodes.insert(N);
1175 do {
1176 N = Nodes.pop_back_val();
1177 if (!N)
1178 continue;
1179
1180 if (N->use_empty()) {
1181 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1182 Nodes.insert(N->getOperand(i).getNode());
1183
1184 removeFromWorklist(N);
1185 DAG.DeleteNode(N);
1186 } else {
1187 AddToWorklist(N);
1188 }
1189 } while (!Nodes.empty());
1190 return true;
1191}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001192
Chris Lattnere49c9742007-05-14 22:04:50 +00001193//===----------------------------------------------------------------------===//
1194// Main DAG Combiner implementation
1195//===----------------------------------------------------------------------===//
1196
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001197void DAGCombiner::Run(CombineLevel AtLevel) {
1198 // set the instance variables, so that the various visit routines may use it.
1199 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001200 LegalOperations = Level >= AfterLegalizeVectorOps;
1201 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001202
Evan Cheng5e7658c2008-08-29 22:21:44 +00001203 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001204 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1205 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001206 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001207
Evan Cheng5e7658c2008-08-29 22:21:44 +00001208 // Create a dummy node (which is not added to allnodes), that adds a reference
1209 // to the root node, preventing it from being deleted, and tracking any
1210 // changes of the root.
1211 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001212
James Molloy67b6b112012-02-16 09:17:04 +00001213 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001214 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001215 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001216 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001217 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001218 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001219 N = Worklist.pop_back_val();
1220 } while (!N);
1221
1222 bool GoodWorklistEntry = WorklistMap.erase(N);
1223 (void)GoodWorklistEntry;
1224 assert(GoodWorklistEntry &&
1225 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001226
Evan Cheng5e7658c2008-08-29 22:21:44 +00001227 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1228 // N is deleted from the DAG, since they too may now be dead or may have a
1229 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001230 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001231 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001232
1233 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001234
Chandler Carruth411fb402014-07-26 05:49:40 +00001235 // If this combine is running after legalizing the DAG, re-legalize any
1236 // nodes pulled off the worklist.
1237 if (Level == AfterLegalizeDAG) {
1238 SmallSetVector<SDNode *, 16> UpdatedNodes;
1239 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1240
1241 for (SDNode *LN : UpdatedNodes) {
1242 AddToWorklist(LN);
1243 AddUsersToWorklist(LN);
1244 }
1245 if (!NIsValid)
1246 continue;
1247 }
1248
Chandler Carruthb1432742014-07-28 17:55:07 +00001249 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1250
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001251 // Add any operands of the new node which have not yet been combined to the
1252 // worklist as well. Because the worklist uniques things already, this
1253 // won't repeatedly process the same operand.
1254 CombinedNodes.insert(N);
1255 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1256 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1257 AddToWorklist(N->getOperand(i).getNode());
1258
Evan Cheng5e7658c2008-08-29 22:21:44 +00001259 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001260
Craig Topperc0196b12014-04-14 00:51:57 +00001261 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001262 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001263
Evan Cheng5e7658c2008-08-29 22:21:44 +00001264 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001265
Evan Cheng5e7658c2008-08-29 22:21:44 +00001266 // If we get back the same node we passed in, rather than a new node or
1267 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001268 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001269 // mechanics for us, we have no work to do in this case.
1270 if (RV.getNode() == N)
1271 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001272
Evan Cheng5e7658c2008-08-29 22:21:44 +00001273 assert(N->getOpcode() != ISD::DELETED_NODE &&
1274 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1275 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001276
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001277 DEBUG(dbgs() << " ... into: ";
1278 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001279
Devang Patelefec7712011-05-23 22:04:42 +00001280 // Transfer debug value.
1281 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001282 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001283 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001284 else {
1285 assert(N->getValueType(0) == RV.getValueType() &&
1286 N->getNumValues() == 1 && "Type mismatch");
1287 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001288 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001289 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001290
Evan Cheng5e7658c2008-08-29 22:21:44 +00001291 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001292 AddToWorklist(RV.getNode());
1293 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001294
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001295 // Finally, if the node is now dead, remove it from the graph. The node
1296 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001297 // something else needing this node. This will also take care of adding any
1298 // operands which have lost a user to the worklist.
1299 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001301
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001302 // If the root changed (e.g. it was a dead load, update the root).
1303 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001304 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001305}
1306
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001307SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001308 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001309 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001310 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001311 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001312 case ISD::ADD: return visitADD(N);
1313 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001314 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001315 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001316 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001317 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001318 case ISD::MUL: return visitMUL(N);
1319 case ISD::SDIV: return visitSDIV(N);
1320 case ISD::UDIV: return visitUDIV(N);
1321 case ISD::SREM: return visitSREM(N);
1322 case ISD::UREM: return visitUREM(N);
1323 case ISD::MULHU: return visitMULHU(N);
1324 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001325 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1326 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001327 case ISD::SMULO: return visitSMULO(N);
1328 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001329 case ISD::SDIVREM: return visitSDIVREM(N);
1330 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001331 case ISD::AND: return visitAND(N);
1332 case ISD::OR: return visitOR(N);
1333 case ISD::XOR: return visitXOR(N);
1334 case ISD::SHL: return visitSHL(N);
1335 case ISD::SRA: return visitSRA(N);
1336 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001337 case ISD::ROTR:
1338 case ISD::ROTL: return visitRotate(N);
Simon Pilgrim011381d2015-06-13 14:08:15 +00001339 case ISD::BSWAP: return visitBSWAP(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001340 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001341 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001342 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001343 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001344 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001345 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001346 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001347 case ISD::SELECT_CC: return visitSELECT_CC(N);
1348 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001349 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1350 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001351 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001352 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
Simon Pilgrime0541992015-05-21 10:05:03 +00001353 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001354 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001355 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001356 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001357 case ISD::FADD: return visitFADD(N);
1358 case ISD::FSUB: return visitFSUB(N);
1359 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001360 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001361 case ISD::FDIV: return visitFDIV(N);
1362 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001363 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001364 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001365 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1366 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1367 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1368 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1369 case ISD::FP_ROUND: return visitFP_ROUND(N);
1370 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1371 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1372 case ISD::FNEG: return visitFNEG(N);
1373 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001374 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001375 case ISD::FMINNUM: return visitFMINNUM(N);
1376 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001377 case ISD::FCEIL: return visitFCEIL(N);
1378 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001379 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001380 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001381 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001382 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001383 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001384 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001385 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1386 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001387 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001388 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +00001389 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001390 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001391 case ISD::MGATHER: return visitMGATHER(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001392 case ISD::MLOAD: return visitMLOAD(N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001393 case ISD::MSCATTER: return visitMSCATTER(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001394 case ISD::MSTORE: return visitMSTORE(N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00001395 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001396 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001397 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001398}
1399
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001400SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001401 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001402
1403 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001404 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001405 assert(N->getOpcode() != ISD::DELETED_NODE &&
1406 "Node was deleted but visit returned NULL!");
1407
1408 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1409 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1410
1411 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001412 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001413 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001414
1415 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1416 }
1417 }
1418
Evan Chengf1005572010-04-28 07:10:39 +00001419 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001420 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001421 switch (N->getOpcode()) {
1422 default: break;
1423 case ISD::ADD:
1424 case ISD::SUB:
1425 case ISD::MUL:
1426 case ISD::AND:
1427 case ISD::OR:
1428 case ISD::XOR:
1429 RV = PromoteIntBinOp(SDValue(N, 0));
1430 break;
1431 case ISD::SHL:
1432 case ISD::SRA:
1433 case ISD::SRL:
1434 RV = PromoteIntShiftOp(SDValue(N, 0));
1435 break;
1436 case ISD::SIGN_EXTEND:
1437 case ISD::ZERO_EXTEND:
1438 case ISD::ANY_EXTEND:
1439 RV = PromoteExtend(SDValue(N, 0));
1440 break;
1441 case ISD::LOAD:
1442 if (PromoteLoad(SDValue(N, 0)))
1443 RV = SDValue(N, 0);
1444 break;
1445 }
1446 }
1447
Scott Michelcf0da6c2009-02-17 22:15:04 +00001448 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001449 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001450 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001451 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001452 SDValue N0 = N->getOperand(0);
1453 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001454
Evan Cheng31604a62008-03-22 01:55:50 +00001455 // Constant operands are canonicalized to RHS.
1456 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001457 SDValue Ops[] = {N1, N0};
1458 SDNode *CSENode;
Nick Lewycky37a17502015-05-13 23:41:47 +00001459 if (const BinaryWithFlagsSDNode *BinNode =
1460 dyn_cast<BinaryWithFlagsSDNode>(N)) {
NAKAMURA Takumid7c0be92015-05-06 14:03:12 +00001461 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
Nick Lewycky37a17502015-05-13 23:41:47 +00001462 BinNode->Flags.hasNoUnsignedWrap(),
1463 BinNode->Flags.hasNoSignedWrap(),
1464 BinNode->Flags.hasExact());
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001465 } else {
1466 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1467 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001468 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001470 }
1471 }
1472
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001473 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001474}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001475
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001476/// Given a node, return its input chain if it has one, otherwise return a null
1477/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001478static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001479 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001480 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001481 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001482 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001483 return N->getOperand(NumOps-1);
1484 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001485 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001486 return N->getOperand(i);
1487 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001488 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001489}
1490
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001491SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001492 // If N has two operands, where one has an input chain equal to the other,
1493 // the 'other' chain is redundant.
1494 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001495 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001496 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001497 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001498 return N->getOperand(1);
1499 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001500
Chris Lattner48fb92f2007-05-16 06:37:59 +00001501 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001502 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001503 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001504 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001505
Jim Laskey708d0db2006-10-04 16:53:27 +00001506 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001507 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001508
Jim Laskey0463e082006-10-07 23:37:56 +00001509 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001510 // encountered.
1511 for (unsigned i = 0; i < TFs.size(); ++i) {
1512 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001513
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 // Check each of the operands.
1515 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001516 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001517
Jim Laskey708d0db2006-10-04 16:53:27 +00001518 switch (Op.getOpcode()) {
1519 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001520 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001521 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001522 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001523 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001524
Jim Laskey708d0db2006-10-04 16:53:27 +00001525 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001526 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001527 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001528 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001529 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001530 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001531 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001532 Changed = true;
1533 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001534 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001535 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001536
Jim Laskey708d0db2006-10-04 16:53:27 +00001537 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001538 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001539 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001540 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001541 else
1542 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001543 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001544 }
1545 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001546 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001547
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001548 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001549
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001550 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001551 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001552 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001553 // The entry token is the only possible outcome.
1554 Result = DAG.getEntryNode();
1555 } else {
1556 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001557 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001558 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001559
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001560 // Add users to worklist if AA is enabled, since it may introduce
1561 // a lot of new chained token factors while removing memory deps.
1562 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1563 : DAG.getSubtarget().useAA();
1564 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001565 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001566
Jim Laskey708d0db2006-10-04 16:53:27 +00001567 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001568}
1569
Chris Lattneree322b42008-02-13 07:25:05 +00001570/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001571SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001572 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001573 // Replacing results may cause a different MERGE_VALUES to suddenly
1574 // be CSE'd with N, and carry its uses with it. Iterate until no
1575 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001576 // First add the users of this node to the work list so that they
1577 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001578 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001579 do {
1580 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001581 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001582 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001583 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001584 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001585}
1586
Matthias Braun1505efb2015-05-18 23:07:27 +00001587static bool isNullConstant(SDValue V) {
1588 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1589 return Const != nullptr && Const->isNullValue();
1590}
1591
Andrea Di Biagio9ac8a6b2015-06-04 19:15:01 +00001592static bool isNullFPConstant(SDValue V) {
1593 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1594 return Const != nullptr && Const->isZero() && !Const->isNegative();
1595}
1596
Matthias Braun03312192015-05-19 00:25:20 +00001597static bool isAllOnesConstant(SDValue V) {
1598 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1599 return Const != nullptr && Const->isAllOnesValue();
1600}
1601
Matthias Braun887fdfb2015-05-19 00:25:21 +00001602static bool isOneConstant(SDValue V) {
1603 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1604 return Const != nullptr && Const->isOne();
1605}
1606
Matthias Braun56a78142015-05-20 18:54:02 +00001607/// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1608/// ContantSDNode pointer else nullptr.
1609static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1610 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1611 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1612}
1613
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001614SDValue DAGCombiner::visitADD(SDNode *N) {
1615 SDValue N0 = N->getOperand(0);
1616 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001617 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001618
1619 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001620 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001621 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1622 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001623
1624 // fold (add x, 0) -> x, vector edition
1625 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1626 return N0;
1627 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1628 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001629 }
Bill Wendling0864a752008-12-10 22:36:00 +00001630
Dan Gohman06563a82007-07-03 14:03:57 +00001631 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001632 if (N0.getOpcode() == ISD::UNDEF)
1633 return N0;
1634 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001635 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001636 // fold (add c1, c2) -> c1+c2
Matthias Braun56a78142015-05-20 18:54:02 +00001637 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1638 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001639 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001640 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001641 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00001642 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1643 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001644 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001645 // fold (add x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00001646 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00001647 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001648 // fold (add Sym, c) -> Sym+c
1649 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001650 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001651 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001652 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001653 GA->getOffset() +
1654 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001655 // fold ((c1-A)+c2) -> (c1+c2)-A
1656 if (N1C && N0.getOpcode() == ISD::SUB)
Matthias Braun56a78142015-05-20 18:54:02 +00001657 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001658 SDLoc DL(N);
1659 return DAG.getNode(ISD::SUB, DL, VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001660 DAG.getConstant(N1C->getAPIntValue()+
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001661 N0C->getAPIntValue(), DL, VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001662 N0.getOperand(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001663 }
Nate Begeman22e251a2006-02-03 06:46:56 +00001664 // reassociate add
Simon Pilgrimd15c2802015-03-29 16:49:51 +00001665 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00001666 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001667 // fold ((0-A) + B) -> B-A
Matthias Braun1505efb2015-05-18 23:07:27 +00001668 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001669 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001670 // fold (A + (0-B)) -> A-B
Matthias Braun1505efb2015-05-18 23:07:27 +00001671 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001672 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001673 // fold (A+(B-A)) -> B
1674 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001675 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001676 // fold ((B-A)+A) -> B
1677 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1678 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001679 // fold (A+(B-(A+C))) to (B-C)
1680 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001681 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001683 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001684 // fold (A+(B-(C+A))) to (B-C)
1685 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001686 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001688 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001689 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001690 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1691 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001692 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001693 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001694 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001695
Dale Johannesen8c766702008-12-02 01:30:54 +00001696 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1697 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1698 SDValue N00 = N0.getOperand(0);
1699 SDValue N01 = N0.getOperand(1);
1700 SDValue N10 = N1.getOperand(0);
1701 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001702
1703 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001704 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1705 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1706 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001707 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001708
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001709 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1710 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001711
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001712 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001713 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001714 APInt LHSZero, LHSOne;
1715 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001716 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001717
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001718 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001719 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001720
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001721 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1722 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001723 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1724 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1725 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1726 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001727 }
1728 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001729
Dan Gohman954f4902010-01-19 23:30:49 +00001730 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
Matthias Braun0542b5d2015-05-19 00:25:17 +00001731 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1732 isNullConstant(N1.getOperand(0).getOperand(0)))
1733 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1734 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1735 N1.getOperand(0).getOperand(1),
1736 N1.getOperand(1)));
1737 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1738 isNullConstant(N0.getOperand(0).getOperand(0)))
1739 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1740 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1741 N0.getOperand(0).getOperand(1),
1742 N0.getOperand(1)));
Dan Gohman954f4902010-01-19 23:30:49 +00001743
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001744 if (N1.getOpcode() == ISD::AND) {
1745 SDValue AndOp0 = N1.getOperand(0);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001746 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1747 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001748
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001749 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1750 // and similar xforms where the inner op is either ~0 or 0.
Matthias Braun887fdfb2015-05-19 00:25:21 +00001751 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001753 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1754 }
1755 }
1756
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001757 // add (sext i1), X -> sub X, (zext i1)
1758 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1759 N0.getOperand(0).getValueType() == MVT::i1 &&
1760 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001761 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001762 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1763 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1764 }
1765
Jan Veselyaf62cf42014-10-17 14:45:25 +00001766 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1767 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1768 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1769 if (TN->getVT() == MVT::i1) {
1770 SDLoc DL(N);
1771 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001772 DAG.getConstant(1, DL, VT));
Jan Veselyaf62cf42014-10-17 14:45:25 +00001773 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1774 }
1775 }
1776
Evan Chengf1005572010-04-28 07:10:39 +00001777 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001778}
1779
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001780SDValue DAGCombiner::visitADDC(SDNode *N) {
1781 SDValue N0 = N->getOperand(0);
1782 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001783 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001784
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001785 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001786 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001787 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001788 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001789 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001790
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001791 // canonicalize constant to RHS.
Matthias Braun00a40762015-02-24 18:52:01 +00001792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001794 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001795 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001796
Chris Lattner47206662007-03-04 20:40:38 +00001797 // fold (addc x, 0) -> x + no carry out
Matthias Braun1505efb2015-05-18 23:07:27 +00001798 if (isNullConstant(N1))
Dale Johannesen5234d372009-06-02 03:12:52 +00001799 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001800 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001801
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001802 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001803 APInt LHSZero, LHSOne;
1804 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001805 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001806
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001807 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001808 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001809
Chris Lattner47206662007-03-04 20:40:38 +00001810 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1811 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001812 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001813 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001814 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001815 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001816 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001817
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001818 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001819}
1820
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001821SDValue DAGCombiner::visitADDE(SDNode *N) {
1822 SDValue N0 = N->getOperand(0);
1823 SDValue N1 = N->getOperand(1);
1824 SDValue CarryIn = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001825
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001826 // canonicalize constant to RHS
Matthias Braun00a40762015-02-24 18:52:01 +00001827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001829 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001830 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001831 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001832
Chris Lattner47206662007-03-04 20:40:38 +00001833 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001834 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001835 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001836
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001837 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001838}
1839
Eric Christophere5ca1e02011-02-16 04:50:12 +00001840// Since it may not be valid to emit a fold to zero for vector initializers
1841// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001842static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001843 SelectionDAG &DAG,
1844 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001845 if (!VT.isVector())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001846 return DAG.getConstant(0, DL, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001847 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001848 return DAG.getConstant(0, DL, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001849 return SDValue();
1850}
1851
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001852SDValue DAGCombiner::visitSUB(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001855 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001856
Dan Gohmana8665142007-06-25 16:23:39 +00001857 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001858 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001859 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1860 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001861
1862 // fold (sub x, 0) -> x, vector edition
1863 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1864 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001865 }
Bill Wendling0864a752008-12-10 22:36:00 +00001866
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001867 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001868 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001869 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001870 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001871 // fold (sub c1, c2) -> c1-c2
Matthias Braun56a78142015-05-20 18:54:02 +00001872 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1873 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001874 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001875 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001876 // fold (sub x, c) -> (add x, -c)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001877 if (N1C) {
1878 SDLoc DL(N);
1879 return DAG.getNode(ISD::ADD, DL, VT, N0,
1880 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1881 }
Evan Cheng88b65bc2010-01-18 21:38:44 +00001882 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
Matthias Braun03312192015-05-19 00:25:20 +00001883 if (isAllOnesConstant(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001884 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001885 // fold A-(A-B) -> B
1886 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1887 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001888 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001889 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001890 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001892 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001893 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001894 // fold C2-(A+C1) -> (C2-C1)-A
Matthias Braun00a40762015-02-24 18:52:01 +00001895 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1896 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001897 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001898 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00001899 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001900 DL, VT);
1901 return DAG.getNode(ISD::SUB, DL, VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001902 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001903 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001904 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001905 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001906 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1907 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001908 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001910 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001911 // fold ((A+(C+B))-B) -> A+C
1912 if (N0.getOpcode() == ISD::ADD &&
1913 N0.getOperand(1).getOpcode() == ISD::ADD &&
1914 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001915 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001916 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001917 // fold ((A-(B-C))-C) -> A-B
1918 if (N0.getOpcode() == ISD::SUB &&
1919 N0.getOperand(1).getOpcode() == ISD::SUB &&
1920 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001921 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001922 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001923
Dan Gohman06563a82007-07-03 14:03:57 +00001924 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001925 if (N0.getOpcode() == ISD::UNDEF)
1926 return N0;
1927 if (N1.getOpcode() == ISD::UNDEF)
1928 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001929
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001930 // If the relocation model supports it, consider symbol offsets.
1931 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001932 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001933 // fold (sub Sym, c) -> Sym-c
1934 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001936 GA->getOffset() -
1937 (uint64_t)N1C->getSExtValue());
1938 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1939 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1940 if (GA->getGlobal() == GB->getGlobal())
1941 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001942 SDLoc(N), VT);
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001943 }
1944
Jan Veselyaf62cf42014-10-17 14:45:25 +00001945 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1946 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1947 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1948 if (TN->getVT() == MVT::i1) {
1949 SDLoc DL(N);
1950 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001951 DAG.getConstant(1, DL, VT));
Jan Veselyaf62cf42014-10-17 14:45:25 +00001952 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1953 }
1954 }
1955
Evan Chengf1005572010-04-28 07:10:39 +00001956 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001957}
1958
Craig Topper43a1bd62012-01-07 09:06:39 +00001959SDValue DAGCombiner::visitSUBC(SDNode *N) {
1960 SDValue N0 = N->getOperand(0);
1961 SDValue N1 = N->getOperand(1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001962 EVT VT = N0.getValueType();
1963
1964 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001965 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001966 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1967 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001968 MVT::Glue));
1969
1970 // fold (subc x, x) -> 0 + no borrow
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001971 if (N0 == N1) {
1972 SDLoc DL(N);
1973 return CombineTo(N, DAG.getConstant(0, DL, VT),
1974 DAG.getNode(ISD::CARRY_FALSE, DL,
Craig Topper43a1bd62012-01-07 09:06:39 +00001975 MVT::Glue));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001976 }
Craig Topper43a1bd62012-01-07 09:06:39 +00001977
1978 // fold (subc x, 0) -> x + no borrow
Matthias Braun1505efb2015-05-18 23:07:27 +00001979 if (isNullConstant(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001980 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001981 MVT::Glue));
1982
1983 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
Matthias Braun03312192015-05-19 00:25:20 +00001984 if (isAllOnesConstant(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1986 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001987 MVT::Glue));
1988
1989 return SDValue();
1990}
1991
1992SDValue DAGCombiner::visitSUBE(SDNode *N) {
1993 SDValue N0 = N->getOperand(0);
1994 SDValue N1 = N->getOperand(1);
1995 SDValue CarryIn = N->getOperand(2);
1996
1997 // fold (sube x, y, false) -> (subc x, y)
1998 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001999 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00002000
2001 return SDValue();
2002}
2003
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002004SDValue DAGCombiner::visitMUL(SDNode *N) {
2005 SDValue N0 = N->getOperand(0);
2006 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002007 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002008
Dan Gohman06563a82007-07-03 14:03:57 +00002009 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002010 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002011 return DAG.getConstant(0, SDLoc(N), VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002012
2013 bool N0IsConst = false;
2014 bool N1IsConst = false;
Matthias Braun56a78142015-05-20 18:54:02 +00002015 bool N1IsOpaqueConst = false;
2016 bool N0IsOpaqueConst = false;
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002017 APInt ConstValue0, ConstValue1;
2018 // fold vector ops
2019 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002020 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2021 return FoldedVOp;
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002022
2023 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2024 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2025 } else {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00002026 N0IsConst = isa<ConstantSDNode>(N0);
Matthias Braun56a78142015-05-20 18:54:02 +00002027 if (N0IsConst) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00002028 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
Matthias Braun56a78142015-05-20 18:54:02 +00002029 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2030 }
Benjamin Kramer619c4e52015-04-10 11:24:51 +00002031 N1IsConst = isa<ConstantSDNode>(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002032 if (N1IsConst) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00002033 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
Matthias Braun56a78142015-05-20 18:54:02 +00002034 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2035 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002036 }
2037
Nate Begeman21158fc2005-09-01 00:19:25 +00002038 // fold (mul c1, c2) -> c1*c2
Matthias Braun56a78142015-05-20 18:54:02 +00002039 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002040 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2041 N0.getNode(), N1.getNode());
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002042
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002043 // canonicalize constant to RHS (vector doesn't have to splat)
2044 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2045 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002046 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002047 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002048 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00002049 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002050 // We require a splat of the entire scalar bit width for non-contiguous
2051 // bit patterns.
2052 bool IsFullSplat =
2053 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002054 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002055 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002056 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002057 // fold (mul x, -1) -> 0-x
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002058 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2059 SDLoc DL(N);
2060 return DAG.getNode(ISD::SUB, DL, VT,
2061 DAG.getConstant(0, DL, VT), N0);
2062 }
Nate Begeman21158fc2005-09-01 00:19:25 +00002063 // fold (mul x, (1 << c)) -> x << c
Matthias Braun56a78142015-05-20 18:54:02 +00002064 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2065 IsFullSplat) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002066 SDLoc DL(N);
2067 return DAG.getNode(ISD::SHL, DL, VT, N0,
2068 DAG.getConstant(ConstValue1.logBase2(), DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002069 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002070 }
Chris Lattnera70878d2005-10-30 06:41:49 +00002071 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Matthias Braun56a78142015-05-20 18:54:02 +00002072 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2073 IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002074 unsigned Log2Val = (-ConstValue1).logBase2();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002075 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002076 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002077 // single-use add), we should put the negate there.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002078 return DAG.getNode(ISD::SUB, DL, VT,
2079 DAG.getConstant(0, DL, VT),
2080 DAG.getNode(ISD::SHL, DL, VT, N0,
2081 DAG.getConstant(Log2Val, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002082 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002083 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002084
2085 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002086 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002087 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002088 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2089 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002090 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002091 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002092 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002093 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002094 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002095 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002096
Chris Lattner324871e2006-03-01 03:44:24 +00002097 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2098 // use.
2099 {
Craig Topperc0196b12014-04-14 00:51:57 +00002100 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002101 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002102 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002103 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2104 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002105 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002106 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002107 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002108 isa<ConstantSDNode>(N1.getOperand(1)) &&
2109 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002110 Sh = N1; Y = N0;
2111 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002112
Gabor Greiff304a7a2008-08-28 21:40:38 +00002113 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002114 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002115 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002116 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002117 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002118 }
2119 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002120
Chris Lattnerf29f5202006-03-04 23:33:26 +00002121 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002122 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2123 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2124 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002125 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2126 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002127 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002128 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002129 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002130
Nate Begeman22e251a2006-02-03 06:46:56 +00002131 // reassociate mul
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002132 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002133 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002134
Evan Chengf1005572010-04-28 07:10:39 +00002135 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002136}
2137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002138SDValue DAGCombiner::visitSDIV(SDNode *N) {
2139 SDValue N0 = N->getOperand(0);
2140 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002141 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002142
Dan Gohmana8665142007-06-25 16:23:39 +00002143 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002144 if (VT.isVector())
2145 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2146 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002147
Nate Begeman21158fc2005-09-01 00:19:25 +00002148 // fold (sdiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002149 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2150 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002151 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002152 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002153 // fold (sdiv X, 1) -> X
Matthias Braun887fdfb2015-05-19 00:25:21 +00002154 if (N1C && N1C->isOne())
Nate Begeman4dd38312005-10-21 00:02:42 +00002155 return N0;
2156 // fold (sdiv X, -1) -> 0-X
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002157 if (N1C && N1C->isAllOnesValue()) {
2158 SDLoc DL(N);
2159 return DAG.getNode(ISD::SUB, DL, VT,
2160 DAG.getConstant(0, DL, VT), N0);
2161 }
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002162 // If we know the sign bits of both operands are zero, strength reduce to a
2163 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002164 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002165 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002166 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002167 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002168 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002169
Nate Begeman57b35672006-02-17 07:26:20 +00002170 // fold (sdiv X, pow2) -> simple ops after legalize
Matthias Braun56a78142015-05-20 18:54:02 +00002171 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2172 (N1C->getAPIntValue().isPowerOf2() ||
2173 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002174 // If dividing by powers of two is cheap, then don't perform the following
2175 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002176 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002177 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002178
Chad Rosier17020f92014-07-23 14:57:52 +00002179 // Target-specific implementation of sdiv x, pow2.
2180 SDValue Res = BuildSDIVPow2(N);
2181 if (Res.getNode())
2182 return Res;
2183
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002184 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002185 SDLoc DL(N);
Bill Wendling5b663e72009-01-30 02:52:17 +00002186
Chris Lattner471627c2006-02-16 08:02:36 +00002187 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002188 SDValue SGN =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002189 DAG.getNode(ISD::SRA, DL, VT, N0,
2190 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
Benjamin Kramerad016872014-04-26 13:00:53 +00002191 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002192 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002193
Chris Lattner471627c2006-02-16 08:02:36 +00002194 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002195 SDValue SRL =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002196 DAG.getNode(ISD::SRL, DL, VT, SGN,
2197 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
Benjamin Kramerad016872014-04-26 13:00:53 +00002198 getShiftAmountTy(SGN.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002199 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002200 AddToWorklist(SRL.getNode());
2201 AddToWorklist(ADD.getNode()); // Divide by pow2
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002202 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2203 DAG.getConstant(lg2, DL,
2204 getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002205
Nate Begeman4dd38312005-10-21 00:02:42 +00002206 // If we're dividing by a positive value, we're done. Otherwise, we must
2207 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002208 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002209 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002210
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002211 AddToWorklist(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002212 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002213 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002214
Sanjay Pateld399d942015-03-31 16:17:51 +00002215 // If integer divide is expensive and we satisfy the requirements, emit an
Nate Begemanc6f067a2005-10-20 02:15:44 +00002216 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002217 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002218 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002219 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002220 }
Dan Gohmana8665142007-06-25 16:23:39 +00002221
Dan Gohman06563a82007-07-03 14:03:57 +00002222 // undef / X -> 0
2223 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002224 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002225 // X / undef -> undef
2226 if (N1.getOpcode() == ISD::UNDEF)
2227 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002229 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002230}
2231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232SDValue DAGCombiner::visitUDIV(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002235 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002236
Dan Gohmana8665142007-06-25 16:23:39 +00002237 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002238 if (VT.isVector())
2239 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2240 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Nate Begeman21158fc2005-09-01 00:19:25 +00002242 // fold (udiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002243 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2244 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002245 if (N0C && N1C)
2246 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2247 N0C, N1C))
2248 return Folded;
Nate Begeman21158fc2005-09-01 00:19:25 +00002249 // fold (udiv x, (1 << c)) -> x >>u c
Matthias Braun56a78142015-05-20 18:54:02 +00002250 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002251 SDLoc DL(N);
2252 return DAG.getNode(ISD::SRL, DL, VT, N0,
2253 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002254 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002255 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002256 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002257 if (N1.getOpcode() == ISD::SHL) {
Matthias Braun56a78142015-05-20 18:54:02 +00002258 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002259 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002260 EVT ADDVT = N1.getOperand(1).getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002261 SDLoc DL(N);
2262 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002263 N1.getOperand(1),
2264 DAG.getConstant(SHC->getAPIntValue()
2265 .logBase2(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002266 DL, ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002267 AddToWorklist(Add.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002268 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002269 }
2270 }
2271 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002272 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002273 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002274 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002275 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002276 }
Dan Gohmana8665142007-06-25 16:23:39 +00002277
Dan Gohman06563a82007-07-03 14:03:57 +00002278 // undef / X -> 0
2279 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002280 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002281 // X / undef -> undef
2282 if (N1.getOpcode() == ISD::UNDEF)
2283 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002284
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002285 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002286}
2287
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002288SDValue DAGCombiner::visitSREM(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002291 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002292
Nate Begeman21158fc2005-09-01 00:19:25 +00002293 // fold (srem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002294 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2295 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002296 if (N0C && N1C)
2297 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2298 N0C, N1C))
2299 return Folded;
Nate Begeman6828ed92005-10-10 21:26:48 +00002300 // If we know the sign bits of both operands are zero, strength reduce to a
2301 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002302 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002303 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002304 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002305 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002306
Dan Gohman9a693412007-11-26 23:46:11 +00002307 // If X/C can be simplified by the division-by-constant logic, lower
2308 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002309 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002310 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002311 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002312 SDValue OptimizedDiv = combine(Div.getNode());
2313 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002314 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002315 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002316 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002317 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002318 return Sub;
2319 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002320 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002321
Dan Gohman06563a82007-07-03 14:03:57 +00002322 // undef % X -> 0
2323 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002324 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002325 // X % undef -> undef
2326 if (N1.getOpcode() == ISD::UNDEF)
2327 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002328
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002329 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002330}
2331
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002332SDValue DAGCombiner::visitUREM(SDNode *N) {
2333 SDValue N0 = N->getOperand(0);
2334 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002335 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002336
Nate Begeman21158fc2005-09-01 00:19:25 +00002337 // fold (urem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002338 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2339 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002340 if (N0C && N1C)
2341 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2342 N0C, N1C))
2343 return Folded;
Nate Begeman6828ed92005-10-10 21:26:48 +00002344 // fold (urem x, pow2) -> (and x, pow2-1)
Matthias Braun56a78142015-05-20 18:54:02 +00002345 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2346 N1C->getAPIntValue().isPowerOf2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002347 SDLoc DL(N);
2348 return DAG.getNode(ISD::AND, DL, VT, N0,
2349 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2350 }
Nate Begemanc89fdf12006-02-05 07:36:48 +00002351 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2352 if (N1.getOpcode() == ISD::SHL) {
Matthias Braun56a78142015-05-20 18:54:02 +00002353 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002354 if (SHC->getAPIntValue().isPowerOf2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002355 SDLoc DL(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002356 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002357 DAG.getNode(ISD::ADD, DL, VT, N1,
2358 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002359 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002360 AddToWorklist(Add.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002361 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002362 }
2363 }
2364 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002365
Dan Gohman9a693412007-11-26 23:46:11 +00002366 // If X/C can be simplified by the division-by-constant logic, lower
2367 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002368 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002369 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002370 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002371 SDValue OptimizedDiv = combine(Div.getNode());
2372 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002373 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002374 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002375 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002376 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002377 return Sub;
2378 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002379 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002380
Dan Gohman06563a82007-07-03 14:03:57 +00002381 // undef % X -> 0
2382 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002383 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002384 // X % undef -> undef
2385 if (N1.getOpcode() == ISD::UNDEF)
2386 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002387
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002388 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002389}
2390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002391SDValue DAGCombiner::visitMULHS(SDNode *N) {
2392 SDValue N0 = N->getOperand(0);
2393 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002394 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002395 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002396
Nate Begeman21158fc2005-09-01 00:19:25 +00002397 // fold (mulhs x, 0) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00002398 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002399 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002400 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Matthias Braun887fdfb2015-05-19 00:25:21 +00002401 if (isOneConstant(N1)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002402 SDLoc DL(N);
2403 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002404 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002405 DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002406 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002407 }
Dan Gohman06563a82007-07-03 14:03:57 +00002408 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002409 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002410 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002411
Chris Lattner10bd29f2010-12-13 08:39:01 +00002412 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2413 // plus a shift.
2414 if (VT.isSimple() && !VT.isVector()) {
2415 MVT Simple = VT.getSimpleVT();
2416 unsigned SimpleSize = Simple.getSizeInBits();
2417 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2418 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2419 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2420 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2421 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002422 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002423 DAG.getConstant(SimpleSize, DL,
2424 getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002425 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2426 }
2427 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002429 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002430}
2431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002432SDValue DAGCombiner::visitMULHU(SDNode *N) {
2433 SDValue N0 = N->getOperand(0);
2434 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002435 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002436 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002437
Nate Begeman21158fc2005-09-01 00:19:25 +00002438 // fold (mulhu x, 0) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00002439 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002440 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002441 // fold (mulhu x, 1) -> 0
Matthias Braun887fdfb2015-05-19 00:25:21 +00002442 if (isOneConstant(N1))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002443 return DAG.getConstant(0, DL, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002444 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002445 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002446 return DAG.getConstant(0, DL, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002447
Chris Lattner10bd29f2010-12-13 08:39:01 +00002448 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2449 // plus a shift.
2450 if (VT.isSimple() && !VT.isVector()) {
2451 MVT Simple = VT.getSimpleVT();
2452 unsigned SimpleSize = Simple.getSizeInBits();
2453 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2454 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2455 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2456 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2457 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2458 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002459 DAG.getConstant(SimpleSize, DL,
2460 getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002461 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2462 }
2463 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002464
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002465 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002466}
2467
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002468/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2469/// give the opcodes for the two computations that are being performed. Return
2470/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002471SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002472 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002473 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002474 bool HiExists = N->hasAnyUseOfValue(1);
2475 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002476 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002477 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002478 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002479 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002480 }
2481
2482 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002483 bool LoExists = N->hasAnyUseOfValue(0);
2484 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002485 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002486 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002487 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002488 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002489 }
2490
Evan Chengece4c682007-11-08 09:25:29 +00002491 // If both halves are used, return as it is.
2492 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002493 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002494
2495 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002496 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002497 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002498 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002499 SDValue LoOpt = combine(Lo.getNode());
2500 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002501 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002502 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002503 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002504 }
2505
Evan Chengece4c682007-11-08 09:25:29 +00002506 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002507 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002508 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002509 SDValue HiOpt = combine(Hi.getNode());
2510 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002511 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002512 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002513 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002514 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002516 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002517}
2518
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002519SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2520 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002521 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002522
Chris Lattner15090e12010-12-15 06:04:19 +00002523 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002524 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002525
Sanjay Pateld399d942015-03-31 16:17:51 +00002526 // If the type is twice as wide is legal, transform the mulhu to a wider
2527 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002528 if (VT.isSimple() && !VT.isVector()) {
2529 MVT Simple = VT.getSimpleVT();
2530 unsigned SimpleSize = Simple.getSizeInBits();
2531 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2532 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2533 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2534 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2535 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2536 // Compute the high part as N1.
2537 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002538 DAG.getConstant(SimpleSize, DL,
2539 getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002540 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2541 // Compute the low part as N0.
2542 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2543 return CombineTo(N, Lo, Hi);
2544 }
2545 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002546
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002547 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002548}
2549
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002550SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2551 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002552 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002553
Chris Lattner15090e12010-12-15 06:04:19 +00002554 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002555 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002556
Sanjay Pateld399d942015-03-31 16:17:51 +00002557 // If the type is twice as wide is legal, transform the mulhu to a wider
2558 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002559 if (VT.isSimple() && !VT.isVector()) {
2560 MVT Simple = VT.getSimpleVT();
2561 unsigned SimpleSize = Simple.getSizeInBits();
2562 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2563 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2564 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2565 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2566 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2567 // Compute the high part as N1.
2568 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002569 DAG.getConstant(SimpleSize, DL,
2570 getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002571 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2572 // Compute the low part as N0.
2573 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2574 return CombineTo(N, Lo, Hi);
2575 }
2576 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002577
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002578 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002579}
2580
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002581SDValue DAGCombiner::visitSMULO(SDNode *N) {
2582 // (smulo x, 2) -> (saddo x, x)
2583 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2584 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002585 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002586 N->getOperand(0), N->getOperand(0));
2587
2588 return SDValue();
2589}
2590
2591SDValue DAGCombiner::visitUMULO(SDNode *N) {
2592 // (umulo x, 2) -> (uaddo x, x)
2593 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2594 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002595 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002596 N->getOperand(0), N->getOperand(0));
2597
2598 return SDValue();
2599}
2600
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002601SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2602 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002603 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002604
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002605 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002606}
2607
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002608SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2609 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002610 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002611
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002612 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002613}
2614
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002615/// If this is a binary operator with two operands of the same opcode, try to
2616/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002617SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2618 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002619 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002620 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002621
Dan Gohmandd5286d2010-01-14 03:08:49 +00002622 // Bail early if none of these transforms apply.
2623 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2624
Chris Lattner002ee912006-05-05 06:31:05 +00002625 // For each of OP in AND/OR/XOR:
2626 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2627 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2628 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002629 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002630 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002631 //
2632 // do not sink logical op inside of a vector extend, since it may combine
2633 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002634 EVT Op0VT = N0.getOperand(0).getValueType();
2635 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002636 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002637 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002638 // Avoid infinite looping with PromoteIntBinOp.
2639 (N0.getOpcode() == ISD::ANY_EXTEND &&
2640 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002641 (N0.getOpcode() == ISD::TRUNCATE &&
2642 (!TLI.isZExtFree(VT, Op0VT) ||
2643 !TLI.isTruncateFree(Op0VT, VT)) &&
2644 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002645 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002646 Op0VT == N1.getOperand(0).getValueType() &&
2647 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002648 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002649 N0.getOperand(0).getValueType(),
2650 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002651 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002652 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002653 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002654
Chris Lattner5ac42932006-05-05 06:10:43 +00002655 // For each of OP in SHL/SRL/SRA/AND...
2656 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2657 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2658 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002659 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002660 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002661 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002662 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002663 N0.getOperand(0).getValueType(),
2664 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002665 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002666 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002667 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002668 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002669
Nadav Rotemb0783502012-04-01 19:31:22 +00002670 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2671 // Only perform this optimization after type legalization and before
2672 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2673 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2674 // we don't want to undo this promotion.
2675 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2676 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002677 if ((N0.getOpcode() == ISD::BITCAST ||
2678 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2679 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002680 SDValue In0 = N0.getOperand(0);
2681 SDValue In1 = N1.getOperand(0);
2682 EVT In0Ty = In0.getValueType();
2683 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002684 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002685 // If both incoming values are integers, and the original types are the
2686 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002687 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002688 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2689 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002690 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002691 return BC;
2692 }
2693 }
2694
2695 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2696 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2697 // If both shuffles use the same mask, and both shuffle within a single
2698 // vector, then it is worthwhile to move the swizzle after the operation.
2699 // The type-legalizer generates this pattern when loading illegal
2700 // vector types from memory. In many cases this allows additional shuffle
2701 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002702 // There are other cases where moving the shuffle after the xor/and/or
2703 // is profitable even if shuffles don't perform a swizzle.
2704 // If both shuffles use the same mask, and both shuffles have the same first
2705 // or second operand, then it might still be profitable to move the shuffle
2706 // after the xor/and/or operation.
2707 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002708 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2709 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002710
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002711 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002712 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002713
Nadav Rotemb0783502012-04-01 19:31:22 +00002714 // Check that both shuffles use the same mask. The masks are known to be of
2715 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002716 // Check also that shuffles have only one use to avoid introducing extra
2717 // instructions.
2718 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2719 SVN0->getMask().equals(SVN1->getMask())) {
2720 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002721
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002722 // Don't try to fold this node if it requires introducing a
2723 // build vector of all zeros that might be illegal at this stage.
2724 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2725 if (!LegalTypes)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002726 ShOp = DAG.getConstant(0, SDLoc(N), VT);
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002727 else
2728 ShOp = SDValue();
2729 }
2730
2731 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2732 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2733 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2734 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2735 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2736 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002737 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002738 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2739 &SVN0->getMask()[0]);
2740 }
2741
2742 // Don't try to fold this node if it requires introducing a
2743 // build vector of all zeros that might be illegal at this stage.
2744 ShOp = N0->getOperand(0);
2745 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2746 if (!LegalTypes)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002747 ShOp = DAG.getConstant(0, SDLoc(N), VT);
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002748 else
2749 ShOp = SDValue();
2750 }
2751
2752 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2753 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2754 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2755 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2756 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2757 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002758 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002759 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2760 &SVN0->getMask()[0]);
2761 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002762 }
2763 }
Craig Topper9c3da312012-04-09 07:19:09 +00002764
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002765 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002766}
2767
Matthias Braun3ecb5572015-03-06 19:49:06 +00002768/// This contains all DAGCombine rules which reduce two values combined by
2769/// an And operation to a single value. This makes them reusable in the context
2770/// of visitSELECT(). Rules involving constants are not included as
2771/// visitSELECT() already handles those cases.
2772SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2773 SDNode *LocReference) {
2774 EVT VT = N1.getValueType();
2775
2776 // fold (and x, undef) -> 0
2777 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002778 return DAG.getConstant(0, SDLoc(LocReference), VT);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002779 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2780 SDValue LL, LR, RL, RR, CC0, CC1;
2781 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2782 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2783 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2784
2785 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2786 LL.getValueType().isInteger()) {
2787 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Matthias Braun1505efb2015-05-18 23:07:27 +00002788 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00002789 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2790 LR.getValueType(), LL, RL);
2791 AddToWorklist(ORNode.getNode());
2792 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2793 }
Matthias Braun03312192015-05-19 00:25:20 +00002794 if (isAllOnesConstant(LR)) {
2795 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2796 if (Op1 == ISD::SETEQ) {
2797 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2798 LR.getValueType(), LL, RL);
2799 AddToWorklist(ANDNode.getNode());
2800 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2801 }
2802 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2803 if (Op1 == ISD::SETGT) {
2804 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2805 LR.getValueType(), LL, RL);
2806 AddToWorklist(ORNode.getNode());
2807 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2808 }
Matthias Braun3ecb5572015-03-06 19:49:06 +00002809 }
2810 }
2811 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2812 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2813 Op0 == Op1 && LL.getValueType().isInteger() &&
Matthias Braun03312192015-05-19 00:25:20 +00002814 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2815 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002816 SDLoc DL(N0);
2817 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2818 LL, DAG.getConstant(1, DL,
2819 LL.getValueType()));
Matthias Braun3ecb5572015-03-06 19:49:06 +00002820 AddToWorklist(ADDNode.getNode());
2821 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002822 DAG.getConstant(2, DL, LL.getValueType()),
2823 ISD::SETUGE);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002824 }
2825 // canonicalize equivalent to ll == rl
2826 if (LL == RR && LR == RL) {
2827 Op1 = ISD::getSetCCSwappedOperands(Op1);
2828 std::swap(RL, RR);
2829 }
2830 if (LL == RL && LR == RR) {
2831 bool isInteger = LL.getValueType().isInteger();
2832 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2833 if (Result != ISD::SETCC_INVALID &&
2834 (!LegalOperations ||
2835 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2836 TLI.isOperationLegal(ISD::SETCC,
2837 getSetCCResultType(N0.getSimpleValueType())))))
2838 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2839 LL, LR, Result);
2840 }
2841 }
2842
2843 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2844 VT.getSizeInBits() <= 64) {
2845 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2846 APInt ADDC = ADDI->getAPIntValue();
2847 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2848 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2849 // immediate for an add, but it is legal if its top c2 bits are set,
2850 // transform the ADD so the immediate doesn't need to be materialized
2851 // in a register.
2852 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2853 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2854 SRLI->getZExtValue());
2855 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2856 ADDC |= Mask;
2857 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002858 SDLoc DL(N0);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002859 SDValue NewAdd =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002860 DAG.getNode(ISD::ADD, DL, VT,
2861 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
Matthias Braun3ecb5572015-03-06 19:49:06 +00002862 CombineTo(N0.getNode(), NewAdd);
2863 // Return N so it doesn't get rechecked!
2864 return SDValue(LocReference, 0);
2865 }
2866 }
2867 }
2868 }
2869 }
2870 }
2871
2872 return SDValue();
2873}
2874
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002875SDValue DAGCombiner::visitAND(SDNode *N) {
2876 SDValue N0 = N->getOperand(0);
2877 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002878 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002879
Dan Gohmana8665142007-06-25 16:23:39 +00002880 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002881 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002882 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2883 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002884
2885 // fold (and x, 0) -> 0, vector edition
2886 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002887 // do not return N0, because undef node may exist in N0
2888 return DAG.getConstant(
2889 APInt::getNullValue(
2890 N0.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002891 SDLoc(N), N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002892 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002893 // do not return N1, because undef node may exist in N1
2894 return DAG.getConstant(
2895 APInt::getNullValue(
2896 N1.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002897 SDLoc(N), N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002898
2899 // fold (and x, -1) -> x, vector edition
2900 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2901 return N1;
2902 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2903 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002904 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002905
Nate Begeman21158fc2005-09-01 00:19:25 +00002906 // fold (and c1, c2) -> c1&c2
Matthias Braun56a78142015-05-20 18:54:02 +00002907 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
Matthias Braun00a40762015-02-24 18:52:01 +00002908 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00002909 if (N0C && N1C && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002910 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002911 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002912 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2913 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002914 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002915 // fold (and x, -1) -> x
Matthias Braun03312192015-05-19 00:25:20 +00002916 if (isAllOnesConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002917 return N0;
2918 // if (and x, c) is known to be zero, return 0
Matthias Braun00a40762015-02-24 18:52:01 +00002919 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002920 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002921 APInt::getAllOnesValue(BitWidth)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002922 return DAG.getConstant(0, SDLoc(N), VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002923 // reassociate and
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002924 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002925 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002926 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002927 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002928 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002929 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002930 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002931 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2932 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002933 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002934 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002935 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002936 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002937 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002938 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002939
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002940 // Replace uses of the AND with uses of the Zero extend node.
2941 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002942
Chris Lattner49beaf42006-02-02 07:17:31 +00002943 // We actually want to replace all uses of the any_extend with the
2944 // zero_extend, to avoid duplicating things. This will later cause this
2945 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002946 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002948 }
2949 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002950 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002951 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2952 // already be zero by virtue of the width of the base type of the load.
2953 //
2954 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2955 // more cases.
2956 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2957 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2958 N0.getOpcode() == ISD::LOAD) {
2959 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2960 N0 : N0.getOperand(0) );
2961
2962 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2963 // This can be a pure constant or a vector splat, in which case we treat the
2964 // vector as a scalar and use the splat value.
2965 APInt Constant = APInt::getNullValue(1);
2966 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2967 Constant = C->getAPIntValue();
2968 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2969 APInt SplatValue, SplatUndef;
2970 unsigned SplatBitSize;
2971 bool HasAnyUndefs;
2972 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2973 SplatBitSize, HasAnyUndefs);
2974 if (IsSplat) {
2975 // Undef bits can contribute to a possible optimisation if set, so
2976 // set them.
2977 SplatValue |= SplatUndef;
2978
2979 // The splat value may be something like "0x00FFFFFF", which means 0 for
2980 // the first vector value and FF for the rest, repeating. We need a mask
2981 // that will apply equally to all members of the vector, so AND all the
2982 // lanes of the constant together.
2983 EVT VT = Vector->getValueType(0);
2984 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002985
2986 // If the splat value has been compressed to a bitlength lower
2987 // than the size of the vector lane, we need to re-expand it to
2988 // the lane size.
2989 if (BitWidth > SplatBitSize)
2990 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2991 SplatBitSize < BitWidth;
2992 SplatBitSize = SplatBitSize * 2)
2993 SplatValue |= SplatValue.shl(SplatBitSize);
2994
Andrea Di Biagioc9d79e82015-03-07 12:24:55 +00002995 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2996 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2997 if (SplatBitSize % BitWidth == 0) {
2998 Constant = APInt::getAllOnesValue(BitWidth);
2999 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3000 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3001 }
James Molloy862fe492012-02-20 12:02:38 +00003002 }
3003 }
3004
3005 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3006 // actually legal and isn't going to get expanded, else this is a false
3007 // optimisation.
3008 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003009 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00003010 Load->getMemoryVT());
3011
3012 // Resize the constant to the same size as the original memory access before
3013 // extension. If it is still the AllOnesValue then this AND is completely
3014 // unneeded.
3015 Constant =
3016 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3017
3018 bool B;
3019 switch (Load->getExtensionType()) {
3020 default: B = false; break;
3021 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3022 case ISD::ZEXTLOAD:
3023 case ISD::NON_EXTLOAD: B = true; break;
3024 }
3025
3026 if (B && Constant.isAllOnesValue()) {
3027 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3028 // preserve semantics once we get rid of the AND.
3029 SDValue NewLoad(Load, 0);
3030 if (Load->getExtensionType() == ISD::EXTLOAD) {
3031 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003032 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00003033 Load->getChain(), Load->getBasePtr(),
3034 Load->getOffset(), Load->getMemoryVT(),
3035 Load->getMemOperand());
3036 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00003037 if (Load->getNumValues() == 3) {
3038 // PRE/POST_INC loads have 3 values.
3039 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3040 NewLoad.getValue(2) };
3041 CombineTo(Load, To, 3, true);
3042 } else {
3043 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3044 }
James Molloy862fe492012-02-20 12:02:38 +00003045 }
3046
3047 // Fold the AND away, taking care not to fold to the old load node if we
3048 // replaced it.
3049 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3050
3051 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 }
3053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003054
Chris Lattnerf0032b32006-02-28 06:49:37 +00003055 // fold (and (load x), 255) -> (zextload x, i8)
3056 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00003057 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3058 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3059 (N0.getOpcode() == ISD::ANY_EXTEND &&
3060 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3061 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3062 LoadSDNode *LN0 = HasAnyExt
3063 ? cast<LoadSDNode>(N0.getOperand(0))
3064 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00003065 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00003066 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00003067 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00003068 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3069 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3070 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003071 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00003072
Evan Cheng166a4e62010-01-06 19:38:29 +00003073 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003074 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3075 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00003076
3077 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003078 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00003079 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3080 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003081 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003082 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3084 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003085
Chris Lattner88de3842010-01-07 21:53:27 +00003086 // Do not change the width of a volatile load.
3087 // Do not generate loads of non-round integer types since these can
3088 // be expensive (and would be wrong if the type is not byte sized).
3089 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003090 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3091 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003092 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003093
Chris Lattner88de3842010-01-07 21:53:27 +00003094 unsigned Alignment = LN0->getAlignment();
3095 SDValue NewPtr = LN0->getBasePtr();
3096
3097 // For big endian targets, we need to add an offset to the pointer
3098 // to load the correct bytes. For little endian systems, we merely
3099 // need to read fewer bytes from the same pointer.
3100 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003101 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3102 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3103 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003104 SDLoc DL(LN0);
3105 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3106 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
Chris Lattner88de3842010-01-07 21:53:27 +00003107 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003108 }
Chris Lattner88de3842010-01-07 21:53:27 +00003109
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003110 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003111
Chris Lattner88de3842010-01-07 21:53:27 +00003112 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003113 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003114 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003115 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003116 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003117 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003118 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003119 CombineTo(LN0, Load, Load.getValue(1));
3120 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003121 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003122 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003123 }
3124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003125
Matthias Braun3ecb5572015-03-06 19:49:06 +00003126 if (SDValue Combined = visitANDLike(N0, N1, N))
3127 return Combined;
3128
3129 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3130 if (N0.getOpcode() == N1.getOpcode()) {
3131 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3132 if (Tmp.getNode()) return Tmp;
Evan Chenge6a3b032012-07-17 18:54:11 +00003133 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003134
Matthias Braun3ecb5572015-03-06 19:49:06 +00003135 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3136 // fold (and (sra)) -> (and (srl)) when possible.
3137 if (!VT.isVector() &&
3138 SimplifyDemandedBits(SDValue(N, 0)))
3139 return SDValue(N, 0);
3140
3141 // fold (zext_inreg (extload x)) -> (zextload x)
3142 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3143 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3144 EVT MemVT = LN0->getMemoryVT();
3145 // If we zero all the possible extended bits, then we can turn this into
3146 // a zextload if we are running before legalize or the operation is legal.
3147 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3148 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3149 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3150 ((!LegalOperations && !LN0->isVolatile()) ||
3151 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3152 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3153 LN0->getChain(), LN0->getBasePtr(),
3154 MemVT, LN0->getMemOperand());
3155 AddToWorklist(N);
3156 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3158 }
3159 }
3160 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3161 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3162 N0.hasOneUse()) {
3163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3164 EVT MemVT = LN0->getMemoryVT();
3165 // If we zero all the possible extended bits, then we can turn this into
3166 // a zextload if we are running before legalize or the operation is legal.
3167 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3168 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3169 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3170 ((!LegalOperations && !LN0->isVolatile()) ||
3171 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3172 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3173 LN0->getChain(), LN0->getBasePtr(),
3174 MemVT, LN0->getMemOperand());
3175 AddToWorklist(N);
3176 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3178 }
3179 }
Tim Northover819bfb52013-08-27 13:46:45 +00003180 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3181 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3182 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3183 N0.getOperand(1), false);
3184 if (BSwap.getNode())
3185 return BSwap;
3186 }
3187
Evan Chengf1005572010-04-28 07:10:39 +00003188 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003189}
3190
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003191/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003192SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3193 bool DemandHighBits) {
3194 if (!LegalOperations)
3195 return SDValue();
3196
3197 EVT VT = N->getValueType(0);
3198 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3199 return SDValue();
3200 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3201 return SDValue();
3202
3203 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3204 bool LookPassAnd0 = false;
3205 bool LookPassAnd1 = false;
3206 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3207 std::swap(N0, N1);
3208 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3209 std::swap(N0, N1);
3210 if (N0.getOpcode() == ISD::AND) {
3211 if (!N0.getNode()->hasOneUse())
3212 return SDValue();
3213 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3214 if (!N01C || N01C->getZExtValue() != 0xFF00)
3215 return SDValue();
3216 N0 = N0.getOperand(0);
3217 LookPassAnd0 = true;
3218 }
3219
3220 if (N1.getOpcode() == ISD::AND) {
3221 if (!N1.getNode()->hasOneUse())
3222 return SDValue();
3223 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3224 if (!N11C || N11C->getZExtValue() != 0xFF)
3225 return SDValue();
3226 N1 = N1.getOperand(0);
3227 LookPassAnd1 = true;
3228 }
3229
3230 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3231 std::swap(N0, N1);
3232 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3233 return SDValue();
3234 if (!N0.getNode()->hasOneUse() ||
3235 !N1.getNode()->hasOneUse())
3236 return SDValue();
3237
3238 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3239 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3240 if (!N01C || !N11C)
3241 return SDValue();
3242 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3243 return SDValue();
3244
3245 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3246 SDValue N00 = N0->getOperand(0);
3247 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3248 if (!N00.getNode()->hasOneUse())
3249 return SDValue();
3250 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3251 if (!N001C || N001C->getZExtValue() != 0xFF)
3252 return SDValue();
3253 N00 = N00.getOperand(0);
3254 LookPassAnd0 = true;
3255 }
3256
3257 SDValue N10 = N1->getOperand(0);
3258 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3259 if (!N10.getNode()->hasOneUse())
3260 return SDValue();
3261 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3262 if (!N101C || N101C->getZExtValue() != 0xFF00)
3263 return SDValue();
3264 N10 = N10.getOperand(0);
3265 LookPassAnd1 = true;
3266 }
3267
3268 if (N00 != N10)
3269 return SDValue();
3270
Tim Northover819bfb52013-08-27 13:46:45 +00003271 // Make sure everything beyond the low halfword gets set to zero since the SRL
3272 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003273 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003274 if (DemandHighBits && OpSizeInBits > 16) {
3275 // If the left-shift isn't masked out then the only way this is a bswap is
3276 // if all bits beyond the low 8 are 0. In that case the entire pattern
3277 // reduces to a left shift anyway: leave it for other parts of the combiner.
3278 if (!LookPassAnd0)
3279 return SDValue();
3280
3281 // However, if the right shift isn't masked out then it might be because
3282 // it's not needed. See if we can spot that too.
3283 if (!LookPassAnd1 &&
3284 !DAG.MaskedValueIsZero(
3285 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3286 return SDValue();
3287 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003288
Andrew Trickef9de2a2013-05-25 02:42:55 +00003289 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003290 if (OpSizeInBits > 16) {
3291 SDLoc DL(N);
3292 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3293 DAG.getConstant(OpSizeInBits - 16, DL,
3294 getShiftAmountTy(VT)));
3295 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00003296 return Res;
3297}
3298
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003299/// Return true if the specified node is an element that makes up a 32-bit
3300/// packed halfword byteswap.
3301/// ((x & 0x000000ff) << 8) |
3302/// ((x & 0x0000ff00) >> 8) |
3303/// ((x & 0x00ff0000) << 8) |
3304/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003305static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003306 if (!N.getNode()->hasOneUse())
3307 return false;
3308
3309 unsigned Opc = N.getOpcode();
3310 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3311 return false;
3312
3313 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3314 if (!N1C)
3315 return false;
3316
3317 unsigned Num;
3318 switch (N1C->getZExtValue()) {
3319 default:
3320 return false;
3321 case 0xFF: Num = 0; break;
3322 case 0xFF00: Num = 1; break;
3323 case 0xFF0000: Num = 2; break;
3324 case 0xFF000000: Num = 3; break;
3325 }
3326
3327 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3328 SDValue N0 = N.getOperand(0);
3329 if (Opc == ISD::AND) {
3330 if (Num == 0 || Num == 2) {
3331 // (x >> 8) & 0xff
3332 // (x >> 8) & 0xff0000
3333 if (N0.getOpcode() != ISD::SRL)
3334 return false;
3335 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3336 if (!C || C->getZExtValue() != 8)
3337 return false;
3338 } else {
3339 // (x << 8) & 0xff00
3340 // (x << 8) & 0xff000000
3341 if (N0.getOpcode() != ISD::SHL)
3342 return false;
3343 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3344 if (!C || C->getZExtValue() != 8)
3345 return false;
3346 }
3347 } else if (Opc == ISD::SHL) {
3348 // (x & 0xff) << 8
3349 // (x & 0xff0000) << 8
3350 if (Num != 0 && Num != 2)
3351 return false;
3352 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3353 if (!C || C->getZExtValue() != 8)
3354 return false;
3355 } else { // Opc == ISD::SRL
3356 // (x & 0xff00) >> 8
3357 // (x & 0xff000000) >> 8
3358 if (Num != 1 && Num != 3)
3359 return false;
3360 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3361 if (!C || C->getZExtValue() != 8)
3362 return false;
3363 }
3364
3365 if (Parts[Num])
3366 return false;
3367
3368 Parts[Num] = N0.getOperand(0).getNode();
3369 return true;
3370}
3371
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003372/// Match a 32-bit packed halfword bswap. That is
3373/// ((x & 0x000000ff) << 8) |
3374/// ((x & 0x0000ff00) >> 8) |
3375/// ((x & 0x00ff0000) << 8) |
3376/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003377/// => (rotl (bswap x), 16)
3378SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3379 if (!LegalOperations)
3380 return SDValue();
3381
3382 EVT VT = N->getValueType(0);
3383 if (VT != MVT::i32)
3384 return SDValue();
3385 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3386 return SDValue();
3387
Evan Cheng4c0bd962011-06-21 06:01:08 +00003388 // Look for either
3389 // (or (or (and), (and)), (or (and), (and)))
3390 // (or (or (or (and), (and)), (and)), (and))
3391 if (N0.getOpcode() != ISD::OR)
3392 return SDValue();
3393 SDValue N00 = N0.getOperand(0);
3394 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003395 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003396
Evan Chengbf0baa92012-12-13 01:34:32 +00003397 if (N1.getOpcode() == ISD::OR &&
3398 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003399 // (or (or (and), (and)), (or (and), (and)))
3400 SDValue N000 = N00.getOperand(0);
3401 if (!isBSwapHWordElement(N000, Parts))
3402 return SDValue();
3403
3404 SDValue N001 = N00.getOperand(1);
3405 if (!isBSwapHWordElement(N001, Parts))
3406 return SDValue();
3407 SDValue N010 = N01.getOperand(0);
3408 if (!isBSwapHWordElement(N010, Parts))
3409 return SDValue();
3410 SDValue N011 = N01.getOperand(1);
3411 if (!isBSwapHWordElement(N011, Parts))
3412 return SDValue();
3413 } else {
3414 // (or (or (or (and), (and)), (and)), (and))
3415 if (!isBSwapHWordElement(N1, Parts))
3416 return SDValue();
3417 if (!isBSwapHWordElement(N01, Parts))
3418 return SDValue();
3419 if (N00.getOpcode() != ISD::OR)
3420 return SDValue();
3421 SDValue N000 = N00.getOperand(0);
3422 if (!isBSwapHWordElement(N000, Parts))
3423 return SDValue();
3424 SDValue N001 = N00.getOperand(1);
3425 if (!isBSwapHWordElement(N001, Parts))
3426 return SDValue();
3427 }
3428
3429 // Make sure the parts are all coming from the same node.
3430 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3431 return SDValue();
3432
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003433 SDLoc DL(N);
3434 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3435 SDValue(Parts[0], 0));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003436
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003437 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003438 // do (x << 16) | (x >> 16).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003439 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003440 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003441 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003442 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003443 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3444 return DAG.getNode(ISD::OR, DL, VT,
3445 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3446 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003447}
3448
Matthias Braun3ecb5572015-03-06 19:49:06 +00003449/// This contains all DAGCombine rules which reduce two values combined by
3450/// an Or operation to a single value \see visitANDLike().
3451SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3452 EVT VT = N1.getValueType();
3453 // fold (or x, undef) -> -1
3454 if (!LegalOperations &&
3455 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3456 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003457 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3458 SDLoc(LocReference), VT);
Matthias Braun3ecb5572015-03-06 19:49:06 +00003459 }
3460 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3461 SDValue LL, LR, RL, RR, CC0, CC1;
3462 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3463 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3464 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3465
Matthias Braun03312192015-05-19 00:25:20 +00003466 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003467 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3468 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Matthias Braun1505efb2015-05-18 23:07:27 +00003469 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003470 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3471 LR.getValueType(), LL, RL);
3472 AddToWorklist(ORNode.getNode());
3473 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3474 }
3475 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3476 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Matthias Braun03312192015-05-19 00:25:20 +00003477 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003478 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3479 LR.getValueType(), LL, RL);
3480 AddToWorklist(ANDNode.getNode());
3481 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3482 }
3483 }
3484 // canonicalize equivalent to ll == rl
3485 if (LL == RR && LR == RL) {
3486 Op1 = ISD::getSetCCSwappedOperands(Op1);
3487 std::swap(RL, RR);
3488 }
3489 if (LL == RL && LR == RR) {
3490 bool isInteger = LL.getValueType().isInteger();
3491 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3492 if (Result != ISD::SETCC_INVALID &&
3493 (!LegalOperations ||
3494 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3495 TLI.isOperationLegal(ISD::SETCC,
3496 getSetCCResultType(N0.getValueType())))))
3497 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3498 LL, LR, Result);
3499 }
3500 }
3501
3502 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Matthias Braun56a78142015-05-20 18:54:02 +00003503 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
Matthias Braun3ecb5572015-03-06 19:49:06 +00003504 // Don't increase # computations.
3505 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3506 // We can only do this xform if we know that bits from X that are set in C2
3507 // but not in C1 are already zero. Likewise for Y.
Matthias Braun56a78142015-05-20 18:54:02 +00003508 if (const ConstantSDNode *N0O1C =
3509 getAsNonOpaqueConstant(N0.getOperand(1))) {
3510 if (const ConstantSDNode *N1O1C =
3511 getAsNonOpaqueConstant(N1.getOperand(1))) {
3512 // We can only do this xform if we know that bits from X that are set in
3513 // C2 but not in C1 are already zero. Likewise for Y.
3514 const APInt &LHSMask = N0O1C->getAPIntValue();
3515 const APInt &RHSMask = N1O1C->getAPIntValue();
Matthias Braun3ecb5572015-03-06 19:49:06 +00003516
Matthias Braun56a78142015-05-20 18:54:02 +00003517 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3518 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3519 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3520 N0.getOperand(0), N1.getOperand(0));
3521 SDLoc DL(LocReference);
3522 return DAG.getNode(ISD::AND, DL, VT, X,
3523 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3524 }
3525 }
Matthias Braun3ecb5572015-03-06 19:49:06 +00003526 }
3527 }
3528
3529 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3530 if (N0.getOpcode() == ISD::AND &&
3531 N1.getOpcode() == ISD::AND &&
3532 N0.getOperand(0) == N1.getOperand(0) &&
3533 // Don't increase # computations.
3534 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3535 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3536 N0.getOperand(1), N1.getOperand(1));
3537 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3538 }
3539
3540 return SDValue();
3541}
3542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003543SDValue DAGCombiner::visitOR(SDNode *N) {
3544 SDValue N0 = N->getOperand(0);
3545 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003546 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003547
Dan Gohmana8665142007-06-25 16:23:39 +00003548 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003549 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003550 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3551 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003552
3553 // fold (or x, 0) -> x, vector edition
3554 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3555 return N1;
3556 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3557 return N0;
3558
3559 // fold (or x, -1) -> -1, vector edition
3560 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003561 // do not return N0, because undef node may exist in N0
3562 return DAG.getConstant(
3563 APInt::getAllOnesValue(
3564 N0.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003565 SDLoc(N), N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003566 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003567 // do not return N1, because undef node may exist in N1
3568 return DAG.getConstant(
3569 APInt::getAllOnesValue(
3570 N1.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003571 SDLoc(N), N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003572
3573 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3574 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3575 // Do this only if the resulting shuffle is legal.
3576 if (isa<ShuffleVectorSDNode>(N0) &&
3577 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003578 // Avoid folding a node with illegal type.
3579 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003580 N0->getOperand(1) == N1->getOperand(1) &&
3581 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3582 bool CanFold = true;
3583 unsigned NumElts = VT.getVectorNumElements();
3584 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3585 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3586 // We construct two shuffle masks:
3587 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3588 // and N1 as the second operand.
3589 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3590 // and N0 as the second operand.
3591 // We do this because OR is commutable and therefore there might be
3592 // two ways to fold this node into a shuffle.
3593 SmallVector<int,4> Mask1;
3594 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003595
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003596 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3597 int M0 = SV0->getMaskElt(i);
3598 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003599
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003600 // Both shuffle indexes are undef. Propagate Undef.
3601 if (M0 < 0 && M1 < 0) {
3602 Mask1.push_back(M0);
3603 Mask2.push_back(M0);
3604 continue;
3605 }
3606
3607 if (M0 < 0 || M1 < 0 ||
3608 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3609 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3610 CanFold = false;
3611 break;
3612 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003613
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003614 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3615 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3616 }
3617
3618 if (CanFold) {
3619 // Fold this sequence only if the resulting shuffle is 'legal'.
3620 if (TLI.isShuffleMaskLegal(Mask1, VT))
3621 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3622 N1->getOperand(0), &Mask1[0]);
3623 if (TLI.isShuffleMaskLegal(Mask2, VT))
3624 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3625 N0->getOperand(0), &Mask2[0]);
3626 }
3627 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003628 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003629
Nate Begeman21158fc2005-09-01 00:19:25 +00003630 // fold (or c1, c2) -> c1|c2
Matthias Braun56a78142015-05-20 18:54:02 +00003631 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
Matthias Braun00a40762015-02-24 18:52:01 +00003632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Matthias Braun56a78142015-05-20 18:54:02 +00003633 if (N0C && N1C && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003634 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003635 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003636 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3637 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003638 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003639 // fold (or x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00003640 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003641 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003642 // fold (or x, -1) -> -1
Matthias Braun03312192015-05-19 00:25:20 +00003643 if (isAllOnesConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003644 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003645 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003646 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003647 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003648
Matthias Braun3ecb5572015-03-06 19:49:06 +00003649 if (SDValue Combined = visitORLike(N0, N1, N))
3650 return Combined;
3651
Evan Cheng4c0bd962011-06-21 06:01:08 +00003652 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3653 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003654 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003655 return BSwap;
3656 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003657 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003658 return BSwap;
3659
Nate Begeman22e251a2006-02-03 06:46:56 +00003660 // reassociate or
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003661 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003662 return ROR;
3663 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003664 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003665 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003666 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003667 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003668 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003669 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3670 N1C, C1))
Matthias Braunf50ab432015-01-13 22:17:46 +00003671 return DAG.getNode(
3672 ISD::AND, SDLoc(N), VT,
3673 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3674 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003675 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003676 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003677 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003678 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003679 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003680 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003681 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003682
Chris Lattner97614c82006-09-14 20:50:57 +00003683 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003684 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003685 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003686
Dan Gohman600f62b2010-06-24 14:30:44 +00003687 // Simplify the operands using demanded-bits information.
3688 if (!VT.isVector() &&
3689 SimplifyDemandedBits(SDValue(N, 0)))
3690 return SDValue(N, 0);
3691
Evan Chengf1005572010-04-28 07:10:39 +00003692 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003693}
3694
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003695/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003696static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003697 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003698 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003699 Mask = Op.getOperand(1);
3700 Op = Op.getOperand(0);
3701 } else {
3702 return false;
3703 }
3704 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003705
Chris Lattner97614c82006-09-14 20:50:57 +00003706 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3707 Shift = Op;
3708 return true;
3709 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003710
Scott Michelcf0da6c2009-02-17 22:15:04 +00003711 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003712}
3713
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003714// Return true if we can prove that, whenever Neg and Pos are both in the
3715// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003716// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3717//
3718// (or (shift1 X, Neg), (shift2 X, Pos))
3719//
Adam Nemetc6553a82014-03-07 23:56:24 +00003720// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3721// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3722// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003723static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003724 // If OpSize is a power of 2 then:
3725 //
3726 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3727 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3728 //
3729 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3730 // for the stronger condition:
3731 //
3732 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3733 //
3734 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3735 // we can just replace Neg with Neg' for the rest of the function.
3736 //
3737 // In other cases we check for the even stronger condition:
3738 //
3739 // Neg == OpSize - Pos [B]
3740 //
3741 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3742 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003743 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003744 // We could actually use [A] whenever OpSize is a power of 2, but the
3745 // only extra cases that it would match are those uninteresting ones
3746 // where Neg and Pos are never in range at the same time. E.g. for
3747 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3748 // as well as (sub 32, Pos), but:
3749 //
3750 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3751 //
3752 // always invokes undefined behavior for 32-bit X.
3753 //
3754 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003755 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003756 if (Neg.getOpcode() == ISD::AND &&
3757 isPowerOf2_64(OpSize) &&
3758 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3759 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3760 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003761 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003762 }
3763
Richard Sandiford0f264db2014-01-09 10:49:40 +00003764 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3765 if (Neg.getOpcode() != ISD::SUB)
3766 return 0;
3767 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3768 if (!NegC)
3769 return 0;
3770 SDValue NegOp1 = Neg.getOperand(1);
3771
Adam Nemet5117f5d2014-03-07 23:56:28 +00003772 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3773 // Pos'. The truncation is redundant for the purpose of the equality.
3774 if (MaskLoBits &&
3775 Pos.getOpcode() == ISD::AND &&
3776 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3777 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3778 Pos = Pos.getOperand(0);
3779
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003780 // The condition we need is now:
3781 //
3782 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3783 //
3784 // If NegOp1 == Pos then we need:
3785 //
3786 // OpSize & Mask == NegC & Mask
3787 //
3788 // (because "x & Mask" is a truncation and distributes through subtraction).
3789 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003790 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003791 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003792 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3793 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003794 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003795 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3796 //
3797 // which, again because "x & Mask" is a truncation, becomes:
3798 //
3799 // NegC & Mask == (OpSize - PosC) & Mask
3800 // OpSize & Mask == (NegC + PosC) & Mask
3801 else if (Pos.getOpcode() == ISD::ADD &&
3802 Pos.getOperand(0) == NegOp1 &&
3803 Pos.getOperand(1).getOpcode() == ISD::Constant)
3804 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3805 NegC->getAPIntValue());
3806 else
3807 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003808
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003809 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003810 if (MaskLoBits)
3811 // Opsize & Mask is 0 since Mask is Opsize - 1.
3812 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003813 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003814}
3815
Richard Sandiford95c864d2014-01-08 15:40:47 +00003816// A subroutine of MatchRotate used once we have found an OR of two opposite
3817// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3818// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3819// former being preferred if supported. InnerPos and InnerNeg are Pos and
3820// Neg with outer conversions stripped away.
3821SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3822 SDValue Neg, SDValue InnerPos,
3823 SDValue InnerNeg, unsigned PosOpcode,
3824 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003825 // fold (or (shl x, (*ext y)),
3826 // (srl x, (*ext (sub 32, y)))) ->
3827 // (rotl x, y) or (rotr x, (sub 32, y))
3828 //
3829 // fold (or (shl x, (*ext (sub 32, y))),
3830 // (srl x, (*ext y))) ->
3831 // (rotr x, y) or (rotl x, (sub 32, y))
3832 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003833 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003834 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3835 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3836 HasPos ? Pos : Neg).getNode();
3837 }
3838
Craig Topperc0196b12014-04-14 00:51:57 +00003839 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003840}
3841
Chris Lattner97614c82006-09-14 20:50:57 +00003842// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3843// idioms for rotate, and if the target supports rotation instructions, generate
3844// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003845SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003846 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003847 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003848 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003849
3850 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003851 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3852 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003853 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003854
Chris Lattner97614c82006-09-14 20:50:57 +00003855 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003856 SDValue LHSShift; // The shift.
3857 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003858 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003859 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003861 SDValue RHSShift; // The shift.
3862 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003863 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003864 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003865
Chris Lattner97614c82006-09-14 20:50:57 +00003866 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003867 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003868
3869 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003870 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003871
Chris Lattner97614c82006-09-14 20:50:57 +00003872 // Canonicalize shl to left side in a shl/srl pair.
3873 if (RHSShift.getOpcode() == ISD::SHL) {
3874 std::swap(LHS, RHS);
3875 std::swap(LHSShift, RHSShift);
3876 std::swap(LHSMask , RHSMask );
3877 }
3878
Duncan Sands13237ac2008-06-06 12:08:01 +00003879 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003880 SDValue LHSShiftArg = LHSShift.getOperand(0);
3881 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003882 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003883 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003884
3885 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3886 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003887 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3888 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003889 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3890 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003891 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003892 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003893
Craig Topper65161fa2012-09-29 06:54:22 +00003894 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3895 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003896
Chris Lattner97614c82006-09-14 20:50:57 +00003897 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003898 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003899 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003900
Gabor Greiff304a7a2008-08-28 21:40:38 +00003901 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003902 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3903 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003904 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003905 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003906 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3907 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003908 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003909
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003910 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003911 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003912
Gabor Greiff304a7a2008-08-28 21:40:38 +00003913 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003914 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003915
Chris Lattner97614c82006-09-14 20:50:57 +00003916 // If there is a mask here, and we have a variable shift, we can't be sure
3917 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003918 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003919 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003920
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003921 // If the shift amount is sign/zext/any-extended just peel it off.
3922 SDValue LExtOp0 = LHSShiftAmt;
3923 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003924 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3925 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3926 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3927 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3928 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3929 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3930 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3931 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003932 LExtOp0 = LHSShiftAmt.getOperand(0);
3933 RExtOp0 = RHSShiftAmt.getOperand(0);
3934 }
3935
Richard Sandiford95c864d2014-01-08 15:40:47 +00003936 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3937 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3938 if (TryL)
3939 return TryL;
3940
3941 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3942 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3943 if (TryR)
3944 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003945
Craig Topperc0196b12014-04-14 00:51:57 +00003946 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003947}
3948
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003949SDValue DAGCombiner::visitXOR(SDNode *N) {
3950 SDValue N0 = N->getOperand(0);
3951 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003952 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003953
Dan Gohmana8665142007-06-25 16:23:39 +00003954 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003955 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003956 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3957 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003958
3959 // fold (xor x, 0) -> x, vector edition
3960 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3961 return N1;
3962 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3963 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003964 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003965
Evan Chengdf1690d2008-03-25 20:08:07 +00003966 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3967 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003968 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003969 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003970 if (N0.getOpcode() == ISD::UNDEF)
3971 return N0;
3972 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003973 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003974 // fold (xor c1, c2) -> c1^c2
Matthias Braun56a78142015-05-20 18:54:02 +00003975 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3976 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003977 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003978 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003979 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003980 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3981 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003982 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003983 // fold (xor x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00003984 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003985 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003986 // reassociate xor
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003987 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003988 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003989
Nate Begeman21158fc2005-09-01 00:19:25 +00003990 // fold !(x cc y) -> (x !cc y)
Matthias Brauna8558ca2015-02-24 18:51:59 +00003991 SDValue LHS, RHS, CC;
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003992 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003993 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003994 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3995 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003996
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003997 if (!LegalOperations ||
3998 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003999 switch (N0.getOpcode()) {
4000 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00004001 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00004002 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00004003 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00004004 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00004005 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00004006 N0.getOperand(3), NotCC);
4007 }
4008 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004009 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00004010
Chris Lattner58c227b2007-09-10 21:39:07 +00004011 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Matthias Braun887fdfb2015-05-19 00:25:21 +00004012 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00004013 N0.getNode()->hasOneUse() &&
4014 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004015 SDValue V = N0.getOperand(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004016 SDLoc DL(N0);
4017 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4018 DAG.getConstant(1, DL, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004019 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004020 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00004021 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004022
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004023 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Matthias Braun887fdfb2015-05-19 00:25:21 +00004024 if (isOneConstant(N1) && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004025 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004026 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004027 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4028 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004029 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4030 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004031 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004032 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00004033 }
4034 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004035 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Matthias Braun03312192015-05-19 00:25:20 +00004036 if (isAllOnesConstant(N1) &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004037 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004038 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004039 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4040 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004041 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4042 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004043 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004044 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00004045 }
4046 }
David Majnemer386ab7f2013-05-08 06:44:42 +00004047 // fold (xor (and x, y), y) -> (and (not x), y)
4048 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00004049 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00004050 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004051 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004052 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004053 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00004054 }
Bill Wendling35972a92009-01-30 21:14:50 +00004055 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00004056 if (N1C && N0.getOpcode() == ISD::XOR) {
Matthias Braun56a78142015-05-20 18:54:02 +00004057 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004058 SDLoc DL(N);
4059 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00004060 DAG.getConstant(N1C->getAPIntValue() ^
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004061 N00C->getAPIntValue(), DL, VT));
4062 }
Matthias Braun56a78142015-05-20 18:54:02 +00004063 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004064 SDLoc DL(N);
4065 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00004066 DAG.getConstant(N1C->getAPIntValue() ^
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004067 N01C->getAPIntValue(), DL, VT));
4068 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00004069 }
4070 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00004071 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00004072 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004073
David Majnemere48237d2015-03-18 00:03:36 +00004074 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4075 // Here is a concrete example of this equivalence:
4076 // i16 x == 14
4077 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4078 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4079 //
4080 // =>
4081 //
4082 // i16 ~1 == 0b1111111111111110
4083 // i16 rol(~1, 14) == 0b1011111111111111
4084 //
4085 // Some additional tips to help conceptualize this transform:
4086 // - Try to see the operation as placing a single zero in a value of all ones.
4087 // - There exists no value for x which would allow the result to contain zero.
4088 // - Values of x larger than the bitwidth are undefined and do not require a
4089 // consistent result.
4090 // - Pushing the zero left requires shifting one bits in from the right.
4091 // A rotate left of ~1 is a nice way of achieving the desired result.
Matthias Braun887fdfb2015-05-19 00:25:21 +00004092 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4093 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4094 SDLoc DL(N);
4095 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4096 N0.getOperand(1));
4097 }
David Majnemere48237d2015-03-18 00:03:36 +00004098
Chris Lattner8d6fc202006-05-05 05:51:50 +00004099 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4100 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004101 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004102 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00004103 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004104
Chris Lattner098c01e2006-04-08 04:15:24 +00004105 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00004106 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004107 SimplifyDemandedBits(SDValue(N, 0)))
4108 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004109
Evan Chengf1005572010-04-28 07:10:39 +00004110 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004111}
4112
Sanjay Patel50cbfc52014-08-28 16:29:51 +00004113/// Handle transforms common to the three shifts, when the shift amount is a
4114/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004115SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004116 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004117 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004118
Chris Lattner7c709a52007-12-06 07:33:36 +00004119 // We want to pull some binops through shifts, so that we have (and (shift))
4120 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4121 // thing happens with address calculations, so it's important to canonicalize
4122 // it.
4123 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00004124
Chris Lattner7c709a52007-12-06 07:33:36 +00004125 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004126 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004127 case ISD::OR:
4128 case ISD::XOR:
4129 HighBitSet = false; // We can only transform sra if the high bit is clear.
4130 break;
4131 case ISD::AND:
4132 HighBitSet = true; // We can only transform sra if the high bit is set.
4133 break;
4134 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00004135 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004136 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00004137 HighBitSet = false; // We can only transform sra if the high bit is clear.
4138 break;
4139 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004140
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004141 // We require the RHS of the binop to be a constant and not opaque as well.
Matthias Braun56a78142015-05-20 18:54:02 +00004142 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4143 if (!BinOpCst) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004144
4145 // FIXME: disable this unless the input to the binop is a shift by a constant.
4146 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004147 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004148 // void foo(int *X, int i) { X[i & 1235] = 1; }
4149 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004150 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004151 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004152 BinOpLHSVal->getOpcode() != ISD::SRA &&
4153 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4154 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004155 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004156
Owen Anderson53aa7a92009-08-10 22:56:29 +00004157 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004158
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004159 // If this is a signed shift right, and the high bit is modified by the
4160 // logical operation, do not perform the transformation. The highBitSet
4161 // boolean indicates the value of the high bit of the constant which would
4162 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004163 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004164 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4165 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004166 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004167 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004168
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004169 if (!TLI.isDesirableToCommuteWithShift(LHS))
4170 return SDValue();
4171
Chris Lattner7c709a52007-12-06 07:33:36 +00004172 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004173 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004174 N->getValueType(0),
4175 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004176 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004177
4178 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004179 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004180 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004181 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004182
4183 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004184 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004185}
4186
Adam Nemet67483892014-03-04 23:28:31 +00004187SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4188 assert(N->getOpcode() == ISD::TRUNCATE);
4189 assert(N->getOperand(0).getOpcode() == ISD::AND);
4190
4191 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4192 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4193 SDValue N01 = N->getOperand(0).getOperand(1);
4194
Matt Arsenault985b9de2014-03-17 18:58:01 +00004195 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Matthias Braun56a78142015-05-20 18:54:02 +00004196 if (!N01C->isOpaque()) {
4197 EVT TruncVT = N->getValueType(0);
4198 SDValue N00 = N->getOperand(0).getOperand(0);
4199 APInt TruncC = N01C->getAPIntValue();
4200 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4201 SDLoc DL(N);
Adam Nemet67483892014-03-04 23:28:31 +00004202
Matthias Braun56a78142015-05-20 18:54:02 +00004203 return DAG.getNode(ISD::AND, DL, TruncVT,
4204 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4205 DAG.getConstant(TruncC, DL, TruncVT));
4206 }
Adam Nemet67483892014-03-04 23:28:31 +00004207 }
4208 }
4209
4210 return SDValue();
4211}
Adam Nemet7f928f12014-03-07 23:56:30 +00004212
4213SDValue DAGCombiner::visitRotate(SDNode *N) {
4214 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4215 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4216 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4217 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4218 if (NewOp1.getNode())
4219 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4220 N->getOperand(0), NewOp1);
4221 }
4222 return SDValue();
4223}
4224
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004225SDValue DAGCombiner::visitSHL(SDNode *N) {
4226 SDValue N0 = N->getOperand(0);
4227 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004228 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004229 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004230
Daniel Sandersa1840d22013-11-11 17:23:41 +00004231 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004233 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004234 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4235 return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004236
4237 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4238 // If setcc produces all-one true value then:
4239 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004240 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004241 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004242 SDValue N00 = N0->getOperand(0);
4243 SDValue N01 = N0->getOperand(1);
4244 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004245
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004246 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4247 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4248 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004249 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4250 N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004251 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4252 }
4253 } else {
4254 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004255 }
4256 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004257 }
4258
Nate Begeman21158fc2005-09-01 00:19:25 +00004259 // fold (shl c1, c2) -> c1<<c2
Matthias Braun56a78142015-05-20 18:54:02 +00004260 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4261 if (N0C && N1C && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004262 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004263 // fold (shl 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004264 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004265 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004266 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004267 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004268 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004269 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004270 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004271 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004272 // fold (shl undef, x) -> 0
4273 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004274 return DAG.getConstant(0, SDLoc(N), VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004275 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004276 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004277 APInt::getAllOnesValue(OpSizeInBits)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004278 return DAG.getConstant(0, SDLoc(N), VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004279 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004280 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004281 N1.getOperand(0).getOpcode() == ISD::AND) {
4282 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4283 if (NewOp1.getNode())
4284 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004285 }
4286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004287 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4288 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004289
4290 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004291 if (N1C && N0.getOpcode() == ISD::SHL) {
4292 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4293 uint64_t c1 = N0C1->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004295 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004296 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004297 return DAG.getConstant(0, DL, VT);
4298 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4299 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004300 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004301 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004302
4303 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4304 // For this to be valid, the second form must not preserve any of the bits
4305 // that are shifted out by the inner shift in the first form. This means
4306 // the outer shift size must be >= the number of bits added by the ext.
4307 // As a corollary, we don't care what kind of ext it is.
4308 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4309 N0.getOpcode() == ISD::ANY_EXTEND ||
4310 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004311 N0.getOperand(0).getOpcode() == ISD::SHL) {
4312 SDValue N0Op0 = N0.getOperand(0);
4313 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4314 uint64_t c1 = N0Op0C1->getZExtValue();
4315 uint64_t c2 = N1C->getZExtValue();
4316 EVT InnerShiftVT = N0Op0.getValueType();
4317 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4318 if (c2 >= OpSizeInBits - InnerShiftSize) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004319 SDLoc DL(N0);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004320 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004321 return DAG.getConstant(0, DL, VT);
4322 return DAG.getNode(ISD::SHL, DL, VT,
4323 DAG.getNode(N0.getOpcode(), DL, VT,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004324 N0Op0->getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004325 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004326 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004327 }
4328 }
4329
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004330 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4331 // Only fold this if the inner zext has no other uses to avoid increasing
4332 // the total number of instructions.
4333 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004334 N0.getOperand(0).getOpcode() == ISD::SRL) {
4335 SDValue N0Op0 = N0.getOperand(0);
4336 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4337 uint64_t c1 = N0Op0C1->getZExtValue();
4338 if (c1 < VT.getScalarSizeInBits()) {
4339 uint64_t c2 = N1C->getZExtValue();
4340 if (c1 == c2) {
4341 SDValue NewOp0 = N0.getOperand(0);
4342 EVT CountVT = NewOp0.getOperand(1).getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004343 SDLoc DL(N);
4344 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4345 NewOp0,
4346 DAG.getConstant(c2, DL, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004347 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004348 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4349 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004350 }
4351 }
4352 }
4353
Eli Friedman1877ac92011-06-09 22:14:44 +00004354 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4355 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004356 // Only fold this if the inner shift has no other uses -- if it does, folding
4357 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004358 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4359 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4360 uint64_t c1 = N0C1->getZExtValue();
4361 if (c1 < OpSizeInBits) {
4362 uint64_t c2 = N1C->getZExtValue();
4363 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4364 SDValue Shift;
4365 if (c2 > c1) {
4366 Mask = Mask.shl(c2 - c1);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004367 SDLoc DL(N);
4368 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4369 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004370 } else {
4371 Mask = Mask.lshr(c1 - c2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004372 SDLoc DL(N);
4373 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4374 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004375 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004376 SDLoc DL(N0);
4377 return DAG.getNode(ISD::AND, DL, VT, Shift,
4378 DAG.getConstant(Mask, DL, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004379 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004380 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004381 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004382 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004383 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004384 unsigned BitSize = VT.getScalarSizeInBits();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004385 SDLoc DL(N);
Dan Gohman5758e1e2009-08-06 09:18:59 +00004386 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004387 DAG.getConstant(APInt::getHighBitsSet(BitSize,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004388 BitSize - N1C->getZExtValue()),
4389 DL, VT);
4390 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004391 HiBitsMask);
4392 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004393
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004394 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4395 // Variant of version done on multiply, except mul by a power of 2 is turned
4396 // into a shift.
4397 APInt Val;
4398 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4399 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4400 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4401 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4402 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4403 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4404 }
4405
Matthias Braun56a78142015-05-20 18:54:02 +00004406 if (N1C && !N1C->isOpaque()) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004407 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004408 if (NewSHL.getNode())
4409 return NewSHL;
4410 }
4411
Evan Chengf1005572010-04-28 07:10:39 +00004412 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004413}
4414
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004415SDValue DAGCombiner::visitSRA(SDNode *N) {
4416 SDValue N0 = N->getOperand(0);
4417 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004418 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004419 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004420
Daniel Sandersa1840d22013-11-11 17:23:41 +00004421 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004422 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004423 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004424 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4425 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004426
4427 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004428 }
4429
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004430 // fold (sra c1, c2) -> (sra c1, c2)
Matthias Braun56a78142015-05-20 18:54:02 +00004431 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4432 if (N0C && N1C && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004433 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004434 // fold (sra 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004435 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004436 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004437 // fold (sra -1, x) -> -1
Matthias Braun03312192015-05-19 00:25:20 +00004438 if (isAllOnesConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004439 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004440 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004441 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004442 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004443 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004444 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004445 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004446 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4447 // sext_inreg.
4448 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004449 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004450 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4451 if (VT.isVector())
4452 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4453 ExtVT, VT.getVectorNumElements());
4454 if ((!LegalOperations ||
4455 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004457 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004458 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004459
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004460 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004461 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004462 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004463 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004464 if (Sum >= OpSizeInBits)
4465 Sum = OpSizeInBits - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004466 SDLoc DL(N);
4467 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4468 DAG.getConstant(Sum, DL, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004469 }
4470 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004471
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004472 // fold (sra (shl X, m), (sub result_size, n))
4473 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004474 // result_size - n != m.
4475 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004476 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004477 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004478 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004479 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4480 if (N01C) {
4481 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004482 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004483 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4484
4485 if (VT.isVector())
4486 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4487
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004488 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004489 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004490
Scott Michelcf0da6c2009-02-17 22:15:04 +00004491 // If the shift is not a no-op (in which case this should be just a sign
4492 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004493 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004494 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004495 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004496 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4497 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004498 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004499
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004500 SDLoc DL(N);
4501 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4502 getShiftAmountTy(N0.getOperand(0).getValueType()));
4503 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4504 N0.getOperand(0), Amt);
4505 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4506 Shift);
4507 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4508 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004509 }
4510 }
4511 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004512
Duncan Sands3ed76882009-02-01 18:06:53 +00004513 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004514 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004515 N1.getOperand(0).getOpcode() == ISD::AND) {
4516 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4517 if (NewOp1.getNode())
4518 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004519 }
4520
Matt Arsenault985b9de2014-03-17 18:58:01 +00004521 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004522 // if c1 is equal to the number of bits the trunc removes
4523 if (N0.getOpcode() == ISD::TRUNCATE &&
4524 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4525 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4526 N0.getOperand(0).hasOneUse() &&
4527 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004528 N1C) {
4529 SDValue N0Op0 = N0.getOperand(0);
4530 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4531 unsigned LargeShiftVal = LargeShift->getZExtValue();
4532 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004533
Matt Arsenault985b9de2014-03-17 18:58:01 +00004534 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004535 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004536 SDValue Amt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004537 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004538 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004539 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004540 N0Op0.getOperand(0), Amt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004541 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004542 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004543 }
4544 }
4545
Scott Michelcf0da6c2009-02-17 22:15:04 +00004546 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004547 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4548 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
4550
Nate Begeman21158fc2005-09-01 00:19:25 +00004551 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004552 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004553 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004554
Matthias Braun56a78142015-05-20 18:54:02 +00004555 if (N1C && !N1C->isOpaque()) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004556 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004557 if (NewSRA.getNode())
4558 return NewSRA;
4559 }
4560
Evan Chengf1005572010-04-28 07:10:39 +00004561 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004562}
4563
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004564SDValue DAGCombiner::visitSRL(SDNode *N) {
4565 SDValue N0 = N->getOperand(0);
4566 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004567 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004568 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004569
Daniel Sandersa1840d22013-11-11 17:23:41 +00004570 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004571 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004572 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004573 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4574 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004575
4576 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004577 }
4578
Nate Begeman21158fc2005-09-01 00:19:25 +00004579 // fold (srl c1, c2) -> c1 >>u c2
Matthias Braun56a78142015-05-20 18:54:02 +00004580 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4581 if (N0C && N1C && !N1C->isOpaque())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004582 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004583 // fold (srl 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004584 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004585 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004586 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004587 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004588 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004589 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004590 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004591 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004592 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004593 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004594 APInt::getAllOnesValue(OpSizeInBits)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004595 return DAG.getConstant(0, SDLoc(N), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004596
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004597 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004598 if (N1C && N0.getOpcode() == ISD::SRL) {
4599 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4600 uint64_t c1 = N01C->getZExtValue();
4601 uint64_t c2 = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004602 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004603 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004604 return DAG.getConstant(0, DL, VT);
4605 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4606 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004607 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004608 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004609
Dale Johannesencd538af2010-12-17 21:45:49 +00004610 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004611 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4612 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004613 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004614 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004615 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4616 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004617 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4618 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004619 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004620 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004621 if (c1 + OpSizeInBits == InnerShiftSize) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004622 SDLoc DL(N0);
Dale Johannesencd538af2010-12-17 21:45:49 +00004623 if (c1 + c2 >= InnerShiftSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004624 return DAG.getConstant(0, DL, VT);
4625 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4626 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004627 N0.getOperand(0)->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004628 DAG.getConstant(c1 + c2, DL,
4629 ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004630 }
4631 }
4632
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004633 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004634 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4635 unsigned BitSize = N0.getScalarValueSizeInBits();
4636 if (BitSize <= 64) {
4637 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004638 SDLoc DL(N);
4639 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4640 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004641 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004642 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004643
Michael Liao62ebfd82013-06-21 18:45:27 +00004644 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004645 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4646 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004647 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004648 unsigned BitSize = SmallVT.getScalarSizeInBits();
4649 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004650 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004651
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004652 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004653 uint64_t ShiftAmt = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004654 SDLoc DL0(N0);
4655 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004656 N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004657 DAG.getConstant(ShiftAmt, DL0,
4658 getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004659 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004660 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004661 SDLoc DL(N);
4662 return DAG.getNode(ISD::AND, DL, VT,
4663 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4664 DAG.getConstant(Mask, DL, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004665 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004666 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004667
Chris Lattner2e33fb42006-10-12 20:23:19 +00004668 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4669 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004670 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004671 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004672 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004673 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004674
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004675 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004676 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004677 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004678 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004679 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004680
Chris Lattner49932492006-04-02 06:11:11 +00004681 // If any of the input bits are KnownOne, then the input couldn't be all
4682 // zeros, thus the result of the srl will always be zero.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004683 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004684
Chris Lattner49932492006-04-02 06:11:11 +00004685 // If all of the bits input the to ctlz node are known to be zero, then
4686 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004687 APInt UnknownBits = ~KnownZero;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004688 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004689
Chris Lattner49932492006-04-02 06:11:11 +00004690 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004691 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004692 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004693 // could be set on input to the CTLZ node. If this bit is set, the SRL
4694 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4695 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004696 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004697 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004698
Chris Lattner49932492006-04-02 06:11:11 +00004699 if (ShAmt) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004700 SDLoc DL(N0);
4701 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4702 DAG.getConstant(ShAmt, DL,
4703 getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004704 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004705 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004706
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004707 SDLoc DL(N);
4708 return DAG.getNode(ISD::XOR, DL, VT,
4709 Op, DAG.getConstant(1, DL, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004710 }
4711 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004712
Duncan Sands3ed76882009-02-01 18:06:53 +00004713 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004714 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004715 N1.getOperand(0).getOpcode() == ISD::AND) {
4716 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4717 if (NewOp1.getNode())
4718 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004719 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004720
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004721 // fold operands of srl based on knowledge that the low bits are not
4722 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004723 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4724 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004725
Matthias Braun56a78142015-05-20 18:54:02 +00004726 if (N1C && !N1C->isOpaque()) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004727 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004728 if (NewSRL.getNode())
4729 return NewSRL;
4730 }
4731
Dan Gohman600f62b2010-06-24 14:30:44 +00004732 // Attempt to convert a srl of a load into a narrower zero-extending load.
4733 SDValue NarrowLoad = ReduceLoadWidth(N);
4734 if (NarrowLoad.getNode())
4735 return NarrowLoad;
4736
Evan Chengb175de62009-12-18 21:31:31 +00004737 // Here is a common situation. We want to optimize:
4738 //
4739 // %a = ...
4740 // %b = and i32 %a, 2
4741 // %c = srl i32 %b, 1
4742 // brcond i32 %c ...
4743 //
4744 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004745 //
Evan Chengb175de62009-12-18 21:31:31 +00004746 // %a = ...
4747 // %b = and %a, 2
4748 // %c = setcc eq %b, 0
4749 // brcond %c ...
4750 //
4751 // However when after the source operand of SRL is optimized into AND, the SRL
4752 // itself may not be optimized further. Look for it and add the BRCOND into
4753 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004754 if (N->hasOneUse()) {
4755 SDNode *Use = *N->use_begin();
4756 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004757 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004758 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4759 // Also look pass the truncate.
4760 Use = *Use->use_begin();
4761 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004762 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004763 }
4764 }
Evan Chengb175de62009-12-18 21:31:31 +00004765
Evan Chengf1005572010-04-28 07:10:39 +00004766 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004767}
4768
Simon Pilgrim011381d2015-06-13 14:08:15 +00004769SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4770 SDValue N0 = N->getOperand(0);
4771 EVT VT = N->getValueType(0);
4772
4773 // fold (bswap c1) -> c2
4774 if (isConstantIntBuildVectorOrConstantInt(N0))
4775 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4776 return SDValue();
4777}
4778
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004779SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4780 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004781 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004782
4783 // fold (ctlz c1) -> c2
Simon Pilgrim4791f6d2015-06-08 16:19:00 +00004784 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004785 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004786 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004787}
4788
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004789SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4790 SDValue N0 = N->getOperand(0);
4791 EVT VT = N->getValueType(0);
4792
4793 // fold (ctlz_zero_undef c1) -> c2
Simon Pilgrim4791f6d2015-06-08 16:19:00 +00004794 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004795 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004796 return SDValue();
4797}
4798
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004799SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4800 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004801 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004802
Nate Begeman21158fc2005-09-01 00:19:25 +00004803 // fold (cttz c1) -> c2
Simon Pilgrimc789e1d2015-06-08 09:57:09 +00004804 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004805 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004806 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004807}
4808
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004809SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4810 SDValue N0 = N->getOperand(0);
4811 EVT VT = N->getValueType(0);
4812
4813 // fold (cttz_zero_undef c1) -> c2
Simon Pilgrimc789e1d2015-06-08 09:57:09 +00004814 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004815 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004816 return SDValue();
4817}
4818
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004819SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4820 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004821 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004822
Nate Begeman21158fc2005-09-01 00:19:25 +00004823 // fold (ctpop c1) -> c2
Simon Pilgrim68cd2372015-06-07 15:37:14 +00004824 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004825 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004826 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004827}
4828
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004829
4830/// \brief Generate Min/Max node
4831static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4832 SDValue True, SDValue False,
4833 ISD::CondCode CC, const TargetLowering &TLI,
4834 SelectionDAG &DAG) {
4835 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4836 return SDValue();
4837
4838 switch (CC) {
4839 case ISD::SETOLT:
4840 case ISD::SETOLE:
4841 case ISD::SETLT:
4842 case ISD::SETLE:
4843 case ISD::SETULT:
4844 case ISD::SETULE: {
4845 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4846 if (TLI.isOperationLegal(Opcode, VT))
4847 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4848 return SDValue();
4849 }
4850 case ISD::SETOGT:
4851 case ISD::SETOGE:
4852 case ISD::SETGT:
4853 case ISD::SETGE:
4854 case ISD::SETUGT:
4855 case ISD::SETUGE: {
4856 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4857 if (TLI.isOperationLegal(Opcode, VT))
4858 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4859 return SDValue();
4860 }
4861 default:
4862 return SDValue();
4863 }
4864}
4865
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004866SDValue DAGCombiner::visitSELECT(SDNode *N) {
4867 SDValue N0 = N->getOperand(0);
4868 SDValue N1 = N->getOperand(1);
4869 SDValue N2 = N->getOperand(2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004870 EVT VT = N->getValueType(0);
4871 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004872
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004873 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004874 if (N1 == N2)
4875 return N1;
Matthias Braun1505efb2015-05-18 23:07:27 +00004876 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4877 // fold (select true, X, Y) -> X
4878 // fold (select false, X, Y) -> Y
4879 return !N0C->isNullValue() ? N1 : N2;
4880 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004881 // fold (select C, 1, X) -> (or C, X)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004882 if (VT == MVT::i1 && isOneConstant(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004883 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004884 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004885 // We can't do this reliably if integer based booleans have different contents
4886 // to floating point based booleans. This is because we can't tell whether we
4887 // have an integer-based boolean or a floating-point-based boolean unless we
4888 // can find the SETCC that produced it and inspect its operands. This is
4889 // fairly easy if C is the SETCC node, but it can potentially be
4890 // undiscoverable (or not reasonably discoverable). For example, it could be
4891 // in another basic block or it could require searching a complicated
4892 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004893 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004894 (VT0 == MVT::i1 || (VT0.isInteger() &&
4895 TLI.getBooleanContents(false, false) ==
4896 TLI.getBooleanContents(false, true) &&
4897 TLI.getBooleanContents(false, false) ==
4898 TargetLowering::ZeroOrOneBooleanContent)) &&
Matthias Braun887fdfb2015-05-19 00:25:21 +00004899 isNullConstant(N1) && isOneConstant(N2)) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004900 SDValue XORNode;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004901 if (VT == VT0) {
4902 SDLoc DL(N);
4903 return DAG.getNode(ISD::XOR, DL, VT0,
4904 N0, DAG.getConstant(1, DL, VT0));
4905 }
4906 SDLoc DL0(N0);
4907 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4908 N0, DAG.getConstant(1, DL0, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004909 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004910 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004911 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4912 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004913 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004914 // fold (select C, 0, X) -> (and (not C), X)
Matthias Braun1505efb2015-05-18 23:07:27 +00004915 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004916 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004917 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004918 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004919 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004920 // fold (select C, X, 1) -> (or (not C), X)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004921 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004922 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004923 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004924 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004925 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004926 // fold (select C, X, 0) -> (and C, X)
Matthias Braun1505efb2015-05-18 23:07:27 +00004927 if (VT == MVT::i1 && isNullConstant(N2))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004928 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004929 // fold (select X, X, Y) -> (or X, Y)
4930 // fold (select X, 1, Y) -> (or X, Y)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004931 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004932 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004933 // fold (select X, Y, X) -> (and X, Y)
4934 // fold (select X, Y, 0) -> (and X, Y)
Matthias Braun0542b5d2015-05-19 00:25:17 +00004935 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004936 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004937
Chris Lattner6c14c352005-10-18 06:04:22 +00004938 // If we can fold this based on the true/false value, do so.
4939 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004940 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004941
Nate Begemanc760f802005-09-19 22:34:01 +00004942 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004943 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004944 // select x, y (fcmp lt x, y) -> fminnum x, y
4945 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4946 //
4947 // This is OK if we don't care about what happens if either operand is a
4948 // NaN.
4949 //
4950
4951 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4952 // no signed zeros as well as no nans.
4953 const TargetOptions &Options = DAG.getTarget().Options;
4954 if (Options.UnsafeFPMath &&
4955 VT.isFloatingPoint() && N0.hasOneUse() &&
4956 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4957 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4958
4959 SDValue FMinMax =
4960 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4961 N1, N2, CC, TLI, DAG);
4962 if (FMinMax)
4963 return FMinMax;
4964 }
4965
Tom Stellard3787b122014-06-10 16:01:29 +00004966 if ((!LegalOperations &&
4967 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004968 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004969 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004970 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004971 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004972 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004973 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004974
Matthias Braun898d11e2015-03-06 19:49:10 +00004975 if (VT0 == MVT::i1) {
4976 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4977 // select (and Cond0, Cond1), X, Y
4978 // -> select Cond0, (select Cond1, X, Y), Y
4979 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4980 SDValue Cond0 = N0->getOperand(0);
4981 SDValue Cond1 = N0->getOperand(1);
4982 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4983 N1.getValueType(), Cond1, N1, N2);
4984 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4985 InnerSelect, N2);
4986 }
4987 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4988 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4989 SDValue Cond0 = N0->getOperand(0);
4990 SDValue Cond1 = N0->getOperand(1);
4991 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4992 N1.getValueType(), Cond1, N1, N2);
4993 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4994 InnerSelect);
4995 }
4996 }
4997
4998 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4999 if (N1->getOpcode() == ISD::SELECT) {
5000 SDValue N1_0 = N1->getOperand(0);
5001 SDValue N1_1 = N1->getOperand(1);
5002 SDValue N1_2 = N1->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00005003 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00005004 // Create the actual and node if we can generate good code for it.
5005 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5006 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5007 N0, N1_0);
5008 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5009 N1_1, N2);
5010 }
5011 // Otherwise see if we can optimize the "and" to a better pattern.
5012 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5013 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5014 N1_1, N2);
5015 }
5016 }
5017 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5018 if (N2->getOpcode() == ISD::SELECT) {
5019 SDValue N2_0 = N2->getOperand(0);
5020 SDValue N2_1 = N2->getOperand(1);
5021 SDValue N2_2 = N2->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00005022 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00005023 // Create the actual or node if we can generate good code for it.
5024 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5025 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5026 N0, N2_0);
5027 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5028 N1, N2_2);
5029 }
5030 // Otherwise see if we can optimize to a better pattern.
5031 if (SDValue Combined = visitORLike(N0, N2_0, N))
5032 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5033 N1, N2_2);
5034 }
5035 }
5036 }
5037
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005038 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00005039}
5040
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005041static
5042std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5043 SDLoc DL(N);
5044 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005045 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005046
5047 // Split the inputs.
5048 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005049 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5050 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005051
5052 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5053 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5054
5055 return std::make_pair(Lo, Hi);
5056}
5057
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005058// This function assumes all the vselect's arguments are CONCAT_VECTOR
5059// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5060static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5061 SDLoc dl(N);
5062 SDValue Cond = N->getOperand(0);
5063 SDValue LHS = N->getOperand(1);
5064 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00005065 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005066 int NumElems = VT.getVectorNumElements();
5067 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5068 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5069 Cond.getOpcode() == ISD::BUILD_VECTOR);
5070
Benjamin Kramerff8b8832014-08-21 13:28:02 +00005071 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5072 // binary ones here.
5073 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5074 return SDValue();
5075
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005076 // We're sure we have an even number of elements due to the
5077 // concat_vectors we have as arguments to vselect.
5078 // Skip BV elements until we find one that's not an UNDEF
5079 // After we find an UNDEF element, keep looping until we get to half the
5080 // length of the BV and see if all the non-undef nodes are the same.
5081 ConstantSDNode *BottomHalf = nullptr;
5082 for (int i = 0; i < NumElems / 2; ++i) {
5083 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5084 continue;
5085
5086 if (BottomHalf == nullptr)
5087 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5088 else if (Cond->getOperand(i).getNode() != BottomHalf)
5089 return SDValue();
5090 }
5091
5092 // Do the same for the second half of the BuildVector
5093 ConstantSDNode *TopHalf = nullptr;
5094 for (int i = NumElems / 2; i < NumElems; ++i) {
5095 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5096 continue;
5097
5098 if (TopHalf == nullptr)
5099 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5100 else if (Cond->getOperand(i).getNode() != TopHalf)
5101 return SDValue();
5102 }
5103
5104 assert(TopHalf && BottomHalf &&
5105 "One half of the selector was all UNDEFs and the other was all the "
5106 "same value. This should have been addressed before this function.");
5107 return DAG.getNode(
5108 ISD::CONCAT_VECTORS, dl, VT,
5109 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5110 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5111}
5112
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005113SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5114
5115 if (Level >= AfterLegalizeTypes)
5116 return SDValue();
5117
5118 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5119 SDValue Mask = MSC->getMask();
5120 SDValue Data = MSC->getValue();
5121 SDLoc DL(N);
5122
5123 // If the MSCATTER data type requires splitting and the mask is provided by a
5124 // SETCC, then split both nodes and its operands before legalization. This
5125 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5126 // and enables future optimizations (e.g. min/max pattern matching on X86).
5127 if (Mask.getOpcode() != ISD::SETCC)
5128 return SDValue();
5129
5130 // Check if any splitting is required.
5131 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5132 TargetLowering::TypeSplitVector)
5133 return SDValue();
5134 SDValue MaskLo, MaskHi, Lo, Hi;
5135 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5136
5137 EVT LoVT, HiVT;
5138 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5139
5140 SDValue Chain = MSC->getChain();
5141
5142 EVT MemoryVT = MSC->getMemoryVT();
5143 unsigned Alignment = MSC->getOriginalAlignment();
5144
5145 EVT LoMemVT, HiMemVT;
5146 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5147
5148 SDValue DataLo, DataHi;
5149 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5150
5151 SDValue BasePtr = MSC->getBasePtr();
5152 SDValue IndexLo, IndexHi;
5153 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5154
5155 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrim096cccd2015-06-13 12:57:36 +00005156 getMachineMemOperand(MSC->getPointerInfo(),
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005157 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5158 Alignment, MSC->getAAInfo(), MSC->getRanges());
5159
5160 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5161 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5162 DL, OpsLo, MMO);
5163
5164 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5165 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5166 DL, OpsHi, MMO);
5167
5168 AddToWorklist(Lo.getNode());
5169 AddToWorklist(Hi.getNode());
5170
5171 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5172}
5173
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005174SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5175
5176 if (Level >= AfterLegalizeTypes)
5177 return SDValue();
5178
5179 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5180 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005181 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005182 SDLoc DL(N);
5183
5184 // If the MSTORE data type requires splitting and the mask is provided by a
5185 // SETCC, then split both nodes and its operands before legalization. This
5186 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5187 // and enables future optimizations (e.g. min/max pattern matching on X86).
5188 if (Mask.getOpcode() == ISD::SETCC) {
5189
5190 // Check if any splitting is required.
5191 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5192 TargetLowering::TypeSplitVector)
5193 return SDValue();
5194
5195 SDValue MaskLo, MaskHi, Lo, Hi;
5196 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5197
5198 EVT LoVT, HiVT;
5199 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5200
5201 SDValue Chain = MST->getChain();
5202 SDValue Ptr = MST->getBasePtr();
5203
5204 EVT MemoryVT = MST->getMemoryVT();
5205 unsigned Alignment = MST->getOriginalAlignment();
5206
5207 // if Alignment is equal to the vector size,
5208 // take the half of it for the second part
5209 unsigned SecondHalfAlignment =
5210 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5211 Alignment/2 : Alignment;
5212
5213 EVT LoMemVT, HiMemVT;
5214 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5215
5216 SDValue DataLo, DataHi;
5217 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5218
5219 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005220 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005221 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5222 Alignment, MST->getAAInfo(), MST->getRanges());
5223
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005224 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5225 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005226
5227 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5228 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005229 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005230
5231 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005232 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005233 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5234 SecondHalfAlignment, MST->getAAInfo(),
5235 MST->getRanges());
5236
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005237 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5238 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005239
5240 AddToWorklist(Lo.getNode());
5241 AddToWorklist(Hi.getNode());
5242
5243 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5244 }
5245 return SDValue();
5246}
5247
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005248SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5249
5250 if (Level >= AfterLegalizeTypes)
5251 return SDValue();
5252
5253 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5254 SDValue Mask = MGT->getMask();
5255 SDLoc DL(N);
5256
5257 // If the MGATHER result requires splitting and the mask is provided by a
5258 // SETCC, then split both nodes and its operands before legalization. This
5259 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5260 // and enables future optimizations (e.g. min/max pattern matching on X86).
5261
5262 if (Mask.getOpcode() != ISD::SETCC)
5263 return SDValue();
5264
5265 EVT VT = N->getValueType(0);
5266
5267 // Check if any splitting is required.
5268 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5269 TargetLowering::TypeSplitVector)
5270 return SDValue();
5271
5272 SDValue MaskLo, MaskHi, Lo, Hi;
5273 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5274
5275 SDValue Src0 = MGT->getValue();
5276 SDValue Src0Lo, Src0Hi;
5277 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5278
5279 EVT LoVT, HiVT;
5280 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5281
5282 SDValue Chain = MGT->getChain();
5283 EVT MemoryVT = MGT->getMemoryVT();
5284 unsigned Alignment = MGT->getOriginalAlignment();
5285
5286 EVT LoMemVT, HiMemVT;
5287 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5288
5289 SDValue BasePtr = MGT->getBasePtr();
5290 SDValue Index = MGT->getIndex();
5291 SDValue IndexLo, IndexHi;
5292 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5293
5294 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrim096cccd2015-06-13 12:57:36 +00005295 getMachineMemOperand(MGT->getPointerInfo(),
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005296 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5297 Alignment, MGT->getAAInfo(), MGT->getRanges());
5298
5299 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5300 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5301 MMO);
5302
5303 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5304 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5305 MMO);
5306
5307 AddToWorklist(Lo.getNode());
5308 AddToWorklist(Hi.getNode());
5309
5310 // Build a factor node to remember that this load is independent of the
5311 // other one.
5312 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5313 Hi.getValue(1));
5314
5315 // Legalized the chain result - switch anything that used the old chain to
5316 // use the new one.
5317 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5318
5319 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5320
5321 SDValue RetOps[] = { GatherRes, Chain };
5322 return DAG.getMergeValues(RetOps, DL);
5323}
5324
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005325SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5326
5327 if (Level >= AfterLegalizeTypes)
5328 return SDValue();
5329
5330 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5331 SDValue Mask = MLD->getMask();
5332 SDLoc DL(N);
5333
5334 // If the MLOAD result requires splitting and the mask is provided by a
5335 // SETCC, then split both nodes and its operands before legalization. This
5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5337 // and enables future optimizations (e.g. min/max pattern matching on X86).
5338
5339 if (Mask.getOpcode() == ISD::SETCC) {
5340 EVT VT = N->getValueType(0);
5341
5342 // Check if any splitting is required.
5343 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5344 TargetLowering::TypeSplitVector)
5345 return SDValue();
5346
5347 SDValue MaskLo, MaskHi, Lo, Hi;
5348 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5349
5350 SDValue Src0 = MLD->getSrc0();
5351 SDValue Src0Lo, Src0Hi;
5352 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5353
5354 EVT LoVT, HiVT;
5355 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5356
5357 SDValue Chain = MLD->getChain();
5358 SDValue Ptr = MLD->getBasePtr();
5359 EVT MemoryVT = MLD->getMemoryVT();
5360 unsigned Alignment = MLD->getOriginalAlignment();
5361
5362 // if Alignment is equal to the vector size,
5363 // take the half of it for the second part
5364 unsigned SecondHalfAlignment =
5365 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5366 Alignment/2 : Alignment;
5367
5368 EVT LoMemVT, HiMemVT;
5369 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5370
5371 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005372 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005373 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5374 Alignment, MLD->getAAInfo(), MLD->getRanges());
5375
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005376 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5377 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005378
5379 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5380 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005381 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005382
5383 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005384 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005385 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5386 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5387
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005388 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5389 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005390
5391 AddToWorklist(Lo.getNode());
5392 AddToWorklist(Hi.getNode());
5393
5394 // Build a factor node to remember that this load is independent of the
5395 // other one.
5396 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5397 Hi.getValue(1));
5398
5399 // Legalized the chain result - switch anything that used the old chain to
5400 // use the new one.
5401 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5402
5403 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5404
5405 SDValue RetOps[] = { LoadRes, Chain };
5406 return DAG.getMergeValues(RetOps, DL);
5407 }
5408 return SDValue();
5409}
5410
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005411SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5412 SDValue N0 = N->getOperand(0);
5413 SDValue N1 = N->getOperand(1);
5414 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005415 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005416
5417 // Canonicalize integer abs.
5418 // vselect (setg[te] X, 0), X, -X ->
5419 // vselect (setgt X, -1), X, -X ->
5420 // vselect (setl[te] X, 0), -X, X ->
5421 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5422 if (N0.getOpcode() == ISD::SETCC) {
5423 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5424 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5425 bool isAbs = false;
5426 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5427
5428 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5429 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5430 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5431 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5432 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5433 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5434 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5435
5436 if (isAbs) {
5437 EVT VT = LHS.getValueType();
5438 SDValue Shift = DAG.getNode(
5439 ISD::SRA, DL, VT, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005440 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005441 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005442 AddToWorklist(Shift.getNode());
5443 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005444 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5445 }
5446 }
5447
Tom Stellard69a7b912015-04-20 19:38:27 +00005448 if (SimplifySelectOps(N, N1, N2))
5449 return SDValue(N, 0); // Don't revisit N.
5450
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005451 // If the VSELECT result requires splitting and the mask is provided by a
5452 // SETCC, then split both nodes and its operands before legalization. This
5453 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5454 // and enables future optimizations (e.g. min/max pattern matching on X86).
5455 if (N0.getOpcode() == ISD::SETCC) {
5456 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005457
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005458 // Check if any splitting is required.
5459 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5460 TargetLowering::TypeSplitVector)
5461 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005462
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005463 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005464 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5465 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5466 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005467
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005468 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5469 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005470
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005471 // Add the new VSELECT nodes to the work list in case they need to be split
5472 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005473 AddToWorklist(Lo.getNode());
5474 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005475
5476 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005477 }
5478
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005479 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5480 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5481 return N1;
5482 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5483 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5484 return N2;
5485
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005486 // The ConvertSelectToConcatVector function is assuming both the above
5487 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5488 // and addressed.
5489 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5490 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5491 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5492 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5493 if (CV.getNode())
5494 return CV;
5495 }
5496
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005497 return SDValue();
5498}
5499
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005500SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5501 SDValue N0 = N->getOperand(0);
5502 SDValue N1 = N->getOperand(1);
5503 SDValue N2 = N->getOperand(2);
5504 SDValue N3 = N->getOperand(3);
5505 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005506 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005507
Nate Begemanc760f802005-09-19 22:34:01 +00005508 // fold select_cc lhs, rhs, x, x, cc -> x
5509 if (N2 == N3)
5510 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005511
Chris Lattner8b68dec2006-09-20 06:19:26 +00005512 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005513 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005514 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005515 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005516 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005517
Stephen Lin605207f2013-06-15 04:03:33 +00005518 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5519 if (!SCCC->isNullValue())
5520 return N2; // cond always true -> true val
5521 else
5522 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005523 } else if (SCC->getOpcode() == ISD::UNDEF) {
5524 // When the condition is UNDEF, just return the first operand. This is
5525 // coherent the DAG creation, no setcc node is created in this case
5526 return N2;
5527 } else if (SCC.getOpcode() == ISD::SETCC) {
5528 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005529 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5530 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5531 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005532 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005533 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005534
Chris Lattner6c14c352005-10-18 06:04:22 +00005535 // If we can fold this based on the true/false value, do so.
5536 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005537 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005538
Nate Begemanc760f802005-09-19 22:34:01 +00005539 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005540 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005541}
5542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005543SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005544 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005545 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005546 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005547}
5548
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005549// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5550// dag node into a ConstantSDNode or a build_vector of constants.
5551// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005552// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005553// Vector extends are not folded if operations are legal; this is to
5554// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005555static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5556 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005557 bool LegalOperations) {
5558 unsigned Opcode = N->getOpcode();
5559 SDValue N0 = N->getOperand(0);
5560 EVT VT = N->getValueType(0);
5561
5562 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
Simon Pilgrime0541992015-05-21 10:05:03 +00005563 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5564 && "Expected EXTEND dag node in input!");
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005565
5566 // fold (sext c1) -> c1
5567 // fold (zext c1) -> c1
5568 // fold (aext c1) -> c1
5569 if (isa<ConstantSDNode>(N0))
5570 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5571
5572 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5573 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5574 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005575 EVT SVT = VT.getScalarType();
5576 if (!(VT.isVector() &&
5577 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005578 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005579 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005580
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005581 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005582 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005583 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5584 unsigned ShAmt = VTBits - EVTBits;
5585 SmallVector<SDValue, 8> Elts;
Simon Pilgrime0541992015-05-21 10:05:03 +00005586 unsigned NumElts = VT.getVectorNumElements();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005587 SDLoc DL(N);
5588
5589 for (unsigned i=0; i != NumElts; ++i) {
5590 SDValue Op = N0->getOperand(i);
5591 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005592 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005593 continue;
5594 }
5595
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005596 SDLoc DL(Op);
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005597 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5598 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
Simon Pilgrime0541992015-05-21 10:05:03 +00005599 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005600 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005601 DL, SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005602 else
5603 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005604 DL, SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005605 }
5606
Craig Topper48d114b2014-04-26 18:35:24 +00005607 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005608}
5609
Evan Chenge106e2f2007-10-29 19:58:20 +00005610// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005611// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005612// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005613// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005614static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005615 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005616 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005617 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005618 bool HasCopyToRegUses = false;
5619 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005620 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5621 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005622 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005623 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005624 if (User == N)
5625 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005626 if (UI.getUse().getResNo() != N0.getResNo())
5627 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005628 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005629 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005630 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5631 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5632 // Sign bits will be lost after a zext.
5633 return false;
5634 bool Add = false;
5635 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005636 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005637 if (UseOp == N0)
5638 continue;
5639 if (!isa<ConstantSDNode>(UseOp))
5640 return false;
5641 Add = true;
5642 }
5643 if (Add)
5644 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005645 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005646 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005647 // If truncates aren't free and there are users we can't
5648 // extend, it isn't worthwhile.
5649 if (!isTruncFree)
5650 return false;
5651 // Remember if this value is live-out.
5652 if (User->getOpcode() == ISD::CopyToReg)
5653 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005654 }
5655
5656 if (HasCopyToRegUses) {
5657 bool BothLiveOut = false;
5658 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5659 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005660 SDUse &Use = UI.getUse();
5661 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5662 BothLiveOut = true;
5663 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005664 }
5665 }
5666 if (BothLiveOut)
5667 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005668 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005669 return ExtendNodes.size();
5670 }
5671 return true;
5672}
5673
Craig Toppere0b71182013-07-13 07:43:40 +00005674void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005675 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005676 ISD::NodeType ExtType) {
5677 // Extend SetCC uses if necessary.
5678 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5679 SDNode *SetCC = SetCCs[i];
5680 SmallVector<SDValue, 4> Ops;
5681
5682 for (unsigned j = 0; j != 2; ++j) {
5683 SDValue SOp = SetCC->getOperand(j);
5684 if (SOp == Trunc)
5685 Ops.push_back(ExtLoad);
5686 else
5687 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5688 }
5689
5690 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005691 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005692 }
5693}
5694
Ahmed Bougachae892d132015-02-05 18:31:02 +00005695// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5696SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5697 SDValue N0 = N->getOperand(0);
5698 EVT DstVT = N->getValueType(0);
5699 EVT SrcVT = N0.getValueType();
5700
5701 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5702 N->getOpcode() == ISD::ZERO_EXTEND) &&
5703 "Unexpected node type (not an extend)!");
5704
5705 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5706 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5707 // (v8i32 (sext (v8i16 (load x))))
5708 // into:
5709 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5710 // (v4i32 (sextload (x + 16)))))
5711 // Where uses of the original load, i.e.:
5712 // (v8i16 (load x))
5713 // are replaced with:
5714 // (v8i16 (truncate
5715 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5716 // (v4i32 (sextload (x + 16)))))))
5717 //
5718 // This combine is only applicable to illegal, but splittable, vectors.
5719 // All legal types, and illegal non-vector types, are handled elsewhere.
5720 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5721 //
5722 if (N0->getOpcode() != ISD::LOAD)
5723 return SDValue();
5724
5725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5726
5727 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5728 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5729 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5730 return SDValue();
5731
5732 SmallVector<SDNode *, 4> SetCCs;
5733 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5734 return SDValue();
5735
5736 ISD::LoadExtType ExtType =
5737 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5738
5739 // Try to split the vector types to get down to legal types.
5740 EVT SplitSrcVT = SrcVT;
5741 EVT SplitDstVT = DstVT;
5742 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5743 SplitSrcVT.getVectorNumElements() > 1) {
5744 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5745 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5746 }
5747
5748 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5749 return SDValue();
5750
5751 SDLoc DL(N);
5752 const unsigned NumSplits =
5753 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5754 const unsigned Stride = SplitSrcVT.getStoreSize();
5755 SmallVector<SDValue, 4> Loads;
5756 SmallVector<SDValue, 4> Chains;
5757
5758 SDValue BasePtr = LN0->getBasePtr();
5759 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5760 const unsigned Offset = Idx * Stride;
5761 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5762
5763 SDValue SplitLoad = DAG.getExtLoad(
5764 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5765 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5766 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5767 Align, LN0->getAAInfo());
5768
5769 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005770 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
Ahmed Bougachae892d132015-02-05 18:31:02 +00005771
5772 Loads.push_back(SplitLoad.getValue(0));
5773 Chains.push_back(SplitLoad.getValue(1));
5774 }
5775
5776 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5777 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5778
5779 CombineTo(N, NewValue);
5780
5781 // Replace uses of the original load (before extension)
5782 // with a truncate of the concatenated sextloaded vectors.
5783 SDValue Trunc =
5784 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5785 CombineTo(N0.getNode(), Trunc, NewChain);
5786 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5787 (ISD::NodeType)N->getOpcode());
5788 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5789}
5790
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005791SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5792 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005793 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005794
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005795 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5796 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005797 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005798
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005799 // fold (sext (sext x)) -> (sext x)
5800 // fold (sext (aext x)) -> (sext x)
5801 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005802 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005803 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005804
Chris Lattnerfce448f2007-02-26 03:13:59 +00005805 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005806 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5807 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005808 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5809 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005810 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5811 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005812 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005813 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005814 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005815 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005817 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005818
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005819 // See if the value being truncated is already sign extended. If so, just
5820 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005821 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005822 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5823 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5824 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005825 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005826
Chris Lattnerfce448f2007-02-26 03:13:59 +00005827 if (OpBits == DestBits) {
5828 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5829 // bits, it is already ready.
5830 if (NumSignBits > DestBits-MidBits)
5831 return Op;
5832 } else if (OpBits < DestBits) {
5833 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5834 // bits, just sext from i32.
5835 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005836 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005837 } else {
5838 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5839 // bits, just truncate to i32.
5840 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005841 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005842 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005843
Chris Lattnerfce448f2007-02-26 03:13:59 +00005844 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005845 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5846 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005847 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005848 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005849 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005850 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5851 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005852 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005853 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005854 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005855
Evan Chengbce7c472005-12-14 02:19:23 +00005856 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005857 // Only generate vector extloads when 1) they're legal, and 2) they are
5858 // deemed desirable by the target.
5859 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5860 ((!LegalOperations && !VT.isVector() &&
5861 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005862 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005863 bool DoXform = true;
5864 SmallVector<SDNode*, 4> SetCCs;
5865 if (!N0.hasOneUse())
5866 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005867 if (VT.isVector())
5868 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005869 if (DoXform) {
5870 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005871 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005872 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005873 LN0->getBasePtr(), N0.getValueType(),
5874 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005875 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005876 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005877 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005878 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005879 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005880 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005882 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005883 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005884
Ahmed Bougachae892d132015-02-05 18:31:02 +00005885 // fold (sext (load x)) to multiple smaller sextloads.
5886 // Only on illegal but splittable vectors.
5887 if (SDValue ExtLoad = CombineExtLoad(N))
5888 return ExtLoad;
5889
Chris Lattner7dac1082005-12-14 19:05:06 +00005890 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5891 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005892 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5893 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005894 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005895 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005896 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005897 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005898 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005899 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005900 LN0->getBasePtr(), MemVT,
5901 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005902 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005903 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005904 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005905 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005906 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005907 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005908 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005909 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005910
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005911 // fold (sext (and/or/xor (load x), cst)) ->
5912 // (and/or/xor (sextload x), (sext cst))
5913 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5914 N0.getOpcode() == ISD::XOR) &&
5915 isa<LoadSDNode>(N0.getOperand(0)) &&
5916 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005917 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005918 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5919 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005920 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005921 bool DoXform = true;
5922 SmallVector<SDNode*, 4> SetCCs;
5923 if (!N0.hasOneUse())
5924 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5925 SetCCs, TLI);
5926 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005927 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005928 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005929 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005930 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005931 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5932 Mask = Mask.sext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005933 SDLoc DL(N);
5934 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5935 ExtLoad, DAG.getConstant(Mask, DL, VT));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005936 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005937 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005938 N0.getOperand(0).getValueType(), ExtLoad);
5939 CombineTo(N, And);
5940 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005941 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005942 ISD::SIGN_EXTEND);
5943 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5944 }
5945 }
5946 }
5947
Chris Lattner65786b02007-04-11 05:32:27 +00005948 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005949 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005950 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005951 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005952 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005953 TLI.getBooleanContents(N0VT) ==
5954 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005955 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5956 // of the same size as the compared operands. Only optimize sext(setcc())
5957 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005958 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005959
5960 // We know that the # elements of the results is the same as the
5961 // # elements of the compare (and the # elements of the compare result
5962 // for that matter). Check to see that they are the same size. If so,
5963 // we know that the element size of the sext'd result matches the
5964 // element size of the compare operands.
5965 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005966 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005967 N0.getOperand(1),
5968 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005969
Dan Gohmane82c25e2010-04-30 17:19:19 +00005970 // If the desired elements are smaller or larger than the source
5971 // elements we can use a matching integer vector type and then
5972 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005973 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005974 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005975 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005976 N0.getOperand(0), N0.getOperand(1),
5977 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005978 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005979 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005980 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005981
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005982 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005983 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005984 SDLoc DL(N);
Dan Gohman5758e1e2009-08-06 09:18:59 +00005985 SDValue NegOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005986 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005987 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005988 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5989 NegOne, DAG.getConstant(0, DL, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005990 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005991 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005992
5993 if (!VT.isVector()) {
5994 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5995 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5996 SDLoc DL(N);
5997 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005998 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005999 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00006000 return DAG.getSelect(DL, VT, SetCC,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006001 NegOne, DAG.getConstant(0, DL, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00006002 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00006003 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006004 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006005
Dan Gohman3eb10f72008-04-28 16:58:24 +00006006 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006007 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00006008 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006009 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006010
Evan Chengf1005572010-04-28 07:10:39 +00006011 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006012}
6013
Rafael Espindola8f62b322012-04-09 16:06:03 +00006014// isTruncateOf - If N is a truncate of some other value, return true, record
6015// the value being truncated in Op and which of Op's bits are zero in KnownZero.
6016// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00006017// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00006018static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6019 APInt &KnownZero) {
6020 APInt KnownOne;
6021 if (N->getOpcode() == ISD::TRUNCATE) {
6022 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00006023 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00006024 return true;
6025 }
6026
6027 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6028 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6029 return false;
6030
6031 SDValue Op0 = N->getOperand(0);
6032 SDValue Op1 = N->getOperand(1);
6033 assert(Op0.getValueType() == Op1.getValueType());
6034
Matthias Braun1505efb2015-05-18 23:07:27 +00006035 if (isNullConstant(Op0))
Rafael Espindola8f62b322012-04-09 16:06:03 +00006036 Op = Op1;
Matthias Braun1505efb2015-05-18 23:07:27 +00006037 else if (isNullConstant(Op1))
Rafael Espindola8f62b322012-04-09 16:06:03 +00006038 Op = Op0;
6039 else
6040 return false;
6041
Jay Foada0653a32014-05-14 21:14:37 +00006042 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00006043
6044 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6045 return false;
6046
6047 return true;
6048}
6049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006050SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6051 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006052 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006053
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006054 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6055 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006056 return SDValue(Res, 0);
6057
Nate Begeman21158fc2005-09-01 00:19:25 +00006058 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006059 // fold (zext (aext x)) -> (zext x)
6060 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006061 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006062 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00006063
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006064 // fold (zext (truncate x)) -> (zext x) or
6065 // (zext (truncate x)) -> (truncate x)
6066 // This is valid when the truncated bits of x are already zero.
6067 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00006068 SDValue Op;
6069 APInt KnownZero;
6070 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6071 APInt TruncatedBits =
6072 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6073 APInt(Op.getValueSizeInBits(), 0) :
6074 APInt::getBitsSet(Op.getValueSizeInBits(),
6075 N0.getValueSizeInBits(),
6076 std::min(Op.getValueSizeInBits(),
6077 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00006078 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006079 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006080 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006081 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006082 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006083
6084 return Op;
6085 }
6086 }
6087
Evan Cheng464dc9b2007-03-22 01:54:19 +00006088 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6089 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00006090 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006091 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00006093 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006095 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00006096 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006097 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00006098 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006100 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006101 }
6102
Chris Lattnera31f0a62006-09-21 06:00:20 +00006103 // fold (zext (truncate x)) -> (and x, mask)
6104 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00006105 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006106
6107 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6108 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6109 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6110 if (NarrowLoad.getNode()) {
6111 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6112 if (NarrowLoad.getNode() != N0.getNode()) {
6113 CombineTo(N0.getNode(), NarrowLoad);
6114 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006115 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00006116 }
6117 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6118 }
6119
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006120 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006121 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006122 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006123 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00006124 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006125 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006126 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00006127 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006128 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00006129 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00006130 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006131
Dan Gohmanad3e5492009-04-08 00:15:30 +00006132 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6133 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006134 if (N0.getOpcode() == ISD::AND &&
6135 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006136 N0.getOperand(1).getOpcode() == ISD::Constant &&
6137 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6138 N0.getValueType()) ||
6139 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006140 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006141 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006142 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006143 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006144 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006145 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006146 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006147 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006148 SDLoc DL(N);
6149 return DAG.getNode(ISD::AND, DL, VT,
6150 X, DAG.getConstant(Mask, DL, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006151 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006152
Evan Chengbce7c472005-12-14 02:19:23 +00006153 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00006154 // Only generate vector extloads when 1) they're legal, and 2) they are
6155 // deemed desirable by the target.
6156 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6157 ((!LegalOperations && !VT.isVector() &&
6158 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006159 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00006160 bool DoXform = true;
6161 SmallVector<SDNode*, 4> SetCCs;
6162 if (!N0.hasOneUse())
6163 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00006164 if (VT.isVector())
6165 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00006166 if (DoXform) {
6167 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006168 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006169 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006170 LN0->getBasePtr(), N0.getValueType(),
6171 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00006172 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006173 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00006174 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006175 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00006176
Andrew Trickef9de2a2013-05-25 02:42:55 +00006177 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006178 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00006180 }
Evan Chengbce7c472005-12-14 02:19:23 +00006181 }
Chris Lattner7dac1082005-12-14 19:05:06 +00006182
Ahmed Bougachae892d132015-02-05 18:31:02 +00006183 // fold (zext (load x)) to multiple smaller zextloads.
6184 // Only on illegal but splittable vectors.
6185 if (SDValue ExtLoad = CombineExtLoad(N))
6186 return ExtLoad;
6187
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006188 // fold (zext (and/or/xor (load x), cst)) ->
6189 // (and/or/xor (zextload x), (zext cst))
6190 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6191 N0.getOpcode() == ISD::XOR) &&
6192 isa<LoadSDNode>(N0.getOperand(0)) &&
6193 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006194 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006195 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6196 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006197 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006198 bool DoXform = true;
6199 SmallVector<SDNode*, 4> SetCCs;
6200 if (!N0.hasOneUse())
6201 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6202 SetCCs, TLI);
6203 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006204 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006205 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006206 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006207 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006208 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6209 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006210 SDLoc DL(N);
6211 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6212 ExtLoad, DAG.getConstant(Mask, DL, VT));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006213 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006214 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006215 N0.getOperand(0).getValueType(), ExtLoad);
6216 CombineTo(N, And);
6217 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006218 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006219 ISD::ZERO_EXTEND);
6220 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6221 }
6222 }
6223 }
6224
Chris Lattner7dac1082005-12-14 19:05:06 +00006225 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6226 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00006227 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6228 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006229 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00006230 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006231 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006232 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006233 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006234 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006235 LN0->getBasePtr(), MemVT,
6236 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00006237 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00006238 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006239 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00006240 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00006241 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006242 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00006243 }
Chris Lattner7dac1082005-12-14 19:05:06 +00006244 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006245
Chris Lattner65786b02007-04-11 05:32:27 +00006246 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00006247 if (!LegalOperations && VT.isVector() &&
6248 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00006249 EVT N0VT = N0.getOperand(0).getValueType();
6250 if (getSetCCResultType(N0VT) == N0.getValueType())
6251 return SDValue();
6252
Evan Chengabd0ad52010-05-19 01:08:17 +00006253 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6254 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00006255 EVT EltVT = VT.getVectorElementType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006256 SDLoc DL(N);
Evan Chengabd0ad52010-05-19 01:08:17 +00006257 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006258 DAG.getConstant(1, DL, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00006259 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00006260 // We know that the # elements of the results is the same as the
6261 // # elements of the compare (and the # elements of the compare result
6262 // for that matter). Check to see that they are the same size. If so,
6263 // we know that the element size of the sext'd result matches the
6264 // element size of the compare operands.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006265 return DAG.getNode(ISD::AND, DL, VT,
6266 DAG.getSetCC(DL, VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00006267 N0.getOperand(1),
6268 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006269 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
Craig Topper48d114b2014-04-26 18:35:24 +00006270 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00006271
6272 // If the desired elements are smaller or larger than the source
6273 // elements we can use a matching integer vector type and then
6274 // truncate/sign extend
6275 EVT MatchingElementType =
6276 EVT::getIntegerVT(*DAG.getContext(),
6277 N0VT.getScalarType().getSizeInBits());
6278 EVT MatchingVectorType =
6279 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6280 N0VT.getVectorNumElements());
6281 SDValue VsetCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006282 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00006283 N0.getOperand(1),
6284 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006285 return DAG.getNode(ISD::AND, DL, VT,
6286 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6287 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00006288 }
6289
6290 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006291 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006292 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006293 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6294 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006295 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006296 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006298
Evan Cheng852c4862009-12-15 03:00:32 +00006299 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00006300 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00006301 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00006302 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6303 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006304 SDValue ShAmt = N0.getOperand(1);
6305 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00006306 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006307 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00006308 // If the original shl may be shifting out bits, do not perform this
6309 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00006310 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6311 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6312 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00006313 return SDValue();
6314 }
Chris Lattnere95d1952011-02-13 19:09:16 +00006315
Andrew Trickef9de2a2013-05-25 02:42:55 +00006316 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006317
6318 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00006319 if (VT.getSizeInBits() >= 256)
6320 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006321
Chris Lattnere95d1952011-02-13 19:09:16 +00006322 return DAG.getNode(N0.getOpcode(), DL, VT,
6323 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6324 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00006325 }
6326
Evan Chengf1005572010-04-28 07:10:39 +00006327 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006328}
6329
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006330SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6331 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006332 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006333
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006334 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6335 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006336 return SDValue(Res, 0);
6337
Chris Lattner812646a2006-05-05 05:58:59 +00006338 // fold (aext (aext x)) -> (aext x)
6339 // fold (aext (zext x)) -> (zext x)
6340 // fold (aext (sext x)) -> (sext x)
6341 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6342 N0.getOpcode() == ISD::ZERO_EXTEND ||
6343 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006344 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006345
Evan Cheng464dc9b2007-03-22 01:54:19 +00006346 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6347 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6348 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006349 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6350 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006351 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6352 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006353 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006354 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006355 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006356 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006357 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006358 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006359 }
6360
Chris Lattner8746e2c2006-09-20 06:29:17 +00006361 // fold (aext (truncate x))
6362 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006363 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006364 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006365 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00006366 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006367 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6368 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006370
Dan Gohmanad3e5492009-04-08 00:15:30 +00006371 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6372 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00006373 if (N0.getOpcode() == ISD::AND &&
6374 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006375 N0.getOperand(1).getOpcode() == ISD::Constant &&
6376 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6377 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006378 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006379 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006380 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006381 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006382 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00006383 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006384 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006385 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006386 SDLoc DL(N);
6387 return DAG.getNode(ISD::AND, DL, VT,
6388 X, DAG.getConstant(Mask, DL, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00006389 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006390
Chris Lattner812646a2006-05-05 05:58:59 +00006391 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006392 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006393 // on vectors in one instruction. We only perform this transformation on
6394 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006395 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006396 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006397 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006398 bool DoXform = true;
6399 SmallVector<SDNode*, 4> SetCCs;
6400 if (!N0.hasOneUse())
6401 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6402 if (DoXform) {
6403 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006404 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006405 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006406 LN0->getBasePtr(), N0.getValueType(),
6407 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006408 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006409 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006410 N0.getValueType(), ExtLoad);
6411 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006412 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006413 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006414 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6415 }
Chris Lattner812646a2006-05-05 05:58:59 +00006416 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006417
Chris Lattner812646a2006-05-05 05:58:59 +00006418 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6419 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6420 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006421 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006422 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006423 N0.hasOneUse()) {
6424 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006425 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006426 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006427 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006428 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6429 VT, LN0->getChain(), LN0->getBasePtr(),
6430 MemVT, LN0->getMemOperand());
6431 CombineTo(N, ExtLoad);
6432 CombineTo(N0.getNode(),
6433 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6434 N0.getValueType(), ExtLoad),
6435 ExtLoad.getValue(1));
6436 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6437 }
Chris Lattner812646a2006-05-05 05:58:59 +00006438 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006439
Chris Lattner65786b02007-04-11 05:32:27 +00006440 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006441 // For vectors:
6442 // aext(setcc) -> vsetcc
6443 // aext(setcc) -> truncate(vsetcc)
6444 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006445 // Only do this before legalize for now.
6446 if (VT.isVector() && !LegalOperations) {
6447 EVT N0VT = N0.getOperand(0).getValueType();
6448 // We know that the # elements of the results is the same as the
6449 // # elements of the compare (and the # elements of the compare result
6450 // for that matter). Check to see that they are the same size. If so,
6451 // we know that the element size of the sext'd result matches the
6452 // element size of the compare operands.
6453 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006454 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006455 N0.getOperand(1),
6456 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006457 // If the desired elements are smaller or larger than the source
6458 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006459 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006460 else {
Hao Liuc636d152014-04-22 09:57:06 +00006461 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006462 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006463 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006464 N0.getOperand(1),
6465 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006466 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006467 }
6468 }
6469
6470 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006471 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006472 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006473 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6474 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006475 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006476 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006477 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006478 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006479
Evan Chengf1005572010-04-28 07:10:39 +00006480 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006481}
6482
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006483/// See if the specified operand can be simplified with the knowledge that only
6484/// the bits specified by Mask are used. If so, return the simpler operand,
6485/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006486SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006487 switch (V.getOpcode()) {
6488 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006489 case ISD::Constant: {
6490 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006491 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006492 const APInt &CVal = CV->getAPIntValue();
6493 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006494 if (NewVal != CVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006495 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006496 break;
6497 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006498 case ISD::OR:
6499 case ISD::XOR:
6500 // If the LHS or RHS don't contribute bits to the or, drop them.
6501 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6502 return V.getOperand(1);
6503 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6504 return V.getOperand(0);
6505 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006506 case ISD::SRL:
6507 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006508 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006509 break;
Matthias Braun56a78142015-05-20 18:54:02 +00006510 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
Chris Lattnerf47e3062007-10-13 06:58:48 +00006511 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006512 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006513
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006514 // Watch out for shift count overflow though.
6515 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006516 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006517 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006518 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006519 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006520 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006521 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006522 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006523 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006524}
6525
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006526/// If the result of a wider load is shifted to right of N bits and then
6527/// truncated to a narrower type and where N is a multiple of number of bits of
6528/// the narrower type, transform it to a narrower load from address + N / num of
6529/// bits of new type. If the result is to be extended, also fold the extension
6530/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006531SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006532 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006533
Evan Cheng464dc9b2007-03-22 01:54:19 +00006534 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006535 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006536 EVT VT = N->getValueType(0);
6537 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006538
Dan Gohman550c9af2008-08-14 20:04:46 +00006539 // This transformation isn't valid for vector loads.
6540 if (VT.isVector())
6541 return SDValue();
6542
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006543 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006544 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006545 if (Opc == ISD::SIGN_EXTEND_INREG) {
6546 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006547 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006548 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006549 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006550 ExtType = ISD::ZEXTLOAD;
6551 N0 = SDValue(N, 0);
6552 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6553 if (!N01) return SDValue();
6554 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6555 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006556 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006557 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006558 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006559
Owen Anderson53aa7a92009-08-10 22:56:29 +00006560 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006561
Chris Lattner9a499e92010-12-22 08:01:44 +00006562 // Do not generate loads of non-round integer types since these can
6563 // be expensive (and would be wrong if the type is not byte sized).
6564 if (!ExtVT.isRound())
6565 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006566
Evan Cheng464dc9b2007-03-22 01:54:19 +00006567 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006568 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006569 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006570 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006571 // Is the shift amount a multiple of size of VT?
6572 if ((ShAmt & (EVTBits-1)) == 0) {
6573 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006574 // Is the load width a multiple of size of VT?
6575 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006576 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006577 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006578
Chris Lattnercafc1e62010-12-22 08:02:57 +00006579 // At this point, we must have a load or else we can't do the transform.
6580 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006581
Chandler Carruthb27041c2012-12-11 00:36:57 +00006582 // Because a SRL must be assumed to *need* to zero-extend the high bits
6583 // (as opposed to anyext the high bits), we can't combine the zextload
6584 // lowering of SRL and an sextload.
6585 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6586 return SDValue();
6587
Chris Lattnera2050552010-10-01 05:36:09 +00006588 // If the shift amount is larger than the input type then we're not
6589 // accessing any of the loaded bytes. If the load was a zextload/extload
6590 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006591 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006592 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006593 }
6594 }
6595
Dan Gohman68fb0042010-11-03 01:47:46 +00006596 // If the load is shifted left (and the result isn't shifted back right),
6597 // we can fold the truncate through the shift.
6598 unsigned ShLeftAmt = 0;
6599 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006600 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006601 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6602 ShLeftAmt = N01->getZExtValue();
6603 N0 = N0.getOperand(0);
6604 }
6605 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006606
Chris Lattner222374d2010-12-22 07:36:50 +00006607 // If we haven't found a load, we can't narrow it. Don't transform one with
6608 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006609 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6610 return SDValue();
6611
6612 // Don't change the width of a volatile load.
6613 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6614 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006615 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006616
Chris Lattner9a499e92010-12-22 08:01:44 +00006617 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006618 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006619 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006620
Bill Schmidtd006c692013-01-14 22:04:38 +00006621 // For the transform to be legal, the load must produce only two values
6622 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006623 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006624 // transformation is not equivalent, and the downstream logic to replace
6625 // uses gets things wrong.
6626 if (LN0->getNumValues() > 2)
6627 return SDValue();
6628
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006629 // If the load that we're shrinking is an extload and we're not just
6630 // discarding the extension we can't simply shrink the load. Bail.
6631 // TODO: It would be possible to merge the extensions in some cases.
6632 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6633 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6634 return SDValue();
6635
Matt Arsenault810cb622014-12-12 00:00:24 +00006636 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6637 return SDValue();
6638
Chris Lattner222374d2010-12-22 07:36:50 +00006639 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006640
Evan Cheng4c6f9172012-06-26 01:19:33 +00006641 if (PtrType == MVT::Untyped || PtrType.isExtended())
6642 // It's not possible to generate a constant of extended or untyped type.
6643 return SDValue();
6644
Chris Lattner222374d2010-12-22 07:36:50 +00006645 // For big endian targets, we need to adjust the offset to the pointer to
6646 // load the correct bytes.
6647 if (TLI.isBigEndian()) {
6648 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6649 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6650 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006651 }
6652
Chris Lattner222374d2010-12-22 07:36:50 +00006653 uint64_t PtrOff = ShAmt / 8;
6654 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006655 SDLoc DL(LN0);
6656 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
Chris Lattner222374d2010-12-22 07:36:50 +00006657 PtrType, LN0->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006658 DAG.getConstant(PtrOff, DL, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006659 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006660
Chris Lattner9a499e92010-12-22 08:01:44 +00006661 SDValue Load;
6662 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006663 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006664 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006665 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006666 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006667 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006668 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006669 LN0->getPointerInfo().getWithOffset(PtrOff),
6670 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006671 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006672
6673 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006674 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006675 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006676
6677 // Shift the result left, if we've swallowed a left shift.
6678 SDValue Result = Load;
6679 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006680 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006681 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6682 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006683 // If the shift amount is as large as the result size (but, presumably,
6684 // no larger than the source) then the useful bits of the result are
6685 // zero; we can't simply return the shortened shift, because the result
6686 // of that operation is undefined.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006687 SDLoc DL(N0);
Paul Redmond288604e2013-02-12 15:21:21 +00006688 if (ShLeftAmt >= VT.getSizeInBits())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006689 Result = DAG.getConstant(0, DL, VT);
Paul Redmond288604e2013-02-12 15:21:21 +00006690 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006691 Result = DAG.getNode(ISD::SHL, DL, VT,
6692 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006693 }
6694
6695 // Return the new loaded value.
6696 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006697}
6698
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006699SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6700 SDValue N0 = N->getOperand(0);
6701 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006702 EVT VT = N->getValueType(0);
6703 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006704 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006705 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006706
Nate Begeman21158fc2005-09-01 00:19:25 +00006707 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006708 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006709 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006710
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006711 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006712 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006713 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006714
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006715 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6716 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006717 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006718 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006719 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006720
Dan Gohman345d63c2008-07-31 00:50:31 +00006721 // fold (sext_in_reg (sext x)) -> (sext x)
6722 // fold (sext_in_reg (aext x)) -> (sext x)
6723 // if x is small enough.
6724 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6725 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006726 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6727 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006728 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006729 }
6730
Chris Lattner9ad59152007-04-17 19:03:21 +00006731 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006732 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006733 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006734
Chris Lattner9ad59152007-04-17 19:03:21 +00006735 // fold operands of sext_in_reg based on knowledge that the top bits are not
6736 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006737 if (SimplifyDemandedBits(SDValue(N, 0)))
6738 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006739
Evan Cheng464dc9b2007-03-22 01:54:19 +00006740 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6741 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006742 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006743 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006744 return NarrowLoad;
6745
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006746 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006747 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006748 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6749 if (N0.getOpcode() == ISD::SRL) {
6750 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006751 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006752 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006753 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006754 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006755 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006756 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006757 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006758 }
6759 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006760
Nate Begeman02b23c62005-10-13 03:11:28 +00006761 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006762 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006763 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006764 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006765 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006766 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006767 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006768 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006769 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006770 LN0->getBasePtr(), EVT,
6771 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006772 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006773 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006774 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006776 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006777 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006778 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006779 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006780 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006781 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006782 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006783 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006784 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006785 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006786 LN0->getBasePtr(), EVT,
6787 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006788 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006789 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006791 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006792
6793 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6794 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6795 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6796 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006797 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006798 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006799 BSwap, N1);
6800 }
6801
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006802 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6803 // into a build_vector.
6804 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6805 SmallVector<SDValue, 8> Elts;
6806 unsigned NumElts = N0->getNumOperands();
6807 unsigned ShAmt = VTBits - EVTBits;
6808
6809 for (unsigned i = 0; i != NumElts; ++i) {
6810 SDValue Op = N0->getOperand(i);
6811 if (Op->getOpcode() == ISD::UNDEF) {
6812 Elts.push_back(Op);
6813 continue;
6814 }
6815
6816 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006817 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6818 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006819 SDLoc(Op), Op.getValueType()));
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006820 }
6821
Craig Topper48d114b2014-04-26 18:35:24 +00006822 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006823 }
6824
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006825 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006826}
6827
Simon Pilgrime0541992015-05-21 10:05:03 +00006828SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6829 SDValue N0 = N->getOperand(0);
6830 EVT VT = N->getValueType(0);
6831
6832 if (N0.getOpcode() == ISD::UNDEF)
6833 return DAG.getUNDEF(VT);
6834
6835 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6836 LegalOperations))
6837 return SDValue(Res, 0);
6838
6839 return SDValue();
6840}
6841
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006842SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6843 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006844 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006845 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006846
6847 // noop truncate
6848 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006849 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006850 // fold (truncate c1) -> c1
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00006851 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006852 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006853 // fold (truncate (truncate x)) -> (truncate x)
6854 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006856 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006857 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6858 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006859 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006860 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006861 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006862 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006863 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006864 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006865 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006866 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006867 // if the source and dest are the same type, we can drop both the extend
6868 // and the truncate.
6869 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006870 }
Evan Chengd63baea2007-03-21 20:14:05 +00006871
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006872 // Fold extract-and-trunc into a narrow extract. For example:
6873 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6874 // i32 y = TRUNCATE(i64 x)
6875 // -- becomes --
6876 // v16i8 b = BITCAST (v2i64 val)
6877 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6878 //
6879 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006880 // creates this pattern) and before operation legalization after which
6881 // we need to be more careful about the vector instructions that we generate.
6882 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006883 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006884
6885 EVT VecTy = N0.getOperand(0).getValueType();
6886 EVT ExTy = N0.getValueType();
6887 EVT TrTy = N->getValueType(0);
6888
6889 unsigned NumElem = VecTy.getVectorNumElements();
6890 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6891
6892 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6893 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6894
6895 SDValue EltNo = N0->getOperand(1);
6896 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6897 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006898 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006899 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6900
Andrew Trickef9de2a2013-05-25 02:42:55 +00006901 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006902 NVT, N0.getOperand(0));
6903
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006904 SDLoc DL(N);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006905 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006906 DL, TrTy, V,
6907 DAG.getConstant(Index, DL, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006908 }
6909 }
6910
Matt Arsenault3332b702014-07-10 18:21:04 +00006911 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6912 if (N0.getOpcode() == ISD::SELECT) {
6913 EVT SrcVT = N0.getValueType();
6914 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6915 TLI.isTruncateFree(SrcVT, VT)) {
6916 SDLoc SL(N0);
6917 SDValue Cond = N0.getOperand(0);
6918 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6919 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6920 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6921 }
6922 }
6923
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006924 // Fold a series of buildvector, bitcast, and truncate if possible.
6925 // For example fold
6926 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6927 // (2xi32 (buildvector x, y)).
6928 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6929 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6930 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6931 N0.getOperand(0).hasOneUse()) {
6932
6933 SDValue BuildVect = N0.getOperand(0);
6934 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6935 EVT TruncVecEltTy = VT.getVectorElementType();
6936
6937 // Check that the element types match.
6938 if (BuildVectEltTy == TruncVecEltTy) {
6939 // Now we only need to compute the offset of the truncated elements.
6940 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6941 unsigned TruncVecNumElts = VT.getVectorNumElements();
6942 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6943
6944 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6945 "Invalid number of elements");
6946
6947 SmallVector<SDValue, 8> Opnds;
6948 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6949 Opnds.push_back(BuildVect.getOperand(i));
6950
Craig Topper48d114b2014-04-26 18:35:24 +00006951 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006952 }
6953 }
6954
Chris Lattner5e6fe052007-10-13 06:35:54 +00006955 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006956 // only the low bits are being used.
6957 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006958 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006959 // may have different active low bits.
6960 if (!VT.isVector()) {
6961 SDValue Shorter =
6962 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6963 VT.getSizeInBits()));
6964 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006965 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006966 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006967 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006968 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006969 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6970 SDValue Reduced = ReduceLoadWidth(N);
6971 if (Reduced.getNode())
6972 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006973 // Handle the case where the load remains an extending load even
6974 // after truncation.
6975 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6976 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6977 if (!LN0->isVolatile() &&
6978 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6979 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6980 VT, LN0->getChain(), LN0->getBasePtr(),
6981 LN0->getMemoryVT(),
6982 LN0->getMemOperand());
6983 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6984 return NewLoad;
6985 }
6986 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006987 }
Michael Liao3ac82012012-10-17 23:45:54 +00006988 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6989 // where ... are all 'undef'.
6990 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6991 SmallVector<EVT, 8> VTs;
6992 SDValue V;
6993 unsigned Idx = 0;
6994 unsigned NumDefs = 0;
6995
6996 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6997 SDValue X = N0.getOperand(i);
6998 if (X.getOpcode() != ISD::UNDEF) {
6999 V = X;
7000 Idx = i;
7001 NumDefs++;
7002 }
7003 // Stop if more than one members are non-undef.
7004 if (NumDefs > 1)
7005 break;
7006 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7007 VT.getVectorElementType(),
7008 X.getValueType().getVectorNumElements()));
7009 }
7010
7011 if (NumDefs == 0)
7012 return DAG.getUNDEF(VT);
7013
7014 if (NumDefs == 1) {
7015 assert(V.getNode() && "The single defined operand is empty!");
7016 SmallVector<SDValue, 8> Opnds;
7017 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7018 if (i != Idx) {
7019 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7020 continue;
7021 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007022 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007023 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00007024 Opnds.push_back(NV);
7025 }
Craig Topper48d114b2014-04-26 18:35:24 +00007026 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00007027 }
7028 }
Dan Gohman600f62b2010-06-24 14:30:44 +00007029
7030 // Simplify the operands using demanded-bits information.
7031 if (!VT.isVector() &&
7032 SimplifyDemandedBits(SDValue(N, 0)))
7033 return SDValue(N, 0);
7034
Evan Chengf1bd5fc2010-04-17 06:13:15 +00007035 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007036}
7037
Evan Chengb980f6f2008-05-12 23:04:07 +00007038static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007039 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00007040 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007041 return Elt.getNode();
7042 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00007043}
7044
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007045/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00007046/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00007047SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00007048 assert(N->getOpcode() == ISD::BUILD_PAIR);
7049
Nate Begeman624690c2009-06-05 21:37:30 +00007050 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7051 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00007052 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00007053 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007054 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00007055 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00007056
Evan Chengb980f6f2008-05-12 23:04:07 +00007057 if (ISD::isNON_EXTLoad(LD2) &&
7058 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00007059 // If both are volatile this would reduce the number of volatile loads.
7060 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00007061 !LD1->isVolatile() &&
7062 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00007063 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00007064 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007065 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00007066 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00007067
Duncan Sands8651e9c2008-06-13 19:07:40 +00007068 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007069 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007070 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00007071 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00007072 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00007073 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00007074
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007075 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00007076}
7077
Wesley Peck527da1b2010-11-23 03:31:01 +00007078SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007079 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007080 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00007081
Dan Gohmana8665142007-06-25 16:23:39 +00007082 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7083 // Only do this before legalize, since afterward the target may be depending
7084 // on the bitconvert.
7085 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007086 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007087 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007088 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00007089 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007090
Owen Anderson53aa7a92009-08-10 22:56:29 +00007091 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007092 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00007093 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00007094 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00007095 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00007096 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007097
Dan Gohman921ddd62008-09-05 01:58:21 +00007098 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00007099 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00007100 // If we can't allow illegal operations, we need to check that this is just
7101 // a fp -> int or int -> conversion and that the resulting operation will
7102 // be legal.
7103 if (!LegalOperations ||
7104 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7105 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7106 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7107 TLI.isOperationLegal(ISD::Constant, VT)))
7108 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00007109 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007110
Bill Wendling4e0a6152009-01-30 22:44:24 +00007111 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00007112 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007113 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007114 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007115
Chris Lattner54560f62005-12-23 05:44:41 +00007116 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00007117 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00007118 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00007119 // Do not change the width of a volatile load.
7120 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00007121 // Do not remove the cast if the types differ in endian layout.
7122 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7123 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00007124 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7125 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007126 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007127 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00007128 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00007129 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00007130
Evan Chenga4cf58a2007-05-07 21:27:48 +00007131 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007132 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00007133 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00007134 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007135 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00007136 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00007137 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00007138 return Load;
7139 }
Chris Lattner54560f62005-12-23 05:44:41 +00007140 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007141
Bill Wendling4e0a6152009-01-30 22:44:24 +00007142 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7143 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00007144 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00007145 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7146 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00007147 N0.getNode()->hasOneUse() && VT.isInteger() &&
7148 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007149 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007150 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007151 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00007152
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007153 SDLoc DL(N);
Duncan Sands13237ac2008-06-06 12:08:01 +00007154 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00007155 if (N0.getOpcode() == ISD::FNEG)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007156 return DAG.getNode(ISD::XOR, DL, VT,
7157 NewConv, DAG.getConstant(SignBit, DL, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00007158 assert(N0.getOpcode() == ISD::FABS);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007159 return DAG.getNode(ISD::AND, DL, VT,
7160 NewConv, DAG.getConstant(~SignBit, DL, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00007161 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007162
Bill Wendling4e0a6152009-01-30 22:44:24 +00007163 // fold (bitconvert (fcopysign cst, x)) ->
7164 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7165 // Note that we don't handle (copysign x, cst) because this can always be
7166 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00007167 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00007168 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007169 VT.isInteger() && !VT.isVector()) {
7170 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00007171 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00007172 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007173 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00007174 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007175 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007176
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007177 // If X has a different width than the result/lhs, sext it or truncate it.
7178 unsigned VTWidth = VT.getSizeInBits();
7179 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007180 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007181 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007182 } else if (OrigXWidth > VTWidth) {
7183 // To get the sign bit in the right place, we have to shift it right
7184 // before truncating.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007185 SDLoc DL(X);
7186 X = DAG.getNode(ISD::SRL, DL,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007187 X.getValueType(), X,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007188 DAG.getConstant(OrigXWidth-VTWidth, DL,
7189 X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007190 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007191 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007192 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007193 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007194
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007195 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007196 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007197 X, DAG.getConstant(SignBit, SDLoc(X), VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007198 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007199
Andrew Trickef9de2a2013-05-25 02:42:55 +00007200 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00007201 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007202 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007203 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007204 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007205
Andrew Trickef9de2a2013-05-25 02:42:55 +00007206 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007207 }
Chris Lattner888560d2008-01-27 17:42:27 +00007208 }
Evan Chengb980f6f2008-05-12 23:04:07 +00007209
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007210 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00007211 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007212 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7213 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00007214 return CombineLD;
7215 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007216
Simon Pilgrim86b034b2015-04-23 08:43:13 +00007217 // Remove double bitcasts from shuffles - this is often a legacy of
7218 // XformToShuffleWithZero being used to combine bitmaskings (of
7219 // float vectors bitcast to integer vectors) into shuffles.
7220 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7221 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7222 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7223 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7224 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7225 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7226
7227 // If operands are a bitcast, peek through if it casts the original VT.
7228 // If operands are a UNDEF or constant, just bitcast back to original VT.
7229 auto PeekThroughBitcast = [&](SDValue Op) {
7230 if (Op.getOpcode() == ISD::BITCAST &&
7231 Op.getOperand(0)->getValueType(0) == VT)
7232 return SDValue(Op.getOperand(0));
7233 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7234 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7235 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7236 return SDValue();
7237 };
7238
7239 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7240 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7241 if (!(SV0 && SV1))
7242 return SDValue();
7243
7244 int MaskScale =
7245 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7246 SmallVector<int, 8> NewMask;
7247 for (int M : SVN->getMask())
7248 for (int i = 0; i != MaskScale; ++i)
7249 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7250
7251 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7252 if (!LegalMask) {
7253 std::swap(SV0, SV1);
7254 ShuffleVectorSDNode::commuteMask(NewMask);
7255 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7256 }
7257
7258 if (LegalMask)
7259 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7260 }
7261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007262 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00007263}
7264
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007265SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007266 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00007267 return CombineConsecutiveLoads(N, VT);
7268}
7269
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007270/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7271/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007272SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00007273ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007274 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007275
Chris Lattnere4e64b62006-04-02 02:53:43 +00007276 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007277 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007278
Duncan Sands13237ac2008-06-06 12:08:01 +00007279 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7280 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007281
Chris Lattnere4e64b62006-04-02 02:53:43 +00007282 // If this is a conversion of N elements of one type to N elements of another
7283 // type, convert each element. This handles FP<->INT cases.
7284 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00007285 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7286 BV->getValueType(0).getVectorNumElements());
7287
7288 // Due to the FP element handling below calling this routine recursively,
7289 // we can end up with a scalar-to-vector node here.
7290 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007291 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7292 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00007293 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00007294
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007295 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007296 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00007297 SDValue Op = BV->getOperand(i);
7298 // If the vector element type is not legal, the BUILD_VECTOR operands
7299 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00007300 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007301 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7302 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00007303 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007304 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00007305 }
Craig Topper48d114b2014-04-26 18:35:24 +00007306 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), 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 // Otherwise, we're growing or shrinking the elements. To avoid having to
7310 // handle annoying details of growing/shrinking FP values, we convert them to
7311 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007312 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007313 // Convert the input float vector to a int vector where the elements are the
7314 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00007315 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007316 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00007317 SrcEltVT = IntVT;
7318 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007319
Chris Lattnere4e64b62006-04-02 02:53:43 +00007320 // Now we know the input is an integer vector. If the output is a FP type,
7321 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00007322 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00007323 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007324 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007325
Chris Lattnere4e64b62006-04-02 02:53:43 +00007326 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00007327 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007328 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007329
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007330 SDLoc DL(BV);
7331
Chris Lattnere4e64b62006-04-02 02:53:43 +00007332 // Okay, we know the src/dst types are both integers of differing types.
7333 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007334 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00007335 if (SrcBitSize < DstBitSize) {
7336 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007337
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007338 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007339 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00007340 i += NumInputsPerOutput) {
7341 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00007342 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007343 bool EltIsUndef = true;
7344 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7345 // Shift the previously computed bits over.
7346 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007347 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007348 if (Op.getOpcode() == ISD::UNDEF) continue;
7349 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007350
Jay Foad583abbc2010-12-07 08:25:19 +00007351 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00007352 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007353 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007354
Chris Lattnere4e64b62006-04-02 02:53:43 +00007355 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00007356 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007357 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007358 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007359 }
7360
Owen Anderson117c9e82009-08-12 00:36:31 +00007361 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007362 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007363 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007364
Chris Lattnere4e64b62006-04-02 02:53:43 +00007365 // Finally, this must be the case where we are shrinking elements: each input
7366 // turns into multiple outputs.
7367 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007368 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7369 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007370 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007371
Dan Gohmana8665142007-06-25 16:23:39 +00007372 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007373 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007374 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007375 continue;
7376 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007377
Jay Foad583abbc2010-12-07 08:25:19 +00007378 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7379 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007380
Chris Lattnere4e64b62006-04-02 02:53:43 +00007381 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007382 APInt ThisVal = OpVal.trunc(DstBitSize);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007383 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
Dan Gohmane1c4f992008-03-03 23:51:38 +00007384 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007385 }
7386
7387 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007388 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007389 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7390 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007391
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007392 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007393}
7394
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007395/// Try to perform FMA combining on a given FADD node.
7396SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007397 SDValue N0 = N->getOperand(0);
7398 SDValue N1 = N->getOperand(1);
7399 EVT VT = N->getValueType(0);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007400 SDLoc SL(N);
7401
7402 const TargetOptions &Options = DAG.getTarget().Options;
7403 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7404 Options.UnsafeFPMath);
7405
7406 // Floating-point multiply-add with intermediate rounding.
7407 bool HasFMAD = (LegalOperations &&
7408 TLI.isOperationLegal(ISD::FMAD, VT));
7409
7410 // Floating-point multiply-add without intermediate rounding.
7411 bool HasFMA = ((!LegalOperations ||
7412 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7413 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7414 UnsafeFPMath);
7415
7416 // No valid opcode, do not combine.
7417 if (!HasFMAD && !HasFMA)
7418 return SDValue();
7419
7420 // Always prefer FMAD to FMA for precision.
7421 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7422 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7423 bool LookThroughFPExt = TLI.isFPExtFree(VT);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007424
7425 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7426 if (N0.getOpcode() == ISD::FMUL &&
7427 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007428 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007429 N0.getOperand(0), N0.getOperand(1), N1);
7430 }
7431
7432 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7433 // Note: Commutes FADD operands.
7434 if (N1.getOpcode() == ISD::FMUL &&
7435 (Aggressive || N1->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007436 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007437 N1.getOperand(0), N1.getOperand(1), N0);
7438 }
7439
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007440 // Look through FP_EXTEND nodes to do more combining.
7441 if (UnsafeFPMath && LookThroughFPExt) {
7442 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7443 if (N0.getOpcode() == ISD::FP_EXTEND) {
7444 SDValue N00 = N0.getOperand(0);
7445 if (N00.getOpcode() == ISD::FMUL)
7446 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7447 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7448 N00.getOperand(0)),
7449 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7450 N00.getOperand(1)), N1);
7451 }
7452
7453 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7454 // Note: Commutes FADD operands.
7455 if (N1.getOpcode() == ISD::FP_EXTEND) {
7456 SDValue N10 = N1.getOperand(0);
7457 if (N10.getOpcode() == ISD::FMUL)
7458 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7459 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7460 N10.getOperand(0)),
7461 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7462 N10.getOperand(1)), N0);
7463 }
7464 }
7465
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007466 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007467 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007468 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007469 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007470 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007471 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007472 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007473 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007474 N0.getOperand(2).getOperand(0),
7475 N0.getOperand(2).getOperand(1),
7476 N1));
7477 }
7478
7479 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007480 if (N1->getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007481 N1.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007482 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007483 N1.getOperand(0), N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007484 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007485 N1.getOperand(2).getOperand(0),
7486 N1.getOperand(2).getOperand(1),
7487 N0));
7488 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007489
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007490 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007491 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7492 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7493 auto FoldFAddFMAFPExtFMul = [&] (
7494 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7495 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7496 DAG.getNode(PreferredFusedOpcode, SL, VT,
7497 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7498 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7499 Z));
7500 };
7501 if (N0.getOpcode() == PreferredFusedOpcode) {
7502 SDValue N02 = N0.getOperand(2);
7503 if (N02.getOpcode() == ISD::FP_EXTEND) {
7504 SDValue N020 = N02.getOperand(0);
7505 if (N020.getOpcode() == ISD::FMUL)
7506 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7507 N020.getOperand(0), N020.getOperand(1),
7508 N1);
7509 }
7510 }
7511
7512 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7513 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7514 // FIXME: This turns two single-precision and one double-precision
7515 // operation into two double-precision operations, which might not be
7516 // interesting for all targets, especially GPUs.
7517 auto FoldFAddFPExtFMAFMul = [&] (
7518 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7519 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7520 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7521 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7522 DAG.getNode(PreferredFusedOpcode, SL, VT,
7523 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7524 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7525 Z));
7526 };
7527 if (N0.getOpcode() == ISD::FP_EXTEND) {
7528 SDValue N00 = N0.getOperand(0);
7529 if (N00.getOpcode() == PreferredFusedOpcode) {
7530 SDValue N002 = N00.getOperand(2);
7531 if (N002.getOpcode() == ISD::FMUL)
7532 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7533 N002.getOperand(0), N002.getOperand(1),
7534 N1);
7535 }
7536 }
7537
7538 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7539 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7540 if (N1.getOpcode() == PreferredFusedOpcode) {
7541 SDValue N12 = N1.getOperand(2);
7542 if (N12.getOpcode() == ISD::FP_EXTEND) {
7543 SDValue N120 = N12.getOperand(0);
7544 if (N120.getOpcode() == ISD::FMUL)
7545 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7546 N120.getOperand(0), N120.getOperand(1),
7547 N0);
7548 }
7549 }
7550
7551 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7552 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7553 // FIXME: This turns two single-precision and one double-precision
7554 // operation into two double-precision operations, which might not be
7555 // interesting for all targets, especially GPUs.
7556 if (N1.getOpcode() == ISD::FP_EXTEND) {
7557 SDValue N10 = N1.getOperand(0);
7558 if (N10.getOpcode() == PreferredFusedOpcode) {
7559 SDValue N102 = N10.getOperand(2);
7560 if (N102.getOpcode() == ISD::FMUL)
7561 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7562 N102.getOperand(0), N102.getOperand(1),
7563 N0);
7564 }
7565 }
7566 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007567 }
7568
7569 return SDValue();
7570}
7571
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007572/// Try to perform FMA combining on a given FSUB node.
7573SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007574 SDValue N0 = N->getOperand(0);
7575 SDValue N1 = N->getOperand(1);
7576 EVT VT = N->getValueType(0);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007577 SDLoc SL(N);
7578
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007579 const TargetOptions &Options = DAG.getTarget().Options;
7580 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7581 Options.UnsafeFPMath);
7582
7583 // Floating-point multiply-add with intermediate rounding.
7584 bool HasFMAD = (LegalOperations &&
7585 TLI.isOperationLegal(ISD::FMAD, VT));
7586
7587 // Floating-point multiply-add without intermediate rounding.
7588 bool HasFMA = ((!LegalOperations ||
7589 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7590 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7591 UnsafeFPMath);
7592
7593 // No valid opcode, do not combine.
7594 if (!HasFMAD && !HasFMA)
7595 return SDValue();
7596
7597 // Always prefer FMAD to FMA for precision.
7598 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7599 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7600 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7601
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007602 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7603 if (N0.getOpcode() == ISD::FMUL &&
7604 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007605 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007606 N0.getOperand(0), N0.getOperand(1),
7607 DAG.getNode(ISD::FNEG, SL, VT, N1));
7608 }
7609
7610 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7611 // Note: Commutes FSUB operands.
7612 if (N1.getOpcode() == ISD::FMUL &&
7613 (Aggressive || N1->hasOneUse()))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007614 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007615 DAG.getNode(ISD::FNEG, SL, VT,
7616 N1.getOperand(0)),
7617 N1.getOperand(1), N0);
7618
7619 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7620 if (N0.getOpcode() == ISD::FNEG &&
7621 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7622 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7623 SDValue N00 = N0.getOperand(0).getOperand(0);
7624 SDValue N01 = N0.getOperand(0).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007625 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007626 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7627 DAG.getNode(ISD::FNEG, SL, VT, N1));
7628 }
7629
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007630 // Look through FP_EXTEND nodes to do more combining.
7631 if (UnsafeFPMath && LookThroughFPExt) {
7632 // fold (fsub (fpext (fmul x, y)), z)
7633 // -> (fma (fpext x), (fpext y), (fneg z))
7634 if (N0.getOpcode() == ISD::FP_EXTEND) {
7635 SDValue N00 = N0.getOperand(0);
7636 if (N00.getOpcode() == ISD::FMUL)
7637 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7638 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7639 N00.getOperand(0)),
7640 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641 N00.getOperand(1)),
7642 DAG.getNode(ISD::FNEG, SL, VT, N1));
7643 }
7644
7645 // fold (fsub x, (fpext (fmul y, z)))
7646 // -> (fma (fneg (fpext y)), (fpext z), x)
7647 // Note: Commutes FSUB operands.
7648 if (N1.getOpcode() == ISD::FP_EXTEND) {
7649 SDValue N10 = N1.getOperand(0);
7650 if (N10.getOpcode() == ISD::FMUL)
7651 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7652 DAG.getNode(ISD::FNEG, SL, VT,
7653 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7654 N10.getOperand(0))),
7655 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7656 N10.getOperand(1)),
7657 N0);
7658 }
7659
7660 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7661 // -> (fneg (fma (fpext x), (fpext y), z))
7662 // Note: This could be removed with appropriate canonicalization of the
7663 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7664 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7665 // from implementing the canonicalization in visitFSUB.
7666 if (N0.getOpcode() == ISD::FP_EXTEND) {
7667 SDValue N00 = N0.getOperand(0);
7668 if (N00.getOpcode() == ISD::FNEG) {
7669 SDValue N000 = N00.getOperand(0);
7670 if (N000.getOpcode() == ISD::FMUL) {
7671 return DAG.getNode(ISD::FNEG, SL, VT,
7672 DAG.getNode(PreferredFusedOpcode, SL, VT,
7673 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7674 N000.getOperand(0)),
7675 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7676 N000.getOperand(1)),
7677 N1));
7678 }
7679 }
7680 }
7681
7682 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7683 // -> (fneg (fma (fpext x)), (fpext y), z)
7684 // Note: This could be removed with appropriate canonicalization of the
7685 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7686 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7687 // from implementing the canonicalization in visitFSUB.
7688 if (N0.getOpcode() == ISD::FNEG) {
7689 SDValue N00 = N0.getOperand(0);
7690 if (N00.getOpcode() == ISD::FP_EXTEND) {
7691 SDValue N000 = N00.getOperand(0);
7692 if (N000.getOpcode() == ISD::FMUL) {
7693 return DAG.getNode(ISD::FNEG, SL, VT,
7694 DAG.getNode(PreferredFusedOpcode, SL, VT,
7695 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7696 N000.getOperand(0)),
7697 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7698 N000.getOperand(1)),
7699 N1));
7700 }
7701 }
7702 }
7703
7704 }
7705
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007706 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007707 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007708 // fold (fsub (fma x, y, (fmul u, v)), z)
7709 // -> (fma x, y (fma u, v, (fneg z)))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007710 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007711 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007712 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007713 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007714 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007715 N0.getOperand(2).getOperand(0),
7716 N0.getOperand(2).getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007717 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007718 N1)));
7719 }
7720
7721 // fold (fsub x, (fma y, z, (fmul u, v)))
7722 // -> (fma (fneg y), z, (fma (fneg u), v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007723 if (N1.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007724 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7725 SDValue N20 = N1.getOperand(2).getOperand(0);
7726 SDValue N21 = N1.getOperand(2).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007727 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7728 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007729 N1.getOperand(0)),
7730 N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007731 DAG.getNode(PreferredFusedOpcode, SL, VT,
7732 DAG.getNode(ISD::FNEG, SL, VT, N20),
7733
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007734 N21, N0));
7735 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007736
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007737 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007738 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7739 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7740 if (N0.getOpcode() == PreferredFusedOpcode) {
7741 SDValue N02 = N0.getOperand(2);
7742 if (N02.getOpcode() == ISD::FP_EXTEND) {
7743 SDValue N020 = N02.getOperand(0);
7744 if (N020.getOpcode() == ISD::FMUL)
7745 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746 N0.getOperand(0), N0.getOperand(1),
7747 DAG.getNode(PreferredFusedOpcode, SL, VT,
7748 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7749 N020.getOperand(0)),
7750 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7751 N020.getOperand(1)),
7752 DAG.getNode(ISD::FNEG, SL, VT,
7753 N1)));
7754 }
7755 }
7756
7757 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7758 // -> (fma (fpext x), (fpext y),
7759 // (fma (fpext u), (fpext v), (fneg z)))
7760 // FIXME: This turns two single-precision and one double-precision
7761 // operation into two double-precision operations, which might not be
7762 // interesting for all targets, especially GPUs.
7763 if (N0.getOpcode() == ISD::FP_EXTEND) {
7764 SDValue N00 = N0.getOperand(0);
7765 if (N00.getOpcode() == PreferredFusedOpcode) {
7766 SDValue N002 = N00.getOperand(2);
7767 if (N002.getOpcode() == ISD::FMUL)
7768 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7769 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7770 N00.getOperand(0)),
7771 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772 N00.getOperand(1)),
7773 DAG.getNode(PreferredFusedOpcode, SL, VT,
7774 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7775 N002.getOperand(0)),
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777 N002.getOperand(1)),
7778 DAG.getNode(ISD::FNEG, SL, VT,
7779 N1)));
7780 }
7781 }
7782
7783 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7784 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7785 if (N1.getOpcode() == PreferredFusedOpcode &&
7786 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7787 SDValue N120 = N1.getOperand(2).getOperand(0);
7788 if (N120.getOpcode() == ISD::FMUL) {
7789 SDValue N1200 = N120.getOperand(0);
7790 SDValue N1201 = N120.getOperand(1);
7791 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7792 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7793 N1.getOperand(1),
7794 DAG.getNode(PreferredFusedOpcode, SL, VT,
7795 DAG.getNode(ISD::FNEG, SL, VT,
7796 DAG.getNode(ISD::FP_EXTEND, SL,
7797 VT, N1200)),
7798 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7799 N1201),
7800 N0));
7801 }
7802 }
7803
7804 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7805 // -> (fma (fneg (fpext y)), (fpext z),
7806 // (fma (fneg (fpext u)), (fpext v), x))
7807 // FIXME: This turns two single-precision and one double-precision
7808 // operation into two double-precision operations, which might not be
7809 // interesting for all targets, especially GPUs.
7810 if (N1.getOpcode() == ISD::FP_EXTEND &&
7811 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7812 SDValue N100 = N1.getOperand(0).getOperand(0);
7813 SDValue N101 = N1.getOperand(0).getOperand(1);
7814 SDValue N102 = N1.getOperand(0).getOperand(2);
7815 if (N102.getOpcode() == ISD::FMUL) {
7816 SDValue N1020 = N102.getOperand(0);
7817 SDValue N1021 = N102.getOperand(1);
7818 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7819 DAG.getNode(ISD::FNEG, SL, VT,
7820 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7821 N100)),
7822 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7823 DAG.getNode(PreferredFusedOpcode, SL, VT,
7824 DAG.getNode(ISD::FNEG, SL, VT,
7825 DAG.getNode(ISD::FP_EXTEND, SL,
7826 VT, N1020)),
7827 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7828 N1021),
7829 N0));
7830 }
7831 }
7832 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007833 }
7834
7835 return SDValue();
7836}
7837
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007838SDValue DAGCombiner::visitFADD(SDNode *N) {
7839 SDValue N0 = N->getOperand(0);
7840 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007843 EVT VT = N->getValueType(0);
Sanjay Patelcaf51802015-04-29 21:01:41 +00007844 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007845 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007846
Dan Gohmana8665142007-06-25 16:23:39 +00007847 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007848 if (VT.isVector())
7849 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7850 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007851
Lang Hamesa33db652012-06-14 20:37:15 +00007852 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007853 if (N0CFP && N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007854 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007855
Nate Begeman418c6e42005-10-18 00:28:13 +00007856 // canonicalize constant to RHS
7857 if (N0CFP && !N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007858 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007859
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007860 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007861 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007862 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007863 return DAG.getNode(ISD::FSUB, DL, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007864 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007865
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007866 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007867 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007868 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007869 return DAG.getNode(ISD::FSUB, DL, VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007870 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007871
Sanjay Patel8170dea2014-09-08 17:32:19 +00007872 // If 'unsafe math' is enabled, fold lots of things.
7873 if (Options.UnsafeFPMath) {
7874 // No FP constant should be created after legalization as Instruction
7875 // Selection pass has a hard time dealing with FP constants.
7876 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007877
Sanjay Patel8170dea2014-09-08 17:32:19 +00007878 // fold (fadd A, 0) -> A
Andrea Di Biagioeb331342015-06-05 10:29:55 +00007879 if (N1CFP && N1CFP->isZero())
Sanjay Patel8170dea2014-09-08 17:32:19 +00007880 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007881
Sanjay Patel8170dea2014-09-08 17:32:19 +00007882 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7883 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7884 isa<ConstantFPSDNode>(N0.getOperand(1)))
Sanjay Patelcaf51802015-04-29 21:01:41 +00007885 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7886 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007887
Sanjay Patel8170dea2014-09-08 17:32:19 +00007888 // If allowed, fold (fadd (fneg x), x) -> 0.0
7889 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007890 return DAG.getConstantFP(0.0, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007891
Sanjay Patel8170dea2014-09-08 17:32:19 +00007892 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7893 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007894 return DAG.getConstantFP(0.0, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007895
Sanjay Patel8170dea2014-09-08 17:32:19 +00007896 // We can fold chains of FADD's of the same value into multiplications.
7897 // This transform is not safe in general because we are reducing the number
7898 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007899 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7900 if (N0.getOpcode() == ISD::FMUL) {
7901 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7902 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007903
Sanjay Patel8170dea2014-09-08 17:32:19 +00007904 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7905 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007906 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007907 DAG.getConstantFP(1.0, DL, VT));
7908 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007909 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007910
Sanjay Patel8170dea2014-09-08 17:32:19 +00007911 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7912 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7913 N1.getOperand(0) == N1.getOperand(1) &&
7914 N0.getOperand(0) == N1.getOperand(0)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007915 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007916 DAG.getConstantFP(2.0, DL, VT));
Sanjay Patelcaf51802015-04-29 21:01:41 +00007917 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007918 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007919 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007920
Sanjay Patel8170dea2014-09-08 17:32:19 +00007921 if (N1.getOpcode() == ISD::FMUL) {
7922 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7923 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007924
Sanjay Patel8170dea2014-09-08 17:32:19 +00007925 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7926 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007927 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007928 DAG.getConstantFP(1.0, DL, VT));
7929 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007930 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007931
Sanjay Patel8170dea2014-09-08 17:32:19 +00007932 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7933 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7934 N0.getOperand(0) == N0.getOperand(1) &&
7935 N1.getOperand(0) == N0.getOperand(0)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007936 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007937 DAG.getConstantFP(2.0, DL, VT));
7938 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007939 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007940 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007941
Sanjay Patel8170dea2014-09-08 17:32:19 +00007942 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7943 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7944 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7945 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007946 (N0.getOperand(0) == N1)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007947 return DAG.getNode(ISD::FMUL, DL, VT,
7948 N1, DAG.getConstantFP(3.0, DL, VT));
7949 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007950 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007951
Sanjay Patel8170dea2014-09-08 17:32:19 +00007952 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7953 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7954 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7955 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007956 N1.getOperand(0) == N0) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007957 return DAG.getNode(ISD::FMUL, DL, VT,
7958 N0, DAG.getConstantFP(3.0, DL, VT));
7959 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007960 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007961
Sanjay Patel8170dea2014-09-08 17:32:19 +00007962 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7963 if (AllowNewConst &&
7964 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007965 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007966 N1.getOperand(0) == N1.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007967 N0.getOperand(0) == N1.getOperand(0)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007968 return DAG.getNode(ISD::FMUL, DL, VT,
7969 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7970 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007971 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007972 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007973
Lang Hames39fb1d02012-06-19 22:51:23 +00007974 // FADD -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007975 SDValue Fused = visitFADDForFMACombine(N);
7976 if (Fused) {
7977 AddToWorklist(Fused.getNode());
7978 return Fused;
Olivier Sallenave04515322015-01-07 20:54:17 +00007979 }
7980
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007981 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007982}
7983
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007984SDValue DAGCombiner::visitFSUB(SDNode *N) {
7985 SDValue N0 = N->getOperand(0);
7986 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007987 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7988 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007989 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007990 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007991 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007992
Dan Gohmana8665142007-06-25 16:23:39 +00007993 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007994 if (VT.isVector())
7995 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7996 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007997
Nate Begeman418c6e42005-10-18 00:28:13 +00007998 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007999 if (N0CFP && N1CFP)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008000 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00008001
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00008002 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008003 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00008004 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008005 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008006
Sanjay Patelae402a32014-08-27 20:57:52 +00008007 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00008008 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00008009 // (fsub A, 0) -> A
Andrea Di Biagioeb331342015-06-05 10:29:55 +00008010 if (N1CFP && N1CFP->isZero())
Sanjay Patelae402a32014-08-27 20:57:52 +00008011 return N0;
8012
8013 // (fsub 0, B) -> -B
Andrea Di Biagioeb331342015-06-05 10:29:55 +00008014 if (N0CFP && N0CFP->isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00008015 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00008016 return GetNegatedExpression(N1, DAG, LegalOperations);
8017 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8018 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8019 }
8020
8021 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00008022 if (N0 == N1)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008023 return DAG.getConstantFP(0.0f, dl, VT);
Owen Andersonab63d842012-05-07 20:51:25 +00008024
Sanjay Patelae402a32014-08-27 20:57:52 +00008025 // (fsub x, (fadd x, y)) -> (fneg y)
8026 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00008027 if (N1.getOpcode() == ISD::FADD) {
8028 SDValue N10 = N1->getOperand(0);
8029 SDValue N11 = N1->getOperand(1);
8030
Sanjay Patel78614bf2014-08-28 15:53:16 +00008031 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00008032 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00008033
Sanjay Patel78614bf2014-08-28 15:53:16 +00008034 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00008035 return GetNegatedExpression(N10, DAG, LegalOperations);
8036 }
8037 }
8038
Lang Hames39fb1d02012-06-19 22:51:23 +00008039 // FSUB -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00008040 SDValue Fused = visitFSUBForFMACombine(N);
8041 if (Fused) {
8042 AddToWorklist(Fused.getNode());
8043 return Fused;
Lang Hames39fb1d02012-06-19 22:51:23 +00008044 }
8045
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008046 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008047}
8048
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008049SDValue DAGCombiner::visitFMUL(SDNode *N) {
8050 SDValue N0 = N->getOperand(0);
8051 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00008052 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8053 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008054 EVT VT = N->getValueType(0);
Sanjay Patelcaf51802015-04-29 21:01:41 +00008055 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008056 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00008057
Dan Gohmana8665142007-06-25 16:23:39 +00008058 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00008059 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008060 // This just handles C1 * C2 for vectors. Other vector folds are below.
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00008061 if (SDValue FoldedVOp = SimplifyVBinOp(N))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008062 return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00008063 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008064
Nate Begemanec48a1b2005-10-17 20:40:11 +00008065 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008066 if (N0CFP && N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00008067 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00008068
Nate Begemanec48a1b2005-10-17 20:40:11 +00008069 // canonicalize constant to RHS
Simon Pilgrimbcf3bc22015-04-05 14:30:37 +00008070 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8071 !isConstantFPBuildVectorOrConstantFP(N1))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008072 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00008073
Owen Andersonb5f167c2012-05-02 21:32:35 +00008074 // fold (fmul A, 1.0) -> A
8075 if (N1CFP && N1CFP->isExactlyValue(1.0))
8076 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00008077
Sanjay Patel394c3332014-09-08 20:16:42 +00008078 if (Options.UnsafeFPMath) {
8079 // fold (fmul A, 0) -> 0
Andrea Di Biagioeb331342015-06-05 10:29:55 +00008080 if (N1CFP && N1CFP->isZero())
Sanjay Patel394c3332014-09-08 20:16:42 +00008081 return N1;
8082
8083 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008084 if (N0.getOpcode() == ISD::FMUL) {
8085 // Fold scalars or any vector constants (not just splats).
8086 // This fold is done in general by InstCombine, but extra fmul insts
8087 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008088 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008089 SDValue N01 = N0.getOperand(1);
8090 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008091 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008092 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Simon Pilgrim096cccd2015-06-13 12:57:36 +00008093
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008094 // Check 1: Make sure that the first operand of the inner multiply is NOT
8095 // a constant. Otherwise, we may induce infinite looping.
8096 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8097 // Check 2: Make sure that the second operand of the inner multiply and
8098 // the second operand of the outer multiply are constants.
8099 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8100 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00008101 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8102 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008103 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008104 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008105 }
8106
Sanjay Patel394c3332014-09-08 20:16:42 +00008107 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008108 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8109 // during an early run of DAGCombiner can prevent folding with fmuls
8110 // inserted during lowering.
8111 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00008112 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8113 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8114 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008115 }
8116 }
8117
Nate Begemanec48a1b2005-10-17 20:40:11 +00008118 // fold (fmul X, 2.0) -> (fadd X, X)
8119 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008120 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00008121
Dan Gohmanb7170912009-08-10 16:50:32 +00008122 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00008123 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00008124 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008125 return DAG.getNode(ISD::FNEG, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008126
Bill Wendling3dc5d242009-01-30 22:57:07 +00008127 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008128 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8129 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008130 // Both can be negated for free, check to see if at least one is cheaper
8131 // negated.
8132 if (LHSNeg == 2 || RHSNeg == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00008133 return DAG.getNode(ISD::FMUL, DL, VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008134 GetNegatedExpression(N0, DAG, LegalOperations),
8135 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008136 }
8137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008139 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008140}
8141
Owen Anderson41b06652012-05-02 22:17:40 +00008142SDValue DAGCombiner::visitFMA(SDNode *N) {
8143 SDValue N0 = N->getOperand(0);
8144 SDValue N1 = N->getOperand(1);
8145 SDValue N2 = N->getOperand(2);
8146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8147 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8148 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008149 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008150 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00008151
8152 // Constant fold FMA.
8153 if (isa<ConstantFPSDNode>(N0) &&
8154 isa<ConstantFPSDNode>(N1) &&
8155 isa<ConstantFPSDNode>(N2)) {
8156 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8157 }
8158
Sanjay Patel78614bf2014-08-28 15:53:16 +00008159 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00008160 if (N0CFP && N0CFP->isZero())
8161 return N2;
8162 if (N1CFP && N1CFP->isZero())
8163 return N2;
8164 }
Owen Anderson41b06652012-05-02 22:17:40 +00008165 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008166 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00008167 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008168 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00008169
Owen Andersonc7aaf522012-05-30 18:50:39 +00008170 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00008171 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008172 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00008173
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008174 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008175 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008176 N2.getOpcode() == ISD::FMUL &&
8177 N0 == N2.getOperand(0) &&
8178 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8179 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8180 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8181 }
8182
8183
8184 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008185 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008186 N0.getOpcode() == ISD::FMUL && N1CFP &&
8187 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8188 return DAG.getNode(ISD::FMA, dl, VT,
8189 N0.getOperand(0),
8190 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8191 N2);
8192 }
8193
8194 // (fma x, 1, y) -> (fadd x, y)
8195 // (fma x, -1, y) -> (fadd (fneg x), y)
8196 if (N1CFP) {
8197 if (N1CFP->isExactlyValue(1.0))
8198 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8199
8200 if (N1CFP->isExactlyValue(-1.0) &&
8201 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8202 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008203 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008204 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8205 }
8206 }
8207
8208 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00008209 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00008210 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008211 DAG.getNode(ISD::FADD, dl, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008212 N1, DAG.getConstantFP(1.0, dl, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008213
8214 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00008215 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00008216 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8217 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008218 DAG.getNode(ISD::FADD, dl, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008219 N1, DAG.getConstantFP(-1.0, dl, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008220
8221
Owen Anderson41b06652012-05-02 22:17:40 +00008222 return SDValue();
8223}
8224
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008225SDValue DAGCombiner::visitFDIV(SDNode *N) {
8226 SDValue N0 = N->getOperand(0);
8227 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008228 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8229 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008230 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008231 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008232 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00008233
Dan Gohmana8665142007-06-25 16:23:39 +00008234 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00008235 if (VT.isVector())
8236 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8237 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008238
Nate Begeman569c4392006-01-18 22:35:16 +00008239 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008240 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008241 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008242
Sanjay Patelb67bd262014-09-21 15:19:15 +00008243 if (Options.UnsafeFPMath) {
8244 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8245 if (N1CFP) {
8246 // Compute the reciprocal 1.0 / c2.
8247 APFloat N1APF = N1CFP->getValueAPF();
8248 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8249 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8250 // Only do the transform if the reciprocal is a legal fp immediate that
8251 // isn't too nasty (eg NaN, denormal, ...).
8252 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8253 (!LegalOperations ||
8254 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8255 // backend)... we should handle this gracefully after Legalize.
8256 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8257 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8258 TLI.isFPImmLegal(Recip, VT)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008259 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8260 DAG.getConstantFP(Recip, DL, VT));
Sanjay Patelb67bd262014-09-21 15:19:15 +00008261 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008262
Sanjay Patelb67bd262014-09-21 15:19:15 +00008263 // If this FDIV is part of a reciprocal square root, it may be folded
8264 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008265 if (N1.getOpcode() == ISD::FSQRT) {
8266 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008267 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8268 }
8269 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8270 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8271 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008272 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8273 AddToWorklist(RV.getNode());
8274 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8275 }
8276 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8277 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8278 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008279 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8280 AddToWorklist(RV.getNode());
8281 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8282 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00008283 } else if (N1.getOpcode() == ISD::FMUL) {
8284 // Look through an FMUL. Even though this won't remove the FDIV directly,
8285 // it's still worthwhile to get rid of the FSQRT if possible.
8286 SDValue SqrtOp;
8287 SDValue OtherOp;
8288 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8289 SqrtOp = N1.getOperand(0);
8290 OtherOp = N1.getOperand(1);
8291 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8292 SqrtOp = N1.getOperand(1);
8293 OtherOp = N1.getOperand(0);
8294 }
8295 if (SqrtOp.getNode()) {
8296 // We found a FSQRT, so try to make this fold:
8297 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8298 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00008299 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8300 AddToWorklist(RV.getNode());
8301 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8302 }
8303 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008304 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008305
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008306 // Fold into a reciprocal estimate and multiply instead of a real divide.
8307 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8308 AddToWorklist(RV.getNode());
8309 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8310 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00008311 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008312
Bill Wendling3dc5d242009-01-30 22:57:07 +00008313 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008314 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8315 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008316 // Both can be negated for free, check to see if at least one is cheaper
8317 // negated.
8318 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008319 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008320 GetNegatedExpression(N0, DAG, LegalOperations),
8321 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008322 }
8323 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008324
Hao Liu44e5d7a2014-11-21 06:39:58 +00008325 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8326 // reciprocal.
8327 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8328 // Notice that this is not always beneficial. One reason is different target
8329 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8330 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8331 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8332 if (Options.UnsafeFPMath) {
8333 // Skip if current node is a reciprocal.
8334 if (N0CFP && N0CFP->isExactlyValue(1.0))
8335 return SDValue();
8336
8337 SmallVector<SDNode *, 4> Users;
8338 // Find all FDIV users of the same divisor.
Sanjay Patel03abbb42015-05-19 20:10:16 +00008339 for (auto *U : N1->uses()) {
Sanjay Patel64a6da92015-05-19 18:24:33 +00008340 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8341 Users.push_back(U);
Hao Liu44e5d7a2014-11-21 06:39:58 +00008342 }
8343
8344 if (TLI.combineRepeatedFPDivisors(Users.size())) {
Sanjay Patelad114152015-05-19 19:10:57 +00008345 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008346 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
Hao Liu44e5d7a2014-11-21 06:39:58 +00008347
8348 // Dividend / Divisor -> Dividend * Reciprocal
Sanjay Patel03abbb42015-05-19 20:10:16 +00008349 for (auto *U : Users) {
Sanjay Patelad114152015-05-19 19:10:57 +00008350 SDValue Dividend = U->getOperand(0);
8351 if (Dividend != FPOne) {
8352 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8353 Reciprocal);
Sanjay Patel3c9e3702015-05-19 17:49:14 +00008354 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
Hao Liu44e5d7a2014-11-21 06:39:58 +00008355 }
8356 }
8357 return SDValue();
8358 }
8359 }
8360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008361 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008362}
8363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008364SDValue DAGCombiner::visitFREM(SDNode *N) {
8365 SDValue N0 = N->getOperand(0);
8366 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008367 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8368 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008369 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00008370
Nate Begeman569c4392006-01-18 22:35:16 +00008371 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008372 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008373 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00008374
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008375 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008376}
8377
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008378SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00008379 if (DAG.getTarget().Options.UnsafeFPMath &&
8380 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008381 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008382 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008383 EVT VT = RV.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008384 SDLoc DL(N);
8385 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008386 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008387
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008388 // Unfortunately, RV is now NaN if the input was exactly 0.
8389 // Select out this case and force the answer to 0.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008390 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008391 SDValue ZeroCmp =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008392 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008393 N->getOperand(0), Zero, ISD::SETEQ);
8394 AddToWorklist(ZeroCmp.getNode());
8395 AddToWorklist(RV.getNode());
8396
8397 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008398 DL, VT, ZeroCmp, Zero, RV);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008399 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008400 }
8401 }
8402 return SDValue();
8403}
8404
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008405SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8406 SDValue N0 = N->getOperand(0);
8407 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008408 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8409 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008410 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00008411
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008412 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00008413 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008414
Chris Lattner3bc40502006-03-05 05:30:57 +00008415 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00008416 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00008417 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8418 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00008419 if (!V.isNegative()) {
8420 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008421 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00008422 } else {
8423 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008424 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8425 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00008426 }
Chris Lattner3bc40502006-03-05 05:30:57 +00008427 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008428
Chris Lattner3bc40502006-03-05 05:30:57 +00008429 // copysign(fabs(x), y) -> copysign(x, y)
8430 // copysign(fneg(x), y) -> copysign(x, y)
8431 // copysign(copysign(x,z), y) -> copysign(x, y)
8432 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8433 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008434 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008435 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008436
8437 // copysign(x, abs(y)) -> abs(x)
8438 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008439 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008440
Chris Lattner3bc40502006-03-05 05:30:57 +00008441 // copysign(x, copysign(y,z)) -> copysign(x, z)
8442 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008443 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008444 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008445
Chris Lattner3bc40502006-03-05 05:30:57 +00008446 // copysign(x, fp_extend(y)) -> copysign(x, y)
8447 // copysign(x, fp_round(y)) -> copysign(x, y)
8448 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008449 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008450 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008452 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00008453}
8454
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008455SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8456 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008457 EVT VT = N->getValueType(0);
8458 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008459
Nate Begeman21158fc2005-09-01 00:19:25 +00008460 // fold (sint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008461 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008462 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008463 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008464 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008465 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008466
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008467 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8468 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008469 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8470 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008471 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008472 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008473 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008474 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008475
Alp Tokercb402912014-01-24 17:20:08 +00008476 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008477 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008478 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8479 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8480 !VT.isVector() &&
8481 (!LegalOperations ||
8482 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008483 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008484 SDValue Ops[] =
8485 { N0.getOperand(0), N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008486 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008487 N0.getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008488 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008489 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008490
Nadav Rotem90560762012-07-23 07:59:50 +00008491 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8492 // (select_cc x, y, 1.0, 0.0,, cc)
8493 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8494 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8495 (!LegalOperations ||
8496 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008497 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008498 SDValue Ops[] =
8499 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008500 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008501 N0.getOperand(0).getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008502 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008503 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008504 }
8505
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008506 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008507}
8508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008509SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8510 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008511 EVT VT = N->getValueType(0);
8512 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00008513
Nate Begeman21158fc2005-09-01 00:19:25 +00008514 // fold (uint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008515 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008516 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008517 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008518 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008519 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008520
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008521 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8522 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008523 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8524 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008525 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008526 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008527 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008528 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008529
Alp Tokercb402912014-01-24 17:20:08 +00008530 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008531 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008532 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008533
Nadav Rotem90560762012-07-23 07:59:50 +00008534 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8535 (!LegalOperations ||
8536 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008537 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008538 SDValue Ops[] =
8539 { N0.getOperand(0), N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008540 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008541 N0.getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008542 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008543 }
8544 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008546 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008547}
8548
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008549// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8550static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8551 SDValue N0 = N->getOperand(0);
8552 EVT VT = N->getValueType(0);
8553
8554 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8555 return SDValue();
8556
8557 SDValue Src = N0.getOperand(0);
8558 EVT SrcVT = Src.getValueType();
8559 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8560 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8561
8562 // We can safely assume the conversion won't overflow the output range,
8563 // because (for example) (uint8_t)18293.f is undefined behavior.
8564
8565 // Since we can assume the conversion won't overflow, our decision as to
8566 // whether the input will fit in the float should depend on the minimum
8567 // of the input range and output range.
8568
8569 // This means this is also safe for a signed input and unsigned output, since
8570 // a negative input would lead to undefined behavior.
8571 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8572 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8573 unsigned ActualSize = std::min(InputSize, OutputSize);
8574 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8575
8576 // We can only fold away the float conversion if the input range can be
8577 // represented exactly in the float range.
8578 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8579 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8580 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8581 : ISD::ZERO_EXTEND;
8582 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8583 }
8584 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8585 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8586 if (SrcVT == VT)
8587 return Src;
8588 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8589 }
8590 return SDValue();
8591}
8592
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008593SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8594 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008595 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008596
Nate Begeman21158fc2005-09-01 00:19:25 +00008597 // fold (fp_to_sint c1fp) -> c1
Simon Pilgrim017ca192015-05-02 13:04:07 +00008598 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008599 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008600
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008601 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008602}
8603
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008604SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8605 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008606 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008607
Nate Begeman21158fc2005-09-01 00:19:25 +00008608 // fold (fp_to_uint c1fp) -> c1
Simon Pilgrim017ca192015-05-02 13:04:07 +00008609 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008610 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008611
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008612 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008613}
8614
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008615SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8616 SDValue N0 = N->getOperand(0);
8617 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008618 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008619 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008620
Nate Begeman21158fc2005-09-01 00:19:25 +00008621 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008622 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008623 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008624
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008625 // fold (fp_round (fp_extend x)) -> x
8626 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8627 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008628
Chris Lattner0feb1b02008-01-24 06:45:35 +00008629 // fold (fp_round (fp_round x)) -> (fp_round x)
8630 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008631 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8632 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8633 // If the first fp_round isn't a value preserving truncation, it might
8634 // introduce a tie in the second fp_round, that wouldn't occur in the
8635 // single-step fp_round we want to fold to.
8636 // In other words, double rounding isn't the same as rounding.
8637 // Also, this is a value preserving truncation iff both fp_round's are.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008638 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8639 SDLoc DL(N);
8640 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8641 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8642 }
Chris Lattner0feb1b02008-01-24 06:45:35 +00008643 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008644
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008645 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008646 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008647 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008648 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008649 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008650 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008651 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008652 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008654 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008655}
8656
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008657SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8658 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008659 EVT VT = N->getValueType(0);
8660 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008661 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008662
Nate Begeman21158fc2005-09-01 00:19:25 +00008663 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008664 if (N0CFP && isTypeLegal(EVT)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008665 SDLoc DL(N);
8666 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8667 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008668 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008669
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008670 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008671}
8672
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008673SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8674 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008675 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008676
Chris Lattner5919b482007-12-29 06:55:23 +00008677 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008678 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008679 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008680 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008681
Nate Begeman21158fc2005-09-01 00:19:25 +00008682 // fold (fp_extend c1fp) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008683 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008684 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008685
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00008686 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8687 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8688 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8689 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8690
Chris Lattner72733e52008-01-17 07:00:52 +00008691 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8692 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008693 if (N0.getOpcode() == ISD::FP_ROUND
8694 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008695 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008696 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008697 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008698 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008699 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008700 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008701 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008702
Chris Lattner72733e52008-01-17 07:00:52 +00008703 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008704 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008705 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008706 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008707 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008708 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008709 LN0->getBasePtr(), N0.getValueType(),
8710 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008711 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008712 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008713 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008714 N0.getValueType(), ExtLoad,
8715 DAG.getIntPtrConstant(1, SDLoc(N0))),
Chris Lattner3d265772006-05-05 21:34:35 +00008716 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008717 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008718 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008719
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008720 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008721}
8722
Sanjay Patelccd26762014-08-28 21:51:37 +00008723SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8724 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008725 EVT VT = N->getValueType(0);
8726
8727 // fold (fceil c1) -> fceil(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008728 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008729 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8730
8731 return SDValue();
8732}
8733
8734SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8735 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008736 EVT VT = N->getValueType(0);
8737
8738 // fold (ftrunc c1) -> ftrunc(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008739 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008740 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8741
8742 return SDValue();
8743}
8744
8745SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8746 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008747 EVT VT = N->getValueType(0);
8748
8749 // fold (ffloor c1) -> ffloor(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008750 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008751 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8752
8753 return SDValue();
8754}
8755
8756// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008757SDValue DAGCombiner::visitFNEG(SDNode *N) {
8758 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008759 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008760
Sanjay Patelccd26762014-08-28 21:51:37 +00008761 // Constant fold FNEG.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008762 if (isConstantFPBuildVectorOrConstantFP(N0))
8763 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008764
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008765 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8766 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008767 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008768
Sanjay Patel35d31332014-08-14 15:15:28 +00008769 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008770 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008771 if (!TLI.isFNegFree(VT) &&
8772 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008773 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008774 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008775 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008776 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008777 APInt SignMask;
8778 if (N0.getValueType().isVector()) {
8779 // For a vector, get a mask such as 0x80... per scalar element
8780 // and splat it.
8781 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8782 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8783 } else {
8784 // For a scalar, just generate 0x80...
8785 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8786 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008787 SDLoc DL0(N0);
8788 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8789 DAG.getConstant(SignMask, DL0, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008790 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008791 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008792 }
8793 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008794
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008795 // (fneg (fmul c, x)) -> (fmul -c, x)
Fiona Glaser666e3522015-06-05 17:52:34 +00008796 if (N0.getOpcode() == ISD::FMUL &&
8797 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008798 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008799 if (CFP1) {
8800 APFloat CVal = CFP1->getValueAPF();
8801 CVal.changeSign();
8802 if (Level >= AfterLegalizeDAG &&
8803 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8804 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8805 return DAG.getNode(
8806 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8807 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8808 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008809 }
8810
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008811 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008812}
8813
Matt Arsenault7c936902014-10-21 23:01:01 +00008814SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8815 SDValue N0 = N->getOperand(0);
8816 SDValue N1 = N->getOperand(1);
8817 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8818 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8819
8820 if (N0CFP && N1CFP) {
8821 const APFloat &C0 = N0CFP->getValueAPF();
8822 const APFloat &C1 = N1CFP->getValueAPF();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008823 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
Matt Arsenault7c936902014-10-21 23:01:01 +00008824 }
8825
8826 if (N0CFP) {
8827 EVT VT = N->getValueType(0);
8828 // Canonicalize to constant on RHS.
8829 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8830 }
8831
8832 return SDValue();
8833}
8834
8835SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8836 SDValue N0 = N->getOperand(0);
8837 SDValue N1 = N->getOperand(1);
8838 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8839 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8840
8841 if (N0CFP && N1CFP) {
8842 const APFloat &C0 = N0CFP->getValueAPF();
8843 const APFloat &C1 = N1CFP->getValueAPF();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008844 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
Matt Arsenault7c936902014-10-21 23:01:01 +00008845 }
8846
8847 if (N0CFP) {
8848 EVT VT = N->getValueType(0);
8849 // Canonicalize to constant on RHS.
8850 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8851 }
8852
8853 return SDValue();
8854}
8855
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008856SDValue DAGCombiner::visitFABS(SDNode *N) {
8857 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008858 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008859
Nate Begeman21158fc2005-09-01 00:19:25 +00008860 // fold (fabs c1) -> fabs(c1)
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008861 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008862 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008863
Nate Begeman21158fc2005-09-01 00:19:25 +00008864 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008865 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008866 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008867
Nate Begeman21158fc2005-09-01 00:19:25 +00008868 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008869 // fold (fabs (fcopysign x, y)) -> (fabs x)
8870 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008871 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008872
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008873 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008874 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008875 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008876 N0.getOpcode() == ISD::BITCAST &&
8877 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008878 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008879 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008880 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008881 APInt SignMask;
8882 if (N0.getValueType().isVector()) {
8883 // For a vector, get a mask such as 0x7f... per scalar element
8884 // and splat it.
8885 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8886 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8887 } else {
8888 // For a scalar, just generate 0x7f...
8889 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8890 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008891 SDLoc DL(N0);
8892 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8893 DAG.getConstant(SignMask, DL, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008894 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008895 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008896 }
8897 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008898
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008899 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008900}
8901
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008902SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8903 SDValue Chain = N->getOperand(0);
8904 SDValue N1 = N->getOperand(1);
8905 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008906
Dan Gohman82e80012009-11-17 00:47:23 +00008907 // If N is a constant we could fold this into a fallthrough or unconditional
8908 // branch. However that doesn't happen very often in normal code, because
8909 // Instcombine/SimplifyCFG should have handled the available opportunities.
8910 // If we did this folding here, it would be necessary to update the
8911 // MachineBasicBlock CFG, which is awkward.
8912
Nate Begeman7e7f4392006-02-01 07:19:44 +00008913 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8914 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008915 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008916 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8917 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008918 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008919 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008920 N1.getOperand(0), N1.getOperand(1), N2);
8921 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008922
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008923 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8924 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8925 (N1.getOperand(0).hasOneUse() &&
8926 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008927 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008928 if (N1.getOpcode() == ISD::TRUNCATE) {
8929 // Look pass the truncate.
8930 Trunc = N1.getNode();
8931 N1 = N1.getOperand(0);
8932 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008933
Bill Wendlingaa28be62009-03-26 06:14:09 +00008934 // Match this pattern so that we can generate simpler code:
8935 //
8936 // %a = ...
8937 // %b = and i32 %a, 2
8938 // %c = srl i32 %b, 1
8939 // brcond i32 %c ...
8940 //
8941 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008942 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008943 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008944 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008945 // %c = setcc eq %b, 0
8946 // brcond %c ...
8947 //
8948 // This applies only when the AND constant value has one bit set and the
8949 // SRL constant is equal to the log2 of the AND constant. The back-end is
8950 // smart enough to convert the result into a TEST/JMP sequence.
8951 SDValue Op0 = N1.getOperand(0);
8952 SDValue Op1 = N1.getOperand(1);
8953
8954 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008955 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008956 SDValue AndOp1 = Op0.getOperand(1);
8957
8958 if (AndOp1.getOpcode() == ISD::Constant) {
8959 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8960
8961 if (AndConst.isPowerOf2() &&
8962 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008963 SDLoc DL(N);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008964 SDValue SetCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008965 DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +00008966 getSetCCResultType(Op0.getValueType()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008967 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008968 ISD::SETNE);
8969
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008970 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
Evan Cheng166a4e62010-01-06 19:38:29 +00008971 MVT::Other, Chain, SetCC, N2);
8972 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8973 // will convert it back to (X & C1) >> C2.
8974 CombineTo(N, NewBRCond, false);
8975 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008976 if (Trunc)
8977 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008978 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008979 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008980 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008981 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008982 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008983 }
8984 }
8985 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008986
8987 if (Trunc)
8988 // Restore N1 if the above transformation doesn't match.
8989 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008990 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008991
Evan Cheng228c31f2010-02-27 07:36:59 +00008992 // Transform br(xor(x, y)) -> br(x != y)
8993 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8994 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8995 SDNode *TheXor = N1.getNode();
8996 SDValue Op0 = TheXor->getOperand(0);
8997 SDValue Op1 = TheXor->getOperand(1);
8998 if (Op0.getOpcode() == Op1.getOpcode()) {
8999 // Avoid missing important xor optimizations.
9000 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00009001 if (Tmp.getNode()) {
9002 if (Tmp.getNode() != TheXor) {
9003 DEBUG(dbgs() << "\nReplacing.8 ";
9004 TheXor->dump(&DAG);
9005 dbgs() << "\nWith: ";
9006 Tmp.getNode()->dump(&DAG);
9007 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009008 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00009009 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00009010 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009011 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00009012 MVT::Other, Chain, Tmp, N2);
9013 }
9014
Benjamin Kramer93354432013-03-30 21:28:18 +00009015 // visitXOR has changed XOR's operands or replaced the XOR completely,
9016 // bail out.
9017 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00009018 }
9019 }
9020
9021 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9022 bool Equal = false;
Matthias Braun887fdfb2015-05-19 00:25:21 +00009023 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9024 Op0.getOpcode() == ISD::XOR) {
9025 TheXor = Op0.getNode();
9026 Equal = true;
9027 }
Evan Cheng228c31f2010-02-27 07:36:59 +00009028
Evan Chengc8d6cfd2010-10-04 22:41:01 +00009029 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00009030 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00009031 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009032 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00009033 SetCCVT,
9034 Op0, Op1,
9035 Equal ? ISD::SETEQ : ISD::SETNE);
9036 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009037 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009038 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00009039 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009040 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00009041 MVT::Other, Chain, SetCC, N2);
9042 }
9043 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00009044
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009045 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00009046}
9047
Chris Lattnera49e16f2005-10-05 06:47:48 +00009048// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9049//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009050SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00009051 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009052 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009053
Dan Gohman82e80012009-11-17 00:47:23 +00009054 // If N is a constant we could fold this into a fallthrough or unconditional
9055 // branch. However that doesn't happen very often in normal code, because
9056 // Instcombine/SimplifyCFG should have handled the available opportunities.
9057 // If we did this folding here, it would be necessary to update the
9058 // MachineBasicBlock CFG, which is awkward.
9059
Duncan Sands93b66092008-06-09 11:32:28 +00009060 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00009061 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00009062 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00009063 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009064 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00009065
Nate Begemanbd7df032005-10-05 21:43:42 +00009066 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00009067 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009068 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00009069 N->getOperand(0), Simp.getOperand(2),
9070 Simp.getOperand(0), Simp.getOperand(1),
9071 N->getOperand(4));
9072
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009073 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00009074}
9075
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009076/// Return true if 'Use' is a load or a store that uses N as its base pointer
9077/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00009078static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9079 SelectionDAG &DAG,
9080 const TargetLowering &TLI) {
9081 EVT VT;
Matt Arsenaultca519dc2015-06-04 16:17:34 +00009082 unsigned AS;
9083
Evan Chengfa832632012-01-13 01:37:24 +00009084 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9085 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9086 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00009087 VT = LD->getMemoryVT();
Matt Arsenaultca519dc2015-06-04 16:17:34 +00009088 AS = LD->getAddressSpace();
Evan Chengfa832632012-01-13 01:37:24 +00009089 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9090 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9091 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00009092 VT = ST->getMemoryVT();
Matt Arsenaultca519dc2015-06-04 16:17:34 +00009093 AS = ST->getAddressSpace();
Evan Chengfa832632012-01-13 01:37:24 +00009094 } else
9095 return false;
9096
Chandler Carruth95f83e02013-01-07 15:14:13 +00009097 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00009098 if (N->getOpcode() == ISD::ADD) {
9099 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9100 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00009101 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00009102 AM.BaseOffs = Offset->getSExtValue();
9103 else
Evan Cheng80893ce2012-03-06 23:33:32 +00009104 // [reg +/- reg]
9105 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00009106 } else if (N->getOpcode() == ISD::SUB) {
9107 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9108 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00009109 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00009110 AM.BaseOffs = -Offset->getSExtValue();
9111 else
Evan Cheng80893ce2012-03-06 23:33:32 +00009112 // [reg +/- reg]
9113 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00009114 } else
9115 return false;
9116
Matt Arsenaultca519dc2015-06-04 16:17:34 +00009117 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
Evan Chengfa832632012-01-13 01:37:24 +00009118}
9119
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009120/// Try turning a load/store into a pre-indexed load/store when the base
9121/// pointer is an add or subtract and it has other uses besides the load/store.
9122/// After the transformation, the new indexed load/store has effectively folded
9123/// the add/subtract in and all of its other uses are redirected to the
9124/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009125bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009126 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009127 return false;
9128
9129 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009130 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009131 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009132 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009133 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009134 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009135 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00009136 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00009137 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9138 return false;
9139 Ptr = LD->getBasePtr();
9140 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009141 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009142 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009143 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009144 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9145 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9146 return false;
9147 Ptr = ST->getBasePtr();
9148 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009149 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009150 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009151 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009152
Chris Lattnereabc15c2006-11-11 00:56:29 +00009153 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9154 // out. There is no reason to make this a preinc/predec.
9155 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00009156 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009157 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00009158
Chris Lattnereabc15c2006-11-11 00:56:29 +00009159 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009160 SDValue BasePtr;
9161 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009162 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9163 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9164 return false;
Hal Finkel25819052013-02-08 21:35:47 +00009165
9166 // Backends without true r+i pre-indexed forms may need to pass a
9167 // constant base with a variable offset so that constant coercion
9168 // will work with the patterns in canonical form.
9169 bool Swapped = false;
9170 if (isa<ConstantSDNode>(BasePtr)) {
9171 std::swap(BasePtr, Offset);
9172 Swapped = true;
9173 }
9174
Evan Cheng044a0a82007-05-03 23:52:19 +00009175 // Don't create a indexed load / store with zero offset.
Matthias Braun1505efb2015-05-18 23:07:27 +00009176 if (isNullConstant(Offset))
Evan Cheng044a0a82007-05-03 23:52:19 +00009177 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009178
Chris Lattnera0a80032006-11-11 01:00:15 +00009179 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00009180 // 1) The new base ptr is a frame index.
9181 // 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 +00009182 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00009183 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00009184 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00009185 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00009186
Chris Lattnera0a80032006-11-11 01:00:15 +00009187 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9188 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00009189 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00009190 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009191
Chris Lattnera0a80032006-11-11 01:00:15 +00009192 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00009193 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009194 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00009195 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009196 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00009197 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009198
Hal Finkel25819052013-02-08 21:35:47 +00009199 // If the offset is a constant, there may be other adds of constants that
9200 // can be folded with this one. We should do this to avoid having to keep
9201 // a copy of the original base pointer.
9202 SmallVector<SDNode *, 16> OtherUses;
9203 if (isa<ConstantSDNode>(Offset))
Hal Finkela60e6332015-05-18 15:46:02 +00009204 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9205 UE = BasePtr.getNode()->use_end();
9206 UI != UE; ++UI) {
9207 SDUse &Use = UI.getUse();
9208 // Skip the use that is Ptr and uses of other results from BasePtr's
9209 // node (important for nodes that return multiple results).
9210 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
Hal Finkel25819052013-02-08 21:35:47 +00009211 continue;
9212
Hal Finkela60e6332015-05-18 15:46:02 +00009213 if (Use.getUser()->isPredecessorOf(N))
Hal Finkel25819052013-02-08 21:35:47 +00009214 continue;
9215
Hal Finkela60e6332015-05-18 15:46:02 +00009216 if (Use.getUser()->getOpcode() != ISD::ADD &&
9217 Use.getUser()->getOpcode() != ISD::SUB) {
Hal Finkel25819052013-02-08 21:35:47 +00009218 OtherUses.clear();
9219 break;
9220 }
9221
Hal Finkela60e6332015-05-18 15:46:02 +00009222 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
Hal Finkel25819052013-02-08 21:35:47 +00009223 if (!isa<ConstantSDNode>(Op1)) {
9224 OtherUses.clear();
9225 break;
9226 }
9227
9228 // FIXME: In some cases, we can be smarter about this.
9229 if (Op1.getValueType() != Offset.getValueType()) {
9230 OtherUses.clear();
9231 break;
9232 }
9233
Hal Finkela60e6332015-05-18 15:46:02 +00009234 OtherUses.push_back(Use.getUser());
Hal Finkel25819052013-02-08 21:35:47 +00009235 }
9236
9237 if (Swapped)
9238 std::swap(BasePtr, Offset);
9239
Evan Chenga4d187b2007-05-24 02:35:39 +00009240 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00009241 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00009242
9243 // Caches for hasPredecessorHelper
9244 SmallPtrSet<const SDNode *, 32> Visited;
9245 SmallVector<const SDNode *, 16> Worklist;
9246
Jim Grosbache8160032014-04-11 01:13:13 +00009247 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009248 if (Use == N)
9249 continue;
Lang Hames5a004992011-07-07 04:31:51 +00009250 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009251 return false;
9252
Evan Chengfa832632012-01-13 01:37:24 +00009253 // If Ptr may be folded in addressing mode of other use, then it's
9254 // not profitable to do this transformation.
9255 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009256 RealUse = true;
9257 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009258
Chris Lattnereabc15c2006-11-11 00:56:29 +00009259 if (!RealUse)
9260 return false;
9261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009262 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009263 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009264 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009265 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009266 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009267 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009268 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009269 ++PreIndexedNodes;
9270 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009271 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009272 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009273 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009274 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009275 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009276 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009277 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009278 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9279 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009280 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009281 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009282 }
9283
Chris Lattnereabc15c2006-11-11 00:56:29 +00009284 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009285 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009286
Hal Finkel25819052013-02-08 21:35:47 +00009287 if (Swapped)
9288 std::swap(BasePtr, Offset);
9289
9290 // Replace other uses of BasePtr that can be updated to use Ptr
9291 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9292 unsigned OffsetIdx = 1;
9293 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9294 OffsetIdx = 0;
9295 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9296 BasePtr.getNode() && "Expected BasePtr operand");
9297
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009298 // We need to replace ptr0 in the following expression:
9299 // x0 * offset0 + y0 * ptr0 = t0
9300 // knowing that
9301 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00009302 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009303 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9304 // indexed load/store and the expresion that needs to be re-written.
9305 //
9306 // Therefore, we have:
9307 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00009308
9309 ConstantSDNode *CN =
9310 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009311 int X0, X1, Y0, Y1;
9312 APInt Offset0 = CN->getAPIntValue();
9313 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00009314
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009315 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9316 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9317 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9318 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00009319
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009320 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9321
9322 APInt CNV = Offset0;
9323 if (X0 < 0) CNV = -CNV;
9324 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9325 else CNV = CNV - Offset1;
9326
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009327 SDLoc DL(OtherUses[i]);
9328
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009329 // We can now generate the new expression.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009330 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009331 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9332
9333 SDValue NewUse = DAG.getNode(Opcode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009334 DL,
Hal Finkel25819052013-02-08 21:35:47 +00009335 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9336 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00009337 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00009338 }
9339
Chris Lattnereabc15c2006-11-11 00:56:29 +00009340 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009341 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009342 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00009343
9344 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009345}
9346
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009347/// Try to combine a load/store with a add/sub of the base pointer node into a
9348/// post-indexed load/store. The transformation folded the add/subtract into the
9349/// new indexed load/store effectively and all of its uses are redirected to the
9350/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009351bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009352 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009353 return false;
9354
9355 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009356 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009357 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009358 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009359 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009360 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009361 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009362 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9363 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9364 return false;
9365 Ptr = LD->getBasePtr();
9366 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009367 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009368 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009369 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009370 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9371 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9372 return false;
9373 Ptr = ST->getBasePtr();
9374 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009375 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009376 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009377 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009378
Gabor Greiff304a7a2008-08-28 21:40:38 +00009379 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009380 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009381
Jim Grosbache8160032014-04-11 01:13:13 +00009382 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009383 if (Op == N ||
9384 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9385 continue;
9386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009387 SDValue BasePtr;
9388 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009389 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9390 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00009391 // Don't create a indexed load / store with zero offset.
Matthias Braun1505efb2015-05-18 23:07:27 +00009392 if (isNullConstant(Offset))
Evan Cheng044a0a82007-05-03 23:52:19 +00009393 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009394
Chris Lattnereabc15c2006-11-11 00:56:29 +00009395 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00009396 // 1) All uses are load / store ops that use it as base ptr (and
9397 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00009398 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9399 // nor a successor of N. Otherwise, if Op is folded that would
9400 // create a cycle.
9401
Evan Chengcfc05132009-05-06 18:25:01 +00009402 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9403 continue;
9404
Chris Lattnereabc15c2006-11-11 00:56:29 +00009405 // Check for #1.
9406 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009407 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009408 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00009409 continue;
9410
Chris Lattnereabc15c2006-11-11 00:56:29 +00009411 // If all the uses are load / store addresses, then don't do the
9412 // transformation.
9413 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9414 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009415 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00009416 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009417 RealUse = true;
9418 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009419
Chris Lattnereabc15c2006-11-11 00:56:29 +00009420 if (!RealUse) {
9421 TryNext = true;
9422 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00009423 }
9424 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009425 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009426
Chris Lattnereabc15c2006-11-11 00:56:29 +00009427 if (TryNext)
9428 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009429
Chris Lattnereabc15c2006-11-11 00:56:29 +00009430 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00009431 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009432 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00009433 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009434 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009435 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009436 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009437 ++PostIndexedNodes;
9438 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009439 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009440 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009441 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009442 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009443 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009444 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009445 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009448 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00009450 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009451
Chris Lattnereabc15c2006-11-11 00:56:29 +00009452 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009453 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009454
9455 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009456 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009457 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009458 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009459 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009460 }
9461 }
9462 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009463
Chris Lattnerffad2162006-11-11 00:39:41 +00009464 return false;
9465}
9466
Hal Finkel51e6fa22014-09-02 06:24:04 +00009467/// \brief Return the base-pointer arithmetic from an indexed \p LD.
9468SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9469 ISD::MemIndexedMode AM = LD->getAddressingMode();
9470 assert(AM != ISD::UNINDEXED);
9471 SDValue BP = LD->getOperand(1);
9472 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00009473
9474 // Some backends use TargetConstants for load offsets, but don't expect
9475 // TargetConstants in general ADD nodes. We can convert these constants into
9476 // regular Constants (if the constant is not opaque).
9477 assert((Inc.getOpcode() != ISD::TargetConstant ||
9478 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9479 "Cannot split out indexing using opaque target constants");
9480 if (Inc.getOpcode() == ISD::TargetConstant) {
9481 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009482 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
Hal Finkele19006e2014-09-02 16:05:23 +00009483 ConstInc->getValueType(0));
9484 }
9485
Hal Finkel51e6fa22014-09-02 06:24:04 +00009486 unsigned Opc =
9487 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9488 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9489}
9490
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009491SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00009492 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009493 SDValue Chain = LD->getChain();
9494 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009495
Evan Chenga684cd22007-05-01 00:38:21 +00009496 // If load is not volatile and there are no uses of the loaded value (and
9497 // the updated indexed value in case of indexed loads), change uses of the
9498 // chain value into uses of the chain input (i.e. delete the dead load).
9499 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00009500 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00009501 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00009502 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00009503 // It's not safe to use the two value CombineTo variant here. e.g.
9504 // v1, chain2 = load chain1, loc
9505 // v2, chain3 = load chain2, loc
9506 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00009507 // Now we replace use of chain2 with chain1. This makes the second load
9508 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00009509 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009510 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009511 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009512 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009513 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009514 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009515 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00009516
Chandler Carruth18066972014-08-02 10:02:07 +00009517 if (N->use_empty())
9518 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00009519
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009520 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00009521 }
Evan Chengb68343c2007-05-01 08:53:39 +00009522 } else {
9523 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00009524 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00009525
Hal Finkele19006e2014-09-02 16:05:23 +00009526 // If this load has an opaque TargetConstant offset, then we cannot split
9527 // the indexing into an add/sub directly (that TargetConstant may not be
9528 // valid for a different type of node, and we cannot convert an opaque
9529 // target constant into a regular constant).
9530 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9531 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00009532
9533 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009534 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009535 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009536 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009537 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009538 Index = SplitIndexingFromLoad(LD);
9539 // Try to fold the base pointer arithmetic into subsequent loads and
9540 // stores.
9541 AddUsersToWorklist(N);
9542 } else
9543 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009544 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009545 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009546 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009547 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009548 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009549 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009550 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009551 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009552 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009553 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009554 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009555 }
Evan Chenga684cd22007-05-01 00:38:21 +00009556 }
9557 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009558
Chris Lattnere260ed82005-10-10 22:04:48 +00009559 // If this load is directly stored, replace the load value with the stored
9560 // value.
9561 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009562 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009563 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009564 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009565 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9566 if (PrevST->getBasePtr() == Ptr &&
9567 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009568 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009569 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009570 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009571
Evan Cheng43cd9e32010-04-01 06:04:33 +00009572 // Try to infer better alignment information than the load already has.
9573 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009574 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009575 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9576 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009577 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009578 LD->getValueType(0),
9579 Chain, Ptr, LD->getPointerInfo(),
9580 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009581 LD->isVolatile(), LD->isNonTemporal(),
9582 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +00009583 if (NewLoad.getNode() != N)
9584 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
Owen Andersonde89ecf2013-02-05 19:24:39 +00009585 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009586 }
9587 }
9588
Eric Christopherf55d4712014-10-08 23:38:39 +00009589 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9590 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009591#ifndef NDEBUG
9592 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9593 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9594 UseAA = false;
9595#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009596 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009597 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009598 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009599
Jim Laskey708d0db2006-10-04 16:53:27 +00009600 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009601 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009602 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009603
Jim Laskeyd07be232006-09-25 16:29:54 +00009604 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009605 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009606 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009607 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009608 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009609 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009610 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009611 BetterChain, Ptr, LD->getMemoryVT(),
9612 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009613 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009614
Jim Laskey708d0db2006-10-04 16:53:27 +00009615 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009616 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009617 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009618
Nate Begeman879d8f12009-09-15 00:18:30 +00009619 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009620 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009621
Jim Laskeydcf983c2006-10-13 23:32:28 +00009622 // Replace uses with load result and token factor. Don't add users
9623 // to work list.
9624 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009625 }
9626 }
9627
Evan Cheng357017f2006-11-03 03:06:21 +00009628 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009629 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009630 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009631
Quentin Colombetde0e0622013-10-11 18:29:42 +00009632 // Try to slice up N to more direct loads if the slices are mapped to
9633 // different register banks or pairing can take place.
9634 if (SliceUpLoad(N))
9635 return SDValue(N, 0);
9636
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009637 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009638}
9639
Quentin Colombetde0e0622013-10-11 18:29:42 +00009640namespace {
9641/// \brief Helper structure used to slice a load in smaller loads.
9642/// Basically a slice is obtained from the following sequence:
9643/// Origin = load Ty1, Base
9644/// Shift = srl Ty1 Origin, CstTy Amount
9645/// Inst = trunc Shift to Ty2
9646///
9647/// Then, it will be rewriten into:
9648/// Slice = load SliceTy, Base + SliceOffset
9649/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9650///
9651/// SliceTy is deduced from the number of bits that are actually used to
9652/// build Inst.
9653struct LoadedSlice {
9654 /// \brief Helper structure used to compute the cost of a slice.
9655 struct Cost {
9656 /// Are we optimizing for code size.
9657 bool ForCodeSize;
9658 /// Various cost.
9659 unsigned Loads;
9660 unsigned Truncates;
9661 unsigned CrossRegisterBanksCopies;
9662 unsigned ZExts;
9663 unsigned Shift;
9664
9665 Cost(bool ForCodeSize = false)
9666 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9667 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9668
9669 /// \brief Get the cost of one isolated slice.
9670 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9671 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9672 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9673 EVT TruncType = LS.Inst->getValueType(0);
9674 EVT LoadedType = LS.getLoadedType();
9675 if (TruncType != LoadedType &&
9676 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9677 ZExts = 1;
9678 }
9679
9680 /// \brief Account for slicing gain in the current cost.
9681 /// Slicing provide a few gains like removing a shift or a
9682 /// truncate. This method allows to grow the cost of the original
9683 /// load with the gain from this slice.
9684 void addSliceGain(const LoadedSlice &LS) {
9685 // Each slice saves a truncate.
9686 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9687 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9688 LS.Inst->getOperand(0).getValueType()))
9689 ++Truncates;
9690 // If there is a shift amount, this slice gets rid of it.
9691 if (LS.Shift)
9692 ++Shift;
9693 // If this slice can merge a cross register bank copy, account for it.
9694 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9695 ++CrossRegisterBanksCopies;
9696 }
9697
9698 Cost &operator+=(const Cost &RHS) {
9699 Loads += RHS.Loads;
9700 Truncates += RHS.Truncates;
9701 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9702 ZExts += RHS.ZExts;
9703 Shift += RHS.Shift;
9704 return *this;
9705 }
9706
9707 bool operator==(const Cost &RHS) const {
9708 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9709 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9710 ZExts == RHS.ZExts && Shift == RHS.Shift;
9711 }
9712
9713 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9714
9715 bool operator<(const Cost &RHS) const {
9716 // Assume cross register banks copies are as expensive as loads.
9717 // FIXME: Do we want some more target hooks?
9718 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9719 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9720 // Unless we are optimizing for code size, consider the
9721 // expensive operation first.
9722 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9723 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9724 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9725 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9726 }
9727
9728 bool operator>(const Cost &RHS) const { return RHS < *this; }
9729
9730 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9731
9732 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9733 };
9734 // The last instruction that represent the slice. This should be a
9735 // truncate instruction.
9736 SDNode *Inst;
9737 // The original load instruction.
9738 LoadSDNode *Origin;
9739 // The right shift amount in bits from the original load.
9740 unsigned Shift;
9741 // The DAG from which Origin came from.
9742 // This is used to get some contextual information about legal types, etc.
9743 SelectionDAG *DAG;
9744
Craig Topperc0196b12014-04-14 00:51:57 +00009745 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9746 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009747 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9748
Quentin Colombetde0e0622013-10-11 18:29:42 +00009749 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9750 /// \return Result is \p BitWidth and has used bits set to 1 and
9751 /// not used bits set to 0.
9752 APInt getUsedBits() const {
9753 // Reproduce the trunc(lshr) sequence:
9754 // - Start from the truncated value.
9755 // - Zero extend to the desired bit width.
9756 // - Shift left.
9757 assert(Origin && "No original load to compare against.");
9758 unsigned BitWidth = Origin->getValueSizeInBits(0);
9759 assert(Inst && "This slice is not bound to an instruction");
9760 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9761 "Extracted slice is bigger than the whole type!");
9762 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9763 UsedBits.setAllBits();
9764 UsedBits = UsedBits.zext(BitWidth);
9765 UsedBits <<= Shift;
9766 return UsedBits;
9767 }
9768
9769 /// \brief Get the size of the slice to be loaded in bytes.
9770 unsigned getLoadedSize() const {
9771 unsigned SliceSize = getUsedBits().countPopulation();
9772 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9773 return SliceSize / 8;
9774 }
9775
9776 /// \brief Get the type that will be loaded for this slice.
9777 /// Note: This may not be the final type for the slice.
9778 EVT getLoadedType() const {
9779 assert(DAG && "Missing context");
9780 LLVMContext &Ctxt = *DAG->getContext();
9781 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9782 }
9783
9784 /// \brief Get the alignment of the load used for this slice.
9785 unsigned getAlignment() const {
9786 unsigned Alignment = Origin->getAlignment();
9787 unsigned Offset = getOffsetFromBase();
9788 if (Offset != 0)
9789 Alignment = MinAlign(Alignment, Alignment + Offset);
9790 return Alignment;
9791 }
9792
9793 /// \brief Check if this slice can be rewritten with legal operations.
9794 bool isLegal() const {
9795 // An invalid slice is not legal.
9796 if (!Origin || !Inst || !DAG)
9797 return false;
9798
9799 // Offsets are for indexed load only, we do not handle that.
9800 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9801 return false;
9802
9803 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9804
9805 // Check that the type is legal.
9806 EVT SliceType = getLoadedType();
9807 if (!TLI.isTypeLegal(SliceType))
9808 return false;
9809
9810 // Check that the load is legal for this type.
9811 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9812 return false;
9813
9814 // Check that the offset can be computed.
9815 // 1. Check its type.
9816 EVT PtrType = Origin->getBasePtr().getValueType();
9817 if (PtrType == MVT::Untyped || PtrType.isExtended())
9818 return false;
9819
9820 // 2. Check that it fits in the immediate.
9821 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9822 return false;
9823
9824 // 3. Check that the computation is legal.
9825 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9826 return false;
9827
9828 // Check that the zext is legal if it needs one.
9829 EVT TruncateType = Inst->getValueType(0);
9830 if (TruncateType != SliceType &&
9831 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9832 return false;
9833
9834 return true;
9835 }
9836
9837 /// \brief Get the offset in bytes of this slice in the original chunk of
9838 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009839 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009840 uint64_t getOffsetFromBase() const {
9841 assert(DAG && "Missing context.");
9842 bool IsBigEndian =
9843 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9844 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9845 uint64_t Offset = Shift / 8;
9846 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9847 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9848 "The size of the original loaded type is not a multiple of a"
9849 " byte.");
9850 // If Offset is bigger than TySizeInBytes, it means we are loading all
9851 // zeros. This should have been optimized before in the process.
9852 assert(TySizeInBytes > Offset &&
9853 "Invalid shift amount for given loaded size");
9854 if (IsBigEndian)
9855 Offset = TySizeInBytes - Offset - getLoadedSize();
9856 return Offset;
9857 }
9858
9859 /// \brief Generate the sequence of instructions to load the slice
9860 /// represented by this object and redirect the uses of this slice to
9861 /// this new sequence of instructions.
9862 /// \pre this->Inst && this->Origin are valid Instructions and this
9863 /// object passed the legal check: LoadedSlice::isLegal returned true.
9864 /// \return The last instruction of the sequence used to load the slice.
9865 SDValue loadSlice() const {
9866 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9867 const SDValue &OldBaseAddr = Origin->getBasePtr();
9868 SDValue BaseAddr = OldBaseAddr;
9869 // Get the offset in that chunk of bytes w.r.t. the endianess.
9870 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9871 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9872 if (Offset) {
9873 // BaseAddr = BaseAddr + Offset.
9874 EVT ArithType = BaseAddr.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009875 SDLoc DL(Origin);
9876 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9877 DAG->getConstant(Offset, DL, ArithType));
Quentin Colombetde0e0622013-10-11 18:29:42 +00009878 }
9879
9880 // Create the type of the loaded slice according to its size.
9881 EVT SliceType = getLoadedType();
9882
9883 // Create the load for the slice.
9884 SDValue LastInst = DAG->getLoad(
9885 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9886 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9887 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9888 // If the final type is not the same as the loaded type, this means that
9889 // we have to pad with zero. Create a zero extend for that.
9890 EVT FinalType = Inst->getValueType(0);
9891 if (SliceType != FinalType)
9892 LastInst =
9893 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9894 return LastInst;
9895 }
9896
9897 /// \brief Check if this slice can be merged with an expensive cross register
9898 /// bank copy. E.g.,
9899 /// i = load i32
9900 /// f = bitcast i32 i to float
9901 bool canMergeExpensiveCrossRegisterBankCopy() const {
9902 if (!Inst || !Inst->hasOneUse())
9903 return false;
9904 SDNode *Use = *Inst->use_begin();
9905 if (Use->getOpcode() != ISD::BITCAST)
9906 return false;
9907 assert(DAG && "Missing context");
9908 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9909 EVT ResVT = Use->getValueType(0);
9910 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9911 const TargetRegisterClass *ArgRC =
9912 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9913 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9914 return false;
9915
9916 // At this point, we know that we perform a cross-register-bank copy.
9917 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009918 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009919 // Assume bitcasts are cheap, unless both register classes do not
9920 // explicitly share a common sub class.
9921 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9922 return false;
9923
9924 // Check if it will be merged with the load.
9925 // 1. Check the alignment constraint.
9926 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9927 ResVT.getTypeForEVT(*DAG->getContext()));
9928
9929 if (RequiredAlignment > getAlignment())
9930 return false;
9931
9932 // 2. Check that the load is a legal operation for that type.
9933 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9934 return false;
9935
9936 // 3. Check that we do not have a zext in the way.
9937 if (Inst->getValueType(0) != getLoadedType())
9938 return false;
9939
9940 return true;
9941 }
9942};
9943}
9944
Quentin Colombetde0e0622013-10-11 18:29:42 +00009945/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9946/// \p UsedBits looks like 0..0 1..1 0..0.
9947static bool areUsedBitsDense(const APInt &UsedBits) {
9948 // If all the bits are one, this is dense!
9949 if (UsedBits.isAllOnesValue())
9950 return true;
9951
9952 // Get rid of the unused bits on the right.
9953 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9954 // Get rid of the unused bits on the left.
9955 if (NarrowedUsedBits.countLeadingZeros())
9956 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9957 // Check that the chunk of bits is completely used.
9958 return NarrowedUsedBits.isAllOnesValue();
9959}
9960
9961/// \brief Check whether or not \p First and \p Second are next to each other
9962/// in memory. This means that there is no hole between the bits loaded
9963/// by \p First and the bits loaded by \p Second.
9964static bool areSlicesNextToEachOther(const LoadedSlice &First,
9965 const LoadedSlice &Second) {
9966 assert(First.Origin == Second.Origin && First.Origin &&
9967 "Unable to match different memory origins.");
9968 APInt UsedBits = First.getUsedBits();
9969 assert((UsedBits & Second.getUsedBits()) == 0 &&
9970 "Slices are not supposed to overlap.");
9971 UsedBits |= Second.getUsedBits();
9972 return areUsedBitsDense(UsedBits);
9973}
9974
9975/// \brief Adjust the \p GlobalLSCost according to the target
9976/// paring capabilities and the layout of the slices.
9977/// \pre \p GlobalLSCost should account for at least as many loads as
9978/// there is in the slices in \p LoadedSlices.
9979static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9980 LoadedSlice::Cost &GlobalLSCost) {
9981 unsigned NumberOfSlices = LoadedSlices.size();
9982 // If there is less than 2 elements, no pairing is possible.
9983 if (NumberOfSlices < 2)
9984 return;
9985
9986 // Sort the slices so that elements that are likely to be next to each
9987 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009988 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9989 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9990 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9991 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9992 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009993 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9994 // First (resp. Second) is the first (resp. Second) potentially candidate
9995 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009996 const LoadedSlice *First = nullptr;
9997 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009998 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9999 // Set the beginning of the pair.
10000 First = Second) {
10001
10002 Second = &LoadedSlices[CurrSlice];
10003
10004 // If First is NULL, it means we start a new pair.
10005 // Get to the next slice.
10006 if (!First)
10007 continue;
10008
10009 EVT LoadedType = First->getLoadedType();
10010
10011 // If the types of the slices are different, we cannot pair them.
10012 if (LoadedType != Second->getLoadedType())
10013 continue;
10014
10015 // Check if the target supplies paired loads for this type.
10016 unsigned RequiredAlignment = 0;
10017 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10018 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +000010019 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +000010020 continue;
10021 }
10022 // Check if we meet the alignment requirement.
10023 if (RequiredAlignment > First->getAlignment())
10024 continue;
10025
10026 // Check that both loads are next to each other in memory.
10027 if (!areSlicesNextToEachOther(*First, *Second))
10028 continue;
10029
10030 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10031 --GlobalLSCost.Loads;
10032 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +000010033 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +000010034 }
10035}
10036
10037/// \brief Check the profitability of all involved LoadedSlice.
10038/// Currently, it is considered profitable if there is exactly two
10039/// involved slices (1) which are (2) next to each other in memory, and
10040/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10041///
10042/// Note: The order of the elements in \p LoadedSlices may be modified, but not
10043/// the elements themselves.
10044///
10045/// FIXME: When the cost model will be mature enough, we can relax
10046/// constraints (1) and (2).
10047static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10048 const APInt &UsedBits, bool ForCodeSize) {
10049 unsigned NumberOfSlices = LoadedSlices.size();
10050 if (StressLoadSlicing)
10051 return NumberOfSlices > 1;
10052
10053 // Check (1).
10054 if (NumberOfSlices != 2)
10055 return false;
10056
10057 // Check (2).
10058 if (!areUsedBitsDense(UsedBits))
10059 return false;
10060
10061 // Check (3).
10062 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10063 // The original code has one big load.
10064 OrigCost.Loads = 1;
10065 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10066 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10067 // Accumulate the cost of all the slices.
10068 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10069 GlobalSlicingCost += SliceCost;
10070
10071 // Account as cost in the original configuration the gain obtained
10072 // with the current slices.
10073 OrigCost.addSliceGain(LS);
10074 }
10075
10076 // If the target supports paired load, adjust the cost accordingly.
10077 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10078 return OrigCost > GlobalSlicingCost;
10079}
10080
10081/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10082/// operations, split it in the various pieces being extracted.
10083///
10084/// This sort of thing is introduced by SROA.
10085/// This slicing takes care not to insert overlapping loads.
10086/// \pre LI is a simple load (i.e., not an atomic or volatile load).
10087bool DAGCombiner::SliceUpLoad(SDNode *N) {
10088 if (Level < AfterLegalizeDAG)
10089 return false;
10090
10091 LoadSDNode *LD = cast<LoadSDNode>(N);
10092 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10093 !LD->getValueType(0).isInteger())
10094 return false;
10095
10096 // Keep track of already used bits to detect overlapping values.
10097 // In that case, we will just abort the transformation.
10098 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10099
10100 SmallVector<LoadedSlice, 4> LoadedSlices;
10101
10102 // Check if this load is used as several smaller chunks of bits.
10103 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10104 // of computation for each trunc.
10105 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10106 UI != UIEnd; ++UI) {
10107 // Skip the uses of the chain.
10108 if (UI.getUse().getResNo() != 0)
10109 continue;
10110
10111 SDNode *User = *UI;
10112 unsigned Shift = 0;
10113
10114 // Check if this is a trunc(lshr).
10115 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10116 isa<ConstantSDNode>(User->getOperand(1))) {
10117 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10118 User = *User->use_begin();
10119 }
10120
10121 // At this point, User is a Truncate, iff we encountered, trunc or
10122 // trunc(lshr).
10123 if (User->getOpcode() != ISD::TRUNCATE)
10124 return false;
10125
10126 // The width of the type must be a power of 2 and greater than 8-bits.
10127 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +000010128 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +000010129 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +000010130 unsigned Width = User->getValueSizeInBits(0);
10131 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10132 return 0;
10133
10134 // Build the slice for this chain of computations.
10135 LoadedSlice LS(User, LD, Shift, &DAG);
10136 APInt CurrentUsedBits = LS.getUsedBits();
10137
10138 // Check if this slice overlaps with another.
10139 if ((CurrentUsedBits & UsedBits) != 0)
10140 return false;
10141 // Update the bits used globally.
10142 UsedBits |= CurrentUsedBits;
10143
10144 // Check if the new slice would be legal.
10145 if (!LS.isLegal())
10146 return false;
10147
10148 // Record the slice.
10149 LoadedSlices.push_back(LS);
10150 }
10151
10152 // Abort slicing if it does not seem to be profitable.
10153 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10154 return false;
10155
10156 ++SlicedLoads;
10157
10158 // Rewrite each chain to use an independent load.
10159 // By construction, each chain can be represented by a unique load.
10160
10161 // Prepare the argument for the new token factor for all the slices.
10162 SmallVector<SDValue, 8> ArgChains;
10163 for (SmallVectorImpl<LoadedSlice>::const_iterator
10164 LSIt = LoadedSlices.begin(),
10165 LSItEnd = LoadedSlices.end();
10166 LSIt != LSItEnd; ++LSIt) {
10167 SDValue SliceInst = LSIt->loadSlice();
10168 CombineTo(LSIt->Inst, SliceInst, true);
10169 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10170 SliceInst = SliceInst.getOperand(0);
10171 assert(SliceInst->getOpcode() == ISD::LOAD &&
10172 "It takes more than a zext to get to the loaded slice!!");
10173 ArgChains.push_back(SliceInst.getValue(1));
10174 }
10175
10176 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +000010177 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +000010178 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10179 return true;
10180}
10181
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010182/// Check to see if V is (and load (ptr), imm), where the load is having
10183/// specific bytes cleared out. If so, return the byte size being masked out
10184/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +000010185static std::pair<unsigned, unsigned>
10186CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10187 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010188
Chris Lattner4041ab62010-04-15 04:48:01 +000010189 // Check for the structure we're looking for.
10190 if (V->getOpcode() != ISD::AND ||
10191 !isa<ConstantSDNode>(V->getOperand(1)) ||
10192 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10193 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +000010194
Chris Lattner3245afd2010-04-15 06:10:49 +000010195 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +000010196 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +000010197 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +000010198
Chris Lattner3245afd2010-04-15 06:10:49 +000010199 // The store should be chained directly to the load or be an operand of a
10200 // tokenfactor.
10201 if (LD == Chain.getNode())
10202 ; // ok.
10203 else if (Chain->getOpcode() != ISD::TokenFactor)
10204 return Result; // Fail.
10205 else {
10206 bool isOk = false;
10207 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10208 if (Chain->getOperand(i).getNode() == LD) {
10209 isOk = true;
10210 break;
10211 }
10212 if (!isOk) return Result;
10213 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010214
Chris Lattner4041ab62010-04-15 04:48:01 +000010215 // This only handles simple types.
10216 if (V.getValueType() != MVT::i16 &&
10217 V.getValueType() != MVT::i32 &&
10218 V.getValueType() != MVT::i64)
10219 return Result;
10220
10221 // Check the constant mask. Invert it so that the bits being masked out are
10222 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10223 // follow the sign bit for uniformity.
10224 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +000010225 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +000010226 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +000010227 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +000010228 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10229 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +000010230
Chris Lattner4041ab62010-04-15 04:48:01 +000010231 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +000010232 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +000010233 return Result;
10234
10235 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10236 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10237 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +000010238
Chris Lattner4041ab62010-04-15 04:48:01 +000010239 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10240 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010241 case 1:
10242 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +000010243 case 4: break;
10244 default: return Result; // All one mask, or 5-byte mask.
10245 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010246
Chris Lattner4041ab62010-04-15 04:48:01 +000010247 // Verify that the first bit starts at a multiple of mask so that the access
10248 // is aligned the same as the access width.
10249 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +000010250
Chris Lattner4041ab62010-04-15 04:48:01 +000010251 Result.first = MaskedBytes;
10252 Result.second = NotMaskTZ/8;
10253 return Result;
10254}
10255
10256
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010257/// Check to see if IVal is something that provides a value as specified by
10258/// MaskInfo. If so, replace the specified store with a narrower store of
10259/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +000010260static SDNode *
10261ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10262 SDValue IVal, StoreSDNode *St,
10263 DAGCombiner *DC) {
10264 unsigned NumBytes = MaskInfo.first;
10265 unsigned ByteShift = MaskInfo.second;
10266 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +000010267
Chris Lattner4041ab62010-04-15 04:48:01 +000010268 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10269 // that uses this. If not, this is not a replacement.
10270 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10271 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +000010272 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +000010273
Chris Lattner4041ab62010-04-15 04:48:01 +000010274 // Check that it is legal on the target to do this. It is legal if the new
10275 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10276 // legalization.
10277 MVT VT = MVT::getIntegerVT(NumBytes*8);
10278 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +000010279 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +000010280
Chris Lattner4041ab62010-04-15 04:48:01 +000010281 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10282 // shifted by ByteShift and truncated down to NumBytes.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010283 if (ByteShift) {
10284 SDLoc DL(IVal);
10285 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10286 DAG.getConstant(ByteShift*8, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010287 DC->getShiftAmountTy(IVal.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010288 }
Chris Lattner4041ab62010-04-15 04:48:01 +000010289
10290 // Figure out the offset for the store and the alignment of the access.
10291 unsigned StOffset;
10292 unsigned NewAlign = St->getAlignment();
10293
10294 if (DAG.getTargetLoweringInfo().isLittleEndian())
10295 StOffset = ByteShift;
10296 else
10297 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +000010298
Chris Lattner4041ab62010-04-15 04:48:01 +000010299 SDValue Ptr = St->getBasePtr();
10300 if (StOffset) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010301 SDLoc DL(IVal);
10302 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10303 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
Chris Lattner4041ab62010-04-15 04:48:01 +000010304 NewAlign = MinAlign(NewAlign, StOffset);
10305 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010306
Chris Lattner4041ab62010-04-15 04:48:01 +000010307 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010308 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +000010309
Chris Lattner4041ab62010-04-15 04:48:01 +000010310 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +000010311 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +000010312 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +000010313 false, false, NewAlign).getNode();
10314}
10315
Evan Chenga9cda8a2009-05-28 00:35:15 +000010316
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010317/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10318/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10319/// narrowing the load and store if it would end up being a win for performance
10320/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010321SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10322 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +000010323 if (ST->isVolatile())
10324 return SDValue();
10325
Evan Chenga9cda8a2009-05-28 00:35:15 +000010326 SDValue Chain = ST->getChain();
10327 SDValue Value = ST->getValue();
10328 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010329 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010330
10331 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +000010332 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010333
10334 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +000010335
Chris Lattner4041ab62010-04-15 04:48:01 +000010336 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10337 // is a byte mask indicating a consecutive number of bytes, check to see if
10338 // Y is known to provide just those bytes. If so, we try to replace the
10339 // load + replace + store sequence with a single (narrower) store, which makes
10340 // the load dead.
10341 if (Opc == ISD::OR) {
10342 std::pair<unsigned, unsigned> MaskedLoad;
10343 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10344 if (MaskedLoad.first)
10345 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10346 Value.getOperand(1), ST,this))
10347 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010348
Chris Lattner4041ab62010-04-15 04:48:01 +000010349 // Or is commutative, so try swapping X and Y.
10350 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10351 if (MaskedLoad.first)
10352 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10353 Value.getOperand(0), ST,this))
10354 return SDValue(NewST, 0);
10355 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010356
Evan Chenga9cda8a2009-05-28 00:35:15 +000010357 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10358 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +000010359 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010360
10361 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +000010362 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10363 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010364 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010365 if (LD->getBasePtr() != Ptr ||
10366 LD->getPointerInfo().getAddrSpace() !=
10367 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +000010368 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010369
10370 // Find the type to narrow it the load / op / store to.
10371 SDValue N1 = Value.getOperand(1);
10372 unsigned BitWidth = N1.getValueSizeInBits();
10373 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10374 if (Opc == ISD::AND)
10375 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +000010376 if (Imm == 0 || Imm.isAllOnesValue())
10377 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010378 unsigned ShAmt = Imm.countTrailingZeros();
10379 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10380 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +000010381 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +000010382 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010383 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010384 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010385 (NewVT.getStoreSizeInBits() != NewBW ||
10386 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10387 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010388 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +000010389 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010390 }
Evan Cheng6673ff02009-05-28 18:41:02 +000010391 if (NewBW >= BitWidth)
10392 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010393
10394 // If the lsb changed does not start at the type bitwidth boundary,
10395 // start at the previous one.
10396 if (ShAmt % NewBW)
10397 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +000010398 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10399 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010400 if ((Imm & Mask) == Imm) {
10401 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10402 if (Opc == ISD::AND)
10403 NewImm ^= APInt::getAllOnesValue(NewBW);
10404 uint64_t PtrOff = ShAmt / 8;
10405 // For big endian targets, we need to adjust the offset to the pointer to
10406 // load the correct bytes.
10407 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +000010408 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +000010409
10410 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +000010411 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010412 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +000010413 return SDValue();
10414
Andrew Trickef9de2a2013-05-25 02:42:55 +000010415 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010416 Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010417 DAG.getConstant(PtrOff, SDLoc(LD),
10418 Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010419 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010420 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010421 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010422 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010423 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010424 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010425 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010426 DAG.getConstant(NewImm, SDLoc(Value),
10427 NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010428 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010429 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010430 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010431 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010432
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010433 AddToWorklist(NewPtr.getNode());
10434 AddToWorklist(NewLD.getNode());
10435 AddToWorklist(NewVal.getNode());
10436 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010437 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010438 ++OpsNarrowed;
10439 return NewST;
10440 }
10441 }
10442
Evan Cheng6673ff02009-05-28 18:41:02 +000010443 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010444}
10445
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010446/// For a given floating point load / store pair, if the load value isn't used
10447/// by any other operations, then consider transforming the pair to integer
10448/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +000010449SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10450 StoreSDNode *ST = cast<StoreSDNode>(N);
10451 SDValue Chain = ST->getChain();
10452 SDValue Value = ST->getValue();
10453 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10454 Value.hasOneUse() &&
10455 Chain == SDValue(Value.getNode(), 1)) {
10456 LoadSDNode *LD = cast<LoadSDNode>(Value);
10457 EVT VT = LD->getMemoryVT();
10458 if (!VT.isFloatingPoint() ||
10459 VT != ST->getMemoryVT() ||
10460 LD->isNonTemporal() ||
10461 ST->isNonTemporal() ||
10462 LD->getPointerInfo().getAddrSpace() != 0 ||
10463 ST->getPointerInfo().getAddrSpace() != 0)
10464 return SDValue();
10465
10466 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10467 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10468 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10469 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10470 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10471 return SDValue();
10472
10473 unsigned LDAlign = LD->getAlignment();
10474 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +000010475 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010476 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +000010477 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10478 return SDValue();
10479
Andrew Trickef9de2a2013-05-25 02:42:55 +000010480 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +000010481 LD->getChain(), LD->getBasePtr(),
10482 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010483 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +000010484
Andrew Trickef9de2a2013-05-25 02:42:55 +000010485 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +000010486 NewLD, ST->getBasePtr(),
10487 ST->getPointerInfo(),
10488 false, false, STAlign);
10489
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010490 AddToWorklist(NewLD.getNode());
10491 AddToWorklist(NewST.getNode());
10492 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010493 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +000010494 ++LdStFP2Int;
10495 return NewST;
10496 }
10497
10498 return SDValue();
10499}
10500
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010501namespace {
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010502/// Helper struct to parse and store a memory address as base + index + offset.
10503/// We ignore sign extensions when it is safe to do so.
10504/// The following two expressions are not equivalent. To differentiate we need
10505/// to store whether there was a sign extension involved in the index
10506/// computation.
10507/// (load (i64 add (i64 copyfromreg %c)
10508/// (i64 signextend (add (i8 load %index)
10509/// (i8 1))))
10510/// vs
10511///
10512/// (load (i64 add (i64 copyfromreg %c)
10513/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10514/// (i32 1)))))
10515struct BaseIndexOffset {
10516 SDValue Base;
10517 SDValue Index;
10518 int64_t Offset;
10519 bool IsIndexSignExt;
10520
10521 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10522
10523 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10524 bool IsIndexSignExt) :
10525 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10526
10527 bool equalBaseIndex(const BaseIndexOffset &Other) {
10528 return Other.Base == Base && Other.Index == Index &&
10529 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010530 }
10531
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010532 /// Parses tree in Ptr for base, index, offset addresses.
10533 static BaseIndexOffset match(SDValue Ptr) {
10534 bool IsIndexSignExt = false;
10535
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010536 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10537 // instruction, then it could be just the BASE or everything else we don't
10538 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010539 if (Ptr->getOpcode() != ISD::ADD)
10540 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10541
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010542 // We know that we have at least an ADD instruction. Try to pattern match
10543 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010544 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10545 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10546 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10547 IsIndexSignExt);
10548 }
10549
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010550 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010551 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010552 // (i64 add (i64 %array_ptr)
10553 // (i64 mul (i64 %induction_var)
10554 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010555 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010556 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010557
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010558 // Look at Base + Index + Offset cases.
10559 SDValue Base = Ptr->getOperand(0);
10560 SDValue IndexOffset = Ptr->getOperand(1);
10561
10562 // Skip signextends.
10563 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10564 IndexOffset = IndexOffset->getOperand(0);
10565 IsIndexSignExt = true;
10566 }
10567
10568 // Either the case of Base + Index (no offset) or something else.
10569 if (IndexOffset->getOpcode() != ISD::ADD)
10570 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10571
10572 // Now we have the case of Base + Index + offset.
10573 SDValue Index = IndexOffset->getOperand(0);
10574 SDValue Offset = IndexOffset->getOperand(1);
10575
10576 if (!isa<ConstantSDNode>(Offset))
10577 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10578
10579 // Ignore signextends.
10580 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10581 Index = Index->getOperand(0);
10582 IsIndexSignExt = true;
10583 } else IsIndexSignExt = false;
10584
10585 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10586 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10587 }
10588};
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010589} // namespace
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010590
Sanjay Patel37c41c12015-01-22 18:21:26 +000010591bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10592 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010593 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010594 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010595 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010596 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010597
Sanjay Patel37c41c12015-01-22 18:21:26 +000010598 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10599 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
Akira Hatanakac6fab802015-04-08 20:34:53 +000010600 unsigned LatestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010601
Quentin Colombet308b1712015-01-27 23:58:01 +000010602 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010603 // Find a chain for the new wide-store operand. Notice that some
10604 // of the store nodes that we found may not be selected for inclusion
10605 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010606 // latest store node which is *used* and replaced by the wide store.
10607 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10608 LatestNodeUsed = i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010609 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010610
Akira Hatanakac6fab802015-04-08 20:34:53 +000010611 // The latest Node in the DAG.
10612 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010613 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010614
Sanjay Patel37c41c12015-01-22 18:21:26 +000010615 SDValue StoredVal;
10616 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010617 // Find a legal type for the vector store.
10618 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010619 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10620 if (IsConstantSrc) {
Reid Kleckner2691c592015-06-11 17:25:24 +000010621 // A vector store with a constant source implies that the constant is
10622 // zero; we only handle merging stores of constant zeros because the zero
10623 // can be materialized without a load.
10624 // It may be beneficial to loosen this restriction to allow non-zero
10625 // store merging.
10626 StoredVal = DAG.getConstant(0, DL, Ty);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010627 } else {
10628 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010629 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010630 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10631 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010632 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010633 if (Val.getValueType() != MemVT)
10634 return false;
10635 Ops.push_back(Val);
10636 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010637
Sanjay Patel37c41c12015-01-22 18:21:26 +000010638 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010639 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010640 }
10641 } else {
10642 // We should always use a vector store when merging extracted vector
10643 // elements, so this path implies a store of constants.
10644 assert(IsConstantSrc && "Merged vector elements should use vector store");
10645
Quentin Colombet308b1712015-01-27 23:58:01 +000010646 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010647 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010648
Sanjay Patel37c41c12015-01-22 18:21:26 +000010649 // Construct a single integer constant which is made of the smaller
10650 // constant inputs.
10651 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010652 for (unsigned i = 0; i < NumElem ; ++i) {
10653 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010654 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10655 SDValue Val = St->getValue();
10656 StoreInt <<= ElementSizeBytes*8;
10657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10658 StoreInt |= C->getAPIntValue().zext(StoreBW);
10659 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10660 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10661 } else {
10662 llvm_unreachable("Invalid constant element type");
10663 }
10664 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010665
Sanjay Patel37c41c12015-01-22 18:21:26 +000010666 // Create the new Load and Store operations.
10667 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010668 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010669 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010670
Akira Hatanakac6fab802015-04-08 20:34:53 +000010671 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010672 FirstInChain->getBasePtr(),
10673 FirstInChain->getPointerInfo(),
10674 false, false,
10675 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010676
Akira Hatanakac6fab802015-04-08 20:34:53 +000010677 // Replace the last store with the new store
10678 CombineTo(LatestOp, NewStore);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010679 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010680 for (unsigned i = 0; i < NumElem ; ++i) {
Akira Hatanakac6fab802015-04-08 20:34:53 +000010681 if (StoreNodes[i].MemNode == LatestOp)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010682 continue;
10683 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10684 // ReplaceAllUsesWith will replace all uses that existed when it was
10685 // called, but graph optimizations may cause new ones to appear. For
10686 // example, the case in pr14333 looks like
10687 //
10688 // St's chain -> St -> another store -> X
10689 //
10690 // And the only difference from St to the other store is the chain.
10691 // When we change it's chain to be St's chain they become identical,
10692 // get CSEed and the net result is that X is now a use of St.
10693 // Since we know that St is redundant, just iterate.
10694 while (!St->use_empty())
10695 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10696 deleteAndRecombine(St);
10697 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010698
Sanjay Patel37c41c12015-01-22 18:21:26 +000010699 return true;
10700}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010701
James Y Knight284e7b32015-05-08 13:47:01 +000010702static bool allowableAlignment(const SelectionDAG &DAG,
10703 const TargetLowering &TLI, EVT EVTTy,
10704 unsigned AS, unsigned Align) {
10705 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10706 return true;
10707
10708 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10709 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10710 return (Align >= ABIAlignment);
10711}
10712
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010713bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010714 if (OptLevel == CodeGenOpt::None)
10715 return false;
10716
Quentin Colombet308b1712015-01-27 23:58:01 +000010717 EVT MemVT = St->getMemoryVT();
10718 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010719 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10720 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010721
James Y Knightfca02be2015-05-09 03:13:37 +000010722 // This function cannot currently deal with non-byte-sized memory sizes.
10723 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10724 return false;
10725
Quentin Colombet308b1712015-01-27 23:58:01 +000010726 // Don't merge vectors into wider inputs.
10727 if (MemVT.isVector() || !MemVT.isSimple())
10728 return false;
10729
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010730 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010731 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010732 SDValue StoredVal = St->getValue();
10733 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010734 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10735 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010736 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010737
Quentin Colombet308b1712015-01-27 23:58:01 +000010738 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010739 return false;
10740
10741 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010742 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010743 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10744 return false;
10745
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010746 // This holds the base pointer, index, and the offset in bytes from the base
10747 // pointer.
10748 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010749
10750 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010751 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010752 return false;
10753
10754 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010755 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010756 return false;
10757
Nadav Rotem307d7672012-11-29 00:00:08 +000010758 // Save the LoadSDNodes that we find in the chain.
10759 // We need to make sure that these nodes do not interfere with
10760 // any of the store nodes.
10761 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10762
10763 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010764 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010765
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010766 // Walk up the chain and look for nodes with offsets from the same
10767 // base pointer. Stop when reaching an instruction with a different kind
10768 // or instruction which has a different base pointer.
10769 unsigned Seq = 0;
10770 StoreSDNode *Index = St;
10771 while (Index) {
10772 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010773 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010774 break;
10775
10776 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010777 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010778
10779 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010780 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010781 break;
10782
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010783 // The memory operands must not be volatile.
10784 if (Index->isVolatile() || Index->isIndexed())
10785 break;
10786
10787 // No truncation.
10788 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10789 if (St->isTruncatingStore())
10790 break;
10791
10792 // The stored memory type must be the same.
10793 if (Index->getMemoryVT() != MemVT)
10794 break;
10795
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010796 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010797 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010798
Nadav Rotem307d7672012-11-29 00:00:08 +000010799 // Find the next memory operand in the chain. If the next operand in the
10800 // chain is a store then move up and continue the scan with the next
10801 // memory operand. If the next operand is a load save it and use alias
10802 // information to check if it interferes with anything.
10803 SDNode *NextInChain = Index->getChain().getNode();
10804 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010805 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010806 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010807 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010808 break;
10809 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010810 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010811 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010812 break;
10813 }
10814
Nadav Rotem307d7672012-11-29 00:00:08 +000010815 // Save the load node for later. Continue the scan.
10816 AliasLoadNodes.push_back(Ldn);
10817 NextInChain = Ldn->getChain().getNode();
10818 continue;
10819 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010820 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010821 break;
10822 }
10823 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010824 }
10825
10826 // Check if there is anything to merge.
10827 if (StoreNodes.size() < 2)
10828 return false;
10829
10830 // Sort the memory operands according to their distance from the base pointer.
10831 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010832 [](MemOpLink LHS, MemOpLink RHS) {
10833 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10834 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10835 LHS.SequenceNum > RHS.SequenceNum);
10836 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010837
10838 // Scan the memory operations on the chain and find the first non-consecutive
10839 // store memory address.
10840 unsigned LastConsecutiveStore = 0;
10841 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010842 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10843
10844 // Check that the addresses are consecutive starting from the second
10845 // element in the list of stores.
10846 if (i > 0) {
10847 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10848 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10849 break;
10850 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010851
Nadav Rotem307d7672012-11-29 00:00:08 +000010852 bool Alias = false;
10853 // Check if this store interferes with any of the loads that we found.
10854 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10855 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10856 Alias = true;
10857 break;
10858 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010859 // We found a load that alias with this store. Stop the sequence.
10860 if (Alias)
10861 break;
10862
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010863 // Mark this node as useful.
10864 LastConsecutiveStore = i;
10865 }
10866
10867 // The node with the lowest store address.
10868 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
James Y Knight284e7b32015-05-08 13:47:01 +000010869 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10870 unsigned FirstStoreAlign = FirstInChain->getAlignment();
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010871
10872 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010873 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010874 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010875 unsigned LastLegalVectorType = 0;
10876 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010877 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10878 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10879 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010880
10881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010882 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010883 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010884 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010885 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010886 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010887 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010888 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010889
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010890 // Find a legal type for the constant store.
10891 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10892 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
James Y Knight284e7b32015-05-08 13:47:01 +000010893 if (TLI.isTypeLegal(StoreTy) &&
10894 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10895 FirstStoreAlign)) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010896 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010897 // Or check whether a truncstore is legal.
James Y Knight284e7b32015-05-08 13:47:01 +000010898 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10899 TargetLowering::TypePromoteInteger) {
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010900 EVT LegalizedStoredValueTy =
10901 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
James Y Knight284e7b32015-05-08 13:47:01 +000010902 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10903 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10904 FirstStoreAlign)) {
10905 LastLegalType = i + 1;
10906 }
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010907 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010908
10909 // Find a legal type for the vector store.
10910 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000010911 if (TLI.isTypeLegal(Ty) &&
10912 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
Nadav Rotemb27777f2012-10-04 22:35:15 +000010913 LastLegalVectorType = i + 1;
James Y Knight284e7b32015-05-08 13:47:01 +000010914 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010915 }
10916
Matt Arsenault65ad1602015-05-24 00:51:27 +000010917
10918 // We only use vectors if the constant is known to be zero or the target
10919 // allows it and the function is not marked with the noimplicitfloat
10920 // attribute.
10921 if (NoVectors) {
Nadav Rotemb27777f2012-10-04 22:35:15 +000010922 LastLegalVectorType = 0;
Matt Arsenault65ad1602015-05-24 00:51:27 +000010923 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10924 LastLegalVectorType,
10925 FirstStoreAS)) {
10926 LastLegalVectorType = 0;
10927 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010928
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010929 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010930 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010931 return false;
10932
Nadav Rotem495b1a42013-02-14 18:28:52 +000010933 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010934 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10935
Sanjay Patel37c41c12015-01-22 18:21:26 +000010936 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10937 true, UseVector);
10938 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010939
Sanjay Patel37c41c12015-01-22 18:21:26 +000010940 // When extracting multiple vector elements, try to store them
10941 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010942 if (IsExtractVecEltSrc) {
10943 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010944 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10945 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010946 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010947 // This restriction could be loosened.
10948 // Bail out if any stored values are not elements extracted from a vector.
10949 // It should be possible to handle mixed sources, but load sources need
10950 // more careful handling (see the block of code below that handles
10951 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010952 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010953 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010954
Nadav Rotemb27777f2012-10-04 22:35:15 +000010955 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010956 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000010957 if (TLI.isTypeLegal(Ty) &&
10958 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
Quentin Colombet308b1712015-01-27 23:58:01 +000010959 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010960 }
10961
Quentin Colombet308b1712015-01-27 23:58:01 +000010962 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010963 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010964 }
10965
10966 // Below we handle the case of multiple consecutive stores that
10967 // come from multiple consecutive loads. We merge them into a single
10968 // wide load and a single wide store.
10969
10970 // Look for load nodes which are used by the stored values.
10971 SmallVector<MemOpLink, 8> LoadNodes;
10972
10973 // Find acceptable loads. Loads need to have the same chain (token factor),
10974 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010975 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010976 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10977 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10978 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10979 if (!Ld) break;
10980
10981 // Loads must only have one use.
10982 if (!Ld->hasNUsesOfValue(1, 0))
10983 break;
10984
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010985 // The memory operands must not be volatile.
10986 if (Ld->isVolatile() || Ld->isIndexed())
10987 break;
10988
10989 // We do not accept ext loads.
10990 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10991 break;
10992
10993 // The stored memory type must be the same.
10994 if (Ld->getMemoryVT() != MemVT)
10995 break;
10996
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010997 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010998 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010999 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011000 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000011001 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011002 break;
11003 } else {
11004 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000011005 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011006 }
11007
11008 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000011009 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011010 }
11011
11012 if (LoadNodes.size() < 2)
11013 return false;
11014
James Molloyce45be02014-08-02 14:51:24 +000011015 // If we have load/store pair instructions and we only have two values,
11016 // don't bother.
11017 unsigned RequiredAlignment;
11018 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11019 St->getAlignment() >= RequiredAlignment)
11020 return false;
11021
James Y Knight284e7b32015-05-08 13:47:01 +000011022 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11023 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11024 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11025
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011026 // Scan the memory operations on the chain and find the first non-consecutive
11027 // load memory address. These variables hold the index in the store node
11028 // array.
11029 unsigned LastConsecutiveLoad = 0;
11030 // This variable refers to the size and not index in the array.
11031 unsigned LastLegalVectorType = 0;
11032 unsigned LastLegalIntegerType = 0;
11033 StartAddress = LoadNodes[0].OffsetFromBase;
James Y Knight284e7b32015-05-08 13:47:01 +000011034 SDValue FirstChain = FirstLoad->getChain();
Nadav Rotemac920662012-10-03 19:30:31 +000011035 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11036 // All loads much share the same chain.
11037 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11038 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000011039
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011040 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11041 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11042 break;
11043 LastConsecutiveLoad = i;
11044
11045 // Find a legal type for the vector store.
11046 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000011047 if (TLI.isTypeLegal(StoreTy) &&
11048 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11049 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011050 LastLegalVectorType = i + 1;
James Y Knight284e7b32015-05-08 13:47:01 +000011051 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011052
11053 // Find a legal type for the integer store.
11054 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
11055 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
James Y Knight284e7b32015-05-08 13:47:01 +000011056 if (TLI.isTypeLegal(StoreTy) &&
11057 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11058 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011059 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000011060 // Or check whether a truncstore and extload is legal.
11061 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11062 TargetLowering::TypePromoteInteger) {
11063 EVT LegalizedStoredValueTy =
11064 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11065 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000011066 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11067 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
James Y Knight284e7b32015-05-08 13:47:01 +000011068 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11069 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11070 FirstStoreAlign) &&
11071 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11072 FirstLoadAlign))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000011073 LastLegalIntegerType = i+1;
11074 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011075 }
11076
11077 // Only use vector types if the vector type is larger than the integer type.
11078 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000011079 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011080 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11081
11082 // We add +1 here because the LastXXX variables refer to location while
11083 // the NumElem refers to array/index size.
11084 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11085 NumElem = std::min(LastLegalType, NumElem);
11086
11087 if (NumElem < 2)
11088 return false;
11089
Akira Hatanakac6fab802015-04-08 20:34:53 +000011090 // The latest Node in the DAG.
11091 unsigned LatestNodeUsed = 0;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011092 for (unsigned i=1; i<NumElem; ++i) {
11093 // Find a chain for the new wide-store operand. Notice that some
11094 // of the store nodes that we found may not be selected for inclusion
11095 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000011096 // latest store node which is *used* and replaced by the wide store.
11097 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11098 LatestNodeUsed = i;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011099 }
11100
Akira Hatanakac6fab802015-04-08 20:34:53 +000011101 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11102
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011103 // Find if it is better to use vectors or integers to load and store
11104 // to memory.
11105 EVT JointMemOpVT;
11106 if (UseVectorTy) {
11107 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11108 } else {
11109 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11110 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11111 }
11112
Andrew Trickef9de2a2013-05-25 02:42:55 +000011113 SDLoc LoadDL(LoadNodes[0].MemNode);
11114 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011115
James Y Knight284e7b32015-05-08 13:47:01 +000011116 SDValue NewLoad = DAG.getLoad(
11117 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11118 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011119
James Y Knight284e7b32015-05-08 13:47:01 +000011120 SDValue NewStore = DAG.getStore(
11121 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11122 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011123
Nadav Rotemac920662012-10-03 19:30:31 +000011124 // Replace one of the loads with the new load.
11125 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11126 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11127 SDValue(NewLoad.getNode(), 1));
11128
11129 // Remove the rest of the load chains.
11130 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011131 // Replace all chain users of the old load nodes with the chain of the new
11132 // load node.
11133 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000011134 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11135 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011136
Akira Hatanakac6fab802015-04-08 20:34:53 +000011137 // Replace the last store with the new store.
11138 CombineTo(LatestOp, NewStore);
Nadav Rotemac920662012-10-03 19:30:31 +000011139 // Erase all other stores.
11140 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011141 // Remove all Store nodes.
Akira Hatanakac6fab802015-04-08 20:34:53 +000011142 if (StoreNodes[i].MemNode == LatestOp)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011143 continue;
11144 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11145 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000011146 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011147 }
11148
11149 return true;
11150}
11151
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011152SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000011153 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011154 SDValue Chain = ST->getChain();
11155 SDValue Value = ST->getValue();
11156 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011157
Evan Chenga4cf58a2007-05-07 21:27:48 +000011158 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000011159 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000011160 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011161 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000011162 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000011163 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011164 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000011165 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000011166 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011167 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000011168 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011169 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000011170 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011171 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000011172 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000011173 }
Owen Andersona5192842011-04-14 17:30:49 +000011174
Chris Lattner41c80e82011-04-09 02:32:02 +000011175 // Turn 'store undef, Ptr' -> nothing.
11176 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11177 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000011178
Nate Begeman8e20c762006-12-11 02:23:46 +000011179 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000011180 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000011181 // NOTE: If the original store is volatile, this transform must not increase
11182 // the number of stores. For example, on x86-32 an f64 can be stored in one
11183 // processor operation but an i64 (which is not legal) requires two. So the
11184 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000011185 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011186 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000011187 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000011188 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000011189 case MVT::f16: // We don't do this for these yet.
11190 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000011191 case MVT::f128:
11192 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000011193 break;
Owen Anderson9f944592009-08-11 20:47:22 +000011194 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000011195 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000011196 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011197 ;
Dale Johannesen028084e2007-09-12 03:30:33 +000011198 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011199 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11200 MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011201 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011202 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000011203 }
11204 break;
Owen Anderson9f944592009-08-11 20:47:22 +000011205 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000011206 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000011207 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000011208 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011209 ;
Dale Johannesen54306fe2008-10-09 18:53:47 +000011210 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011211 getZExtValue(), SDLoc(CFP), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011212 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011213 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000011214 }
Owen Andersona5192842011-04-14 17:30:49 +000011215
Chris Lattner41c80e82011-04-09 02:32:02 +000011216 if (!ST->isVolatile() &&
11217 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000011218 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000011219 // argument passing. Since this is so common, custom legalize the
11220 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000011221 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011222 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11223 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000011224 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000011225
Dan Gohman2af30632007-07-09 22:18:38 +000011226 unsigned Alignment = ST->getAlignment();
11227 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000011228 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000011229 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000011230
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011231 SDLoc DL(N);
11232
Andrew Trickef9de2a2013-05-25 02:42:55 +000011233 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000011234 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000011235 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000011236 ST->getAlignment(), AAInfo);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011237 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11238 DAG.getConstant(4, DL, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000011239 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011240 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000011241 Ptr, ST->getPointerInfo().getWithOffset(4),
11242 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000011243 Alignment, AAInfo);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011244 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000011245 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000011246 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011247
Chris Lattnerb7524b62006-12-12 04:16:14 +000011248 break;
Evan Cheng21836982006-12-11 17:25:19 +000011249 }
Nate Begeman8e20c762006-12-11 02:23:46 +000011250 }
Nate Begeman8e20c762006-12-11 02:23:46 +000011251 }
11252
Evan Cheng43cd9e32010-04-01 06:04:33 +000011253 // Try to infer better alignment information than the store already has.
11254 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000011255 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersondb420122015-03-19 22:48:57 +000011256 if (Align > ST->getAlignment()) {
11257 SDValue NewStore =
11258 DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000011259 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011260 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000011261 ST->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +000011262 if (NewStore.getNode() != N)
11263 return CombineTo(ST, NewStore, true);
11264 }
Evan Cheng43cd9e32010-04-01 06:04:33 +000011265 }
11266 }
11267
Evan Chengd42641c2011-02-02 01:06:55 +000011268 // Try transforming a pair floating point load / store ops to integer
11269 // load / store ops.
11270 SDValue NewST = TransformFPLoadStorePair(N);
11271 if (NewST.getNode())
11272 return NewST;
11273
Eric Christopherf55d4712014-10-08 23:38:39 +000011274 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11275 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011276#ifndef NDEBUG
11277 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11278 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11279 UseAA = false;
11280#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000011281 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000011282 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011283 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011284
Jim Laskey708d0db2006-10-04 16:53:27 +000011285 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000011286 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011287 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000011288
11289 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011290 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011291 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011292 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011293 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011294 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011295 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011296 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011297
Jim Laskeyd07be232006-09-25 16:29:54 +000011298 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011299 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000011300 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011301
Nate Begeman879d8f12009-09-15 00:18:30 +000011302 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011303 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000011304
Jim Laskeydcf983c2006-10-13 23:32:28 +000011305 // Don't add users to work list.
11306 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000011307 }
Jim Laskey5d19d592006-09-21 16:28:59 +000011308 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011309
Evan Cheng33157702006-11-05 09:31:14 +000011310 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000011311 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011312 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000011313
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011314 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011315 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000011316 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000011317 // See if we can simplify the input to this truncstore with knowledge that
11318 // only the low bits are being used. For example:
11319 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000011320 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000011321 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000011322 APInt::getLowBitsSet(
11323 Value.getValueType().getScalarType().getSizeInBits(),
11324 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011325 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011326 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000011327 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011328 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000011329
Chris Lattnerf47e3062007-10-13 06:58:48 +000011330 // Otherwise, see if we can simplify the operation with
11331 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000011332 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011333 APInt::getLowBitsSet(
11334 Value.getValueType().getScalarType().getSizeInBits(),
11335 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011336 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000011337 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011338
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011339 // If this is a load followed by a store to the same location, then the store
11340 // is dead/noop.
11341 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011342 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011343 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000011344 // There can't be any side effects between the load and store, such as
11345 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011346 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011347 // The store is dead, remove it.
11348 return Chain;
11349 }
11350 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011351
James Molloy463db9a2014-09-27 17:02:54 +000011352 // If this is a store followed by a store with the same value to the same
11353 // location, then the store is dead/noop.
11354 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11355 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11356 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11357 ST1->isUnindexed() && !ST1->isVolatile()) {
11358 // The store is dead, remove it.
11359 return Chain;
11360 }
11361 }
11362
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011363 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11364 // truncating store. We can do this even if this is already a truncstore.
11365 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011366 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011367 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011368 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011369 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011370 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011371 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011372
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011373 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000011374 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000011375 if (!LegalTypes) {
11376 bool EverChanged = false;
11377
11378 do {
11379 // There can be multiple store sequences on the same chain.
11380 // Keep trying to merge store sequences until we are unable to do so
11381 // or until we merge the last store on the chain.
11382 bool Changed = MergeConsecutiveStores(ST);
11383 EverChanged |= Changed;
11384 if (!Changed) break;
11385 } while (ST->getOpcode() != ISD::DELETED_NODE);
11386
11387 if (EverChanged)
11388 return SDValue(N, 0);
11389 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011390
Evan Chenga9cda8a2009-05-28 00:35:15 +000011391 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000011392}
11393
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011394SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11395 SDValue InVec = N->getOperand(0);
11396 SDValue InVal = N->getOperand(1);
11397 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011398 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011399
Bob Wilson42603952010-05-19 23:42:58 +000011400 // If the inserted element is an UNDEF, just use the input vector.
11401 if (InVal.getOpcode() == ISD::UNDEF)
11402 return InVec;
11403
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011404 EVT VT = InVec.getValueType();
11405
Owen Andersonb2c80da2011-02-25 21:41:48 +000011406 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011407 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11408 return SDValue();
11409
Eli Friedmanb7910b72011-09-09 21:04:06 +000011410 // Check that we know which element is being inserted
11411 if (!isa<ConstantSDNode>(EltNo))
11412 return SDValue();
11413 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011414
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011415 // Canonicalize insert_vector_elt dag nodes.
11416 // Example:
11417 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11418 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11419 //
11420 // Do this only if the child insert_vector node has one use; also
11421 // do this only if indices are both constants and Idx1 < Idx0.
11422 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11423 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11424 unsigned OtherElt =
11425 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11426 if (Elt < OtherElt) {
11427 // Swap nodes.
11428 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11429 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011430 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011431 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11432 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11433 }
11434 }
11435
Eli Friedmanb7910b72011-09-09 21:04:06 +000011436 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11437 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11438 // vector elements.
11439 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000011440 // Do not combine these two vectors if the output vector will not replace
11441 // the input vector.
11442 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000011443 Ops.append(InVec.getNode()->op_begin(),
11444 InVec.getNode()->op_end());
11445 } else if (InVec.getOpcode() == ISD::UNDEF) {
11446 unsigned NElts = VT.getVectorNumElements();
11447 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11448 } else {
11449 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011450 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000011451
11452 // Insert the element
11453 if (Elt < Ops.size()) {
11454 // All the operands of BUILD_VECTOR must have the same type;
11455 // we enforce that here.
11456 EVT OpVT = Ops[0].getValueType();
11457 if (InVal.getValueType() != OpVT)
11458 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11459 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11460 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11461 Ops[Elt] = InVal;
11462 }
11463
11464 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000011465 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000011466}
11467
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011468SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11469 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11470 EVT ResultVT = EVE->getValueType(0);
11471 EVT VecEltVT = InVecVT.getVectorElementType();
11472 unsigned Align = OriginalLoad->getAlignment();
11473 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11474 VecEltVT.getTypeForEVT(*DAG.getContext()));
11475
11476 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11477 return SDValue();
11478
11479 Align = NewAlign;
11480
11481 SDValue NewPtr = OriginalLoad->getBasePtr();
11482 SDValue Offset;
11483 EVT PtrType = NewPtr.getValueType();
11484 MachinePointerInfo MPI;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011485 SDLoc DL(EVE);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011486 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11487 int Elt = ConstEltNo->getZExtValue();
11488 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011489 Offset = DAG.getConstant(PtrOff, DL, PtrType);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011490 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11491 } else {
Ulrich Weigand9958c482015-05-05 19:34:10 +000011492 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011493 Offset = DAG.getNode(
Ulrich Weigand9958c482015-05-05 19:34:10 +000011494 ISD::MUL, DL, PtrType, Offset,
11495 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011496 MPI = OriginalLoad->getPointerInfo();
11497 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011498 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011499
11500 // The replacement we need to do here is a little tricky: we need to
11501 // replace an extractelement of a load with a load.
11502 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11503 // Note that this replacement assumes that the extractvalue is the only
11504 // use of the load; that's okay because we don't want to perform this
11505 // transformation in other cases anyway.
11506 SDValue Load;
11507 SDValue Chain;
11508 if (ResultVT.bitsGT(VecEltVT)) {
11509 // If the result type of vextract is wider than the load, then issue an
11510 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000011511 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11512 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011513 ? ISD::ZEXTLOAD
11514 : ISD::EXTLOAD;
11515 Load = DAG.getExtLoad(
11516 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11517 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11518 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11519 Chain = Load.getValue(1);
11520 } else {
11521 Load = DAG.getLoad(
11522 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11523 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11524 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11525 Chain = Load.getValue(1);
11526 if (ResultVT.bitsLT(VecEltVT))
11527 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11528 else
11529 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11530 }
11531 WorklistRemover DeadNodes(*this);
11532 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11533 SDValue To[] = { Load, Chain };
11534 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11535 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11536 // worklist explicitly as well.
11537 AddToWorklist(Load.getNode());
11538 AddUsersToWorklist(Load.getNode()); // Add users too
11539 // Make sure to revisit this node to clean it up; it will usually be dead.
11540 AddToWorklist(EVE);
11541 ++OpsNarrowed;
11542 return SDValue(EVE, 0);
11543}
11544
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011545SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000011546 // (vextract (scalar_to_vector val, 0) -> val
11547 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011548 EVT VT = InVec.getValueType();
11549 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000011550
Duncan Sands6be291a2011-05-09 08:03:33 +000011551 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11552 // Check if the result type doesn't match the inserted element type. A
11553 // SCALAR_TO_VECTOR may truncate the inserted element and the
11554 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11555 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000011556 if (InOp.getValueType() != NVT) {
11557 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000011558 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000011559 }
11560 return InOp;
11561 }
Evan Cheng1120279a2008-05-13 08:35:03 +000011562
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011563 SDValue EltNo = N->getOperand(1);
11564 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11565
11566 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11567 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000011568 // we may introduce new vector instructions which are not backed by TD
11569 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000011570 // without using extract_subvector. However, if we can find an underlying
11571 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011572 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000011573 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011574 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11575 int NumElem = VT.getVectorNumElements();
11576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11577 // Find the new index to extract from.
11578 int OrigElt = SVOp->getMaskElt(Elt);
11579
11580 // Extracting an undef index is undef.
11581 if (OrigElt == -1)
11582 return DAG.getUNDEF(NVT);
11583
11584 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011585 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011586 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011587 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011588 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011589 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011590 OrigElt -= NumElem;
11591 }
11592
Hal Finkel02807592014-03-31 11:43:19 +000011593 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11594 SDValue InOp = SVInVec.getOperand(OrigElt);
11595 if (InOp.getValueType() != NVT) {
11596 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11597 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11598 }
11599
11600 return InOp;
11601 }
11602
11603 // FIXME: We should handle recursing on other vector shuffles and
11604 // scalar_to_vector here as well.
11605
11606 if (!LegalOperations) {
11607 EVT IndexTy = TLI.getVectorIdxTy();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011608 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11609 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
Hal Finkel02807592014-03-31 11:43:19 +000011610 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011611 }
11612
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011613 bool BCNumEltsChanged = false;
11614 EVT ExtVT = VT.getVectorElementType();
11615 EVT LVT = ExtVT;
11616
11617 // If the result of load has to be truncated, then it's not necessarily
11618 // profitable.
11619 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11620 return SDValue();
11621
11622 if (InVec.getOpcode() == ISD::BITCAST) {
11623 // Don't duplicate a load with other uses.
11624 if (!InVec.hasOneUse())
11625 return SDValue();
11626
11627 EVT BCVT = InVec.getOperand(0).getValueType();
11628 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11629 return SDValue();
11630 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11631 BCNumEltsChanged = true;
11632 InVec = InVec.getOperand(0);
11633 ExtVT = BCVT.getVectorElementType();
11634 }
11635
11636 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11637 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11638 ISD::isNormalLoad(InVec.getNode()) &&
11639 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11640 SDValue Index = N->getOperand(1);
11641 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11642 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11643 OrigLoad);
11644 }
11645
Evan Cheng1120279a2008-05-13 08:35:03 +000011646 // Perform only after legalization to ensure build_vector / vector_shuffle
11647 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011648 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011649
Mon P Wangca6d6de2009-01-17 00:07:25 +000011650 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11651 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11652 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011653
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011654 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011655 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011656
Craig Topperc0196b12014-04-14 00:51:57 +000011657 LoadSDNode *LN0 = nullptr;
11658 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011659 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011660 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011661 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011662 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011663 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011664 // Don't duplicate a load with other uses.
11665 if (!InVec.hasOneUse())
11666 return SDValue();
11667
Evan Cheng1120279a2008-05-13 08:35:03 +000011668 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011669 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011670 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11671 // =>
11672 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011673
Eli Friedmane96286c2011-12-26 22:49:32 +000011674 // Don't duplicate a load with other uses.
11675 if (!InVec.hasOneUse())
11676 return SDValue();
11677
Mon P Wangb5eb7202008-12-11 00:26:16 +000011678 // If the bit convert changed the number of elements, it is unsafe
11679 // to examine the mask.
11680 if (BCNumEltsChanged)
11681 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011682
11683 // Select the input vector, guarding against out of range extract vector.
11684 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011685 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011686 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11687
Eli Friedmane96286c2011-12-26 22:49:32 +000011688 if (InVec.getOpcode() == ISD::BITCAST) {
11689 // Don't duplicate a load with other uses.
11690 if (!InVec.hasOneUse())
11691 return SDValue();
11692
Evan Cheng1120279a2008-05-13 08:35:03 +000011693 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011694 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011695 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011696 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011697 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011698 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011699 }
11700 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011701
Eli Friedmane96286c2011-12-26 22:49:32 +000011702 // Make sure we found a non-volatile load and the extractelement is
11703 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011704 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011705 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011706
Eric Christopherc6418b12010-11-03 20:44:42 +000011707 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11708 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011709 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011710
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011711 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011712 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011713
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011714 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011715}
Evan Cheng0de312d2007-10-06 08:19:55 +000011716
Michael Liao6d106b72012-10-23 23:06:52 +000011717// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11718SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11719 // We perform this optimization post type-legalization because
11720 // the type-legalizer often scalarizes integer-promoted vectors.
11721 // Performing this optimization before may create bit-casts which
11722 // will be type-legalized to complex code sequences.
11723 // We perform this optimization only before the operation legalizer because we
11724 // may introduce illegal operations.
11725 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11726 return SDValue();
11727
Dan Gohmana8665142007-06-25 16:23:39 +000011728 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011729 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011730 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011731
Nadav Rotembf6568b2011-10-29 21:23:04 +000011732 // Check to see if this is a BUILD_VECTOR of a bunch of values
11733 // which come from any_extend or zero_extend nodes. If so, we can create
11734 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011735 // optimizations. We do not handle sign-extend because we can't fill the sign
11736 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011737 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011738 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011739
Craig Topper02cb0fb2012-01-17 09:09:48 +000011740 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011741 SDValue In = N->getOperand(i);
11742 // Ignore undef inputs.
11743 if (In.getOpcode() == ISD::UNDEF) continue;
11744
11745 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11746 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11747
Nadav Rotemf3103612011-10-31 20:08:25 +000011748 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011749 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011750 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011751 break;
11752 }
11753
11754 // The input is a ZeroExt or AnyExt. Check the original type.
11755 EVT InTy = In.getOperand(0).getValueType();
11756
11757 // Check that all of the widened source types are the same.
11758 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011759 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011760 SourceType = InTy;
11761 else if (InTy != SourceType) {
11762 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011763 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011764 break;
11765 }
11766
11767 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011768 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011769 }
11770
Nadav Rotemf3103612011-10-31 20:08:25 +000011771 // In order to have valid types, all of the inputs must be extended from the
11772 // same source type and all of the inputs must be any or zero extend.
11773 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011774 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011775 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011776 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11777 isPowerOf2_32(SourceType.getSizeInBits());
11778
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011779 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11780 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011781 if (!ValidTypes)
11782 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011783
Michael Liao6d106b72012-10-23 23:06:52 +000011784 bool isLE = TLI.isLittleEndian();
11785 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11786 assert(ElemRatio > 1 && "Invalid element size ratio");
11787 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011788 DAG.getConstant(0, SDLoc(N), SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011789
Michael Liao6d106b72012-10-23 23:06:52 +000011790 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11791 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011792
Michael Liao6d106b72012-10-23 23:06:52 +000011793 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011794 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011795 SDValue Cast = N->getOperand(i);
11796 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11797 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11798 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11799 SDValue In;
11800 if (Cast.getOpcode() == ISD::UNDEF)
11801 In = DAG.getUNDEF(SourceType);
11802 else
11803 In = Cast->getOperand(0);
11804 unsigned Index = isLE ? (i * ElemRatio) :
11805 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011806
Michael Liao6d106b72012-10-23 23:06:52 +000011807 assert(Index < Ops.size() && "Invalid index");
11808 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011809 }
Chris Lattner5336a592006-03-19 01:27:56 +000011810
Michael Liao6d106b72012-10-23 23:06:52 +000011811 // The type of the new BUILD_VECTOR node.
11812 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11813 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11814 "Invalid vector size");
11815 // Check if the new vector type is legal.
11816 if (!isTypeLegal(VecVT)) return SDValue();
11817
11818 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011819 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011820
11821 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011822 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011823 // Bitcast to the desired type.
11824 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11825}
11826
Michael Liao59229792012-10-24 04:14:18 +000011827SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11828 EVT VT = N->getValueType(0);
11829
11830 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011831 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011832
11833 EVT SrcVT = MVT::Other;
11834 unsigned Opcode = ISD::DELETED_NODE;
11835 unsigned NumDefs = 0;
11836
11837 for (unsigned i = 0; i != NumInScalars; ++i) {
11838 SDValue In = N->getOperand(i);
11839 unsigned Opc = In.getOpcode();
11840
11841 if (Opc == ISD::UNDEF)
11842 continue;
11843
11844 // If all scalar values are floats and converted from integers.
11845 if (Opcode == ISD::DELETED_NODE &&
11846 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11847 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011848 }
Tom Stellard567f8862013-01-02 22:13:01 +000011849
Michael Liao59229792012-10-24 04:14:18 +000011850 if (Opc != Opcode)
11851 return SDValue();
11852
11853 EVT InVT = In.getOperand(0).getValueType();
11854
11855 // If all scalar values are typed differently, bail out. It's chosen to
11856 // simplify BUILD_VECTOR of integer types.
11857 if (SrcVT == MVT::Other)
11858 SrcVT = InVT;
11859 if (SrcVT != InVT)
11860 return SDValue();
11861 NumDefs++;
11862 }
11863
11864 // If the vector has just one element defined, it's not worth to fold it into
11865 // a vectorized one.
11866 if (NumDefs < 2)
11867 return SDValue();
11868
11869 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11870 && "Should only handle conversion from integer to float.");
11871 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11872
11873 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011874
11875 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11876 return SDValue();
11877
Hal Finkele2dd84e2015-02-22 16:10:22 +000011878 // Just because the floating-point vector type is legal does not necessarily
11879 // mean that the corresponding integer vector type is.
11880 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011881 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011882
Michael Liao59229792012-10-24 04:14:18 +000011883 SmallVector<SDValue, 8> Opnds;
11884 for (unsigned i = 0; i != NumInScalars; ++i) {
11885 SDValue In = N->getOperand(i);
11886
11887 if (In.getOpcode() == ISD::UNDEF)
11888 Opnds.push_back(DAG.getUNDEF(SrcVT));
11889 else
11890 Opnds.push_back(In.getOperand(0));
11891 }
Craig Topper48d114b2014-04-26 18:35:24 +000011892 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011893 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011894
11895 return DAG.getNode(Opcode, dl, VT, BV);
11896}
11897
Michael Liao6d106b72012-10-23 23:06:52 +000011898SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11899 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011900 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011901 EVT VT = N->getValueType(0);
11902
11903 // A vector built entirely of undefs is undef.
11904 if (ISD::allOperandsUndef(N))
11905 return DAG.getUNDEF(VT);
11906
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011907 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011908 return V;
11909
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011910 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011911 return V;
11912
Dan Gohmana8665142007-06-25 16:23:39 +000011913 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11914 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11915 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011916
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011917 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11918 if (!isTypeLegal(VT))
11919 return SDValue();
11920
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011921 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011922 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011923 return SDValue();
11924
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011925 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011926 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011927 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011928 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011929 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011930 if (Op.getOpcode() == ISD::UNDEF) continue;
11931
11932 // See if we can combine this build_vector into a blend with a zero vector.
Andrea Di Biagio9ac8a6b2015-06-04 19:15:01 +000011933 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011934 UsesZeroVector = true;
11935 continue;
11936 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011937
Dan Gohmana8665142007-06-25 16:23:39 +000011938 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011939 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011940 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11941 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011942 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011943 break;
11944 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011945
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011946 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011947 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011948 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11949 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011950
Craig Topperc0196b12014-04-14 00:51:57 +000011951 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011952 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011953 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011954 VecIn2 = ExtractedFromVec;
11955 } else {
11956 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011957 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011958 break;
11959 }
11960 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011961
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011962 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011963 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011964 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011965 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011966 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011967 unsigned Opcode = N->getOperand(i).getOpcode();
11968 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011969 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011970 continue;
11971 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011972
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011973 // Operands can also be zero.
11974 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11975 assert(UsesZeroVector &&
11976 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11977 "Unexpected node found!");
11978 Mask.push_back(NumInScalars+i);
11979 continue;
11980 }
11981
Rafael Espindolab93db662009-04-24 12:40:33 +000011982 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011983 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011984 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011985 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011986 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011987 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011988 continue;
11989 }
11990
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011991 // Otherwise, use InIdx + InputVecSize
11992 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011993 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011994
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011995 // Avoid introducing illegal shuffles with zero.
11996 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11997 return SDValue();
11998
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011999 // We can't generate a shuffle node with mismatched input and output types.
12000 // Attempt to transform a single input vector to the correct type.
12001 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000012002 // If the input vector type has a different base type to the output
12003 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000012004 EVT VTElemType = VT.getVectorElementType();
12005 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12006 (VecIn2.getNode() &&
12007 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000012008 return SDValue();
12009
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012010 // If the input vector is too small, widen it.
12011 // We only support widening of vectors which are half the size of the
12012 // output registers. For example XMM->YMM widening on X86 with AVX.
12013 EVT VecInT = VecIn1.getValueType();
12014 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000012015 // If we only have one small input, widen it by adding undef values.
12016 if (!VecIn2.getNode())
12017 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12018 DAG.getUNDEF(VecIn1.getValueType()));
12019 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12020 // If we have two small inputs of the same type, try to concat them.
12021 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12022 VecIn2 = SDValue(nullptr, 0);
12023 } else
12024 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012025 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12026 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000012027 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000012028 // If the zero vector was used, we can not split the vector,
12029 // since we'd need 3 inputs.
12030 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000012031 return SDValue();
12032
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012033 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12034 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012035
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012036 // Try to replace VecIn1 with two extract_subvectors
12037 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012038 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000012039 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012040 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000012041 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000012042 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000012043 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000012044 }
12045
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000012046 if (UsesZeroVector)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000012047 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12048 DAG.getConstantFP(0.0, dl, VT);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000012049 else
12050 // If VecIn2 is unused then change it to undef.
12051 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000012052
Nadav Rotem841c9a82012-09-20 08:53:31 +000012053 // Check that we were able to transform all incoming values to the same
12054 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000012055 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12056 VecIn1.getValueType() != VT)
12057 return SDValue();
12058
Dan Gohmana8665142007-06-25 16:23:39 +000012059 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012060 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000012061 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000012062 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000012063 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000012064 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012065
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012066 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000012067}
12068
Ahmed Bougachac984b902015-04-16 02:39:14 +000012069static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12070 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12071 EVT OpVT = N->getOperand(0).getValueType();
12072
12073 // If the operands are legal vectors, leave them alone.
12074 if (TLI.isTypeLegal(OpVT))
12075 return SDValue();
12076
12077 SDLoc DL(N);
12078 EVT VT = N->getValueType(0);
12079 SmallVector<SDValue, 8> Ops;
12080
12081 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12082 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12083
12084 // Keep track of what we encounter.
12085 bool AnyInteger = false;
12086 bool AnyFP = false;
12087 for (const SDValue &Op : N->ops()) {
12088 if (ISD::BITCAST == Op.getOpcode() &&
12089 !Op.getOperand(0).getValueType().isVector())
12090 Ops.push_back(Op.getOperand(0));
12091 else if (ISD::UNDEF == Op.getOpcode())
12092 Ops.push_back(ScalarUndef);
12093 else
12094 return SDValue();
12095
12096 // Note whether we encounter an integer or floating point scalar.
12097 // If it's neither, bail out, it could be something weird like x86mmx.
12098 EVT LastOpVT = Ops.back().getValueType();
12099 if (LastOpVT.isFloatingPoint())
12100 AnyFP = true;
12101 else if (LastOpVT.isInteger())
12102 AnyInteger = true;
12103 else
12104 return SDValue();
12105 }
12106
12107 // If any of the operands is a floating point scalar bitcast to a vector,
Simon Pilgrim096cccd2015-06-13 12:57:36 +000012108 // use floating point types throughout, and bitcast everything.
Ahmed Bougachac984b902015-04-16 02:39:14 +000012109 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12110 if (AnyFP) {
12111 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12112 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12113 if (AnyInteger) {
12114 for (SDValue &Op : Ops) {
12115 if (Op.getValueType() == SVT)
12116 continue;
12117 if (Op.getOpcode() == ISD::UNDEF)
12118 Op = ScalarUndef;
12119 else
12120 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12121 }
12122 }
12123 }
12124
12125 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12126 VT.getSizeInBits() / SVT.getSizeInBits());
12127 return DAG.getNode(ISD::BITCAST, DL, VT,
12128 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12129}
12130
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012131SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000012132 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12133 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12134 // inputs come from at most two distinct vectors, turn this into a shuffle
12135 // node.
12136
12137 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000012138 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000012139 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000012140
Nadav Rotem01892102012-07-14 21:30:27 +000012141 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012142 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000012143 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012144 return DAG.getUNDEF(VT);
12145
Ahmed Bougachadf437372015-04-09 20:04:47 +000012146 // Optimize concat_vectors where all but the first of the vectors are undef.
12147 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12148 return Op.getOpcode() == ISD::UNDEF;
12149 })) {
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012150 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000012151 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012152
12153 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12154 if (In->getOpcode() == ISD::BITCAST &&
12155 !In->getOperand(0)->getValueType(0).isVector()) {
12156 SDValue Scalar = In->getOperand(0);
Ahmed Bougachadf437372015-04-09 20:04:47 +000012157
12158 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12159 // look through the trunc so we can still do the transform:
12160 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12161 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12162 !TLI.isTypeLegal(Scalar.getValueType()) &&
12163 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12164 Scalar = Scalar->getOperand(0);
12165
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012166 EVT SclTy = Scalar->getValueType(0);
12167
12168 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12169 return SDValue();
12170
12171 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12172 VT.getSizeInBits() / SclTy.getSizeInBits());
12173 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12174 return SDValue();
12175
12176 SDLoc dl = SDLoc(N);
12177 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12178 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12179 }
12180 }
Nadav Rotem01892102012-07-14 21:30:27 +000012181
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012182 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12183 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000012184 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12185 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012186 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12187 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12188 };
12189 bool AllBuildVectorsOrUndefs =
12190 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12191 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000012192 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012193 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000012194
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012195 EVT MinVT = SVT;
12196 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000012197 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012198 // operand types. Get the smallest type and truncate all operands to it.
12199 bool FoundMinVT = false;
12200 for (const SDValue &Op : N->ops())
12201 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12202 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12203 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12204 FoundMinVT = true;
12205 }
12206 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000012207 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000012208
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012209 for (const SDValue &Op : N->ops()) {
12210 EVT OpVT = Op.getValueType();
12211 unsigned NumElts = OpVT.getVectorNumElements();
12212
12213 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000012214 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012215
12216 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12217 if (SVT.isFloatingPoint()) {
12218 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000012219 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012220 } else {
12221 for (unsigned i = 0; i != NumElts; ++i)
12222 Opnds.push_back(
12223 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12224 }
12225 }
12226 }
12227
12228 assert(VT.getVectorNumElements() == Opnds.size() &&
12229 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000012230 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000012231 }
12232
Ahmed Bougachac984b902015-04-16 02:39:14 +000012233 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12234 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12235 return V;
12236
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012237 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12238 // nodes often generate nop CONCAT_VECTOR nodes.
12239 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12240 // place the incoming vectors at the exact same location.
12241 SDValue SingleSource = SDValue();
12242 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12243
12244 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12245 SDValue Op = N->getOperand(i);
12246
12247 if (Op.getOpcode() == ISD::UNDEF)
12248 continue;
12249
12250 // Check if this is the identity extract:
12251 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12252 return SDValue();
12253
12254 // Find the single incoming vector for the extract_subvector.
12255 if (SingleSource.getNode()) {
12256 if (Op.getOperand(0) != SingleSource)
12257 return SDValue();
12258 } else {
12259 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000012260
12261 // Check the source type is the same as the type of the result.
12262 // If not, this concat may extend the vector, so we can not
12263 // optimize it away.
12264 if (SingleSource.getValueType() != N->getValueType(0))
12265 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012266 }
12267
12268 unsigned IdentityIndex = i * PartNumElem;
12269 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12270 // The extract index must be constant.
12271 if (!CS)
12272 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000012273
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012274 // Check that we are reading from the identity index.
12275 if (CS->getZExtValue() != IdentityIndex)
12276 return SDValue();
12277 }
12278
12279 if (SingleSource.getNode())
12280 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000012281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012282 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000012283}
12284
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000012285SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12286 EVT NVT = N->getValueType(0);
12287 SDValue V = N->getOperand(0);
12288
Michael Liao7a442c802012-10-17 20:48:33 +000012289 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12290 // Combine:
12291 // (extract_subvec (concat V1, V2, ...), i)
12292 // Into:
12293 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000012294 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12295 // type.
Michael Liao2c235802012-10-19 03:17:00 +000012296 if (V->getOperand(0).getValueType() != NVT)
12297 return SDValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +000012298 unsigned Idx = N->getConstantOperandVal(1);
Michael Liao7a442c802012-10-17 20:48:33 +000012299 unsigned NumElems = NVT.getVectorNumElements();
12300 assert((Idx % NumElems) == 0 &&
12301 "IDX in concat is not a multiple of the result vector length.");
12302 return V->getOperand(Idx / NumElems);
12303 }
12304
Michael Liaobb05a1d2013-03-25 23:47:35 +000012305 // Skip bitcasting
12306 if (V->getOpcode() == ISD::BITCAST)
12307 V = V.getOperand(0);
12308
12309 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012310 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000012311 // Handle only simple case where vector being inserted and vector
12312 // being extracted are of same type, and are half size of larger vectors.
12313 EVT BigVT = V->getOperand(0).getValueType();
12314 EVT SmallVT = V->getOperand(1).getValueType();
12315 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12316 return SDValue();
12317
12318 // Only handle cases where both indexes are constants with the same type.
12319 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12320 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12321
12322 if (InsIdx && ExtIdx &&
12323 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12324 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12325 // Combine:
12326 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12327 // Into:
12328 // indices are equal or bit offsets are equal => V1
12329 // otherwise => (extract_subvec V1, ExtIdx)
12330 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12331 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12332 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12333 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12334 DAG.getNode(ISD::BITCAST, dl,
12335 N->getOperand(0).getValueType(),
12336 V->getOperand(0)), N->getOperand(1));
12337 }
12338 }
12339
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000012340 return SDValue();
12341}
12342
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012343static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12344 SDValue V, SelectionDAG &DAG) {
12345 SDLoc DL(V);
12346 EVT VT = V.getValueType();
12347
12348 switch (V.getOpcode()) {
12349 default:
12350 return V;
12351
12352 case ISD::CONCAT_VECTORS: {
12353 EVT OpVT = V->getOperand(0).getValueType();
12354 int OpSize = OpVT.getVectorNumElements();
12355 SmallBitVector OpUsedElements(OpSize, false);
12356 bool FoundSimplification = false;
12357 SmallVector<SDValue, 4> NewOps;
12358 NewOps.reserve(V->getNumOperands());
12359 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12360 SDValue Op = V->getOperand(i);
12361 bool OpUsed = false;
12362 for (int j = 0; j < OpSize; ++j)
12363 if (UsedElements[i * OpSize + j]) {
12364 OpUsedElements[j] = true;
12365 OpUsed = true;
12366 }
12367 NewOps.push_back(
12368 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12369 : DAG.getUNDEF(OpVT));
12370 FoundSimplification |= Op == NewOps.back();
12371 OpUsedElements.reset();
12372 }
12373 if (FoundSimplification)
12374 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12375 return V;
12376 }
12377
12378 case ISD::INSERT_SUBVECTOR: {
12379 SDValue BaseV = V->getOperand(0);
12380 SDValue SubV = V->getOperand(1);
12381 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12382 if (!IdxN)
12383 return V;
12384
12385 int SubSize = SubV.getValueType().getVectorNumElements();
12386 int Idx = IdxN->getZExtValue();
12387 bool SubVectorUsed = false;
12388 SmallBitVector SubUsedElements(SubSize, false);
12389 for (int i = 0; i < SubSize; ++i)
12390 if (UsedElements[i + Idx]) {
12391 SubVectorUsed = true;
12392 SubUsedElements[i] = true;
12393 UsedElements[i + Idx] = false;
12394 }
12395
12396 // Now recurse on both the base and sub vectors.
12397 SDValue SimplifiedSubV =
12398 SubVectorUsed
12399 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12400 : DAG.getUNDEF(SubV.getValueType());
12401 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12402 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12403 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12404 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12405 return V;
12406 }
12407 }
12408}
12409
12410static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12411 SDValue N1, SelectionDAG &DAG) {
12412 EVT VT = SVN->getValueType(0);
12413 int NumElts = VT.getVectorNumElements();
12414 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12415 for (int M : SVN->getMask())
12416 if (M >= 0 && M < NumElts)
12417 N0UsedElements[M] = true;
12418 else if (M >= NumElts)
12419 N1UsedElements[M - NumElts] = true;
12420
12421 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12422 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12423 if (S0 == N0 && S1 == N1)
12424 return SDValue();
12425
12426 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12427}
12428
Mehdi Amini37f316a2015-01-17 01:35:56 +000012429// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12430// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012431static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12432 EVT VT = N->getValueType(0);
12433 unsigned NumElts = VT.getVectorNumElements();
12434
12435 SDValue N0 = N->getOperand(0);
12436 SDValue N1 = N->getOperand(1);
12437 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12438
12439 SmallVector<SDValue, 4> Ops;
12440 EVT ConcatVT = N0.getOperand(0).getValueType();
12441 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12442 unsigned NumConcats = NumElts / NumElemsPerConcat;
12443
Mehdi Amini37f316a2015-01-17 01:35:56 +000012444 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12445 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12446 // half vector elements.
12447 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12448 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12449 SVN->getMask().end(), [](int i) { return i == -1; })) {
12450 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12451 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12452 N1 = DAG.getUNDEF(ConcatVT);
12453 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12454 }
12455
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012456 // Look at every vector that's inserted. We're looking for exact
12457 // subvector-sized copies from a concatenated vector
12458 for (unsigned I = 0; I != NumConcats; ++I) {
12459 // Make sure we're dealing with a copy.
12460 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000012461 bool AllUndef = true, NoUndef = true;
12462 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12463 if (SVN->getMaskElt(J) >= 0)
12464 AllUndef = false;
12465 else
12466 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012467 }
12468
Hao Liubc601962013-05-13 02:07:05 +000012469 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000012470 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12471 return SDValue();
12472
12473 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12474 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12475 return SDValue();
12476
12477 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12478 if (FirstElt < N0.getNumOperands())
12479 Ops.push_back(N0.getOperand(FirstElt));
12480 else
12481 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12482
12483 } else if (AllUndef) {
12484 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12485 } else { // Mixed with general masks and undefs, can't do optimization.
12486 return SDValue();
12487 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012488 }
12489
Craig Topper48d114b2014-04-26 18:35:24 +000012490 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012491}
12492
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012493SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012494 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012495 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012496
Mon P Wang25f01062008-11-10 04:46:22 +000012497 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000012498 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000012499
Craig Topper5894fe42012-04-09 05:16:56 +000012500 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000012501
Craig Topper279c77b2012-01-04 08:07:43 +000012502 // Canonicalize shuffle undef, undef -> undef
12503 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12504 return DAG.getUNDEF(VT);
12505
12506 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12507
12508 // Canonicalize shuffle v, v -> v, undef
12509 if (N0 == N1) {
12510 SmallVector<int, 8> NewMask;
12511 for (unsigned i = 0; i != NumElts; ++i) {
12512 int Idx = SVN->getMaskElt(i);
12513 if (Idx >= (int)NumElts) Idx -= NumElts;
12514 NewMask.push_back(Idx);
12515 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012516 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012517 &NewMask[0]);
12518 }
12519
12520 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12521 if (N0.getOpcode() == ISD::UNDEF) {
12522 SmallVector<int, 8> NewMask;
12523 for (unsigned i = 0; i != NumElts; ++i) {
12524 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000012525 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000012526 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000012527 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000012528 else
12529 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000012530 }
12531 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000012532 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012533 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012534 &NewMask[0]);
12535 }
12536
12537 // Remove references to rhs if it is undef
12538 if (N1.getOpcode() == ISD::UNDEF) {
12539 bool Changed = false;
12540 SmallVector<int, 8> NewMask;
12541 for (unsigned i = 0; i != NumElts; ++i) {
12542 int Idx = SVN->getMaskElt(i);
12543 if (Idx >= (int)NumElts) {
12544 Idx = -1;
12545 Changed = true;
12546 }
12547 NewMask.push_back(Idx);
12548 }
12549 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000012550 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000012551 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000012552
Bob Wilsonf63da122010-10-28 17:06:14 +000012553 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012554 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000012555 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000012556 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000012557
Dan Gohmana8665142007-06-25 16:23:39 +000012558 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000012559 // not the number of vector elements, look through it. Be careful not to
12560 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000012561 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012562 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000012563 if (ConvInput.getValueType().isVector() &&
12564 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000012565 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000012566 }
12567
Dan Gohmana8665142007-06-25 16:23:39 +000012568 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000012569 assert(V->getNumOperands() == NumElts &&
12570 "BUILD_VECTOR has wrong number of operands");
12571 SDValue Base;
12572 bool AllSame = true;
12573 for (unsigned i = 0; i != NumElts; ++i) {
12574 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12575 Base = V->getOperand(i);
12576 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000012577 }
Evan Cheng7c970b92006-07-21 08:25:53 +000012578 }
Bob Wilsonf63da122010-10-28 17:06:14 +000012579 // Splat of <u, u, u, u>, return <u, u, u, u>
12580 if (!Base.getNode())
12581 return N0;
12582 for (unsigned i = 0; i != NumElts; ++i) {
12583 if (V->getOperand(i) != Base) {
12584 AllSame = false;
12585 break;
12586 }
12587 }
12588 // Splat of <x, x, x, x>, return <x, x, x, x>
12589 if (AllSame)
12590 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012591
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012592 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012593 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012594 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12595 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12596 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012597
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012598 // We may have jumped through bitcasts, so the type of the
12599 // BUILD_VECTOR may not match the type of the shuffle.
12600 if (V->getValueType(0) != VT)
Sanjay Pateld95dd9e2015-03-26 16:55:17 +000012601 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012602 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000012603 }
12604 }
Nadav Rotemb0783502012-04-01 19:31:22 +000012605
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012606 // There are various patterns used to build up a vector from smaller vectors,
12607 // subvectors, or elements. Scan chains of these and replace unused insertions
12608 // or components with undef.
12609 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12610 return S;
12611
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012612 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12613 Level < AfterLegalizeVectorOps &&
12614 (N1.getOpcode() == ISD::UNDEF ||
12615 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12616 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12617 SDValue V = partitionShuffleOfConcats(N, DAG);
12618
12619 if (V.getNode())
12620 return V;
12621 }
12622
Simon Pilgrimed2ba33ba2015-04-03 10:02:21 +000012623 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12624 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12625 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12626 SmallVector<SDValue, 8> Ops;
12627 for (int M : SVN->getMask()) {
12628 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12629 if (M >= 0) {
12630 int Idx = M % NumElts;
12631 SDValue &S = (M < (int)NumElts ? N0 : N1);
12632 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12633 Op = S.getOperand(Idx);
12634 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12635 if (Idx == 0)
12636 Op = S.getOperand(0);
12637 } else {
12638 // Operand can't be combined - bail out.
12639 break;
12640 }
12641 }
12642 Ops.push_back(Op);
12643 }
12644 if (Ops.size() == VT.getVectorNumElements()) {
12645 // BUILD_VECTOR requires all inputs to be of the same type, find the
12646 // maximum type and extend them all.
12647 EVT SVT = VT.getScalarType();
12648 if (SVT.isInteger())
12649 for (SDValue &Op : Ops)
12650 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12651 if (SVT != VT.getScalarType())
12652 for (SDValue &Op : Ops)
12653 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12654 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12655 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12656 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12657 }
12658 }
12659
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012660 // If this shuffle only has a single input that is a bitcasted shuffle,
12661 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12662 // back to their original types.
12663 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12664 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12665 TLI.isTypeLegal(VT)) {
12666
12667 // Peek through the bitcast only if there is one user.
12668 SDValue BC0 = N0;
12669 while (BC0.getOpcode() == ISD::BITCAST) {
12670 if (!BC0.hasOneUse())
12671 break;
12672 BC0 = BC0.getOperand(0);
12673 }
12674
12675 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12676 if (Scale == 1)
12677 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12678
12679 SmallVector<int, 8> NewMask;
12680 for (int M : Mask)
12681 for (int s = 0; s != Scale; ++s)
12682 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12683 return NewMask;
12684 };
12685
12686 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12687 EVT SVT = VT.getScalarType();
12688 EVT InnerVT = BC0->getValueType(0);
12689 EVT InnerSVT = InnerVT.getScalarType();
12690
12691 // Determine which shuffle works with the smaller scalar type.
12692 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12693 EVT ScaleSVT = ScaleVT.getScalarType();
12694
12695 if (TLI.isTypeLegal(ScaleVT) &&
12696 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12697 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12698
12699 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12700 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12701
12702 // Scale the shuffle masks to the smaller scalar type.
12703 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12704 SmallVector<int, 8> InnerMask =
12705 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12706 SmallVector<int, 8> OuterMask =
12707 ScaleShuffleMask(SVN->getMask(), OuterScale);
12708
12709 // Merge the shuffle masks.
12710 SmallVector<int, 8> NewMask;
12711 for (int M : OuterMask)
12712 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12713
12714 // Test for shuffle mask legality over both commutations.
12715 SDValue SV0 = BC0->getOperand(0);
12716 SDValue SV1 = BC0->getOperand(1);
12717 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12718 if (!LegalMask) {
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012719 std::swap(SV0, SV1);
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012720 ShuffleVectorSDNode::commuteMask(NewMask);
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012721 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12722 }
12723
12724 if (LegalMask) {
12725 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12726 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12727 return DAG.getNode(
12728 ISD::BITCAST, SDLoc(N), VT,
12729 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12730 }
12731 }
12732 }
12733 }
12734
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012735 // Canonicalize shuffles according to rules:
12736 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12737 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12738 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012739 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012740 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12741 TLI.isTypeLegal(VT)) {
12742 // The incoming shuffle must be of the same type as the result of the
12743 // current shuffle.
12744 assert(N1->getOperand(0).getValueType() == VT &&
12745 "Shuffle types don't match");
12746
12747 SDValue SV0 = N1->getOperand(0);
12748 SDValue SV1 = N1->getOperand(1);
12749 bool HasSameOp0 = N0 == SV0;
12750 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12751 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12752 // Commute the operands of this shuffle so that next rule
12753 // will trigger.
12754 return DAG.getCommutedVectorShuffle(*SVN);
12755 }
12756
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012757 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012758 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12759 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12760 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012761 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012762 // Only fold if this shuffle is the only user of the other shuffle.
12763 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12764 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012765 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12766
12767 // The incoming shuffle must be of the same type as the result of the
12768 // current shuffle.
12769 assert(OtherSV->getOperand(0).getValueType() == VT &&
12770 "Shuffle types don't match");
12771
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012772 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012773 SmallVector<int, 4> Mask;
12774 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12775 // operand, and SV1 as the second operand.
12776 for (unsigned i = 0; i != NumElts; ++i) {
12777 int Idx = SVN->getMaskElt(i);
12778 if (Idx < 0) {
12779 // Propagate Undef.
12780 Mask.push_back(Idx);
12781 continue;
12782 }
12783
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012784 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012785 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012786 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12787 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012788 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012789 if (Idx < 0) {
12790 // Propagate Undef.
12791 Mask.push_back(Idx);
12792 continue;
12793 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012794
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012795 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12796 : OtherSV->getOperand(1);
12797 } else {
12798 // This shuffle index references an element within N1.
12799 CurrentVec = N1;
12800 }
12801
12802 // Simple case where 'CurrentVec' is UNDEF.
12803 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12804 Mask.push_back(-1);
12805 continue;
12806 }
12807
12808 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12809 // will be the first or second operand of the combined shuffle.
12810 Idx = Idx % NumElts;
12811 if (!SV0.getNode() || SV0 == CurrentVec) {
12812 // Ok. CurrentVec is the left hand side.
12813 // Update the mask accordingly.
12814 SV0 = CurrentVec;
12815 Mask.push_back(Idx);
12816 continue;
12817 }
12818
12819 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12820 if (SV1.getNode() && SV1 != CurrentVec)
12821 return SDValue();
12822
12823 // Ok. CurrentVec is the right hand side.
12824 // Update the mask accordingly.
12825 SV1 = CurrentVec;
12826 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012827 }
12828
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012829 // Check if all indices in Mask are Undef. In case, propagate Undef.
12830 bool isUndefMask = true;
12831 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12832 isUndefMask &= Mask[i] < 0;
12833
12834 if (isUndefMask)
12835 return DAG.getUNDEF(VT);
12836
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012837 if (!SV0.getNode())
12838 SV0 = DAG.getUNDEF(VT);
12839 if (!SV1.getNode())
12840 SV1 = DAG.getUNDEF(VT);
12841
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012842 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012843 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012844 ShuffleVectorSDNode::commuteMask(Mask);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012845
12846 if (!TLI.isShuffleMaskLegal(Mask, VT))
12847 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012848
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012849 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12850 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12851 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12852 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012853 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012854
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012855 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12856 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12857 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12858 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012859 }
12860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012861 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012862}
12863
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012864SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12865 SDValue InVal = N->getOperand(0);
12866 EVT VT = N->getValueType(0);
12867
12868 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12869 // with a VECTOR_SHUFFLE.
12870 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12871 SDValue InVec = InVal->getOperand(0);
12872 SDValue EltNo = InVal->getOperand(1);
12873
12874 // FIXME: We could support implicit truncation if the shuffle can be
12875 // scaled to a smaller vector scalar type.
12876 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12877 if (C0 && VT == InVec.getValueType() &&
12878 VT.getScalarType() == InVal.getValueType()) {
12879 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12880 int Elt = C0->getZExtValue();
12881 NewMask[0] = Elt;
12882
12883 if (TLI.isShuffleMaskLegal(NewMask, VT))
12884 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12885 NewMask);
12886 }
12887 }
12888
12889 return SDValue();
12890}
12891
Manman Ren413a6cb2014-01-31 01:10:35 +000012892SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12893 SDValue N0 = N->getOperand(0);
12894 SDValue N2 = N->getOperand(2);
12895
12896 // If the input vector is a concatenation, and the insert replaces
12897 // one of the halves, we can optimize into a single concat_vectors.
12898 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12899 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12900 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12901 EVT VT = N->getValueType(0);
12902
12903 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12904 // (concat_vectors Z, Y)
12905 if (InsIdx == 0)
12906 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12907 N->getOperand(1), N0.getOperand(1));
12908
12909 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12910 // (concat_vectors X, Z)
12911 if (InsIdx == VT.getVectorNumElements()/2)
12912 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12913 N0.getOperand(0), N->getOperand(1));
12914 }
12915
12916 return SDValue();
12917}
12918
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +000012919SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12920 SDValue N0 = N->getOperand(0);
12921
12922 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12923 if (N0->getOpcode() == ISD::FP16_TO_FP)
12924 return N0->getOperand(0);
12925
12926 return SDValue();
12927}
12928
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012929/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12930/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012931/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012932/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012933SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012934 EVT VT = N->getValueType(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012935 SDValue LHS = N->getOperand(0);
12936 SDValue RHS = N->getOperand(1);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012937 SDLoc dl(N);
Craig Toppere5893f62012-04-09 05:59:53 +000012938
Simon Pilgrim096cccd2015-06-13 12:57:36 +000012939 // Make sure we're not running after operation legalization where it
Simon Pilgrim257849f2015-03-17 22:19:08 +000012940 // may have custom lowered the vector shuffles.
12941 if (LegalOperations)
12942 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012943
Simon Pilgrim257849f2015-03-17 22:19:08 +000012944 if (N->getOpcode() != ISD::AND)
12945 return SDValue();
12946
12947 if (RHS.getOpcode() == ISD::BITCAST)
12948 RHS = RHS.getOperand(0);
12949
12950 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12951 SmallVector<int, 8> Indices;
12952 unsigned NumElts = RHS.getNumOperands();
12953
12954 for (unsigned i = 0; i != NumElts; ++i) {
12955 SDValue Elt = RHS.getOperand(i);
Matthias Braun03312192015-05-19 00:25:20 +000012956 if (isAllOnesConstant(Elt))
12957 Indices.push_back(i);
12958 else if (isNullConstant(Elt))
12959 Indices.push_back(NumElts+i);
12960 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012961 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012962 }
Simon Pilgrim257849f2015-03-17 22:19:08 +000012963
12964 // Let's see if the target supports this vector_shuffle.
12965 EVT RVT = RHS.getValueType();
12966 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12967 return SDValue();
12968
12969 // Return the new VECTOR_SHUFFLE node.
12970 EVT EltVT = RVT.getVectorElementType();
12971 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000012972 DAG.getConstant(0, dl, EltVT));
12973 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012974 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12975 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12976 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012977 }
Bill Wendling31b50992009-01-30 23:59:18 +000012978
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012979 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012980}
12981
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012982/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012983SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012984 assert(N->getValueType(0).isVector() &&
12985 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012987 SDValue LHS = N->getOperand(0);
12988 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012989
12990 if (SDValue Shuffle = XformToShuffleWithZero(N))
12991 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012992
Dan Gohmana8665142007-06-25 16:23:39 +000012993 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012994 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012995 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012996 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012997 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012998 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12999 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000013000 return SDValue();
13001
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013002 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000013003 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013004 SDValue LHSOp = LHS.getOperand(i);
13005 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000013006
Evan Cheng64d28462006-05-31 06:08:35 +000013007 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000013008 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13009 N->getOpcode() == ISD::FDIV) {
Matthias Braun1505efb2015-05-18 23:07:27 +000013010 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
Andrea Di Biagioeb331342015-06-05 10:29:55 +000013011 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000013012 break;
13013 }
Bill Wendling31b50992009-01-30 23:59:18 +000013014
Bob Wilson54081442010-12-17 23:06:49 +000013015 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000013016 EVT RVT = RHSOp.getValueType();
13017 if (RVT != VT) {
13018 // Integer BUILD_VECTOR operands may have types larger than the element
13019 // size (e.g., when the element type is not legal). Prior to type
13020 // legalization, the types may not match between the two BUILD_VECTORS.
13021 // Truncate one of the operands to make them match.
13022 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013023 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000013024 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013025 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000013026 VT = RVT;
13027 }
13028 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000013029 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000013030 LHSOp, RHSOp);
13031 if (FoldOp.getOpcode() != ISD::UNDEF &&
13032 FoldOp.getOpcode() != ISD::Constant &&
13033 FoldOp.getOpcode() != ISD::ConstantFP)
13034 break;
13035 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013036 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000013037 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013038
Bob Wilson54081442010-12-17 23:06:49 +000013039 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000013040 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000013041 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013042
Andrea Di Biagio446a5272014-05-30 23:17:53 +000013043 // Type legalization might introduce new shuffles in the DAG.
13044 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13045 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13046 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13047 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13048 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13049 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13050 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13051 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13052
13053 if (SVN0->getMask().equals(SVN1->getMask())) {
13054 EVT VT = N->getValueType(0);
13055 SDValue UndefVector = LHS.getOperand(1);
13056 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13057 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013058 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000013059 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13060 &SVN0->getMask()[0]);
13061 }
13062 }
13063
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013064 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000013065}
13066
Andrew Trickef9de2a2013-05-25 02:42:55 +000013067SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000013068 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000013069 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000013070
Bill Wendling31b50992009-01-30 23:59:18 +000013071 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000013072 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000013073
Nate Begeman2042aa52005-10-08 00:29:44 +000013074 // If we got a simplified select_cc node back from SimplifySelectCC, then
13075 // break it down into a new SETCC node, and a new SELECT node, and then return
13076 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000013077 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000013078 // Check to see if we got a select_cc back (to turn into setcc/select).
13079 // Otherwise, just return whatever node we got back, like fabs.
13080 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013081 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013082 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000013083 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000013084 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013085 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000013086 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13087 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000013088 }
Bill Wendling31b50992009-01-30 23:59:18 +000013089
Nate Begeman2042aa52005-10-08 00:29:44 +000013090 return SCC;
13091 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013092 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013093}
13094
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013095/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13096/// being selected between, see if we can simplify the select. Callers of this
13097/// should assume that TheSelect is deleted if this returns true. As such, they
13098/// should return the appropriate thing (e.g. the node) back to the top-level of
13099/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013100bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013101 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013102
Tom Stellard69a7b912015-04-20 19:38:27 +000013103 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13104 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13105 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13106 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13107 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13108 SDValue Sqrt = RHS;
13109 ISD::CondCode CC;
13110 SDValue CmpLHS;
13111 const ConstantFPSDNode *NegZero = nullptr;
13112
13113 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13114 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13115 CmpLHS = TheSelect->getOperand(0);
13116 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13117 } else {
13118 // SELECT or VSELECT
13119 SDValue Cmp = TheSelect->getOperand(0);
13120 if (Cmp.getOpcode() == ISD::SETCC) {
13121 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13122 CmpLHS = Cmp.getOperand(0);
13123 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13124 }
13125 }
13126 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13127 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13128 CC == ISD::SETULT || CC == ISD::SETLT)) {
13129 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13130 CombineTo(TheSelect, Sqrt);
13131 return true;
13132 }
13133 }
13134 }
Nadav Rotema49a02a2011-02-11 19:57:47 +000013135 // Cannot simplify select with vector condition
13136 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13137
Chris Lattner6c14c352005-10-18 06:04:22 +000013138 // If this is a select from two identical things, try to pull the operation
13139 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000013140 if (LHS.getOpcode() != RHS.getOpcode() ||
13141 !LHS.hasOneUse() || !RHS.hasOneUse())
13142 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013143
Chris Lattner254c4452010-09-21 15:46:59 +000013144 // If this is a load and the token chain is identical, replace the select
13145 // of two loads with a load through a select of the address to load from.
13146 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13147 // constants have been dropped into the constant pool.
13148 if (LHS.getOpcode() == ISD::LOAD) {
13149 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13150 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000013151
Chris Lattner254c4452010-09-21 15:46:59 +000013152 // Token chains must be identical.
13153 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000013154 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000013155 LLD->isVolatile() || RLD->isVolatile() ||
Hal Finkel0d49cf22015-04-22 11:32:25 +000013156 // FIXME: If either is a pre/post inc/dec load,
13157 // we'd need to split out the address adjustment.
13158 LLD->isIndexed() || RLD->isIndexed() ||
Chris Lattner254c4452010-09-21 15:46:59 +000013159 // If this is an EXTLOAD, the VT's must match.
13160 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000013161 // If this is an EXTLOAD, the kind of extension must match.
13162 (LLD->getExtensionType() != RLD->getExtensionType() &&
13163 // The only exception is if one of the extensions is anyext.
13164 LLD->getExtensionType() != ISD::EXTLOAD &&
13165 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000013166 // FIXME: this discards src value information. This is
13167 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000013168 // both potential memory locations. Since we are discarding
13169 // src value info, don't do the transformation if the memory
13170 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000013171 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000013172 RLD->getPointerInfo().getAddrSpace() != 0 ||
13173 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13174 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000013175 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013176
Chris Lattnere3267522010-09-21 15:58:55 +000013177 // Check that the select condition doesn't reach either load. If so,
13178 // folding this will induce a cycle into the DAG. If not, this is safe to
13179 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000013180 SDValue Addr;
13181 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000013182 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13183 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13184 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13185 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000013186 // The loads must not depend on one another.
13187 if (LLD->isPredecessorOf(RLD) ||
13188 RLD->isPredecessorOf(LLD))
13189 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000013190 Addr = DAG.getSelect(SDLoc(TheSelect),
13191 LLD->getBasePtr().getValueType(),
13192 TheSelect->getOperand(0), LLD->getBasePtr(),
13193 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000013194 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000013195 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13196 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13197
13198 if ((LLD->hasAnyUseOfValue(1) &&
13199 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000013200 (RLD->hasAnyUseOfValue(1) &&
13201 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000013202 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013203
Andrew Trickef9de2a2013-05-25 02:42:55 +000013204 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000013205 LLD->getBasePtr().getValueType(),
13206 TheSelect->getOperand(0),
13207 TheSelect->getOperand(1),
13208 LLD->getBasePtr(), RLD->getBasePtr(),
13209 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000013210 }
13211
Chris Lattnere3267522010-09-21 15:58:55 +000013212 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000013213 // It is safe to replace the two loads if they have different alignments,
13214 // but the new load must be the minimum (most restrictive) alignment of the
13215 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000013216 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000013217 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000013218 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13219 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000013220 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000013221 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000013222 LLD->getChain(), Addr, MachinePointerInfo(),
13223 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000013224 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000013225 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000013226 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13227 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000013228 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000013229 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000013230 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000013231 LLD->getChain(), Addr, MachinePointerInfo(),
13232 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000013233 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000013234 }
Chris Lattnere3267522010-09-21 15:58:55 +000013235
13236 // Users of the select now use the result of the load.
13237 CombineTo(TheSelect, Load);
13238
13239 // Users of the old loads now use the new load's chain. We know the
13240 // old-load value is dead now.
13241 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13242 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13243 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000013244 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013245
Chris Lattner6c14c352005-10-18 06:04:22 +000013246 return false;
13247}
13248
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013249/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000013250/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000013251SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013252 SDValue N2, SDValue N3,
13253 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000013254 // (x ? y : y) -> y.
13255 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000013256
Owen Anderson53aa7a92009-08-10 22:56:29 +000013257 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000013258 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13259 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013260
13261 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000013262 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000013263 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013264 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013265
Matthias Braun1505efb2015-05-18 23:07:27 +000013266 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13267 // fold select_cc true, x, y -> x
13268 // fold select_cc false, x, y -> y
13269 return !SCCC->isNullValue() ? N2 : N3;
13270 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013271
Nate Begeman2042aa52005-10-08 00:29:44 +000013272 // Check to see if we can simplify the select into an fabs node
13273 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13274 // Allow either -0.0 or 0.0
Andrea Di Biagioeb331342015-06-05 10:29:55 +000013275 if (CFP->isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000013276 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13277 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13278 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13279 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000013280 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013281
Nate Begeman2042aa52005-10-08 00:29:44 +000013282 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13283 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13284 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13285 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000013286 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000013287 }
13288 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013289
Chris Lattner43d63772009-03-11 05:08:08 +000013290 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13291 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13292 // in it. This is a win when the constant is not otherwise available because
13293 // it replaces two constant pool loads with one. We only do this if the FP
13294 // type is known to be legal, because if it isn't, then we are before legalize
13295 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000013296 // messing with soft float) and if the ConstantFP is not legal, because if
13297 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000013298 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13299 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13300 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000013301 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000013302 TargetLowering::Legal &&
13303 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13304 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000013305 // If both constants have multiple uses, then we won't need to do an
13306 // extra load, they are likely around in registers for other users.
13307 (TV->hasOneUse() || FV->hasOneUse())) {
13308 Constant *Elts[] = {
13309 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13310 const_cast<ConstantFP*>(TV->getConstantFPValue())
13311 };
Chris Lattner229907c2011-07-18 04:54:35 +000013312 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000013313 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000013314
Chris Lattner43d63772009-03-11 05:08:08 +000013315 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000013316 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000013317 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13318 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000013319 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000013320
13321 // Get the offsets to the 0 and 1 element of the array so that we can
13322 // select between them.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013323 SDValue Zero = DAG.getIntPtrConstant(0, DL);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000013324 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013325 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
Wesley Peck527da1b2010-11-23 03:31:01 +000013326
Chris Lattner43d63772009-03-11 05:08:08 +000013327 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000013328 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000013329 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013330 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000013331 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13332 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013333 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000013334 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000013335 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013336 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000013337 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000013338 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000013339 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000013340 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013341 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013342
Nate Begeman2042aa52005-10-08 00:29:44 +000013343 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000013344 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Matthias Braun887fdfb2015-05-19 00:25:21 +000013345 if (isNullConstant(N3) && CC == ISD::SETLT &&
13346 (isNullConstant(N1) || // (a < 0) ? b : 0
13347 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000013348 EVT XType = N0.getValueType();
13349 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000013350 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000013351 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000013352 // single-bit constant.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013353 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
Dan Gohmanb72127a2008-03-13 22:13:53 +000013354 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013355 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13356 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013357 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013358 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013359 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013360 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013361
Duncan Sands11dd4242008-06-08 20:54:56 +000013362 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013363 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013364 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013365 }
Bill Wendling31b50992009-01-30 23:59:18 +000013366
13367 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013368 }
Bill Wendling31b50992009-01-30 23:59:18 +000013369
Andrew Trickef9de2a2013-05-25 02:42:55 +000013370 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013371 XType, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013372 DAG.getConstant(XType.getSizeInBits() - 1,
13373 SDLoc(N0),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013374 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013375 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013376
Duncan Sands11dd4242008-06-08 20:54:56 +000013377 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013378 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013379 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013380 }
Bill Wendling31b50992009-01-30 23:59:18 +000013381
13382 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013383 }
13384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013385
Owen Anderson3231d132010-09-22 22:58:22 +000013386 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13387 // where y is has a single bit set.
13388 // A plaintext description would be, we can turn the SELECT_CC into an AND
13389 // when the condition can be materialized as an all-ones register. Any
13390 // single bit-test can be materialized as an all-ones register with
13391 // shift-left and shift-right-arith.
13392 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
Matthias Braun1505efb2015-05-18 23:07:27 +000013393 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
Owen Anderson3231d132010-09-22 22:58:22 +000013394 SDValue AndLHS = N0->getOperand(0);
13395 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13396 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13397 // Shift the tested bit over the sign bit.
13398 APInt AndMask = ConstAndRHS->getAPIntValue();
13399 SDValue ShlAmt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013400 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013401 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013402 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013403
Owen Anderson3231d132010-09-22 22:58:22 +000013404 // Now arithmetic right shift it all the way over, so the result is either
13405 // all-ones, or zero.
13406 SDValue ShrAmt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013407 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013408 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013409 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013410
Owen Anderson3231d132010-09-22 22:58:22 +000013411 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13412 }
13413 }
13414
Nate Begeman6828ed92005-10-10 21:26:48 +000013415 // fold select C, 16, 0 -> shl C, 4
Matthias Braun1505efb2015-05-18 23:07:27 +000013416 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000013417 TLI.getBooleanContents(N0.getValueType()) ==
13418 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013419
Chris Lattnera083ffc2007-04-11 06:50:51 +000013420 // If the caller doesn't want us to simplify this into a zext of a compare,
13421 // don't do it.
Matthias Braun887fdfb2015-05-19 00:25:21 +000013422 if (NotExtCompare && N2C->isOne())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013423 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013424
Nate Begeman6828ed92005-10-10 21:26:48 +000013425 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013426 // NOTE: Don't create a SETCC if it's not legal on this target.
13427 if (!LegalOperations ||
13428 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000013429 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013430 SDValue Temp, SCC;
13431 // cast from setcc result type to select result type
13432 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000013433 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013434 N0, N1, CC);
13435 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000013436 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013437 N2.getValueType());
13438 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000013439 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013440 N2.getValueType(), SCC);
13441 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013442 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13443 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000013444 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013445 }
13446
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013447 AddToWorklist(SCC.getNode());
13448 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013449
Matthias Braun887fdfb2015-05-19 00:25:21 +000013450 if (N2C->isOne())
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013451 return Temp;
13452
13453 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000013454 return DAG.getNode(
13455 ISD::SHL, DL, N2.getValueType(), Temp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013456 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
Jack Carterd4e96152013-10-17 01:34:33 +000013457 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000013458 }
Nate Begeman6828ed92005-10-10 21:26:48 +000013459 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013460
Nate Begeman2042aa52005-10-08 00:29:44 +000013461 // Check to see if this is the equivalent of setcc
13462 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13463 // otherwise, go ahead with the folds.
Matthias Braun887fdfb2015-05-19 00:25:21 +000013464 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000013465 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013466 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000013467 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13468 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000013469 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000013470 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000013471 return Res;
13472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013473
Bill Wendling31b50992009-01-30 23:59:18 +000013474 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Matthias Braun1505efb2015-05-18 23:07:27 +000013475 if (isNullConstant(N1) && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013476 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000013477 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013478 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013479 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000013480 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013481 SDLoc(Ctlz),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013482 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000013483 }
Bill Wendling31b50992009-01-30 23:59:18 +000013484 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Matthias Braun1505efb2015-05-18 23:07:27 +000013485 if (isNullConstant(N1) && CC == ISD::SETGT) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013486 SDLoc DL(N0);
13487 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13488 XType, DAG.getConstant(0, DL, XType), N0);
13489 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000013490 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000013491 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013492 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013493 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000013494 }
Bill Wendling31b50992009-01-30 23:59:18 +000013495 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Matthias Braun03312192015-05-19 00:25:20 +000013496 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013497 SDLoc DL(N0);
13498 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13499 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013500 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013501 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13502 XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000013503 }
13504 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013505
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013506 // Check to see if this is an integer abs.
13507 // select_cc setg[te] X, 0, X, -X ->
13508 // select_cc setgt X, -1, X, -X ->
13509 // select_cc setl[te] X, 0, -X, X ->
13510 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000013511 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013512 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000013513 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013514 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13515 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13516 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13517 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13518 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13519 (N1C->isOne() && CC == ISD::SETLT)) &&
13520 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13521 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13522
Owen Anderson53aa7a92009-08-10 22:56:29 +000013523 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013524 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013525 SDLoc DL(N0);
13526 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013527 N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013528 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013529 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013530 SDValue Add = DAG.getNode(ISD::ADD, DL,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013531 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013532 AddToWorklist(Shift.getNode());
13533 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013534 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000013535 }
13536 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013538 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013539}
13540
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013541/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000013542SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013543 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000013544 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013545 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000013546 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000013547 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000013548}
13549
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013550/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000013551/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000013552/// by a magic number.
13553/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013554SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013555 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13556 if (!C)
13557 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013558
13559 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013560 if (C->isNullValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013561 return SDValue();
13562
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013563 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013564 SDValue S =
13565 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013566
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013567 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013568 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013569 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013570}
13571
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013572/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13573/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000013574SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13575 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13576 if (!C)
13577 return SDValue();
13578
13579 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013580 if (C->isNullValue())
Chad Rosier17020f92014-07-23 14:57:52 +000013581 return SDValue();
13582
13583 std::vector<SDNode *> Built;
13584 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13585
13586 for (SDNode *N : Built)
13587 AddToWorklist(N);
13588 return S;
13589}
13590
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013591/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13592/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000013593/// number.
13594/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013595SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013596 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13597 if (!C)
13598 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013599
13600 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013601 if (C->isNullValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013602 return SDValue();
13603
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013604 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013605 SDValue S =
13606 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000013607
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013608 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013609 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013610 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013611}
13612
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013613SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13614 if (Level >= AfterLegalizeDAG)
13615 return SDValue();
13616
Sanjay Patelb67bd262014-09-21 15:19:15 +000013617 // Expose the DAG combiner to the target combiner implementations.
13618 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000013619
Sanjay Patelab7f4602014-09-30 20:44:23 +000013620 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000013621 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000013622 if (Iterations) {
13623 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13624 // For the reciprocal, we need to find the zero of the function:
13625 // F(X) = A X - 1 [which has a zero at X = 1/A]
13626 // =>
13627 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13628 // does not require additional intermediate precision]
13629 EVT VT = Op.getValueType();
13630 SDLoc DL(Op);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013631 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013632
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013633 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013634
Sanjay Patelab7f4602014-09-30 20:44:23 +000013635 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13636 for (unsigned i = 0; i < Iterations; ++i) {
13637 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13638 AddToWorklist(NewEst.getNode());
13639
13640 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13641 AddToWorklist(NewEst.getNode());
13642
13643 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13644 AddToWorklist(NewEst.getNode());
13645
13646 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13647 AddToWorklist(Est.getNode());
13648 }
13649 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013650 return Est;
13651 }
13652
13653 return SDValue();
13654}
13655
Sanjay Patel957efc232014-10-24 17:02:16 +000013656/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13657/// For the reciprocal sqrt, we need to find the zero of the function:
13658/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13659/// =>
13660/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13661/// As a result, we precompute A/2 prior to the iteration loop.
13662SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13663 unsigned Iterations) {
13664 EVT VT = Arg.getValueType();
13665 SDLoc DL(Arg);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013666 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013667
Sanjay Patel957efc232014-10-24 17:02:16 +000013668 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13669 // this entire sequence requires only one FP constant.
13670 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13671 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013672
Sanjay Patel957efc232014-10-24 17:02:16 +000013673 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13674 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013675
Sanjay Patel957efc232014-10-24 17:02:16 +000013676 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13677 for (unsigned i = 0; i < Iterations; ++i) {
13678 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13679 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013680
Sanjay Patel957efc232014-10-24 17:02:16 +000013681 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13682 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013683
Sanjay Patel957efc232014-10-24 17:02:16 +000013684 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13685 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013686
Sanjay Patel957efc232014-10-24 17:02:16 +000013687 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13688 AddToWorklist(Est.getNode());
13689 }
13690 return Est;
13691}
13692
13693/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13694/// For the reciprocal sqrt, we need to find the zero of the function:
13695/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13696/// =>
13697/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13698SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13699 unsigned Iterations) {
13700 EVT VT = Arg.getValueType();
13701 SDLoc DL(Arg);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013702 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13703 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
Sanjay Patel957efc232014-10-24 17:02:16 +000013704
13705 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13706 for (unsigned i = 0; i < Iterations; ++i) {
13707 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13708 AddToWorklist(HalfEst.getNode());
13709
13710 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13711 AddToWorklist(Est.getNode());
13712
13713 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13714 AddToWorklist(Est.getNode());
13715
13716 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13717 AddToWorklist(Est.getNode());
13718
13719 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13720 AddToWorklist(Est.getNode());
13721 }
13722 return Est;
13723}
13724
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013725SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13726 if (Level >= AfterLegalizeDAG)
13727 return SDValue();
13728
13729 // Expose the DAG combiner to the target combiner implementations.
13730 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013731 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013732 bool UseOneConstNR = false;
13733 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13734 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013735 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013736 Est = UseOneConstNR ?
13737 BuildRsqrtNROneConst(Op, Est, Iterations) :
13738 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013739 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013740 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013741 }
13742
13743 return SDValue();
13744}
13745
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013746/// Return true if base is a frame index, which is known not to alias with
13747/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013748static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013749 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013750 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013751 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013752
Jim Laskey0463e082006-10-07 23:37:56 +000013753 // If it's an adding a simple constant then integrate the offset.
13754 if (Base.getOpcode() == ISD::ADD) {
13755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13756 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013757 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013758 }
13759 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013760
Nate Begeman18150d52009-09-25 06:05:26 +000013761 // Return the underlying GlobalValue, and update the Offset. Return false
13762 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13763 // by multiple nodes with different offsets.
13764 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13765 GV = G->getGlobal();
13766 Offset += G->getOffset();
13767 return false;
13768 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013769
Nate Begeman18150d52009-09-25 06:05:26 +000013770 // Return the underlying Constant value, and update the Offset. Return false
13771 // for ConstantSDNodes since the same constant pool entry may be represented
13772 // by multiple nodes with different offsets.
13773 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013774 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13775 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013776 Offset += C->getOffset();
13777 return false;
13778 }
Jim Laskey0463e082006-10-07 23:37:56 +000013779 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013780 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013781}
13782
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013783/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013784bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013785 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013786 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013787
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013788 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013789 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013790
Jim Laskey0463e082006-10-07 23:37:56 +000013791 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013792 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013793 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013794 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013795 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013796 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13797 Base1, Offset1, GV1, CV1);
13798 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13799 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013800
Nate Begeman18150d52009-09-25 06:05:26 +000013801 // If they have a same base address then check to see if they overlap.
13802 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013803 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13804 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013805
Owen Anderson272ff942010-09-20 20:39:59 +000013806 // It is possible for different frame indices to alias each other, mostly
13807 // when tail call optimization reuses return address slots for arguments.
13808 // To catch this case, look up the actual index of frame indices to compute
13809 // the real alias relationship.
13810 if (isFrameIndex1 && isFrameIndex2) {
13811 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13812 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13813 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013814 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13815 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013816 }
13817
Wesley Peck527da1b2010-11-23 03:31:01 +000013818 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013819 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013820 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13821 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013822
Nate Begeman879d8f12009-09-15 00:18:30 +000013823 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13824 // compared to the size and offset of the access, we may be able to prove they
13825 // do not alias. This check is conservative for now to catch cases created by
13826 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013827 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13828 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13829 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13830 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13831 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13832 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13833 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013834
Nate Begeman879d8f12009-09-15 00:18:30 +000013835 // There is no overlap between these relatively aligned accesses of similar
13836 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013837 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13838 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013839 return false;
13840 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013841
Eric Christopherf55d4712014-10-08 23:38:39 +000013842 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13843 ? CombinerGlobalAA
13844 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013845#ifndef NDEBUG
13846 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13847 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13848 UseAA = false;
13849#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013850 if (UseAA &&
13851 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013852 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013853 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13854 Op1->getSrcValueOffset());
13855 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13856 Op0->getSrcValueOffset() - MinOffset;
13857 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13858 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013859 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013860 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13861 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013862 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013863 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13864 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013865 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013866 if (AAResult == AliasAnalysis::NoAlias)
13867 return false;
13868 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013869
13870 // Otherwise we have to assume they alias.
13871 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013872}
13873
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013874/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013875/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013876void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013877 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013878 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013879 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013880
Jim Laskeyd07be232006-09-25 16:29:54 +000013881 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013882 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013883
Jim Laskey708d0db2006-10-04 16:53:27 +000013884 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013885 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013886 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013887
Jim Laskey6549d222006-10-05 15:07:25 +000013888 // Look at each chain and determine if it is an alias. If so, add it to the
13889 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013890 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013891 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013892 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013893 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013894
13895 // For TokenFactor nodes, look at each operand and only continue up the
13896 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013897 // find more and revert to original chain since the xform is unlikely to be
13898 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013899 //
13900 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013901 // chain we found before we hit a tokenfactor rather than the original
13902 // chain.
13903 if (Depth > 6 || Aliases.size() == 2) {
13904 Aliases.clear();
13905 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013906 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013907 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013908
Nate Begeman879d8f12009-09-15 00:18:30 +000013909 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013910 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013911 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013912
Jim Laskey6549d222006-10-05 15:07:25 +000013913 switch (Chain.getOpcode()) {
13914 case ISD::EntryToken:
13915 // Entry token is ideal chain operand, but handled in FindBetterChain.
13916 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013917
Jim Laskey6549d222006-10-05 15:07:25 +000013918 case ISD::LOAD:
13919 case ISD::STORE: {
13920 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013921 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13922 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013923
Jim Laskey6549d222006-10-05 15:07:25 +000013924 // If chain is alias then stop here.
13925 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013926 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013927 Aliases.push_back(Chain);
13928 } else {
13929 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013930 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013931 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013932 }
Jim Laskey6549d222006-10-05 15:07:25 +000013933 break;
13934 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013935
Jim Laskey6549d222006-10-05 15:07:25 +000013936 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013937 // We have to check each of the operands of the token factor for "small"
13938 // token factors, so we queue them up. Adding the operands to the queue
13939 // (stack) in reverse order maintains the original order and increases the
13940 // likelihood that getNode will find a matching token factor (CSE.)
13941 if (Chain.getNumOperands() > 16) {
13942 Aliases.push_back(Chain);
13943 break;
13944 }
Jim Laskey6549d222006-10-05 15:07:25 +000013945 for (unsigned n = Chain.getNumOperands(); n;)
13946 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013947 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013948 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013949
Jim Laskey6549d222006-10-05 15:07:25 +000013950 default:
13951 // For all other instructions we will just have to take what we can get.
13952 Aliases.push_back(Chain);
13953 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013954 }
13955 }
Hal Finkel51a98382014-01-24 20:12:02 +000013956
13957 // We need to be careful here to also search for aliases through the
13958 // value operand of a store, etc. Consider the following situation:
13959 // Token1 = ...
13960 // L1 = load Token1, %52
13961 // S1 = store Token1, L1, %51
13962 // L2 = load Token1, %52+8
13963 // S2 = store Token1, L2, %51+8
13964 // Token2 = Token(S1, S2)
13965 // L3 = load Token2, %53
13966 // S3 = store Token2, L3, %52
13967 // L4 = load Token2, %53+8
13968 // S4 = store Token2, L4, %52+8
13969 // If we search for aliases of S3 (which loads address %52), and we look
13970 // only through the chain, then we'll miss the trivial dependence on L1
13971 // (which also loads from %52). We then might change all loads and
13972 // stores to use Token1 as their chain operand, which could result in
13973 // copying %53 into %52 before copying %52 into %51 (which should
13974 // happen first).
13975 //
13976 // The problem is, however, that searching for such data dependencies
13977 // can become expensive, and the cost is not directly related to the
13978 // chain depth. Instead, we'll rule out such configurations here by
13979 // insisting that we've visited all chain users (except for users
13980 // of the original chain, which is not necessary). When doing this,
13981 // we need to look through nodes we don't care about (otherwise, things
13982 // like register copies will interfere with trivial cases).
13983
13984 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013985 for (const SDNode *N : Visited)
13986 if (N != OriginalChain.getNode())
13987 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013988
13989 while (!Worklist.empty()) {
13990 const SDNode *M = Worklist.pop_back_val();
13991
13992 // We have already visited M, and want to make sure we've visited any uses
13993 // of M that we care about. For uses that we've not visisted, and don't
13994 // care about, queue them to the worklist.
13995
13996 for (SDNode::use_iterator UI = M->use_begin(),
13997 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013998 if (UI.getUse().getValueType() == MVT::Other &&
13999 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000014000 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
14001 // We've not visited this use, and we care about it (it could have an
14002 // ordering dependency with the original node).
14003 Aliases.clear();
14004 Aliases.push_back(OriginalChain);
14005 return;
14006 }
14007
14008 // We've not visited this use, but we don't care about it. Mark it as
14009 // visited and enqueue it to the worklist.
14010 Worklist.push_back(*UI);
14011 }
14012 }
Jim Laskey708d0db2006-10-04 16:53:27 +000014013}
14014
Sanjay Patel50cbfc52014-08-28 16:29:51 +000014015/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14016/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000014017SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14018 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000014019
Jim Laskey708d0db2006-10-04 16:53:27 +000014020 // Accumulate all the aliases to this node.
14021 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000014022
Dan Gohman4298df62011-05-17 22:20:36 +000014023 // If no operands then chain to entry token.
14024 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000014025 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000014026
14027 // If a single operand then chain to it. We don't need to revisit it.
14028 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000014029 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000014030
Jim Laskey708d0db2006-10-04 16:53:27 +000014031 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000014032 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000014033}
14034
Sanjay Patel50cbfc52014-08-28 16:29:51 +000014035/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000014036void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000014037 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000014038 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000014039 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000014040}