blob: a0cd22fd7dc5a3b86e4a652cd53440f30a8128dd [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000021#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitOR(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000257 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000258 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000260 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000264 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000272 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000277 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000280 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +0000306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000311 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000312 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313
Matt Arsenault985b9de2014-03-17 18:58:01 +0000314 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000318 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000320 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000321 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000322 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000323 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000324
325 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
326 SDValue &CC) const;
327 bool isOneUseSetCC(SDValue N) const;
328
Scott Michelcf0da6c2009-02-17 22:15:04 +0000329 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000330 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000331 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000332 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000333 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000334 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000335 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000336 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000337 SDValue BuildReciprocalEstimate(SDValue Op);
338 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000339 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000341 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342 bool DemandHighBits = true);
343 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000344 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345 SDValue InnerPos, SDValue InnerNeg,
346 unsigned PosOpcode, unsigned NegOpcode,
347 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000348 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000349 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000350 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000351 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000352 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000353 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000354
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000355 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000356
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000357 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000358 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000359 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000360 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000361
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000362 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000363 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000364
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000365 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000367 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000368
Sanjay Patel37c41c12015-01-22 18:21:26 +0000369 /// Holds a pointer to an LSBaseSDNode as well as information on where it
370 /// is located in a sequence of memory operations connected by a chain.
371 struct MemOpLink {
372 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374 // Ptr to the mem node.
375 LSBaseSDNode *MemNode;
376 // Offset from the base ptr.
377 int64_t OffsetFromBase;
378 // What is the sequence number of this mem node.
379 // Lowest mem operand in the DAG starts at zero.
380 unsigned SequenceNum;
381 };
382
383 /// This is a helper function for MergeConsecutiveStores. When the source
384 /// elements of the consecutive stores are all constants or all extracted
385 /// vector elements, try to merge them into one larger store.
386 /// \return True if a merged store was created.
387 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000388 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000389 bool IsConstantSrc, bool UseVector);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +0000390
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000391 /// Merge consecutive store operations into a wide store.
392 /// This optimization uses wide integers or vectors when possible.
393 /// \return True if some memory operations were changed.
394 bool MergeConsecutiveStores(StoreSDNode *N);
395
Adam Nemet67483892014-03-04 23:28:31 +0000396 /// \brief Try to transform a truncation where C is a constant:
397 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
398 ///
399 /// \p N needs to be a truncation and its first operand an AND. Other
400 /// requirements are checked by the function (e.g. that trunc is
401 /// single-use) and if missed an empty SDValue is returned.
402 SDValue distributeTruncateThroughAnd(SDNode *N);
403
Chris Lattner4041ab62010-04-15 04:48:01 +0000404 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000405 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000406 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000408 auto *F = DAG.getMachineFunction().getFunction();
409 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000411 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000412
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000413 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000414 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000415
Chris Lattner4041ab62010-04-15 04:48:01 +0000416 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000417
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000418 /// Returns a type large enough to hold any valid shift amount - before type
419 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000420 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422 if (LHSTy.isVector())
423 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000426 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000427
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000428 /// This method returns true if we are running before type legalization or
429 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000430 bool isTypeLegal(const EVT &VT) {
431 if (!LegalTypes) return true;
432 return TLI.isTypeLegal(VT);
433 }
Matt Arsenault758659232013-05-18 00:21:46 +0000434
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000435 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000436 EVT getSetCCResultType(EVT VT) const {
437 return TLI.getSetCCResultType(*DAG.getContext(), VT);
438 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000439 };
440}
441
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000442
443namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000444/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000445/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000446class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000447 DAGCombiner &DC;
448public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000449 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000451
Craig Topper7b883b32014-03-08 06:31:39 +0000452 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000453 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000454 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000455};
456}
457
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000458//===----------------------------------------------------------------------===//
459// TargetLowering::DAGCombinerInfo implementation
460//===----------------------------------------------------------------------===//
461
462void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000463 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000464}
465
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000466void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000467 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000468}
469
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000470SDValue TargetLowering::DAGCombinerInfo::
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +0000471CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
Evan Chengfd81c732009-03-28 05:57:29 +0000472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000473}
474
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000475SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000476CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000478}
479
480
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000481SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000482CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000484}
485
Dan Gohmane58ab792009-01-29 01:59:02 +0000486void TargetLowering::DAGCombinerInfo::
487CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
489}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000490
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000491//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000492// Helper Functions
493//===----------------------------------------------------------------------===//
494
Chandler Carruth18066972014-08-02 10:02:07 +0000495void DAGCombiner::deleteAndRecombine(SDNode *N) {
496 removeFromWorklist(N);
497
498 // If the operands of this node are only used by the node, they will now be
499 // dead. Make sure to re-visit them and recursively delete dead nodes.
500 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000501 // For an operand generating multiple values, one of the values may
502 // become dead allowing further simplification (e.g. split index
503 // arithmetic from an indexed load).
504 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000505 AddToWorklist(Op.getNode());
506
507 DAG.DeleteNode(N);
508}
509
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000510/// Return 1 if we can compute the negated form of the specified expression for
511/// the same cost as the expression itself, or 2 if we can compute the negated
512/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000513static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000515 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000516 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 // fneg is removable even if it has multiple uses.
518 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000519
Chris Lattnere49c9742007-05-14 22:04:50 +0000520 // Don't allow anything with multiple uses.
521 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000522
Chris Lattner46980832007-05-25 02:19:06 +0000523 // Don't recurse exponentially.
524 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 switch (Op.getOpcode()) {
527 default: return false;
528 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000529 // Don't invert constant FP values after legalize. The negated constant
530 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000531 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000532 case ISD::FADD:
533 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000534 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000535
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000536 // After operation legalization, it might not be legal to create new FSUBs.
537 if (LegalOperations &&
538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
539 return 0;
540
Craig Topper03f39772012-09-09 22:58:45 +0000541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
543 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000544 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000547 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000549 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000550 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000551
Bill Wendling6fbf5492009-01-30 23:10:18 +0000552 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000554
Chris Lattnere49c9742007-05-14 22:04:50 +0000555 case ISD::FMUL:
556 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000557 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000558
Bill Wendling6fbf5492009-01-30 23:10:18 +0000559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
561 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000562 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000563
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000565 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000566
Chris Lattnere49c9742007-05-14 22:04:50 +0000567 case ISD::FP_EXTEND:
568 case ISD::FP_ROUND:
569 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000571 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000572 }
573}
574
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000575/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000576static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000577 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000578 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000579 // fneg is removable even if it has multiple uses.
580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000581
Chris Lattnere49c9742007-05-14 22:04:50 +0000582 // Don't allow anything with multiple uses.
583 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584
Chris Lattner46980832007-05-25 02:19:06 +0000585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000587 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000588 case ISD::ConstantFP: {
589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
590 V.changeSign();
591 return DAG.getConstantFP(V, Op.getValueType());
592 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000593 case ISD::FADD:
594 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000595 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000596
Bill Wendling6fbf5492009-01-30 23:10:18 +0000597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000599 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000601 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000602 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000603 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000606 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000607 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000608 Op.getOperand(0));
609 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000610 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000611 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000612
Bill Wendling6fbf5492009-01-30 23:10:18 +0000613 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000615 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000616 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000617
Bill Wendling6fbf5492009-01-30 23:10:18 +0000618 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000620 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000621
Chris Lattnere49c9742007-05-14 22:04:50 +0000622 case ISD::FMUL:
623 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000624 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000625
Bill Wendling6fbf5492009-01-30 23:10:18 +0000626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000628 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000630 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000631 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000632 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000633
Bill Wendling6fbf5492009-01-30 23:10:18 +0000634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000636 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000637 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000638 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000639
Chris Lattnere49c9742007-05-14 22:04:50 +0000640 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000641 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000643 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000644 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000645 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000647 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000648 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000649 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000650 }
651}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000652
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000653// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000654// that selects between the target values used for true and false, making it
655// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656// the appropriate nodes based on the type of node we are checking. This
657// simplifies life a bit for the callers.
658bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
659 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000660 if (N.getOpcode() == ISD::SETCC) {
661 LHS = N.getOperand(0);
662 RHS = N.getOperand(1);
663 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000664 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000665 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000666
667 if (N.getOpcode() != ISD::SELECT_CC ||
668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
670 return false;
671
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000672 if (TLI.getBooleanContents(N.getValueType()) ==
673 TargetLowering::UndefinedBooleanContent)
674 return false;
675
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000676 LHS = N.getOperand(0);
677 RHS = N.getOperand(1);
678 CC = N.getOperand(4);
679 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000680}
681
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000682/// Return true if this is a SetCC-equivalent operation with only one use.
683/// If this is true, it allows the users to invert the operation for free when
684/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000685bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000686 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000688 return true;
689 return false;
690}
691
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000692/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000693/// elements are all the same constant or undefined.
694static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
696 if (!C)
697 return false;
698
699 APInt SplatUndef;
700 unsigned SplatBitSize;
701 bool HasAnyUndefs;
702 EVT EltVT = N->getValueType(0).getVectorElementType();
703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
704 HasAnyUndefs) &&
705 EltVT.getSizeInBits() >= SplatBitSize);
706}
707
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000708// \brief Returns the SDNode if it is a constant integer BuildVector
709// or constant integer.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000710static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
711 if (isa<ConstantSDNode>(N))
712 return N.getNode();
713 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
714 return N.getNode();
715 return nullptr;
716}
717
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000718// \brief Returns the SDNode if it is a constant float BuildVector
719// or constant float.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000720static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
721 if (isa<ConstantFPSDNode>(N))
722 return N.getNode();
723 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
724 return N.getNode();
725 return nullptr;
726}
727
Matt Arsenault985b9de2014-03-17 18:58:01 +0000728// \brief Returns the SDNode if it is a constant splat BuildVector or constant
729// int.
730static ConstantSDNode *isConstOrConstSplat(SDValue N) {
731 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
732 return CN;
733
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000734 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000735 BitVector UndefElements;
736 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000737
738 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000739 // FIXME: We blindly ignore splats which include undef which is overly
740 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000741 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000742 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000743 return CN;
744 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000745
746 return nullptr;
747}
748
Matt Arsenault6cc00422014-08-16 10:14:19 +0000749// \brief Returns the SDNode if it is a constant splat BuildVector or constant
750// float.
751static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
752 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
753 return CN;
754
755 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
756 BitVector UndefElements;
757 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
758
Matt Arsenault965de302014-09-02 18:33:51 +0000759 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000760 return CN;
761 }
762
763 return nullptr;
764}
765
Andrew Trickef9de2a2013-05-25 02:42:55 +0000766SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000767 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000768 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000769 if (N0.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000770 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
771 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000772 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000773 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
774 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
775 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000776 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000777 if (N0.hasOneUse()) {
778 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
779 // use
780 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
781 if (!OpNode.getNode())
782 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000783 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000784 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000785 }
786 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000787 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000788
Juergen Ributzka68402822014-01-13 21:49:25 +0000789 if (N1.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000790 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
791 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000792 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000793 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
794 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
795 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000796 }
797 if (N1.hasOneUse()) {
798 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
799 // use
800 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
801 if (!OpNode.getNode())
802 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000803 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000804 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
805 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000806 }
807 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000808
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000809 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000810}
811
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000812SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
813 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000814 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
815 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000816 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000817 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000818 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000819 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000820 dbgs() << " and " << NumTo-1 << " other values\n");
821 for (unsigned i = 0, e = NumTo; i != e; ++i)
822 assert((!To[i].getNode() ||
823 N->getValueType(i) == To[i].getValueType()) &&
824 "Cannot combine value to value of different type!");
825
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000826 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000827 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000828 if (AddTo) {
829 // Push the new nodes and any users onto the worklist
830 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000831 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000832 AddToWorklist(To[i].getNode());
833 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000834 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000835 }
836 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000837
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000838 // Finally, if the node is now dead, remove it from the graph. The node
839 // may not be dead if the replacement process recursively simplified to
840 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000841 if (N->use_empty())
842 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000843 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000844}
845
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000846void DAGCombiner::
847CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000848 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000849 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000850 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000851 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000852
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000853 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000854 AddToWorklist(TLO.New.getNode());
855 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000856
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000857 // Finally, if the node is now dead, remove it from the graph. The node
858 // may not be dead if the replacement process recursively simplified to
859 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000860 if (TLO.Old.getNode()->use_empty())
861 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000862}
863
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000864/// Check the specified integer node value to see if it can be simplified or if
865/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000866bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000867 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000868 APInt KnownZero, KnownOne;
869 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
870 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000871
Dan Gohmane58ab792009-01-29 01:59:02 +0000872 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000873 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000874
Dan Gohmane58ab792009-01-29 01:59:02 +0000875 // Replace the old value with the new one.
876 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000877 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000878 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000879 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000880 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000881 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000882
Dan Gohmane58ab792009-01-29 01:59:02 +0000883 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000884 return true;
885}
886
Evan Cheng0abb54d2010-04-24 04:43:44 +0000887void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000888 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000889 EVT VT = Load->getValueType(0);
890 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000891
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892 DEBUG(dbgs() << "\nReplacing.9 ";
893 Load->dump(&DAG);
894 dbgs() << "\nWith: ";
895 Trunc.getNode()->dump(&DAG);
896 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000897 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000898 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
899 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000900 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000901 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000902}
903
904SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
905 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000906 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000907 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000908 EVT MemVT = LD->getMemoryVT();
909 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000910 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
911 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000912 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000913 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000914 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000915 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000916 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000917 }
918
Evan Chenge19aa5c2010-04-19 19:29:22 +0000919 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000920 switch (Opc) {
921 default: break;
922 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000923 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000924 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000925 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000926 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000927 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000928 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000929 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000930 case ISD::Constant: {
931 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000932 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000933 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000934 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000935 }
936
937 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000938 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000939 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000940}
941
Evan Cheng0abb54d2010-04-24 04:43:44 +0000942SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000943 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
944 return SDValue();
945 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000946 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000947 bool Replace = false;
948 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000949 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000950 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000951 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000952
953 if (Replace)
954 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
955 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000956 DAG.getValueType(OldVT));
957}
958
Evan Cheng0abb54d2010-04-24 04:43:44 +0000959SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000961 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962 bool Replace = false;
963 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000964 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000965 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000966 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000967
968 if (Replace)
969 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
970 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000971}
972
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000973/// Promote the specified integer binary operation if the target indicates it is
974/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
975/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000976SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
977 if (!LegalOperations)
978 return SDValue();
979
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
982 return SDValue();
983
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000984 // If operation type is 'undesirable', e.g. i16 on x86, consider
985 // promoting it.
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
988 return SDValue();
989
Evan Chengaf56fac2010-04-16 06:14:10 +0000990 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000994 assert(PVT != VT && "Don't know what type to promote to!");
995
Evan Cheng0abb54d2010-04-24 04:43:44 +0000996 bool Replace0 = false;
997 SDValue N0 = Op.getOperand(0);
998 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000999 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +00001000 return SDValue();
1001
Evan Cheng0abb54d2010-04-24 04:43:44 +00001002 bool Replace1 = false;
1003 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +00001004 SDValue NN1;
1005 if (N0 == N1)
1006 NN1 = NN0;
1007 else {
1008 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +00001009 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +00001010 return SDValue();
1011 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001012
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001013 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001014 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001015 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001016
1017 if (Replace0)
1018 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1019 if (Replace1)
1020 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001021
Evan Chenge8136902010-04-27 19:48:13 +00001022 DEBUG(dbgs() << "\nPromoting ";
1023 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001024 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001025 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001026 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001027 }
1028 return SDValue();
1029}
1030
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001031/// Promote the specified integer shift operation if the target indicates it is
1032/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1033/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001034SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1035 if (!LegalOperations)
1036 return SDValue();
1037
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1040 return SDValue();
1041
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1043 // promoting it.
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1046 return SDValue();
1047
1048 EVT PVT = VT;
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1053
Evan Cheng0abb54d2010-04-24 04:43:44 +00001054 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001055 SDValue N0 = Op.getOperand(0);
1056 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001057 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001058 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001059 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001060 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001061 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001062 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001063 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001064
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001065 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001066 if (Replace)
1067 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001068
Evan Chenge8136902010-04-27 19:48:13 +00001069 DEBUG(dbgs() << "\nPromoting ";
1070 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001071 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001072 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001073 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001074 }
1075 return SDValue();
1076}
1077
Evan Chenge19aa5c2010-04-19 19:29:22 +00001078SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1079 if (!LegalOperations)
1080 return SDValue();
1081
1082 EVT VT = Op.getValueType();
1083 if (VT.isVector() || !VT.isInteger())
1084 return SDValue();
1085
1086 // If operation type is 'undesirable', e.g. i16 on x86, consider
1087 // promoting it.
1088 unsigned Opc = Op.getOpcode();
1089 if (TLI.isTypeDesirableForOp(Opc, VT))
1090 return SDValue();
1091
1092 EVT PVT = VT;
1093 // Consult target whether it is a good idea to promote this operation and
1094 // what's the right type to promote it to.
1095 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1096 assert(PVT != VT && "Don't know what type to promote to!");
1097 // fold (aext (aext x)) -> (aext x)
1098 // fold (aext (zext x)) -> (zext x)
1099 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001100 DEBUG(dbgs() << "\nPromoting ";
1101 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001102 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001103 }
1104 return SDValue();
1105}
1106
1107bool DAGCombiner::PromoteLoad(SDValue Op) {
1108 if (!LegalOperations)
1109 return false;
1110
1111 EVT VT = Op.getValueType();
1112 if (VT.isVector() || !VT.isInteger())
1113 return false;
1114
1115 // If operation type is 'undesirable', e.g. i16 on x86, consider
1116 // promoting it.
1117 unsigned Opc = Op.getOpcode();
1118 if (TLI.isTypeDesirableForOp(Opc, VT))
1119 return false;
1120
1121 EVT PVT = VT;
1122 // Consult target whether it is a good idea to promote this operation and
1123 // what's the right type to promote it to.
1124 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1125 assert(PVT != VT && "Don't know what type to promote to!");
1126
Andrew Trickef9de2a2013-05-25 02:42:55 +00001127 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001128 SDNode *N = Op.getNode();
1129 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001130 EVT MemVT = LD->getMemoryVT();
1131 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001132 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1133 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001134 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001135 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001136 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001137 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001138 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1139
Evan Cheng0abb54d2010-04-24 04:43:44 +00001140 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001141 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001142 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001143 Result.getNode()->dump(&DAG);
1144 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001145 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1147 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001148 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001149 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001150 return true;
1151 }
1152 return false;
1153}
1154
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001155/// \brief Recursively delete a node which has no uses and any operands for
1156/// which it is the only use.
1157///
1158/// Note that this both deletes the nodes and removes them from the worklist.
1159/// It also adds any nodes who have had a user deleted to the worklist as they
1160/// may now have only one use and subject to other combines.
1161bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1162 if (!N->use_empty())
1163 return false;
1164
1165 SmallSetVector<SDNode *, 16> Nodes;
1166 Nodes.insert(N);
1167 do {
1168 N = Nodes.pop_back_val();
1169 if (!N)
1170 continue;
1171
1172 if (N->use_empty()) {
1173 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1174 Nodes.insert(N->getOperand(i).getNode());
1175
1176 removeFromWorklist(N);
1177 DAG.DeleteNode(N);
1178 } else {
1179 AddToWorklist(N);
1180 }
1181 } while (!Nodes.empty());
1182 return true;
1183}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001184
Chris Lattnere49c9742007-05-14 22:04:50 +00001185//===----------------------------------------------------------------------===//
1186// Main DAG Combiner implementation
1187//===----------------------------------------------------------------------===//
1188
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001189void DAGCombiner::Run(CombineLevel AtLevel) {
1190 // set the instance variables, so that the various visit routines may use it.
1191 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001192 LegalOperations = Level >= AfterLegalizeVectorOps;
1193 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001194
Evan Cheng5e7658c2008-08-29 22:21:44 +00001195 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001196 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1197 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001198 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001199
Evan Cheng5e7658c2008-08-29 22:21:44 +00001200 // Create a dummy node (which is not added to allnodes), that adds a reference
1201 // to the root node, preventing it from being deleted, and tracking any
1202 // changes of the root.
1203 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001204
James Molloy67b6b112012-02-16 09:17:04 +00001205 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001206 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001207 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001208 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001209 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001210 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001211 N = Worklist.pop_back_val();
1212 } while (!N);
1213
1214 bool GoodWorklistEntry = WorklistMap.erase(N);
1215 (void)GoodWorklistEntry;
1216 assert(GoodWorklistEntry &&
1217 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001218
Evan Cheng5e7658c2008-08-29 22:21:44 +00001219 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1220 // N is deleted from the DAG, since they too may now be dead or may have a
1221 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001222 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001223 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001224
1225 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001226
Chandler Carruth411fb402014-07-26 05:49:40 +00001227 // If this combine is running after legalizing the DAG, re-legalize any
1228 // nodes pulled off the worklist.
1229 if (Level == AfterLegalizeDAG) {
1230 SmallSetVector<SDNode *, 16> UpdatedNodes;
1231 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1232
1233 for (SDNode *LN : UpdatedNodes) {
1234 AddToWorklist(LN);
1235 AddUsersToWorklist(LN);
1236 }
1237 if (!NIsValid)
1238 continue;
1239 }
1240
Chandler Carruthb1432742014-07-28 17:55:07 +00001241 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1242
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001243 // Add any operands of the new node which have not yet been combined to the
1244 // worklist as well. Because the worklist uniques things already, this
1245 // won't repeatedly process the same operand.
1246 CombinedNodes.insert(N);
1247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1248 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1249 AddToWorklist(N->getOperand(i).getNode());
1250
Evan Cheng5e7658c2008-08-29 22:21:44 +00001251 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001252
Craig Topperc0196b12014-04-14 00:51:57 +00001253 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001254 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001255
Evan Cheng5e7658c2008-08-29 22:21:44 +00001256 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001257
Evan Cheng5e7658c2008-08-29 22:21:44 +00001258 // If we get back the same node we passed in, rather than a new node or
1259 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001260 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001261 // mechanics for us, we have no work to do in this case.
1262 if (RV.getNode() == N)
1263 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001264
Evan Cheng5e7658c2008-08-29 22:21:44 +00001265 assert(N->getOpcode() != ISD::DELETED_NODE &&
1266 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1267 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001268
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001269 DEBUG(dbgs() << " ... into: ";
1270 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001271
Devang Patelefec7712011-05-23 22:04:42 +00001272 // Transfer debug value.
1273 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001274 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001275 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001276 else {
1277 assert(N->getValueType(0) == RV.getValueType() &&
1278 N->getNumValues() == 1 && "Type mismatch");
1279 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001280 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001281 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001282
Evan Cheng5e7658c2008-08-29 22:21:44 +00001283 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001284 AddToWorklist(RV.getNode());
1285 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001286
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001287 // Finally, if the node is now dead, remove it from the graph. The node
1288 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001289 // something else needing this node. This will also take care of adding any
1290 // operands which have lost a user to the worklist.
1291 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001292 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001293
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001294 // If the root changed (e.g. it was a dead load, update the root).
1295 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001296 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001297}
1298
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001299SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001300 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001301 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001302 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001303 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001304 case ISD::ADD: return visitADD(N);
1305 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001306 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001307 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001308 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001309 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001310 case ISD::MUL: return visitMUL(N);
1311 case ISD::SDIV: return visitSDIV(N);
1312 case ISD::UDIV: return visitUDIV(N);
1313 case ISD::SREM: return visitSREM(N);
1314 case ISD::UREM: return visitUREM(N);
1315 case ISD::MULHU: return visitMULHU(N);
1316 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001317 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1318 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001319 case ISD::SMULO: return visitSMULO(N);
1320 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001321 case ISD::SDIVREM: return visitSDIVREM(N);
1322 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001323 case ISD::AND: return visitAND(N);
1324 case ISD::OR: return visitOR(N);
1325 case ISD::XOR: return visitXOR(N);
1326 case ISD::SHL: return visitSHL(N);
1327 case ISD::SRA: return visitSRA(N);
1328 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001329 case ISD::ROTR:
1330 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001331 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001332 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001333 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001334 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001335 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001336 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001337 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001338 case ISD::SELECT_CC: return visitSELECT_CC(N);
1339 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001340 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1341 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001342 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001343 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1344 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001345 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001346 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001347 case ISD::FADD: return visitFADD(N);
1348 case ISD::FSUB: return visitFSUB(N);
1349 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001350 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001351 case ISD::FDIV: return visitFDIV(N);
1352 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001353 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001354 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001355 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1356 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1357 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1358 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1359 case ISD::FP_ROUND: return visitFP_ROUND(N);
1360 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1361 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1362 case ISD::FNEG: return visitFNEG(N);
1363 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001364 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001365 case ISD::FMINNUM: return visitFMINNUM(N);
1366 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001367 case ISD::FCEIL: return visitFCEIL(N);
1368 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001369 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001370 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001371 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001372 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001373 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001374 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001375 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1376 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001377 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001378 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +00001379 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001380 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001381 case ISD::MLOAD: return visitMLOAD(N);
1382 case ISD::MSTORE: return visitMSTORE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001383 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001384 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001385}
1386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001387SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001388 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001389
1390 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001391 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001392 assert(N->getOpcode() != ISD::DELETED_NODE &&
1393 "Node was deleted but visit returned NULL!");
1394
1395 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1396 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1397
1398 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001399 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001400 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001401
1402 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1403 }
1404 }
1405
Evan Chengf1005572010-04-28 07:10:39 +00001406 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001407 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001408 switch (N->getOpcode()) {
1409 default: break;
1410 case ISD::ADD:
1411 case ISD::SUB:
1412 case ISD::MUL:
1413 case ISD::AND:
1414 case ISD::OR:
1415 case ISD::XOR:
1416 RV = PromoteIntBinOp(SDValue(N, 0));
1417 break;
1418 case ISD::SHL:
1419 case ISD::SRA:
1420 case ISD::SRL:
1421 RV = PromoteIntShiftOp(SDValue(N, 0));
1422 break;
1423 case ISD::SIGN_EXTEND:
1424 case ISD::ZERO_EXTEND:
1425 case ISD::ANY_EXTEND:
1426 RV = PromoteExtend(SDValue(N, 0));
1427 break;
1428 case ISD::LOAD:
1429 if (PromoteLoad(SDValue(N, 0)))
1430 RV = SDValue(N, 0);
1431 break;
1432 }
1433 }
1434
Scott Michelcf0da6c2009-02-17 22:15:04 +00001435 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001436 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001437 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001438 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001439 SDValue N0 = N->getOperand(0);
1440 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001441
Evan Cheng31604a62008-03-22 01:55:50 +00001442 // Constant operands are canonicalized to RHS.
1443 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001444 SDValue Ops[] = {N1, N0};
1445 SDNode *CSENode;
1446 if (const BinaryWithFlagsSDNode *BinNode =
1447 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1448 CSENode = DAG.getNodeIfExists(
1449 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1450 BinNode->hasNoSignedWrap(), BinNode->isExact());
1451 } else {
1452 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1453 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001454 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001455 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001456 }
1457 }
1458
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001459 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001460}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001461
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001462/// Given a node, return its input chain if it has one, otherwise return a null
1463/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001464static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001465 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001466 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001467 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001468 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001469 return N->getOperand(NumOps-1);
1470 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001471 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001472 return N->getOperand(i);
1473 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001474 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001475}
1476
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001477SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001478 // If N has two operands, where one has an input chain equal to the other,
1479 // the 'other' chain is redundant.
1480 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001481 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001482 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001483 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001484 return N->getOperand(1);
1485 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001486
Chris Lattner48fb92f2007-05-16 06:37:59 +00001487 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001488 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001489 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001490 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001491
Jim Laskey708d0db2006-10-04 16:53:27 +00001492 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001493 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001494
Jim Laskey0463e082006-10-07 23:37:56 +00001495 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001496 // encountered.
1497 for (unsigned i = 0; i < TFs.size(); ++i) {
1498 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001499
Jim Laskey708d0db2006-10-04 16:53:27 +00001500 // Check each of the operands.
1501 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001502 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001503
Jim Laskey708d0db2006-10-04 16:53:27 +00001504 switch (Op.getOpcode()) {
1505 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001506 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001507 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001508 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001509 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001510
Jim Laskey708d0db2006-10-04 16:53:27 +00001511 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001512 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001513 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001515 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001516 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001517 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001518 Changed = true;
1519 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001520 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001521 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001522
Jim Laskey708d0db2006-10-04 16:53:27 +00001523 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001524 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001525 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001526 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001527 else
1528 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001529 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001530 }
1531 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001532 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001533
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001534 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001535
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001536 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001537 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001538 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001539 // The entry token is the only possible outcome.
1540 Result = DAG.getEntryNode();
1541 } else {
1542 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001543 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001544 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001545
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001546 // Add users to worklist if AA is enabled, since it may introduce
1547 // a lot of new chained token factors while removing memory deps.
1548 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1549 : DAG.getSubtarget().useAA();
1550 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001551 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001552
Jim Laskey708d0db2006-10-04 16:53:27 +00001553 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001554}
1555
Chris Lattneree322b42008-02-13 07:25:05 +00001556/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001557SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001558 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001559 // Replacing results may cause a different MERGE_VALUES to suddenly
1560 // be CSE'd with N, and carry its uses with it. Iterate until no
1561 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001562 // First add the users of this node to the work list so that they
1563 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001564 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001565 do {
1566 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001568 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001569 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001570 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001571}
1572
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001573SDValue DAGCombiner::visitADD(SDNode *N) {
1574 SDValue N0 = N->getOperand(0);
1575 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001576 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001577
1578 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001579 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001580 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1581 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001582
1583 // fold (add x, 0) -> x, vector edition
1584 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1585 return N0;
1586 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1587 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001588 }
Bill Wendling0864a752008-12-10 22:36:00 +00001589
Dan Gohman06563a82007-07-03 14:03:57 +00001590 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001591 if (N0.getOpcode() == ISD::UNDEF)
1592 return N0;
1593 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001594 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001595 // fold (add c1, c2) -> c1+c2
Matthias Braun00a40762015-02-24 18:52:01 +00001596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001598 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001599 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001600 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001601 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001602 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001603 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001604 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001605 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001606 // fold (add Sym, c) -> Sym+c
1607 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001608 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001609 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001610 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001611 GA->getOffset() +
1612 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001613 // fold ((c1-A)+c2) -> (c1+c2)-A
1614 if (N1C && N0.getOpcode() == ISD::SUB)
1615 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001616 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001617 DAG.getConstant(N1C->getAPIntValue()+
1618 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001619 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001620 // reassociate add
Simon Pilgrimd15c2802015-03-29 16:49:51 +00001621 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00001622 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001623 // fold ((0-A) + B) -> B-A
1624 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1625 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001626 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001627 // fold (A + (0-B)) -> A-B
1628 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1629 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001630 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001631 // fold (A+(B-A)) -> B
1632 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001633 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001634 // fold ((B-A)+A) -> B
1635 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1636 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001637 // fold (A+(B-(A+C))) to (B-C)
1638 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001639 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001640 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001641 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001642 // fold (A+(B-(C+A))) to (B-C)
1643 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001644 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001645 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001646 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001647 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001648 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1649 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001650 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001651 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001652 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001653
Dale Johannesen8c766702008-12-02 01:30:54 +00001654 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1655 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1656 SDValue N00 = N0.getOperand(0);
1657 SDValue N01 = N0.getOperand(1);
1658 SDValue N10 = N1.getOperand(0);
1659 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001660
1661 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001662 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1663 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1664 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001665 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001666
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001667 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1668 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001669
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001670 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001671 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001672 APInt LHSZero, LHSOne;
1673 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001674 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001675
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001676 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001677 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001678
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001679 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1680 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001681 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1682 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1683 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1684 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001685 }
1686 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001687
Dan Gohman954f4902010-01-19 23:30:49 +00001688 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1689 if (N1.getOpcode() == ISD::SHL &&
1690 N1.getOperand(0).getOpcode() == ISD::SUB)
1691 if (ConstantSDNode *C =
1692 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1693 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1695 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001696 N1.getOperand(0).getOperand(1),
1697 N1.getOperand(1)));
1698 if (N0.getOpcode() == ISD::SHL &&
1699 N0.getOperand(0).getOpcode() == ISD::SUB)
1700 if (ConstantSDNode *C =
1701 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1702 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001703 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1704 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001705 N0.getOperand(0).getOperand(1),
1706 N0.getOperand(1)));
1707
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001708 if (N1.getOpcode() == ISD::AND) {
1709 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001710 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001711 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1712 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001713
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001714 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1715 // and similar xforms where the inner op is either ~0 or 0.
1716 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001717 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001718 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1719 }
1720 }
1721
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001722 // add (sext i1), X -> sub X, (zext i1)
1723 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1724 N0.getOperand(0).getValueType() == MVT::i1 &&
1725 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001726 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001727 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1728 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1729 }
1730
Jan Veselyaf62cf42014-10-17 14:45:25 +00001731 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1732 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1733 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1734 if (TN->getVT() == MVT::i1) {
1735 SDLoc DL(N);
1736 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1737 DAG.getConstant(1, VT));
1738 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1739 }
1740 }
1741
Evan Chengf1005572010-04-28 07:10:39 +00001742 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001743}
1744
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001745SDValue DAGCombiner::visitADDC(SDNode *N) {
1746 SDValue N0 = N->getOperand(0);
1747 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001748 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001749
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001750 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001751 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001753 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001754 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001755
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001756 // canonicalize constant to RHS.
Matthias Braun00a40762015-02-24 18:52:01 +00001757 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1758 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001759 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001761
Chris Lattner47206662007-03-04 20:40:38 +00001762 // fold (addc x, 0) -> x + no carry out
1763 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001764 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001765 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001766
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001767 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001768 APInt LHSZero, LHSOne;
1769 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001770 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001771
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001772 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001773 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001774
Chris Lattner47206662007-03-04 20:40:38 +00001775 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1776 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001777 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001778 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001779 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001781 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001782
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001783 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001784}
1785
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001786SDValue DAGCombiner::visitADDE(SDNode *N) {
1787 SDValue N0 = N->getOperand(0);
1788 SDValue N1 = N->getOperand(1);
1789 SDValue CarryIn = N->getOperand(2);
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::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001796 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001797
Chris Lattner47206662007-03-04 20:40:38 +00001798 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001799 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001800 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001801
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001802 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001803}
1804
Eric Christophere5ca1e02011-02-16 04:50:12 +00001805// Since it may not be valid to emit a fold to zero for vector initializers
1806// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001807static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001808 SelectionDAG &DAG,
1809 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001810 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001811 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001812 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1813 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001814 return SDValue();
1815}
1816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001817SDValue DAGCombiner::visitSUB(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001820 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001821
Dan Gohmana8665142007-06-25 16:23:39 +00001822 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001823 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001824 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1825 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001826
1827 // fold (sub x, 0) -> x, vector edition
1828 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1829 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001830 }
Bill Wendling0864a752008-12-10 22:36:00 +00001831
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001832 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001833 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001834 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001835 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001836 // fold (sub c1, c2) -> c1-c2
Matthias Braun00a40762015-02-24 18:52:01 +00001837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001839 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001840 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001841 // fold (sub x, c) -> (add x, -c)
1842 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001843 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001844 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001845 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1846 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001848 // fold A-(A-B) -> B
1849 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1850 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001851 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001852 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001853 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001854 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001855 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001856 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001857 // fold C2-(A+C1) -> (C2-C1)-A
Matthias Braun00a40762015-02-24 18:52:01 +00001858 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1859 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001860 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001861 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1862 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001863 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001864 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001865 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001866 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001867 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001868 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1869 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001870 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001871 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001872 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001873 // fold ((A+(C+B))-B) -> A+C
1874 if (N0.getOpcode() == ISD::ADD &&
1875 N0.getOperand(1).getOpcode() == ISD::ADD &&
1876 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001877 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001878 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001879 // fold ((A-(B-C))-C) -> A-B
1880 if (N0.getOpcode() == ISD::SUB &&
1881 N0.getOperand(1).getOpcode() == ISD::SUB &&
1882 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001883 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001884 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001885
Dan Gohman06563a82007-07-03 14:03:57 +00001886 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001887 if (N0.getOpcode() == ISD::UNDEF)
1888 return N0;
1889 if (N1.getOpcode() == ISD::UNDEF)
1890 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001891
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001892 // If the relocation model supports it, consider symbol offsets.
1893 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001894 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001895 // fold (sub Sym, c) -> Sym-c
1896 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001898 GA->getOffset() -
1899 (uint64_t)N1C->getSExtValue());
1900 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1901 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1902 if (GA->getGlobal() == GB->getGlobal())
1903 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1904 VT);
1905 }
1906
Jan Veselyaf62cf42014-10-17 14:45:25 +00001907 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1908 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1909 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1910 if (TN->getVT() == MVT::i1) {
1911 SDLoc DL(N);
1912 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1913 DAG.getConstant(1, VT));
1914 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1915 }
1916 }
1917
Evan Chengf1005572010-04-28 07:10:39 +00001918 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001919}
1920
Craig Topper43a1bd62012-01-07 09:06:39 +00001921SDValue DAGCombiner::visitSUBC(SDNode *N) {
1922 SDValue N0 = N->getOperand(0);
1923 SDValue N1 = N->getOperand(1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001924 EVT VT = N0.getValueType();
1925
1926 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001927 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001928 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1929 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001930 MVT::Glue));
1931
1932 // fold (subc x, x) -> 0 + no borrow
1933 if (N0 == N1)
1934 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001936 MVT::Glue));
1937
1938 // fold (subc x, 0) -> x + no borrow
Matthias Braun00a40762015-02-24 18:52:01 +00001939 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1940 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001941 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001942 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001943 MVT::Glue));
1944
1945 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1946 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1948 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001949 MVT::Glue));
1950
1951 return SDValue();
1952}
1953
1954SDValue DAGCombiner::visitSUBE(SDNode *N) {
1955 SDValue N0 = N->getOperand(0);
1956 SDValue N1 = N->getOperand(1);
1957 SDValue CarryIn = N->getOperand(2);
1958
1959 // fold (sube x, y, false) -> (subc x, y)
1960 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001961 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001962
1963 return SDValue();
1964}
1965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001966SDValue DAGCombiner::visitMUL(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001969 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001970
Dan Gohman06563a82007-07-03 14:03:57 +00001971 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001972 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001973 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001974
1975 bool N0IsConst = false;
1976 bool N1IsConst = false;
1977 APInt ConstValue0, ConstValue1;
1978 // fold vector ops
1979 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001980 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1981 return FoldedVOp;
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001982
1983 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1984 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1985 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001986 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001987 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1988 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001989 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001990 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1991 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001992 }
1993
Nate Begeman21158fc2005-09-01 00:19:25 +00001994 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001995 if (N0IsConst && N1IsConst)
1996 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1997
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001998 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001999 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002001 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002002 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00002003 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002004 // We require a splat of the entire scalar bit width for non-contiguous
2005 // bit patterns.
2006 bool IsFullSplat =
2007 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002008 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002009 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002010 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002011 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002012 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002013 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002014 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002015 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002016 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002017 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002018 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002019 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00002020 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002021 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002022 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002023 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002024 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002025 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002026 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002027 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002028 DAG.getConstant(Log2Val,
2029 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002030 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002031
2032 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002033 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002034 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002035 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002038 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002039 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002040 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002041 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002042 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002043
Chris Lattner324871e2006-03-01 03:44:24 +00002044 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2045 // use.
2046 {
Craig Topperc0196b12014-04-14 00:51:57 +00002047 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002048 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002049 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002050 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2051 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002052 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002053 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002054 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002055 isa<ConstantSDNode>(N1.getOperand(1)) &&
2056 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002057 Sh = N1; Y = N0;
2058 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002059
Gabor Greiff304a7a2008-08-28 21:40:38 +00002060 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002061 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002062 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002063 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002064 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002065 }
2066 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002067
Chris Lattnerf29f5202006-03-04 23:33:26 +00002068 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002069 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2070 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2071 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002072 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2073 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002074 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002075 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002076 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002077
Nate Begeman22e251a2006-02-03 06:46:56 +00002078 // reassociate mul
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002079 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002080 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002081
Evan Chengf1005572010-04-28 07:10:39 +00002082 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002083}
2084
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002085SDValue DAGCombiner::visitSDIV(SDNode *N) {
2086 SDValue N0 = N->getOperand(0);
2087 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002088 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002089
Dan Gohmana8665142007-06-25 16:23:39 +00002090 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002091 if (VT.isVector())
2092 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2093 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002094
Nate Begeman21158fc2005-09-01 00:19:25 +00002095 // fold (sdiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002096 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2097 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002098 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002099 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002100 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002101 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002102 return N0;
2103 // fold (sdiv X, -1) -> 0-X
2104 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002105 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002106 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002107 // If we know the sign bits of both operands are zero, strength reduce to a
2108 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002109 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002110 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002111 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002112 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002113 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002114
Nate Begeman57b35672006-02-17 07:26:20 +00002115 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002116 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2117 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002118 // If dividing by powers of two is cheap, then don't perform the following
2119 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002120 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002121 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002122
Chad Rosier17020f92014-07-23 14:57:52 +00002123 // Target-specific implementation of sdiv x, pow2.
2124 SDValue Res = BuildSDIVPow2(N);
2125 if (Res.getNode())
2126 return Res;
2127
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002128 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002129
Chris Lattner471627c2006-02-16 08:02:36 +00002130 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002131 SDValue SGN =
2132 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2133 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2134 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002135 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002136
Chris Lattner471627c2006-02-16 08:02:36 +00002137 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002138 SDValue SRL =
2139 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2140 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2141 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002142 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002143 AddToWorklist(SRL.getNode());
2144 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002145 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002146 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002147
Nate Begeman4dd38312005-10-21 00:02:42 +00002148 // If we're dividing by a positive value, we're done. Otherwise, we must
2149 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002150 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002151 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002152
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002153 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002154 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002155 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002156
Nate Begemanc6f067a2005-10-20 02:15:44 +00002157 // if integer divide is expensive and we satisfy the requirements, emit an
2158 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002159 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002160 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002161 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002162 }
Dan Gohmana8665142007-06-25 16:23:39 +00002163
Dan Gohman06563a82007-07-03 14:03:57 +00002164 // undef / X -> 0
2165 if (N0.getOpcode() == ISD::UNDEF)
2166 return DAG.getConstant(0, VT);
2167 // X / undef -> undef
2168 if (N1.getOpcode() == ISD::UNDEF)
2169 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002170
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002171 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002172}
2173
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002174SDValue DAGCombiner::visitUDIV(SDNode *N) {
2175 SDValue N0 = N->getOperand(0);
2176 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002177 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002178
Dan Gohmana8665142007-06-25 16:23:39 +00002179 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002180 if (VT.isVector())
2181 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2182 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002183
Nate Begeman21158fc2005-09-01 00:19:25 +00002184 // fold (udiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002185 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002187 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002188 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002189 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002190 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002191 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002192 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002193 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002194 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002195 if (N1.getOpcode() == ISD::SHL) {
2196 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002197 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002198 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002199 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002200 N1.getOperand(1),
2201 DAG.getConstant(SHC->getAPIntValue()
2202 .logBase2(),
2203 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002204 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002205 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002206 }
2207 }
2208 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002209 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002210 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002211 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002212 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002213 }
Dan Gohmana8665142007-06-25 16:23:39 +00002214
Dan Gohman06563a82007-07-03 14:03:57 +00002215 // undef / X -> 0
2216 if (N0.getOpcode() == ISD::UNDEF)
2217 return DAG.getConstant(0, VT);
2218 // X / undef -> undef
2219 if (N1.getOpcode() == ISD::UNDEF)
2220 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002221
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002222 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002223}
2224
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002225SDValue DAGCombiner::visitSREM(SDNode *N) {
2226 SDValue N0 = N->getOperand(0);
2227 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002228 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002229
Nate Begeman21158fc2005-09-01 00:19:25 +00002230 // fold (srem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002231 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002233 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002234 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002235 // If we know the sign bits of both operands are zero, strength reduce to a
2236 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002237 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002238 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002239 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Dan Gohman9a693412007-11-26 23:46:11 +00002242 // If X/C can be simplified by the division-by-constant logic, lower
2243 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002244 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002245 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002246 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002247 SDValue OptimizedDiv = combine(Div.getNode());
2248 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002249 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002250 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002251 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002252 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002253 return Sub;
2254 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002256
Dan Gohman06563a82007-07-03 14:03:57 +00002257 // undef % X -> 0
2258 if (N0.getOpcode() == ISD::UNDEF)
2259 return DAG.getConstant(0, VT);
2260 // X % undef -> undef
2261 if (N1.getOpcode() == ISD::UNDEF)
2262 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002263
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002264 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002265}
2266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002267SDValue DAGCombiner::visitUREM(SDNode *N) {
2268 SDValue N0 = N->getOperand(0);
2269 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002270 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002271
Nate Begeman21158fc2005-09-01 00:19:25 +00002272 // fold (urem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002273 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2274 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002275 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002276 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002277 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002278 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002279 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002280 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002281 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2282 if (N1.getOpcode() == ISD::SHL) {
2283 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002284 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002285 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002286 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002287 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002288 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002289 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002290 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002291 }
2292 }
2293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002294
Dan Gohman9a693412007-11-26 23:46:11 +00002295 // If X/C can be simplified by the division-by-constant logic, lower
2296 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002297 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002298 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002299 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002300 SDValue OptimizedDiv = combine(Div.getNode());
2301 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002302 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002303 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002304 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002305 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002306 return Sub;
2307 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002308 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002309
Dan Gohman06563a82007-07-03 14:03:57 +00002310 // undef % X -> 0
2311 if (N0.getOpcode() == ISD::UNDEF)
2312 return DAG.getConstant(0, VT);
2313 // X % undef -> undef
2314 if (N1.getOpcode() == ISD::UNDEF)
2315 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002317 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002318}
2319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002320SDValue DAGCombiner::visitMULHS(SDNode *N) {
2321 SDValue N0 = N->getOperand(0);
2322 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002324 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002325 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002326
Nate Begeman21158fc2005-09-01 00:19:25 +00002327 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002328 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002329 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002330 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002331 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002333 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002334 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002335 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002336 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002337 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002338
Chris Lattner10bd29f2010-12-13 08:39:01 +00002339 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2340 // plus a shift.
2341 if (VT.isSimple() && !VT.isVector()) {
2342 MVT Simple = VT.getSimpleVT();
2343 unsigned SimpleSize = Simple.getSizeInBits();
2344 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2345 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2346 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2347 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2348 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002349 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002350 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002351 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2352 }
2353 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002354
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002355 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002356}
2357
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002358SDValue DAGCombiner::visitMULHU(SDNode *N) {
2359 SDValue N0 = N->getOperand(0);
2360 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002361 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002362 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002363 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002364
Nate Begeman21158fc2005-09-01 00:19:25 +00002365 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002366 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002367 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002368 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002369 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002370 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002371 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002372 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002373 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002374
Chris Lattner10bd29f2010-12-13 08:39:01 +00002375 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2376 // plus a shift.
2377 if (VT.isSimple() && !VT.isVector()) {
2378 MVT Simple = VT.getSimpleVT();
2379 unsigned SimpleSize = Simple.getSizeInBits();
2380 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2383 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2384 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2385 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002386 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002387 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2388 }
2389 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002391 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002392}
2393
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002394/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2395/// give the opcodes for the two computations that are being performed. Return
2396/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002397SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002398 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002399 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002400 bool HiExists = N->hasAnyUseOfValue(1);
2401 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002402 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002403 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002404 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002405 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002406 }
2407
2408 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002409 bool LoExists = N->hasAnyUseOfValue(0);
2410 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002411 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002412 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002413 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002414 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002415 }
2416
Evan Chengece4c682007-11-08 09:25:29 +00002417 // If both halves are used, return as it is.
2418 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002419 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002420
2421 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002422 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002423 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002424 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002425 SDValue LoOpt = combine(Lo.getNode());
2426 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002427 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002428 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002429 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002430 }
2431
Evan Chengece4c682007-11-08 09:25:29 +00002432 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002433 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002434 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002435 SDValue HiOpt = combine(Hi.getNode());
2436 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002437 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002438 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002439 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002440 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002441
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002442 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002443}
2444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002445SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2446 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002447 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002448
Chris Lattner15090e12010-12-15 06:04:19 +00002449 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002450 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002451
2452 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2453 // plus a shift.
2454 if (VT.isSimple() && !VT.isVector()) {
2455 MVT Simple = VT.getSimpleVT();
2456 unsigned SimpleSize = Simple.getSizeInBits();
2457 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2460 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2461 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2462 // Compute the high part as N1.
2463 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002464 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002465 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2466 // Compute the low part as N0.
2467 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2468 return CombineTo(N, Lo, Hi);
2469 }
2470 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002471
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002472 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002473}
2474
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002475SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002477 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002478
Chris Lattner15090e12010-12-15 06:04:19 +00002479 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002481
Chris Lattner15090e12010-12-15 06:04:19 +00002482 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2483 // plus a shift.
2484 if (VT.isSimple() && !VT.isVector()) {
2485 MVT Simple = VT.getSimpleVT();
2486 unsigned SimpleSize = Simple.getSizeInBits();
2487 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2488 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2489 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2490 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2491 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2492 // Compute the high part as N1.
2493 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002494 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002495 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2496 // Compute the low part as N0.
2497 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2498 return CombineTo(N, Lo, Hi);
2499 }
2500 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002502 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002503}
2504
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002505SDValue DAGCombiner::visitSMULO(SDNode *N) {
2506 // (smulo x, 2) -> (saddo x, x)
2507 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2508 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002509 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002510 N->getOperand(0), N->getOperand(0));
2511
2512 return SDValue();
2513}
2514
2515SDValue DAGCombiner::visitUMULO(SDNode *N) {
2516 // (umulo x, 2) -> (uaddo x, x)
2517 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002519 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002520 N->getOperand(0), N->getOperand(0));
2521
2522 return SDValue();
2523}
2524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002525SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2526 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002527 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002528
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002529 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002530}
2531
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002532SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002534 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002536 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002537}
2538
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002539/// If this is a binary operator with two operands of the same opcode, try to
2540/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002541SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2542 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002543 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002544 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002545
Dan Gohmandd5286d2010-01-14 03:08:49 +00002546 // Bail early if none of these transforms apply.
2547 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2548
Chris Lattner002ee912006-05-05 06:31:05 +00002549 // For each of OP in AND/OR/XOR:
2550 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2551 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2552 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002553 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002554 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002555 //
2556 // do not sink logical op inside of a vector extend, since it may combine
2557 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002558 EVT Op0VT = N0.getOperand(0).getValueType();
2559 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002560 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002561 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002562 // Avoid infinite looping with PromoteIntBinOp.
2563 (N0.getOpcode() == ISD::ANY_EXTEND &&
2564 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002565 (N0.getOpcode() == ISD::TRUNCATE &&
2566 (!TLI.isZExtFree(VT, Op0VT) ||
2567 !TLI.isTruncateFree(Op0VT, VT)) &&
2568 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002569 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002570 Op0VT == N1.getOperand(0).getValueType() &&
2571 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002572 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002573 N0.getOperand(0).getValueType(),
2574 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002575 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002576 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002578
Chris Lattner5ac42932006-05-05 06:10:43 +00002579 // For each of OP in SHL/SRL/SRA/AND...
2580 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2581 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2582 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002583 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002584 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002585 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002586 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002587 N0.getOperand(0).getValueType(),
2588 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002589 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002590 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002591 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002592 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002593
Nadav Rotemb0783502012-04-01 19:31:22 +00002594 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2595 // Only perform this optimization after type legalization and before
2596 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2597 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2598 // we don't want to undo this promotion.
2599 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2600 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002601 if ((N0.getOpcode() == ISD::BITCAST ||
2602 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2603 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002604 SDValue In0 = N0.getOperand(0);
2605 SDValue In1 = N1.getOperand(0);
2606 EVT In0Ty = In0.getValueType();
2607 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002608 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002609 // If both incoming values are integers, and the original types are the
2610 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002611 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002612 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2613 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002614 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002615 return BC;
2616 }
2617 }
2618
2619 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2620 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2621 // If both shuffles use the same mask, and both shuffle within a single
2622 // vector, then it is worthwhile to move the swizzle after the operation.
2623 // The type-legalizer generates this pattern when loading illegal
2624 // vector types from memory. In many cases this allows additional shuffle
2625 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002626 // There are other cases where moving the shuffle after the xor/and/or
2627 // is profitable even if shuffles don't perform a swizzle.
2628 // If both shuffles use the same mask, and both shuffles have the same first
2629 // or second operand, then it might still be profitable to move the shuffle
2630 // after the xor/and/or operation.
2631 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002632 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2633 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002634
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002635 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002636 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002637
Nadav Rotemb0783502012-04-01 19:31:22 +00002638 // Check that both shuffles use the same mask. The masks are known to be of
2639 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002640 // Check also that shuffles have only one use to avoid introducing extra
2641 // instructions.
2642 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2643 SVN0->getMask().equals(SVN1->getMask())) {
2644 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002645
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002646 // Don't try to fold this node if it requires introducing a
2647 // build vector of all zeros that might be illegal at this stage.
2648 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2649 if (!LegalTypes)
2650 ShOp = DAG.getConstant(0, VT);
2651 else
2652 ShOp = SDValue();
2653 }
2654
2655 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2656 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2657 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2658 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2659 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2660 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002661 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002662 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2663 &SVN0->getMask()[0]);
2664 }
2665
2666 // Don't try to fold this node if it requires introducing a
2667 // build vector of all zeros that might be illegal at this stage.
2668 ShOp = N0->getOperand(0);
2669 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2670 if (!LegalTypes)
2671 ShOp = DAG.getConstant(0, VT);
2672 else
2673 ShOp = SDValue();
2674 }
2675
2676 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2677 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2678 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2679 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2680 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2681 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002682 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002683 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2684 &SVN0->getMask()[0]);
2685 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002686 }
2687 }
Craig Topper9c3da312012-04-09 07:19:09 +00002688
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002689 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002690}
2691
Matthias Braun3ecb5572015-03-06 19:49:06 +00002692/// This contains all DAGCombine rules which reduce two values combined by
2693/// an And operation to a single value. This makes them reusable in the context
2694/// of visitSELECT(). Rules involving constants are not included as
2695/// visitSELECT() already handles those cases.
2696SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2697 SDNode *LocReference) {
2698 EVT VT = N1.getValueType();
2699
2700 // fold (and x, undef) -> 0
2701 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2702 return DAG.getConstant(0, VT);
2703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704 SDValue LL, LR, RL, RR, CC0, CC1;
2705 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2706 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2707 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2708
2709 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2710 LL.getValueType().isInteger()) {
2711 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2712 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2713 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2714 LR.getValueType(), LL, RL);
2715 AddToWorklist(ORNode.getNode());
2716 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2717 }
2718 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2719 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2720 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorklist(ANDNode.getNode());
2723 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2724 }
2725 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2727 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorklist(ORNode.getNode());
2730 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2731 }
2732 }
2733 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2734 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2735 Op0 == Op1 && LL.getValueType().isInteger() &&
2736 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2737 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2738 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2739 cast<ConstantSDNode>(RR)->isNullValue()))) {
2740 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2741 LL, DAG.getConstant(1, LL.getValueType()));
2742 AddToWorklist(ADDNode.getNode());
2743 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2744 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2745 }
2746 // canonicalize equivalent to ll == rl
2747 if (LL == RR && LR == RL) {
2748 Op1 = ISD::getSetCCSwappedOperands(Op1);
2749 std::swap(RL, RR);
2750 }
2751 if (LL == RL && LR == RR) {
2752 bool isInteger = LL.getValueType().isInteger();
2753 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2754 if (Result != ISD::SETCC_INVALID &&
2755 (!LegalOperations ||
2756 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2757 TLI.isOperationLegal(ISD::SETCC,
2758 getSetCCResultType(N0.getSimpleValueType())))))
2759 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2760 LL, LR, Result);
2761 }
2762 }
2763
2764 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2765 VT.getSizeInBits() <= 64) {
2766 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2767 APInt ADDC = ADDI->getAPIntValue();
2768 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2769 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2770 // immediate for an add, but it is legal if its top c2 bits are set,
2771 // transform the ADD so the immediate doesn't need to be materialized
2772 // in a register.
2773 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2774 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2775 SRLI->getZExtValue());
2776 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2777 ADDC |= Mask;
2778 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779 SDValue NewAdd =
2780 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2781 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2782 CombineTo(N0.getNode(), NewAdd);
2783 // Return N so it doesn't get rechecked!
2784 return SDValue(LocReference, 0);
2785 }
2786 }
2787 }
2788 }
2789 }
2790 }
2791
2792 return SDValue();
2793}
2794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002795SDValue DAGCombiner::visitAND(SDNode *N) {
2796 SDValue N0 = N->getOperand(0);
2797 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002798 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002799
Dan Gohmana8665142007-06-25 16:23:39 +00002800 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002801 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002802 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2803 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002804
2805 // fold (and x, 0) -> 0, vector edition
2806 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002807 // do not return N0, because undef node may exist in N0
2808 return DAG.getConstant(
2809 APInt::getNullValue(
2810 N0.getValueType().getScalarType().getSizeInBits()),
2811 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002812 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002813 // do not return N1, because undef node may exist in N1
2814 return DAG.getConstant(
2815 APInt::getNullValue(
2816 N1.getValueType().getScalarType().getSizeInBits()),
2817 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002818
2819 // fold (and x, -1) -> x, vector edition
2820 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2821 return N1;
2822 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2823 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002825
Nate Begeman21158fc2005-09-01 00:19:25 +00002826 // fold (and c1, c2) -> c1&c2
Matthias Braun00a40762015-02-24 18:52:01 +00002827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002829 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002830 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002831 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002832 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002833 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002834 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002835 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002836 return N0;
2837 // if (and x, c) is known to be zero, return 0
Matthias Braun00a40762015-02-24 18:52:01 +00002838 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002839 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002840 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002841 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002842 // reassociate and
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002843 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002844 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002845 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002846 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002847 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002848 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002849 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002850 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2851 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002852 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002853 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002854 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002855 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002856 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002857 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002858
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002859 // Replace uses of the AND with uses of the Zero extend node.
2860 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002861
Chris Lattner49beaf42006-02-02 07:17:31 +00002862 // We actually want to replace all uses of the any_extend with the
2863 // zero_extend, to avoid duplicating things. This will later cause this
2864 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002865 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002867 }
2868 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002869 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002870 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2871 // already be zero by virtue of the width of the base type of the load.
2872 //
2873 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2874 // more cases.
2875 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2876 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2877 N0.getOpcode() == ISD::LOAD) {
2878 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2879 N0 : N0.getOperand(0) );
2880
2881 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2882 // This can be a pure constant or a vector splat, in which case we treat the
2883 // vector as a scalar and use the splat value.
2884 APInt Constant = APInt::getNullValue(1);
2885 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2886 Constant = C->getAPIntValue();
2887 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2888 APInt SplatValue, SplatUndef;
2889 unsigned SplatBitSize;
2890 bool HasAnyUndefs;
2891 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2892 SplatBitSize, HasAnyUndefs);
2893 if (IsSplat) {
2894 // Undef bits can contribute to a possible optimisation if set, so
2895 // set them.
2896 SplatValue |= SplatUndef;
2897
2898 // The splat value may be something like "0x00FFFFFF", which means 0 for
2899 // the first vector value and FF for the rest, repeating. We need a mask
2900 // that will apply equally to all members of the vector, so AND all the
2901 // lanes of the constant together.
2902 EVT VT = Vector->getValueType(0);
2903 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002904
2905 // If the splat value has been compressed to a bitlength lower
2906 // than the size of the vector lane, we need to re-expand it to
2907 // the lane size.
2908 if (BitWidth > SplatBitSize)
2909 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2910 SplatBitSize < BitWidth;
2911 SplatBitSize = SplatBitSize * 2)
2912 SplatValue |= SplatValue.shl(SplatBitSize);
2913
Andrea Di Biagioc9d79e82015-03-07 12:24:55 +00002914 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2915 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2916 if (SplatBitSize % BitWidth == 0) {
2917 Constant = APInt::getAllOnesValue(BitWidth);
2918 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2919 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2920 }
James Molloy862fe492012-02-20 12:02:38 +00002921 }
2922 }
2923
2924 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2925 // actually legal and isn't going to get expanded, else this is a false
2926 // optimisation.
2927 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002928 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002929 Load->getMemoryVT());
2930
2931 // Resize the constant to the same size as the original memory access before
2932 // extension. If it is still the AllOnesValue then this AND is completely
2933 // unneeded.
2934 Constant =
2935 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2936
2937 bool B;
2938 switch (Load->getExtensionType()) {
2939 default: B = false; break;
2940 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2941 case ISD::ZEXTLOAD:
2942 case ISD::NON_EXTLOAD: B = true; break;
2943 }
2944
2945 if (B && Constant.isAllOnesValue()) {
2946 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2947 // preserve semantics once we get rid of the AND.
2948 SDValue NewLoad(Load, 0);
2949 if (Load->getExtensionType() == ISD::EXTLOAD) {
2950 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002951 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002952 Load->getChain(), Load->getBasePtr(),
2953 Load->getOffset(), Load->getMemoryVT(),
2954 Load->getMemOperand());
2955 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002956 if (Load->getNumValues() == 3) {
2957 // PRE/POST_INC loads have 3 values.
2958 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2959 NewLoad.getValue(2) };
2960 CombineTo(Load, To, 3, true);
2961 } else {
2962 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2963 }
James Molloy862fe492012-02-20 12:02:38 +00002964 }
2965
2966 // Fold the AND away, taking care not to fold to the old load node if we
2967 // replaced it.
2968 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2969
2970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2971 }
2972 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002973
Chris Lattnerf0032b32006-02-28 06:49:37 +00002974 // fold (and (load x), 255) -> (zextload x, i8)
2975 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002976 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2977 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2978 (N0.getOpcode() == ISD::ANY_EXTEND &&
2979 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2980 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2981 LoadSDNode *LN0 = HasAnyExt
2982 ? cast<LoadSDNode>(N0.getOperand(0))
2983 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002984 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002985 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002986 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002987 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2988 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2989 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002990 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00002991
Evan Cheng166a4e62010-01-06 19:38:29 +00002992 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002993 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00002995
2996 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002997 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002998 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2999 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003000 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003001 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3003 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003004
Chris Lattner88de3842010-01-07 21:53:27 +00003005 // Do not change the width of a volatile load.
3006 // Do not generate loads of non-round integer types since these can
3007 // be expensive (and would be wrong if the type is not byte sized).
3008 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003009 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3010 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003011 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003012
Chris Lattner88de3842010-01-07 21:53:27 +00003013 unsigned Alignment = LN0->getAlignment();
3014 SDValue NewPtr = LN0->getBasePtr();
3015
3016 // For big endian targets, we need to add an offset to the pointer
3017 // to load the correct bytes. For little endian systems, we merely
3018 // need to read fewer bytes from the same pointer.
3019 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003020 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3021 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3022 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003023 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003024 NewPtr, DAG.getConstant(PtrOff, PtrType));
3025 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003026 }
Chris Lattner88de3842010-01-07 21:53:27 +00003027
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003028 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003029
Chris Lattner88de3842010-01-07 21:53:27 +00003030 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003032 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003033 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003034 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003035 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003036 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003037 CombineTo(LN0, Load, Load.getValue(1));
3038 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003039 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003040 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003041 }
3042 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003043
Matthias Braun3ecb5572015-03-06 19:49:06 +00003044 if (SDValue Combined = visitANDLike(N0, N1, N))
3045 return Combined;
3046
3047 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3048 if (N0.getOpcode() == N1.getOpcode()) {
3049 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3050 if (Tmp.getNode()) return Tmp;
Evan Chenge6a3b032012-07-17 18:54:11 +00003051 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003052
Matthias Braun3ecb5572015-03-06 19:49:06 +00003053 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3054 // fold (and (sra)) -> (and (srl)) when possible.
3055 if (!VT.isVector() &&
3056 SimplifyDemandedBits(SDValue(N, 0)))
3057 return SDValue(N, 0);
3058
3059 // fold (zext_inreg (extload x)) -> (zextload x)
3060 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3061 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3062 EVT MemVT = LN0->getMemoryVT();
3063 // If we zero all the possible extended bits, then we can turn this into
3064 // a zextload if we are running before legalize or the operation is legal.
3065 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3066 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3067 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3068 ((!LegalOperations && !LN0->isVolatile()) ||
3069 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3070 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3071 LN0->getChain(), LN0->getBasePtr(),
3072 MemVT, LN0->getMemOperand());
3073 AddToWorklist(N);
3074 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3075 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3076 }
3077 }
3078 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3079 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3080 N0.hasOneUse()) {
3081 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3082 EVT MemVT = LN0->getMemoryVT();
3083 // If we zero all the possible extended bits, then we can turn this into
3084 // a zextload if we are running before legalize or the operation is legal.
3085 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3086 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3087 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3088 ((!LegalOperations && !LN0->isVolatile()) ||
3089 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3090 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3091 LN0->getChain(), LN0->getBasePtr(),
3092 MemVT, LN0->getMemOperand());
3093 AddToWorklist(N);
3094 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3095 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3096 }
3097 }
Tim Northover819bfb52013-08-27 13:46:45 +00003098 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3099 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3100 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3101 N0.getOperand(1), false);
3102 if (BSwap.getNode())
3103 return BSwap;
3104 }
3105
Evan Chengf1005572010-04-28 07:10:39 +00003106 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003107}
3108
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003109/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003110SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3111 bool DemandHighBits) {
3112 if (!LegalOperations)
3113 return SDValue();
3114
3115 EVT VT = N->getValueType(0);
3116 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3117 return SDValue();
3118 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3119 return SDValue();
3120
3121 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3122 bool LookPassAnd0 = false;
3123 bool LookPassAnd1 = false;
3124 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3125 std::swap(N0, N1);
3126 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3127 std::swap(N0, N1);
3128 if (N0.getOpcode() == ISD::AND) {
3129 if (!N0.getNode()->hasOneUse())
3130 return SDValue();
3131 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3132 if (!N01C || N01C->getZExtValue() != 0xFF00)
3133 return SDValue();
3134 N0 = N0.getOperand(0);
3135 LookPassAnd0 = true;
3136 }
3137
3138 if (N1.getOpcode() == ISD::AND) {
3139 if (!N1.getNode()->hasOneUse())
3140 return SDValue();
3141 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3142 if (!N11C || N11C->getZExtValue() != 0xFF)
3143 return SDValue();
3144 N1 = N1.getOperand(0);
3145 LookPassAnd1 = true;
3146 }
3147
3148 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3149 std::swap(N0, N1);
3150 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3151 return SDValue();
3152 if (!N0.getNode()->hasOneUse() ||
3153 !N1.getNode()->hasOneUse())
3154 return SDValue();
3155
3156 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3157 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3158 if (!N01C || !N11C)
3159 return SDValue();
3160 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3161 return SDValue();
3162
3163 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3164 SDValue N00 = N0->getOperand(0);
3165 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3166 if (!N00.getNode()->hasOneUse())
3167 return SDValue();
3168 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3169 if (!N001C || N001C->getZExtValue() != 0xFF)
3170 return SDValue();
3171 N00 = N00.getOperand(0);
3172 LookPassAnd0 = true;
3173 }
3174
3175 SDValue N10 = N1->getOperand(0);
3176 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3177 if (!N10.getNode()->hasOneUse())
3178 return SDValue();
3179 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3180 if (!N101C || N101C->getZExtValue() != 0xFF00)
3181 return SDValue();
3182 N10 = N10.getOperand(0);
3183 LookPassAnd1 = true;
3184 }
3185
3186 if (N00 != N10)
3187 return SDValue();
3188
Tim Northover819bfb52013-08-27 13:46:45 +00003189 // Make sure everything beyond the low halfword gets set to zero since the SRL
3190 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003191 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003192 if (DemandHighBits && OpSizeInBits > 16) {
3193 // If the left-shift isn't masked out then the only way this is a bswap is
3194 // if all bits beyond the low 8 are 0. In that case the entire pattern
3195 // reduces to a left shift anyway: leave it for other parts of the combiner.
3196 if (!LookPassAnd0)
3197 return SDValue();
3198
3199 // However, if the right shift isn't masked out then it might be because
3200 // it's not needed. See if we can spot that too.
3201 if (!LookPassAnd1 &&
3202 !DAG.MaskedValueIsZero(
3203 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3204 return SDValue();
3205 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003206
Andrew Trickef9de2a2013-05-25 02:42:55 +00003207 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003208 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003209 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003210 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3211 return Res;
3212}
3213
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003214/// Return true if the specified node is an element that makes up a 32-bit
3215/// packed halfword byteswap.
3216/// ((x & 0x000000ff) << 8) |
3217/// ((x & 0x0000ff00) >> 8) |
3218/// ((x & 0x00ff0000) << 8) |
3219/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003220static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003221 if (!N.getNode()->hasOneUse())
3222 return false;
3223
3224 unsigned Opc = N.getOpcode();
3225 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3226 return false;
3227
3228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3229 if (!N1C)
3230 return false;
3231
3232 unsigned Num;
3233 switch (N1C->getZExtValue()) {
3234 default:
3235 return false;
3236 case 0xFF: Num = 0; break;
3237 case 0xFF00: Num = 1; break;
3238 case 0xFF0000: Num = 2; break;
3239 case 0xFF000000: Num = 3; break;
3240 }
3241
3242 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3243 SDValue N0 = N.getOperand(0);
3244 if (Opc == ISD::AND) {
3245 if (Num == 0 || Num == 2) {
3246 // (x >> 8) & 0xff
3247 // (x >> 8) & 0xff0000
3248 if (N0.getOpcode() != ISD::SRL)
3249 return false;
3250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3251 if (!C || C->getZExtValue() != 8)
3252 return false;
3253 } else {
3254 // (x << 8) & 0xff00
3255 // (x << 8) & 0xff000000
3256 if (N0.getOpcode() != ISD::SHL)
3257 return false;
3258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259 if (!C || C->getZExtValue() != 8)
3260 return false;
3261 }
3262 } else if (Opc == ISD::SHL) {
3263 // (x & 0xff) << 8
3264 // (x & 0xff0000) << 8
3265 if (Num != 0 && Num != 2)
3266 return false;
3267 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3268 if (!C || C->getZExtValue() != 8)
3269 return false;
3270 } else { // Opc == ISD::SRL
3271 // (x & 0xff00) >> 8
3272 // (x & 0xff000000) >> 8
3273 if (Num != 1 && Num != 3)
3274 return false;
3275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276 if (!C || C->getZExtValue() != 8)
3277 return false;
3278 }
3279
3280 if (Parts[Num])
3281 return false;
3282
3283 Parts[Num] = N0.getOperand(0).getNode();
3284 return true;
3285}
3286
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003287/// Match a 32-bit packed halfword bswap. That is
3288/// ((x & 0x000000ff) << 8) |
3289/// ((x & 0x0000ff00) >> 8) |
3290/// ((x & 0x00ff0000) << 8) |
3291/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003292/// => (rotl (bswap x), 16)
3293SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3294 if (!LegalOperations)
3295 return SDValue();
3296
3297 EVT VT = N->getValueType(0);
3298 if (VT != MVT::i32)
3299 return SDValue();
3300 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3301 return SDValue();
3302
Evan Cheng4c0bd962011-06-21 06:01:08 +00003303 // Look for either
3304 // (or (or (and), (and)), (or (and), (and)))
3305 // (or (or (or (and), (and)), (and)), (and))
3306 if (N0.getOpcode() != ISD::OR)
3307 return SDValue();
3308 SDValue N00 = N0.getOperand(0);
3309 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003310 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003311
Evan Chengbf0baa92012-12-13 01:34:32 +00003312 if (N1.getOpcode() == ISD::OR &&
3313 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003314 // (or (or (and), (and)), (or (and), (and)))
3315 SDValue N000 = N00.getOperand(0);
3316 if (!isBSwapHWordElement(N000, Parts))
3317 return SDValue();
3318
3319 SDValue N001 = N00.getOperand(1);
3320 if (!isBSwapHWordElement(N001, Parts))
3321 return SDValue();
3322 SDValue N010 = N01.getOperand(0);
3323 if (!isBSwapHWordElement(N010, Parts))
3324 return SDValue();
3325 SDValue N011 = N01.getOperand(1);
3326 if (!isBSwapHWordElement(N011, Parts))
3327 return SDValue();
3328 } else {
3329 // (or (or (or (and), (and)), (and)), (and))
3330 if (!isBSwapHWordElement(N1, Parts))
3331 return SDValue();
3332 if (!isBSwapHWordElement(N01, Parts))
3333 return SDValue();
3334 if (N00.getOpcode() != ISD::OR)
3335 return SDValue();
3336 SDValue N000 = N00.getOperand(0);
3337 if (!isBSwapHWordElement(N000, Parts))
3338 return SDValue();
3339 SDValue N001 = N00.getOperand(1);
3340 if (!isBSwapHWordElement(N001, Parts))
3341 return SDValue();
3342 }
3343
3344 // Make sure the parts are all coming from the same node.
3345 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3346 return SDValue();
3347
Andrew Trickef9de2a2013-05-25 02:42:55 +00003348 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003349 SDValue(Parts[0],0));
3350
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003351 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003352 // do (x << 16) | (x >> 16).
3353 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3354 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003355 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003356 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003357 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3358 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3359 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3360 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003361}
3362
Matthias Braun3ecb5572015-03-06 19:49:06 +00003363/// This contains all DAGCombine rules which reduce two values combined by
3364/// an Or operation to a single value \see visitANDLike().
3365SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3366 EVT VT = N1.getValueType();
3367 // fold (or x, undef) -> -1
3368 if (!LegalOperations &&
3369 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3370 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3371 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3372 }
3373 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3374 SDValue LL, LR, RL, RR, CC0, CC1;
3375 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3376 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3377 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3378
3379 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3380 LL.getValueType().isInteger()) {
3381 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3382 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3383 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3384 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3385 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3386 LR.getValueType(), LL, RL);
3387 AddToWorklist(ORNode.getNode());
3388 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3389 }
3390 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3391 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3392 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3393 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3394 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3395 LR.getValueType(), LL, RL);
3396 AddToWorklist(ANDNode.getNode());
3397 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3398 }
3399 }
3400 // canonicalize equivalent to ll == rl
3401 if (LL == RR && LR == RL) {
3402 Op1 = ISD::getSetCCSwappedOperands(Op1);
3403 std::swap(RL, RR);
3404 }
3405 if (LL == RL && LR == RR) {
3406 bool isInteger = LL.getValueType().isInteger();
3407 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3408 if (Result != ISD::SETCC_INVALID &&
3409 (!LegalOperations ||
3410 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3411 TLI.isOperationLegal(ISD::SETCC,
3412 getSetCCResultType(N0.getValueType())))))
3413 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3414 LL, LR, Result);
3415 }
3416 }
3417
3418 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3419 if (N0.getOpcode() == ISD::AND &&
3420 N1.getOpcode() == ISD::AND &&
3421 N0.getOperand(1).getOpcode() == ISD::Constant &&
3422 N1.getOperand(1).getOpcode() == ISD::Constant &&
3423 // Don't increase # computations.
3424 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3425 // We can only do this xform if we know that bits from X that are set in C2
3426 // but not in C1 are already zero. Likewise for Y.
3427 const APInt &LHSMask =
3428 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3429 const APInt &RHSMask =
3430 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3431
3432 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3433 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3434 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3435 N0.getOperand(0), N1.getOperand(0));
3436 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3437 DAG.getConstant(LHSMask | RHSMask, VT));
3438 }
3439 }
3440
3441 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3442 if (N0.getOpcode() == ISD::AND &&
3443 N1.getOpcode() == ISD::AND &&
3444 N0.getOperand(0) == N1.getOperand(0) &&
3445 // Don't increase # computations.
3446 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3447 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3448 N0.getOperand(1), N1.getOperand(1));
3449 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3450 }
3451
3452 return SDValue();
3453}
3454
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003455SDValue DAGCombiner::visitOR(SDNode *N) {
3456 SDValue N0 = N->getOperand(0);
3457 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003458 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003459
Dan Gohmana8665142007-06-25 16:23:39 +00003460 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003461 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003462 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3463 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003464
3465 // fold (or x, 0) -> x, vector edition
3466 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3467 return N1;
3468 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3469 return N0;
3470
3471 // fold (or x, -1) -> -1, vector edition
3472 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003473 // do not return N0, because undef node may exist in N0
3474 return DAG.getConstant(
3475 APInt::getAllOnesValue(
3476 N0.getValueType().getScalarType().getSizeInBits()),
3477 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003478 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003479 // do not return N1, because undef node may exist in N1
3480 return DAG.getConstant(
3481 APInt::getAllOnesValue(
3482 N1.getValueType().getScalarType().getSizeInBits()),
3483 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003484
3485 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3486 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3487 // Do this only if the resulting shuffle is legal.
3488 if (isa<ShuffleVectorSDNode>(N0) &&
3489 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003490 // Avoid folding a node with illegal type.
3491 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003492 N0->getOperand(1) == N1->getOperand(1) &&
3493 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3494 bool CanFold = true;
3495 unsigned NumElts = VT.getVectorNumElements();
3496 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3497 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3498 // We construct two shuffle masks:
3499 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3500 // and N1 as the second operand.
3501 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3502 // and N0 as the second operand.
3503 // We do this because OR is commutable and therefore there might be
3504 // two ways to fold this node into a shuffle.
3505 SmallVector<int,4> Mask1;
3506 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003507
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003508 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3509 int M0 = SV0->getMaskElt(i);
3510 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003511
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003512 // Both shuffle indexes are undef. Propagate Undef.
3513 if (M0 < 0 && M1 < 0) {
3514 Mask1.push_back(M0);
3515 Mask2.push_back(M0);
3516 continue;
3517 }
3518
3519 if (M0 < 0 || M1 < 0 ||
3520 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3521 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3522 CanFold = false;
3523 break;
3524 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003525
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003526 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3527 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3528 }
3529
3530 if (CanFold) {
3531 // Fold this sequence only if the resulting shuffle is 'legal'.
3532 if (TLI.isShuffleMaskLegal(Mask1, VT))
3533 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3534 N1->getOperand(0), &Mask1[0]);
3535 if (TLI.isShuffleMaskLegal(Mask2, VT))
3536 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3537 N0->getOperand(0), &Mask2[0]);
3538 }
3539 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003540 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003541
Nate Begeman21158fc2005-09-01 00:19:25 +00003542 // fold (or c1, c2) -> c1|c2
Matthias Braun00a40762015-02-24 18:52:01 +00003543 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3544 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003545 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003546 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003547 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003548 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003549 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003550 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003551 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003552 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003553 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003554 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003555 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003556 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003557 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003558 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003559
Matthias Braun3ecb5572015-03-06 19:49:06 +00003560 if (SDValue Combined = visitORLike(N0, N1, N))
3561 return Combined;
3562
Evan Cheng4c0bd962011-06-21 06:01:08 +00003563 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3564 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003565 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003566 return BSwap;
3567 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003568 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003569 return BSwap;
3570
Nate Begeman22e251a2006-02-03 06:46:56 +00003571 // reassociate or
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003572 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003573 return ROR;
3574 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003575 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003576 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003577 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003578 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003579 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Matthias Braunf50ab432015-01-13 22:17:46 +00003580 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3581 return DAG.getNode(
3582 ISD::AND, SDLoc(N), VT,
3583 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3584 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003585 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003586 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003587 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003588 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003589 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003590 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003591 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003592
Chris Lattner97614c82006-09-14 20:50:57 +00003593 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003594 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003595 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003596
Dan Gohman600f62b2010-06-24 14:30:44 +00003597 // Simplify the operands using demanded-bits information.
3598 if (!VT.isVector() &&
3599 SimplifyDemandedBits(SDValue(N, 0)))
3600 return SDValue(N, 0);
3601
Evan Chengf1005572010-04-28 07:10:39 +00003602 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003603}
3604
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003605/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003606static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003607 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003608 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003609 Mask = Op.getOperand(1);
3610 Op = Op.getOperand(0);
3611 } else {
3612 return false;
3613 }
3614 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003615
Chris Lattner97614c82006-09-14 20:50:57 +00003616 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3617 Shift = Op;
3618 return true;
3619 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003620
Scott Michelcf0da6c2009-02-17 22:15:04 +00003621 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003622}
3623
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003624// Return true if we can prove that, whenever Neg and Pos are both in the
3625// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003626// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3627//
3628// (or (shift1 X, Neg), (shift2 X, Pos))
3629//
Adam Nemetc6553a82014-03-07 23:56:24 +00003630// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3631// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3632// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003633static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003634 // If OpSize is a power of 2 then:
3635 //
3636 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3637 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3638 //
3639 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3640 // for the stronger condition:
3641 //
3642 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3643 //
3644 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3645 // we can just replace Neg with Neg' for the rest of the function.
3646 //
3647 // In other cases we check for the even stronger condition:
3648 //
3649 // Neg == OpSize - Pos [B]
3650 //
3651 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3652 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003653 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003654 // We could actually use [A] whenever OpSize is a power of 2, but the
3655 // only extra cases that it would match are those uninteresting ones
3656 // where Neg and Pos are never in range at the same time. E.g. for
3657 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3658 // as well as (sub 32, Pos), but:
3659 //
3660 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3661 //
3662 // always invokes undefined behavior for 32-bit X.
3663 //
3664 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003665 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003666 if (Neg.getOpcode() == ISD::AND &&
3667 isPowerOf2_64(OpSize) &&
3668 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3669 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3670 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003671 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003672 }
3673
Richard Sandiford0f264db2014-01-09 10:49:40 +00003674 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3675 if (Neg.getOpcode() != ISD::SUB)
3676 return 0;
3677 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3678 if (!NegC)
3679 return 0;
3680 SDValue NegOp1 = Neg.getOperand(1);
3681
Adam Nemet5117f5d2014-03-07 23:56:28 +00003682 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3683 // Pos'. The truncation is redundant for the purpose of the equality.
3684 if (MaskLoBits &&
3685 Pos.getOpcode() == ISD::AND &&
3686 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3687 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3688 Pos = Pos.getOperand(0);
3689
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003690 // The condition we need is now:
3691 //
3692 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3693 //
3694 // If NegOp1 == Pos then we need:
3695 //
3696 // OpSize & Mask == NegC & Mask
3697 //
3698 // (because "x & Mask" is a truncation and distributes through subtraction).
3699 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003700 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003701 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003702 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3703 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003704 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003705 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3706 //
3707 // which, again because "x & Mask" is a truncation, becomes:
3708 //
3709 // NegC & Mask == (OpSize - PosC) & Mask
3710 // OpSize & Mask == (NegC + PosC) & Mask
3711 else if (Pos.getOpcode() == ISD::ADD &&
3712 Pos.getOperand(0) == NegOp1 &&
3713 Pos.getOperand(1).getOpcode() == ISD::Constant)
3714 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3715 NegC->getAPIntValue());
3716 else
3717 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003718
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003719 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003720 if (MaskLoBits)
3721 // Opsize & Mask is 0 since Mask is Opsize - 1.
3722 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003723 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003724}
3725
Richard Sandiford95c864d2014-01-08 15:40:47 +00003726// A subroutine of MatchRotate used once we have found an OR of two opposite
3727// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3728// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3729// former being preferred if supported. InnerPos and InnerNeg are Pos and
3730// Neg with outer conversions stripped away.
3731SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3732 SDValue Neg, SDValue InnerPos,
3733 SDValue InnerNeg, unsigned PosOpcode,
3734 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003735 // fold (or (shl x, (*ext y)),
3736 // (srl x, (*ext (sub 32, y)))) ->
3737 // (rotl x, y) or (rotr x, (sub 32, y))
3738 //
3739 // fold (or (shl x, (*ext (sub 32, y))),
3740 // (srl x, (*ext y))) ->
3741 // (rotr x, y) or (rotl x, (sub 32, y))
3742 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003743 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003744 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3745 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3746 HasPos ? Pos : Neg).getNode();
3747 }
3748
Craig Topperc0196b12014-04-14 00:51:57 +00003749 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003750}
3751
Chris Lattner97614c82006-09-14 20:50:57 +00003752// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3753// idioms for rotate, and if the target supports rotation instructions, generate
3754// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003755SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003756 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003757 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003758 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003759
3760 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003761 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3762 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003763 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003764
Chris Lattner97614c82006-09-14 20:50:57 +00003765 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003766 SDValue LHSShift; // The shift.
3767 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003768 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003769 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003770
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003771 SDValue RHSShift; // The shift.
3772 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003773 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003774 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003775
Chris Lattner97614c82006-09-14 20:50:57 +00003776 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003777 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003778
3779 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003780 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003781
Chris Lattner97614c82006-09-14 20:50:57 +00003782 // Canonicalize shl to left side in a shl/srl pair.
3783 if (RHSShift.getOpcode() == ISD::SHL) {
3784 std::swap(LHS, RHS);
3785 std::swap(LHSShift, RHSShift);
3786 std::swap(LHSMask , RHSMask );
3787 }
3788
Duncan Sands13237ac2008-06-06 12:08:01 +00003789 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003790 SDValue LHSShiftArg = LHSShift.getOperand(0);
3791 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003792 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003793 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003794
3795 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3796 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003797 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3798 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003799 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3800 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003801 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003802 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003803
Craig Topper65161fa2012-09-29 06:54:22 +00003804 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3805 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003806
Chris Lattner97614c82006-09-14 20:50:57 +00003807 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003808 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003809 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003810
Gabor Greiff304a7a2008-08-28 21:40:38 +00003811 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003812 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3813 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003814 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003815 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003816 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3817 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003818 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003819
Bill Wendling35972a92009-01-30 21:14:50 +00003820 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003822
Gabor Greiff304a7a2008-08-28 21:40:38 +00003823 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003825
Chris Lattner97614c82006-09-14 20:50:57 +00003826 // If there is a mask here, and we have a variable shift, we can't be sure
3827 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003828 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003829 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003830
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003831 // If the shift amount is sign/zext/any-extended just peel it off.
3832 SDValue LExtOp0 = LHSShiftAmt;
3833 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003834 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3835 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3836 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3837 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3838 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3839 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3840 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3841 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003842 LExtOp0 = LHSShiftAmt.getOperand(0);
3843 RExtOp0 = RHSShiftAmt.getOperand(0);
3844 }
3845
Richard Sandiford95c864d2014-01-08 15:40:47 +00003846 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3847 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3848 if (TryL)
3849 return TryL;
3850
3851 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3852 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3853 if (TryR)
3854 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003855
Craig Topperc0196b12014-04-14 00:51:57 +00003856 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003857}
3858
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003859SDValue DAGCombiner::visitXOR(SDNode *N) {
3860 SDValue N0 = N->getOperand(0);
3861 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003862 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003863
Dan Gohmana8665142007-06-25 16:23:39 +00003864 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003865 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003866 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3867 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003868
3869 // fold (xor x, 0) -> x, vector edition
3870 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3871 return N1;
3872 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3873 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003874 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003875
Evan Chengdf1690d2008-03-25 20:08:07 +00003876 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3877 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3878 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003879 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003880 if (N0.getOpcode() == ISD::UNDEF)
3881 return N0;
3882 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003883 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003884 // fold (xor c1, c2) -> c1^c2
Matthias Braun00a40762015-02-24 18:52:01 +00003885 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3886 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003887 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003888 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003889 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003890 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003891 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003892 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003893 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003894 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003895 // reassociate xor
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003896 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003897 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003898
Nate Begeman21158fc2005-09-01 00:19:25 +00003899 // fold !(x cc y) -> (x !cc y)
Matthias Brauna8558ca2015-02-24 18:51:59 +00003900 SDValue LHS, RHS, CC;
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003901 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003902 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003903 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3904 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003905
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003906 if (!LegalOperations ||
3907 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003908 switch (N0.getOpcode()) {
3909 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003910 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003911 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003912 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003913 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003914 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003915 N0.getOperand(3), NotCC);
3916 }
3917 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003918 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003919
Chris Lattner58c227b2007-09-10 21:39:07 +00003920 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003921 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003922 N0.getNode()->hasOneUse() &&
3923 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003924 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003925 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003926 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003927 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003928 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003929 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003931 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003932 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003933 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003934 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003935 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3936 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003937 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3938 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003939 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003940 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003941 }
3942 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003943 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003944 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003945 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003946 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003947 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3948 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003949 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3950 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003951 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003952 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003953 }
3954 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003955 // fold (xor (and x, y), y) -> (and (not x), y)
3956 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003957 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003958 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003959 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003960 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003961 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003962 }
Bill Wendling35972a92009-01-30 21:14:50 +00003963 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003964 if (N1C && N0.getOpcode() == ISD::XOR) {
3965 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3966 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3967 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003968 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003969 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003970 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003971 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003972 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003973 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003974 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003975 }
3976 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003977 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003978 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003979
David Majnemere48237d2015-03-18 00:03:36 +00003980 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3981 // Here is a concrete example of this equivalence:
3982 // i16 x == 14
3983 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
3984 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3985 //
3986 // =>
3987 //
3988 // i16 ~1 == 0b1111111111111110
3989 // i16 rol(~1, 14) == 0b1011111111111111
3990 //
3991 // Some additional tips to help conceptualize this transform:
3992 // - Try to see the operation as placing a single zero in a value of all ones.
3993 // - There exists no value for x which would allow the result to contain zero.
3994 // - Values of x larger than the bitwidth are undefined and do not require a
3995 // consistent result.
3996 // - Pushing the zero left requires shifting one bits in from the right.
3997 // A rotate left of ~1 is a nice way of achieving the desired result.
3998 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3999 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4000 if (N0.getOpcode() == ISD::SHL)
4001 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4002 if (N1C->isAllOnesValue() && ShlLHS->isOne())
4003 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4004 N0.getOperand(1));
4005
Chris Lattner8d6fc202006-05-05 05:51:50 +00004006 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4007 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004008 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004009 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00004010 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004011
Chris Lattner098c01e2006-04-08 04:15:24 +00004012 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00004013 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004014 SimplifyDemandedBits(SDValue(N, 0)))
4015 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004016
Evan Chengf1005572010-04-28 07:10:39 +00004017 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004018}
4019
Sanjay Patel50cbfc52014-08-28 16:29:51 +00004020/// Handle transforms common to the three shifts, when the shift amount is a
4021/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004022SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004023 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004024 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004025 return SDValue();
4026
Gabor Greiff304a7a2008-08-28 21:40:38 +00004027 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004028 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004029
Chris Lattner7c709a52007-12-06 07:33:36 +00004030 // We want to pull some binops through shifts, so that we have (and (shift))
4031 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4032 // thing happens with address calculations, so it's important to canonicalize
4033 // it.
4034 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00004035
Chris Lattner7c709a52007-12-06 07:33:36 +00004036 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004037 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004038 case ISD::OR:
4039 case ISD::XOR:
4040 HighBitSet = false; // We can only transform sra if the high bit is clear.
4041 break;
4042 case ISD::AND:
4043 HighBitSet = true; // We can only transform sra if the high bit is set.
4044 break;
4045 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00004046 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004047 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00004048 HighBitSet = false; // We can only transform sra if the high bit is clear.
4049 break;
4050 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004051
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004052 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00004053 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004054 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004055
4056 // FIXME: disable this unless the input to the binop is a shift by a constant.
4057 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004058 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004059 // void foo(int *X, int i) { X[i & 1235] = 1; }
4060 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004061 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004062 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004063 BinOpLHSVal->getOpcode() != ISD::SRA &&
4064 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4065 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004066 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004067
Owen Anderson53aa7a92009-08-10 22:56:29 +00004068 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004069
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004070 // If this is a signed shift right, and the high bit is modified by the
4071 // logical operation, do not perform the transformation. The highBitSet
4072 // boolean indicates the value of the high bit of the constant which would
4073 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004074 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004075 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4076 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004077 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004078 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004079
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004080 if (!TLI.isDesirableToCommuteWithShift(LHS))
4081 return SDValue();
4082
Chris Lattner7c709a52007-12-06 07:33:36 +00004083 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004084 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004085 N->getValueType(0),
4086 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004087 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004088
4089 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004090 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004091 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004092 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004093
4094 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004095 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004096}
4097
Adam Nemet67483892014-03-04 23:28:31 +00004098SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4099 assert(N->getOpcode() == ISD::TRUNCATE);
4100 assert(N->getOperand(0).getOpcode() == ISD::AND);
4101
4102 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4103 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4104 SDValue N01 = N->getOperand(0).getOperand(1);
4105
Matt Arsenault985b9de2014-03-17 18:58:01 +00004106 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004107 EVT TruncVT = N->getValueType(0);
4108 SDValue N00 = N->getOperand(0).getOperand(0);
4109 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004110 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004111
4112 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4113 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4114 DAG.getConstant(TruncC, TruncVT));
4115 }
4116 }
4117
4118 return SDValue();
4119}
Adam Nemet7f928f12014-03-07 23:56:30 +00004120
4121SDValue DAGCombiner::visitRotate(SDNode *N) {
4122 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4123 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4124 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4125 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4126 if (NewOp1.getNode())
4127 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4128 N->getOperand(0), NewOp1);
4129 }
4130 return SDValue();
4131}
4132
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004133SDValue DAGCombiner::visitSHL(SDNode *N) {
4134 SDValue N0 = N->getOperand(0);
4135 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004136 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004137 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004138
Daniel Sandersa1840d22013-11-11 17:23:41 +00004139 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004141 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004142 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4143 return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004144
4145 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4146 // If setcc produces all-one true value then:
4147 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004148 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004149 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004150 SDValue N00 = N0->getOperand(0);
4151 SDValue N01 = N0->getOperand(1);
4152 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004153
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004154 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4155 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4156 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matthias Braunf50ab432015-01-13 22:17:46 +00004157 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004158 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4159 }
4160 } else {
4161 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004162 }
4163 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004164 }
4165
Nate Begeman21158fc2005-09-01 00:19:25 +00004166 // fold (shl c1, c2) -> c1<<c2
Matthias Braun00a40762015-02-24 18:52:01 +00004167 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004168 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004169 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004170 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004171 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004172 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004173 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004174 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004175 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004176 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004177 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004178 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004179 // fold (shl undef, x) -> 0
4180 if (N0.getOpcode() == ISD::UNDEF)
4181 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004182 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004183 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004184 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004185 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004186 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004187 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004188 N1.getOperand(0).getOpcode() == ISD::AND) {
4189 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4190 if (NewOp1.getNode())
4191 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004192 }
4193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004194 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4195 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004196
4197 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004198 if (N1C && N0.getOpcode() == ISD::SHL) {
4199 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4200 uint64_t c1 = N0C1->getZExtValue();
4201 uint64_t c2 = N1C->getZExtValue();
4202 if (c1 + c2 >= OpSizeInBits)
4203 return DAG.getConstant(0, VT);
4204 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4205 DAG.getConstant(c1 + c2, N1.getValueType()));
4206 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004207 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004208
4209 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4210 // For this to be valid, the second form must not preserve any of the bits
4211 // that are shifted out by the inner shift in the first form. This means
4212 // the outer shift size must be >= the number of bits added by the ext.
4213 // As a corollary, we don't care what kind of ext it is.
4214 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4215 N0.getOpcode() == ISD::ANY_EXTEND ||
4216 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004217 N0.getOperand(0).getOpcode() == ISD::SHL) {
4218 SDValue N0Op0 = N0.getOperand(0);
4219 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4220 uint64_t c1 = N0Op0C1->getZExtValue();
4221 uint64_t c2 = N1C->getZExtValue();
4222 EVT InnerShiftVT = N0Op0.getValueType();
4223 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4224 if (c2 >= OpSizeInBits - InnerShiftSize) {
4225 if (c1 + c2 >= OpSizeInBits)
4226 return DAG.getConstant(0, VT);
4227 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4228 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4229 N0Op0->getOperand(0)),
4230 DAG.getConstant(c1 + c2, N1.getValueType()));
4231 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004232 }
4233 }
4234
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004235 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4236 // Only fold this if the inner zext has no other uses to avoid increasing
4237 // the total number of instructions.
4238 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004239 N0.getOperand(0).getOpcode() == ISD::SRL) {
4240 SDValue N0Op0 = N0.getOperand(0);
4241 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4242 uint64_t c1 = N0Op0C1->getZExtValue();
4243 if (c1 < VT.getScalarSizeInBits()) {
4244 uint64_t c2 = N1C->getZExtValue();
4245 if (c1 == c2) {
4246 SDValue NewOp0 = N0.getOperand(0);
4247 EVT CountVT = NewOp0.getOperand(1).getValueType();
4248 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4249 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004250 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004251 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4252 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004253 }
4254 }
4255 }
4256
Eli Friedman1877ac92011-06-09 22:14:44 +00004257 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4258 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004259 // Only fold this if the inner shift has no other uses -- if it does, folding
4260 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004261 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4262 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4263 uint64_t c1 = N0C1->getZExtValue();
4264 if (c1 < OpSizeInBits) {
4265 uint64_t c2 = N1C->getZExtValue();
4266 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4267 SDValue Shift;
4268 if (c2 > c1) {
4269 Mask = Mask.shl(c2 - c1);
4270 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4271 DAG.getConstant(c2 - c1, N1.getValueType()));
4272 } else {
4273 Mask = Mask.lshr(c1 - c2);
4274 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4275 DAG.getConstant(c1 - c2, N1.getValueType()));
4276 }
4277 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4278 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004279 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004280 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004281 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004282 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004283 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004284 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004285 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004286 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4287 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004288 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004289 HiBitsMask);
4290 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004291
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004292 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4293 // Variant of version done on multiply, except mul by a power of 2 is turned
4294 // into a shift.
4295 APInt Val;
4296 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4297 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4298 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4299 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4300 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4301 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4302 }
4303
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004304 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004305 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004306 if (NewSHL.getNode())
4307 return NewSHL;
4308 }
4309
Evan Chengf1005572010-04-28 07:10:39 +00004310 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004311}
4312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004313SDValue DAGCombiner::visitSRA(SDNode *N) {
4314 SDValue N0 = N->getOperand(0);
4315 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004316 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004317 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004318
Daniel Sandersa1840d22013-11-11 17:23:41 +00004319 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004320 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004321 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004322 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4323 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004324
4325 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004326 }
4327
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004328 // fold (sra c1, c2) -> (sra c1, c2)
Matthias Braun00a40762015-02-24 18:52:01 +00004329 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004330 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004331 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004332 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004333 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004334 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004335 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004336 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004337 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004338 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004339 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004340 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004341 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004342 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004343 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004344 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4345 // sext_inreg.
4346 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004347 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004348 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4349 if (VT.isVector())
4350 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4351 ExtVT, VT.getVectorNumElements());
4352 if ((!LegalOperations ||
4353 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004354 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004355 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004356 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004357
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004358 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004359 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004360 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004361 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004362 if (Sum >= OpSizeInBits)
4363 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004364 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004365 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004366 }
4367 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004368
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004369 // fold (sra (shl X, m), (sub result_size, n))
4370 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004371 // result_size - n != m.
4372 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004373 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004374 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004375 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004376 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4377 if (N01C) {
4378 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004379 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004380 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4381
4382 if (VT.isVector())
4383 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4384
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004385 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004386 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004387
Scott Michelcf0da6c2009-02-17 22:15:04 +00004388 // If the shift is not a no-op (in which case this should be just a sign
4389 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004390 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004391 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004392 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004393 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4394 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004395 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004396
Owen Andersonb2c80da2011-02-25 21:41:48 +00004397 SDValue Amt = DAG.getConstant(ShiftAmt,
4398 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004399 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004400 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004401 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004402 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004403 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004404 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004405 }
4406 }
4407 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004408
Duncan Sands3ed76882009-02-01 18:06:53 +00004409 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004410 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004411 N1.getOperand(0).getOpcode() == ISD::AND) {
4412 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4413 if (NewOp1.getNode())
4414 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004415 }
4416
Matt Arsenault985b9de2014-03-17 18:58:01 +00004417 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004418 // if c1 is equal to the number of bits the trunc removes
4419 if (N0.getOpcode() == ISD::TRUNCATE &&
4420 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4421 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4422 N0.getOperand(0).hasOneUse() &&
4423 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004424 N1C) {
4425 SDValue N0Op0 = N0.getOperand(0);
4426 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4427 unsigned LargeShiftVal = LargeShift->getZExtValue();
4428 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004429
Matt Arsenault985b9de2014-03-17 18:58:01 +00004430 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4431 SDValue Amt =
4432 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4433 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4434 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4435 N0Op0.getOperand(0), Amt);
4436 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4437 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004438 }
4439 }
4440
Scott Michelcf0da6c2009-02-17 22:15:04 +00004441 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004442 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4443 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004444
4445
Nate Begeman21158fc2005-09-01 00:19:25 +00004446 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004447 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004448 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004449
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004450 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004451 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004452 if (NewSRA.getNode())
4453 return NewSRA;
4454 }
4455
Evan Chengf1005572010-04-28 07:10:39 +00004456 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004457}
4458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004459SDValue DAGCombiner::visitSRL(SDNode *N) {
4460 SDValue N0 = N->getOperand(0);
4461 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004462 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004463 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004464
Daniel Sandersa1840d22013-11-11 17:23:41 +00004465 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004466 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004467 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004468 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4469 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004470
4471 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004472 }
4473
Nate Begeman21158fc2005-09-01 00:19:25 +00004474 // fold (srl c1, c2) -> c1 >>u c2
Matthias Braun00a40762015-02-24 18:52:01 +00004475 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004476 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004477 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004478 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004479 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004480 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004481 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004482 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004483 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004484 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004485 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004486 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004487 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004488 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004489 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004490 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004491
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004492 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004493 if (N1C && N0.getOpcode() == ISD::SRL) {
4494 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4495 uint64_t c1 = N01C->getZExtValue();
4496 uint64_t c2 = N1C->getZExtValue();
4497 if (c1 + c2 >= OpSizeInBits)
4498 return DAG.getConstant(0, VT);
4499 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4500 DAG.getConstant(c1 + c2, N1.getValueType()));
4501 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004502 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004503
Dale Johannesencd538af2010-12-17 21:45:49 +00004504 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004505 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4506 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004507 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004508 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004509 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4510 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004511 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4512 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004513 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004514 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004515 if (c1 + OpSizeInBits == InnerShiftSize) {
4516 if (c1 + c2 >= InnerShiftSize)
4517 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004518 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4519 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004520 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004521 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004522 }
4523 }
4524
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004525 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004526 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4527 unsigned BitSize = N0.getScalarValueSizeInBits();
4528 if (BitSize <= 64) {
4529 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4530 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4531 DAG.getConstant(~0ULL >> ShAmt, VT));
4532 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004533 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004534
Michael Liao62ebfd82013-06-21 18:45:27 +00004535 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004536 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4537 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004538 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004539 unsigned BitSize = SmallVT.getScalarSizeInBits();
4540 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004541 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004542
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004543 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004544 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004545 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004546 N0.getOperand(0),
4547 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004548 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004549 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004550 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4551 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4552 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004553 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004554 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004555
Chris Lattner2e33fb42006-10-12 20:23:19 +00004556 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4557 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004558 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004559 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004560 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004561 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004562
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004563 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004564 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004565 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004566 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004567 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004568
Chris Lattner49932492006-04-02 06:11:11 +00004569 // If any of the input bits are KnownOne, then the input couldn't be all
4570 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004571 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004572
Chris Lattner49932492006-04-02 06:11:11 +00004573 // If all of the bits input the to ctlz node are known to be zero, then
4574 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004575 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004576 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004577
Chris Lattner49932492006-04-02 06:11:11 +00004578 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004579 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004580 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004581 // could be set on input to the CTLZ node. If this bit is set, the SRL
4582 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4583 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004584 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004585 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004586
Chris Lattner49932492006-04-02 06:11:11 +00004587 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004588 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004589 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004590 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004591 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004592
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004594 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004595 }
4596 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004597
Duncan Sands3ed76882009-02-01 18:06:53 +00004598 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004599 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004600 N1.getOperand(0).getOpcode() == ISD::AND) {
4601 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4602 if (NewOp1.getNode())
4603 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004604 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004605
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004606 // fold operands of srl based on knowledge that the low bits are not
4607 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004608 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4609 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004610
Evan Chengb175de62009-12-18 21:31:31 +00004611 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004612 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004613 if (NewSRL.getNode())
4614 return NewSRL;
4615 }
4616
Dan Gohman600f62b2010-06-24 14:30:44 +00004617 // Attempt to convert a srl of a load into a narrower zero-extending load.
4618 SDValue NarrowLoad = ReduceLoadWidth(N);
4619 if (NarrowLoad.getNode())
4620 return NarrowLoad;
4621
Evan Chengb175de62009-12-18 21:31:31 +00004622 // Here is a common situation. We want to optimize:
4623 //
4624 // %a = ...
4625 // %b = and i32 %a, 2
4626 // %c = srl i32 %b, 1
4627 // brcond i32 %c ...
4628 //
4629 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004630 //
Evan Chengb175de62009-12-18 21:31:31 +00004631 // %a = ...
4632 // %b = and %a, 2
4633 // %c = setcc eq %b, 0
4634 // brcond %c ...
4635 //
4636 // However when after the source operand of SRL is optimized into AND, the SRL
4637 // itself may not be optimized further. Look for it and add the BRCOND into
4638 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004639 if (N->hasOneUse()) {
4640 SDNode *Use = *N->use_begin();
4641 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004642 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004643 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4644 // Also look pass the truncate.
4645 Use = *Use->use_begin();
4646 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004647 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004648 }
4649 }
Evan Chengb175de62009-12-18 21:31:31 +00004650
Evan Chengf1005572010-04-28 07:10:39 +00004651 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004652}
4653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004654SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4655 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004656 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004657
4658 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004659 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004660 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004661 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004662}
4663
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004664SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4665 SDValue N0 = N->getOperand(0);
4666 EVT VT = N->getValueType(0);
4667
4668 // fold (ctlz_zero_undef c1) -> c2
4669 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004670 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004671 return SDValue();
4672}
4673
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004674SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4675 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004676 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004677
Nate Begeman21158fc2005-09-01 00:19:25 +00004678 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004679 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004680 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004681 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004682}
4683
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004684SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4685 SDValue N0 = N->getOperand(0);
4686 EVT VT = N->getValueType(0);
4687
4688 // fold (cttz_zero_undef c1) -> c2
4689 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004690 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004691 return SDValue();
4692}
4693
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004694SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4695 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004696 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004697
Nate Begeman21158fc2005-09-01 00:19:25 +00004698 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004699 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004700 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004701 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004702}
4703
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004704
4705/// \brief Generate Min/Max node
4706static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4707 SDValue True, SDValue False,
4708 ISD::CondCode CC, const TargetLowering &TLI,
4709 SelectionDAG &DAG) {
4710 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4711 return SDValue();
4712
4713 switch (CC) {
4714 case ISD::SETOLT:
4715 case ISD::SETOLE:
4716 case ISD::SETLT:
4717 case ISD::SETLE:
4718 case ISD::SETULT:
4719 case ISD::SETULE: {
4720 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4721 if (TLI.isOperationLegal(Opcode, VT))
4722 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4723 return SDValue();
4724 }
4725 case ISD::SETOGT:
4726 case ISD::SETOGE:
4727 case ISD::SETGT:
4728 case ISD::SETGE:
4729 case ISD::SETUGT:
4730 case ISD::SETUGE: {
4731 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4732 if (TLI.isOperationLegal(Opcode, VT))
4733 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4734 return SDValue();
4735 }
4736 default:
4737 return SDValue();
4738 }
4739}
4740
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004741SDValue DAGCombiner::visitSELECT(SDNode *N) {
4742 SDValue N0 = N->getOperand(0);
4743 SDValue N1 = N->getOperand(1);
4744 SDValue N2 = N->getOperand(2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004745 EVT VT = N->getValueType(0);
4746 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004747
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004748 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004749 if (N1 == N2)
4750 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004751 // fold (select true, X, Y) -> X
Matthias Braun00a40762015-02-24 18:52:01 +00004752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004753 if (N0C && !N0C->isNullValue())
4754 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004755 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004756 if (N0C && N0C->isNullValue())
4757 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004758 // fold (select C, 1, X) -> (or C, X)
Matthias Braun00a40762015-02-24 18:52:01 +00004759 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson9f944592009-08-11 20:47:22 +00004760 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004761 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004762 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004763 // We can't do this reliably if integer based booleans have different contents
4764 // to floating point based booleans. This is because we can't tell whether we
4765 // have an integer-based boolean or a floating-point-based boolean unless we
4766 // can find the SETCC that produced it and inspect its operands. This is
4767 // fairly easy if C is the SETCC node, but it can potentially be
4768 // undiscoverable (or not reasonably discoverable). For example, it could be
4769 // in another basic block or it could require searching a complicated
4770 // expression.
Matthias Braun00a40762015-02-24 18:52:01 +00004771 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004772 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004773 (VT0 == MVT::i1 || (VT0.isInteger() &&
4774 TLI.getBooleanContents(false, false) ==
4775 TLI.getBooleanContents(false, true) &&
4776 TLI.getBooleanContents(false, false) ==
4777 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004778 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004779 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004780 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004781 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004782 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004783 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004784 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004785 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004786 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004787 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4788 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004789 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004790 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004791 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004792 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004793 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004794 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004795 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004796 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004797 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004798 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004799 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004800 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004801 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004802 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004803 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004804 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004805 // fold (select X, X, Y) -> (or X, Y)
4806 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004807 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004808 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004809 // fold (select X, Y, X) -> (and X, Y)
4810 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004811 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004812 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004813
Chris Lattner6c14c352005-10-18 06:04:22 +00004814 // If we can fold this based on the true/false value, do so.
4815 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004816 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004817
Nate Begemanc760f802005-09-19 22:34:01 +00004818 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004819 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004820 // select x, y (fcmp lt x, y) -> fminnum x, y
4821 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4822 //
4823 // This is OK if we don't care about what happens if either operand is a
4824 // NaN.
4825 //
4826
4827 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4828 // no signed zeros as well as no nans.
4829 const TargetOptions &Options = DAG.getTarget().Options;
4830 if (Options.UnsafeFPMath &&
4831 VT.isFloatingPoint() && N0.hasOneUse() &&
4832 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4833 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4834
4835 SDValue FMinMax =
4836 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4837 N1, N2, CC, TLI, DAG);
4838 if (FMinMax)
4839 return FMinMax;
4840 }
4841
Tom Stellard3787b122014-06-10 16:01:29 +00004842 if ((!LegalOperations &&
4843 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004844 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004845 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004846 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004847 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004848 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004849 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004850
Matthias Braun898d11e2015-03-06 19:49:10 +00004851 if (VT0 == MVT::i1) {
4852 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4853 // select (and Cond0, Cond1), X, Y
4854 // -> select Cond0, (select Cond1, X, Y), Y
4855 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4856 SDValue Cond0 = N0->getOperand(0);
4857 SDValue Cond1 = N0->getOperand(1);
4858 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4859 N1.getValueType(), Cond1, N1, N2);
4860 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4861 InnerSelect, N2);
4862 }
4863 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4864 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4865 SDValue Cond0 = N0->getOperand(0);
4866 SDValue Cond1 = N0->getOperand(1);
4867 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4868 N1.getValueType(), Cond1, N1, N2);
4869 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4870 InnerSelect);
4871 }
4872 }
4873
4874 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4875 if (N1->getOpcode() == ISD::SELECT) {
4876 SDValue N1_0 = N1->getOperand(0);
4877 SDValue N1_1 = N1->getOperand(1);
4878 SDValue N1_2 = N1->getOperand(2);
4879 if (N1_2 == N2) {
4880 // Create the actual and node if we can generate good code for it.
4881 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4882 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4883 N0, N1_0);
4884 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4885 N1_1, N2);
4886 }
4887 // Otherwise see if we can optimize the "and" to a better pattern.
4888 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4889 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4890 N1_1, N2);
4891 }
4892 }
4893 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4894 if (N2->getOpcode() == ISD::SELECT) {
4895 SDValue N2_0 = N2->getOperand(0);
4896 SDValue N2_1 = N2->getOperand(1);
4897 SDValue N2_2 = N2->getOperand(2);
4898 if (N2_1 == N1) {
4899 // Create the actual or node if we can generate good code for it.
4900 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4901 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4902 N0, N2_0);
4903 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4904 N1, N2_2);
4905 }
4906 // Otherwise see if we can optimize to a better pattern.
4907 if (SDValue Combined = visitORLike(N0, N2_0, N))
4908 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4909 N1, N2_2);
4910 }
4911 }
4912 }
4913
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004914 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004915}
4916
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004917static
4918std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4919 SDLoc DL(N);
4920 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004921 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004922
4923 // Split the inputs.
4924 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004925 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4926 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004927
4928 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4929 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4930
4931 return std::make_pair(Lo, Hi);
4932}
4933
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004934// This function assumes all the vselect's arguments are CONCAT_VECTOR
4935// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4936static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4937 SDLoc dl(N);
4938 SDValue Cond = N->getOperand(0);
4939 SDValue LHS = N->getOperand(1);
4940 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004941 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004942 int NumElems = VT.getVectorNumElements();
4943 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4944 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4945 Cond.getOpcode() == ISD::BUILD_VECTOR);
4946
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004947 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4948 // binary ones here.
4949 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4950 return SDValue();
4951
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004952 // We're sure we have an even number of elements due to the
4953 // concat_vectors we have as arguments to vselect.
4954 // Skip BV elements until we find one that's not an UNDEF
4955 // After we find an UNDEF element, keep looping until we get to half the
4956 // length of the BV and see if all the non-undef nodes are the same.
4957 ConstantSDNode *BottomHalf = nullptr;
4958 for (int i = 0; i < NumElems / 2; ++i) {
4959 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4960 continue;
4961
4962 if (BottomHalf == nullptr)
4963 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4964 else if (Cond->getOperand(i).getNode() != BottomHalf)
4965 return SDValue();
4966 }
4967
4968 // Do the same for the second half of the BuildVector
4969 ConstantSDNode *TopHalf = nullptr;
4970 for (int i = NumElems / 2; i < NumElems; ++i) {
4971 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4972 continue;
4973
4974 if (TopHalf == nullptr)
4975 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4976 else if (Cond->getOperand(i).getNode() != TopHalf)
4977 return SDValue();
4978 }
4979
4980 assert(TopHalf && BottomHalf &&
4981 "One half of the selector was all UNDEFs and the other was all the "
4982 "same value. This should have been addressed before this function.");
4983 return DAG.getNode(
4984 ISD::CONCAT_VECTORS, dl, VT,
4985 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4986 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4987}
4988
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004989SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4990
4991 if (Level >= AfterLegalizeTypes)
4992 return SDValue();
4993
4994 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4995 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004996 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004997 SDLoc DL(N);
4998
4999 // If the MSTORE data type requires splitting and the mask is provided by a
5000 // SETCC, then split both nodes and its operands before legalization. This
5001 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5002 // and enables future optimizations (e.g. min/max pattern matching on X86).
5003 if (Mask.getOpcode() == ISD::SETCC) {
5004
5005 // Check if any splitting is required.
5006 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5007 TargetLowering::TypeSplitVector)
5008 return SDValue();
5009
5010 SDValue MaskLo, MaskHi, Lo, Hi;
5011 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5012
5013 EVT LoVT, HiVT;
5014 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5015
5016 SDValue Chain = MST->getChain();
5017 SDValue Ptr = MST->getBasePtr();
5018
5019 EVT MemoryVT = MST->getMemoryVT();
5020 unsigned Alignment = MST->getOriginalAlignment();
5021
5022 // if Alignment is equal to the vector size,
5023 // take the half of it for the second part
5024 unsigned SecondHalfAlignment =
5025 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5026 Alignment/2 : Alignment;
5027
5028 EVT LoMemVT, HiMemVT;
5029 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5030
5031 SDValue DataLo, DataHi;
5032 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5033
5034 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005035 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005036 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5037 Alignment, MST->getAAInfo(), MST->getRanges());
5038
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005039 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5040 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005041
5042 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5043 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5044 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5045
5046 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005047 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005048 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5049 SecondHalfAlignment, MST->getAAInfo(),
5050 MST->getRanges());
5051
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005052 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5053 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005054
5055 AddToWorklist(Lo.getNode());
5056 AddToWorklist(Hi.getNode());
5057
5058 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5059 }
5060 return SDValue();
5061}
5062
5063SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5064
5065 if (Level >= AfterLegalizeTypes)
5066 return SDValue();
5067
5068 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5069 SDValue Mask = MLD->getMask();
5070 SDLoc DL(N);
5071
5072 // If the MLOAD result requires splitting and the mask is provided by a
5073 // SETCC, then split both nodes and its operands before legalization. This
5074 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5075 // and enables future optimizations (e.g. min/max pattern matching on X86).
5076
5077 if (Mask.getOpcode() == ISD::SETCC) {
5078 EVT VT = N->getValueType(0);
5079
5080 // Check if any splitting is required.
5081 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5082 TargetLowering::TypeSplitVector)
5083 return SDValue();
5084
5085 SDValue MaskLo, MaskHi, Lo, Hi;
5086 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5087
5088 SDValue Src0 = MLD->getSrc0();
5089 SDValue Src0Lo, Src0Hi;
5090 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5091
5092 EVT LoVT, HiVT;
5093 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5094
5095 SDValue Chain = MLD->getChain();
5096 SDValue Ptr = MLD->getBasePtr();
5097 EVT MemoryVT = MLD->getMemoryVT();
5098 unsigned Alignment = MLD->getOriginalAlignment();
5099
5100 // if Alignment is equal to the vector size,
5101 // take the half of it for the second part
5102 unsigned SecondHalfAlignment =
5103 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5104 Alignment/2 : Alignment;
5105
5106 EVT LoMemVT, HiMemVT;
5107 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5108
5109 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005110 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005111 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5112 Alignment, MLD->getAAInfo(), MLD->getRanges());
5113
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005114 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5115 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005116
5117 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5118 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5119 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5120
5121 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005122 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005123 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5124 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5125
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005126 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5127 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005128
5129 AddToWorklist(Lo.getNode());
5130 AddToWorklist(Hi.getNode());
5131
5132 // Build a factor node to remember that this load is independent of the
5133 // other one.
5134 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5135 Hi.getValue(1));
5136
5137 // Legalized the chain result - switch anything that used the old chain to
5138 // use the new one.
5139 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5140
5141 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5142
5143 SDValue RetOps[] = { LoadRes, Chain };
5144 return DAG.getMergeValues(RetOps, DL);
5145 }
5146 return SDValue();
5147}
5148
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005149SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5150 SDValue N0 = N->getOperand(0);
5151 SDValue N1 = N->getOperand(1);
5152 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005153 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005154
5155 // Canonicalize integer abs.
5156 // vselect (setg[te] X, 0), X, -X ->
5157 // vselect (setgt X, -1), X, -X ->
5158 // vselect (setl[te] X, 0), -X, X ->
5159 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5160 if (N0.getOpcode() == ISD::SETCC) {
5161 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5162 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5163 bool isAbs = false;
5164 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5165
5166 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5167 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5168 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5169 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5170 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5171 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5172 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5173
5174 if (isAbs) {
5175 EVT VT = LHS.getValueType();
5176 SDValue Shift = DAG.getNode(
5177 ISD::SRA, DL, VT, LHS,
5178 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5179 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005180 AddToWorklist(Shift.getNode());
5181 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005182 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5183 }
5184 }
5185
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005186 // If the VSELECT result requires splitting and the mask is provided by a
5187 // SETCC, then split both nodes and its operands before legalization. This
5188 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5189 // and enables future optimizations (e.g. min/max pattern matching on X86).
5190 if (N0.getOpcode() == ISD::SETCC) {
5191 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005192
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005193 // Check if any splitting is required.
5194 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5195 TargetLowering::TypeSplitVector)
5196 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005197
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005198 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005199 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5200 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5201 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005202
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005203 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5204 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005205
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005206 // Add the new VSELECT nodes to the work list in case they need to be split
5207 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005208 AddToWorklist(Lo.getNode());
5209 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005210
5211 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005212 }
5213
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005214 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5215 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5216 return N1;
5217 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5218 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5219 return N2;
5220
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005221 // The ConvertSelectToConcatVector function is assuming both the above
5222 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5223 // and addressed.
5224 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5225 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5226 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5227 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5228 if (CV.getNode())
5229 return CV;
5230 }
5231
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005232 return SDValue();
5233}
5234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005235SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5236 SDValue N0 = N->getOperand(0);
5237 SDValue N1 = N->getOperand(1);
5238 SDValue N2 = N->getOperand(2);
5239 SDValue N3 = N->getOperand(3);
5240 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005241 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005242
Nate Begemanc760f802005-09-19 22:34:01 +00005243 // fold select_cc lhs, rhs, x, x, cc -> x
5244 if (N2 == N3)
5245 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005246
Chris Lattner8b68dec2006-09-20 06:19:26 +00005247 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005248 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005249 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005250 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005251 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005252
Stephen Lin605207f2013-06-15 04:03:33 +00005253 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5254 if (!SCCC->isNullValue())
5255 return N2; // cond always true -> true val
5256 else
5257 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005258 } else if (SCC->getOpcode() == ISD::UNDEF) {
5259 // When the condition is UNDEF, just return the first operand. This is
5260 // coherent the DAG creation, no setcc node is created in this case
5261 return N2;
5262 } else if (SCC.getOpcode() == ISD::SETCC) {
5263 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005264 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5265 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5266 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005267 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005269
Chris Lattner6c14c352005-10-18 06:04:22 +00005270 // If we can fold this based on the true/false value, do so.
5271 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005272 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005273
Nate Begemanc760f802005-09-19 22:34:01 +00005274 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005275 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005276}
5277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005278SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005279 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005280 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005281 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005282}
5283
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005284// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5285// dag node into a ConstantSDNode or a build_vector of constants.
5286// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005287// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005288// Vector extends are not folded if operations are legal; this is to
5289// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005290static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5291 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005292 bool LegalOperations) {
5293 unsigned Opcode = N->getOpcode();
5294 SDValue N0 = N->getOperand(0);
5295 EVT VT = N->getValueType(0);
5296
5297 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5298 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5299
5300 // fold (sext c1) -> c1
5301 // fold (zext c1) -> c1
5302 // fold (aext c1) -> c1
5303 if (isa<ConstantSDNode>(N0))
5304 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5305
5306 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5307 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5308 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005309 EVT SVT = VT.getScalarType();
5310 if (!(VT.isVector() &&
5311 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005312 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005313 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005314
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005315 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005316 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005317 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5318 unsigned ShAmt = VTBits - EVTBits;
5319 SmallVector<SDValue, 8> Elts;
5320 unsigned NumElts = N0->getNumOperands();
5321 SDLoc DL(N);
5322
5323 for (unsigned i=0; i != NumElts; ++i) {
5324 SDValue Op = N0->getOperand(i);
5325 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005326 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005327 continue;
5328 }
5329
5330 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5331 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5332 if (Opcode == ISD::SIGN_EXTEND)
5333 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005334 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005335 else
5336 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005337 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005338 }
5339
Craig Topper48d114b2014-04-26 18:35:24 +00005340 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005341}
5342
Evan Chenge106e2f2007-10-29 19:58:20 +00005343// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005344// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005345// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005346// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005347static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005348 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005349 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005350 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005351 bool HasCopyToRegUses = false;
5352 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005353 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5354 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005355 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005356 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005357 if (User == N)
5358 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005359 if (UI.getUse().getResNo() != N0.getResNo())
5360 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005361 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005362 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005363 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5364 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5365 // Sign bits will be lost after a zext.
5366 return false;
5367 bool Add = false;
5368 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005369 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005370 if (UseOp == N0)
5371 continue;
5372 if (!isa<ConstantSDNode>(UseOp))
5373 return false;
5374 Add = true;
5375 }
5376 if (Add)
5377 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005378 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005379 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005380 // If truncates aren't free and there are users we can't
5381 // extend, it isn't worthwhile.
5382 if (!isTruncFree)
5383 return false;
5384 // Remember if this value is live-out.
5385 if (User->getOpcode() == ISD::CopyToReg)
5386 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005387 }
5388
5389 if (HasCopyToRegUses) {
5390 bool BothLiveOut = false;
5391 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5392 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005393 SDUse &Use = UI.getUse();
5394 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5395 BothLiveOut = true;
5396 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005397 }
5398 }
5399 if (BothLiveOut)
5400 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005401 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005402 return ExtendNodes.size();
5403 }
5404 return true;
5405}
5406
Craig Toppere0b71182013-07-13 07:43:40 +00005407void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005408 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005409 ISD::NodeType ExtType) {
5410 // Extend SetCC uses if necessary.
5411 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5412 SDNode *SetCC = SetCCs[i];
5413 SmallVector<SDValue, 4> Ops;
5414
5415 for (unsigned j = 0; j != 2; ++j) {
5416 SDValue SOp = SetCC->getOperand(j);
5417 if (SOp == Trunc)
5418 Ops.push_back(ExtLoad);
5419 else
5420 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5421 }
5422
5423 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005424 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005425 }
5426}
5427
Ahmed Bougachae892d132015-02-05 18:31:02 +00005428// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5429SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5430 SDValue N0 = N->getOperand(0);
5431 EVT DstVT = N->getValueType(0);
5432 EVT SrcVT = N0.getValueType();
5433
5434 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5435 N->getOpcode() == ISD::ZERO_EXTEND) &&
5436 "Unexpected node type (not an extend)!");
5437
5438 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5439 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5440 // (v8i32 (sext (v8i16 (load x))))
5441 // into:
5442 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5443 // (v4i32 (sextload (x + 16)))))
5444 // Where uses of the original load, i.e.:
5445 // (v8i16 (load x))
5446 // are replaced with:
5447 // (v8i16 (truncate
5448 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5449 // (v4i32 (sextload (x + 16)))))))
5450 //
5451 // This combine is only applicable to illegal, but splittable, vectors.
5452 // All legal types, and illegal non-vector types, are handled elsewhere.
5453 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5454 //
5455 if (N0->getOpcode() != ISD::LOAD)
5456 return SDValue();
5457
5458 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5459
5460 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5461 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5462 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5463 return SDValue();
5464
5465 SmallVector<SDNode *, 4> SetCCs;
5466 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5467 return SDValue();
5468
5469 ISD::LoadExtType ExtType =
5470 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5471
5472 // Try to split the vector types to get down to legal types.
5473 EVT SplitSrcVT = SrcVT;
5474 EVT SplitDstVT = DstVT;
5475 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5476 SplitSrcVT.getVectorNumElements() > 1) {
5477 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5478 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5479 }
5480
5481 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5482 return SDValue();
5483
5484 SDLoc DL(N);
5485 const unsigned NumSplits =
5486 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5487 const unsigned Stride = SplitSrcVT.getStoreSize();
5488 SmallVector<SDValue, 4> Loads;
5489 SmallVector<SDValue, 4> Chains;
5490
5491 SDValue BasePtr = LN0->getBasePtr();
5492 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5493 const unsigned Offset = Idx * Stride;
5494 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5495
5496 SDValue SplitLoad = DAG.getExtLoad(
5497 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5498 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5499 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5500 Align, LN0->getAAInfo());
5501
5502 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5503 DAG.getConstant(Stride, BasePtr.getValueType()));
5504
5505 Loads.push_back(SplitLoad.getValue(0));
5506 Chains.push_back(SplitLoad.getValue(1));
5507 }
5508
5509 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5510 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5511
5512 CombineTo(N, NewValue);
5513
5514 // Replace uses of the original load (before extension)
5515 // with a truncate of the concatenated sextloaded vectors.
5516 SDValue Trunc =
5517 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5518 CombineTo(N0.getNode(), Trunc, NewChain);
5519 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5520 (ISD::NodeType)N->getOpcode());
5521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5522}
5523
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005524SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5525 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005526 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005527
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005528 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5529 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005530 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005531
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005532 // fold (sext (sext x)) -> (sext x)
5533 // fold (sext (aext x)) -> (sext x)
5534 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005535 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005536 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005537
Chris Lattnerfce448f2007-02-26 03:13:59 +00005538 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005539 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5540 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005541 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5542 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005543 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5544 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005545 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005546 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005547 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005548 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005549 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005550 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005551
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005552 // See if the value being truncated is already sign extended. If so, just
5553 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005554 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005555 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5556 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5557 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005558 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005559
Chris Lattnerfce448f2007-02-26 03:13:59 +00005560 if (OpBits == DestBits) {
5561 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5562 // bits, it is already ready.
5563 if (NumSignBits > DestBits-MidBits)
5564 return Op;
5565 } else if (OpBits < DestBits) {
5566 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5567 // bits, just sext from i32.
5568 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005569 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005570 } else {
5571 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5572 // bits, just truncate to i32.
5573 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005574 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005575 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005576
Chris Lattnerfce448f2007-02-26 03:13:59 +00005577 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005578 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5579 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005580 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005581 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005582 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005583 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5584 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005585 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005586 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005587 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005588
Evan Chengbce7c472005-12-14 02:19:23 +00005589 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005590 // Only generate vector extloads when 1) they're legal, and 2) they are
5591 // deemed desirable by the target.
5592 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5593 ((!LegalOperations && !VT.isVector() &&
5594 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005595 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005596 bool DoXform = true;
5597 SmallVector<SDNode*, 4> SetCCs;
5598 if (!N0.hasOneUse())
5599 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005600 if (VT.isVector())
5601 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005602 if (DoXform) {
5603 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005604 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005605 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005606 LN0->getBasePtr(), N0.getValueType(),
5607 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005608 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005609 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005610 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005611 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005612 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005613 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005614 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005615 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005616 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005617
Ahmed Bougachae892d132015-02-05 18:31:02 +00005618 // fold (sext (load x)) to multiple smaller sextloads.
5619 // Only on illegal but splittable vectors.
5620 if (SDValue ExtLoad = CombineExtLoad(N))
5621 return ExtLoad;
5622
Chris Lattner7dac1082005-12-14 19:05:06 +00005623 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5624 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005625 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5626 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005627 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005628 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005629 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005630 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005631 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005632 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005633 LN0->getBasePtr(), MemVT,
5634 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005635 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005636 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005637 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005638 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005639 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005640 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005641 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005642 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005643
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005644 // fold (sext (and/or/xor (load x), cst)) ->
5645 // (and/or/xor (sextload x), (sext cst))
5646 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5647 N0.getOpcode() == ISD::XOR) &&
5648 isa<LoadSDNode>(N0.getOperand(0)) &&
5649 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005650 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005651 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5652 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005653 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005654 bool DoXform = true;
5655 SmallVector<SDNode*, 4> SetCCs;
5656 if (!N0.hasOneUse())
5657 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5658 SetCCs, TLI);
5659 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005660 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005661 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005662 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005663 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005664 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5665 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005666 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005667 ExtLoad, DAG.getConstant(Mask, VT));
5668 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005669 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005670 N0.getOperand(0).getValueType(), ExtLoad);
5671 CombineTo(N, And);
5672 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005673 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005674 ISD::SIGN_EXTEND);
5675 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5676 }
5677 }
5678 }
5679
Chris Lattner65786b02007-04-11 05:32:27 +00005680 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005681 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005682 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005683 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005684 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005685 TLI.getBooleanContents(N0VT) ==
5686 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005687 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5688 // of the same size as the compared operands. Only optimize sext(setcc())
5689 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005690 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005691
5692 // We know that the # elements of the results is the same as the
5693 // # elements of the compare (and the # elements of the compare result
5694 // for that matter). Check to see that they are the same size. If so,
5695 // we know that the element size of the sext'd result matches the
5696 // element size of the compare operands.
5697 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005698 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005699 N0.getOperand(1),
5700 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005701
Dan Gohmane82c25e2010-04-30 17:19:19 +00005702 // If the desired elements are smaller or larger than the source
5703 // elements we can use a matching integer vector type and then
5704 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005705 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005706 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005707 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005708 N0.getOperand(0), N0.getOperand(1),
5709 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005710 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005711 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005712 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005713
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005714 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005715 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005716 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005717 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005718 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005719 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005720 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005721 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005722 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005723
5724 if (!VT.isVector()) {
5725 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5726 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5727 SDLoc DL(N);
5728 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005729 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005730 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005731 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005732 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005733 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005734 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005735 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005736
Dan Gohman3eb10f72008-04-28 16:58:24 +00005737 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005738 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005739 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005740 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005741
Evan Chengf1005572010-04-28 07:10:39 +00005742 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005743}
5744
Rafael Espindola8f62b322012-04-09 16:06:03 +00005745// isTruncateOf - If N is a truncate of some other value, return true, record
5746// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5747// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005748// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005749static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5750 APInt &KnownZero) {
5751 APInt KnownOne;
5752 if (N->getOpcode() == ISD::TRUNCATE) {
5753 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005754 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005755 return true;
5756 }
5757
5758 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5759 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5760 return false;
5761
5762 SDValue Op0 = N->getOperand(0);
5763 SDValue Op1 = N->getOperand(1);
5764 assert(Op0.getValueType() == Op1.getValueType());
5765
5766 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5767 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005768 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005769 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005770 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005771 Op = Op0;
5772 else
5773 return false;
5774
Jay Foada0653a32014-05-14 21:14:37 +00005775 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005776
5777 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5778 return false;
5779
5780 return true;
5781}
5782
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005783SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5784 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005785 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005786
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005787 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5788 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005789 return SDValue(Res, 0);
5790
Nate Begeman21158fc2005-09-01 00:19:25 +00005791 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005792 // fold (zext (aext x)) -> (zext x)
5793 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005794 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005795 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005796
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005797 // fold (zext (truncate x)) -> (zext x) or
5798 // (zext (truncate x)) -> (truncate x)
5799 // This is valid when the truncated bits of x are already zero.
5800 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005801 SDValue Op;
5802 APInt KnownZero;
5803 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5804 APInt TruncatedBits =
5805 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5806 APInt(Op.getValueSizeInBits(), 0) :
5807 APInt::getBitsSet(Op.getValueSizeInBits(),
5808 N0.getValueSizeInBits(),
5809 std::min(Op.getValueSizeInBits(),
5810 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005811 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005812 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005813 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005814 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005815 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005816
5817 return Op;
5818 }
5819 }
5820
Evan Cheng464dc9b2007-03-22 01:54:19 +00005821 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5822 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005823 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005824 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5825 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005826 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5827 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005828 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005829 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005830 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005831 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005833 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005834 }
5835
Chris Lattnera31f0a62006-09-21 06:00:20 +00005836 // fold (zext (truncate x)) -> (and x, mask)
5837 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005838 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005839
5840 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5841 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5842 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5843 if (NarrowLoad.getNode()) {
5844 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5845 if (NarrowLoad.getNode() != N0.getNode()) {
5846 CombineTo(N0.getNode(), NarrowLoad);
5847 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005848 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005849 }
5850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5851 }
5852
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005853 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005854 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005855 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005856 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005857 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005858 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005859 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005860 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005861 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005862 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005863 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005864
Dan Gohmanad3e5492009-04-08 00:15:30 +00005865 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5866 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005867 if (N0.getOpcode() == ISD::AND &&
5868 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005869 N0.getOperand(1).getOpcode() == ISD::Constant &&
5870 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5871 N0.getValueType()) ||
5872 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005873 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005874 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005875 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005876 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005877 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005878 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005879 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005880 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005881 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005882 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005883 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005884
Evan Chengbce7c472005-12-14 02:19:23 +00005885 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005886 // Only generate vector extloads when 1) they're legal, and 2) they are
5887 // deemed desirable by the target.
5888 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889 ((!LegalOperations && !VT.isVector() &&
5890 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005891 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005892 bool DoXform = true;
5893 SmallVector<SDNode*, 4> SetCCs;
5894 if (!N0.hasOneUse())
5895 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005896 if (VT.isVector())
5897 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005898 if (DoXform) {
5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005900 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005901 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005902 LN0->getBasePtr(), N0.getValueType(),
5903 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005904 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005905 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005906 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005907 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005908
Andrew Trickef9de2a2013-05-25 02:42:55 +00005909 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005910 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005912 }
Evan Chengbce7c472005-12-14 02:19:23 +00005913 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005914
Ahmed Bougachae892d132015-02-05 18:31:02 +00005915 // fold (zext (load x)) to multiple smaller zextloads.
5916 // Only on illegal but splittable vectors.
5917 if (SDValue ExtLoad = CombineExtLoad(N))
5918 return ExtLoad;
5919
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005920 // fold (zext (and/or/xor (load x), cst)) ->
5921 // (and/or/xor (zextload x), (zext cst))
5922 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5923 N0.getOpcode() == ISD::XOR) &&
5924 isa<LoadSDNode>(N0.getOperand(0)) &&
5925 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005926 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005927 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5928 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005929 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005930 bool DoXform = true;
5931 SmallVector<SDNode*, 4> SetCCs;
5932 if (!N0.hasOneUse())
5933 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5934 SetCCs, TLI);
5935 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005936 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005937 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005938 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005939 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005940 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5941 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005942 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005943 ExtLoad, DAG.getConstant(Mask, VT));
5944 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005945 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005946 N0.getOperand(0).getValueType(), ExtLoad);
5947 CombineTo(N, And);
5948 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005949 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005950 ISD::ZERO_EXTEND);
5951 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5952 }
5953 }
5954 }
5955
Chris Lattner7dac1082005-12-14 19:05:06 +00005956 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5957 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005958 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5959 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005960 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005961 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005962 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005963 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005964 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005965 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005966 LN0->getBasePtr(), MemVT,
5967 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005968 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005969 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005970 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005971 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005972 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005973 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005974 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005975 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005976
Chris Lattner65786b02007-04-11 05:32:27 +00005977 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005978 if (!LegalOperations && VT.isVector() &&
5979 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005980 EVT N0VT = N0.getOperand(0).getValueType();
5981 if (getSetCCResultType(N0VT) == N0.getValueType())
5982 return SDValue();
5983
Evan Chengabd0ad52010-05-19 01:08:17 +00005984 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5985 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005986 EVT EltVT = VT.getVectorElementType();
5987 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5988 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005989 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005990 // We know that the # elements of the results is the same as the
5991 // # elements of the compare (and the # elements of the compare result
5992 // for that matter). Check to see that they are the same size. If so,
5993 // we know that the element size of the sext'd result matches the
5994 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005995 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5996 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005997 N0.getOperand(1),
5998 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00006000 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00006001
6002 // If the desired elements are smaller or larger than the source
6003 // elements we can use a matching integer vector type and then
6004 // truncate/sign extend
6005 EVT MatchingElementType =
6006 EVT::getIntegerVT(*DAG.getContext(),
6007 N0VT.getScalarType().getSizeInBits());
6008 EVT MatchingVectorType =
6009 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6010 N0VT.getVectorNumElements());
6011 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006012 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00006013 N0.getOperand(1),
6014 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006015 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6016 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00006017 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00006018 }
6019
6020 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006021 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006022 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00006023 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006024 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006025 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006027
Evan Cheng852c4862009-12-15 03:00:32 +00006028 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00006029 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00006030 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00006031 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6032 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006033 SDValue ShAmt = N0.getOperand(1);
6034 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00006035 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006036 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00006037 // If the original shl may be shifting out bits, do not perform this
6038 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00006039 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6040 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6041 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00006042 return SDValue();
6043 }
Chris Lattnere95d1952011-02-13 19:09:16 +00006044
Andrew Trickef9de2a2013-05-25 02:42:55 +00006045 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006046
6047 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00006048 if (VT.getSizeInBits() >= 256)
6049 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006050
Chris Lattnere95d1952011-02-13 19:09:16 +00006051 return DAG.getNode(N0.getOpcode(), DL, VT,
6052 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6053 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00006054 }
6055
Evan Chengf1005572010-04-28 07:10:39 +00006056 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006057}
6058
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006059SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6060 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006061 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006062
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006063 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6064 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006065 return SDValue(Res, 0);
6066
Chris Lattner812646a2006-05-05 05:58:59 +00006067 // fold (aext (aext x)) -> (aext x)
6068 // fold (aext (zext x)) -> (zext x)
6069 // fold (aext (sext x)) -> (sext x)
6070 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6071 N0.getOpcode() == ISD::ZERO_EXTEND ||
6072 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006073 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006074
Evan Cheng464dc9b2007-03-22 01:54:19 +00006075 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6076 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6077 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006078 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6079 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006080 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6081 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006082 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006083 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006084 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006085 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006086 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006087 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006088 }
6089
Chris Lattner8746e2c2006-09-20 06:29:17 +00006090 // fold (aext (truncate x))
6091 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006092 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006093 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006094 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00006095 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006096 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6097 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006098 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006099
Dan Gohmanad3e5492009-04-08 00:15:30 +00006100 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6101 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00006102 if (N0.getOpcode() == ISD::AND &&
6103 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006104 N0.getOperand(1).getOpcode() == ISD::Constant &&
6105 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006107 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006108 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006110 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006111 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00006112 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006113 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006114 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006115 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00006116 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00006117 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006118
Chris Lattner812646a2006-05-05 05:58:59 +00006119 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006120 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006121 // on vectors in one instruction. We only perform this transformation on
6122 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006123 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006124 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006125 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006126 bool DoXform = true;
6127 SmallVector<SDNode*, 4> SetCCs;
6128 if (!N0.hasOneUse())
6129 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6130 if (DoXform) {
6131 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006132 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006133 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006134 LN0->getBasePtr(), N0.getValueType(),
6135 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006136 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006137 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006138 N0.getValueType(), ExtLoad);
6139 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006140 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006141 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006142 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6143 }
Chris Lattner812646a2006-05-05 05:58:59 +00006144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006145
Chris Lattner812646a2006-05-05 05:58:59 +00006146 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6147 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6148 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006149 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006150 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006151 N0.hasOneUse()) {
6152 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006153 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006154 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006155 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006156 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6157 VT, LN0->getChain(), LN0->getBasePtr(),
6158 MemVT, LN0->getMemOperand());
6159 CombineTo(N, ExtLoad);
6160 CombineTo(N0.getNode(),
6161 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6162 N0.getValueType(), ExtLoad),
6163 ExtLoad.getValue(1));
6164 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6165 }
Chris Lattner812646a2006-05-05 05:58:59 +00006166 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006167
Chris Lattner65786b02007-04-11 05:32:27 +00006168 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006169 // For vectors:
6170 // aext(setcc) -> vsetcc
6171 // aext(setcc) -> truncate(vsetcc)
6172 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006173 // Only do this before legalize for now.
6174 if (VT.isVector() && !LegalOperations) {
6175 EVT N0VT = N0.getOperand(0).getValueType();
6176 // We know that the # elements of the results is the same as the
6177 // # elements of the compare (and the # elements of the compare result
6178 // for that matter). Check to see that they are the same size. If so,
6179 // we know that the element size of the sext'd result matches the
6180 // element size of the compare operands.
6181 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006182 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006183 N0.getOperand(1),
6184 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006185 // If the desired elements are smaller or larger than the source
6186 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006187 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006188 else {
Hao Liuc636d152014-04-22 09:57:06 +00006189 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006190 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006191 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006192 N0.getOperand(1),
6193 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006194 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006195 }
6196 }
6197
6198 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006199 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006200 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006201 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006202 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006203 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006204 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006205 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006206
Evan Chengf1005572010-04-28 07:10:39 +00006207 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006208}
6209
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006210/// See if the specified operand can be simplified with the knowledge that only
6211/// the bits specified by Mask are used. If so, return the simpler operand,
6212/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006213SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006214 switch (V.getOpcode()) {
6215 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006216 case ISD::Constant: {
6217 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006218 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006219 const APInt &CVal = CV->getAPIntValue();
6220 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006221 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00006222 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006223 break;
6224 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006225 case ISD::OR:
6226 case ISD::XOR:
6227 // If the LHS or RHS don't contribute bits to the or, drop them.
6228 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6229 return V.getOperand(1);
6230 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6231 return V.getOperand(0);
6232 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006233 case ISD::SRL:
6234 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006235 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006236 break;
6237 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6238 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006239 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006240
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006241 // Watch out for shift count overflow though.
6242 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006243 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006244 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006245 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006246 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006247 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006248 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006249 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006250 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006251}
6252
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006253/// If the result of a wider load is shifted to right of N bits and then
6254/// truncated to a narrower type and where N is a multiple of number of bits of
6255/// the narrower type, transform it to a narrower load from address + N / num of
6256/// bits of new type. If the result is to be extended, also fold the extension
6257/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006258SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006259 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006260
Evan Cheng464dc9b2007-03-22 01:54:19 +00006261 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006262 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006263 EVT VT = N->getValueType(0);
6264 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006265
Dan Gohman550c9af2008-08-14 20:04:46 +00006266 // This transformation isn't valid for vector loads.
6267 if (VT.isVector())
6268 return SDValue();
6269
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006270 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006271 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006272 if (Opc == ISD::SIGN_EXTEND_INREG) {
6273 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006274 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006275 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006276 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006277 ExtType = ISD::ZEXTLOAD;
6278 N0 = SDValue(N, 0);
6279 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6280 if (!N01) return SDValue();
6281 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6282 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006283 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006284 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006285 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006286
Owen Anderson53aa7a92009-08-10 22:56:29 +00006287 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006288
Chris Lattner9a499e92010-12-22 08:01:44 +00006289 // Do not generate loads of non-round integer types since these can
6290 // be expensive (and would be wrong if the type is not byte sized).
6291 if (!ExtVT.isRound())
6292 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006293
Evan Cheng464dc9b2007-03-22 01:54:19 +00006294 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006295 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006296 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006297 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006298 // Is the shift amount a multiple of size of VT?
6299 if ((ShAmt & (EVTBits-1)) == 0) {
6300 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006301 // Is the load width a multiple of size of VT?
6302 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006303 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006304 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006305
Chris Lattnercafc1e62010-12-22 08:02:57 +00006306 // At this point, we must have a load or else we can't do the transform.
6307 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006308
Chandler Carruthb27041c2012-12-11 00:36:57 +00006309 // Because a SRL must be assumed to *need* to zero-extend the high bits
6310 // (as opposed to anyext the high bits), we can't combine the zextload
6311 // lowering of SRL and an sextload.
6312 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6313 return SDValue();
6314
Chris Lattnera2050552010-10-01 05:36:09 +00006315 // If the shift amount is larger than the input type then we're not
6316 // accessing any of the loaded bytes. If the load was a zextload/extload
6317 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006318 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006319 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006320 }
6321 }
6322
Dan Gohman68fb0042010-11-03 01:47:46 +00006323 // If the load is shifted left (and the result isn't shifted back right),
6324 // we can fold the truncate through the shift.
6325 unsigned ShLeftAmt = 0;
6326 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006327 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006328 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6329 ShLeftAmt = N01->getZExtValue();
6330 N0 = N0.getOperand(0);
6331 }
6332 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006333
Chris Lattner222374d2010-12-22 07:36:50 +00006334 // If we haven't found a load, we can't narrow it. Don't transform one with
6335 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006336 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6337 return SDValue();
6338
6339 // Don't change the width of a volatile load.
6340 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6341 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006342 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006343
Chris Lattner9a499e92010-12-22 08:01:44 +00006344 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006345 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006346 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006347
Bill Schmidtd006c692013-01-14 22:04:38 +00006348 // For the transform to be legal, the load must produce only two values
6349 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006350 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006351 // transformation is not equivalent, and the downstream logic to replace
6352 // uses gets things wrong.
6353 if (LN0->getNumValues() > 2)
6354 return SDValue();
6355
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006356 // If the load that we're shrinking is an extload and we're not just
6357 // discarding the extension we can't simply shrink the load. Bail.
6358 // TODO: It would be possible to merge the extensions in some cases.
6359 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6360 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6361 return SDValue();
6362
Matt Arsenault810cb622014-12-12 00:00:24 +00006363 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6364 return SDValue();
6365
Chris Lattner222374d2010-12-22 07:36:50 +00006366 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006367
Evan Cheng4c6f9172012-06-26 01:19:33 +00006368 if (PtrType == MVT::Untyped || PtrType.isExtended())
6369 // It's not possible to generate a constant of extended or untyped type.
6370 return SDValue();
6371
Chris Lattner222374d2010-12-22 07:36:50 +00006372 // For big endian targets, we need to adjust the offset to the pointer to
6373 // load the correct bytes.
6374 if (TLI.isBigEndian()) {
6375 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6376 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6377 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006378 }
6379
Chris Lattner222374d2010-12-22 07:36:50 +00006380 uint64_t PtrOff = ShAmt / 8;
6381 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006382 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006383 PtrType, LN0->getBasePtr(),
6384 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006385 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006386
Chris Lattner9a499e92010-12-22 08:01:44 +00006387 SDValue Load;
6388 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006389 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006390 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006391 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006392 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006393 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006394 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006395 LN0->getPointerInfo().getWithOffset(PtrOff),
6396 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006397 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006398
6399 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006400 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006401 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006402
6403 // Shift the result left, if we've swallowed a left shift.
6404 SDValue Result = Load;
6405 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006406 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006407 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6408 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006409 // If the shift amount is as large as the result size (but, presumably,
6410 // no larger than the source) then the useful bits of the result are
6411 // zero; we can't simply return the shortened shift, because the result
6412 // of that operation is undefined.
6413 if (ShLeftAmt >= VT.getSizeInBits())
6414 Result = DAG.getConstant(0, VT);
6415 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006416 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006417 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006418 }
6419
6420 // Return the new loaded value.
6421 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006422}
6423
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006424SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6425 SDValue N0 = N->getOperand(0);
6426 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006427 EVT VT = N->getValueType(0);
6428 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006429 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006430 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006431
Nate Begeman21158fc2005-09-01 00:19:25 +00006432 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006433 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006434 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006435
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006436 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006437 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006438 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006439
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006440 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6441 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006442 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006443 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006444 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006445
Dan Gohman345d63c2008-07-31 00:50:31 +00006446 // fold (sext_in_reg (sext x)) -> (sext x)
6447 // fold (sext_in_reg (aext x)) -> (sext x)
6448 // if x is small enough.
6449 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6450 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006451 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6452 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006453 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006454 }
6455
Chris Lattner9ad59152007-04-17 19:03:21 +00006456 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006457 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006458 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006459
Chris Lattner9ad59152007-04-17 19:03:21 +00006460 // fold operands of sext_in_reg based on knowledge that the top bits are not
6461 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006462 if (SimplifyDemandedBits(SDValue(N, 0)))
6463 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006464
Evan Cheng464dc9b2007-03-22 01:54:19 +00006465 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6466 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006467 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006468 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006469 return NarrowLoad;
6470
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006471 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006472 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006473 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6474 if (N0.getOpcode() == ISD::SRL) {
6475 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006476 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006477 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006478 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006479 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006480 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006481 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006482 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006483 }
6484 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006485
Nate Begeman02b23c62005-10-13 03:11:28 +00006486 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006487 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006488 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006489 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006490 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006491 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006492 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006493 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006494 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006495 LN0->getBasePtr(), EVT,
6496 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006497 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006498 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006499 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006500 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006501 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006502 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006503 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006504 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006505 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006506 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006507 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006508 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006509 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006510 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006511 LN0->getBasePtr(), EVT,
6512 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006513 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006514 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006515 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006516 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006517
6518 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6519 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6520 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6521 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006522 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006523 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006524 BSwap, N1);
6525 }
6526
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006527 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6528 // into a build_vector.
6529 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6530 SmallVector<SDValue, 8> Elts;
6531 unsigned NumElts = N0->getNumOperands();
6532 unsigned ShAmt = VTBits - EVTBits;
6533
6534 for (unsigned i = 0; i != NumElts; ++i) {
6535 SDValue Op = N0->getOperand(i);
6536 if (Op->getOpcode() == ISD::UNDEF) {
6537 Elts.push_back(Op);
6538 continue;
6539 }
6540
6541 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006542 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6543 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006544 Op.getValueType()));
6545 }
6546
Craig Topper48d114b2014-04-26 18:35:24 +00006547 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006548 }
6549
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006550 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006551}
6552
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006553SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6554 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006555 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006556 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006557
6558 // noop truncate
6559 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006560 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006561 // fold (truncate c1) -> c1
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00006562 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006563 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006564 // fold (truncate (truncate x)) -> (truncate x)
6565 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006566 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006567 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006568 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6569 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006570 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006571 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006572 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006573 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006574 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006575 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006576 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006577 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006578 // if the source and dest are the same type, we can drop both the extend
6579 // and the truncate.
6580 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006581 }
Evan Chengd63baea2007-03-21 20:14:05 +00006582
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006583 // Fold extract-and-trunc into a narrow extract. For example:
6584 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6585 // i32 y = TRUNCATE(i64 x)
6586 // -- becomes --
6587 // v16i8 b = BITCAST (v2i64 val)
6588 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6589 //
6590 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006591 // creates this pattern) and before operation legalization after which
6592 // we need to be more careful about the vector instructions that we generate.
6593 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006594 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006595
6596 EVT VecTy = N0.getOperand(0).getValueType();
6597 EVT ExTy = N0.getValueType();
6598 EVT TrTy = N->getValueType(0);
6599
6600 unsigned NumElem = VecTy.getVectorNumElements();
6601 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6602
6603 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6604 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6605
6606 SDValue EltNo = N0->getOperand(1);
6607 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6608 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006609 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006610 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6611
Andrew Trickef9de2a2013-05-25 02:42:55 +00006612 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006613 NVT, N0.getOperand(0));
6614
6615 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006616 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006617 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006618 }
6619 }
6620
Matt Arsenault3332b702014-07-10 18:21:04 +00006621 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6622 if (N0.getOpcode() == ISD::SELECT) {
6623 EVT SrcVT = N0.getValueType();
6624 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6625 TLI.isTruncateFree(SrcVT, VT)) {
6626 SDLoc SL(N0);
6627 SDValue Cond = N0.getOperand(0);
6628 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6629 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6630 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6631 }
6632 }
6633
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006634 // Fold a series of buildvector, bitcast, and truncate if possible.
6635 // For example fold
6636 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6637 // (2xi32 (buildvector x, y)).
6638 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6639 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6640 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6641 N0.getOperand(0).hasOneUse()) {
6642
6643 SDValue BuildVect = N0.getOperand(0);
6644 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6645 EVT TruncVecEltTy = VT.getVectorElementType();
6646
6647 // Check that the element types match.
6648 if (BuildVectEltTy == TruncVecEltTy) {
6649 // Now we only need to compute the offset of the truncated elements.
6650 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6651 unsigned TruncVecNumElts = VT.getVectorNumElements();
6652 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6653
6654 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6655 "Invalid number of elements");
6656
6657 SmallVector<SDValue, 8> Opnds;
6658 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6659 Opnds.push_back(BuildVect.getOperand(i));
6660
Craig Topper48d114b2014-04-26 18:35:24 +00006661 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006662 }
6663 }
6664
Chris Lattner5e6fe052007-10-13 06:35:54 +00006665 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006666 // only the low bits are being used.
6667 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006668 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006669 // may have different active low bits.
6670 if (!VT.isVector()) {
6671 SDValue Shorter =
6672 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6673 VT.getSizeInBits()));
6674 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006675 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006676 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006677 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006678 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006679 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6680 SDValue Reduced = ReduceLoadWidth(N);
6681 if (Reduced.getNode())
6682 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006683 // Handle the case where the load remains an extending load even
6684 // after truncation.
6685 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6686 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6687 if (!LN0->isVolatile() &&
6688 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6689 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6690 VT, LN0->getChain(), LN0->getBasePtr(),
6691 LN0->getMemoryVT(),
6692 LN0->getMemOperand());
6693 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6694 return NewLoad;
6695 }
6696 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006697 }
Michael Liao3ac82012012-10-17 23:45:54 +00006698 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6699 // where ... are all 'undef'.
6700 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6701 SmallVector<EVT, 8> VTs;
6702 SDValue V;
6703 unsigned Idx = 0;
6704 unsigned NumDefs = 0;
6705
6706 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6707 SDValue X = N0.getOperand(i);
6708 if (X.getOpcode() != ISD::UNDEF) {
6709 V = X;
6710 Idx = i;
6711 NumDefs++;
6712 }
6713 // Stop if more than one members are non-undef.
6714 if (NumDefs > 1)
6715 break;
6716 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6717 VT.getVectorElementType(),
6718 X.getValueType().getVectorNumElements()));
6719 }
6720
6721 if (NumDefs == 0)
6722 return DAG.getUNDEF(VT);
6723
6724 if (NumDefs == 1) {
6725 assert(V.getNode() && "The single defined operand is empty!");
6726 SmallVector<SDValue, 8> Opnds;
6727 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6728 if (i != Idx) {
6729 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6730 continue;
6731 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006732 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006733 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006734 Opnds.push_back(NV);
6735 }
Craig Topper48d114b2014-04-26 18:35:24 +00006736 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006737 }
6738 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006739
6740 // Simplify the operands using demanded-bits information.
6741 if (!VT.isVector() &&
6742 SimplifyDemandedBits(SDValue(N, 0)))
6743 return SDValue(N, 0);
6744
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006745 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006746}
6747
Evan Chengb980f6f2008-05-12 23:04:07 +00006748static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006749 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006750 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006751 return Elt.getNode();
6752 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006753}
6754
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006755/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006756/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006757SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006758 assert(N->getOpcode() == ISD::BUILD_PAIR);
6759
Nate Begeman624690c2009-06-05 21:37:30 +00006760 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6761 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006762 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006763 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006764 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006765 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006766
Evan Chengb980f6f2008-05-12 23:04:07 +00006767 if (ISD::isNON_EXTLoad(LD2) &&
6768 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006769 // If both are volatile this would reduce the number of volatile loads.
6770 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006771 !LD1->isVolatile() &&
6772 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006773 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006774 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006775 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006776 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006777
Duncan Sands8651e9c2008-06-13 19:07:40 +00006778 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006779 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006780 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006781 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006782 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006783 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006784
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006785 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006786}
6787
Wesley Peck527da1b2010-11-23 03:31:01 +00006788SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006789 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006790 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006791
Dan Gohmana8665142007-06-25 16:23:39 +00006792 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6793 // Only do this before legalize, since afterward the target may be depending
6794 // on the bitconvert.
6795 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006796 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006797 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006798 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006799 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006800
Owen Anderson53aa7a92009-08-10 22:56:29 +00006801 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006802 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006803 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006804 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006805 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006806 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006807
Dan Gohman921ddd62008-09-05 01:58:21 +00006808 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006809 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00006810 // If we can't allow illegal operations, we need to check that this is just
6811 // a fp -> int or int -> conversion and that the resulting operation will
6812 // be legal.
6813 if (!LegalOperations ||
6814 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6815 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6816 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6817 TLI.isOperationLegal(ISD::Constant, VT)))
6818 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00006819 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006820
Bill Wendling4e0a6152009-01-30 22:44:24 +00006821 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006822 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006823 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006824 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006825
Chris Lattner54560f62005-12-23 05:44:41 +00006826 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006827 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006828 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006829 // Do not change the width of a volatile load.
6830 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006831 // Do not remove the cast if the types differ in endian layout.
6832 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6833 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006834 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6835 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006836 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006837 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006838 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006839 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006840
Evan Chenga4cf58a2007-05-07 21:27:48 +00006841 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006842 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006843 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006844 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006845 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006846 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006847 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006848 return Load;
6849 }
Chris Lattner54560f62005-12-23 05:44:41 +00006850 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006851
Bill Wendling4e0a6152009-01-30 22:44:24 +00006852 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6853 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006854 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006855 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6856 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006857 N0.getNode()->hasOneUse() && VT.isInteger() &&
6858 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006859 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006860 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006861 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006862
Duncan Sands13237ac2008-06-06 12:08:01 +00006863 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006864 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006865 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006866 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006867 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006868 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006869 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006870 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006871
Bill Wendling4e0a6152009-01-30 22:44:24 +00006872 // fold (bitconvert (fcopysign cst, x)) ->
6873 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6874 // Note that we don't handle (copysign x, cst) because this can always be
6875 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006876 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006877 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006878 VT.isInteger() && !VT.isVector()) {
6879 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006880 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006881 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006882 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006883 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006884 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006885
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006886 // If X has a different width than the result/lhs, sext it or truncate it.
6887 unsigned VTWidth = VT.getSizeInBits();
6888 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006889 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006890 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006891 } else if (OrigXWidth > VTWidth) {
6892 // To get the sign bit in the right place, we have to shift it right
6893 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006894 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006895 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006896 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006897 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006898 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006899 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006900 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006901
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006902 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006903 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006904 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006905 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006906
Andrew Trickef9de2a2013-05-25 02:42:55 +00006907 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006908 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006909 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006910 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006911 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006912
Andrew Trickef9de2a2013-05-25 02:42:55 +00006913 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006914 }
Chris Lattner888560d2008-01-27 17:42:27 +00006915 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006916
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006917 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006918 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006919 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6920 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006921 return CombineLD;
6922 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006923
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006924 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006925}
6926
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006927SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006928 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006929 return CombineConsecutiveLoads(N, VT);
6930}
6931
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006932/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6933/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006934SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006935ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006936 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006937
Chris Lattnere4e64b62006-04-02 02:53:43 +00006938 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006939 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006940
Duncan Sands13237ac2008-06-06 12:08:01 +00006941 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6942 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006943
Chris Lattnere4e64b62006-04-02 02:53:43 +00006944 // If this is a conversion of N elements of one type to N elements of another
6945 // type, convert each element. This handles FP<->INT cases.
6946 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006947 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6948 BV->getValueType(0).getVectorNumElements());
6949
6950 // Due to the FP element handling below calling this routine recursively,
6951 // we can end up with a scalar-to-vector node here.
6952 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006953 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6954 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006955 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006956
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006957 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006958 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006959 SDValue Op = BV->getOperand(i);
6960 // If the vector element type is not legal, the BUILD_VECTOR operands
6961 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006962 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006963 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6964 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006965 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006966 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006967 }
Craig Topper48d114b2014-04-26 18:35:24 +00006968 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006969 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006970
Chris Lattnere4e64b62006-04-02 02:53:43 +00006971 // Otherwise, we're growing or shrinking the elements. To avoid having to
6972 // handle annoying details of growing/shrinking FP values, we convert them to
6973 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006974 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006975 // Convert the input float vector to a int vector where the elements are the
6976 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00006977 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006978 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006979 SrcEltVT = IntVT;
6980 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006981
Chris Lattnere4e64b62006-04-02 02:53:43 +00006982 // Now we know the input is an integer vector. If the output is a FP type,
6983 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006984 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00006985 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006986 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006987
Chris Lattnere4e64b62006-04-02 02:53:43 +00006988 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006989 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006990 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006991
Chris Lattnere4e64b62006-04-02 02:53:43 +00006992 // Okay, we know the src/dst types are both integers of differing types.
6993 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006994 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006995 if (SrcBitSize < DstBitSize) {
6996 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006997
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006998 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006999 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00007000 i += NumInputsPerOutput) {
7001 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00007002 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007003 bool EltIsUndef = true;
7004 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7005 // Shift the previously computed bits over.
7006 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007007 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007008 if (Op.getOpcode() == ISD::UNDEF) continue;
7009 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007010
Jay Foad583abbc2010-12-07 08:25:19 +00007011 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00007012 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007013 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007014
Chris Lattnere4e64b62006-04-02 02:53:43 +00007015 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00007016 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007017 else
7018 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7019 }
7020
Owen Anderson117c9e82009-08-12 00:36:31 +00007021 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00007022 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007024
Chris Lattnere4e64b62006-04-02 02:53:43 +00007025 // Finally, this must be the case where we are shrinking elements: each input
7026 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00007027 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007028 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007029 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7030 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007031 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007032
Dan Gohmana8665142007-06-25 16:23:39 +00007033 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007034 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007035 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007036 continue;
7037 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007038
Jay Foad583abbc2010-12-07 08:25:19 +00007039 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7040 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007041
Chris Lattnere4e64b62006-04-02 02:53:43 +00007042 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007043 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007044 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00007045 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00007046 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007047 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007048 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00007049 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007050 }
7051
7052 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007053 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007054 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7055 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007056
Craig Topper48d114b2014-04-26 18:35:24 +00007057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007058}
7059
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007060// Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7061static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7062 bool Aggressive,
7063 SDNode *N,
7064 const TargetLowering &TLI,
7065 SelectionDAG &DAG) {
7066 SDValue N0 = N->getOperand(0);
7067 SDValue N1 = N->getOperand(1);
7068 EVT VT = N->getValueType(0);
7069
7070 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7071 if (N0.getOpcode() == ISD::FMUL &&
7072 (Aggressive || N0->hasOneUse())) {
7073 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7074 N0.getOperand(0), N0.getOperand(1), N1);
7075 }
7076
7077 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7078 // Note: Commutes FADD operands.
7079 if (N1.getOpcode() == ISD::FMUL &&
7080 (Aggressive || N1->hasOneUse())) {
7081 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7082 N1.getOperand(0), N1.getOperand(1), N0);
7083 }
7084
7085 // More folding opportunities when target permits.
7086 if (Aggressive) {
7087 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7088 if (N0.getOpcode() == ISD::FMA &&
7089 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7090 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7091 N0.getOperand(0), N0.getOperand(1),
7092 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7093 N0.getOperand(2).getOperand(0),
7094 N0.getOperand(2).getOperand(1),
7095 N1));
7096 }
7097
7098 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7099 if (N1->getOpcode() == ISD::FMA &&
7100 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7101 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7102 N1.getOperand(0), N1.getOperand(1),
7103 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7104 N1.getOperand(2).getOperand(0),
7105 N1.getOperand(2).getOperand(1),
7106 N0));
7107 }
7108 }
7109
7110 return SDValue();
7111}
7112
7113static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7114 bool Aggressive,
7115 SDNode *N,
7116 const TargetLowering &TLI,
7117 SelectionDAG &DAG) {
7118 SDValue N0 = N->getOperand(0);
7119 SDValue N1 = N->getOperand(1);
7120 EVT VT = N->getValueType(0);
7121
7122 SDLoc SL(N);
7123
7124 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7125 if (N0.getOpcode() == ISD::FMUL &&
7126 (Aggressive || N0->hasOneUse())) {
7127 return DAG.getNode(FusedOpcode, SL, VT,
7128 N0.getOperand(0), N0.getOperand(1),
7129 DAG.getNode(ISD::FNEG, SL, VT, N1));
7130 }
7131
7132 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7133 // Note: Commutes FSUB operands.
7134 if (N1.getOpcode() == ISD::FMUL &&
7135 (Aggressive || N1->hasOneUse()))
7136 return DAG.getNode(FusedOpcode, SL, VT,
7137 DAG.getNode(ISD::FNEG, SL, VT,
7138 N1.getOperand(0)),
7139 N1.getOperand(1), N0);
7140
7141 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7142 if (N0.getOpcode() == ISD::FNEG &&
7143 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7144 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7145 SDValue N00 = N0.getOperand(0).getOperand(0);
7146 SDValue N01 = N0.getOperand(0).getOperand(1);
7147 return DAG.getNode(FusedOpcode, SL, VT,
7148 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7149 DAG.getNode(ISD::FNEG, SL, VT, N1));
7150 }
7151
7152 // More folding opportunities when target permits.
7153 if (Aggressive) {
7154 // fold (fsub (fma x, y, (fmul u, v)), z)
7155 // -> (fma x, y (fma u, v, (fneg z)))
7156 if (N0.getOpcode() == FusedOpcode &&
7157 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7158 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7159 N0.getOperand(0), N0.getOperand(1),
7160 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7161 N0.getOperand(2).getOperand(0),
7162 N0.getOperand(2).getOperand(1),
7163 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7164 N1)));
7165 }
7166
7167 // fold (fsub x, (fma y, z, (fmul u, v)))
7168 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7169 if (N1.getOpcode() == FusedOpcode &&
7170 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7171 SDValue N20 = N1.getOperand(2).getOperand(0);
7172 SDValue N21 = N1.getOperand(2).getOperand(1);
7173 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7174 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7175 N1.getOperand(0)),
7176 N1.getOperand(1),
7177 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7178 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7179 N20),
7180 N21, N0));
7181 }
7182 }
7183
7184 return SDValue();
7185}
7186
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007187SDValue DAGCombiner::visitFADD(SDNode *N) {
7188 SDValue N0 = N->getOperand(0);
7189 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007192 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007193 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007194
Dan Gohmana8665142007-06-25 16:23:39 +00007195 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007196 if (VT.isVector())
7197 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7198 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007199
Lang Hamesa33db652012-06-14 20:37:15 +00007200 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007201 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007202 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007203
Nate Begeman418c6e42005-10-18 00:28:13 +00007204 // canonicalize constant to RHS
7205 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007206 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007207
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007208 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007209 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007210 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007211 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007212 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007213
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007214 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007215 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007216 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007217 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007218 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007219
Sanjay Patel8170dea2014-09-08 17:32:19 +00007220 // If 'unsafe math' is enabled, fold lots of things.
7221 if (Options.UnsafeFPMath) {
7222 // No FP constant should be created after legalization as Instruction
7223 // Selection pass has a hard time dealing with FP constants.
7224 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007225
Sanjay Patel8170dea2014-09-08 17:32:19 +00007226 // fold (fadd A, 0) -> A
7227 if (N1CFP && N1CFP->getValueAPF().isZero())
7228 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007229
Sanjay Patel8170dea2014-09-08 17:32:19 +00007230 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7231 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7232 isa<ConstantFPSDNode>(N0.getOperand(1)))
7233 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7234 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7235 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007236
Sanjay Patel8170dea2014-09-08 17:32:19 +00007237 // If allowed, fold (fadd (fneg x), x) -> 0.0
7238 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7239 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007240
Sanjay Patel8170dea2014-09-08 17:32:19 +00007241 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7242 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7243 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007244
Sanjay Patel8170dea2014-09-08 17:32:19 +00007245 // We can fold chains of FADD's of the same value into multiplications.
7246 // This transform is not safe in general because we are reducing the number
7247 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007248 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7249 if (N0.getOpcode() == ISD::FMUL) {
7250 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7251 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007252
Sanjay Patel8170dea2014-09-08 17:32:19 +00007253 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7254 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7255 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7256 SDValue(CFP01, 0),
7257 DAG.getConstantFP(1.0, VT));
7258 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7259 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007260
Sanjay Patel8170dea2014-09-08 17:32:19 +00007261 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7262 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7263 N1.getOperand(0) == N1.getOperand(1) &&
7264 N0.getOperand(0) == N1.getOperand(0)) {
7265 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7266 SDValue(CFP01, 0),
7267 DAG.getConstantFP(2.0, VT));
7268 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7269 N0.getOperand(0), NewCFP);
7270 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007271 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007272
Sanjay Patel8170dea2014-09-08 17:32:19 +00007273 if (N1.getOpcode() == ISD::FMUL) {
7274 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7275 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007276
Sanjay Patel8170dea2014-09-08 17:32:19 +00007277 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7278 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7279 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7280 SDValue(CFP11, 0),
7281 DAG.getConstantFP(1.0, VT));
7282 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7283 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007284
Sanjay Patel8170dea2014-09-08 17:32:19 +00007285 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7286 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7287 N0.getOperand(0) == N0.getOperand(1) &&
7288 N1.getOperand(0) == N0.getOperand(0)) {
7289 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7290 SDValue(CFP11, 0),
7291 DAG.getConstantFP(2.0, VT));
7292 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7293 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007294 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007295
Sanjay Patel8170dea2014-09-08 17:32:19 +00007296 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7297 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7298 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7299 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7300 (N0.getOperand(0) == N1))
7301 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7302 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007303 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007304
Sanjay Patel8170dea2014-09-08 17:32:19 +00007305 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7306 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7307 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7308 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7309 N1.getOperand(0) == N0)
7310 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7311 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007312 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007313
Sanjay Patel8170dea2014-09-08 17:32:19 +00007314 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7315 if (AllowNewConst &&
7316 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007317 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007318 N1.getOperand(0) == N1.getOperand(1) &&
7319 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007320 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00007321 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007322 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007323 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007324
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007325 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7326 // Assume if there is an fmad instruction that it should be aggressively
7327 // used.
7328 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7329 return Fused;
7330 }
7331
Lang Hames39fb1d02012-06-19 22:51:23 +00007332 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007333 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007334 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007335 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007336
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007337 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7338 // Don't form FMA if we are preferring FMAD.
7339 if (SDValue Fused
7340 = performFaddFmulCombines(ISD::FMA,
7341 TLI.enableAggressiveFMAFusion(VT),
7342 N, TLI, DAG)) {
7343 return Fused;
7344 }
7345 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007346
Olivier Sallenave32509692015-01-13 15:06:36 +00007347 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7348 // to combine into FMA, arrange such nodes accordingly.
7349 if (TLI.isFPExtFree(VT)) {
7350
7351 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7352 if (N0.getOpcode() == ISD::FP_EXTEND) {
7353 SDValue N00 = N0.getOperand(0);
7354 if (N00.getOpcode() == ISD::FMUL)
7355 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7356 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7357 N00.getOperand(0)),
7358 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7359 N00.getOperand(1)), N1);
7360 }
7361
7362 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7363 // Note: Commutes FADD operands.
7364 if (N1.getOpcode() == ISD::FP_EXTEND) {
7365 SDValue N10 = N1.getOperand(0);
7366 if (N10.getOpcode() == ISD::FMUL)
7367 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7368 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7369 N10.getOperand(0)),
7370 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7371 N10.getOperand(1)), N0);
7372 }
7373 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007374 }
7375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007376 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007377}
7378
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007379SDValue DAGCombiner::visitFSUB(SDNode *N) {
7380 SDValue N0 = N->getOperand(0);
7381 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007382 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7383 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007384 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007385 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007386 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007387
Dan Gohmana8665142007-06-25 16:23:39 +00007388 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007389 if (VT.isVector())
7390 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7391 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007392
Nate Begeman418c6e42005-10-18 00:28:13 +00007393 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007394 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007395 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007396
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007397 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007398 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007399 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007400 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007401
Sanjay Patelae402a32014-08-27 20:57:52 +00007402 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007403 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007404 // (fsub A, 0) -> A
7405 if (N1CFP && N1CFP->getValueAPF().isZero())
7406 return N0;
7407
7408 // (fsub 0, B) -> -B
7409 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007410 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007411 return GetNegatedExpression(N1, DAG, LegalOperations);
7412 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7413 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7414 }
7415
7416 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007417 if (N0 == N1)
7418 return DAG.getConstantFP(0.0f, VT);
7419
Sanjay Patelae402a32014-08-27 20:57:52 +00007420 // (fsub x, (fadd x, y)) -> (fneg y)
7421 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007422 if (N1.getOpcode() == ISD::FADD) {
7423 SDValue N10 = N1->getOperand(0);
7424 SDValue N11 = N1->getOperand(1);
7425
Sanjay Patel78614bf2014-08-28 15:53:16 +00007426 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007427 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007428
Sanjay Patel78614bf2014-08-28 15:53:16 +00007429 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007430 return GetNegatedExpression(N10, DAG, LegalOperations);
7431 }
7432 }
7433
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007434 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7435 // Assume if there is an fmad instruction that it should be aggressively
7436 // used.
7437 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7438 return Fused;
7439 }
7440
Lang Hames39fb1d02012-06-19 22:51:23 +00007441 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007442 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007443 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007444 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007445
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007446 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7447 // Don't form FMA if we are preferring FMAD.
Lang Hames39fb1d02012-06-19 22:51:23 +00007448
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007449 if (SDValue Fused
7450 = performFsubFmulCombines(ISD::FMA,
7451 TLI.enableAggressiveFMAFusion(VT),
7452 N, TLI, DAG)) {
7453 return Fused;
7454 }
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007455 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007456
Olivier Sallenave32509692015-01-13 15:06:36 +00007457 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7458 // to combine into FMA, arrange such nodes accordingly.
7459 if (TLI.isFPExtFree(VT)) {
Olivier Sallenave32509692015-01-13 15:06:36 +00007460 // fold (fsub (fpext (fmul x, y)), z)
7461 // -> (fma (fpext x), (fpext y), (fneg z))
7462 if (N0.getOpcode() == ISD::FP_EXTEND) {
7463 SDValue N00 = N0.getOperand(0);
7464 if (N00.getOpcode() == ISD::FMUL)
7465 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7466 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7467 N00.getOperand(0)),
7468 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7469 N00.getOperand(1)),
7470 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7471 }
7472
7473 // fold (fsub x, (fpext (fmul y, z)))
7474 // -> (fma (fneg (fpext y)), (fpext z), x)
7475 // Note: Commutes FSUB operands.
7476 if (N1.getOpcode() == ISD::FP_EXTEND) {
7477 SDValue N10 = N1.getOperand(0);
7478 if (N10.getOpcode() == ISD::FMUL)
7479 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7480 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7481 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7482 VT, N10.getOperand(0))),
7483 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7484 N10.getOperand(1)),
7485 N0);
7486 }
7487
7488 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7489 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7490 if (N0.getOpcode() == ISD::FP_EXTEND) {
7491 SDValue N00 = N0.getOperand(0);
7492 if (N00.getOpcode() == ISD::FNEG) {
7493 SDValue N000 = N00.getOperand(0);
7494 if (N000.getOpcode() == ISD::FMUL) {
7495 return DAG.getNode(ISD::FMA, dl, VT,
7496 DAG.getNode(ISD::FNEG, dl, VT,
7497 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7498 VT, N000.getOperand(0))),
7499 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7500 N000.getOperand(1)),
7501 DAG.getNode(ISD::FNEG, dl, VT, N1));
7502 }
7503 }
7504 }
7505
7506 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7507 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7508 if (N0.getOpcode() == ISD::FNEG) {
7509 SDValue N00 = N0.getOperand(0);
7510 if (N00.getOpcode() == ISD::FP_EXTEND) {
7511 SDValue N000 = N00.getOperand(0);
7512 if (N000.getOpcode() == ISD::FMUL) {
7513 return DAG.getNode(ISD::FMA, dl, VT,
7514 DAG.getNode(ISD::FNEG, dl, VT,
7515 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7516 VT, N000.getOperand(0))),
7517 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7518 N000.getOperand(1)),
7519 DAG.getNode(ISD::FNEG, dl, VT, N1));
7520 }
7521 }
7522 }
7523 }
Lang Hames39fb1d02012-06-19 22:51:23 +00007524 }
7525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007526 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007527}
7528
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007529SDValue DAGCombiner::visitFMUL(SDNode *N) {
7530 SDValue N0 = N->getOperand(0);
7531 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007532 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7533 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007534 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007535 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007536
Dan Gohmana8665142007-06-25 16:23:39 +00007537 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007538 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007539 // This just handles C1 * C2 for vectors. Other vector folds are below.
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007540 if (SDValue FoldedVOp = SimplifyVBinOp(N))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007541 return FoldedVOp;
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007542
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007543 // Canonicalize vector constant to RHS.
7544 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7545 N1.getOpcode() != ISD::BUILD_VECTOR)
7546 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7547 if (BV0->isConstant())
7548 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00007549 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007550
Nate Begemanec48a1b2005-10-17 20:40:11 +00007551 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007552 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007553 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007554
Nate Begemanec48a1b2005-10-17 20:40:11 +00007555 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00007556 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007557 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007558
Owen Andersonb5f167c2012-05-02 21:32:35 +00007559 // fold (fmul A, 1.0) -> A
7560 if (N1CFP && N1CFP->isExactlyValue(1.0))
7561 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007562
Sanjay Patel394c3332014-09-08 20:16:42 +00007563 if (Options.UnsafeFPMath) {
7564 // fold (fmul A, 0) -> 0
7565 if (N1CFP && N1CFP->getValueAPF().isZero())
7566 return N1;
7567
7568 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007569 if (N0.getOpcode() == ISD::FMUL) {
7570 // Fold scalars or any vector constants (not just splats).
7571 // This fold is done in general by InstCombine, but extra fmul insts
7572 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007573 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007574 SDValue N01 = N0.getOperand(1);
7575 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007576 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007577 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007578
7579 // Check 1: Make sure that the first operand of the inner multiply is NOT
7580 // a constant. Otherwise, we may induce infinite looping.
7581 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7582 // Check 2: Make sure that the second operand of the inner multiply and
7583 // the second operand of the outer multiply are constants.
7584 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7585 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7586 SDLoc SL(N);
7587 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7588 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7589 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007590 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007591 }
7592
Sanjay Patel394c3332014-09-08 20:16:42 +00007593 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007594 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7595 // during an early run of DAGCombiner can prevent folding with fmuls
7596 // inserted during lowering.
7597 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7598 SDLoc SL(N);
7599 const SDValue Two = DAG.getConstantFP(2.0, VT);
7600 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7601 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7602 }
7603 }
7604
Nate Begemanec48a1b2005-10-17 20:40:11 +00007605 // fold (fmul X, 2.0) -> (fadd X, X)
7606 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007607 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007608
Dan Gohmanb7170912009-08-10 16:50:32 +00007609 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007610 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007611 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007612 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007613
Bill Wendling3dc5d242009-01-30 22:57:07 +00007614 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007615 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7616 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007617 // Both can be negated for free, check to see if at least one is cheaper
7618 // negated.
7619 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007620 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007621 GetNegatedExpression(N0, DAG, LegalOperations),
7622 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007623 }
7624 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007625
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007626 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007627}
7628
Owen Anderson41b06652012-05-02 22:17:40 +00007629SDValue DAGCombiner::visitFMA(SDNode *N) {
7630 SDValue N0 = N->getOperand(0);
7631 SDValue N1 = N->getOperand(1);
7632 SDValue N2 = N->getOperand(2);
7633 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7634 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7635 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007636 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007637 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007638
7639 // Constant fold FMA.
7640 if (isa<ConstantFPSDNode>(N0) &&
7641 isa<ConstantFPSDNode>(N1) &&
7642 isa<ConstantFPSDNode>(N2)) {
7643 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7644 }
7645
Sanjay Patel78614bf2014-08-28 15:53:16 +00007646 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007647 if (N0CFP && N0CFP->isZero())
7648 return N2;
7649 if (N1CFP && N1CFP->isZero())
7650 return N2;
7651 }
Owen Anderson41b06652012-05-02 22:17:40 +00007652 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007653 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007654 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007655 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007656
Owen Andersonc7aaf522012-05-30 18:50:39 +00007657 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007658 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007659 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007660
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007661 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007662 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007663 N2.getOpcode() == ISD::FMUL &&
7664 N0 == N2.getOperand(0) &&
7665 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7666 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7667 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7668 }
7669
7670
7671 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007672 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007673 N0.getOpcode() == ISD::FMUL && N1CFP &&
7674 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7675 return DAG.getNode(ISD::FMA, dl, VT,
7676 N0.getOperand(0),
7677 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7678 N2);
7679 }
7680
7681 // (fma x, 1, y) -> (fadd x, y)
7682 // (fma x, -1, y) -> (fadd (fneg x), y)
7683 if (N1CFP) {
7684 if (N1CFP->isExactlyValue(1.0))
7685 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7686
7687 if (N1CFP->isExactlyValue(-1.0) &&
7688 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7689 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007690 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007691 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7692 }
7693 }
7694
7695 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007696 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007697 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007698 DAG.getNode(ISD::FADD, dl, VT,
7699 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007700
7701 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007702 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007703 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7704 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007705 DAG.getNode(ISD::FADD, dl, VT,
7706 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007707
7708
Owen Anderson41b06652012-05-02 22:17:40 +00007709 return SDValue();
7710}
7711
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007712SDValue DAGCombiner::visitFDIV(SDNode *N) {
7713 SDValue N0 = N->getOperand(0);
7714 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007715 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7716 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007717 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007718 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007719 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007720
Dan Gohmana8665142007-06-25 16:23:39 +00007721 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007722 if (VT.isVector())
7723 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7724 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007725
Nate Begeman569c4392006-01-18 22:35:16 +00007726 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007727 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007728 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007729
Sanjay Patelb67bd262014-09-21 15:19:15 +00007730 if (Options.UnsafeFPMath) {
7731 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7732 if (N1CFP) {
7733 // Compute the reciprocal 1.0 / c2.
7734 APFloat N1APF = N1CFP->getValueAPF();
7735 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7736 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7737 // Only do the transform if the reciprocal is a legal fp immediate that
7738 // isn't too nasty (eg NaN, denormal, ...).
7739 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7740 (!LegalOperations ||
7741 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7742 // backend)... we should handle this gracefully after Legalize.
7743 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7744 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7745 TLI.isFPImmLegal(Recip, VT)))
7746 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7747 DAG.getConstantFP(Recip, VT));
7748 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007749
Sanjay Patelb67bd262014-09-21 15:19:15 +00007750 // If this FDIV is part of a reciprocal square root, it may be folded
7751 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007752 if (N1.getOpcode() == ISD::FSQRT) {
7753 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007754 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7755 }
7756 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7757 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7758 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007759 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7760 AddToWorklist(RV.getNode());
7761 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7762 }
7763 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7764 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7765 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007766 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7767 AddToWorklist(RV.getNode());
7768 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7769 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007770 } else if (N1.getOpcode() == ISD::FMUL) {
7771 // Look through an FMUL. Even though this won't remove the FDIV directly,
7772 // it's still worthwhile to get rid of the FSQRT if possible.
7773 SDValue SqrtOp;
7774 SDValue OtherOp;
7775 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7776 SqrtOp = N1.getOperand(0);
7777 OtherOp = N1.getOperand(1);
7778 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7779 SqrtOp = N1.getOperand(1);
7780 OtherOp = N1.getOperand(0);
7781 }
7782 if (SqrtOp.getNode()) {
7783 // We found a FSQRT, so try to make this fold:
7784 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7785 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007786 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7787 AddToWorklist(RV.getNode());
7788 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7789 }
7790 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007791 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007792
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007793 // Fold into a reciprocal estimate and multiply instead of a real divide.
7794 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7795 AddToWorklist(RV.getNode());
7796 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7797 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007798 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007799
Bill Wendling3dc5d242009-01-30 22:57:07 +00007800 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007801 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7802 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007803 // Both can be negated for free, check to see if at least one is cheaper
7804 // negated.
7805 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007806 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007807 GetNegatedExpression(N0, DAG, LegalOperations),
7808 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007809 }
7810 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007811
Hao Liu44e5d7a2014-11-21 06:39:58 +00007812 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7813 // reciprocal.
7814 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7815 // Notice that this is not always beneficial. One reason is different target
7816 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7817 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7818 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7819 if (Options.UnsafeFPMath) {
7820 // Skip if current node is a reciprocal.
7821 if (N0CFP && N0CFP->isExactlyValue(1.0))
7822 return SDValue();
7823
7824 SmallVector<SDNode *, 4> Users;
7825 // Find all FDIV users of the same divisor.
7826 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7827 UE = N1.getNode()->use_end();
7828 UI != UE; ++UI) {
7829 SDNode *User = UI.getUse().getUser();
7830 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7831 Users.push_back(User);
7832 }
7833
7834 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7835 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7836 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7837
7838 // Dividend / Divisor -> Dividend * Reciprocal
7839 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7840 if ((*I)->getOperand(0) != FPOne) {
7841 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7842 (*I)->getOperand(0), Reciprocal);
7843 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7844 }
7845 }
7846 return SDValue();
7847 }
7848 }
7849
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007850 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007851}
7852
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007853SDValue DAGCombiner::visitFREM(SDNode *N) {
7854 SDValue N0 = N->getOperand(0);
7855 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007856 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7857 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007858 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007859
Nate Begeman569c4392006-01-18 22:35:16 +00007860 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007861 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007862 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007863
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007864 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007865}
7866
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007867SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00007868 if (DAG.getTarget().Options.UnsafeFPMath &&
7869 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007870 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007871 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007872 EVT VT = RV.getValueType();
7873 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7874 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007875
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007876 // Unfortunately, RV is now NaN if the input was exactly 0.
7877 // Select out this case and force the answer to 0.
7878 SDValue Zero = DAG.getConstantFP(0.0, VT);
7879 SDValue ZeroCmp =
7880 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7881 N->getOperand(0), Zero, ISD::SETEQ);
7882 AddToWorklist(ZeroCmp.getNode());
7883 AddToWorklist(RV.getNode());
7884
7885 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7886 SDLoc(N), VT, ZeroCmp, Zero, RV);
7887 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007888 }
7889 }
7890 return SDValue();
7891}
7892
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007893SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7894 SDValue N0 = N->getOperand(0);
7895 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007896 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7897 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007898 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007899
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007900 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007901 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007902
Chris Lattner3bc40502006-03-05 05:30:57 +00007903 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007904 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007905 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7906 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007907 if (!V.isNegative()) {
7908 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007909 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007910 } else {
7911 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007912 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7913 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007914 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007915 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007916
Chris Lattner3bc40502006-03-05 05:30:57 +00007917 // copysign(fabs(x), y) -> copysign(x, y)
7918 // copysign(fneg(x), y) -> copysign(x, y)
7919 // copysign(copysign(x,z), y) -> copysign(x, y)
7920 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7921 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007922 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007923 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007924
7925 // copysign(x, abs(y)) -> abs(x)
7926 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007927 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007928
Chris Lattner3bc40502006-03-05 05:30:57 +00007929 // copysign(x, copysign(y,z)) -> copysign(x, z)
7930 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007931 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007932 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007933
Chris Lattner3bc40502006-03-05 05:30:57 +00007934 // copysign(x, fp_extend(y)) -> copysign(x, y)
7935 // copysign(x, fp_round(y)) -> copysign(x, y)
7936 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007937 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007938 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007940 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007941}
7942
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007943SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7944 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007945 EVT VT = N->getValueType(0);
7946 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007947
Nate Begeman21158fc2005-09-01 00:19:25 +00007948 // fold (sint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00007949 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007950 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007951 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007952 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007953 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007954
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007955 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7956 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007957 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7958 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007959 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007960 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007961 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007962 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007963
Alp Tokercb402912014-01-24 17:20:08 +00007964 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007965 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007966 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7967 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7968 !VT.isVector() &&
7969 (!LegalOperations ||
7970 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7971 SDValue Ops[] =
7972 { N0.getOperand(0), N0.getOperand(1),
7973 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7974 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007975 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007976 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007977
Nadav Rotem90560762012-07-23 07:59:50 +00007978 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7979 // (select_cc x, y, 1.0, 0.0,, cc)
7980 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7981 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7982 (!LegalOperations ||
7983 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7984 SDValue Ops[] =
7985 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7986 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7987 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007988 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007989 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007990 }
7991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007992 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007993}
7994
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007995SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7996 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007997 EVT VT = N->getValueType(0);
7998 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007999
Nate Begeman21158fc2005-09-01 00:19:25 +00008000 // fold (uint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008001 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008002 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008003 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008004 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008005 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008006
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008007 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8008 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008009 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8010 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008011 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008012 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008013 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008014 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008015
Alp Tokercb402912014-01-24 17:20:08 +00008016 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008017 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008018 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008019
Nadav Rotem90560762012-07-23 07:59:50 +00008020 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8021 (!LegalOperations ||
8022 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8023 SDValue Ops[] =
8024 { N0.getOperand(0), N0.getOperand(1),
8025 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8026 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008027 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008028 }
8029 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008030
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008031 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008032}
8033
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008034// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8035static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8036 SDValue N0 = N->getOperand(0);
8037 EVT VT = N->getValueType(0);
8038
8039 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8040 return SDValue();
8041
8042 SDValue Src = N0.getOperand(0);
8043 EVT SrcVT = Src.getValueType();
8044 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8045 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8046
8047 // We can safely assume the conversion won't overflow the output range,
8048 // because (for example) (uint8_t)18293.f is undefined behavior.
8049
8050 // Since we can assume the conversion won't overflow, our decision as to
8051 // whether the input will fit in the float should depend on the minimum
8052 // of the input range and output range.
8053
8054 // This means this is also safe for a signed input and unsigned output, since
8055 // a negative input would lead to undefined behavior.
8056 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8057 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8058 unsigned ActualSize = std::min(InputSize, OutputSize);
8059 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8060
8061 // We can only fold away the float conversion if the input range can be
8062 // represented exactly in the float range.
8063 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8064 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8065 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8066 : ISD::ZERO_EXTEND;
8067 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8068 }
8069 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8070 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8071 if (SrcVT == VT)
8072 return Src;
8073 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8074 }
8075 return SDValue();
8076}
8077
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008078SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8079 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008080 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008081 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008082
Nate Begeman21158fc2005-09-01 00:19:25 +00008083 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008084 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008085 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008086
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008087 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008088}
8089
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008090SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8091 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008092 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008093 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008094
Nate Begeman21158fc2005-09-01 00:19:25 +00008095 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008096 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008097 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008098
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008099 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008100}
8101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008102SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8103 SDValue N0 = N->getOperand(0);
8104 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008105 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008106 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008107
Nate Begeman21158fc2005-09-01 00:19:25 +00008108 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008109 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008110 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008111
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008112 // fold (fp_round (fp_extend x)) -> x
8113 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8114 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008115
Chris Lattner0feb1b02008-01-24 06:45:35 +00008116 // fold (fp_round (fp_round x)) -> (fp_round x)
8117 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008118 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8119 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8120 // If the first fp_round isn't a value preserving truncation, it might
8121 // introduce a tie in the second fp_round, that wouldn't occur in the
8122 // single-step fp_round we want to fold to.
8123 // In other words, double rounding isn't the same as rounding.
8124 // Also, this is a value preserving truncation iff both fp_round's are.
8125 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8126 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8127 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
Chris Lattner0feb1b02008-01-24 06:45:35 +00008128 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008129
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008130 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008131 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008132 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008133 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008134 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008135 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008136 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008139 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008140}
8141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008142SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8143 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008144 EVT VT = N->getValueType(0);
8145 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008147
Nate Begeman21158fc2005-09-01 00:19:25 +00008148 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008149 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00008150 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008151 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008152 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008154 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008155}
8156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008157SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8158 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008159 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008160
Chris Lattner5919b482007-12-29 06:55:23 +00008161 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008162 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008163 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008164 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008165
Nate Begeman21158fc2005-09-01 00:19:25 +00008166 // fold (fp_extend c1fp) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008167 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008168 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008169
8170 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8171 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008172 if (N0.getOpcode() == ISD::FP_ROUND
8173 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008174 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008175 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008176 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008177 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008178 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008179 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008181
Chris Lattner72733e52008-01-17 07:00:52 +00008182 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008183 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008184 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008185 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008186 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008187 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008188 LN0->getBasePtr(), N0.getValueType(),
8189 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008190 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008191 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008192 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00008193 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00008194 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008195 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008196 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008197
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008198 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008199}
8200
Sanjay Patelccd26762014-08-28 21:51:37 +00008201SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8202 SDValue N0 = N->getOperand(0);
8203 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8204 EVT VT = N->getValueType(0);
8205
8206 // fold (fceil c1) -> fceil(c1)
8207 if (N0CFP)
8208 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8209
8210 return SDValue();
8211}
8212
8213SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8214 SDValue N0 = N->getOperand(0);
8215 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8216 EVT VT = N->getValueType(0);
8217
8218 // fold (ftrunc c1) -> ftrunc(c1)
8219 if (N0CFP)
8220 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8221
8222 return SDValue();
8223}
8224
8225SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8226 SDValue N0 = N->getOperand(0);
8227 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8228 EVT VT = N->getValueType(0);
8229
8230 // fold (ffloor c1) -> ffloor(c1)
8231 if (N0CFP)
8232 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8233
8234 return SDValue();
8235}
8236
8237// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008238SDValue DAGCombiner::visitFNEG(SDNode *N) {
8239 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008240 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008241
Sanjay Patelccd26762014-08-28 21:51:37 +00008242 // Constant fold FNEG.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008243 if (isConstantFPBuildVectorOrConstantFP(N0))
8244 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008245
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008246 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8247 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008248 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008249
Sanjay Patel35d31332014-08-14 15:15:28 +00008250 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008251 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008252 if (!TLI.isFNegFree(VT) &&
8253 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008254 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008255 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008256 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008257 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008258 APInt SignMask;
8259 if (N0.getValueType().isVector()) {
8260 // For a vector, get a mask such as 0x80... per scalar element
8261 // and splat it.
8262 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8263 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8264 } else {
8265 // For a scalar, just generate 0x80...
8266 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8267 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008268 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00008269 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008270 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008271 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008272 }
8273 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008274
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008275 // (fneg (fmul c, x)) -> (fmul -c, x)
8276 if (N0.getOpcode() == ISD::FMUL) {
8277 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008278 if (CFP1) {
8279 APFloat CVal = CFP1->getValueAPF();
8280 CVal.changeSign();
8281 if (Level >= AfterLegalizeDAG &&
8282 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8283 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8284 return DAG.getNode(
8285 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8286 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8287 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008288 }
8289
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008290 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008291}
8292
Matt Arsenault7c936902014-10-21 23:01:01 +00008293SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8294 SDValue N0 = N->getOperand(0);
8295 SDValue N1 = N->getOperand(1);
8296 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8297 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8298
8299 if (N0CFP && N1CFP) {
8300 const APFloat &C0 = N0CFP->getValueAPF();
8301 const APFloat &C1 = N1CFP->getValueAPF();
8302 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8303 }
8304
8305 if (N0CFP) {
8306 EVT VT = N->getValueType(0);
8307 // Canonicalize to constant on RHS.
8308 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8309 }
8310
8311 return SDValue();
8312}
8313
8314SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8315 SDValue N0 = N->getOperand(0);
8316 SDValue N1 = N->getOperand(1);
8317 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8318 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8319
8320 if (N0CFP && N1CFP) {
8321 const APFloat &C0 = N0CFP->getValueAPF();
8322 const APFloat &C1 = N1CFP->getValueAPF();
8323 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8324 }
8325
8326 if (N0CFP) {
8327 EVT VT = N->getValueType(0);
8328 // Canonicalize to constant on RHS.
8329 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8330 }
8331
8332 return SDValue();
8333}
8334
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008335SDValue DAGCombiner::visitFABS(SDNode *N) {
8336 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008337 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008338
Nate Begeman21158fc2005-09-01 00:19:25 +00008339 // fold (fabs c1) -> fabs(c1)
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008340 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008341 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008342
Nate Begeman21158fc2005-09-01 00:19:25 +00008343 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008344 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008345 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008346
Nate Begeman21158fc2005-09-01 00:19:25 +00008347 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008348 // fold (fabs (fcopysign x, y)) -> (fabs x)
8349 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008350 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008351
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008352 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008353 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008354 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008355 N0.getOpcode() == ISD::BITCAST &&
8356 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008357 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008358 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008359 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008360 APInt SignMask;
8361 if (N0.getValueType().isVector()) {
8362 // For a vector, get a mask such as 0x7f... per scalar element
8363 // and splat it.
8364 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8365 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8366 } else {
8367 // For a scalar, just generate 0x7f...
8368 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8369 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008370 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008371 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008372 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008373 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008374 }
8375 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008376
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008377 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008378}
8379
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008380SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8381 SDValue Chain = N->getOperand(0);
8382 SDValue N1 = N->getOperand(1);
8383 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008384
Dan Gohman82e80012009-11-17 00:47:23 +00008385 // If N is a constant we could fold this into a fallthrough or unconditional
8386 // branch. However that doesn't happen very often in normal code, because
8387 // Instcombine/SimplifyCFG should have handled the available opportunities.
8388 // If we did this folding here, it would be necessary to update the
8389 // MachineBasicBlock CFG, which is awkward.
8390
Nate Begeman7e7f4392006-02-01 07:19:44 +00008391 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8392 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008393 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008394 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8395 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008396 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008397 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008398 N1.getOperand(0), N1.getOperand(1), N2);
8399 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008400
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008401 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8402 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8403 (N1.getOperand(0).hasOneUse() &&
8404 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008405 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008406 if (N1.getOpcode() == ISD::TRUNCATE) {
8407 // Look pass the truncate.
8408 Trunc = N1.getNode();
8409 N1 = N1.getOperand(0);
8410 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008411
Bill Wendlingaa28be62009-03-26 06:14:09 +00008412 // Match this pattern so that we can generate simpler code:
8413 //
8414 // %a = ...
8415 // %b = and i32 %a, 2
8416 // %c = srl i32 %b, 1
8417 // brcond i32 %c ...
8418 //
8419 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008420 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008421 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008422 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008423 // %c = setcc eq %b, 0
8424 // brcond %c ...
8425 //
8426 // This applies only when the AND constant value has one bit set and the
8427 // SRL constant is equal to the log2 of the AND constant. The back-end is
8428 // smart enough to convert the result into a TEST/JMP sequence.
8429 SDValue Op0 = N1.getOperand(0);
8430 SDValue Op1 = N1.getOperand(1);
8431
8432 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008433 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008434 SDValue AndOp1 = Op0.getOperand(1);
8435
8436 if (AndOp1.getOpcode() == ISD::Constant) {
8437 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8438
8439 if (AndConst.isPowerOf2() &&
8440 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8441 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008442 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008443 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008444 Op0, DAG.getConstant(0, Op0.getValueType()),
8445 ISD::SETNE);
8446
Andrew Trickef9de2a2013-05-25 02:42:55 +00008447 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008448 MVT::Other, Chain, SetCC, N2);
8449 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8450 // will convert it back to (X & C1) >> C2.
8451 CombineTo(N, NewBRCond, false);
8452 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008453 if (Trunc)
8454 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008455 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008456 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008457 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008458 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008459 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008460 }
8461 }
8462 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008463
8464 if (Trunc)
8465 // Restore N1 if the above transformation doesn't match.
8466 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008467 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008468
Evan Cheng228c31f2010-02-27 07:36:59 +00008469 // Transform br(xor(x, y)) -> br(x != y)
8470 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8471 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8472 SDNode *TheXor = N1.getNode();
8473 SDValue Op0 = TheXor->getOperand(0);
8474 SDValue Op1 = TheXor->getOperand(1);
8475 if (Op0.getOpcode() == Op1.getOpcode()) {
8476 // Avoid missing important xor optimizations.
8477 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008478 if (Tmp.getNode()) {
8479 if (Tmp.getNode() != TheXor) {
8480 DEBUG(dbgs() << "\nReplacing.8 ";
8481 TheXor->dump(&DAG);
8482 dbgs() << "\nWith: ";
8483 Tmp.getNode()->dump(&DAG);
8484 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008485 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008486 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008487 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008488 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008489 MVT::Other, Chain, Tmp, N2);
8490 }
8491
Benjamin Kramer93354432013-03-30 21:28:18 +00008492 // visitXOR has changed XOR's operands or replaced the XOR completely,
8493 // bail out.
8494 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008495 }
8496 }
8497
8498 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8499 bool Equal = false;
8500 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8501 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8502 Op0.getOpcode() == ISD::XOR) {
8503 TheXor = Op0.getNode();
8504 Equal = true;
8505 }
8506
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008507 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008508 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008509 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008510 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008511 SetCCVT,
8512 Op0, Op1,
8513 Equal ? ISD::SETEQ : ISD::SETNE);
8514 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008515 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008516 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008517 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008518 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008519 MVT::Other, Chain, SetCC, N2);
8520 }
8521 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008522
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008523 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008524}
8525
Chris Lattnera49e16f2005-10-05 06:47:48 +00008526// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8527//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008528SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008529 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008530 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008531
Dan Gohman82e80012009-11-17 00:47:23 +00008532 // If N is a constant we could fold this into a fallthrough or unconditional
8533 // branch. However that doesn't happen very often in normal code, because
8534 // Instcombine/SimplifyCFG should have handled the available opportunities.
8535 // If we did this folding here, it would be necessary to update the
8536 // MachineBasicBlock CFG, which is awkward.
8537
Duncan Sands93b66092008-06-09 11:32:28 +00008538 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008539 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008540 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008541 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008542 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008543
Nate Begemanbd7df032005-10-05 21:43:42 +00008544 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008545 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008546 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008547 N->getOperand(0), Simp.getOperand(2),
8548 Simp.getOperand(0), Simp.getOperand(1),
8549 N->getOperand(4));
8550
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008551 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008552}
8553
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008554/// Return true if 'Use' is a load or a store that uses N as its base pointer
8555/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008556static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8557 SelectionDAG &DAG,
8558 const TargetLowering &TLI) {
8559 EVT VT;
8560 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8561 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8562 return false;
8563 VT = Use->getValueType(0);
8564 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8565 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8566 return false;
8567 VT = ST->getValue().getValueType();
8568 } else
8569 return false;
8570
Chandler Carruth95f83e02013-01-07 15:14:13 +00008571 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008572 if (N->getOpcode() == ISD::ADD) {
8573 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8574 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008575 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008576 AM.BaseOffs = Offset->getSExtValue();
8577 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008578 // [reg +/- reg]
8579 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008580 } else if (N->getOpcode() == ISD::SUB) {
8581 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8582 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008583 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008584 AM.BaseOffs = -Offset->getSExtValue();
8585 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008586 // [reg +/- reg]
8587 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008588 } else
8589 return false;
8590
8591 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8592}
8593
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008594/// Try turning a load/store into a pre-indexed load/store when the base
8595/// pointer is an add or subtract and it has other uses besides the load/store.
8596/// After the transformation, the new indexed load/store has effectively folded
8597/// the add/subtract in and all of its other uses are redirected to the
8598/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008599bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008600 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008601 return false;
8602
8603 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008604 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008605 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008606 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008607 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008608 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008609 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008610 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008611 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8612 return false;
8613 Ptr = LD->getBasePtr();
8614 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008615 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008616 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008617 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008618 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8619 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8620 return false;
8621 Ptr = ST->getBasePtr();
8622 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008623 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008624 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008625 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008626
Chris Lattnereabc15c2006-11-11 00:56:29 +00008627 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8628 // out. There is no reason to make this a preinc/predec.
8629 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008630 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008631 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008632
Chris Lattnereabc15c2006-11-11 00:56:29 +00008633 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008634 SDValue BasePtr;
8635 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008636 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8637 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8638 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008639
8640 // Backends without true r+i pre-indexed forms may need to pass a
8641 // constant base with a variable offset so that constant coercion
8642 // will work with the patterns in canonical form.
8643 bool Swapped = false;
8644 if (isa<ConstantSDNode>(BasePtr)) {
8645 std::swap(BasePtr, Offset);
8646 Swapped = true;
8647 }
8648
Evan Cheng044a0a82007-05-03 23:52:19 +00008649 // Don't create a indexed load / store with zero offset.
8650 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008651 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008652 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008653
Chris Lattnera0a80032006-11-11 01:00:15 +00008654 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008655 // 1) The new base ptr is a frame index.
8656 // 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 +00008657 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008658 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008659 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008660 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008661
Chris Lattnera0a80032006-11-11 01:00:15 +00008662 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8663 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008664 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008665 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008666
Chris Lattnera0a80032006-11-11 01:00:15 +00008667 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008668 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008669 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008670 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008671 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008672 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008673
Hal Finkel25819052013-02-08 21:35:47 +00008674 // If the offset is a constant, there may be other adds of constants that
8675 // can be folded with this one. We should do this to avoid having to keep
8676 // a copy of the original base pointer.
8677 SmallVector<SDNode *, 16> OtherUses;
8678 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008679 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008680 if (Use == Ptr.getNode())
8681 continue;
8682
8683 if (Use->isPredecessorOf(N))
8684 continue;
8685
8686 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8687 OtherUses.clear();
8688 break;
8689 }
8690
8691 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8692 if (Op1.getNode() == BasePtr.getNode())
8693 std::swap(Op0, Op1);
8694 assert(Op0.getNode() == BasePtr.getNode() &&
8695 "Use of ADD/SUB but not an operand");
8696
8697 if (!isa<ConstantSDNode>(Op1)) {
8698 OtherUses.clear();
8699 break;
8700 }
8701
8702 // FIXME: In some cases, we can be smarter about this.
8703 if (Op1.getValueType() != Offset.getValueType()) {
8704 OtherUses.clear();
8705 break;
8706 }
8707
8708 OtherUses.push_back(Use);
8709 }
8710
8711 if (Swapped)
8712 std::swap(BasePtr, Offset);
8713
Evan Chenga4d187b2007-05-24 02:35:39 +00008714 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008715 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008716
8717 // Caches for hasPredecessorHelper
8718 SmallPtrSet<const SDNode *, 32> Visited;
8719 SmallVector<const SDNode *, 16> Worklist;
8720
Jim Grosbache8160032014-04-11 01:13:13 +00008721 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008722 if (Use == N)
8723 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008724 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008725 return false;
8726
Evan Chengfa832632012-01-13 01:37:24 +00008727 // If Ptr may be folded in addressing mode of other use, then it's
8728 // not profitable to do this transformation.
8729 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008730 RealUse = true;
8731 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008732
Chris Lattnereabc15c2006-11-11 00:56:29 +00008733 if (!RealUse)
8734 return false;
8735
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008736 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008737 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008738 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008739 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008740 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008741 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008742 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008743 ++PreIndexedNodes;
8744 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008745 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008746 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008747 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008748 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008749 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008750 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008751 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008752 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8753 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008754 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008755 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008756 }
8757
Chris Lattnereabc15c2006-11-11 00:56:29 +00008758 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008759 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008760
Hal Finkel25819052013-02-08 21:35:47 +00008761 if (Swapped)
8762 std::swap(BasePtr, Offset);
8763
8764 // Replace other uses of BasePtr that can be updated to use Ptr
8765 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8766 unsigned OffsetIdx = 1;
8767 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8768 OffsetIdx = 0;
8769 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8770 BasePtr.getNode() && "Expected BasePtr operand");
8771
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008772 // We need to replace ptr0 in the following expression:
8773 // x0 * offset0 + y0 * ptr0 = t0
8774 // knowing that
8775 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008776 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008777 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8778 // indexed load/store and the expresion that needs to be re-written.
8779 //
8780 // Therefore, we have:
8781 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008782
8783 ConstantSDNode *CN =
8784 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008785 int X0, X1, Y0, Y1;
8786 APInt Offset0 = CN->getAPIntValue();
8787 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008788
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008789 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8790 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8791 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8792 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008793
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008794 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8795
8796 APInt CNV = Offset0;
8797 if (X0 < 0) CNV = -CNV;
8798 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8799 else CNV = CNV - Offset1;
8800
8801 // We can now generate the new expression.
8802 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8803 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8804
8805 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00008806 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00008807 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8808 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00008809 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00008810 }
8811
Chris Lattnereabc15c2006-11-11 00:56:29 +00008812 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008813 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008814 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00008815
8816 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008817}
8818
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008819/// Try to combine a load/store with a add/sub of the base pointer node into a
8820/// post-indexed load/store. The transformation folded the add/subtract into the
8821/// new indexed load/store effectively and all of its uses are redirected to the
8822/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008823bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008824 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008825 return false;
8826
8827 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008828 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008829 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008830 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008831 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008832 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008833 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008834 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8835 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8836 return false;
8837 Ptr = LD->getBasePtr();
8838 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008839 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008840 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008841 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008842 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8843 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8844 return false;
8845 Ptr = ST->getBasePtr();
8846 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008847 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008848 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008849 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008850
Gabor Greiff304a7a2008-08-28 21:40:38 +00008851 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008852 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008853
Jim Grosbache8160032014-04-11 01:13:13 +00008854 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008855 if (Op == N ||
8856 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8857 continue;
8858
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008859 SDValue BasePtr;
8860 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008861 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8862 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00008863 // Don't create a indexed load / store with zero offset.
8864 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008865 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008866 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008867
Chris Lattnereabc15c2006-11-11 00:56:29 +00008868 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008869 // 1) All uses are load / store ops that use it as base ptr (and
8870 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008871 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8872 // nor a successor of N. Otherwise, if Op is folded that would
8873 // create a cycle.
8874
Evan Chengcfc05132009-05-06 18:25:01 +00008875 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8876 continue;
8877
Chris Lattnereabc15c2006-11-11 00:56:29 +00008878 // Check for #1.
8879 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008880 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008881 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008882 continue;
8883
Chris Lattnereabc15c2006-11-11 00:56:29 +00008884 // If all the uses are load / store addresses, then don't do the
8885 // transformation.
8886 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8887 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008888 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008889 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008890 RealUse = true;
8891 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008892
Chris Lattnereabc15c2006-11-11 00:56:29 +00008893 if (!RealUse) {
8894 TryNext = true;
8895 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008896 }
8897 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008898 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008899
Chris Lattnereabc15c2006-11-11 00:56:29 +00008900 if (TryNext)
8901 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008902
Chris Lattnereabc15c2006-11-11 00:56:29 +00008903 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008904 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008905 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008906 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008907 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008908 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008909 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008910 ++PostIndexedNodes;
8911 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008912 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008913 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008914 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008915 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008916 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008917 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008918 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008919 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8920 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008921 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008922 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008923 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008924
Chris Lattnereabc15c2006-11-11 00:56:29 +00008925 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008926 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008927
8928 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008929 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008930 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008931 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008932 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008933 }
8934 }
8935 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008936
Chris Lattnerffad2162006-11-11 00:39:41 +00008937 return false;
8938}
8939
Hal Finkel51e6fa22014-09-02 06:24:04 +00008940/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8941SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8942 ISD::MemIndexedMode AM = LD->getAddressingMode();
8943 assert(AM != ISD::UNINDEXED);
8944 SDValue BP = LD->getOperand(1);
8945 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008946
8947 // Some backends use TargetConstants for load offsets, but don't expect
8948 // TargetConstants in general ADD nodes. We can convert these constants into
8949 // regular Constants (if the constant is not opaque).
8950 assert((Inc.getOpcode() != ISD::TargetConstant ||
8951 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8952 "Cannot split out indexing using opaque target constants");
8953 if (Inc.getOpcode() == ISD::TargetConstant) {
8954 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8955 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8956 ConstInc->getValueType(0));
8957 }
8958
Hal Finkel51e6fa22014-09-02 06:24:04 +00008959 unsigned Opc =
8960 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8961 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8962}
8963
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008964SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008965 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008966 SDValue Chain = LD->getChain();
8967 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008968
Evan Chenga684cd22007-05-01 00:38:21 +00008969 // If load is not volatile and there are no uses of the loaded value (and
8970 // the updated indexed value in case of indexed loads), change uses of the
8971 // chain value into uses of the chain input (i.e. delete the dead load).
8972 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008973 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008974 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008975 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008976 // It's not safe to use the two value CombineTo variant here. e.g.
8977 // v1, chain2 = load chain1, loc
8978 // v2, chain3 = load chain2, loc
8979 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008980 // Now we replace use of chain2 with chain1. This makes the second load
8981 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008982 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008983 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008984 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008985 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008986 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008987 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008988 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008989
Chandler Carruth18066972014-08-02 10:02:07 +00008990 if (N->use_empty())
8991 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008992
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008993 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008994 }
Evan Chengb68343c2007-05-01 08:53:39 +00008995 } else {
8996 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008997 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008998
Hal Finkele19006e2014-09-02 16:05:23 +00008999 // If this load has an opaque TargetConstant offset, then we cannot split
9000 // the indexing into an add/sub directly (that TargetConstant may not be
9001 // valid for a different type of node, and we cannot convert an opaque
9002 // target constant into a regular constant).
9003 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9004 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00009005
9006 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009007 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009008 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009009 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009010 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009011 Index = SplitIndexingFromLoad(LD);
9012 // Try to fold the base pointer arithmetic into subsequent loads and
9013 // stores.
9014 AddUsersToWorklist(N);
9015 } else
9016 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009017 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009018 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009019 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009020 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009021 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009022 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009023 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009024 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009025 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009026 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009028 }
Evan Chenga684cd22007-05-01 00:38:21 +00009029 }
9030 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009031
Chris Lattnere260ed82005-10-10 22:04:48 +00009032 // If this load is directly stored, replace the load value with the stored
9033 // value.
9034 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009035 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009036 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009037 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009038 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9039 if (PrevST->getBasePtr() == Ptr &&
9040 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009041 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009042 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009043 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009044
Evan Cheng43cd9e32010-04-01 06:04:33 +00009045 // Try to infer better alignment information than the load already has.
9046 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009047 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009048 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9049 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009050 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009051 LD->getValueType(0),
9052 Chain, Ptr, LD->getPointerInfo(),
9053 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009054 LD->isVolatile(), LD->isNonTemporal(),
9055 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +00009056 if (NewLoad.getNode() != N)
9057 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
Owen Andersonde89ecf2013-02-05 19:24:39 +00009058 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009059 }
9060 }
9061
Eric Christopherf55d4712014-10-08 23:38:39 +00009062 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9063 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009064#ifndef NDEBUG
9065 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9066 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9067 UseAA = false;
9068#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009069 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009070 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009071 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009072
Jim Laskey708d0db2006-10-04 16:53:27 +00009073 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009074 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009075 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009076
Jim Laskeyd07be232006-09-25 16:29:54 +00009077 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009078 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009079 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009080 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009081 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009082 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009083 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009084 BetterChain, Ptr, LD->getMemoryVT(),
9085 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009086 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009087
Jim Laskey708d0db2006-10-04 16:53:27 +00009088 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009089 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009090 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009091
Nate Begeman879d8f12009-09-15 00:18:30 +00009092 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009093 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009094
Jim Laskeydcf983c2006-10-13 23:32:28 +00009095 // Replace uses with load result and token factor. Don't add users
9096 // to work list.
9097 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009098 }
9099 }
9100
Evan Cheng357017f2006-11-03 03:06:21 +00009101 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009102 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009103 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009104
Quentin Colombetde0e0622013-10-11 18:29:42 +00009105 // Try to slice up N to more direct loads if the slices are mapped to
9106 // different register banks or pairing can take place.
9107 if (SliceUpLoad(N))
9108 return SDValue(N, 0);
9109
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009110 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009111}
9112
Quentin Colombetde0e0622013-10-11 18:29:42 +00009113namespace {
9114/// \brief Helper structure used to slice a load in smaller loads.
9115/// Basically a slice is obtained from the following sequence:
9116/// Origin = load Ty1, Base
9117/// Shift = srl Ty1 Origin, CstTy Amount
9118/// Inst = trunc Shift to Ty2
9119///
9120/// Then, it will be rewriten into:
9121/// Slice = load SliceTy, Base + SliceOffset
9122/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9123///
9124/// SliceTy is deduced from the number of bits that are actually used to
9125/// build Inst.
9126struct LoadedSlice {
9127 /// \brief Helper structure used to compute the cost of a slice.
9128 struct Cost {
9129 /// Are we optimizing for code size.
9130 bool ForCodeSize;
9131 /// Various cost.
9132 unsigned Loads;
9133 unsigned Truncates;
9134 unsigned CrossRegisterBanksCopies;
9135 unsigned ZExts;
9136 unsigned Shift;
9137
9138 Cost(bool ForCodeSize = false)
9139 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9140 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9141
9142 /// \brief Get the cost of one isolated slice.
9143 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9144 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9145 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9146 EVT TruncType = LS.Inst->getValueType(0);
9147 EVT LoadedType = LS.getLoadedType();
9148 if (TruncType != LoadedType &&
9149 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9150 ZExts = 1;
9151 }
9152
9153 /// \brief Account for slicing gain in the current cost.
9154 /// Slicing provide a few gains like removing a shift or a
9155 /// truncate. This method allows to grow the cost of the original
9156 /// load with the gain from this slice.
9157 void addSliceGain(const LoadedSlice &LS) {
9158 // Each slice saves a truncate.
9159 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9160 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9161 LS.Inst->getOperand(0).getValueType()))
9162 ++Truncates;
9163 // If there is a shift amount, this slice gets rid of it.
9164 if (LS.Shift)
9165 ++Shift;
9166 // If this slice can merge a cross register bank copy, account for it.
9167 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9168 ++CrossRegisterBanksCopies;
9169 }
9170
9171 Cost &operator+=(const Cost &RHS) {
9172 Loads += RHS.Loads;
9173 Truncates += RHS.Truncates;
9174 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9175 ZExts += RHS.ZExts;
9176 Shift += RHS.Shift;
9177 return *this;
9178 }
9179
9180 bool operator==(const Cost &RHS) const {
9181 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9182 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9183 ZExts == RHS.ZExts && Shift == RHS.Shift;
9184 }
9185
9186 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9187
9188 bool operator<(const Cost &RHS) const {
9189 // Assume cross register banks copies are as expensive as loads.
9190 // FIXME: Do we want some more target hooks?
9191 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9192 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9193 // Unless we are optimizing for code size, consider the
9194 // expensive operation first.
9195 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9196 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9197 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9198 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9199 }
9200
9201 bool operator>(const Cost &RHS) const { return RHS < *this; }
9202
9203 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9204
9205 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9206 };
9207 // The last instruction that represent the slice. This should be a
9208 // truncate instruction.
9209 SDNode *Inst;
9210 // The original load instruction.
9211 LoadSDNode *Origin;
9212 // The right shift amount in bits from the original load.
9213 unsigned Shift;
9214 // The DAG from which Origin came from.
9215 // This is used to get some contextual information about legal types, etc.
9216 SelectionDAG *DAG;
9217
Craig Topperc0196b12014-04-14 00:51:57 +00009218 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9219 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009220 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9221
Quentin Colombetde0e0622013-10-11 18:29:42 +00009222 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9223 /// \return Result is \p BitWidth and has used bits set to 1 and
9224 /// not used bits set to 0.
9225 APInt getUsedBits() const {
9226 // Reproduce the trunc(lshr) sequence:
9227 // - Start from the truncated value.
9228 // - Zero extend to the desired bit width.
9229 // - Shift left.
9230 assert(Origin && "No original load to compare against.");
9231 unsigned BitWidth = Origin->getValueSizeInBits(0);
9232 assert(Inst && "This slice is not bound to an instruction");
9233 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9234 "Extracted slice is bigger than the whole type!");
9235 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9236 UsedBits.setAllBits();
9237 UsedBits = UsedBits.zext(BitWidth);
9238 UsedBits <<= Shift;
9239 return UsedBits;
9240 }
9241
9242 /// \brief Get the size of the slice to be loaded in bytes.
9243 unsigned getLoadedSize() const {
9244 unsigned SliceSize = getUsedBits().countPopulation();
9245 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9246 return SliceSize / 8;
9247 }
9248
9249 /// \brief Get the type that will be loaded for this slice.
9250 /// Note: This may not be the final type for the slice.
9251 EVT getLoadedType() const {
9252 assert(DAG && "Missing context");
9253 LLVMContext &Ctxt = *DAG->getContext();
9254 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9255 }
9256
9257 /// \brief Get the alignment of the load used for this slice.
9258 unsigned getAlignment() const {
9259 unsigned Alignment = Origin->getAlignment();
9260 unsigned Offset = getOffsetFromBase();
9261 if (Offset != 0)
9262 Alignment = MinAlign(Alignment, Alignment + Offset);
9263 return Alignment;
9264 }
9265
9266 /// \brief Check if this slice can be rewritten with legal operations.
9267 bool isLegal() const {
9268 // An invalid slice is not legal.
9269 if (!Origin || !Inst || !DAG)
9270 return false;
9271
9272 // Offsets are for indexed load only, we do not handle that.
9273 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9274 return false;
9275
9276 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9277
9278 // Check that the type is legal.
9279 EVT SliceType = getLoadedType();
9280 if (!TLI.isTypeLegal(SliceType))
9281 return false;
9282
9283 // Check that the load is legal for this type.
9284 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9285 return false;
9286
9287 // Check that the offset can be computed.
9288 // 1. Check its type.
9289 EVT PtrType = Origin->getBasePtr().getValueType();
9290 if (PtrType == MVT::Untyped || PtrType.isExtended())
9291 return false;
9292
9293 // 2. Check that it fits in the immediate.
9294 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9295 return false;
9296
9297 // 3. Check that the computation is legal.
9298 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9299 return false;
9300
9301 // Check that the zext is legal if it needs one.
9302 EVT TruncateType = Inst->getValueType(0);
9303 if (TruncateType != SliceType &&
9304 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9305 return false;
9306
9307 return true;
9308 }
9309
9310 /// \brief Get the offset in bytes of this slice in the original chunk of
9311 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009312 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009313 uint64_t getOffsetFromBase() const {
9314 assert(DAG && "Missing context.");
9315 bool IsBigEndian =
9316 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9317 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9318 uint64_t Offset = Shift / 8;
9319 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9320 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9321 "The size of the original loaded type is not a multiple of a"
9322 " byte.");
9323 // If Offset is bigger than TySizeInBytes, it means we are loading all
9324 // zeros. This should have been optimized before in the process.
9325 assert(TySizeInBytes > Offset &&
9326 "Invalid shift amount for given loaded size");
9327 if (IsBigEndian)
9328 Offset = TySizeInBytes - Offset - getLoadedSize();
9329 return Offset;
9330 }
9331
9332 /// \brief Generate the sequence of instructions to load the slice
9333 /// represented by this object and redirect the uses of this slice to
9334 /// this new sequence of instructions.
9335 /// \pre this->Inst && this->Origin are valid Instructions and this
9336 /// object passed the legal check: LoadedSlice::isLegal returned true.
9337 /// \return The last instruction of the sequence used to load the slice.
9338 SDValue loadSlice() const {
9339 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9340 const SDValue &OldBaseAddr = Origin->getBasePtr();
9341 SDValue BaseAddr = OldBaseAddr;
9342 // Get the offset in that chunk of bytes w.r.t. the endianess.
9343 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9344 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9345 if (Offset) {
9346 // BaseAddr = BaseAddr + Offset.
9347 EVT ArithType = BaseAddr.getValueType();
9348 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9349 DAG->getConstant(Offset, ArithType));
9350 }
9351
9352 // Create the type of the loaded slice according to its size.
9353 EVT SliceType = getLoadedType();
9354
9355 // Create the load for the slice.
9356 SDValue LastInst = DAG->getLoad(
9357 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9358 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9359 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9360 // If the final type is not the same as the loaded type, this means that
9361 // we have to pad with zero. Create a zero extend for that.
9362 EVT FinalType = Inst->getValueType(0);
9363 if (SliceType != FinalType)
9364 LastInst =
9365 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9366 return LastInst;
9367 }
9368
9369 /// \brief Check if this slice can be merged with an expensive cross register
9370 /// bank copy. E.g.,
9371 /// i = load i32
9372 /// f = bitcast i32 i to float
9373 bool canMergeExpensiveCrossRegisterBankCopy() const {
9374 if (!Inst || !Inst->hasOneUse())
9375 return false;
9376 SDNode *Use = *Inst->use_begin();
9377 if (Use->getOpcode() != ISD::BITCAST)
9378 return false;
9379 assert(DAG && "Missing context");
9380 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9381 EVT ResVT = Use->getValueType(0);
9382 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9383 const TargetRegisterClass *ArgRC =
9384 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9385 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9386 return false;
9387
9388 // At this point, we know that we perform a cross-register-bank copy.
9389 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009390 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009391 // Assume bitcasts are cheap, unless both register classes do not
9392 // explicitly share a common sub class.
9393 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9394 return false;
9395
9396 // Check if it will be merged with the load.
9397 // 1. Check the alignment constraint.
9398 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9399 ResVT.getTypeForEVT(*DAG->getContext()));
9400
9401 if (RequiredAlignment > getAlignment())
9402 return false;
9403
9404 // 2. Check that the load is a legal operation for that type.
9405 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9406 return false;
9407
9408 // 3. Check that we do not have a zext in the way.
9409 if (Inst->getValueType(0) != getLoadedType())
9410 return false;
9411
9412 return true;
9413 }
9414};
9415}
9416
Quentin Colombetde0e0622013-10-11 18:29:42 +00009417/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9418/// \p UsedBits looks like 0..0 1..1 0..0.
9419static bool areUsedBitsDense(const APInt &UsedBits) {
9420 // If all the bits are one, this is dense!
9421 if (UsedBits.isAllOnesValue())
9422 return true;
9423
9424 // Get rid of the unused bits on the right.
9425 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9426 // Get rid of the unused bits on the left.
9427 if (NarrowedUsedBits.countLeadingZeros())
9428 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9429 // Check that the chunk of bits is completely used.
9430 return NarrowedUsedBits.isAllOnesValue();
9431}
9432
9433/// \brief Check whether or not \p First and \p Second are next to each other
9434/// in memory. This means that there is no hole between the bits loaded
9435/// by \p First and the bits loaded by \p Second.
9436static bool areSlicesNextToEachOther(const LoadedSlice &First,
9437 const LoadedSlice &Second) {
9438 assert(First.Origin == Second.Origin && First.Origin &&
9439 "Unable to match different memory origins.");
9440 APInt UsedBits = First.getUsedBits();
9441 assert((UsedBits & Second.getUsedBits()) == 0 &&
9442 "Slices are not supposed to overlap.");
9443 UsedBits |= Second.getUsedBits();
9444 return areUsedBitsDense(UsedBits);
9445}
9446
9447/// \brief Adjust the \p GlobalLSCost according to the target
9448/// paring capabilities and the layout of the slices.
9449/// \pre \p GlobalLSCost should account for at least as many loads as
9450/// there is in the slices in \p LoadedSlices.
9451static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9452 LoadedSlice::Cost &GlobalLSCost) {
9453 unsigned NumberOfSlices = LoadedSlices.size();
9454 // If there is less than 2 elements, no pairing is possible.
9455 if (NumberOfSlices < 2)
9456 return;
9457
9458 // Sort the slices so that elements that are likely to be next to each
9459 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009460 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9461 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9462 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9463 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9464 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009465 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9466 // First (resp. Second) is the first (resp. Second) potentially candidate
9467 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009468 const LoadedSlice *First = nullptr;
9469 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009470 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9471 // Set the beginning of the pair.
9472 First = Second) {
9473
9474 Second = &LoadedSlices[CurrSlice];
9475
9476 // If First is NULL, it means we start a new pair.
9477 // Get to the next slice.
9478 if (!First)
9479 continue;
9480
9481 EVT LoadedType = First->getLoadedType();
9482
9483 // If the types of the slices are different, we cannot pair them.
9484 if (LoadedType != Second->getLoadedType())
9485 continue;
9486
9487 // Check if the target supplies paired loads for this type.
9488 unsigned RequiredAlignment = 0;
9489 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9490 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009491 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009492 continue;
9493 }
9494 // Check if we meet the alignment requirement.
9495 if (RequiredAlignment > First->getAlignment())
9496 continue;
9497
9498 // Check that both loads are next to each other in memory.
9499 if (!areSlicesNextToEachOther(*First, *Second))
9500 continue;
9501
9502 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9503 --GlobalLSCost.Loads;
9504 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009505 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009506 }
9507}
9508
9509/// \brief Check the profitability of all involved LoadedSlice.
9510/// Currently, it is considered profitable if there is exactly two
9511/// involved slices (1) which are (2) next to each other in memory, and
9512/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9513///
9514/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9515/// the elements themselves.
9516///
9517/// FIXME: When the cost model will be mature enough, we can relax
9518/// constraints (1) and (2).
9519static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9520 const APInt &UsedBits, bool ForCodeSize) {
9521 unsigned NumberOfSlices = LoadedSlices.size();
9522 if (StressLoadSlicing)
9523 return NumberOfSlices > 1;
9524
9525 // Check (1).
9526 if (NumberOfSlices != 2)
9527 return false;
9528
9529 // Check (2).
9530 if (!areUsedBitsDense(UsedBits))
9531 return false;
9532
9533 // Check (3).
9534 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9535 // The original code has one big load.
9536 OrigCost.Loads = 1;
9537 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9538 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9539 // Accumulate the cost of all the slices.
9540 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9541 GlobalSlicingCost += SliceCost;
9542
9543 // Account as cost in the original configuration the gain obtained
9544 // with the current slices.
9545 OrigCost.addSliceGain(LS);
9546 }
9547
9548 // If the target supports paired load, adjust the cost accordingly.
9549 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9550 return OrigCost > GlobalSlicingCost;
9551}
9552
9553/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9554/// operations, split it in the various pieces being extracted.
9555///
9556/// This sort of thing is introduced by SROA.
9557/// This slicing takes care not to insert overlapping loads.
9558/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9559bool DAGCombiner::SliceUpLoad(SDNode *N) {
9560 if (Level < AfterLegalizeDAG)
9561 return false;
9562
9563 LoadSDNode *LD = cast<LoadSDNode>(N);
9564 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9565 !LD->getValueType(0).isInteger())
9566 return false;
9567
9568 // Keep track of already used bits to detect overlapping values.
9569 // In that case, we will just abort the transformation.
9570 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9571
9572 SmallVector<LoadedSlice, 4> LoadedSlices;
9573
9574 // Check if this load is used as several smaller chunks of bits.
9575 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9576 // of computation for each trunc.
9577 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9578 UI != UIEnd; ++UI) {
9579 // Skip the uses of the chain.
9580 if (UI.getUse().getResNo() != 0)
9581 continue;
9582
9583 SDNode *User = *UI;
9584 unsigned Shift = 0;
9585
9586 // Check if this is a trunc(lshr).
9587 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9588 isa<ConstantSDNode>(User->getOperand(1))) {
9589 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9590 User = *User->use_begin();
9591 }
9592
9593 // At this point, User is a Truncate, iff we encountered, trunc or
9594 // trunc(lshr).
9595 if (User->getOpcode() != ISD::TRUNCATE)
9596 return false;
9597
9598 // The width of the type must be a power of 2 and greater than 8-bits.
9599 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009600 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009601 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009602 unsigned Width = User->getValueSizeInBits(0);
9603 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9604 return 0;
9605
9606 // Build the slice for this chain of computations.
9607 LoadedSlice LS(User, LD, Shift, &DAG);
9608 APInt CurrentUsedBits = LS.getUsedBits();
9609
9610 // Check if this slice overlaps with another.
9611 if ((CurrentUsedBits & UsedBits) != 0)
9612 return false;
9613 // Update the bits used globally.
9614 UsedBits |= CurrentUsedBits;
9615
9616 // Check if the new slice would be legal.
9617 if (!LS.isLegal())
9618 return false;
9619
9620 // Record the slice.
9621 LoadedSlices.push_back(LS);
9622 }
9623
9624 // Abort slicing if it does not seem to be profitable.
9625 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9626 return false;
9627
9628 ++SlicedLoads;
9629
9630 // Rewrite each chain to use an independent load.
9631 // By construction, each chain can be represented by a unique load.
9632
9633 // Prepare the argument for the new token factor for all the slices.
9634 SmallVector<SDValue, 8> ArgChains;
9635 for (SmallVectorImpl<LoadedSlice>::const_iterator
9636 LSIt = LoadedSlices.begin(),
9637 LSItEnd = LoadedSlices.end();
9638 LSIt != LSItEnd; ++LSIt) {
9639 SDValue SliceInst = LSIt->loadSlice();
9640 CombineTo(LSIt->Inst, SliceInst, true);
9641 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9642 SliceInst = SliceInst.getOperand(0);
9643 assert(SliceInst->getOpcode() == ISD::LOAD &&
9644 "It takes more than a zext to get to the loaded slice!!");
9645 ArgChains.push_back(SliceInst.getValue(1));
9646 }
9647
9648 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009649 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9651 return true;
9652}
9653
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009654/// Check to see if V is (and load (ptr), imm), where the load is having
9655/// specific bytes cleared out. If so, return the byte size being masked out
9656/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009657static std::pair<unsigned, unsigned>
9658CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9659 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009660
Chris Lattner4041ab62010-04-15 04:48:01 +00009661 // Check for the structure we're looking for.
9662 if (V->getOpcode() != ISD::AND ||
9663 !isa<ConstantSDNode>(V->getOperand(1)) ||
9664 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9665 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009666
Chris Lattner3245afd2010-04-15 06:10:49 +00009667 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009668 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009669 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009670
Chris Lattner3245afd2010-04-15 06:10:49 +00009671 // The store should be chained directly to the load or be an operand of a
9672 // tokenfactor.
9673 if (LD == Chain.getNode())
9674 ; // ok.
9675 else if (Chain->getOpcode() != ISD::TokenFactor)
9676 return Result; // Fail.
9677 else {
9678 bool isOk = false;
9679 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9680 if (Chain->getOperand(i).getNode() == LD) {
9681 isOk = true;
9682 break;
9683 }
9684 if (!isOk) return Result;
9685 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009686
Chris Lattner4041ab62010-04-15 04:48:01 +00009687 // This only handles simple types.
9688 if (V.getValueType() != MVT::i16 &&
9689 V.getValueType() != MVT::i32 &&
9690 V.getValueType() != MVT::i64)
9691 return Result;
9692
9693 // Check the constant mask. Invert it so that the bits being masked out are
9694 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9695 // follow the sign bit for uniformity.
9696 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009697 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009698 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009699 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009700 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9701 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009702
Chris Lattner4041ab62010-04-15 04:48:01 +00009703 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00009704 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +00009705 return Result;
9706
9707 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9708 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9709 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009710
Chris Lattner4041ab62010-04-15 04:48:01 +00009711 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9712 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009713 case 1:
9714 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009715 case 4: break;
9716 default: return Result; // All one mask, or 5-byte mask.
9717 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009718
Chris Lattner4041ab62010-04-15 04:48:01 +00009719 // Verify that the first bit starts at a multiple of mask so that the access
9720 // is aligned the same as the access width.
9721 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009722
Chris Lattner4041ab62010-04-15 04:48:01 +00009723 Result.first = MaskedBytes;
9724 Result.second = NotMaskTZ/8;
9725 return Result;
9726}
9727
9728
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009729/// Check to see if IVal is something that provides a value as specified by
9730/// MaskInfo. If so, replace the specified store with a narrower store of
9731/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009732static SDNode *
9733ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9734 SDValue IVal, StoreSDNode *St,
9735 DAGCombiner *DC) {
9736 unsigned NumBytes = MaskInfo.first;
9737 unsigned ByteShift = MaskInfo.second;
9738 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009739
Chris Lattner4041ab62010-04-15 04:48:01 +00009740 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9741 // that uses this. If not, this is not a replacement.
9742 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9743 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009744 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009745
Chris Lattner4041ab62010-04-15 04:48:01 +00009746 // Check that it is legal on the target to do this. It is legal if the new
9747 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9748 // legalization.
9749 MVT VT = MVT::getIntegerVT(NumBytes*8);
9750 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009751 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009752
Chris Lattner4041ab62010-04-15 04:48:01 +00009753 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9754 // shifted by ByteShift and truncated down to NumBytes.
9755 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009756 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009757 DAG.getConstant(ByteShift*8,
9758 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009759
9760 // Figure out the offset for the store and the alignment of the access.
9761 unsigned StOffset;
9762 unsigned NewAlign = St->getAlignment();
9763
9764 if (DAG.getTargetLoweringInfo().isLittleEndian())
9765 StOffset = ByteShift;
9766 else
9767 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009768
Chris Lattner4041ab62010-04-15 04:48:01 +00009769 SDValue Ptr = St->getBasePtr();
9770 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009771 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009772 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9773 NewAlign = MinAlign(NewAlign, StOffset);
9774 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009775
Chris Lattner4041ab62010-04-15 04:48:01 +00009776 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009777 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009778
Chris Lattner4041ab62010-04-15 04:48:01 +00009779 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009780 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009781 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009782 false, false, NewAlign).getNode();
9783}
9784
Evan Chenga9cda8a2009-05-28 00:35:15 +00009785
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009786/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9787/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9788/// narrowing the load and store if it would end up being a win for performance
9789/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009790SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9791 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009792 if (ST->isVolatile())
9793 return SDValue();
9794
Evan Chenga9cda8a2009-05-28 00:35:15 +00009795 SDValue Chain = ST->getChain();
9796 SDValue Value = ST->getValue();
9797 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009798 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009799
9800 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00009801 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009802
9803 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00009804
Chris Lattner4041ab62010-04-15 04:48:01 +00009805 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9806 // is a byte mask indicating a consecutive number of bytes, check to see if
9807 // Y is known to provide just those bytes. If so, we try to replace the
9808 // load + replace + store sequence with a single (narrower) store, which makes
9809 // the load dead.
9810 if (Opc == ISD::OR) {
9811 std::pair<unsigned, unsigned> MaskedLoad;
9812 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9813 if (MaskedLoad.first)
9814 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9815 Value.getOperand(1), ST,this))
9816 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009817
Chris Lattner4041ab62010-04-15 04:48:01 +00009818 // Or is commutative, so try swapping X and Y.
9819 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9820 if (MaskedLoad.first)
9821 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9822 Value.getOperand(0), ST,this))
9823 return SDValue(NewST, 0);
9824 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009825
Evan Chenga9cda8a2009-05-28 00:35:15 +00009826 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9827 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00009828 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009829
9830 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00009831 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9832 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009833 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009834 if (LD->getBasePtr() != Ptr ||
9835 LD->getPointerInfo().getAddrSpace() !=
9836 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00009837 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009838
9839 // Find the type to narrow it the load / op / store to.
9840 SDValue N1 = Value.getOperand(1);
9841 unsigned BitWidth = N1.getValueSizeInBits();
9842 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9843 if (Opc == ISD::AND)
9844 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00009845 if (Imm == 0 || Imm.isAllOnesValue())
9846 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009847 unsigned ShAmt = Imm.countTrailingZeros();
9848 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9849 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00009850 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00009851 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009852 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009853 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009854 (NewVT.getStoreSizeInBits() != NewBW ||
9855 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9856 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009857 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00009858 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009859 }
Evan Cheng6673ff02009-05-28 18:41:02 +00009860 if (NewBW >= BitWidth)
9861 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009862
9863 // If the lsb changed does not start at the type bitwidth boundary,
9864 // start at the previous one.
9865 if (ShAmt % NewBW)
9866 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009867 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9868 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009869 if ((Imm & Mask) == Imm) {
9870 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9871 if (Opc == ISD::AND)
9872 NewImm ^= APInt::getAllOnesValue(NewBW);
9873 uint64_t PtrOff = ShAmt / 8;
9874 // For big endian targets, we need to adjust the offset to the pointer to
9875 // load the correct bytes.
9876 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009877 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009878
9879 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009880 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009881 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009882 return SDValue();
9883
Andrew Trickef9de2a2013-05-25 02:42:55 +00009884 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009885 Ptr.getValueType(), Ptr,
9886 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009887 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009888 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009889 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009890 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009891 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009892 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009893 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009894 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009895 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009896 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009897 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009898 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009899
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009900 AddToWorklist(NewPtr.getNode());
9901 AddToWorklist(NewLD.getNode());
9902 AddToWorklist(NewVal.getNode());
9903 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009904 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009905 ++OpsNarrowed;
9906 return NewST;
9907 }
9908 }
9909
Evan Cheng6673ff02009-05-28 18:41:02 +00009910 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009911}
9912
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009913/// For a given floating point load / store pair, if the load value isn't used
9914/// by any other operations, then consider transforming the pair to integer
9915/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009916SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9917 StoreSDNode *ST = cast<StoreSDNode>(N);
9918 SDValue Chain = ST->getChain();
9919 SDValue Value = ST->getValue();
9920 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9921 Value.hasOneUse() &&
9922 Chain == SDValue(Value.getNode(), 1)) {
9923 LoadSDNode *LD = cast<LoadSDNode>(Value);
9924 EVT VT = LD->getMemoryVT();
9925 if (!VT.isFloatingPoint() ||
9926 VT != ST->getMemoryVT() ||
9927 LD->isNonTemporal() ||
9928 ST->isNonTemporal() ||
9929 LD->getPointerInfo().getAddrSpace() != 0 ||
9930 ST->getPointerInfo().getAddrSpace() != 0)
9931 return SDValue();
9932
9933 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9934 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9935 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9936 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9937 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9938 return SDValue();
9939
9940 unsigned LDAlign = LD->getAlignment();
9941 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009942 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009943 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009944 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9945 return SDValue();
9946
Andrew Trickef9de2a2013-05-25 02:42:55 +00009947 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009948 LD->getChain(), LD->getBasePtr(),
9949 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009950 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009951
Andrew Trickef9de2a2013-05-25 02:42:55 +00009952 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009953 NewLD, ST->getBasePtr(),
9954 ST->getPointerInfo(),
9955 false, false, STAlign);
9956
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009957 AddToWorklist(NewLD.getNode());
9958 AddToWorklist(NewST.getNode());
9959 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009960 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009961 ++LdStFP2Int;
9962 return NewST;
9963 }
9964
9965 return SDValue();
9966}
9967
Benjamin Kramer51f6096c2015-03-23 12:30:58 +00009968namespace {
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009969/// Helper struct to parse and store a memory address as base + index + offset.
9970/// We ignore sign extensions when it is safe to do so.
9971/// The following two expressions are not equivalent. To differentiate we need
9972/// to store whether there was a sign extension involved in the index
9973/// computation.
9974/// (load (i64 add (i64 copyfromreg %c)
9975/// (i64 signextend (add (i8 load %index)
9976/// (i8 1))))
9977/// vs
9978///
9979/// (load (i64 add (i64 copyfromreg %c)
9980/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9981/// (i32 1)))))
9982struct BaseIndexOffset {
9983 SDValue Base;
9984 SDValue Index;
9985 int64_t Offset;
9986 bool IsIndexSignExt;
9987
9988 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9989
9990 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9991 bool IsIndexSignExt) :
9992 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9993
9994 bool equalBaseIndex(const BaseIndexOffset &Other) {
9995 return Other.Base == Base && Other.Index == Index &&
9996 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009997 }
9998
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009999 /// Parses tree in Ptr for base, index, offset addresses.
10000 static BaseIndexOffset match(SDValue Ptr) {
10001 bool IsIndexSignExt = false;
10002
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010003 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10004 // instruction, then it could be just the BASE or everything else we don't
10005 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010006 if (Ptr->getOpcode() != ISD::ADD)
10007 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10008
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010009 // We know that we have at least an ADD instruction. Try to pattern match
10010 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010011 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10012 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10013 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10014 IsIndexSignExt);
10015 }
10016
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010017 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010018 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010019 // (i64 add (i64 %array_ptr)
10020 // (i64 mul (i64 %induction_var)
10021 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010022 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010023 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010024
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010025 // Look at Base + Index + Offset cases.
10026 SDValue Base = Ptr->getOperand(0);
10027 SDValue IndexOffset = Ptr->getOperand(1);
10028
10029 // Skip signextends.
10030 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10031 IndexOffset = IndexOffset->getOperand(0);
10032 IsIndexSignExt = true;
10033 }
10034
10035 // Either the case of Base + Index (no offset) or something else.
10036 if (IndexOffset->getOpcode() != ISD::ADD)
10037 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10038
10039 // Now we have the case of Base + Index + offset.
10040 SDValue Index = IndexOffset->getOperand(0);
10041 SDValue Offset = IndexOffset->getOperand(1);
10042
10043 if (!isa<ConstantSDNode>(Offset))
10044 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10045
10046 // Ignore signextends.
10047 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10048 Index = Index->getOperand(0);
10049 IsIndexSignExt = true;
10050 } else IsIndexSignExt = false;
10051
10052 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10053 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10054 }
10055};
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010056} // namespace
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010057
Sanjay Patel37c41c12015-01-22 18:21:26 +000010058bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10059 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010060 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010061 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010062 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010063 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010064
Sanjay Patel37c41c12015-01-22 18:21:26 +000010065 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10066 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10067 unsigned EarliestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010068
Quentin Colombet308b1712015-01-27 23:58:01 +000010069 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010070 // Find a chain for the new wide-store operand. Notice that some
10071 // of the store nodes that we found may not be selected for inclusion
10072 // in the wide store. The chain we use needs to be the chain of the
10073 // earliest store node which is *used* and replaced by the wide store.
10074 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10075 EarliestNodeUsed = i;
10076 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010077
Sanjay Patel37c41c12015-01-22 18:21:26 +000010078 // The earliest Node in the DAG.
10079 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10080 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010081
Sanjay Patel37c41c12015-01-22 18:21:26 +000010082 SDValue StoredVal;
10083 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010084 // Find a legal type for the vector store.
10085 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010086 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10087 if (IsConstantSrc) {
10088 // A vector store with a constant source implies that the constant is
10089 // zero; we only handle merging stores of constant zeros because the zero
10090 // can be materialized without a load.
10091 // It may be beneficial to loosen this restriction to allow non-zero
10092 // store merging.
10093 StoredVal = DAG.getConstant(0, Ty);
10094 } else {
10095 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010096 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010097 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10098 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010099 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010100 if (Val.getValueType() != MemVT)
10101 return false;
10102 Ops.push_back(Val);
10103 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010104
Sanjay Patel37c41c12015-01-22 18:21:26 +000010105 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010106 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010107 }
10108 } else {
10109 // We should always use a vector store when merging extracted vector
10110 // elements, so this path implies a store of constants.
10111 assert(IsConstantSrc && "Merged vector elements should use vector store");
10112
Quentin Colombet308b1712015-01-27 23:58:01 +000010113 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010114 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010115
Sanjay Patel37c41c12015-01-22 18:21:26 +000010116 // Construct a single integer constant which is made of the smaller
10117 // constant inputs.
10118 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010119 for (unsigned i = 0; i < NumElem ; ++i) {
10120 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010121 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10122 SDValue Val = St->getValue();
10123 StoreInt <<= ElementSizeBytes*8;
10124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10125 StoreInt |= C->getAPIntValue().zext(StoreBW);
10126 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10127 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10128 } else {
10129 llvm_unreachable("Invalid constant element type");
10130 }
10131 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010132
Sanjay Patel37c41c12015-01-22 18:21:26 +000010133 // Create the new Load and Store operations.
10134 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10135 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10136 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010137
Sanjay Patel37c41c12015-01-22 18:21:26 +000010138 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10139 FirstInChain->getBasePtr(),
10140 FirstInChain->getPointerInfo(),
10141 false, false,
10142 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010143
Sanjay Patel37c41c12015-01-22 18:21:26 +000010144 // Replace the first store with the new store
10145 CombineTo(EarliestOp, NewStore);
10146 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010147 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010148 if (StoreNodes[i].MemNode == EarliestOp)
10149 continue;
10150 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10151 // ReplaceAllUsesWith will replace all uses that existed when it was
10152 // called, but graph optimizations may cause new ones to appear. For
10153 // example, the case in pr14333 looks like
10154 //
10155 // St's chain -> St -> another store -> X
10156 //
10157 // And the only difference from St to the other store is the chain.
10158 // When we change it's chain to be St's chain they become identical,
10159 // get CSEed and the net result is that X is now a use of St.
10160 // Since we know that St is redundant, just iterate.
10161 while (!St->use_empty())
10162 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10163 deleteAndRecombine(St);
10164 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010165
Sanjay Patel37c41c12015-01-22 18:21:26 +000010166 return true;
10167}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010168
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010169bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010170 if (OptLevel == CodeGenOpt::None)
10171 return false;
10172
Quentin Colombet308b1712015-01-27 23:58:01 +000010173 EVT MemVT = St->getMemoryVT();
10174 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010175 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10176 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010177
Quentin Colombet308b1712015-01-27 23:58:01 +000010178 // Don't merge vectors into wider inputs.
10179 if (MemVT.isVector() || !MemVT.isSimple())
10180 return false;
10181
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010182 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010183 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010184 SDValue StoredVal = St->getValue();
10185 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010186 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10187 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010188 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010189
Quentin Colombet308b1712015-01-27 23:58:01 +000010190 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010191 return false;
10192
10193 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010194 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010195 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10196 return false;
10197
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010198 // This holds the base pointer, index, and the offset in bytes from the base
10199 // pointer.
10200 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010201
10202 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010203 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010204 return false;
10205
10206 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010207 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010208 return false;
10209
Nadav Rotem307d7672012-11-29 00:00:08 +000010210 // Save the LoadSDNodes that we find in the chain.
10211 // We need to make sure that these nodes do not interfere with
10212 // any of the store nodes.
10213 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10214
10215 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010216 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010217
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010218 // Walk up the chain and look for nodes with offsets from the same
10219 // base pointer. Stop when reaching an instruction with a different kind
10220 // or instruction which has a different base pointer.
10221 unsigned Seq = 0;
10222 StoreSDNode *Index = St;
10223 while (Index) {
10224 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010225 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010226 break;
10227
10228 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010229 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010230
10231 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010232 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010233 break;
10234
10235 // Check that the alignment is the same.
10236 if (Index->getAlignment() != St->getAlignment())
10237 break;
10238
10239 // The memory operands must not be volatile.
10240 if (Index->isVolatile() || Index->isIndexed())
10241 break;
10242
10243 // No truncation.
10244 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10245 if (St->isTruncatingStore())
10246 break;
10247
10248 // The stored memory type must be the same.
10249 if (Index->getMemoryVT() != MemVT)
10250 break;
10251
10252 // We do not allow unaligned stores because we want to prevent overriding
10253 // stores.
10254 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10255 break;
10256
10257 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010258 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010259
Nadav Rotem307d7672012-11-29 00:00:08 +000010260 // Find the next memory operand in the chain. If the next operand in the
10261 // chain is a store then move up and continue the scan with the next
10262 // memory operand. If the next operand is a load save it and use alias
10263 // information to check if it interferes with anything.
10264 SDNode *NextInChain = Index->getChain().getNode();
10265 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010266 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010267 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010268 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010269 break;
10270 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010271 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010272 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010273 break;
10274 }
10275
Nadav Rotem307d7672012-11-29 00:00:08 +000010276 // Save the load node for later. Continue the scan.
10277 AliasLoadNodes.push_back(Ldn);
10278 NextInChain = Ldn->getChain().getNode();
10279 continue;
10280 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010281 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010282 break;
10283 }
10284 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010285 }
10286
10287 // Check if there is anything to merge.
10288 if (StoreNodes.size() < 2)
10289 return false;
10290
10291 // Sort the memory operands according to their distance from the base pointer.
10292 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010293 [](MemOpLink LHS, MemOpLink RHS) {
10294 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10295 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10296 LHS.SequenceNum > RHS.SequenceNum);
10297 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010298
10299 // Scan the memory operations on the chain and find the first non-consecutive
10300 // store memory address.
10301 unsigned LastConsecutiveStore = 0;
10302 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010303 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10304
10305 // Check that the addresses are consecutive starting from the second
10306 // element in the list of stores.
10307 if (i > 0) {
10308 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10309 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10310 break;
10311 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010312
Nadav Rotem307d7672012-11-29 00:00:08 +000010313 bool Alias = false;
10314 // Check if this store interferes with any of the loads that we found.
10315 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10316 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10317 Alias = true;
10318 break;
10319 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010320 // We found a load that alias with this store. Stop the sequence.
10321 if (Alias)
10322 break;
10323
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010324 // Mark this node as useful.
10325 LastConsecutiveStore = i;
10326 }
10327
10328 // The node with the lowest store address.
10329 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10330
10331 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010332 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010333 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010334 unsigned LastLegalVectorType = 0;
10335 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010336 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10337 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10338 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010339
10340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010341 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010342 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010343 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010344 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010345 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010346 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010347 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010348
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010349 // Find a legal type for the constant store.
10350 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10351 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10352 if (TLI.isTypeLegal(StoreTy))
10353 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010354 // Or check whether a truncstore is legal.
10355 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10356 TargetLowering::TypePromoteInteger) {
10357 EVT LegalizedStoredValueTy =
10358 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10359 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10360 LastLegalType = i+1;
10361 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010362
10363 // Find a legal type for the vector store.
10364 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10365 if (TLI.isTypeLegal(Ty))
10366 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010367 }
10368
Bob Wilson3365b802012-12-20 01:36:20 +000010369 // We only use vectors if the constant is known to be zero and the
10370 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010371 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010372 LastLegalVectorType = 0;
10373
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010374 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010375 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010376 return false;
10377
Nadav Rotem495b1a42013-02-14 18:28:52 +000010378 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010379 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10380
Sanjay Patel37c41c12015-01-22 18:21:26 +000010381 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10382 true, UseVector);
10383 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010384
Sanjay Patel37c41c12015-01-22 18:21:26 +000010385 // When extracting multiple vector elements, try to store them
10386 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010387 if (IsExtractVecEltSrc) {
10388 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010389 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10390 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010391 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010392 // This restriction could be loosened.
10393 // Bail out if any stored values are not elements extracted from a vector.
10394 // It should be possible to handle mixed sources, but load sources need
10395 // more careful handling (see the block of code below that handles
10396 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010397 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010398 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010399
Nadav Rotemb27777f2012-10-04 22:35:15 +000010400 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010401 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10402 if (TLI.isTypeLegal(Ty))
10403 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010404 }
10405
Quentin Colombet308b1712015-01-27 23:58:01 +000010406 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010407 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010408 }
10409
10410 // Below we handle the case of multiple consecutive stores that
10411 // come from multiple consecutive loads. We merge them into a single
10412 // wide load and a single wide store.
10413
10414 // Look for load nodes which are used by the stored values.
10415 SmallVector<MemOpLink, 8> LoadNodes;
10416
10417 // Find acceptable loads. Loads need to have the same chain (token factor),
10418 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010419 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010420 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10421 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10422 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10423 if (!Ld) break;
10424
10425 // Loads must only have one use.
10426 if (!Ld->hasNUsesOfValue(1, 0))
10427 break;
10428
10429 // Check that the alignment is the same as the stores.
10430 if (Ld->getAlignment() != St->getAlignment())
10431 break;
10432
10433 // The memory operands must not be volatile.
10434 if (Ld->isVolatile() || Ld->isIndexed())
10435 break;
10436
10437 // We do not accept ext loads.
10438 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10439 break;
10440
10441 // The stored memory type must be the same.
10442 if (Ld->getMemoryVT() != MemVT)
10443 break;
10444
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010445 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010446 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010447 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010448 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010449 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010450 break;
10451 } else {
10452 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010453 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010454 }
10455
10456 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010457 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010458 }
10459
10460 if (LoadNodes.size() < 2)
10461 return false;
10462
James Molloyce45be02014-08-02 14:51:24 +000010463 // If we have load/store pair instructions and we only have two values,
10464 // don't bother.
10465 unsigned RequiredAlignment;
10466 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10467 St->getAlignment() >= RequiredAlignment)
10468 return false;
10469
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010470 // Scan the memory operations on the chain and find the first non-consecutive
10471 // load memory address. These variables hold the index in the store node
10472 // array.
10473 unsigned LastConsecutiveLoad = 0;
10474 // This variable refers to the size and not index in the array.
10475 unsigned LastLegalVectorType = 0;
10476 unsigned LastLegalIntegerType = 0;
10477 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010478 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10479 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10480 // All loads much share the same chain.
10481 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10482 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010483
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010484 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10485 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10486 break;
10487 LastConsecutiveLoad = i;
10488
10489 // Find a legal type for the vector store.
10490 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10491 if (TLI.isTypeLegal(StoreTy))
10492 LastLegalVectorType = i + 1;
10493
10494 // Find a legal type for the integer store.
10495 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10496 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10497 if (TLI.isTypeLegal(StoreTy))
10498 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010499 // Or check whether a truncstore and extload is legal.
10500 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10501 TargetLowering::TypePromoteInteger) {
10502 EVT LegalizedStoredValueTy =
10503 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10504 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010505 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10506 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10507 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010508 LastLegalIntegerType = i+1;
10509 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010510 }
10511
10512 // Only use vector types if the vector type is larger than the integer type.
10513 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010514 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010515 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10516
10517 // We add +1 here because the LastXXX variables refer to location while
10518 // the NumElem refers to array/index size.
10519 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10520 NumElem = std::min(LastLegalType, NumElem);
10521
10522 if (NumElem < 2)
10523 return false;
10524
10525 // The earliest Node in the DAG.
10526 unsigned EarliestNodeUsed = 0;
10527 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10528 for (unsigned i=1; i<NumElem; ++i) {
10529 // Find a chain for the new wide-store operand. Notice that some
10530 // of the store nodes that we found may not be selected for inclusion
10531 // in the wide store. The chain we use needs to be the chain of the
10532 // earliest store node which is *used* and replaced by the wide store.
10533 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10534 EarliestNodeUsed = i;
10535 }
10536
10537 // Find if it is better to use vectors or integers to load and store
10538 // to memory.
10539 EVT JointMemOpVT;
10540 if (UseVectorTy) {
10541 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10542 } else {
10543 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10544 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10545 }
10546
Andrew Trickef9de2a2013-05-25 02:42:55 +000010547 SDLoc LoadDL(LoadNodes[0].MemNode);
10548 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010549
10550 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10551 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10552 FirstLoad->getChain(),
10553 FirstLoad->getBasePtr(),
10554 FirstLoad->getPointerInfo(),
10555 false, false, false,
10556 FirstLoad->getAlignment());
10557
10558 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10559 FirstInChain->getBasePtr(),
10560 FirstInChain->getPointerInfo(), false, false,
10561 FirstInChain->getAlignment());
10562
Nadav Rotemac920662012-10-03 19:30:31 +000010563 // Replace one of the loads with the new load.
10564 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10565 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10566 SDValue(NewLoad.getNode(), 1));
10567
10568 // Remove the rest of the load chains.
10569 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010570 // Replace all chain users of the old load nodes with the chain of the new
10571 // load node.
10572 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010573 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10574 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010575
Nadav Rotemac920662012-10-03 19:30:31 +000010576 // Replace the first store with the new store.
10577 CombineTo(EarliestOp, NewStore);
10578 // Erase all other stores.
10579 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010580 // Remove all Store nodes.
10581 if (StoreNodes[i].MemNode == EarliestOp)
10582 continue;
10583 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10584 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010585 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010586 }
10587
10588 return true;
10589}
10590
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010591SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010592 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010593 SDValue Chain = ST->getChain();
10594 SDValue Value = ST->getValue();
10595 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010596
Evan Chenga4cf58a2007-05-07 21:27:48 +000010597 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010598 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010599 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010600 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010601 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010602 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010603 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010604 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010605 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010606 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010607 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010608 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010609 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010610 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010611 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010612 }
Owen Andersona5192842011-04-14 17:30:49 +000010613
Chris Lattner41c80e82011-04-09 02:32:02 +000010614 // Turn 'store undef, Ptr' -> nothing.
10615 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10616 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010617
Nate Begeman8e20c762006-12-11 02:23:46 +000010618 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010619 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010620 // NOTE: If the original store is volatile, this transform must not increase
10621 // the number of stores. For example, on x86-32 an f64 can be stored in one
10622 // processor operation but an i64 (which is not legal) requires two. So the
10623 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010624 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010625 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010626 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010627 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010628 case MVT::f16: // We don't do this for these yet.
10629 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010630 case MVT::f128:
10631 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010632 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010633 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010634 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010635 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010636 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010637 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010638 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010639 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010640 }
10641 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010642 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010643 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010644 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010645 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010646 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010647 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010648 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010649 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010650 }
Owen Andersona5192842011-04-14 17:30:49 +000010651
Chris Lattner41c80e82011-04-09 02:32:02 +000010652 if (!ST->isVolatile() &&
10653 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010654 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010655 // argument passing. Since this is so common, custom legalize the
10656 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010657 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010658 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10659 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010660 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010661
Dan Gohman2af30632007-07-09 22:18:38 +000010662 unsigned Alignment = ST->getAlignment();
10663 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010664 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010665 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010666
Andrew Trickef9de2a2013-05-25 02:42:55 +000010667 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010668 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010669 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010670 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010671 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010672 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010673 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010674 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010675 Ptr, ST->getPointerInfo().getWithOffset(4),
10676 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010677 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010678 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010679 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010680 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010681
Chris Lattnerb7524b62006-12-12 04:16:14 +000010682 break;
Evan Cheng21836982006-12-11 17:25:19 +000010683 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010684 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010685 }
10686
Evan Cheng43cd9e32010-04-01 06:04:33 +000010687 // Try to infer better alignment information than the store already has.
10688 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010689 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersondb420122015-03-19 22:48:57 +000010690 if (Align > ST->getAlignment()) {
10691 SDValue NewStore =
10692 DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010693 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010694 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010695 ST->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +000010696 if (NewStore.getNode() != N)
10697 return CombineTo(ST, NewStore, true);
10698 }
Evan Cheng43cd9e32010-04-01 06:04:33 +000010699 }
10700 }
10701
Evan Chengd42641c2011-02-02 01:06:55 +000010702 // Try transforming a pair floating point load / store ops to integer
10703 // load / store ops.
10704 SDValue NewST = TransformFPLoadStorePair(N);
10705 if (NewST.getNode())
10706 return NewST;
10707
Eric Christopherf55d4712014-10-08 23:38:39 +000010708 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10709 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010710#ifndef NDEBUG
10711 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10712 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10713 UseAA = false;
10714#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010715 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010716 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010717 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010718
Jim Laskey708d0db2006-10-04 16:53:27 +000010719 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010720 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010721 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010722
10723 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010724 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010725 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010726 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010727 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010728 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010729 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010730 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010731
Jim Laskeyd07be232006-09-25 16:29:54 +000010732 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010733 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010734 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010735
Nate Begeman879d8f12009-09-15 00:18:30 +000010736 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010737 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010738
Jim Laskeydcf983c2006-10-13 23:32:28 +000010739 // Don't add users to work list.
10740 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010741 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010742 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010743
Evan Cheng33157702006-11-05 09:31:14 +000010744 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010745 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010746 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010747
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010748 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010749 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010750 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010751 // See if we can simplify the input to this truncstore with knowledge that
10752 // only the low bits are being used. For example:
10753 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010754 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010755 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010756 APInt::getLowBitsSet(
10757 Value.getValueType().getScalarType().getSizeInBits(),
10758 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010759 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010760 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010761 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010762 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010763
Chris Lattnerf47e3062007-10-13 06:58:48 +000010764 // Otherwise, see if we can simplify the operation with
10765 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010766 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010767 APInt::getLowBitsSet(
10768 Value.getValueType().getScalarType().getSizeInBits(),
10769 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010770 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010771 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010772
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010773 // If this is a load followed by a store to the same location, then the store
10774 // is dead/noop.
10775 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010776 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010777 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010778 // There can't be any side effects between the load and store, such as
10779 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010780 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010781 // The store is dead, remove it.
10782 return Chain;
10783 }
10784 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010785
James Molloy463db9a2014-09-27 17:02:54 +000010786 // If this is a store followed by a store with the same value to the same
10787 // location, then the store is dead/noop.
10788 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10789 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10790 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10791 ST1->isUnindexed() && !ST1->isVolatile()) {
10792 // The store is dead, remove it.
10793 return Chain;
10794 }
10795 }
10796
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010797 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10798 // truncating store. We can do this even if this is already a truncstore.
10799 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010800 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010801 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010802 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010803 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010804 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010805 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010806
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010807 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000010808 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000010809 if (!LegalTypes) {
10810 bool EverChanged = false;
10811
10812 do {
10813 // There can be multiple store sequences on the same chain.
10814 // Keep trying to merge store sequences until we are unable to do so
10815 // or until we merge the last store on the chain.
10816 bool Changed = MergeConsecutiveStores(ST);
10817 EverChanged |= Changed;
10818 if (!Changed) break;
10819 } while (ST->getOpcode() != ISD::DELETED_NODE);
10820
10821 if (EverChanged)
10822 return SDValue(N, 0);
10823 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010824
Evan Chenga9cda8a2009-05-28 00:35:15 +000010825 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000010826}
10827
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010828SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10829 SDValue InVec = N->getOperand(0);
10830 SDValue InVal = N->getOperand(1);
10831 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010832 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010833
Bob Wilson42603952010-05-19 23:42:58 +000010834 // If the inserted element is an UNDEF, just use the input vector.
10835 if (InVal.getOpcode() == ISD::UNDEF)
10836 return InVec;
10837
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010838 EVT VT = InVec.getValueType();
10839
Owen Andersonb2c80da2011-02-25 21:41:48 +000010840 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010841 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10842 return SDValue();
10843
Eli Friedmanb7910b72011-09-09 21:04:06 +000010844 // Check that we know which element is being inserted
10845 if (!isa<ConstantSDNode>(EltNo))
10846 return SDValue();
10847 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010848
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010849 // Canonicalize insert_vector_elt dag nodes.
10850 // Example:
10851 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10852 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10853 //
10854 // Do this only if the child insert_vector node has one use; also
10855 // do this only if indices are both constants and Idx1 < Idx0.
10856 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10857 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10858 unsigned OtherElt =
10859 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10860 if (Elt < OtherElt) {
10861 // Swap nodes.
10862 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10863 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010864 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010865 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10866 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10867 }
10868 }
10869
Eli Friedmanb7910b72011-09-09 21:04:06 +000010870 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10871 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10872 // vector elements.
10873 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000010874 // Do not combine these two vectors if the output vector will not replace
10875 // the input vector.
10876 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000010877 Ops.append(InVec.getNode()->op_begin(),
10878 InVec.getNode()->op_end());
10879 } else if (InVec.getOpcode() == ISD::UNDEF) {
10880 unsigned NElts = VT.getVectorNumElements();
10881 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10882 } else {
10883 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010884 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000010885
10886 // Insert the element
10887 if (Elt < Ops.size()) {
10888 // All the operands of BUILD_VECTOR must have the same type;
10889 // we enforce that here.
10890 EVT OpVT = Ops[0].getValueType();
10891 if (InVal.getValueType() != OpVT)
10892 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10893 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10894 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10895 Ops[Elt] = InVal;
10896 }
10897
10898 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000010899 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000010900}
10901
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010902SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10903 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10904 EVT ResultVT = EVE->getValueType(0);
10905 EVT VecEltVT = InVecVT.getVectorElementType();
10906 unsigned Align = OriginalLoad->getAlignment();
10907 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10908 VecEltVT.getTypeForEVT(*DAG.getContext()));
10909
10910 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10911 return SDValue();
10912
10913 Align = NewAlign;
10914
10915 SDValue NewPtr = OriginalLoad->getBasePtr();
10916 SDValue Offset;
10917 EVT PtrType = NewPtr.getValueType();
10918 MachinePointerInfo MPI;
10919 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10920 int Elt = ConstEltNo->getZExtValue();
10921 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10922 if (TLI.isBigEndian())
10923 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10924 Offset = DAG.getConstant(PtrOff, PtrType);
10925 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10926 } else {
10927 Offset = DAG.getNode(
10928 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10929 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10930 if (TLI.isBigEndian())
10931 Offset = DAG.getNode(
10932 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10933 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10934 MPI = OriginalLoad->getPointerInfo();
10935 }
10936 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10937
10938 // The replacement we need to do here is a little tricky: we need to
10939 // replace an extractelement of a load with a load.
10940 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10941 // Note that this replacement assumes that the extractvalue is the only
10942 // use of the load; that's okay because we don't want to perform this
10943 // transformation in other cases anyway.
10944 SDValue Load;
10945 SDValue Chain;
10946 if (ResultVT.bitsGT(VecEltVT)) {
10947 // If the result type of vextract is wider than the load, then issue an
10948 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010949 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10950 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010951 ? ISD::ZEXTLOAD
10952 : ISD::EXTLOAD;
10953 Load = DAG.getExtLoad(
10954 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10955 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10956 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10957 Chain = Load.getValue(1);
10958 } else {
10959 Load = DAG.getLoad(
10960 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10961 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10962 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10963 Chain = Load.getValue(1);
10964 if (ResultVT.bitsLT(VecEltVT))
10965 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10966 else
10967 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10968 }
10969 WorklistRemover DeadNodes(*this);
10970 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10971 SDValue To[] = { Load, Chain };
10972 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10973 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10974 // worklist explicitly as well.
10975 AddToWorklist(Load.getNode());
10976 AddUsersToWorklist(Load.getNode()); // Add users too
10977 // Make sure to revisit this node to clean it up; it will usually be dead.
10978 AddToWorklist(EVE);
10979 ++OpsNarrowed;
10980 return SDValue(EVE, 0);
10981}
10982
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010983SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010984 // (vextract (scalar_to_vector val, 0) -> val
10985 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010986 EVT VT = InVec.getValueType();
10987 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010988
Duncan Sands6be291a2011-05-09 08:03:33 +000010989 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10990 // Check if the result type doesn't match the inserted element type. A
10991 // SCALAR_TO_VECTOR may truncate the inserted element and the
10992 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10993 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010994 if (InOp.getValueType() != NVT) {
10995 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010996 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010997 }
10998 return InOp;
10999 }
Evan Cheng1120279a2008-05-13 08:35:03 +000011000
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011001 SDValue EltNo = N->getOperand(1);
11002 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11003
11004 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11005 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000011006 // we may introduce new vector instructions which are not backed by TD
11007 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000011008 // without using extract_subvector. However, if we can find an underlying
11009 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011010 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000011011 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011012 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11013 int NumElem = VT.getVectorNumElements();
11014 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11015 // Find the new index to extract from.
11016 int OrigElt = SVOp->getMaskElt(Elt);
11017
11018 // Extracting an undef index is undef.
11019 if (OrigElt == -1)
11020 return DAG.getUNDEF(NVT);
11021
11022 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011023 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011024 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011025 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011026 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011027 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011028 OrigElt -= NumElem;
11029 }
11030
Hal Finkel02807592014-03-31 11:43:19 +000011031 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11032 SDValue InOp = SVInVec.getOperand(OrigElt);
11033 if (InOp.getValueType() != NVT) {
11034 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11035 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11036 }
11037
11038 return InOp;
11039 }
11040
11041 // FIXME: We should handle recursing on other vector shuffles and
11042 // scalar_to_vector here as well.
11043
11044 if (!LegalOperations) {
11045 EVT IndexTy = TLI.getVectorIdxTy();
11046 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11047 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11048 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011049 }
11050
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011051 bool BCNumEltsChanged = false;
11052 EVT ExtVT = VT.getVectorElementType();
11053 EVT LVT = ExtVT;
11054
11055 // If the result of load has to be truncated, then it's not necessarily
11056 // profitable.
11057 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11058 return SDValue();
11059
11060 if (InVec.getOpcode() == ISD::BITCAST) {
11061 // Don't duplicate a load with other uses.
11062 if (!InVec.hasOneUse())
11063 return SDValue();
11064
11065 EVT BCVT = InVec.getOperand(0).getValueType();
11066 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11067 return SDValue();
11068 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11069 BCNumEltsChanged = true;
11070 InVec = InVec.getOperand(0);
11071 ExtVT = BCVT.getVectorElementType();
11072 }
11073
11074 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11075 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11076 ISD::isNormalLoad(InVec.getNode()) &&
11077 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11078 SDValue Index = N->getOperand(1);
11079 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11080 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11081 OrigLoad);
11082 }
11083
Evan Cheng1120279a2008-05-13 08:35:03 +000011084 // Perform only after legalization to ensure build_vector / vector_shuffle
11085 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011086 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011087
Mon P Wangca6d6de2009-01-17 00:07:25 +000011088 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11089 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11090 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011091
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011092 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011093 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011094
Craig Topperc0196b12014-04-14 00:51:57 +000011095 LoadSDNode *LN0 = nullptr;
11096 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011097 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011098 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011099 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011100 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011101 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011102 // Don't duplicate a load with other uses.
11103 if (!InVec.hasOneUse())
11104 return SDValue();
11105
Evan Cheng1120279a2008-05-13 08:35:03 +000011106 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011107 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011108 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11109 // =>
11110 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011111
Eli Friedmane96286c2011-12-26 22:49:32 +000011112 // Don't duplicate a load with other uses.
11113 if (!InVec.hasOneUse())
11114 return SDValue();
11115
Mon P Wangb5eb7202008-12-11 00:26:16 +000011116 // If the bit convert changed the number of elements, it is unsafe
11117 // to examine the mask.
11118 if (BCNumEltsChanged)
11119 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011120
11121 // Select the input vector, guarding against out of range extract vector.
11122 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011123 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011124 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11125
Eli Friedmane96286c2011-12-26 22:49:32 +000011126 if (InVec.getOpcode() == ISD::BITCAST) {
11127 // Don't duplicate a load with other uses.
11128 if (!InVec.hasOneUse())
11129 return SDValue();
11130
Evan Cheng1120279a2008-05-13 08:35:03 +000011131 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011132 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011133 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011134 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011135 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011136 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011137 }
11138 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011139
Eli Friedmane96286c2011-12-26 22:49:32 +000011140 // Make sure we found a non-volatile load and the extractelement is
11141 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011142 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011143 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011144
Eric Christopherc6418b12010-11-03 20:44:42 +000011145 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11146 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011147 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011148
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011149 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011150 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011151
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011152 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011153}
Evan Cheng0de312d2007-10-06 08:19:55 +000011154
Michael Liao6d106b72012-10-23 23:06:52 +000011155// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11156SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11157 // We perform this optimization post type-legalization because
11158 // the type-legalizer often scalarizes integer-promoted vectors.
11159 // Performing this optimization before may create bit-casts which
11160 // will be type-legalized to complex code sequences.
11161 // We perform this optimization only before the operation legalizer because we
11162 // may introduce illegal operations.
11163 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11164 return SDValue();
11165
Dan Gohmana8665142007-06-25 16:23:39 +000011166 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011167 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011168 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011169
Nadav Rotembf6568b2011-10-29 21:23:04 +000011170 // Check to see if this is a BUILD_VECTOR of a bunch of values
11171 // which come from any_extend or zero_extend nodes. If so, we can create
11172 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011173 // optimizations. We do not handle sign-extend because we can't fill the sign
11174 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011175 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011176 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011177
Craig Topper02cb0fb2012-01-17 09:09:48 +000011178 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011179 SDValue In = N->getOperand(i);
11180 // Ignore undef inputs.
11181 if (In.getOpcode() == ISD::UNDEF) continue;
11182
11183 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11184 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11185
Nadav Rotemf3103612011-10-31 20:08:25 +000011186 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011187 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011188 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011189 break;
11190 }
11191
11192 // The input is a ZeroExt or AnyExt. Check the original type.
11193 EVT InTy = In.getOperand(0).getValueType();
11194
11195 // Check that all of the widened source types are the same.
11196 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011197 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011198 SourceType = InTy;
11199 else if (InTy != SourceType) {
11200 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011201 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011202 break;
11203 }
11204
11205 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011206 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011207 }
11208
Nadav Rotemf3103612011-10-31 20:08:25 +000011209 // In order to have valid types, all of the inputs must be extended from the
11210 // same source type and all of the inputs must be any or zero extend.
11211 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011212 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011213 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011214 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11215 isPowerOf2_32(SourceType.getSizeInBits());
11216
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011217 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11218 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011219 if (!ValidTypes)
11220 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011221
Michael Liao6d106b72012-10-23 23:06:52 +000011222 bool isLE = TLI.isLittleEndian();
11223 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11224 assert(ElemRatio > 1 && "Invalid element size ratio");
11225 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11226 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011227
Michael Liao6d106b72012-10-23 23:06:52 +000011228 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11229 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011230
Michael Liao6d106b72012-10-23 23:06:52 +000011231 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011232 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011233 SDValue Cast = N->getOperand(i);
11234 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11235 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11236 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11237 SDValue In;
11238 if (Cast.getOpcode() == ISD::UNDEF)
11239 In = DAG.getUNDEF(SourceType);
11240 else
11241 In = Cast->getOperand(0);
11242 unsigned Index = isLE ? (i * ElemRatio) :
11243 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011244
Michael Liao6d106b72012-10-23 23:06:52 +000011245 assert(Index < Ops.size() && "Invalid index");
11246 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011247 }
Chris Lattner5336a592006-03-19 01:27:56 +000011248
Michael Liao6d106b72012-10-23 23:06:52 +000011249 // The type of the new BUILD_VECTOR node.
11250 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11251 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11252 "Invalid vector size");
11253 // Check if the new vector type is legal.
11254 if (!isTypeLegal(VecVT)) return SDValue();
11255
11256 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011257 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011258
11259 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011260 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011261 // Bitcast to the desired type.
11262 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11263}
11264
Michael Liao59229792012-10-24 04:14:18 +000011265SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11266 EVT VT = N->getValueType(0);
11267
11268 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011269 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011270
11271 EVT SrcVT = MVT::Other;
11272 unsigned Opcode = ISD::DELETED_NODE;
11273 unsigned NumDefs = 0;
11274
11275 for (unsigned i = 0; i != NumInScalars; ++i) {
11276 SDValue In = N->getOperand(i);
11277 unsigned Opc = In.getOpcode();
11278
11279 if (Opc == ISD::UNDEF)
11280 continue;
11281
11282 // If all scalar values are floats and converted from integers.
11283 if (Opcode == ISD::DELETED_NODE &&
11284 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11285 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011286 }
Tom Stellard567f8862013-01-02 22:13:01 +000011287
Michael Liao59229792012-10-24 04:14:18 +000011288 if (Opc != Opcode)
11289 return SDValue();
11290
11291 EVT InVT = In.getOperand(0).getValueType();
11292
11293 // If all scalar values are typed differently, bail out. It's chosen to
11294 // simplify BUILD_VECTOR of integer types.
11295 if (SrcVT == MVT::Other)
11296 SrcVT = InVT;
11297 if (SrcVT != InVT)
11298 return SDValue();
11299 NumDefs++;
11300 }
11301
11302 // If the vector has just one element defined, it's not worth to fold it into
11303 // a vectorized one.
11304 if (NumDefs < 2)
11305 return SDValue();
11306
11307 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11308 && "Should only handle conversion from integer to float.");
11309 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11310
11311 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011312
11313 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11314 return SDValue();
11315
Hal Finkele2dd84e2015-02-22 16:10:22 +000011316 // Just because the floating-point vector type is legal does not necessarily
11317 // mean that the corresponding integer vector type is.
11318 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011319 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011320
Michael Liao59229792012-10-24 04:14:18 +000011321 SmallVector<SDValue, 8> Opnds;
11322 for (unsigned i = 0; i != NumInScalars; ++i) {
11323 SDValue In = N->getOperand(i);
11324
11325 if (In.getOpcode() == ISD::UNDEF)
11326 Opnds.push_back(DAG.getUNDEF(SrcVT));
11327 else
11328 Opnds.push_back(In.getOperand(0));
11329 }
Craig Topper48d114b2014-04-26 18:35:24 +000011330 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011331 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011332
11333 return DAG.getNode(Opcode, dl, VT, BV);
11334}
11335
Michael Liao6d106b72012-10-23 23:06:52 +000011336SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11337 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011338 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011339 EVT VT = N->getValueType(0);
11340
11341 // A vector built entirely of undefs is undef.
11342 if (ISD::allOperandsUndef(N))
11343 return DAG.getUNDEF(VT);
11344
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011345 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011346 return V;
11347
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011348 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011349 return V;
11350
Dan Gohmana8665142007-06-25 16:23:39 +000011351 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11352 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11353 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011354
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011355 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11356 if (!isTypeLegal(VT))
11357 return SDValue();
11358
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011359 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011360 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011361 return SDValue();
11362
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011363 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011364 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011365 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011366 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011367 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011368 if (Op.getOpcode() == ISD::UNDEF) continue;
11369
11370 // See if we can combine this build_vector into a blend with a zero vector.
11371 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11372 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11373 (Op.getOpcode() == ISD::ConstantFP &&
11374 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11375 UsesZeroVector = true;
11376 continue;
11377 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011378
Dan Gohmana8665142007-06-25 16:23:39 +000011379 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011380 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011381 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11382 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011383 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011384 break;
11385 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011386
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011387 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011388 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011389 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11390 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011391
Craig Topperc0196b12014-04-14 00:51:57 +000011392 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011393 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011394 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011395 VecIn2 = ExtractedFromVec;
11396 } else {
11397 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011398 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011399 break;
11400 }
11401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011402
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011403 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011404 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011405 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011406 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011407 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011408 unsigned Opcode = N->getOperand(i).getOpcode();
11409 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011410 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011411 continue;
11412 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011413
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011414 // Operands can also be zero.
11415 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11416 assert(UsesZeroVector &&
11417 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11418 "Unexpected node found!");
11419 Mask.push_back(NumInScalars+i);
11420 continue;
11421 }
11422
Rafael Espindolab93db662009-04-24 12:40:33 +000011423 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011424 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011425 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011426 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011427 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011428 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011429 continue;
11430 }
11431
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011432 // Otherwise, use InIdx + InputVecSize
11433 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011434 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011435
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011436 // Avoid introducing illegal shuffles with zero.
11437 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11438 return SDValue();
11439
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011440 // We can't generate a shuffle node with mismatched input and output types.
11441 // Attempt to transform a single input vector to the correct type.
11442 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011443 // If the input vector type has a different base type to the output
11444 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011445 EVT VTElemType = VT.getVectorElementType();
11446 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11447 (VecIn2.getNode() &&
11448 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011449 return SDValue();
11450
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011451 // If the input vector is too small, widen it.
11452 // We only support widening of vectors which are half the size of the
11453 // output registers. For example XMM->YMM widening on X86 with AVX.
11454 EVT VecInT = VecIn1.getValueType();
11455 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011456 // If we only have one small input, widen it by adding undef values.
11457 if (!VecIn2.getNode())
11458 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11459 DAG.getUNDEF(VecIn1.getValueType()));
11460 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11461 // If we have two small inputs of the same type, try to concat them.
11462 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11463 VecIn2 = SDValue(nullptr, 0);
11464 } else
11465 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011466 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11467 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011468 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000011469 // If the zero vector was used, we can not split the vector,
11470 // since we'd need 3 inputs.
11471 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011472 return SDValue();
11473
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011474 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11475 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011476
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011477 // Try to replace VecIn1 with two extract_subvectors
11478 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011479 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011480 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11481 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11482 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011483 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011484 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011485 }
11486
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011487 if (UsesZeroVector)
11488 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11489 DAG.getConstantFP(0.0, VT);
11490 else
11491 // If VecIn2 is unused then change it to undef.
11492 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011493
Nadav Rotem841c9a82012-09-20 08:53:31 +000011494 // Check that we were able to transform all incoming values to the same
11495 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011496 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11497 VecIn1.getValueType() != VT)
11498 return SDValue();
11499
Dan Gohmana8665142007-06-25 16:23:39 +000011500 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011501 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011502 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011503 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011504 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011506
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011507 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011508}
11509
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011510SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011511 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11512 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11513 // inputs come from at most two distinct vectors, turn this into a shuffle
11514 // node.
11515
11516 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011517 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011518 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011519
Nadav Rotem01892102012-07-14 21:30:27 +000011520 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011521 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011522 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011523 return DAG.getUNDEF(VT);
11524
11525 // Optimize concat_vectors where one of the vectors is undef.
11526 if (N->getNumOperands() == 2 &&
11527 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11528 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011529 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011530
11531 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11532 if (In->getOpcode() == ISD::BITCAST &&
11533 !In->getOperand(0)->getValueType(0).isVector()) {
11534 SDValue Scalar = In->getOperand(0);
11535 EVT SclTy = Scalar->getValueType(0);
11536
11537 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11538 return SDValue();
11539
11540 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11541 VT.getSizeInBits() / SclTy.getSizeInBits());
11542 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11543 return SDValue();
11544
11545 SDLoc dl = SDLoc(N);
11546 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11547 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11548 }
11549 }
Nadav Rotem01892102012-07-14 21:30:27 +000011550
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011551 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11552 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000011553 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11554 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011555 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11556 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11557 };
11558 bool AllBuildVectorsOrUndefs =
11559 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11560 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000011561 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011562 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000011563
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011564 EVT MinVT = SVT;
11565 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000011566 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011567 // operand types. Get the smallest type and truncate all operands to it.
11568 bool FoundMinVT = false;
11569 for (const SDValue &Op : N->ops())
11570 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11571 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11572 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11573 FoundMinVT = true;
11574 }
11575 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000011576 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011577
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011578 for (const SDValue &Op : N->ops()) {
11579 EVT OpVT = Op.getValueType();
11580 unsigned NumElts = OpVT.getVectorNumElements();
11581
11582 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011583 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011584
11585 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11586 if (SVT.isFloatingPoint()) {
11587 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011588 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011589 } else {
11590 for (unsigned i = 0; i != NumElts; ++i)
11591 Opnds.push_back(
11592 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11593 }
11594 }
11595 }
11596
11597 assert(VT.getVectorNumElements() == Opnds.size() &&
11598 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000011599 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011600 }
11601
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011602 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11603 // nodes often generate nop CONCAT_VECTOR nodes.
11604 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11605 // place the incoming vectors at the exact same location.
11606 SDValue SingleSource = SDValue();
11607 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11608
11609 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11610 SDValue Op = N->getOperand(i);
11611
11612 if (Op.getOpcode() == ISD::UNDEF)
11613 continue;
11614
11615 // Check if this is the identity extract:
11616 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11617 return SDValue();
11618
11619 // Find the single incoming vector for the extract_subvector.
11620 if (SingleSource.getNode()) {
11621 if (Op.getOperand(0) != SingleSource)
11622 return SDValue();
11623 } else {
11624 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011625
11626 // Check the source type is the same as the type of the result.
11627 // If not, this concat may extend the vector, so we can not
11628 // optimize it away.
11629 if (SingleSource.getValueType() != N->getValueType(0))
11630 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011631 }
11632
11633 unsigned IdentityIndex = i * PartNumElem;
11634 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11635 // The extract index must be constant.
11636 if (!CS)
11637 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011638
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011639 // Check that we are reading from the identity index.
11640 if (CS->getZExtValue() != IdentityIndex)
11641 return SDValue();
11642 }
11643
11644 if (SingleSource.getNode())
11645 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011646
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011647 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011648}
11649
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011650SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11651 EVT NVT = N->getValueType(0);
11652 SDValue V = N->getOperand(0);
11653
Michael Liao7a442c802012-10-17 20:48:33 +000011654 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11655 // Combine:
11656 // (extract_subvec (concat V1, V2, ...), i)
11657 // Into:
11658 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011659 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11660 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011661 if (V->getOperand(0).getValueType() != NVT)
11662 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000011663 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11664 unsigned NumElems = NVT.getVectorNumElements();
11665 assert((Idx % NumElems) == 0 &&
11666 "IDX in concat is not a multiple of the result vector length.");
11667 return V->getOperand(Idx / NumElems);
11668 }
11669
Michael Liaobb05a1d2013-03-25 23:47:35 +000011670 // Skip bitcasting
11671 if (V->getOpcode() == ISD::BITCAST)
11672 V = V.getOperand(0);
11673
11674 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011675 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011676 // Handle only simple case where vector being inserted and vector
11677 // being extracted are of same type, and are half size of larger vectors.
11678 EVT BigVT = V->getOperand(0).getValueType();
11679 EVT SmallVT = V->getOperand(1).getValueType();
11680 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11681 return SDValue();
11682
11683 // Only handle cases where both indexes are constants with the same type.
11684 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11685 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11686
11687 if (InsIdx && ExtIdx &&
11688 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11689 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11690 // Combine:
11691 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11692 // Into:
11693 // indices are equal or bit offsets are equal => V1
11694 // otherwise => (extract_subvec V1, ExtIdx)
11695 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11696 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11697 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11698 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11699 DAG.getNode(ISD::BITCAST, dl,
11700 N->getOperand(0).getValueType(),
11701 V->getOperand(0)), N->getOperand(1));
11702 }
11703 }
11704
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011705 return SDValue();
11706}
11707
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011708static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11709 SDValue V, SelectionDAG &DAG) {
11710 SDLoc DL(V);
11711 EVT VT = V.getValueType();
11712
11713 switch (V.getOpcode()) {
11714 default:
11715 return V;
11716
11717 case ISD::CONCAT_VECTORS: {
11718 EVT OpVT = V->getOperand(0).getValueType();
11719 int OpSize = OpVT.getVectorNumElements();
11720 SmallBitVector OpUsedElements(OpSize, false);
11721 bool FoundSimplification = false;
11722 SmallVector<SDValue, 4> NewOps;
11723 NewOps.reserve(V->getNumOperands());
11724 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11725 SDValue Op = V->getOperand(i);
11726 bool OpUsed = false;
11727 for (int j = 0; j < OpSize; ++j)
11728 if (UsedElements[i * OpSize + j]) {
11729 OpUsedElements[j] = true;
11730 OpUsed = true;
11731 }
11732 NewOps.push_back(
11733 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11734 : DAG.getUNDEF(OpVT));
11735 FoundSimplification |= Op == NewOps.back();
11736 OpUsedElements.reset();
11737 }
11738 if (FoundSimplification)
11739 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11740 return V;
11741 }
11742
11743 case ISD::INSERT_SUBVECTOR: {
11744 SDValue BaseV = V->getOperand(0);
11745 SDValue SubV = V->getOperand(1);
11746 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11747 if (!IdxN)
11748 return V;
11749
11750 int SubSize = SubV.getValueType().getVectorNumElements();
11751 int Idx = IdxN->getZExtValue();
11752 bool SubVectorUsed = false;
11753 SmallBitVector SubUsedElements(SubSize, false);
11754 for (int i = 0; i < SubSize; ++i)
11755 if (UsedElements[i + Idx]) {
11756 SubVectorUsed = true;
11757 SubUsedElements[i] = true;
11758 UsedElements[i + Idx] = false;
11759 }
11760
11761 // Now recurse on both the base and sub vectors.
11762 SDValue SimplifiedSubV =
11763 SubVectorUsed
11764 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11765 : DAG.getUNDEF(SubV.getValueType());
11766 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11767 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11768 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11769 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11770 return V;
11771 }
11772 }
11773}
11774
11775static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11776 SDValue N1, SelectionDAG &DAG) {
11777 EVT VT = SVN->getValueType(0);
11778 int NumElts = VT.getVectorNumElements();
11779 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11780 for (int M : SVN->getMask())
11781 if (M >= 0 && M < NumElts)
11782 N0UsedElements[M] = true;
11783 else if (M >= NumElts)
11784 N1UsedElements[M - NumElts] = true;
11785
11786 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11787 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11788 if (S0 == N0 && S1 == N1)
11789 return SDValue();
11790
11791 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11792}
11793
Mehdi Amini37f316a2015-01-17 01:35:56 +000011794// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11795// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011796static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11797 EVT VT = N->getValueType(0);
11798 unsigned NumElts = VT.getVectorNumElements();
11799
11800 SDValue N0 = N->getOperand(0);
11801 SDValue N1 = N->getOperand(1);
11802 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11803
11804 SmallVector<SDValue, 4> Ops;
11805 EVT ConcatVT = N0.getOperand(0).getValueType();
11806 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11807 unsigned NumConcats = NumElts / NumElemsPerConcat;
11808
Mehdi Amini37f316a2015-01-17 01:35:56 +000011809 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11810 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11811 // half vector elements.
11812 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11813 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11814 SVN->getMask().end(), [](int i) { return i == -1; })) {
11815 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11816 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11817 N1 = DAG.getUNDEF(ConcatVT);
11818 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11819 }
11820
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011821 // Look at every vector that's inserted. We're looking for exact
11822 // subvector-sized copies from a concatenated vector
11823 for (unsigned I = 0; I != NumConcats; ++I) {
11824 // Make sure we're dealing with a copy.
11825 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000011826 bool AllUndef = true, NoUndef = true;
11827 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11828 if (SVN->getMaskElt(J) >= 0)
11829 AllUndef = false;
11830 else
11831 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011832 }
11833
Hao Liubc601962013-05-13 02:07:05 +000011834 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000011835 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11836 return SDValue();
11837
11838 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11839 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11840 return SDValue();
11841
11842 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11843 if (FirstElt < N0.getNumOperands())
11844 Ops.push_back(N0.getOperand(FirstElt));
11845 else
11846 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11847
11848 } else if (AllUndef) {
11849 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11850 } else { // Mixed with general masks and undefs, can't do optimization.
11851 return SDValue();
11852 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011853 }
11854
Craig Topper48d114b2014-04-26 18:35:24 +000011855 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011856}
11857
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011858SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011859 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011860 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011861
Mon P Wang25f01062008-11-10 04:46:22 +000011862 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000011863 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000011864
Craig Topper5894fe42012-04-09 05:16:56 +000011865 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000011866
Craig Topper279c77b2012-01-04 08:07:43 +000011867 // Canonicalize shuffle undef, undef -> undef
11868 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11869 return DAG.getUNDEF(VT);
11870
11871 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11872
11873 // Canonicalize shuffle v, v -> v, undef
11874 if (N0 == N1) {
11875 SmallVector<int, 8> NewMask;
11876 for (unsigned i = 0; i != NumElts; ++i) {
11877 int Idx = SVN->getMaskElt(i);
11878 if (Idx >= (int)NumElts) Idx -= NumElts;
11879 NewMask.push_back(Idx);
11880 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011881 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011882 &NewMask[0]);
11883 }
11884
11885 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11886 if (N0.getOpcode() == ISD::UNDEF) {
11887 SmallVector<int, 8> NewMask;
11888 for (unsigned i = 0; i != NumElts; ++i) {
11889 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000011890 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000011891 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000011892 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000011893 else
11894 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000011895 }
11896 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000011897 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011898 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011899 &NewMask[0]);
11900 }
11901
11902 // Remove references to rhs if it is undef
11903 if (N1.getOpcode() == ISD::UNDEF) {
11904 bool Changed = false;
11905 SmallVector<int, 8> NewMask;
11906 for (unsigned i = 0; i != NumElts; ++i) {
11907 int Idx = SVN->getMaskElt(i);
11908 if (Idx >= (int)NumElts) {
11909 Idx = -1;
11910 Changed = true;
11911 }
11912 NewMask.push_back(Idx);
11913 }
11914 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000011915 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000011916 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000011917
Bob Wilsonf63da122010-10-28 17:06:14 +000011918 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011919 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000011920 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000011921 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000011922
Dan Gohmana8665142007-06-25 16:23:39 +000011923 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000011924 // not the number of vector elements, look through it. Be careful not to
11925 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000011926 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011927 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000011928 if (ConvInput.getValueType().isVector() &&
11929 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011930 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000011931 }
11932
Dan Gohmana8665142007-06-25 16:23:39 +000011933 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000011934 assert(V->getNumOperands() == NumElts &&
11935 "BUILD_VECTOR has wrong number of operands");
11936 SDValue Base;
11937 bool AllSame = true;
11938 for (unsigned i = 0; i != NumElts; ++i) {
11939 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11940 Base = V->getOperand(i);
11941 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000011942 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011943 }
Bob Wilsonf63da122010-10-28 17:06:14 +000011944 // Splat of <u, u, u, u>, return <u, u, u, u>
11945 if (!Base.getNode())
11946 return N0;
11947 for (unsigned i = 0; i != NumElts; ++i) {
11948 if (V->getOperand(i) != Base) {
11949 AllSame = false;
11950 break;
11951 }
11952 }
11953 // Splat of <x, x, x, x>, return <x, x, x, x>
11954 if (AllSame)
11955 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011956
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011957 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011958 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011959 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11960 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11961 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011962
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011963 // We may have jumped through bitcasts, so the type of the
11964 // BUILD_VECTOR may not match the type of the shuffle.
11965 if (V->getValueType(0) != VT)
Sanjay Pateld95dd9e2015-03-26 16:55:17 +000011966 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011967 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000011968 }
11969 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011970
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011971 // There are various patterns used to build up a vector from smaller vectors,
11972 // subvectors, or elements. Scan chains of these and replace unused insertions
11973 // or components with undef.
11974 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11975 return S;
11976
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011977 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11978 Level < AfterLegalizeVectorOps &&
11979 (N1.getOpcode() == ISD::UNDEF ||
11980 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11981 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11982 SDValue V = partitionShuffleOfConcats(N, DAG);
11983
11984 if (V.getNode())
11985 return V;
11986 }
11987
Simon Pilgrim7189084b2015-03-05 17:14:04 +000011988 // If this shuffle only has a single input that is a bitcasted shuffle,
11989 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11990 // back to their original types.
11991 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11992 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11993 TLI.isTypeLegal(VT)) {
11994
11995 // Peek through the bitcast only if there is one user.
11996 SDValue BC0 = N0;
11997 while (BC0.getOpcode() == ISD::BITCAST) {
11998 if (!BC0.hasOneUse())
11999 break;
12000 BC0 = BC0.getOperand(0);
12001 }
12002
12003 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12004 if (Scale == 1)
12005 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12006
12007 SmallVector<int, 8> NewMask;
12008 for (int M : Mask)
12009 for (int s = 0; s != Scale; ++s)
12010 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12011 return NewMask;
12012 };
12013
12014 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12015 EVT SVT = VT.getScalarType();
12016 EVT InnerVT = BC0->getValueType(0);
12017 EVT InnerSVT = InnerVT.getScalarType();
12018
12019 // Determine which shuffle works with the smaller scalar type.
12020 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12021 EVT ScaleSVT = ScaleVT.getScalarType();
12022
12023 if (TLI.isTypeLegal(ScaleVT) &&
12024 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12025 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12026
12027 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12028 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12029
12030 // Scale the shuffle masks to the smaller scalar type.
12031 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12032 SmallVector<int, 8> InnerMask =
12033 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12034 SmallVector<int, 8> OuterMask =
12035 ScaleShuffleMask(SVN->getMask(), OuterScale);
12036
12037 // Merge the shuffle masks.
12038 SmallVector<int, 8> NewMask;
12039 for (int M : OuterMask)
12040 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12041
12042 // Test for shuffle mask legality over both commutations.
12043 SDValue SV0 = BC0->getOperand(0);
12044 SDValue SV1 = BC0->getOperand(1);
12045 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12046 if (!LegalMask) {
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012047 std::swap(SV0, SV1);
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012048 ShuffleVectorSDNode::commuteMask(NewMask);
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012049 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12050 }
12051
12052 if (LegalMask) {
12053 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12054 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12055 return DAG.getNode(
12056 ISD::BITCAST, SDLoc(N), VT,
12057 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12058 }
12059 }
12060 }
12061 }
12062
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012063 // Canonicalize shuffles according to rules:
12064 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12065 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12066 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012067 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012068 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12069 TLI.isTypeLegal(VT)) {
12070 // The incoming shuffle must be of the same type as the result of the
12071 // current shuffle.
12072 assert(N1->getOperand(0).getValueType() == VT &&
12073 "Shuffle types don't match");
12074
12075 SDValue SV0 = N1->getOperand(0);
12076 SDValue SV1 = N1->getOperand(1);
12077 bool HasSameOp0 = N0 == SV0;
12078 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12079 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12080 // Commute the operands of this shuffle so that next rule
12081 // will trigger.
12082 return DAG.getCommutedVectorShuffle(*SVN);
12083 }
12084
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012085 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012086 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12087 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12088 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012089 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012090 // Only fold if this shuffle is the only user of the other shuffle.
12091 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12092 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012093 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12094
12095 // The incoming shuffle must be of the same type as the result of the
12096 // current shuffle.
12097 assert(OtherSV->getOperand(0).getValueType() == VT &&
12098 "Shuffle types don't match");
12099
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012100 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012101 SmallVector<int, 4> Mask;
12102 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12103 // operand, and SV1 as the second operand.
12104 for (unsigned i = 0; i != NumElts; ++i) {
12105 int Idx = SVN->getMaskElt(i);
12106 if (Idx < 0) {
12107 // Propagate Undef.
12108 Mask.push_back(Idx);
12109 continue;
12110 }
12111
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012112 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012113 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012114 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12115 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012116 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012117 if (Idx < 0) {
12118 // Propagate Undef.
12119 Mask.push_back(Idx);
12120 continue;
12121 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012122
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012123 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12124 : OtherSV->getOperand(1);
12125 } else {
12126 // This shuffle index references an element within N1.
12127 CurrentVec = N1;
12128 }
12129
12130 // Simple case where 'CurrentVec' is UNDEF.
12131 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12132 Mask.push_back(-1);
12133 continue;
12134 }
12135
12136 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12137 // will be the first or second operand of the combined shuffle.
12138 Idx = Idx % NumElts;
12139 if (!SV0.getNode() || SV0 == CurrentVec) {
12140 // Ok. CurrentVec is the left hand side.
12141 // Update the mask accordingly.
12142 SV0 = CurrentVec;
12143 Mask.push_back(Idx);
12144 continue;
12145 }
12146
12147 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12148 if (SV1.getNode() && SV1 != CurrentVec)
12149 return SDValue();
12150
12151 // Ok. CurrentVec is the right hand side.
12152 // Update the mask accordingly.
12153 SV1 = CurrentVec;
12154 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012155 }
12156
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012157 // Check if all indices in Mask are Undef. In case, propagate Undef.
12158 bool isUndefMask = true;
12159 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12160 isUndefMask &= Mask[i] < 0;
12161
12162 if (isUndefMask)
12163 return DAG.getUNDEF(VT);
12164
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012165 if (!SV0.getNode())
12166 SV0 = DAG.getUNDEF(VT);
12167 if (!SV1.getNode())
12168 SV1 = DAG.getUNDEF(VT);
12169
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012170 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012171 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012172 ShuffleVectorSDNode::commuteMask(Mask);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012173
12174 if (!TLI.isShuffleMaskLegal(Mask, VT))
12175 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012176
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012177 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12178 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12179 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12180 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012181 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012182
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012183 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12184 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12185 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12186 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012187 }
12188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012189 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012190}
12191
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012192SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12193 SDValue InVal = N->getOperand(0);
12194 EVT VT = N->getValueType(0);
12195
12196 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12197 // with a VECTOR_SHUFFLE.
12198 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12199 SDValue InVec = InVal->getOperand(0);
12200 SDValue EltNo = InVal->getOperand(1);
12201
12202 // FIXME: We could support implicit truncation if the shuffle can be
12203 // scaled to a smaller vector scalar type.
12204 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12205 if (C0 && VT == InVec.getValueType() &&
12206 VT.getScalarType() == InVal.getValueType()) {
12207 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12208 int Elt = C0->getZExtValue();
12209 NewMask[0] = Elt;
12210
12211 if (TLI.isShuffleMaskLegal(NewMask, VT))
12212 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12213 NewMask);
12214 }
12215 }
12216
12217 return SDValue();
12218}
12219
Manman Ren413a6cb2014-01-31 01:10:35 +000012220SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12221 SDValue N0 = N->getOperand(0);
12222 SDValue N2 = N->getOperand(2);
12223
12224 // If the input vector is a concatenation, and the insert replaces
12225 // one of the halves, we can optimize into a single concat_vectors.
12226 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12227 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12228 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12229 EVT VT = N->getValueType(0);
12230
12231 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12232 // (concat_vectors Z, Y)
12233 if (InsIdx == 0)
12234 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12235 N->getOperand(1), N0.getOperand(1));
12236
12237 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12238 // (concat_vectors X, Z)
12239 if (InsIdx == VT.getVectorNumElements()/2)
12240 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12241 N0.getOperand(0), N->getOperand(1));
12242 }
12243
12244 return SDValue();
12245}
12246
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012247/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12248/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012249/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012250/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012251SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012252 EVT VT = N->getValueType(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012253 SDValue LHS = N->getOperand(0);
12254 SDValue RHS = N->getOperand(1);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012255 SDLoc dl(N);
Craig Toppere5893f62012-04-09 05:59:53 +000012256
Simon Pilgrim257849f2015-03-17 22:19:08 +000012257 // Make sure we're not running after operation legalization where it
12258 // may have custom lowered the vector shuffles.
12259 if (LegalOperations)
12260 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012261
Simon Pilgrim257849f2015-03-17 22:19:08 +000012262 if (N->getOpcode() != ISD::AND)
12263 return SDValue();
12264
12265 if (RHS.getOpcode() == ISD::BITCAST)
12266 RHS = RHS.getOperand(0);
12267
12268 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12269 SmallVector<int, 8> Indices;
12270 unsigned NumElts = RHS.getNumOperands();
12271
12272 for (unsigned i = 0; i != NumElts; ++i) {
12273 SDValue Elt = RHS.getOperand(i);
12274 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012275 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012276
Simon Pilgrim257849f2015-03-17 22:19:08 +000012277 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12278 Indices.push_back(i);
12279 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12280 Indices.push_back(NumElts+i);
12281 else
12282 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012283 }
Simon Pilgrim257849f2015-03-17 22:19:08 +000012284
12285 // Let's see if the target supports this vector_shuffle.
12286 EVT RVT = RHS.getValueType();
12287 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12288 return SDValue();
12289
12290 // Return the new VECTOR_SHUFFLE node.
12291 EVT EltVT = RVT.getVectorElementType();
12292 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12293 DAG.getConstant(0, EltVT));
12294 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12295 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12296 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12297 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012298 }
Bill Wendling31b50992009-01-30 23:59:18 +000012299
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012300 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012301}
12302
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012303/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012304SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012305 assert(N->getValueType(0).isVector() &&
12306 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012308 SDValue LHS = N->getOperand(0);
12309 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012310
12311 if (SDValue Shuffle = XformToShuffleWithZero(N))
12312 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012313
Dan Gohmana8665142007-06-25 16:23:39 +000012314 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012315 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012316 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012317 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012318 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012319 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12320 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012321 return SDValue();
12322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012323 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012324 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012325 SDValue LHSOp = LHS.getOperand(i);
12326 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012327
Evan Cheng64d28462006-05-31 06:08:35 +000012328 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012329 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12330 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000012331 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012332 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000012333 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012334 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012335 break;
12336 }
Bill Wendling31b50992009-01-30 23:59:18 +000012337
Bob Wilson54081442010-12-17 23:06:49 +000012338 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012339 EVT RVT = RHSOp.getValueType();
12340 if (RVT != VT) {
12341 // Integer BUILD_VECTOR operands may have types larger than the element
12342 // size (e.g., when the element type is not legal). Prior to type
12343 // legalization, the types may not match between the two BUILD_VECTORS.
12344 // Truncate one of the operands to make them match.
12345 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012346 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012347 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012348 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012349 VT = RVT;
12350 }
12351 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012352 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012353 LHSOp, RHSOp);
12354 if (FoldOp.getOpcode() != ISD::UNDEF &&
12355 FoldOp.getOpcode() != ISD::Constant &&
12356 FoldOp.getOpcode() != ISD::ConstantFP)
12357 break;
12358 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012359 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012361
Bob Wilson54081442010-12-17 23:06:49 +000012362 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012363 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012364 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012365
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012366 // Type legalization might introduce new shuffles in the DAG.
12367 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12368 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12369 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12370 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12371 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12372 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12373 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12374 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12375
12376 if (SVN0->getMask().equals(SVN1->getMask())) {
12377 EVT VT = N->getValueType(0);
12378 SDValue UndefVector = LHS.getOperand(1);
12379 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12380 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012381 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012382 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12383 &SVN0->getMask()[0]);
12384 }
12385 }
12386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012387 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012388}
12389
Andrew Trickef9de2a2013-05-25 02:42:55 +000012390SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012391 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000012392 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000012393
Bill Wendling31b50992009-01-30 23:59:18 +000012394 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000012395 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000012396
Nate Begeman2042aa52005-10-08 00:29:44 +000012397 // If we got a simplified select_cc node back from SimplifySelectCC, then
12398 // break it down into a new SETCC node, and a new SELECT node, and then return
12399 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000012400 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012401 // Check to see if we got a select_cc back (to turn into setcc/select).
12402 // Otherwise, just return whatever node we got back, like fabs.
12403 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012404 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012405 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000012406 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000012407 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012408 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000012409 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12410 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000012411 }
Bill Wendling31b50992009-01-30 23:59:18 +000012412
Nate Begeman2042aa52005-10-08 00:29:44 +000012413 return SCC;
12414 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012415 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012416}
12417
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012418/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12419/// being selected between, see if we can simplify the select. Callers of this
12420/// should assume that TheSelect is deleted if this returns true. As such, they
12421/// should return the appropriate thing (e.g. the node) back to the top-level of
12422/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012423bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012424 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012425
Nadav Rotema49a02a2011-02-11 19:57:47 +000012426 // Cannot simplify select with vector condition
12427 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12428
Chris Lattner6c14c352005-10-18 06:04:22 +000012429 // If this is a select from two identical things, try to pull the operation
12430 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000012431 if (LHS.getOpcode() != RHS.getOpcode() ||
12432 !LHS.hasOneUse() || !RHS.hasOneUse())
12433 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012434
Chris Lattner254c4452010-09-21 15:46:59 +000012435 // If this is a load and the token chain is identical, replace the select
12436 // of two loads with a load through a select of the address to load from.
12437 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12438 // constants have been dropped into the constant pool.
12439 if (LHS.getOpcode() == ISD::LOAD) {
12440 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12441 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000012442
Chris Lattner254c4452010-09-21 15:46:59 +000012443 // Token chains must be identical.
12444 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000012445 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000012446 LLD->isVolatile() || RLD->isVolatile() ||
12447 // If this is an EXTLOAD, the VT's must match.
12448 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000012449 // If this is an EXTLOAD, the kind of extension must match.
12450 (LLD->getExtensionType() != RLD->getExtensionType() &&
12451 // The only exception is if one of the extensions is anyext.
12452 LLD->getExtensionType() != ISD::EXTLOAD &&
12453 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000012454 // FIXME: this discards src value information. This is
12455 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000012456 // both potential memory locations. Since we are discarding
12457 // src value info, don't do the transformation if the memory
12458 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000012459 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000012460 RLD->getPointerInfo().getAddrSpace() != 0 ||
12461 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12462 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000012463 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012464
Chris Lattnere3267522010-09-21 15:58:55 +000012465 // Check that the select condition doesn't reach either load. If so,
12466 // folding this will induce a cycle into the DAG. If not, this is safe to
12467 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000012468 SDValue Addr;
12469 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000012470 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12471 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12472 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12473 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000012474 // The loads must not depend on one another.
12475 if (LLD->isPredecessorOf(RLD) ||
12476 RLD->isPredecessorOf(LLD))
12477 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012478 Addr = DAG.getSelect(SDLoc(TheSelect),
12479 LLD->getBasePtr().getValueType(),
12480 TheSelect->getOperand(0), LLD->getBasePtr(),
12481 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000012482 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000012483 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12484 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12485
12486 if ((LLD->hasAnyUseOfValue(1) &&
12487 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000012488 (RLD->hasAnyUseOfValue(1) &&
12489 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000012490 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012491
Andrew Trickef9de2a2013-05-25 02:42:55 +000012492 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000012493 LLD->getBasePtr().getValueType(),
12494 TheSelect->getOperand(0),
12495 TheSelect->getOperand(1),
12496 LLD->getBasePtr(), RLD->getBasePtr(),
12497 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000012498 }
12499
Chris Lattnere3267522010-09-21 15:58:55 +000012500 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000012501 // It is safe to replace the two loads if they have different alignments,
12502 // but the new load must be the minimum (most restrictive) alignment of the
12503 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000012504 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000012505 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000012506 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12507 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012508 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000012509 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012510 LLD->getChain(), Addr, MachinePointerInfo(),
12511 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012512 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000012513 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000012514 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12515 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012516 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000012517 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012518 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012519 LLD->getChain(), Addr, MachinePointerInfo(),
12520 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012521 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012522 }
Chris Lattnere3267522010-09-21 15:58:55 +000012523
12524 // Users of the select now use the result of the load.
12525 CombineTo(TheSelect, Load);
12526
12527 // Users of the old loads now use the new load's chain. We know the
12528 // old-load value is dead now.
12529 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12530 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12531 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012532 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012533
Chris Lattner6c14c352005-10-18 06:04:22 +000012534 return false;
12535}
12536
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012537/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012538/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012539SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012540 SDValue N2, SDValue N3,
12541 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012542 // (x ? y : y) -> y.
12543 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012544
Owen Anderson53aa7a92009-08-10 22:56:29 +000012545 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12547 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12548 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012549
12550 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012551 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012552 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012553 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012554 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012555
12556 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012557 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012558 return N2;
12559 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012560 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012561 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012562
Nate Begeman2042aa52005-10-08 00:29:44 +000012563 // Check to see if we can simplify the select into an fabs node
12564 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12565 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012566 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012567 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12568 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12569 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12570 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012571 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012572
Nate Begeman2042aa52005-10-08 00:29:44 +000012573 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12574 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12575 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12576 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012577 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012578 }
12579 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012580
Chris Lattner43d63772009-03-11 05:08:08 +000012581 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12582 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12583 // in it. This is a win when the constant is not otherwise available because
12584 // it replaces two constant pool loads with one. We only do this if the FP
12585 // type is known to be legal, because if it isn't, then we are before legalize
12586 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012587 // messing with soft float) and if the ConstantFP is not legal, because if
12588 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012589 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12590 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12591 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012592 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012593 TargetLowering::Legal &&
12594 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12595 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012596 // If both constants have multiple uses, then we won't need to do an
12597 // extra load, they are likely around in registers for other users.
12598 (TV->hasOneUse() || FV->hasOneUse())) {
12599 Constant *Elts[] = {
12600 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12601 const_cast<ConstantFP*>(TV->getConstantFPValue())
12602 };
Chris Lattner229907c2011-07-18 04:54:35 +000012603 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000012604 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000012605
Chris Lattner43d63772009-03-11 05:08:08 +000012606 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000012607 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000012608 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12609 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000012610 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000012611
12612 // Get the offsets to the 0 and 1 element of the array so that we can
12613 // select between them.
12614 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000012615 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000012616 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000012617
Chris Lattner43d63772009-03-11 05:08:08 +000012618 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000012619 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000012620 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012621 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012622 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12623 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012624 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000012625 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000012626 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012627 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000012628 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000012629 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000012630 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000012631
12632 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012633 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012634
Nate Begeman2042aa52005-10-08 00:29:44 +000012635 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000012636 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000012637 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000012638 (N1C->isNullValue() || // (a < 0) ? b : 0
12639 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000012640 EVT XType = N0.getValueType();
12641 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000012642 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000012643 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000012644 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012645 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12646 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000012647 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000012648 SDValue ShCt = DAG.getConstant(ShCtV,
12649 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012650 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012651 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012652 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012653
Duncan Sands11dd4242008-06-08 20:54:56 +000012654 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012655 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012656 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012657 }
Bill Wendling31b50992009-01-30 23:59:18 +000012658
12659 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012660 }
Bill Wendling31b50992009-01-30 23:59:18 +000012661
Andrew Trickef9de2a2013-05-25 02:42:55 +000012662 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012663 XType, N0,
12664 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012665 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012666 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012667
Duncan Sands11dd4242008-06-08 20:54:56 +000012668 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012669 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012670 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012671 }
Bill Wendling31b50992009-01-30 23:59:18 +000012672
12673 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012674 }
12675 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012676
Owen Anderson3231d132010-09-22 22:58:22 +000012677 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12678 // where y is has a single bit set.
12679 // A plaintext description would be, we can turn the SELECT_CC into an AND
12680 // when the condition can be materialized as an all-ones register. Any
12681 // single bit-test can be materialized as an all-ones register with
12682 // shift-left and shift-right-arith.
12683 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12684 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000012685 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000012686 N2C && N2C->isNullValue()) {
12687 SDValue AndLHS = N0->getOperand(0);
12688 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12689 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12690 // Shift the tested bit over the sign bit.
12691 APInt AndMask = ConstAndRHS->getAPIntValue();
12692 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012693 DAG.getConstant(AndMask.countLeadingZeros(),
12694 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012695 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012696
Owen Anderson3231d132010-09-22 22:58:22 +000012697 // Now arithmetic right shift it all the way over, so the result is either
12698 // all-ones, or zero.
12699 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012700 DAG.getConstant(AndMask.getBitWidth()-1,
12701 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012702 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012703
Owen Anderson3231d132010-09-22 22:58:22 +000012704 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12705 }
12706 }
12707
Nate Begeman6828ed92005-10-10 21:26:48 +000012708 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000012709 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000012710 TLI.getBooleanContents(N0.getValueType()) ==
12711 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012712
Chris Lattnera083ffc2007-04-11 06:50:51 +000012713 // If the caller doesn't want us to simplify this into a zext of a compare,
12714 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012715 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012716 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012717
Nate Begeman6828ed92005-10-10 21:26:48 +000012718 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012719 // NOTE: Don't create a SETCC if it's not legal on this target.
12720 if (!LegalOperations ||
12721 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000012722 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012723 SDValue Temp, SCC;
12724 // cast from setcc result type to select result type
12725 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000012726 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012727 N0, N1, CC);
12728 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000012729 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012730 N2.getValueType());
12731 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000012732 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012733 N2.getValueType(), SCC);
12734 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012735 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12736 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000012737 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012738 }
12739
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012740 AddToWorklist(SCC.getNode());
12741 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012742
12743 if (N2C->getAPIntValue() == 1)
12744 return Temp;
12745
12746 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000012747 return DAG.getNode(
12748 ISD::SHL, DL, N2.getValueType(), Temp,
12749 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12750 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000012751 }
Nate Begeman6828ed92005-10-10 21:26:48 +000012752 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012753
Nate Begeman2042aa52005-10-08 00:29:44 +000012754 // Check to see if this is the equivalent of setcc
12755 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12756 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012757 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012758 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012759 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000012760 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12761 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000012762 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000012763 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000012764 return Res;
12765 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012766
Bill Wendling31b50992009-01-30 23:59:18 +000012767 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012768 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012769 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000012770 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012771 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012772 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000012773 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000012774 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000012775 }
Bill Wendling31b50992009-01-30 23:59:18 +000012776 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012777 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012778 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012779 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000012780 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000012781 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000012782 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000012783 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012784 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000012785 }
Bill Wendling31b50992009-01-30 23:59:18 +000012786 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000012787 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012788 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012789 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012790 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000012791 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000012792 }
12793 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012794
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012795 // Check to see if this is an integer abs.
12796 // select_cc setg[te] X, 0, X, -X ->
12797 // select_cc setgt X, -1, X, -X ->
12798 // select_cc setl[te] X, 0, -X, X ->
12799 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000012800 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012801 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000012802 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012803 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12804 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12805 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12806 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12807 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12808 (N1C->isOne() && CC == ISD::SETLT)) &&
12809 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12810 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12811
Owen Anderson53aa7a92009-08-10 22:56:29 +000012812 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012813 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012814 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012815 N0,
12816 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012817 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012818 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012819 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012820 AddToWorklist(Shift.getNode());
12821 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012822 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000012823 }
12824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012825
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012826 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012827}
12828
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012829/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012830SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012831 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000012832 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012833 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000012834 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000012835 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000012836}
12837
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012838/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000012839/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000012840/// by a magic number.
12841/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012842SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012843 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12844 if (!C)
12845 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012846
12847 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012848 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012849 return SDValue();
12850
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012851 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012852 SDValue S =
12853 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012854
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012855 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012856 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012857 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012858}
12859
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012860/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12861/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000012862SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12863 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12864 if (!C)
12865 return SDValue();
12866
12867 // Avoid division by zero.
12868 if (!C->getAPIntValue())
12869 return SDValue();
12870
12871 std::vector<SDNode *> Built;
12872 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12873
12874 for (SDNode *N : Built)
12875 AddToWorklist(N);
12876 return S;
12877}
12878
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012879/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12880/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000012881/// number.
12882/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012883SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012884 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12885 if (!C)
12886 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012887
12888 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012889 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012890 return SDValue();
12891
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012892 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012893 SDValue S =
12894 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000012895
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012896 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012897 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012898 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012899}
12900
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012901SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12902 if (Level >= AfterLegalizeDAG)
12903 return SDValue();
12904
Sanjay Patelb67bd262014-09-21 15:19:15 +000012905 // Expose the DAG combiner to the target combiner implementations.
12906 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000012907
Sanjay Patelab7f4602014-09-30 20:44:23 +000012908 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000012909 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000012910 if (Iterations) {
12911 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12912 // For the reciprocal, we need to find the zero of the function:
12913 // F(X) = A X - 1 [which has a zero at X = 1/A]
12914 // =>
12915 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12916 // does not require additional intermediate precision]
12917 EVT VT = Op.getValueType();
12918 SDLoc DL(Op);
12919 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012920
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012921 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012922
Sanjay Patelab7f4602014-09-30 20:44:23 +000012923 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12924 for (unsigned i = 0; i < Iterations; ++i) {
12925 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12926 AddToWorklist(NewEst.getNode());
12927
12928 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12929 AddToWorklist(NewEst.getNode());
12930
12931 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12932 AddToWorklist(NewEst.getNode());
12933
12934 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12935 AddToWorklist(Est.getNode());
12936 }
12937 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012938 return Est;
12939 }
12940
12941 return SDValue();
12942}
12943
Sanjay Patel957efc232014-10-24 17:02:16 +000012944/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12945/// For the reciprocal sqrt, we need to find the zero of the function:
12946/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12947/// =>
12948/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12949/// As a result, we precompute A/2 prior to the iteration loop.
12950SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12951 unsigned Iterations) {
12952 EVT VT = Arg.getValueType();
12953 SDLoc DL(Arg);
12954 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012955
Sanjay Patel957efc232014-10-24 17:02:16 +000012956 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12957 // this entire sequence requires only one FP constant.
12958 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12959 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012960
Sanjay Patel957efc232014-10-24 17:02:16 +000012961 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12962 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012963
Sanjay Patel957efc232014-10-24 17:02:16 +000012964 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12965 for (unsigned i = 0; i < Iterations; ++i) {
12966 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12967 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012968
Sanjay Patel957efc232014-10-24 17:02:16 +000012969 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12970 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012971
Sanjay Patel957efc232014-10-24 17:02:16 +000012972 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12973 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012974
Sanjay Patel957efc232014-10-24 17:02:16 +000012975 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12976 AddToWorklist(Est.getNode());
12977 }
12978 return Est;
12979}
12980
12981/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12982/// For the reciprocal sqrt, we need to find the zero of the function:
12983/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12984/// =>
12985/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12986SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12987 unsigned Iterations) {
12988 EVT VT = Arg.getValueType();
12989 SDLoc DL(Arg);
12990 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12991 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12992
12993 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12994 for (unsigned i = 0; i < Iterations; ++i) {
12995 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12996 AddToWorklist(HalfEst.getNode());
12997
12998 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12999 AddToWorklist(Est.getNode());
13000
13001 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13002 AddToWorklist(Est.getNode());
13003
13004 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13005 AddToWorklist(Est.getNode());
13006
13007 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13008 AddToWorklist(Est.getNode());
13009 }
13010 return Est;
13011}
13012
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013013SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13014 if (Level >= AfterLegalizeDAG)
13015 return SDValue();
13016
13017 // Expose the DAG combiner to the target combiner implementations.
13018 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013019 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013020 bool UseOneConstNR = false;
13021 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13022 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013023 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013024 Est = UseOneConstNR ?
13025 BuildRsqrtNROneConst(Op, Est, Iterations) :
13026 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013027 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013028 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013029 }
13030
13031 return SDValue();
13032}
13033
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013034/// Return true if base is a frame index, which is known not to alias with
13035/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013036static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013037 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013038 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013039 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013040
Jim Laskey0463e082006-10-07 23:37:56 +000013041 // If it's an adding a simple constant then integrate the offset.
13042 if (Base.getOpcode() == ISD::ADD) {
13043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13044 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013045 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013046 }
13047 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013048
Nate Begeman18150d52009-09-25 06:05:26 +000013049 // Return the underlying GlobalValue, and update the Offset. Return false
13050 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13051 // by multiple nodes with different offsets.
13052 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13053 GV = G->getGlobal();
13054 Offset += G->getOffset();
13055 return false;
13056 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013057
Nate Begeman18150d52009-09-25 06:05:26 +000013058 // Return the underlying Constant value, and update the Offset. Return false
13059 // for ConstantSDNodes since the same constant pool entry may be represented
13060 // by multiple nodes with different offsets.
13061 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013062 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13063 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013064 Offset += C->getOffset();
13065 return false;
13066 }
Jim Laskey0463e082006-10-07 23:37:56 +000013067 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013068 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013069}
13070
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013071/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013072bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013073 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013074 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013075
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013076 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013077 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013078
Jim Laskey0463e082006-10-07 23:37:56 +000013079 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013080 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013081 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013082 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013083 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013084 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13085 Base1, Offset1, GV1, CV1);
13086 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13087 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013088
Nate Begeman18150d52009-09-25 06:05:26 +000013089 // If they have a same base address then check to see if they overlap.
13090 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013091 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13092 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013093
Owen Anderson272ff942010-09-20 20:39:59 +000013094 // It is possible for different frame indices to alias each other, mostly
13095 // when tail call optimization reuses return address slots for arguments.
13096 // To catch this case, look up the actual index of frame indices to compute
13097 // the real alias relationship.
13098 if (isFrameIndex1 && isFrameIndex2) {
13099 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13100 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13101 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013102 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13103 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013104 }
13105
Wesley Peck527da1b2010-11-23 03:31:01 +000013106 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013107 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013108 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13109 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013110
Nate Begeman879d8f12009-09-15 00:18:30 +000013111 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13112 // compared to the size and offset of the access, we may be able to prove they
13113 // do not alias. This check is conservative for now to catch cases created by
13114 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013115 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13116 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13117 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13118 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13119 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13120 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13121 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013122
Nate Begeman879d8f12009-09-15 00:18:30 +000013123 // There is no overlap between these relatively aligned accesses of similar
13124 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013125 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13126 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013127 return false;
13128 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013129
Eric Christopherf55d4712014-10-08 23:38:39 +000013130 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13131 ? CombinerGlobalAA
13132 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013133#ifndef NDEBUG
13134 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13135 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13136 UseAA = false;
13137#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013138 if (UseAA &&
13139 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013140 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013141 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13142 Op1->getSrcValueOffset());
13143 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13144 Op0->getSrcValueOffset() - MinOffset;
13145 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13146 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013147 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013148 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13149 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013150 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013151 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13152 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013153 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013154 if (AAResult == AliasAnalysis::NoAlias)
13155 return false;
13156 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013157
13158 // Otherwise we have to assume they alias.
13159 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013160}
13161
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013162/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013163/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013164void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013165 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013166 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013167 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013168
Jim Laskeyd07be232006-09-25 16:29:54 +000013169 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013170 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013171
Jim Laskey708d0db2006-10-04 16:53:27 +000013172 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013173 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013174 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013175
Jim Laskey6549d222006-10-05 15:07:25 +000013176 // Look at each chain and determine if it is an alias. If so, add it to the
13177 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013178 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013179 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013180 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013181 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013182
13183 // For TokenFactor nodes, look at each operand and only continue up the
13184 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013185 // find more and revert to original chain since the xform is unlikely to be
13186 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013187 //
13188 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013189 // chain we found before we hit a tokenfactor rather than the original
13190 // chain.
13191 if (Depth > 6 || Aliases.size() == 2) {
13192 Aliases.clear();
13193 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013194 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013195 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013196
Nate Begeman879d8f12009-09-15 00:18:30 +000013197 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013198 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013199 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013200
Jim Laskey6549d222006-10-05 15:07:25 +000013201 switch (Chain.getOpcode()) {
13202 case ISD::EntryToken:
13203 // Entry token is ideal chain operand, but handled in FindBetterChain.
13204 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013205
Jim Laskey6549d222006-10-05 15:07:25 +000013206 case ISD::LOAD:
13207 case ISD::STORE: {
13208 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013209 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13210 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013211
Jim Laskey6549d222006-10-05 15:07:25 +000013212 // If chain is alias then stop here.
13213 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013214 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013215 Aliases.push_back(Chain);
13216 } else {
13217 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013218 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013219 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013220 }
Jim Laskey6549d222006-10-05 15:07:25 +000013221 break;
13222 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013223
Jim Laskey6549d222006-10-05 15:07:25 +000013224 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013225 // We have to check each of the operands of the token factor for "small"
13226 // token factors, so we queue them up. Adding the operands to the queue
13227 // (stack) in reverse order maintains the original order and increases the
13228 // likelihood that getNode will find a matching token factor (CSE.)
13229 if (Chain.getNumOperands() > 16) {
13230 Aliases.push_back(Chain);
13231 break;
13232 }
Jim Laskey6549d222006-10-05 15:07:25 +000013233 for (unsigned n = Chain.getNumOperands(); n;)
13234 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013235 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013236 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013237
Jim Laskey6549d222006-10-05 15:07:25 +000013238 default:
13239 // For all other instructions we will just have to take what we can get.
13240 Aliases.push_back(Chain);
13241 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013242 }
13243 }
Hal Finkel51a98382014-01-24 20:12:02 +000013244
13245 // We need to be careful here to also search for aliases through the
13246 // value operand of a store, etc. Consider the following situation:
13247 // Token1 = ...
13248 // L1 = load Token1, %52
13249 // S1 = store Token1, L1, %51
13250 // L2 = load Token1, %52+8
13251 // S2 = store Token1, L2, %51+8
13252 // Token2 = Token(S1, S2)
13253 // L3 = load Token2, %53
13254 // S3 = store Token2, L3, %52
13255 // L4 = load Token2, %53+8
13256 // S4 = store Token2, L4, %52+8
13257 // If we search for aliases of S3 (which loads address %52), and we look
13258 // only through the chain, then we'll miss the trivial dependence on L1
13259 // (which also loads from %52). We then might change all loads and
13260 // stores to use Token1 as their chain operand, which could result in
13261 // copying %53 into %52 before copying %52 into %51 (which should
13262 // happen first).
13263 //
13264 // The problem is, however, that searching for such data dependencies
13265 // can become expensive, and the cost is not directly related to the
13266 // chain depth. Instead, we'll rule out such configurations here by
13267 // insisting that we've visited all chain users (except for users
13268 // of the original chain, which is not necessary). When doing this,
13269 // we need to look through nodes we don't care about (otherwise, things
13270 // like register copies will interfere with trivial cases).
13271
13272 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013273 for (const SDNode *N : Visited)
13274 if (N != OriginalChain.getNode())
13275 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013276
13277 while (!Worklist.empty()) {
13278 const SDNode *M = Worklist.pop_back_val();
13279
13280 // We have already visited M, and want to make sure we've visited any uses
13281 // of M that we care about. For uses that we've not visisted, and don't
13282 // care about, queue them to the worklist.
13283
13284 for (SDNode::use_iterator UI = M->use_begin(),
13285 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013286 if (UI.getUse().getValueType() == MVT::Other &&
13287 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013288 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13289 // We've not visited this use, and we care about it (it could have an
13290 // ordering dependency with the original node).
13291 Aliases.clear();
13292 Aliases.push_back(OriginalChain);
13293 return;
13294 }
13295
13296 // We've not visited this use, but we don't care about it. Mark it as
13297 // visited and enqueue it to the worklist.
13298 Worklist.push_back(*UI);
13299 }
13300 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013301}
13302
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013303/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13304/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013305SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13306 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013307
Jim Laskey708d0db2006-10-04 16:53:27 +000013308 // Accumulate all the aliases to this node.
13309 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013310
Dan Gohman4298df62011-05-17 22:20:36 +000013311 // If no operands then chain to entry token.
13312 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013313 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013314
13315 // If a single operand then chain to it. We don't need to revisit it.
13316 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013317 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013318
Jim Laskey708d0db2006-10-04 16:53:27 +000013319 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013320 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013321}
13322
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013323/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013324void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013325 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013326 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013327 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013328}