blob: 3a292c5821d34978cd294575eee8bd8f2fdd6cf9 [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"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000021#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#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
Jim Laskey6549d222006-10-05 15:07:25 +000080//------------------------------ DAGCombiner ---------------------------------//
81
Nick Lewycky02d5f772009-10-25 06:33:48 +000082 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000083 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000084 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000085 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000086 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000087 bool LegalOperations;
88 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000089 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000090
Chandler Carruth9a0051c2014-07-23 07:08:53 +000091 /// \brief Worklist of all of the nodes that need to be simplified.
92 ///
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
95 ///
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
99
100 /// \brief Mapping from an SDNode to its position on the worklist.
101 ///
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000106
Jim Laskeydcb2b832006-10-16 20:52:31 +0000107 // AA - Used for DAG load/store alias analysis.
108 AliasAnalysis &AA;
109
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000110 /// AddUsersToWorklist - When an instruction is simplified, add all users of
Nate Begeman21158fc2005-09-01 00:19:25 +0000111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000114 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000115 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000116 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000117 }
118
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000119 /// visit - call the node-specific routine that knows how to fold each
120 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000121 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000122
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000123 public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 /// AddToWorklist - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000125 /// back (next to be processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000126 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000127 // Skip handle nodes as they can't usefully be combined and confuse the
128 // zero-use deletion strategy.
129 if (N->getOpcode() == ISD::HANDLENODE)
130 return;
131
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000132 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
133 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000134 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000135
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000136 /// removeFromWorklist - remove all instances of N from the worklist.
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000137 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000138 void removeFromWorklist(SDNode *N) {
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 auto It = WorklistMap.find(N);
140 if (It == WorklistMap.end())
141 return; // Not in the worklist.
142
143 // Null out the entry rather than erasing it to avoid a linear operation.
144 Worklist[It->second] = nullptr;
145 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000146 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000147
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000148 bool recursivelyDeleteUnusedNodes(SDNode *N);
149
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000150 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000151 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000152
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000153 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000154 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000157 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000158 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000160 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000161 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000162
163 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000164
165 private:
166
Chris Lattner375e1a72006-02-17 21:58:01 +0000167 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000168 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000169 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000170 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000171 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
172 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000173 return SimplifyDemandedBits(Op, Demanded);
174 }
175
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000176 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000177
Chris Lattnerffad2162006-11-11 00:39:41 +0000178 bool CombineToPreIndexedLoadStore(SDNode *N);
179 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000180 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000181
Evan Cheng0abb54d2010-04-24 04:43:44 +0000182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000186 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000187 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000190
Craig Toppere0b71182013-07-13 07:43:40 +0000191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000193 ISD::NodeType ExtType);
194
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000198 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000199
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
202 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000206 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000212 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000213 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000214 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000232 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000236 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000237 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000243 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000251 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000256 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000286
Matt Arsenault985b9de2014-03-17 18:58:01 +0000287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000288
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000293 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000294 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000296 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000297
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
299 SDValue &CC) const;
300 bool isOneUseSetCC(SDValue N) const;
301
Scott Michelcf0da6c2009-02-17 22:15:04 +0000302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000303 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000307 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000308 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000309 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
310 bool DemandHighBits = true);
311 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000312 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
313 SDValue InnerPos, SDValue InnerNeg,
314 unsigned PosOpcode, unsigned NegOpcode,
315 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000318 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000319 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000320 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000321 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000323 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000324
Jim Laskey708d0db2006-10-04 16:53:27 +0000325 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
326 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000327 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000328 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000329
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000330 /// isAlias - Return true if there is any possibility that the two addresses
331 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000333
Jim Laskeyd07be232006-09-25 16:29:54 +0000334 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000335 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000336 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000337
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000338 /// Merge consecutive store operations into a wide store.
339 /// This optimization uses wide integers or vectors when possible.
340 /// \return True if some memory operations were changed.
341 bool MergeConsecutiveStores(StoreSDNode *N);
342
Adam Nemet67483892014-03-04 23:28:31 +0000343 /// \brief Try to transform a truncation where C is a constant:
344 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
345 ///
346 /// \p N needs to be a truncation and its first operand an AND. Other
347 /// requirements are checked by the function (e.g. that trunc is
348 /// single-use) and if missed an empty SDValue is returned.
349 SDValue distributeTruncateThroughAnd(SDNode *N);
350
Chris Lattner4041ab62010-04-15 04:48:01 +0000351 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000352 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000353 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
354 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
355 AttributeSet FnAttrs =
356 DAG.getMachineFunction().getFunction()->getAttributes();
357 ForCodeSize =
358 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
359 Attribute::OptimizeForSize) ||
360 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
361 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000362
Nate Begeman21158fc2005-09-01 00:19:25 +0000363 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000364 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000365
Chris Lattner4041ab62010-04-15 04:48:01 +0000366 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000367
Chris Lattner4041ab62010-04-15 04:48:01 +0000368 /// getShiftAmountTy - Returns a type large enough to hold any valid
369 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000370 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000371 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
372 if (LHSTy.isVector())
373 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000374 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
375 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000376 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000377
Chris Lattner4041ab62010-04-15 04:48:01 +0000378 /// isTypeLegal - This method returns true if we are running before type
379 /// legalization or if the specified VT is legal.
380 bool isTypeLegal(const EVT &VT) {
381 if (!LegalTypes) return true;
382 return TLI.isTypeLegal(VT);
383 }
Matt Arsenault758659232013-05-18 00:21:46 +0000384
385 /// getSetCCResultType - Convenience wrapper around
386 /// TargetLowering::getSetCCResultType
387 EVT getSetCCResultType(EVT VT) const {
388 return TLI.getSetCCResultType(*DAG.getContext(), VT);
389 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000390 };
391}
392
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000393
394namespace {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000395/// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000396/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000397class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000398 DAGCombiner &DC;
399public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000400 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000401 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000402
Craig Topper7b883b32014-03-08 06:31:39 +0000403 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000404 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000405 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000406};
407}
408
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000409//===----------------------------------------------------------------------===//
410// TargetLowering::DAGCombinerInfo implementation
411//===----------------------------------------------------------------------===//
412
413void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000414 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000415}
416
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000417void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000418 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000419}
420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000421SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000422CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000424}
425
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000426SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000427CombineTo(SDNode *N, SDValue Res, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000429}
430
431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000432SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000433CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
434 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000435}
436
Dan Gohmane58ab792009-01-29 01:59:02 +0000437void TargetLowering::DAGCombinerInfo::
438CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
439 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
440}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000441
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000443// Helper Functions
444//===----------------------------------------------------------------------===//
445
446/// isNegatibleForFree - Return 1 if we can compute the negated form of the
447/// specified expression for the same cost as the expression itself, or 2 if we
448/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000449static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000450 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000451 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000452 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000453 // fneg is removable even if it has multiple uses.
454 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000455
Chris Lattnere49c9742007-05-14 22:04:50 +0000456 // Don't allow anything with multiple uses.
457 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000458
Chris Lattner46980832007-05-25 02:19:06 +0000459 // Don't recurse exponentially.
460 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000461
Chris Lattnere49c9742007-05-14 22:04:50 +0000462 switch (Op.getOpcode()) {
463 default: return false;
464 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000465 // Don't invert constant FP values after legalize. The negated constant
466 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000467 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000468 case ISD::FADD:
469 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000470 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000471
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000472 // After operation legalization, it might not be legal to create new FSUBs.
473 if (LegalOperations &&
474 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
475 return 0;
476
Craig Topper03f39772012-09-09 22:58:45 +0000477 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000480 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000481 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000483 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000484 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000485 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000486 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000487
Bill Wendling6fbf5492009-01-30 23:10:18 +0000488 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000490
Chris Lattnere49c9742007-05-14 22:04:50 +0000491 case ISD::FMUL:
492 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Bill Wendling6fbf5492009-01-30 23:10:18 +0000495 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000496 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
497 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000499
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000500 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Chris Lattnere49c9742007-05-14 22:04:50 +0000503 case ISD::FP_EXTEND:
504 case ISD::FP_ROUND:
505 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000506 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000507 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000508 }
509}
510
511/// GetNegatedExpression - If isNegatibleForFree returns true, this function
512/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000513static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000514 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000515 // fneg is removable even if it has multiple uses.
516 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000517
Chris Lattnere49c9742007-05-14 22:04:50 +0000518 // Don't allow anything with multiple uses.
519 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Chris Lattner46980832007-05-25 02:19:06 +0000521 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000523 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000524 case ISD::ConstantFP: {
525 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 V.changeSign();
527 return DAG.getConstantFP(V, Op.getValueType());
528 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 case ISD::FADD:
530 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000531 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Bill Wendling6fbf5492009-01-30 23:10:18 +0000533 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000534 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000535 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000536 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000537 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000538 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000539 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000541 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000542 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000543 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000544 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 Op.getOperand(0));
546 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000547 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000548 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000549
Bill Wendling6fbf5492009-01-30 23:10:18 +0000550 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000551 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000552 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000553 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000554
Bill Wendling6fbf5492009-01-30 23:10:18 +0000555 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000557 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000558
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 case ISD::FMUL:
560 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000561 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Bill Wendling6fbf5492009-01-30 23:10:18 +0000563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000564 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000565 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000566 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000568 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000569 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000570 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000571
Bill Wendling6fbf5492009-01-30 23:10:18 +0000572 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000573 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000574 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000575 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000577
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000579 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000580 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000581 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000582 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000583 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000584 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000586 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000587 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000588 }
589}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000590
Nate Begeman2504fe22005-09-01 23:24:04 +0000591// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000592// that selects between the target values used for true and false, making it
593// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
594// the appropriate nodes based on the type of node we are checking. This
595// simplifies life a bit for the callers.
596bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
597 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000598 if (N.getOpcode() == ISD::SETCC) {
599 LHS = N.getOperand(0);
600 RHS = N.getOperand(1);
601 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000602 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000603 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000604
605 if (N.getOpcode() != ISD::SELECT_CC ||
606 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
607 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
608 return false;
609
610 LHS = N.getOperand(0);
611 RHS = N.getOperand(1);
612 CC = N.getOperand(4);
613 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000614}
615
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000616// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
617// one use. If this is true, it allows the users to invert the operation for
618// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000619bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000620 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000621 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000622 return true;
623 return false;
624}
625
Matt Arsenault985b9de2014-03-17 18:58:01 +0000626/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
627/// elements are all the same constant or undefined.
628static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
629 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
630 if (!C)
631 return false;
632
633 APInt SplatUndef;
634 unsigned SplatBitSize;
635 bool HasAnyUndefs;
636 EVT EltVT = N->getValueType(0).getVectorElementType();
637 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
638 HasAnyUndefs) &&
639 EltVT.getSizeInBits() >= SplatBitSize);
640}
641
642// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000643static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
644 if (isa<ConstantSDNode>(N))
645 return N.getNode();
646 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
647 if(BV && BV->isConstant())
648 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000649 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000650}
651
Matt Arsenault985b9de2014-03-17 18:58:01 +0000652// \brief Returns the SDNode if it is a constant splat BuildVector or constant
653// int.
654static ConstantSDNode *isConstOrConstSplat(SDValue N) {
655 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
656 return CN;
657
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000658 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000659 BitVector UndefElements;
660 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000661
662 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000663 // FIXME: We blindly ignore splats which include undef which is overly
664 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000665 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000666 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000667 return CN;
668 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000669
670 return nullptr;
671}
672
Andrew Trickef9de2a2013-05-25 02:42:55 +0000673SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000674 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000675 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000676 if (N0.getOpcode() == Opc) {
677 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
678 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
679 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
680 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
681 if (!OpNode.getNode())
682 return SDValue();
683 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000684 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000685 if (N0.hasOneUse()) {
686 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
687 // use
688 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
689 if (!OpNode.getNode())
690 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000691 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000692 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000693 }
694 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000695 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000696
Juergen Ributzka68402822014-01-13 21:49:25 +0000697 if (N1.getOpcode() == Opc) {
698 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
699 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
700 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
701 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
702 if (!OpNode.getNode())
703 return SDValue();
704 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
705 }
706 if (N1.hasOneUse()) {
707 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
708 // use
709 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
710 if (!OpNode.getNode())
711 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000712 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000713 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
714 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000715 }
716 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000718 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000719}
720
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000721SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
722 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000723 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
724 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000725 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000726 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000727 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000728 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000729 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000730 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000731 assert((!To[i].getNode() ||
732 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000733 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000734 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000735 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000736 if (AddTo) {
737 // Push the new nodes and any users onto the worklist
738 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000739 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000740 AddToWorklist(To[i].getNode());
741 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000742 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000743 }
744 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000745
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000746 // Finally, if the node is now dead, remove it from the graph. The node
747 // may not be dead if the replacement process recursively simplified to
748 // something else needing this node.
749 if (N->use_empty()) {
750 // Nodes can be reintroduced into the worklist. Make sure we do not
751 // process a node that has been replaced.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000752 removeFromWorklist(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000753
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000754 // Finally, since the node is now dead, remove it from the graph.
755 DAG.DeleteNode(N);
756 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000757 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000758}
759
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000760void DAGCombiner::
761CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000762 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000763 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000764 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000765 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000766
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000767 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000768 AddToWorklist(TLO.New.getNode());
769 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000770
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000771 // Finally, if the node is now dead, remove it from the graph. The node
772 // may not be dead if the replacement process recursively simplified to
773 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000774 if (TLO.Old.getNode()->use_empty()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000775 removeFromWorklist(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000776
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000777 // If the operands of this node are only used by the node, they will now
778 // be dead. Make sure to visit them first to delete dead nodes early.
Hal Finkel2c77fe52014-05-28 15:33:19 +0000779 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
780 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000781 AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
Hal Finkel2c77fe52014-05-28 15:33:19 +0000782
Gabor Greiff304a7a2008-08-28 21:40:38 +0000783 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000784 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000785}
786
787/// SimplifyDemandedBits - Check the specified integer node value to see if
788/// it can be simplified or if things it uses can be simplified by bit
789/// propagation. If so, return true.
790bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000791 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000792 APInt KnownZero, KnownOne;
793 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
794 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000795
Dan Gohmane58ab792009-01-29 01:59:02 +0000796 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000797 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000798
Dan Gohmane58ab792009-01-29 01:59:02 +0000799 // Replace the old value with the new one.
800 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000801 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000802 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000803 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000804 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000805 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000806
Dan Gohmane58ab792009-01-29 01:59:02 +0000807 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000808 return true;
809}
810
Evan Cheng0abb54d2010-04-24 04:43:44 +0000811void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000812 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000813 EVT VT = Load->getValueType(0);
814 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000815
Evan Cheng0abb54d2010-04-24 04:43:44 +0000816 DEBUG(dbgs() << "\nReplacing.9 ";
817 Load->dump(&DAG);
818 dbgs() << "\nWith: ";
819 Trunc.getNode()->dump(&DAG);
820 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000821 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000822 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
823 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000824 removeFromWorklist(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000825 DAG.DeleteNode(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000826 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000827}
828
829SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
830 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000831 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000832 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000833 EVT MemVT = LD->getMemoryVT();
834 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000835 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000836 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000837 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000838 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000839 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000840 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000841 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000842 }
843
Evan Chenge19aa5c2010-04-19 19:29:22 +0000844 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000845 switch (Opc) {
846 default: break;
847 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000848 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000849 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000850 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000851 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000852 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000853 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000854 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000855 case ISD::Constant: {
856 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000857 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000858 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000859 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000860 }
861
862 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000864 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000865}
866
Evan Cheng0abb54d2010-04-24 04:43:44 +0000867SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000868 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
869 return SDValue();
870 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000871 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872 bool Replace = false;
873 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000874 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000876 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000877
878 if (Replace)
879 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
880 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000881 DAG.getValueType(OldVT));
882}
883
Evan Cheng0abb54d2010-04-24 04:43:44 +0000884SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000885 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000886 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000887 bool Replace = false;
888 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000889 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000890 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000891 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892
893 if (Replace)
894 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
895 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000896}
897
Evan Chengaf56fac2010-04-16 06:14:10 +0000898/// PromoteIntBinOp - Promote the specified integer binary operation if the
899/// target indicates it is beneficial. e.g. On x86, it's usually better to
900/// promote i16 operations to i32 since i16 instructions are longer.
901SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
902 if (!LegalOperations)
903 return SDValue();
904
905 EVT VT = Op.getValueType();
906 if (VT.isVector() || !VT.isInteger())
907 return SDValue();
908
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000909 // If operation type is 'undesirable', e.g. i16 on x86, consider
910 // promoting it.
911 unsigned Opc = Op.getOpcode();
912 if (TLI.isTypeDesirableForOp(Opc, VT))
913 return SDValue();
914
Evan Chengaf56fac2010-04-16 06:14:10 +0000915 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000916 // Consult target whether it is a good idea to promote this operation and
917 // what's the right type to promote it to.
918 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000919 assert(PVT != VT && "Don't know what type to promote to!");
920
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921 bool Replace0 = false;
922 SDValue N0 = Op.getOperand(0);
923 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000924 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000925 return SDValue();
926
Evan Cheng0abb54d2010-04-24 04:43:44 +0000927 bool Replace1 = false;
928 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000929 SDValue NN1;
930 if (N0 == N1)
931 NN1 = NN0;
932 else {
933 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000934 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000935 return SDValue();
936 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000937
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000938 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000939 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000940 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000941
942 if (Replace0)
943 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
944 if (Replace1)
945 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000946
Evan Chenge8136902010-04-27 19:48:13 +0000947 DEBUG(dbgs() << "\nPromoting ";
948 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000949 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000950 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000951 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000952 }
953 return SDValue();
954}
955
956/// PromoteIntShiftOp - Promote the specified integer shift operation if the
957/// target indicates it is beneficial. e.g. On x86, it's usually better to
958/// promote i16 operations to i32 since i16 instructions are longer.
959SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
960 if (!LegalOperations)
961 return SDValue();
962
963 EVT VT = Op.getValueType();
964 if (VT.isVector() || !VT.isInteger())
965 return SDValue();
966
967 // If operation type is 'undesirable', e.g. i16 on x86, consider
968 // promoting it.
969 unsigned Opc = Op.getOpcode();
970 if (TLI.isTypeDesirableForOp(Opc, VT))
971 return SDValue();
972
973 EVT PVT = VT;
974 // Consult target whether it is a good idea to promote this operation and
975 // what's the right type to promote it to.
976 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
977 assert(PVT != VT && "Don't know what type to promote to!");
978
Evan Cheng0abb54d2010-04-24 04:43:44 +0000979 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000980 SDValue N0 = Op.getOperand(0);
981 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000982 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000983 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000985 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000986 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000987 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000988 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000989
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000990 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000991 if (Replace)
992 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000993
Evan Chenge8136902010-04-27 19:48:13 +0000994 DEBUG(dbgs() << "\nPromoting ";
995 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000996 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000997 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000998 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000999 }
1000 return SDValue();
1001}
1002
Evan Chenge19aa5c2010-04-19 19:29:22 +00001003SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1004 if (!LegalOperations)
1005 return SDValue();
1006
1007 EVT VT = Op.getValueType();
1008 if (VT.isVector() || !VT.isInteger())
1009 return SDValue();
1010
1011 // If operation type is 'undesirable', e.g. i16 on x86, consider
1012 // promoting it.
1013 unsigned Opc = Op.getOpcode();
1014 if (TLI.isTypeDesirableForOp(Opc, VT))
1015 return SDValue();
1016
1017 EVT PVT = VT;
1018 // Consult target whether it is a good idea to promote this operation and
1019 // what's the right type to promote it to.
1020 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021 assert(PVT != VT && "Don't know what type to promote to!");
1022 // fold (aext (aext x)) -> (aext x)
1023 // fold (aext (zext x)) -> (zext x)
1024 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001025 DEBUG(dbgs() << "\nPromoting ";
1026 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001027 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001028 }
1029 return SDValue();
1030}
1031
1032bool DAGCombiner::PromoteLoad(SDValue Op) {
1033 if (!LegalOperations)
1034 return false;
1035
1036 EVT VT = Op.getValueType();
1037 if (VT.isVector() || !VT.isInteger())
1038 return false;
1039
1040 // If operation type is 'undesirable', e.g. i16 on x86, consider
1041 // promoting it.
1042 unsigned Opc = Op.getOpcode();
1043 if (TLI.isTypeDesirableForOp(Opc, VT))
1044 return false;
1045
1046 EVT PVT = VT;
1047 // Consult target whether it is a good idea to promote this operation and
1048 // what's the right type to promote it to.
1049 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1050 assert(PVT != VT && "Don't know what type to promote to!");
1051
Andrew Trickef9de2a2013-05-25 02:42:55 +00001052 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001053 SDNode *N = Op.getNode();
1054 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001055 EVT MemVT = LD->getMemoryVT();
1056 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001057 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001058 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001059 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001060 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001061 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001062 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001063 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1064
Evan Cheng0abb54d2010-04-24 04:43:44 +00001065 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001066 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001067 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 Result.getNode()->dump(&DAG);
1069 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001070 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1072 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001073 removeFromWorklist(N);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001074 DAG.DeleteNode(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001075 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001076 return true;
1077 }
1078 return false;
1079}
1080
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001081/// \brief Recursively delete a node which has no uses and any operands for
1082/// which it is the only use.
1083///
1084/// Note that this both deletes the nodes and removes them from the worklist.
1085/// It also adds any nodes who have had a user deleted to the worklist as they
1086/// may now have only one use and subject to other combines.
1087bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1088 if (!N->use_empty())
1089 return false;
1090
1091 SmallSetVector<SDNode *, 16> Nodes;
1092 Nodes.insert(N);
1093 do {
1094 N = Nodes.pop_back_val();
1095 if (!N)
1096 continue;
1097
1098 if (N->use_empty()) {
1099 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1100 Nodes.insert(N->getOperand(i).getNode());
1101
1102 removeFromWorklist(N);
1103 DAG.DeleteNode(N);
1104 } else {
1105 AddToWorklist(N);
1106 }
1107 } while (!Nodes.empty());
1108 return true;
1109}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001110
Chris Lattnere49c9742007-05-14 22:04:50 +00001111//===----------------------------------------------------------------------===//
1112// Main DAG Combiner implementation
1113//===----------------------------------------------------------------------===//
1114
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001115void DAGCombiner::Run(CombineLevel AtLevel) {
1116 // set the instance variables, so that the various visit routines may use it.
1117 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001118 LegalOperations = Level >= AfterLegalizeVectorOps;
1119 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001120
Evan Cheng5e7658c2008-08-29 22:21:44 +00001121 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001122 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1123 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001124 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001125
Evan Cheng5e7658c2008-08-29 22:21:44 +00001126 // Create a dummy node (which is not added to allnodes), that adds a reference
1127 // to the root node, preventing it from being deleted, and tracking any
1128 // changes of the root.
1129 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001130
Jim Laskeye7d2c242006-10-17 19:33:52 +00001131 // The root of the dag may dangle to deleted nodes until the dag combiner is
1132 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001133 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001134
James Molloy67b6b112012-02-16 09:17:04 +00001135 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001136 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001137 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001138 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001139 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001140 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001141 N = Worklist.pop_back_val();
1142 } while (!N);
1143
1144 bool GoodWorklistEntry = WorklistMap.erase(N);
1145 (void)GoodWorklistEntry;
1146 assert(GoodWorklistEntry &&
1147 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001148
Evan Cheng5e7658c2008-08-29 22:21:44 +00001149 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1150 // N is deleted from the DAG, since they too may now be dead or may have a
1151 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001152 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001153 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001154
1155 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001156
Evan Cheng5e7658c2008-08-29 22:21:44 +00001157 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001158
Craig Topperc0196b12014-04-14 00:51:57 +00001159 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001161
Evan Cheng5e7658c2008-08-29 22:21:44 +00001162 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001163
Evan Cheng5e7658c2008-08-29 22:21:44 +00001164 // If we get back the same node we passed in, rather than a new node or
1165 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001166 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001167 // mechanics for us, we have no work to do in this case.
1168 if (RV.getNode() == N)
1169 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001170
Evan Cheng5e7658c2008-08-29 22:21:44 +00001171 assert(N->getOpcode() != ISD::DELETED_NODE &&
1172 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1173 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001174
Wesley Peck527da1b2010-11-23 03:31:01 +00001175 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001176 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001177 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001178 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001179 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001180
Devang Patelefec7712011-05-23 22:04:42 +00001181 // Transfer debug value.
1182 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001183 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001184 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001185 else {
1186 assert(N->getValueType(0) == RV.getValueType() &&
1187 N->getNumValues() == 1 && "Type mismatch");
1188 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001189 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001190 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001191
Evan Cheng5e7658c2008-08-29 22:21:44 +00001192 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001193 AddToWorklist(RV.getNode());
1194 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001195
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001196 // Finally, if the node is now dead, remove it from the graph. The node
1197 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001198 // something else needing this node. This will also take care of adding any
1199 // operands which have lost a user to the worklist.
1200 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001201 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001202
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001203 // If the root changed (e.g. it was a dead load, update the root).
1204 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001205 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001206}
1207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001208SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001209 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001210 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001211 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001212 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001213 case ISD::ADD: return visitADD(N);
1214 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001215 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001216 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001217 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001218 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001219 case ISD::MUL: return visitMUL(N);
1220 case ISD::SDIV: return visitSDIV(N);
1221 case ISD::UDIV: return visitUDIV(N);
1222 case ISD::SREM: return visitSREM(N);
1223 case ISD::UREM: return visitUREM(N);
1224 case ISD::MULHU: return visitMULHU(N);
1225 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001226 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1227 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001228 case ISD::SMULO: return visitSMULO(N);
1229 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001230 case ISD::SDIVREM: return visitSDIVREM(N);
1231 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001232 case ISD::AND: return visitAND(N);
1233 case ISD::OR: return visitOR(N);
1234 case ISD::XOR: return visitXOR(N);
1235 case ISD::SHL: return visitSHL(N);
1236 case ISD::SRA: return visitSRA(N);
1237 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001238 case ISD::ROTR:
1239 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001240 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001241 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001242 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001243 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001244 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001245 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001246 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001247 case ISD::SELECT_CC: return visitSELECT_CC(N);
1248 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001249 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1250 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001251 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001252 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1253 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001254 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001255 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001256 case ISD::FADD: return visitFADD(N);
1257 case ISD::FSUB: return visitFSUB(N);
1258 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001259 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001260 case ISD::FDIV: return visitFDIV(N);
1261 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001262 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001263 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1264 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1265 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1266 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1267 case ISD::FP_ROUND: return visitFP_ROUND(N);
1268 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1269 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1270 case ISD::FNEG: return visitFNEG(N);
1271 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001272 case ISD::FFLOOR: return visitFFLOOR(N);
1273 case ISD::FCEIL: return visitFCEIL(N);
1274 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001275 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001276 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001277 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001278 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001279 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001280 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001281 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1282 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001283 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001284 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001285 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001286 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001287 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001288}
1289
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001290SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001291 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001292
1293 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001294 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001295 assert(N->getOpcode() != ISD::DELETED_NODE &&
1296 "Node was deleted but visit returned NULL!");
1297
1298 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1299 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1300
1301 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001302 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001303 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001304
1305 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1306 }
1307 }
1308
Evan Chengf1005572010-04-28 07:10:39 +00001309 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001310 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001311 switch (N->getOpcode()) {
1312 default: break;
1313 case ISD::ADD:
1314 case ISD::SUB:
1315 case ISD::MUL:
1316 case ISD::AND:
1317 case ISD::OR:
1318 case ISD::XOR:
1319 RV = PromoteIntBinOp(SDValue(N, 0));
1320 break;
1321 case ISD::SHL:
1322 case ISD::SRA:
1323 case ISD::SRL:
1324 RV = PromoteIntShiftOp(SDValue(N, 0));
1325 break;
1326 case ISD::SIGN_EXTEND:
1327 case ISD::ZERO_EXTEND:
1328 case ISD::ANY_EXTEND:
1329 RV = PromoteExtend(SDValue(N, 0));
1330 break;
1331 case ISD::LOAD:
1332 if (PromoteLoad(SDValue(N, 0)))
1333 RV = SDValue(N, 0);
1334 break;
1335 }
1336 }
1337
Scott Michelcf0da6c2009-02-17 22:15:04 +00001338 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001339 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001340 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001341 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342 SDValue N0 = N->getOperand(0);
1343 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001344
Evan Cheng31604a62008-03-22 01:55:50 +00001345 // Constant operands are canonicalized to RHS.
1346 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001347 SDValue Ops[] = {N1, N0};
1348 SDNode *CSENode;
1349 if (const BinaryWithFlagsSDNode *BinNode =
1350 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1351 CSENode = DAG.getNodeIfExists(
1352 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1353 BinNode->hasNoSignedWrap(), BinNode->isExact());
1354 } else {
1355 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1356 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001357 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001358 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001359 }
1360 }
1361
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001362 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001363}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001364
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001365/// getInputChainForNode - Given a node, return its input chain if it has one,
1366/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001367static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001368 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001369 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001370 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001371 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001372 return N->getOperand(NumOps-1);
1373 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001374 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001375 return N->getOperand(i);
1376 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001377 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001378}
1379
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001380SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001381 // If N has two operands, where one has an input chain equal to the other,
1382 // the 'other' chain is redundant.
1383 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001384 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001385 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001386 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001387 return N->getOperand(1);
1388 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001389
Chris Lattner48fb92f2007-05-16 06:37:59 +00001390 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001391 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001392 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001393 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001394
Jim Laskey708d0db2006-10-04 16:53:27 +00001395 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001396 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001397
Jim Laskey0463e082006-10-07 23:37:56 +00001398 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001399 // encountered.
1400 for (unsigned i = 0; i < TFs.size(); ++i) {
1401 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001402
Jim Laskey708d0db2006-10-04 16:53:27 +00001403 // Check each of the operands.
1404 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001405 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001406
Jim Laskey708d0db2006-10-04 16:53:27 +00001407 switch (Op.getOpcode()) {
1408 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001409 // Entry tokens don't need to be added to the list. They are
1410 // rededundant.
1411 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001412 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001413
Jim Laskey708d0db2006-10-04 16:53:27 +00001414 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001415 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001416 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001417 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001418 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001419 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001420 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001421 Changed = true;
1422 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001423 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001424 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001425
Jim Laskey708d0db2006-10-04 16:53:27 +00001426 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001427 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001428 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001429 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001430 else
1431 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001432 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001433 }
1434 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001435 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001437 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001438
1439 // If we've change things around then replace token factor.
1440 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001441 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001442 // The entry token is the only possible outcome.
1443 Result = DAG.getEntryNode();
1444 } else {
1445 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001446 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001447 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001448
Jim Laskeydcf983c2006-10-13 23:32:28 +00001449 // Don't add users to work list.
1450 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001451 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001452
Jim Laskey708d0db2006-10-04 16:53:27 +00001453 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001454}
1455
Chris Lattneree322b42008-02-13 07:25:05 +00001456/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001457SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001458 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001459 // Replacing results may cause a different MERGE_VALUES to suddenly
1460 // be CSE'd with N, and carry its uses with it. Iterate until no
1461 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001462 // First add the users of this node to the work list so that they
1463 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001464 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001465 do {
1466 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001467 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001468 } while (!N->use_empty());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001469 removeFromWorklist(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001470 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001471 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001472}
1473
Evan Cheng92011002007-01-19 17:51:44 +00001474static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001475SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001476 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001477 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001478 SDValue N00 = N0.getOperand(0);
1479 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001480 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001481
Gabor Greiff304a7a2008-08-28 21:40:38 +00001482 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001483 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001484 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001485 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1486 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001487 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001488 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001489 N00.getOperand(1), N01));
1490 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001491 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001492
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001493 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001494}
1495
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001496SDValue DAGCombiner::visitADD(SDNode *N) {
1497 SDValue N0 = N->getOperand(0);
1498 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001499 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1500 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001501 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001502
1503 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001504 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001505 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001506 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001507
1508 // fold (add x, 0) -> x, vector edition
1509 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1510 return N0;
1511 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1512 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001513 }
Bill Wendling0864a752008-12-10 22:36:00 +00001514
Dan Gohman06563a82007-07-03 14:03:57 +00001515 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001516 if (N0.getOpcode() == ISD::UNDEF)
1517 return N0;
1518 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001519 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001520 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001521 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001522 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001523 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001524 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001525 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001526 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001527 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001528 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001529 // fold (add Sym, c) -> Sym+c
1530 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001531 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001532 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001533 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001534 GA->getOffset() +
1535 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001536 // fold ((c1-A)+c2) -> (c1+c2)-A
1537 if (N1C && N0.getOpcode() == ISD::SUB)
1538 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001539 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001540 DAG.getConstant(N1C->getAPIntValue()+
1541 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001542 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001543 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001544 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001545 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001546 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001547 // fold ((0-A) + B) -> B-A
1548 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1549 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001551 // fold (A + (0-B)) -> A-B
1552 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1553 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001554 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001555 // fold (A+(B-A)) -> B
1556 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001557 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001558 // fold ((B-A)+A) -> B
1559 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1560 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001561 // fold (A+(B-(A+C))) to (B-C)
1562 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001563 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001564 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001565 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001566 // fold (A+(B-(C+A))) to (B-C)
1567 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001568 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001569 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001570 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001571 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001572 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1573 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001574 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001575 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001576 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001577
Dale Johannesen8c766702008-12-02 01:30:54 +00001578 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1579 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1580 SDValue N00 = N0.getOperand(0);
1581 SDValue N01 = N0.getOperand(1);
1582 SDValue N10 = N1.getOperand(0);
1583 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001584
1585 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001586 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1587 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1588 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001589 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001590
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001591 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1592 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001593
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001594 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001595 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001596 APInt LHSZero, LHSOne;
1597 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001598 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001599
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001600 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001601 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001602
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001603 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1604 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001605 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1606 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1607 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1608 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001609 }
1610 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001611
Evan Cheng92011002007-01-19 17:51:44 +00001612 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001613 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001614 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001615 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001616 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001617 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001618 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001619 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001620 }
1621
Dan Gohman954f4902010-01-19 23:30:49 +00001622 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1623 if (N1.getOpcode() == ISD::SHL &&
1624 N1.getOperand(0).getOpcode() == ISD::SUB)
1625 if (ConstantSDNode *C =
1626 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1627 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001628 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1629 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001630 N1.getOperand(0).getOperand(1),
1631 N1.getOperand(1)));
1632 if (N0.getOpcode() == ISD::SHL &&
1633 N0.getOperand(0).getOpcode() == ISD::SUB)
1634 if (ConstantSDNode *C =
1635 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1636 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001637 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1638 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001639 N0.getOperand(0).getOperand(1),
1640 N0.getOperand(1)));
1641
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001642 if (N1.getOpcode() == ISD::AND) {
1643 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001644 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001645 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1646 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001647
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001648 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1649 // and similar xforms where the inner op is either ~0 or 0.
1650 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001651 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001652 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1653 }
1654 }
1655
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001656 // add (sext i1), X -> sub X, (zext i1)
1657 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1658 N0.getOperand(0).getValueType() == MVT::i1 &&
1659 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001660 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001661 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1662 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1663 }
1664
Evan Chengf1005572010-04-28 07:10:39 +00001665 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001666}
1667
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001668SDValue DAGCombiner::visitADDC(SDNode *N) {
1669 SDValue N0 = N->getOperand(0);
1670 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001671 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001673 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001674
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001675 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001676 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001677 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001678 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001679 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001680
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001681 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001682 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001683 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001684
Chris Lattner47206662007-03-04 20:40:38 +00001685 // fold (addc x, 0) -> x + no carry out
1686 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001687 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001688 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001689
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001690 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001691 APInt LHSZero, LHSOne;
1692 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001693 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001694
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001695 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001696 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001697
Chris Lattner47206662007-03-04 20:40:38 +00001698 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1699 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001700 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001701 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001702 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001703 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001704 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001705
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001706 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001707}
1708
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001709SDValue DAGCombiner::visitADDE(SDNode *N) {
1710 SDValue N0 = N->getOperand(0);
1711 SDValue N1 = N->getOperand(1);
1712 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001713 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001715
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001716 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001717 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001718 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001719 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001720
Chris Lattner47206662007-03-04 20:40:38 +00001721 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001722 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001724
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001725 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001726}
1727
Eric Christophere5ca1e02011-02-16 04:50:12 +00001728// Since it may not be valid to emit a fold to zero for vector initializers
1729// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001730static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001731 SelectionDAG &DAG,
1732 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001733 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001734 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001735 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1736 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001737 return SDValue();
1738}
1739
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001740SDValue DAGCombiner::visitSUB(SDNode *N) {
1741 SDValue N0 = N->getOperand(0);
1742 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001745 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001746 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001747 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001748
Dan Gohmana8665142007-06-25 16:23:39 +00001749 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001750 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001751 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001752 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001753
1754 // fold (sub x, 0) -> x, vector edition
1755 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1756 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001757 }
Bill Wendling0864a752008-12-10 22:36:00 +00001758
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001759 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001760 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001761 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001762 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001763 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001764 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001765 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001766 // fold (sub x, c) -> (add x, -c)
1767 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001768 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001769 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001770 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1771 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001773 // fold A-(A-B) -> B
1774 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1775 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001776 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001777 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001778 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001779 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001780 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001781 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001782 // fold C2-(A+C1) -> (C2-C1)-A
1783 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001784 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1785 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001787 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001788 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001789 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001790 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001791 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1792 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001793 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001794 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001795 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001796 // fold ((A+(C+B))-B) -> A+C
1797 if (N0.getOpcode() == ISD::ADD &&
1798 N0.getOperand(1).getOpcode() == ISD::ADD &&
1799 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001800 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001801 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001802 // fold ((A-(B-C))-C) -> A-B
1803 if (N0.getOpcode() == ISD::SUB &&
1804 N0.getOperand(1).getOpcode() == ISD::SUB &&
1805 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001807 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001808
Dan Gohman06563a82007-07-03 14:03:57 +00001809 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001810 if (N0.getOpcode() == ISD::UNDEF)
1811 return N0;
1812 if (N1.getOpcode() == ISD::UNDEF)
1813 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001814
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001815 // If the relocation model supports it, consider symbol offsets.
1816 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001817 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001818 // fold (sub Sym, c) -> Sym-c
1819 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001820 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001821 GA->getOffset() -
1822 (uint64_t)N1C->getSExtValue());
1823 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1824 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1825 if (GA->getGlobal() == GB->getGlobal())
1826 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1827 VT);
1828 }
1829
Evan Chengf1005572010-04-28 07:10:39 +00001830 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001831}
1832
Craig Topper43a1bd62012-01-07 09:06:39 +00001833SDValue DAGCombiner::visitSUBC(SDNode *N) {
1834 SDValue N0 = N->getOperand(0);
1835 SDValue N1 = N->getOperand(1);
1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1838 EVT VT = N0.getValueType();
1839
1840 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001841 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001842 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1843 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001844 MVT::Glue));
1845
1846 // fold (subc x, x) -> 0 + no borrow
1847 if (N0 == N1)
1848 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001849 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001850 MVT::Glue));
1851
1852 // fold (subc x, 0) -> x + no borrow
1853 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001854 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001855 MVT::Glue));
1856
1857 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1858 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001859 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1860 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001861 MVT::Glue));
1862
1863 return SDValue();
1864}
1865
1866SDValue DAGCombiner::visitSUBE(SDNode *N) {
1867 SDValue N0 = N->getOperand(0);
1868 SDValue N1 = N->getOperand(1);
1869 SDValue CarryIn = N->getOperand(2);
1870
1871 // fold (sube x, y, false) -> (subc x, y)
1872 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001873 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001874
1875 return SDValue();
1876}
1877
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001878SDValue DAGCombiner::visitMUL(SDNode *N) {
1879 SDValue N0 = N->getOperand(0);
1880 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001881 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001882
Dan Gohman06563a82007-07-03 14:03:57 +00001883 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001884 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001885 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001886
1887 bool N0IsConst = false;
1888 bool N1IsConst = false;
1889 APInt ConstValue0, ConstValue1;
1890 // fold vector ops
1891 if (VT.isVector()) {
1892 SDValue FoldedVOp = SimplifyVBinOp(N);
1893 if (FoldedVOp.getNode()) return FoldedVOp;
1894
1895 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1896 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1897 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001898 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001899 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1900 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001901 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001902 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1903 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001904 }
1905
Nate Begeman21158fc2005-09-01 00:19:25 +00001906 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907 if (N0IsConst && N1IsConst)
1908 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1909
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001910 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001911 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001912 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001913 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001914 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001915 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001916 // We require a splat of the entire scalar bit width for non-contiguous
1917 // bit patterns.
1918 bool IsFullSplat =
1919 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001920 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001921 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001922 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001923 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001924 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001925 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001926 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001927 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001928 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001929 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001930 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001931 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001932 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001933 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001934 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001935 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001936 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001937 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001938 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001939 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001940 DAG.getConstant(Log2Val,
1941 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001942 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001943
1944 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001945 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001946 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001947 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1948 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001949 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001950 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001951 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001952 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001953 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001954 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001955
Chris Lattner324871e2006-03-01 03:44:24 +00001956 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1957 // use.
1958 {
Craig Topperc0196b12014-04-14 00:51:57 +00001959 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001960 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001961 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001964 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001965 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001966 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001967 isa<ConstantSDNode>(N1.getOperand(1)) &&
1968 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001969 Sh = N1; Y = N0;
1970 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001971
Gabor Greiff304a7a2008-08-28 21:40:38 +00001972 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001973 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001974 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001975 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001976 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001977 }
1978 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001979
Chris Lattnerf29f5202006-03-04 23:33:26 +00001980 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001981 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1982 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1983 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001984 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1985 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001986 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001987 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001988 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001989
Nate Begeman22e251a2006-02-03 06:46:56 +00001990 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001991 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001992 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001993 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001994
Evan Chengf1005572010-04-28 07:10:39 +00001995 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001996}
1997
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001998SDValue DAGCombiner::visitSDIV(SDNode *N) {
1999 SDValue N0 = N->getOperand(0);
2000 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002001 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2002 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002003 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002004
Dan Gohmana8665142007-06-25 16:23:39 +00002005 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002006 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002007 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002008 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002009 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002010
Nate Begeman21158fc2005-09-01 00:19:25 +00002011 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002012 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002013 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002014 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002015 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002016 return N0;
2017 // fold (sdiv X, -1) -> 0-X
2018 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002019 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002020 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002021 // If we know the sign bits of both operands are zero, strength reduce to a
2022 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002023 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002024 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002025 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002026 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002027 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002028
Nate Begeman57b35672006-02-17 07:26:20 +00002029 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002030 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2031 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002032 // If dividing by powers of two is cheap, then don't perform the following
2033 // fold.
2034 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002035 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002036
Chad Rosier17020f92014-07-23 14:57:52 +00002037 // Target-specific implementation of sdiv x, pow2.
2038 SDValue Res = BuildSDIVPow2(N);
2039 if (Res.getNode())
2040 return Res;
2041
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002042 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002043
Chris Lattner471627c2006-02-16 08:02:36 +00002044 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002045 SDValue SGN =
2046 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2047 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2048 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002049 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002050
Chris Lattner471627c2006-02-16 08:02:36 +00002051 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002052 SDValue SRL =
2053 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2054 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2055 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002056 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002057 AddToWorklist(SRL.getNode());
2058 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002059 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002060 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002061
Nate Begeman4dd38312005-10-21 00:02:42 +00002062 // If we're dividing by a positive value, we're done. Otherwise, we must
2063 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002064 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002065 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002066
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002067 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002068 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002069 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002070
Nate Begemanc6f067a2005-10-20 02:15:44 +00002071 // if integer divide is expensive and we satisfy the requirements, emit an
2072 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002073 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002074 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002075 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002076 }
Dan Gohmana8665142007-06-25 16:23:39 +00002077
Dan Gohman06563a82007-07-03 14:03:57 +00002078 // undef / X -> 0
2079 if (N0.getOpcode() == ISD::UNDEF)
2080 return DAG.getConstant(0, VT);
2081 // X / undef -> undef
2082 if (N1.getOpcode() == ISD::UNDEF)
2083 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002084
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002085 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002086}
2087
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002088SDValue DAGCombiner::visitUDIV(SDNode *N) {
2089 SDValue N0 = N->getOperand(0);
2090 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002091 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2092 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002093 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002094
Dan Gohmana8665142007-06-25 16:23:39 +00002095 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002096 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002097 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002098 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002099 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002100
Nate Begeman21158fc2005-09-01 00:19:25 +00002101 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002102 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002103 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002104 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002105 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002106 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002107 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002108 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002109 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002110 if (N1.getOpcode() == ISD::SHL) {
2111 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002112 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002113 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002114 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002115 N1.getOperand(1),
2116 DAG.getConstant(SHC->getAPIntValue()
2117 .logBase2(),
2118 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002119 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002120 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002121 }
2122 }
2123 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002124 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002125 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002126 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002127 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002128 }
Dan Gohmana8665142007-06-25 16:23:39 +00002129
Dan Gohman06563a82007-07-03 14:03:57 +00002130 // undef / X -> 0
2131 if (N0.getOpcode() == ISD::UNDEF)
2132 return DAG.getConstant(0, VT);
2133 // X / undef -> undef
2134 if (N1.getOpcode() == ISD::UNDEF)
2135 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002136
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002137 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002138}
2139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002140SDValue DAGCombiner::visitSREM(SDNode *N) {
2141 SDValue N0 = N->getOperand(0);
2142 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002143 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2144 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002145 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002146
Nate Begeman21158fc2005-09-01 00:19:25 +00002147 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002148 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002149 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002150 // If we know the sign bits of both operands are zero, strength reduce to a
2151 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002152 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002153 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002154 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002156
Dan Gohman9a693412007-11-26 23:46:11 +00002157 // If X/C can be simplified by the division-by-constant logic, lower
2158 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002159 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002160 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002161 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002162 SDValue OptimizedDiv = combine(Div.getNode());
2163 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002164 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002165 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002166 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002167 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002168 return Sub;
2169 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002170 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002171
Dan Gohman06563a82007-07-03 14:03:57 +00002172 // undef % X -> 0
2173 if (N0.getOpcode() == ISD::UNDEF)
2174 return DAG.getConstant(0, VT);
2175 // X % undef -> undef
2176 if (N1.getOpcode() == ISD::UNDEF)
2177 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002179 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002180}
2181
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002182SDValue DAGCombiner::visitUREM(SDNode *N) {
2183 SDValue N0 = N->getOperand(0);
2184 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002185 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002187 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002188
Nate Begeman21158fc2005-09-01 00:19:25 +00002189 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002190 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002191 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002192 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002193 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002195 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002196 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2197 if (N1.getOpcode() == ISD::SHL) {
2198 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002199 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002200 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002201 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002202 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002203 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002204 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002205 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002206 }
2207 }
2208 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002209
Dan Gohman9a693412007-11-26 23:46:11 +00002210 // If X/C can be simplified by the division-by-constant logic, lower
2211 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002212 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002213 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002214 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002215 SDValue OptimizedDiv = combine(Div.getNode());
2216 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002217 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002218 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002219 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002220 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002221 return Sub;
2222 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002223 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002224
Dan Gohman06563a82007-07-03 14:03:57 +00002225 // undef % X -> 0
2226 if (N0.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2228 // X % undef -> undef
2229 if (N1.getOpcode() == ISD::UNDEF)
2230 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002233}
2234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002235SDValue DAGCombiner::visitMULHS(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002239 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002240 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Nate Begeman21158fc2005-09-01 00:19:25 +00002242 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002243 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002244 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002245 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002246 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002247 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002248 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002249 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002250 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002251 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002252 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002253
Chris Lattner10bd29f2010-12-13 08:39:01 +00002254 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2255 // plus a shift.
2256 if (VT.isSimple() && !VT.isVector()) {
2257 MVT Simple = VT.getSimpleVT();
2258 unsigned SimpleSize = Simple.getSizeInBits();
2259 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2260 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2261 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2262 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2263 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002264 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002265 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002266 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2267 }
2268 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002270 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002271}
2272
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002273SDValue DAGCombiner::visitMULHU(SDNode *N) {
2274 SDValue N0 = N->getOperand(0);
2275 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002277 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002278 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002279
Nate Begeman21158fc2005-09-01 00:19:25 +00002280 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002281 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002282 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002283 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002284 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002285 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002286 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002287 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002288 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002289
Chris Lattner10bd29f2010-12-13 08:39:01 +00002290 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2291 // plus a shift.
2292 if (VT.isSimple() && !VT.isVector()) {
2293 MVT Simple = VT.getSimpleVT();
2294 unsigned SimpleSize = Simple.getSizeInBits();
2295 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2296 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2297 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2298 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2299 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2300 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002301 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002302 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2303 }
2304 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002305
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002306 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002307}
2308
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002309/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2310/// compute two values. LoOp and HiOp give the opcodes for the two computations
2311/// that are being performed. Return true if a simplification was made.
2312///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002313SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002314 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002315 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002316 bool HiExists = N->hasAnyUseOfValue(1);
2317 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002318 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002319 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002320 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002321 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002322 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002323 }
2324
2325 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002326 bool LoExists = N->hasAnyUseOfValue(0);
2327 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002328 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002329 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002330 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002331 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002332 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002333 }
2334
Evan Chengece4c682007-11-08 09:25:29 +00002335 // If both halves are used, return as it is.
2336 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002337 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002338
2339 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002340 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002341 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002342 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002343 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002344 SDValue LoOpt = combine(Lo.getNode());
2345 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002346 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002347 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002348 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002349 }
2350
Evan Chengece4c682007-11-08 09:25:29 +00002351 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002352 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002353 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002354 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002355 SDValue HiOpt = combine(Hi.getNode());
2356 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002357 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002358 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002359 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002360 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002362 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002363}
2364
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002365SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2366 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002367 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002368
Chris Lattner15090e12010-12-15 06:04:19 +00002369 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002370 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002371
2372 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2373 // plus a shift.
2374 if (VT.isSimple() && !VT.isVector()) {
2375 MVT Simple = VT.getSimpleVT();
2376 unsigned SimpleSize = Simple.getSizeInBits();
2377 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2378 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2379 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2380 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2381 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2382 // Compute the high part as N1.
2383 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002384 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002385 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2386 // Compute the low part as N0.
2387 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2388 return CombineTo(N, Lo, Hi);
2389 }
2390 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002391
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002392 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002393}
2394
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002395SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002397 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002398
Chris Lattner15090e12010-12-15 06:04:19 +00002399 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002400 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002401
Chris Lattner15090e12010-12-15 06:04:19 +00002402 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2403 // plus a shift.
2404 if (VT.isSimple() && !VT.isVector()) {
2405 MVT Simple = VT.getSimpleVT();
2406 unsigned SimpleSize = Simple.getSizeInBits();
2407 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2408 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2409 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2410 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2411 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2412 // Compute the high part as N1.
2413 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002414 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002415 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2416 // Compute the low part as N0.
2417 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2418 return CombineTo(N, Lo, Hi);
2419 }
2420 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002421
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002422 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002423}
2424
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002425SDValue DAGCombiner::visitSMULO(SDNode *N) {
2426 // (smulo x, 2) -> (saddo x, x)
2427 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2428 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002429 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002430 N->getOperand(0), N->getOperand(0));
2431
2432 return SDValue();
2433}
2434
2435SDValue DAGCombiner::visitUMULO(SDNode *N) {
2436 // (umulo x, 2) -> (uaddo x, x)
2437 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2438 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002439 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002440 N->getOperand(0), N->getOperand(0));
2441
2442 return SDValue();
2443}
2444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002445SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2446 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002447 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002448
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002449 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002450}
2451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002452SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2453 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002454 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002455
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002456 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002457}
2458
Chris Lattner8d6fc202006-05-05 05:51:50 +00002459/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2460/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002461SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2462 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002463 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002464 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002465
Dan Gohmandd5286d2010-01-14 03:08:49 +00002466 // Bail early if none of these transforms apply.
2467 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2468
Chris Lattner002ee912006-05-05 06:31:05 +00002469 // For each of OP in AND/OR/XOR:
2470 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2471 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2472 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002473 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002474 //
2475 // do not sink logical op inside of a vector extend, since it may combine
2476 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002477 EVT Op0VT = N0.getOperand(0).getValueType();
2478 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002479 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002480 // Avoid infinite looping with PromoteIntBinOp.
2481 (N0.getOpcode() == ISD::ANY_EXTEND &&
2482 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002483 (N0.getOpcode() == ISD::TRUNCATE &&
2484 (!TLI.isZExtFree(VT, Op0VT) ||
2485 !TLI.isTruncateFree(Op0VT, VT)) &&
2486 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002487 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002488 Op0VT == N1.getOperand(0).getValueType() &&
2489 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002490 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002491 N0.getOperand(0).getValueType(),
2492 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002493 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002494 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002496
Chris Lattner5ac42932006-05-05 06:10:43 +00002497 // For each of OP in SHL/SRL/SRA/AND...
2498 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2499 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2500 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002501 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002502 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002503 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002504 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002505 N0.getOperand(0).getValueType(),
2506 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002507 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002508 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002509 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002510 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002511
Nadav Rotemb0783502012-04-01 19:31:22 +00002512 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2513 // Only perform this optimization after type legalization and before
2514 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2515 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2516 // we don't want to undo this promotion.
2517 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2518 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002519 if ((N0.getOpcode() == ISD::BITCAST ||
2520 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2521 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002522 SDValue In0 = N0.getOperand(0);
2523 SDValue In1 = N1.getOperand(0);
2524 EVT In0Ty = In0.getValueType();
2525 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002526 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002527 // If both incoming values are integers, and the original types are the
2528 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002529 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002530 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2531 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002532 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002533 return BC;
2534 }
2535 }
2536
2537 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2538 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2539 // If both shuffles use the same mask, and both shuffle within a single
2540 // vector, then it is worthwhile to move the swizzle after the operation.
2541 // The type-legalizer generates this pattern when loading illegal
2542 // vector types from memory. In many cases this allows additional shuffle
2543 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002544 // There are other cases where moving the shuffle after the xor/and/or
2545 // is profitable even if shuffles don't perform a swizzle.
2546 // If both shuffles use the same mask, and both shuffles have the same first
2547 // or second operand, then it might still be profitable to move the shuffle
2548 // after the xor/and/or operation.
2549 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002550 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2551 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002552
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002553 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002554 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002555
Nadav Rotemb0783502012-04-01 19:31:22 +00002556 // Check that both shuffles use the same mask. The masks are known to be of
2557 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002558 // Check also that shuffles have only one use to avoid introducing extra
2559 // instructions.
2560 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2561 SVN0->getMask().equals(SVN1->getMask())) {
2562 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002563
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002564 // Don't try to fold this node if it requires introducing a
2565 // build vector of all zeros that might be illegal at this stage.
2566 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2567 if (!LegalTypes)
2568 ShOp = DAG.getConstant(0, VT);
2569 else
2570 ShOp = SDValue();
2571 }
2572
2573 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2574 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2575 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2576 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2577 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2578 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002579 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002580 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2581 &SVN0->getMask()[0]);
2582 }
2583
2584 // Don't try to fold this node if it requires introducing a
2585 // build vector of all zeros that might be illegal at this stage.
2586 ShOp = N0->getOperand(0);
2587 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2588 if (!LegalTypes)
2589 ShOp = DAG.getConstant(0, VT);
2590 else
2591 ShOp = SDValue();
2592 }
2593
2594 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2595 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2596 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2597 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2598 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2599 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002600 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002601 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2602 &SVN0->getMask()[0]);
2603 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002604 }
2605 }
Craig Topper9c3da312012-04-09 07:19:09 +00002606
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002607 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002608}
2609
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002610SDValue DAGCombiner::visitAND(SDNode *N) {
2611 SDValue N0 = N->getOperand(0);
2612 SDValue N1 = N->getOperand(1);
2613 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002614 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2615 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002616 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002617 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002618
Dan Gohmana8665142007-06-25 16:23:39 +00002619 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002620 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002621 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002622 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002623
2624 // fold (and x, 0) -> 0, vector edition
2625 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2626 return N0;
2627 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2628 return N1;
2629
2630 // fold (and x, -1) -> x, vector edition
2631 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2632 return N1;
2633 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2634 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002635 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002636
Dan Gohman06563a82007-07-03 14:03:57 +00002637 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002638 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002639 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002640 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002641 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002642 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002643 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002644 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002645 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002646 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002647 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002648 return N0;
2649 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002650 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002651 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002652 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002653 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002654 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002655 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002656 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002657 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002658 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002659 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002660 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002661 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002662 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2663 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002664 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002665 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002666 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002667 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002668 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002669 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002670
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002671 // Replace uses of the AND with uses of the Zero extend node.
2672 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002673
Chris Lattner49beaf42006-02-02 07:17:31 +00002674 // We actually want to replace all uses of the any_extend with the
2675 // zero_extend, to avoid duplicating things. This will later cause this
2676 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002677 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002678 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002679 }
2680 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002681 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002682 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2683 // already be zero by virtue of the width of the base type of the load.
2684 //
2685 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2686 // more cases.
2687 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2688 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2689 N0.getOpcode() == ISD::LOAD) {
2690 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2691 N0 : N0.getOperand(0) );
2692
2693 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2694 // This can be a pure constant or a vector splat, in which case we treat the
2695 // vector as a scalar and use the splat value.
2696 APInt Constant = APInt::getNullValue(1);
2697 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2698 Constant = C->getAPIntValue();
2699 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2700 APInt SplatValue, SplatUndef;
2701 unsigned SplatBitSize;
2702 bool HasAnyUndefs;
2703 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2704 SplatBitSize, HasAnyUndefs);
2705 if (IsSplat) {
2706 // Undef bits can contribute to a possible optimisation if set, so
2707 // set them.
2708 SplatValue |= SplatUndef;
2709
2710 // The splat value may be something like "0x00FFFFFF", which means 0 for
2711 // the first vector value and FF for the rest, repeating. We need a mask
2712 // that will apply equally to all members of the vector, so AND all the
2713 // lanes of the constant together.
2714 EVT VT = Vector->getValueType(0);
2715 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002716
2717 // If the splat value has been compressed to a bitlength lower
2718 // than the size of the vector lane, we need to re-expand it to
2719 // the lane size.
2720 if (BitWidth > SplatBitSize)
2721 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2722 SplatBitSize < BitWidth;
2723 SplatBitSize = SplatBitSize * 2)
2724 SplatValue |= SplatValue.shl(SplatBitSize);
2725
James Molloy862fe492012-02-20 12:02:38 +00002726 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002727 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002728 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2729 }
2730 }
2731
2732 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2733 // actually legal and isn't going to get expanded, else this is a false
2734 // optimisation.
2735 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2736 Load->getMemoryVT());
2737
2738 // Resize the constant to the same size as the original memory access before
2739 // extension. If it is still the AllOnesValue then this AND is completely
2740 // unneeded.
2741 Constant =
2742 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2743
2744 bool B;
2745 switch (Load->getExtensionType()) {
2746 default: B = false; break;
2747 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2748 case ISD::ZEXTLOAD:
2749 case ISD::NON_EXTLOAD: B = true; break;
2750 }
2751
2752 if (B && Constant.isAllOnesValue()) {
2753 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2754 // preserve semantics once we get rid of the AND.
2755 SDValue NewLoad(Load, 0);
2756 if (Load->getExtensionType() == ISD::EXTLOAD) {
2757 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002758 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002759 Load->getChain(), Load->getBasePtr(),
2760 Load->getOffset(), Load->getMemoryVT(),
2761 Load->getMemOperand());
2762 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002763 if (Load->getNumValues() == 3) {
2764 // PRE/POST_INC loads have 3 values.
2765 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2766 NewLoad.getValue(2) };
2767 CombineTo(Load, To, 3, true);
2768 } else {
2769 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2770 }
James Molloy862fe492012-02-20 12:02:38 +00002771 }
2772
2773 // Fold the AND away, taking care not to fold to the old load node if we
2774 // replaced it.
2775 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2776
2777 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2778 }
2779 }
Nate Begeman049b7482005-09-09 19:49:52 +00002780 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2781 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2782 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2783 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002784
Tom Stellard7783b0a2014-06-12 16:04:47 +00002785 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002786 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002787 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002788 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002789 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002790 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002791 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002792 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002793 }
Bill Wendling86171912009-01-30 20:43:18 +00002794 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002795 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002796 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002797 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002798 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002799 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002800 }
Bill Wendling86171912009-01-30 20:43:18 +00002801 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002802 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002803 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002804 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002805 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002806 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002807 }
2808 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002809 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2810 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2811 Op0 == Op1 && LL.getValueType().isInteger() &&
2812 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2813 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2814 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2815 cast<ConstantSDNode>(RR)->isNullValue()))) {
2816 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2817 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002818 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002819 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2820 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2821 }
Nate Begeman049b7482005-09-09 19:49:52 +00002822 // canonicalize equivalent to ll == rl
2823 if (LL == RR && LR == RL) {
2824 Op1 = ISD::getSetCCSwappedOperands(Op1);
2825 std::swap(RL, RR);
2826 }
2827 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002828 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002829 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002830 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002831 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002832 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2833 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002834 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002835 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002836 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002837 }
2838 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002839
Bill Wendling86171912009-01-30 20:43:18 +00002840 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002841 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002842 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002843 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002844 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002845
Nate Begemandc7bba92006-02-03 22:24:05 +00002846 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2847 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002848 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002849 SimplifyDemandedBits(SDValue(N, 0)))
2850 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002851
Nate Begeman02b23c62005-10-13 03:11:28 +00002852 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002853 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002855 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002856 // If we zero all the possible extended bits, then we can turn this into
2857 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002858 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002859 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002860 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002861 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002863 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002864 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002865 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002866 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002869 }
2870 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002871 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002872 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002873 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002874 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002875 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002876 // If we zero all the possible extended bits, then we can turn this into
2877 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002878 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002879 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002880 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002881 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002882 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002884 LN0->getChain(), LN0->getBasePtr(),
2885 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002886 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002887 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002889 }
2890 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002891
Chris Lattnerf0032b32006-02-28 06:49:37 +00002892 // fold (and (load x), 255) -> (zextload x, i8)
2893 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002894 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2895 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2896 (N0.getOpcode() == ISD::ANY_EXTEND &&
2897 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2898 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2899 LoadSDNode *LN0 = HasAnyExt
2900 ? cast<LoadSDNode>(N0.getOperand(0))
2901 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002902 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002903 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002904 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002905 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2906 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2907 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002908
Evan Cheng166a4e62010-01-06 19:38:29 +00002909 if (ExtVT == LoadedVT &&
2910 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002911 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002912
2913 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002914 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002915 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2916 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002917 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002918 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2920 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002921
Chris Lattner88de3842010-01-07 21:53:27 +00002922 // Do not change the width of a volatile load.
2923 // Do not generate loads of non-round integer types since these can
2924 // be expensive (and would be wrong if the type is not byte sized).
2925 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2926 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2927 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002928
Chris Lattner88de3842010-01-07 21:53:27 +00002929 unsigned Alignment = LN0->getAlignment();
2930 SDValue NewPtr = LN0->getBasePtr();
2931
2932 // For big endian targets, we need to add an offset to the pointer
2933 // to load the correct bytes. For little endian systems, we merely
2934 // need to read fewer bytes from the same pointer.
2935 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002936 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2937 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2938 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002939 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002940 NewPtr, DAG.getConstant(PtrOff, PtrType));
2941 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002942 }
Chris Lattner88de3842010-01-07 21:53:27 +00002943
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002944 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002945
Chris Lattner88de3842010-01-07 21:53:27 +00002946 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2947 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002948 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002949 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002950 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002951 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002952 Alignment, LN0->getTBAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002953 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002954 CombineTo(LN0, Load, Load.getValue(1));
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002956 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002957 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002958 }
2959 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002960
Evan Chenge6a3b032012-07-17 18:54:11 +00002961 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2962 VT.getSizeInBits() <= 64) {
2963 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2964 APInt ADDC = ADDI->getAPIntValue();
2965 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2966 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2967 // immediate for an add, but it is legal if its top c2 bits are set,
2968 // transform the ADD so the immediate doesn't need to be materialized
2969 // in a register.
2970 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2971 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2972 SRLI->getZExtValue());
2973 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2974 ADDC |= Mask;
2975 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2976 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002977 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002978 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2979 CombineTo(N0.getNode(), NewAdd);
2980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2981 }
2982 }
2983 }
2984 }
2985 }
2986 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002987
Tim Northover819bfb52013-08-27 13:46:45 +00002988 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2989 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2990 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2991 N0.getOperand(1), false);
2992 if (BSwap.getNode())
2993 return BSwap;
2994 }
2995
Evan Chengf1005572010-04-28 07:10:39 +00002996 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002997}
2998
Evan Cheng4c0bd962011-06-21 06:01:08 +00002999/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3000///
3001SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3002 bool DemandHighBits) {
3003 if (!LegalOperations)
3004 return SDValue();
3005
3006 EVT VT = N->getValueType(0);
3007 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3008 return SDValue();
3009 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3010 return SDValue();
3011
3012 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3013 bool LookPassAnd0 = false;
3014 bool LookPassAnd1 = false;
3015 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3016 std::swap(N0, N1);
3017 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3018 std::swap(N0, N1);
3019 if (N0.getOpcode() == ISD::AND) {
3020 if (!N0.getNode()->hasOneUse())
3021 return SDValue();
3022 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023 if (!N01C || N01C->getZExtValue() != 0xFF00)
3024 return SDValue();
3025 N0 = N0.getOperand(0);
3026 LookPassAnd0 = true;
3027 }
3028
3029 if (N1.getOpcode() == ISD::AND) {
3030 if (!N1.getNode()->hasOneUse())
3031 return SDValue();
3032 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3033 if (!N11C || N11C->getZExtValue() != 0xFF)
3034 return SDValue();
3035 N1 = N1.getOperand(0);
3036 LookPassAnd1 = true;
3037 }
3038
3039 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3040 std::swap(N0, N1);
3041 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3042 return SDValue();
3043 if (!N0.getNode()->hasOneUse() ||
3044 !N1.getNode()->hasOneUse())
3045 return SDValue();
3046
3047 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3048 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3049 if (!N01C || !N11C)
3050 return SDValue();
3051 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3052 return SDValue();
3053
3054 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3055 SDValue N00 = N0->getOperand(0);
3056 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3057 if (!N00.getNode()->hasOneUse())
3058 return SDValue();
3059 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3060 if (!N001C || N001C->getZExtValue() != 0xFF)
3061 return SDValue();
3062 N00 = N00.getOperand(0);
3063 LookPassAnd0 = true;
3064 }
3065
3066 SDValue N10 = N1->getOperand(0);
3067 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3068 if (!N10.getNode()->hasOneUse())
3069 return SDValue();
3070 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3071 if (!N101C || N101C->getZExtValue() != 0xFF00)
3072 return SDValue();
3073 N10 = N10.getOperand(0);
3074 LookPassAnd1 = true;
3075 }
3076
3077 if (N00 != N10)
3078 return SDValue();
3079
Tim Northover819bfb52013-08-27 13:46:45 +00003080 // Make sure everything beyond the low halfword gets set to zero since the SRL
3081 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003082 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003083 if (DemandHighBits && OpSizeInBits > 16) {
3084 // If the left-shift isn't masked out then the only way this is a bswap is
3085 // if all bits beyond the low 8 are 0. In that case the entire pattern
3086 // reduces to a left shift anyway: leave it for other parts of the combiner.
3087 if (!LookPassAnd0)
3088 return SDValue();
3089
3090 // However, if the right shift isn't masked out then it might be because
3091 // it's not needed. See if we can spot that too.
3092 if (!LookPassAnd1 &&
3093 !DAG.MaskedValueIsZero(
3094 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3095 return SDValue();
3096 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003097
Andrew Trickef9de2a2013-05-25 02:42:55 +00003098 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003099 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003100 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003101 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3102 return Res;
3103}
3104
3105/// isBSwapHWordElement - Return true if the specified node is an element
3106/// that makes up a 32-bit packed halfword byteswap. i.e.
3107/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003108static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003109 if (!N.getNode()->hasOneUse())
3110 return false;
3111
3112 unsigned Opc = N.getOpcode();
3113 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3114 return false;
3115
3116 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3117 if (!N1C)
3118 return false;
3119
3120 unsigned Num;
3121 switch (N1C->getZExtValue()) {
3122 default:
3123 return false;
3124 case 0xFF: Num = 0; break;
3125 case 0xFF00: Num = 1; break;
3126 case 0xFF0000: Num = 2; break;
3127 case 0xFF000000: Num = 3; break;
3128 }
3129
3130 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3131 SDValue N0 = N.getOperand(0);
3132 if (Opc == ISD::AND) {
3133 if (Num == 0 || Num == 2) {
3134 // (x >> 8) & 0xff
3135 // (x >> 8) & 0xff0000
3136 if (N0.getOpcode() != ISD::SRL)
3137 return false;
3138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3139 if (!C || C->getZExtValue() != 8)
3140 return false;
3141 } else {
3142 // (x << 8) & 0xff00
3143 // (x << 8) & 0xff000000
3144 if (N0.getOpcode() != ISD::SHL)
3145 return false;
3146 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3147 if (!C || C->getZExtValue() != 8)
3148 return false;
3149 }
3150 } else if (Opc == ISD::SHL) {
3151 // (x & 0xff) << 8
3152 // (x & 0xff0000) << 8
3153 if (Num != 0 && Num != 2)
3154 return false;
3155 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3156 if (!C || C->getZExtValue() != 8)
3157 return false;
3158 } else { // Opc == ISD::SRL
3159 // (x & 0xff00) >> 8
3160 // (x & 0xff000000) >> 8
3161 if (Num != 1 && Num != 3)
3162 return false;
3163 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3164 if (!C || C->getZExtValue() != 8)
3165 return false;
3166 }
3167
3168 if (Parts[Num])
3169 return false;
3170
3171 Parts[Num] = N0.getOperand(0).getNode();
3172 return true;
3173}
3174
3175/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3176/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3177/// => (rotl (bswap x), 16)
3178SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3179 if (!LegalOperations)
3180 return SDValue();
3181
3182 EVT VT = N->getValueType(0);
3183 if (VT != MVT::i32)
3184 return SDValue();
3185 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3186 return SDValue();
3187
Craig Topperc0196b12014-04-14 00:51:57 +00003188 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003189 // Look for either
3190 // (or (or (and), (and)), (or (and), (and)))
3191 // (or (or (or (and), (and)), (and)), (and))
3192 if (N0.getOpcode() != ISD::OR)
3193 return SDValue();
3194 SDValue N00 = N0.getOperand(0);
3195 SDValue N01 = N0.getOperand(1);
3196
Evan Chengbf0baa92012-12-13 01:34:32 +00003197 if (N1.getOpcode() == ISD::OR &&
3198 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003199 // (or (or (and), (and)), (or (and), (and)))
3200 SDValue N000 = N00.getOperand(0);
3201 if (!isBSwapHWordElement(N000, Parts))
3202 return SDValue();
3203
3204 SDValue N001 = N00.getOperand(1);
3205 if (!isBSwapHWordElement(N001, Parts))
3206 return SDValue();
3207 SDValue N010 = N01.getOperand(0);
3208 if (!isBSwapHWordElement(N010, Parts))
3209 return SDValue();
3210 SDValue N011 = N01.getOperand(1);
3211 if (!isBSwapHWordElement(N011, Parts))
3212 return SDValue();
3213 } else {
3214 // (or (or (or (and), (and)), (and)), (and))
3215 if (!isBSwapHWordElement(N1, Parts))
3216 return SDValue();
3217 if (!isBSwapHWordElement(N01, Parts))
3218 return SDValue();
3219 if (N00.getOpcode() != ISD::OR)
3220 return SDValue();
3221 SDValue N000 = N00.getOperand(0);
3222 if (!isBSwapHWordElement(N000, Parts))
3223 return SDValue();
3224 SDValue N001 = N00.getOperand(1);
3225 if (!isBSwapHWordElement(N001, Parts))
3226 return SDValue();
3227 }
3228
3229 // Make sure the parts are all coming from the same node.
3230 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3231 return SDValue();
3232
Andrew Trickef9de2a2013-05-25 02:42:55 +00003233 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003234 SDValue(Parts[0],0));
3235
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003236 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003237 // do (x << 16) | (x >> 16).
3238 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3239 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003240 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003241 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003242 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3243 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3244 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3245 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003246}
3247
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003248SDValue DAGCombiner::visitOR(SDNode *N) {
3249 SDValue N0 = N->getOperand(0);
3250 SDValue N1 = N->getOperand(1);
3251 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003252 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003254 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003255
Dan Gohmana8665142007-06-25 16:23:39 +00003256 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003257 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003258 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003259 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003260
3261 // fold (or x, 0) -> x, vector edition
3262 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3263 return N1;
3264 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3265 return N0;
3266
3267 // fold (or x, -1) -> -1, vector edition
3268 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3269 return N0;
3270 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3271 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003272
3273 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3274 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3275 // Do this only if the resulting shuffle is legal.
3276 if (isa<ShuffleVectorSDNode>(N0) &&
3277 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003278 // Avoid folding a node with illegal type.
3279 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003280 N0->getOperand(1) == N1->getOperand(1) &&
3281 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3282 bool CanFold = true;
3283 unsigned NumElts = VT.getVectorNumElements();
3284 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3285 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3286 // We construct two shuffle masks:
3287 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3288 // and N1 as the second operand.
3289 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3290 // and N0 as the second operand.
3291 // We do this because OR is commutable and therefore there might be
3292 // two ways to fold this node into a shuffle.
3293 SmallVector<int,4> Mask1;
3294 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003295
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003296 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3297 int M0 = SV0->getMaskElt(i);
3298 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003299
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003300 // Both shuffle indexes are undef. Propagate Undef.
3301 if (M0 < 0 && M1 < 0) {
3302 Mask1.push_back(M0);
3303 Mask2.push_back(M0);
3304 continue;
3305 }
3306
3307 if (M0 < 0 || M1 < 0 ||
3308 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3309 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3310 CanFold = false;
3311 break;
3312 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003313
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003314 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3315 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3316 }
3317
3318 if (CanFold) {
3319 // Fold this sequence only if the resulting shuffle is 'legal'.
3320 if (TLI.isShuffleMaskLegal(Mask1, VT))
3321 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3322 N1->getOperand(0), &Mask1[0]);
3323 if (TLI.isShuffleMaskLegal(Mask2, VT))
3324 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3325 N0->getOperand(0), &Mask2[0]);
3326 }
3327 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003328 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003329
Dan Gohman06563a82007-07-03 14:03:57 +00003330 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003331 if (!LegalOperations &&
3332 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003333 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3334 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3335 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003336 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003337 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003338 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003339 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003340 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003341 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003342 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003343 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003344 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003345 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003346 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003347 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003348 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003349 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003350 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003351
3352 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3353 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003354 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003355 return BSwap;
3356 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003357 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003358 return BSwap;
3359
Nate Begeman22e251a2006-02-03 06:46:56 +00003360 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003361 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003362 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003363 return ROR;
3364 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003365 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003366 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003367 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003368 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003369 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3370 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3371 if (!COR.getNode())
3372 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003373 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3374 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003375 N0.getOperand(0), N1), COR);
3376 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003377 }
Nate Begeman049b7482005-09-09 19:49:52 +00003378 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3379 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3380 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3381 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003382
Nate Begeman049b7482005-09-09 19:49:52 +00003383 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003384 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003385 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3386 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003387 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003388 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003389 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003390 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003391 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003392 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003393 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003394 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3395 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003396 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003397 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003398 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003399 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003400 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003401 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003402 }
3403 }
3404 // canonicalize equivalent to ll == rl
3405 if (LL == RR && LR == RL) {
3406 Op1 = ISD::getSetCCSwappedOperands(Op1);
3407 std::swap(RL, RR);
3408 }
3409 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003410 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003411 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003412 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003413 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003414 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3415 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003416 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003417 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003418 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003419 }
3420 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003421
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003422 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003423 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003424 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003425 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003427
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003428 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003429 if (N0.getOpcode() == ISD::AND &&
3430 N1.getOpcode() == ISD::AND &&
3431 N0.getOperand(1).getOpcode() == ISD::Constant &&
3432 N1.getOperand(1).getOpcode() == ISD::Constant &&
3433 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003434 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003435 // We can only do this xform if we know that bits from X that are set in C2
3436 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003437 const APInt &LHSMask =
3438 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3439 const APInt &RHSMask =
3440 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003441
Dan Gohman309d3d52007-06-22 14:59:07 +00003442 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3443 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003444 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003445 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003446 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003447 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003448 }
3449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003450
Chris Lattner97614c82006-09-14 20:50:57 +00003451 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003452 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003453 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003454
Dan Gohman600f62b2010-06-24 14:30:44 +00003455 // Simplify the operands using demanded-bits information.
3456 if (!VT.isVector() &&
3457 SimplifyDemandedBits(SDValue(N, 0)))
3458 return SDValue(N, 0);
3459
Evan Chengf1005572010-04-28 07:10:39 +00003460 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003461}
3462
Chris Lattner97614c82006-09-14 20:50:57 +00003463/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003464static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003465 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003466 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003467 Mask = Op.getOperand(1);
3468 Op = Op.getOperand(0);
3469 } else {
3470 return false;
3471 }
3472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003473
Chris Lattner97614c82006-09-14 20:50:57 +00003474 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3475 Shift = Op;
3476 return true;
3477 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003478
Scott Michelcf0da6c2009-02-17 22:15:04 +00003479 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003480}
3481
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003482// Return true if we can prove that, whenever Neg and Pos are both in the
3483// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003484// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3485//
3486// (or (shift1 X, Neg), (shift2 X, Pos))
3487//
Adam Nemetc6553a82014-03-07 23:56:24 +00003488// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3489// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3490// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003491static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003492 // If OpSize is a power of 2 then:
3493 //
3494 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3495 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3496 //
3497 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3498 // for the stronger condition:
3499 //
3500 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3501 //
3502 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3503 // we can just replace Neg with Neg' for the rest of the function.
3504 //
3505 // In other cases we check for the even stronger condition:
3506 //
3507 // Neg == OpSize - Pos [B]
3508 //
3509 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3510 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003511 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003512 // We could actually use [A] whenever OpSize is a power of 2, but the
3513 // only extra cases that it would match are those uninteresting ones
3514 // where Neg and Pos are never in range at the same time. E.g. for
3515 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3516 // as well as (sub 32, Pos), but:
3517 //
3518 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3519 //
3520 // always invokes undefined behavior for 32-bit X.
3521 //
3522 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003523 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003524 if (Neg.getOpcode() == ISD::AND &&
3525 isPowerOf2_64(OpSize) &&
3526 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3527 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3528 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003529 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003530 }
3531
Richard Sandiford0f264db2014-01-09 10:49:40 +00003532 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3533 if (Neg.getOpcode() != ISD::SUB)
3534 return 0;
3535 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3536 if (!NegC)
3537 return 0;
3538 SDValue NegOp1 = Neg.getOperand(1);
3539
Adam Nemet5117f5d2014-03-07 23:56:28 +00003540 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3541 // Pos'. The truncation is redundant for the purpose of the equality.
3542 if (MaskLoBits &&
3543 Pos.getOpcode() == ISD::AND &&
3544 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3545 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3546 Pos = Pos.getOperand(0);
3547
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003548 // The condition we need is now:
3549 //
3550 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3551 //
3552 // If NegOp1 == Pos then we need:
3553 //
3554 // OpSize & Mask == NegC & Mask
3555 //
3556 // (because "x & Mask" is a truncation and distributes through subtraction).
3557 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003558 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003559 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003560 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3561 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003562 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003563 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3564 //
3565 // which, again because "x & Mask" is a truncation, becomes:
3566 //
3567 // NegC & Mask == (OpSize - PosC) & Mask
3568 // OpSize & Mask == (NegC + PosC) & Mask
3569 else if (Pos.getOpcode() == ISD::ADD &&
3570 Pos.getOperand(0) == NegOp1 &&
3571 Pos.getOperand(1).getOpcode() == ISD::Constant)
3572 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3573 NegC->getAPIntValue());
3574 else
3575 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003576
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003577 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003578 if (MaskLoBits)
3579 // Opsize & Mask is 0 since Mask is Opsize - 1.
3580 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003581 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003582}
3583
Richard Sandiford95c864d2014-01-08 15:40:47 +00003584// A subroutine of MatchRotate used once we have found an OR of two opposite
3585// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3586// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3587// former being preferred if supported. InnerPos and InnerNeg are Pos and
3588// Neg with outer conversions stripped away.
3589SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3590 SDValue Neg, SDValue InnerPos,
3591 SDValue InnerNeg, unsigned PosOpcode,
3592 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003593 // fold (or (shl x, (*ext y)),
3594 // (srl x, (*ext (sub 32, y)))) ->
3595 // (rotl x, y) or (rotr x, (sub 32, y))
3596 //
3597 // fold (or (shl x, (*ext (sub 32, y))),
3598 // (srl x, (*ext y))) ->
3599 // (rotr x, y) or (rotl x, (sub 32, y))
3600 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003601 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003602 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3603 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3604 HasPos ? Pos : Neg).getNode();
3605 }
3606
Craig Topperc0196b12014-04-14 00:51:57 +00003607 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003608}
3609
Chris Lattner97614c82006-09-14 20:50:57 +00003610// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3611// idioms for rotate, and if the target supports rotation instructions, generate
3612// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003613SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003614 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003615 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003616 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003617
3618 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003619 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3620 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003621 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003622
Chris Lattner97614c82006-09-14 20:50:57 +00003623 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003624 SDValue LHSShift; // The shift.
3625 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003626 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003627 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003628
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003629 SDValue RHSShift; // The shift.
3630 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003631 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003632 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003633
Chris Lattner97614c82006-09-14 20:50:57 +00003634 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003635 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003636
3637 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003638 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003639
Chris Lattner97614c82006-09-14 20:50:57 +00003640 // Canonicalize shl to left side in a shl/srl pair.
3641 if (RHSShift.getOpcode() == ISD::SHL) {
3642 std::swap(LHS, RHS);
3643 std::swap(LHSShift, RHSShift);
3644 std::swap(LHSMask , RHSMask );
3645 }
3646
Duncan Sands13237ac2008-06-06 12:08:01 +00003647 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003648 SDValue LHSShiftArg = LHSShift.getOperand(0);
3649 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003650 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003651 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003652
3653 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3654 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003655 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3656 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003657 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3658 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003659 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003660 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003661
Craig Topper65161fa2012-09-29 06:54:22 +00003662 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3663 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003664
Chris Lattner97614c82006-09-14 20:50:57 +00003665 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003666 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003667 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003668
Gabor Greiff304a7a2008-08-28 21:40:38 +00003669 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003670 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3671 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003672 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003673 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003674 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3675 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003676 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003677
Bill Wendling35972a92009-01-30 21:14:50 +00003678 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003679 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003680
Gabor Greiff304a7a2008-08-28 21:40:38 +00003681 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003682 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003683
Chris Lattner97614c82006-09-14 20:50:57 +00003684 // If there is a mask here, and we have a variable shift, we can't be sure
3685 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003686 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003687 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003688
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003689 // If the shift amount is sign/zext/any-extended just peel it off.
3690 SDValue LExtOp0 = LHSShiftAmt;
3691 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003692 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3693 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3694 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3695 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3696 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3697 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3698 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3699 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003700 LExtOp0 = LHSShiftAmt.getOperand(0);
3701 RExtOp0 = RHSShiftAmt.getOperand(0);
3702 }
3703
Richard Sandiford95c864d2014-01-08 15:40:47 +00003704 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3705 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3706 if (TryL)
3707 return TryL;
3708
3709 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3710 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3711 if (TryR)
3712 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003713
Craig Topperc0196b12014-04-14 00:51:57 +00003714 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003715}
3716
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003717SDValue DAGCombiner::visitXOR(SDNode *N) {
3718 SDValue N0 = N->getOperand(0);
3719 SDValue N1 = N->getOperand(1);
3720 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003723 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003724
Dan Gohmana8665142007-06-25 16:23:39 +00003725 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003726 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003727 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003728 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003729
3730 // fold (xor x, 0) -> x, vector edition
3731 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3732 return N1;
3733 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3734 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003735 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003736
Evan Chengdf1690d2008-03-25 20:08:07 +00003737 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3738 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3739 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003740 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003741 if (N0.getOpcode() == ISD::UNDEF)
3742 return N0;
3743 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003744 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003745 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003746 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003747 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003748 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003749 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003750 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003751 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003752 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003753 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003754 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003755 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003756 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003757 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003758
Nate Begeman21158fc2005-09-01 00:19:25 +00003759 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003760 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003761 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003762 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3763 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003764
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003765 if (!LegalOperations ||
3766 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003767 switch (N0.getOpcode()) {
3768 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003769 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003770 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003771 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003772 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003773 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003774 N0.getOperand(3), NotCC);
3775 }
3776 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003777 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003778
Chris Lattner58c227b2007-09-10 21:39:07 +00003779 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003780 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003781 N0.getNode()->hasOneUse() &&
3782 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003783 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003784 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003785 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003786 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003787 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003788 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003789
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003790 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003791 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003792 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003793 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003794 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3795 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003796 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3797 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003798 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003799 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003800 }
3801 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003802 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003803 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003804 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003805 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003806 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3807 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003808 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3809 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003810 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003811 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003812 }
3813 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003814 // fold (xor (and x, y), y) -> (and (not x), y)
3815 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003816 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003817 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003818 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003819 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003820 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003821 }
Bill Wendling35972a92009-01-30 21:14:50 +00003822 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003823 if (N1C && N0.getOpcode() == ISD::XOR) {
3824 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3825 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3826 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003827 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003828 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003829 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003830 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003831 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003832 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003833 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003834 }
3835 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003836 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003837 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003838
Chris Lattner8d6fc202006-05-05 05:51:50 +00003839 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3840 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003841 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003842 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003843 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003844
Chris Lattner098c01e2006-04-08 04:15:24 +00003845 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003846 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003847 SimplifyDemandedBits(SDValue(N, 0)))
3848 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003849
Evan Chengf1005572010-04-28 07:10:39 +00003850 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003851}
3852
Chris Lattner7c709a52007-12-06 07:33:36 +00003853/// visitShiftByConstant - Handle transforms common to the three shifts, when
3854/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003855SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003856 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003857 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003858 return SDValue();
3859
Gabor Greiff304a7a2008-08-28 21:40:38 +00003860 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003861 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003862
Chris Lattner7c709a52007-12-06 07:33:36 +00003863 // We want to pull some binops through shifts, so that we have (and (shift))
3864 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3865 // thing happens with address calculations, so it's important to canonicalize
3866 // it.
3867 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003868
Chris Lattner7c709a52007-12-06 07:33:36 +00003869 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003870 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003871 case ISD::OR:
3872 case ISD::XOR:
3873 HighBitSet = false; // We can only transform sra if the high bit is clear.
3874 break;
3875 case ISD::AND:
3876 HighBitSet = true; // We can only transform sra if the high bit is set.
3877 break;
3878 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003879 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003880 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003881 HighBitSet = false; // We can only transform sra if the high bit is clear.
3882 break;
3883 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003884
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003885 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003886 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003887 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003888
3889 // FIXME: disable this unless the input to the binop is a shift by a constant.
3890 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003891 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003892 // void foo(int *X, int i) { X[i & 1235] = 1; }
3893 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003894 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003895 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003896 BinOpLHSVal->getOpcode() != ISD::SRA &&
3897 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3898 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003899 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003900
Owen Anderson53aa7a92009-08-10 22:56:29 +00003901 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003902
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003903 // If this is a signed shift right, and the high bit is modified by the
3904 // logical operation, do not perform the transformation. The highBitSet
3905 // boolean indicates the value of the high bit of the constant which would
3906 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003907 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003908 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3909 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003910 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003911 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003912
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003913 if (!TLI.isDesirableToCommuteWithShift(LHS))
3914 return SDValue();
3915
Chris Lattner7c709a52007-12-06 07:33:36 +00003916 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003917 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003918 N->getValueType(0),
3919 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003920 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003921
3922 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003923 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003924 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003925 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003926
3927 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003928 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003929}
3930
Adam Nemet67483892014-03-04 23:28:31 +00003931SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3932 assert(N->getOpcode() == ISD::TRUNCATE);
3933 assert(N->getOperand(0).getOpcode() == ISD::AND);
3934
3935 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3936 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3937 SDValue N01 = N->getOperand(0).getOperand(1);
3938
Matt Arsenault985b9de2014-03-17 18:58:01 +00003939 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003940 EVT TruncVT = N->getValueType(0);
3941 SDValue N00 = N->getOperand(0).getOperand(0);
3942 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003943 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003944
3945 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3946 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3947 DAG.getConstant(TruncC, TruncVT));
3948 }
3949 }
3950
3951 return SDValue();
3952}
Adam Nemet7f928f12014-03-07 23:56:30 +00003953
3954SDValue DAGCombiner::visitRotate(SDNode *N) {
3955 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3956 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3957 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3958 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3959 if (NewOp1.getNode())
3960 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3961 N->getOperand(0), NewOp1);
3962 }
3963 return SDValue();
3964}
3965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003966SDValue DAGCombiner::visitSHL(SDNode *N) {
3967 SDValue N0 = N->getOperand(0);
3968 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003971 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003972 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003973
Daniel Sandersa1840d22013-11-11 17:23:41 +00003974 // fold vector ops
3975 if (VT.isVector()) {
3976 SDValue FoldedVOp = SimplifyVBinOp(N);
3977 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003978
3979 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3980 // If setcc produces all-one true value then:
3981 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003982 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00003983 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00003984 SDValue N00 = N0->getOperand(0);
3985 SDValue N01 = N0->getOperand(1);
3986 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003987
Daniel Sanderscbd44c52014-07-10 10:18:12 +00003988 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3989 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3990 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00003991 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3992 if (C.getNode())
3993 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3994 }
3995 } else {
3996 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003997 }
3998 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003999 }
4000
Nate Begeman21158fc2005-09-01 00:19:25 +00004001 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004002 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004003 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004004 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004005 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004006 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004007 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004008 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004009 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004010 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004011 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004012 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004013 // fold (shl undef, x) -> 0
4014 if (N0.getOpcode() == ISD::UNDEF)
4015 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004016 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004017 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004018 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004019 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004020 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004021 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004022 N1.getOperand(0).getOpcode() == ISD::AND) {
4023 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4024 if (NewOp1.getNode())
4025 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004026 }
4027
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004028 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4029 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004030
4031 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004032 if (N1C && N0.getOpcode() == ISD::SHL) {
4033 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4034 uint64_t c1 = N0C1->getZExtValue();
4035 uint64_t c2 = N1C->getZExtValue();
4036 if (c1 + c2 >= OpSizeInBits)
4037 return DAG.getConstant(0, VT);
4038 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4039 DAG.getConstant(c1 + c2, N1.getValueType()));
4040 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004041 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004042
4043 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4044 // For this to be valid, the second form must not preserve any of the bits
4045 // that are shifted out by the inner shift in the first form. This means
4046 // the outer shift size must be >= the number of bits added by the ext.
4047 // As a corollary, we don't care what kind of ext it is.
4048 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4049 N0.getOpcode() == ISD::ANY_EXTEND ||
4050 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004051 N0.getOperand(0).getOpcode() == ISD::SHL) {
4052 SDValue N0Op0 = N0.getOperand(0);
4053 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4054 uint64_t c1 = N0Op0C1->getZExtValue();
4055 uint64_t c2 = N1C->getZExtValue();
4056 EVT InnerShiftVT = N0Op0.getValueType();
4057 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4058 if (c2 >= OpSizeInBits - InnerShiftSize) {
4059 if (c1 + c2 >= OpSizeInBits)
4060 return DAG.getConstant(0, VT);
4061 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4062 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4063 N0Op0->getOperand(0)),
4064 DAG.getConstant(c1 + c2, N1.getValueType()));
4065 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004066 }
4067 }
4068
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004069 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4070 // Only fold this if the inner zext has no other uses to avoid increasing
4071 // the total number of instructions.
4072 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004073 N0.getOperand(0).getOpcode() == ISD::SRL) {
4074 SDValue N0Op0 = N0.getOperand(0);
4075 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4076 uint64_t c1 = N0Op0C1->getZExtValue();
4077 if (c1 < VT.getScalarSizeInBits()) {
4078 uint64_t c2 = N1C->getZExtValue();
4079 if (c1 == c2) {
4080 SDValue NewOp0 = N0.getOperand(0);
4081 EVT CountVT = NewOp0.getOperand(1).getValueType();
4082 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4083 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004084 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004085 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4086 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004087 }
4088 }
4089 }
4090
Eli Friedman1877ac92011-06-09 22:14:44 +00004091 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4092 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004093 // Only fold this if the inner shift has no other uses -- if it does, folding
4094 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004095 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4096 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4097 uint64_t c1 = N0C1->getZExtValue();
4098 if (c1 < OpSizeInBits) {
4099 uint64_t c2 = N1C->getZExtValue();
4100 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4101 SDValue Shift;
4102 if (c2 > c1) {
4103 Mask = Mask.shl(c2 - c1);
4104 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4105 DAG.getConstant(c2 - c1, N1.getValueType()));
4106 } else {
4107 Mask = Mask.lshr(c1 - c2);
4108 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4109 DAG.getConstant(c1 - c2, N1.getValueType()));
4110 }
4111 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4112 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004113 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004114 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004115 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004116 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004117 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004118 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004119 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004120 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4121 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004122 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004123 HiBitsMask);
4124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004125
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004126 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004127 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004128 if (NewSHL.getNode())
4129 return NewSHL;
4130 }
4131
Evan Chengf1005572010-04-28 07:10:39 +00004132 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004133}
4134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004135SDValue DAGCombiner::visitSRA(SDNode *N) {
4136 SDValue N0 = N->getOperand(0);
4137 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004140 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004141 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004142
Daniel Sandersa1840d22013-11-11 17:23:41 +00004143 // fold vector ops
4144 if (VT.isVector()) {
4145 SDValue FoldedVOp = SimplifyVBinOp(N);
4146 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004147
4148 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004149 }
4150
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004151 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004152 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004153 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004154 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004155 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004156 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004157 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004158 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004159 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004160 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004161 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004162 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004163 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004164 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004165 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004166 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4167 // sext_inreg.
4168 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004169 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004170 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4171 if (VT.isVector())
4172 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4173 ExtVT, VT.getVectorNumElements());
4174 if ((!LegalOperations ||
4175 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004176 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004177 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004178 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004179
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004180 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004181 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004182 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004183 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004184 if (Sum >= OpSizeInBits)
4185 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004186 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004187 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004188 }
4189 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004190
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004191 // fold (sra (shl X, m), (sub result_size, n))
4192 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004193 // result_size - n != m.
4194 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004195 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004196 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004197 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004198 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4199 if (N01C) {
4200 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004201 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004202 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4203
4204 if (VT.isVector())
4205 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4206
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004207 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004208 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004209
Scott Michelcf0da6c2009-02-17 22:15:04 +00004210 // If the shift is not a no-op (in which case this should be just a sign
4211 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004212 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004213 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004214 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004215 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4216 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004217 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004218
Owen Andersonb2c80da2011-02-25 21:41:48 +00004219 SDValue Amt = DAG.getConstant(ShiftAmt,
4220 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004221 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004222 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004223 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004224 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004225 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004226 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004227 }
4228 }
4229 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004230
Duncan Sands3ed76882009-02-01 18:06:53 +00004231 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004232 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004233 N1.getOperand(0).getOpcode() == ISD::AND) {
4234 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4235 if (NewOp1.getNode())
4236 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004237 }
4238
Matt Arsenault985b9de2014-03-17 18:58:01 +00004239 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004240 // if c1 is equal to the number of bits the trunc removes
4241 if (N0.getOpcode() == ISD::TRUNCATE &&
4242 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4243 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4244 N0.getOperand(0).hasOneUse() &&
4245 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004246 N1C) {
4247 SDValue N0Op0 = N0.getOperand(0);
4248 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4249 unsigned LargeShiftVal = LargeShift->getZExtValue();
4250 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004251
Matt Arsenault985b9de2014-03-17 18:58:01 +00004252 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4253 SDValue Amt =
4254 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4255 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4256 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4257 N0Op0.getOperand(0), Amt);
4258 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4259 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004260 }
4261 }
4262
Scott Michelcf0da6c2009-02-17 22:15:04 +00004263 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004264 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4265 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004266
4267
Nate Begeman21158fc2005-09-01 00:19:25 +00004268 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004269 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004270 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004271
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004272 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004273 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004274 if (NewSRA.getNode())
4275 return NewSRA;
4276 }
4277
Evan Chengf1005572010-04-28 07:10:39 +00004278 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004279}
4280
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004281SDValue DAGCombiner::visitSRL(SDNode *N) {
4282 SDValue N0 = N->getOperand(0);
4283 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004284 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4285 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004286 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004287 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004288
Daniel Sandersa1840d22013-11-11 17:23:41 +00004289 // fold vector ops
4290 if (VT.isVector()) {
4291 SDValue FoldedVOp = SimplifyVBinOp(N);
4292 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004293
4294 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004295 }
4296
Nate Begeman21158fc2005-09-01 00:19:25 +00004297 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004298 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004299 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004300 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004301 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004302 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004303 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004304 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004305 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004306 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004307 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004308 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004309 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004310 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004311 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004312 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004313
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004314 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004315 if (N1C && N0.getOpcode() == ISD::SRL) {
4316 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4317 uint64_t c1 = N01C->getZExtValue();
4318 uint64_t c2 = N1C->getZExtValue();
4319 if (c1 + c2 >= OpSizeInBits)
4320 return DAG.getConstant(0, VT);
4321 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4322 DAG.getConstant(c1 + c2, N1.getValueType()));
4323 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004324 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004325
Dale Johannesencd538af2010-12-17 21:45:49 +00004326 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004327 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4328 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004329 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004330 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004331 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4332 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004333 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4334 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004335 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004336 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004337 if (c1 + OpSizeInBits == InnerShiftSize) {
4338 if (c1 + c2 >= InnerShiftSize)
4339 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004340 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4341 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004342 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004343 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004344 }
4345 }
4346
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004347 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004348 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4349 unsigned BitSize = N0.getScalarValueSizeInBits();
4350 if (BitSize <= 64) {
4351 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4352 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4353 DAG.getConstant(~0ULL >> ShAmt, VT));
4354 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004355 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004356
Michael Liao62ebfd82013-06-21 18:45:27 +00004357 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004358 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4359 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004360 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004361 unsigned BitSize = SmallVT.getScalarSizeInBits();
4362 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004363 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004364
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004365 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004366 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004367 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004368 N0.getOperand(0),
4369 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004370 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004371 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004372 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4373 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4374 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004375 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004376 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004377
Chris Lattner2e33fb42006-10-12 20:23:19 +00004378 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4379 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004380 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004381 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004382 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004384
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004385 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004386 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004387 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004388 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004389 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004390
Chris Lattner49932492006-04-02 06:11:11 +00004391 // If any of the input bits are KnownOne, then the input couldn't be all
4392 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004393 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004394
Chris Lattner49932492006-04-02 06:11:11 +00004395 // If all of the bits input the to ctlz node are known to be zero, then
4396 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004397 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004398 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004399
Chris Lattner49932492006-04-02 06:11:11 +00004400 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004401 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004402 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004403 // could be set on input to the CTLZ node. If this bit is set, the SRL
4404 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4405 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004406 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004407 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004408
Chris Lattner49932492006-04-02 06:11:11 +00004409 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004410 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004411 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004412 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004413 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004414
Andrew Trickef9de2a2013-05-25 02:42:55 +00004415 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004416 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004417 }
4418 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004419
Duncan Sands3ed76882009-02-01 18:06:53 +00004420 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004421 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004422 N1.getOperand(0).getOpcode() == ISD::AND) {
4423 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4424 if (NewOp1.getNode())
4425 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004427
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004428 // fold operands of srl based on knowledge that the low bits are not
4429 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004430 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4431 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004432
Evan Chengb175de62009-12-18 21:31:31 +00004433 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004434 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004435 if (NewSRL.getNode())
4436 return NewSRL;
4437 }
4438
Dan Gohman600f62b2010-06-24 14:30:44 +00004439 // Attempt to convert a srl of a load into a narrower zero-extending load.
4440 SDValue NarrowLoad = ReduceLoadWidth(N);
4441 if (NarrowLoad.getNode())
4442 return NarrowLoad;
4443
Evan Chengb175de62009-12-18 21:31:31 +00004444 // Here is a common situation. We want to optimize:
4445 //
4446 // %a = ...
4447 // %b = and i32 %a, 2
4448 // %c = srl i32 %b, 1
4449 // brcond i32 %c ...
4450 //
4451 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004452 //
Evan Chengb175de62009-12-18 21:31:31 +00004453 // %a = ...
4454 // %b = and %a, 2
4455 // %c = setcc eq %b, 0
4456 // brcond %c ...
4457 //
4458 // However when after the source operand of SRL is optimized into AND, the SRL
4459 // itself may not be optimized further. Look for it and add the BRCOND into
4460 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004461 if (N->hasOneUse()) {
4462 SDNode *Use = *N->use_begin();
4463 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004464 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004465 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4466 // Also look pass the truncate.
4467 Use = *Use->use_begin();
4468 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004469 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004470 }
4471 }
Evan Chengb175de62009-12-18 21:31:31 +00004472
Evan Chengf1005572010-04-28 07:10:39 +00004473 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004474}
4475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004476SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4477 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004478 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004479
4480 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004481 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004482 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004483 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004484}
4485
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004486SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4487 SDValue N0 = N->getOperand(0);
4488 EVT VT = N->getValueType(0);
4489
4490 // fold (ctlz_zero_undef c1) -> c2
4491 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004492 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004493 return SDValue();
4494}
4495
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004496SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4497 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004498 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004499
Nate Begeman21158fc2005-09-01 00:19:25 +00004500 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004501 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004502 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004503 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004504}
4505
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004506SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4509
4510 // fold (cttz_zero_undef c1) -> c2
4511 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004512 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004513 return SDValue();
4514}
4515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004516SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004518 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004519
Nate Begeman21158fc2005-09-01 00:19:25 +00004520 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004521 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004523 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004524}
4525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004526SDValue DAGCombiner::visitSELECT(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 SDValue N1 = N->getOperand(1);
4529 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004530 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4531 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4532 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004533 EVT VT = N->getValueType(0);
4534 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004535
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004536 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004537 if (N1 == N2)
4538 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004539 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004540 if (N0C && !N0C->isNullValue())
4541 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004542 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004543 if (N0C && N0C->isNullValue())
4544 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004545 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004546 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004547 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004548 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004549 // We can't do this reliably if integer based booleans have different contents
4550 // to floating point based booleans. This is because we can't tell whether we
4551 // have an integer-based boolean or a floating-point-based boolean unless we
4552 // can find the SETCC that produced it and inspect its operands. This is
4553 // fairly easy if C is the SETCC node, but it can potentially be
4554 // undiscoverable (or not reasonably discoverable). For example, it could be
4555 // in another basic block or it could require searching a complicated
4556 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004557 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004558 (VT0 == MVT::i1 || (VT0.isInteger() &&
4559 TLI.getBooleanContents(false, false) ==
4560 TLI.getBooleanContents(false, true) &&
4561 TLI.getBooleanContents(false, false) ==
4562 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004563 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004564 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004565 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004566 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004567 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004568 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004569 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004570 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004571 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4573 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004574 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004575 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004576 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004577 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004578 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004579 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004580 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004581 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004582 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004583 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004584 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004585 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004586 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004587 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004588 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004589 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004590 // fold (select X, X, Y) -> (or X, Y)
4591 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004592 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004594 // fold (select X, Y, X) -> (and X, Y)
4595 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004596 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004597 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004598
Chris Lattner6c14c352005-10-18 06:04:22 +00004599 // If we can fold this based on the true/false value, do so.
4600 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004601 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004602
Nate Begemanc760f802005-09-19 22:34:01 +00004603 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004604 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004605 if ((!LegalOperations &&
4606 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4607 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004608 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004609 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004610 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004611 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004612 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004613
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004614 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004615}
4616
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004617static
4618std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4619 SDLoc DL(N);
4620 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004621 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004622
4623 // Split the inputs.
4624 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004625 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4626 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004627
4628 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4629 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4630
4631 return std::make_pair(Lo, Hi);
4632}
4633
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004634// This function assumes all the vselect's arguments are CONCAT_VECTOR
4635// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4636static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4637 SDLoc dl(N);
4638 SDValue Cond = N->getOperand(0);
4639 SDValue LHS = N->getOperand(1);
4640 SDValue RHS = N->getOperand(2);
4641 MVT VT = N->getSimpleValueType(0);
4642 int NumElems = VT.getVectorNumElements();
4643 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4644 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4645 Cond.getOpcode() == ISD::BUILD_VECTOR);
4646
4647 // We're sure we have an even number of elements due to the
4648 // concat_vectors we have as arguments to vselect.
4649 // Skip BV elements until we find one that's not an UNDEF
4650 // After we find an UNDEF element, keep looping until we get to half the
4651 // length of the BV and see if all the non-undef nodes are the same.
4652 ConstantSDNode *BottomHalf = nullptr;
4653 for (int i = 0; i < NumElems / 2; ++i) {
4654 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4655 continue;
4656
4657 if (BottomHalf == nullptr)
4658 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4659 else if (Cond->getOperand(i).getNode() != BottomHalf)
4660 return SDValue();
4661 }
4662
4663 // Do the same for the second half of the BuildVector
4664 ConstantSDNode *TopHalf = nullptr;
4665 for (int i = NumElems / 2; i < NumElems; ++i) {
4666 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4667 continue;
4668
4669 if (TopHalf == nullptr)
4670 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4671 else if (Cond->getOperand(i).getNode() != TopHalf)
4672 return SDValue();
4673 }
4674
4675 assert(TopHalf && BottomHalf &&
4676 "One half of the selector was all UNDEFs and the other was all the "
4677 "same value. This should have been addressed before this function.");
4678 return DAG.getNode(
4679 ISD::CONCAT_VECTORS, dl, VT,
4680 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4681 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4682}
4683
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004684SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4685 SDValue N0 = N->getOperand(0);
4686 SDValue N1 = N->getOperand(1);
4687 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004688 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004689
4690 // Canonicalize integer abs.
4691 // vselect (setg[te] X, 0), X, -X ->
4692 // vselect (setgt X, -1), X, -X ->
4693 // vselect (setl[te] X, 0), -X, X ->
4694 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4695 if (N0.getOpcode() == ISD::SETCC) {
4696 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4697 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4698 bool isAbs = false;
4699 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4700
4701 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4702 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4703 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4704 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4705 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4706 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4707 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4708
4709 if (isAbs) {
4710 EVT VT = LHS.getValueType();
4711 SDValue Shift = DAG.getNode(
4712 ISD::SRA, DL, VT, LHS,
4713 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4714 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004715 AddToWorklist(Shift.getNode());
4716 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004717 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4718 }
4719 }
4720
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004721 // If the VSELECT result requires splitting and the mask is provided by a
4722 // SETCC, then split both nodes and its operands before legalization. This
4723 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4724 // and enables future optimizations (e.g. min/max pattern matching on X86).
4725 if (N0.getOpcode() == ISD::SETCC) {
4726 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004727
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004728 // Check if any splitting is required.
4729 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4730 TargetLowering::TypeSplitVector)
4731 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004732
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004733 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004734 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4735 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4736 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004737
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004738 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4739 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004740
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004741 // Add the new VSELECT nodes to the work list in case they need to be split
4742 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004743 AddToWorklist(Lo.getNode());
4744 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004745
4746 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004747 }
4748
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004749 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4750 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4751 return N1;
4752 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4753 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4754 return N2;
4755
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004756 // The ConvertSelectToConcatVector function is assuming both the above
4757 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4758 // and addressed.
4759 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4760 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4761 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4762 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4763 if (CV.getNode())
4764 return CV;
4765 }
4766
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004767 return SDValue();
4768}
4769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004770SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4771 SDValue N0 = N->getOperand(0);
4772 SDValue N1 = N->getOperand(1);
4773 SDValue N2 = N->getOperand(2);
4774 SDValue N3 = N->getOperand(3);
4775 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004776 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004777
Nate Begemanc760f802005-09-19 22:34:01 +00004778 // fold select_cc lhs, rhs, x, x, cc -> x
4779 if (N2 == N3)
4780 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004781
Chris Lattner8b68dec2006-09-20 06:19:26 +00004782 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004783 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004784 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004785 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004786 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004787
Stephen Lin605207f2013-06-15 04:03:33 +00004788 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4789 if (!SCCC->isNullValue())
4790 return N2; // cond always true -> true val
4791 else
4792 return N3; // cond always false -> false val
4793 }
4794
4795 // Fold to a simpler select_cc
4796 if (SCC.getOpcode() == ISD::SETCC)
4797 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4798 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4799 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004801
Chris Lattner6c14c352005-10-18 06:04:22 +00004802 // If we can fold this based on the true/false value, do so.
4803 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004804 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004805
Nate Begemanc760f802005-09-19 22:34:01 +00004806 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004807 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004808}
4809
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004810SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004811 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004812 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004813 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004814}
4815
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004816// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4817// dag node into a ConstantSDNode or a build_vector of constants.
4818// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004819// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004820// Vector extends are not folded if operations are legal; this is to
4821// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004822static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4823 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004824 bool LegalOperations) {
4825 unsigned Opcode = N->getOpcode();
4826 SDValue N0 = N->getOperand(0);
4827 EVT VT = N->getValueType(0);
4828
4829 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4830 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4831
4832 // fold (sext c1) -> c1
4833 // fold (zext c1) -> c1
4834 // fold (aext c1) -> c1
4835 if (isa<ConstantSDNode>(N0))
4836 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4837
4838 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4839 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4840 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004841 EVT SVT = VT.getScalarType();
4842 if (!(VT.isVector() &&
4843 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004844 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004845 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004846
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004847 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004848 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004849 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4850 unsigned ShAmt = VTBits - EVTBits;
4851 SmallVector<SDValue, 8> Elts;
4852 unsigned NumElts = N0->getNumOperands();
4853 SDLoc DL(N);
4854
4855 for (unsigned i=0; i != NumElts; ++i) {
4856 SDValue Op = N0->getOperand(i);
4857 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004858 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004859 continue;
4860 }
4861
4862 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4863 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4864 if (Opcode == ISD::SIGN_EXTEND)
4865 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004866 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004867 else
4868 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004869 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004870 }
4871
Craig Topper48d114b2014-04-26 18:35:24 +00004872 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004873}
4874
Evan Chenge106e2f2007-10-29 19:58:20 +00004875// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004876// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004877// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004878// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004879static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004880 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004881 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004882 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004883 bool HasCopyToRegUses = false;
4884 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004885 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4886 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004887 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004888 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004889 if (User == N)
4890 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004891 if (UI.getUse().getResNo() != N0.getResNo())
4892 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004893 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004894 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004895 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4896 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4897 // Sign bits will be lost after a zext.
4898 return false;
4899 bool Add = false;
4900 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004901 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004902 if (UseOp == N0)
4903 continue;
4904 if (!isa<ConstantSDNode>(UseOp))
4905 return false;
4906 Add = true;
4907 }
4908 if (Add)
4909 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004910 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004911 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004912 // If truncates aren't free and there are users we can't
4913 // extend, it isn't worthwhile.
4914 if (!isTruncFree)
4915 return false;
4916 // Remember if this value is live-out.
4917 if (User->getOpcode() == ISD::CopyToReg)
4918 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004919 }
4920
4921 if (HasCopyToRegUses) {
4922 bool BothLiveOut = false;
4923 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4924 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004925 SDUse &Use = UI.getUse();
4926 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4927 BothLiveOut = true;
4928 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004929 }
4930 }
4931 if (BothLiveOut)
4932 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004933 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004934 return ExtendNodes.size();
4935 }
4936 return true;
4937}
4938
Craig Toppere0b71182013-07-13 07:43:40 +00004939void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004940 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004941 ISD::NodeType ExtType) {
4942 // Extend SetCC uses if necessary.
4943 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4944 SDNode *SetCC = SetCCs[i];
4945 SmallVector<SDValue, 4> Ops;
4946
4947 for (unsigned j = 0; j != 2; ++j) {
4948 SDValue SOp = SetCC->getOperand(j);
4949 if (SOp == Trunc)
4950 Ops.push_back(ExtLoad);
4951 else
4952 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4953 }
4954
4955 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004956 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004957 }
4958}
4959
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004960SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4961 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004962 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004963
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004964 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4965 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004966 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004967
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004968 // fold (sext (sext x)) -> (sext x)
4969 // fold (sext (aext x)) -> (sext x)
4970 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004971 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004972 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004973
Chris Lattnerfce448f2007-02-26 03:13:59 +00004974 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004975 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4976 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004977 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4978 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004979 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4980 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004981 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004982 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004983 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004984 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004986 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004987
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004988 // See if the value being truncated is already sign extended. If so, just
4989 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004990 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004991 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4992 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4993 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004994 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004995
Chris Lattnerfce448f2007-02-26 03:13:59 +00004996 if (OpBits == DestBits) {
4997 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4998 // bits, it is already ready.
4999 if (NumSignBits > DestBits-MidBits)
5000 return Op;
5001 } else if (OpBits < DestBits) {
5002 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5003 // bits, just sext from i32.
5004 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005005 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005006 } else {
5007 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5008 // bits, just truncate to i32.
5009 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005010 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005011 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005012
Chris Lattnerfce448f2007-02-26 03:13:59 +00005013 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005014 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5015 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005016 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005017 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005018 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005019 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5020 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005021 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005022 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005024
Evan Chengbce7c472005-12-14 02:19:23 +00005025 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005026 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005027 // on vectors in one instruction. We only perform this transformation on
5028 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005029 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005030 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005031 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005032 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005033 bool DoXform = true;
5034 SmallVector<SDNode*, 4> SetCCs;
5035 if (!N0.hasOneUse())
5036 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5037 if (DoXform) {
5038 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005039 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005040 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005041 LN0->getBasePtr(), N0.getValueType(),
5042 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005043 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005044 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005045 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005046 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005047 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005048 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005050 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005051 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005052
5053 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5054 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005055 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5056 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005057 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005058 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005059 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005060 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005061 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005062 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005063 LN0->getBasePtr(), MemVT,
5064 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005065 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005066 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005067 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005068 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005069 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005070 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005071 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005072 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005073
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005074 // fold (sext (and/or/xor (load x), cst)) ->
5075 // (and/or/xor (sextload x), (sext cst))
5076 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5077 N0.getOpcode() == ISD::XOR) &&
5078 isa<LoadSDNode>(N0.getOperand(0)) &&
5079 N0.getOperand(1).getOpcode() == ISD::Constant &&
5080 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5081 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5082 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005083 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005084 bool DoXform = true;
5085 SmallVector<SDNode*, 4> SetCCs;
5086 if (!N0.hasOneUse())
5087 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5088 SetCCs, TLI);
5089 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005091 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005092 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005093 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005094 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5095 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005096 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005097 ExtLoad, DAG.getConstant(Mask, VT));
5098 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005099 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005100 N0.getOperand(0).getValueType(), ExtLoad);
5101 CombineTo(N, And);
5102 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005103 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005104 ISD::SIGN_EXTEND);
5105 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5106 }
5107 }
5108 }
5109
Chris Lattner65786b02007-04-11 05:32:27 +00005110 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005111 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005112 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005113 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005114 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005115 TLI.getBooleanContents(N0VT) ==
5116 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005117 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5118 // of the same size as the compared operands. Only optimize sext(setcc())
5119 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005120 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005121
5122 // We know that the # elements of the results is the same as the
5123 // # elements of the compare (and the # elements of the compare result
5124 // for that matter). Check to see that they are the same size. If so,
5125 // we know that the element size of the sext'd result matches the
5126 // element size of the compare operands.
5127 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005128 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005129 N0.getOperand(1),
5130 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005131
Dan Gohmane82c25e2010-04-30 17:19:19 +00005132 // If the desired elements are smaller or larger than the source
5133 // elements we can use a matching integer vector type and then
5134 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005135 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005136 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005137 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005138 N0.getOperand(0), N0.getOperand(1),
5139 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005140 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005141 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005142 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005143
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005144 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005145 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005146 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005147 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005148 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005149 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005150 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005151 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005152 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005153
5154 if (!VT.isVector()) {
5155 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5156 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5157 SDLoc DL(N);
5158 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5159 SDValue SetCC = DAG.getSetCC(DL,
5160 SetCCVT,
5161 N0.getOperand(0), N0.getOperand(1), CC);
5162 EVT SelectVT = getSetCCResultType(VT);
5163 return DAG.getSelect(DL, VT,
5164 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5165 NegOne, DAG.getConstant(0, VT));
5166
5167 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005168 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005169 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005170
Dan Gohman3eb10f72008-04-28 16:58:24 +00005171 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005172 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005173 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005174 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005175
Evan Chengf1005572010-04-28 07:10:39 +00005176 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005177}
5178
Rafael Espindola8f62b322012-04-09 16:06:03 +00005179// isTruncateOf - If N is a truncate of some other value, return true, record
5180// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5181// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005182// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005183static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5184 APInt &KnownZero) {
5185 APInt KnownOne;
5186 if (N->getOpcode() == ISD::TRUNCATE) {
5187 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005188 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005189 return true;
5190 }
5191
5192 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5193 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5194 return false;
5195
5196 SDValue Op0 = N->getOperand(0);
5197 SDValue Op1 = N->getOperand(1);
5198 assert(Op0.getValueType() == Op1.getValueType());
5199
5200 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5201 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005202 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005203 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005204 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005205 Op = Op0;
5206 else
5207 return false;
5208
Jay Foada0653a32014-05-14 21:14:37 +00005209 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005210
5211 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5212 return false;
5213
5214 return true;
5215}
5216
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005217SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5218 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005219 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005220
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005221 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5222 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005223 return SDValue(Res, 0);
5224
Nate Begeman21158fc2005-09-01 00:19:25 +00005225 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005226 // fold (zext (aext x)) -> (zext x)
5227 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005228 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005229 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005230
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005231 // fold (zext (truncate x)) -> (zext x) or
5232 // (zext (truncate x)) -> (truncate x)
5233 // This is valid when the truncated bits of x are already zero.
5234 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005235 SDValue Op;
5236 APInt KnownZero;
5237 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5238 APInt TruncatedBits =
5239 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5240 APInt(Op.getValueSizeInBits(), 0) :
5241 APInt::getBitsSet(Op.getValueSizeInBits(),
5242 N0.getValueSizeInBits(),
5243 std::min(Op.getValueSizeInBits(),
5244 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005245 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005246 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005247 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005248 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005249 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005250
5251 return Op;
5252 }
5253 }
5254
Evan Cheng464dc9b2007-03-22 01:54:19 +00005255 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5256 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005257 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005258 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5259 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005260 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5261 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005262 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005263 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005264 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005265 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005267 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005268 }
5269
Chris Lattnera31f0a62006-09-21 06:00:20 +00005270 // fold (zext (truncate x)) -> (and x, mask)
5271 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005272 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005273
5274 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5275 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5276 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5277 if (NarrowLoad.getNode()) {
5278 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5279 if (NarrowLoad.getNode() != N0.getNode()) {
5280 CombineTo(N0.getNode(), NarrowLoad);
5281 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005282 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005283 }
5284 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5285 }
5286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005287 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005288 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005289 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005290 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005291 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005292 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005293 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005294 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005295 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005296 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005298
Dan Gohmanad3e5492009-04-08 00:15:30 +00005299 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5300 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005301 if (N0.getOpcode() == ISD::AND &&
5302 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005303 N0.getOperand(1).getOpcode() == ISD::Constant &&
5304 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5305 N0.getValueType()) ||
5306 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005307 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005308 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005309 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005310 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005311 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005312 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005313 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005314 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005315 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005316 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005317 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005318
Evan Chengbce7c472005-12-14 02:19:23 +00005319 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005320 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005321 // on vectors in one instruction. We only perform this transformation on
5322 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005323 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005324 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005325 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005326 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005327 bool DoXform = true;
5328 SmallVector<SDNode*, 4> SetCCs;
5329 if (!N0.hasOneUse())
5330 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5331 if (DoXform) {
5332 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005334 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005335 LN0->getBasePtr(), N0.getValueType(),
5336 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005337 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005338 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005339 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005340 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005341
Andrew Trickef9de2a2013-05-25 02:42:55 +00005342 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005343 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005344 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005345 }
Evan Chengbce7c472005-12-14 02:19:23 +00005346 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005347
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005348 // fold (zext (and/or/xor (load x), cst)) ->
5349 // (and/or/xor (zextload x), (zext cst))
5350 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5351 N0.getOpcode() == ISD::XOR) &&
5352 isa<LoadSDNode>(N0.getOperand(0)) &&
5353 N0.getOperand(1).getOpcode() == ISD::Constant &&
5354 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5355 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5356 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005357 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005358 bool DoXform = true;
5359 SmallVector<SDNode*, 4> SetCCs;
5360 if (!N0.hasOneUse())
5361 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5362 SetCCs, TLI);
5363 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005364 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005365 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005366 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005367 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005368 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5369 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005370 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005371 ExtLoad, DAG.getConstant(Mask, VT));
5372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005373 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005374 N0.getOperand(0).getValueType(), ExtLoad);
5375 CombineTo(N, And);
5376 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005377 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005378 ISD::ZERO_EXTEND);
5379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5380 }
5381 }
5382 }
5383
Chris Lattner7dac1082005-12-14 19:05:06 +00005384 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5385 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005386 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5387 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005389 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005390 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005391 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005392 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005393 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005394 LN0->getBasePtr(), MemVT,
5395 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005396 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005397 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005399 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005400 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005402 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005404
Chris Lattner65786b02007-04-11 05:32:27 +00005405 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005406 if (!LegalOperations && VT.isVector() &&
5407 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005408 EVT N0VT = N0.getOperand(0).getValueType();
5409 if (getSetCCResultType(N0VT) == N0.getValueType())
5410 return SDValue();
5411
Evan Chengabd0ad52010-05-19 01:08:17 +00005412 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5413 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005414 EVT EltVT = VT.getVectorElementType();
5415 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5416 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005417 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005418 // We know that the # elements of the results is the same as the
5419 // # elements of the compare (and the # elements of the compare result
5420 // for that matter). Check to see that they are the same size. If so,
5421 // we know that the element size of the sext'd result matches the
5422 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005423 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5424 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005425 N0.getOperand(1),
5426 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005427 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005428 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005429
5430 // If the desired elements are smaller or larger than the source
5431 // elements we can use a matching integer vector type and then
5432 // truncate/sign extend
5433 EVT MatchingElementType =
5434 EVT::getIntegerVT(*DAG.getContext(),
5435 N0VT.getScalarType().getSizeInBits());
5436 EVT MatchingVectorType =
5437 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5438 N0VT.getVectorNumElements());
5439 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005440 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005441 N0.getOperand(1),
5442 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005443 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5444 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005445 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005446 }
5447
5448 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005449 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005450 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005451 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005452 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005453 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005454 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005455
Evan Cheng852c4862009-12-15 03:00:32 +00005456 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005457 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005458 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005459 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5460 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005461 SDValue ShAmt = N0.getOperand(1);
5462 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005463 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005464 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005465 // If the original shl may be shifting out bits, do not perform this
5466 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005467 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5468 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5469 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005470 return SDValue();
5471 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005472
Andrew Trickef9de2a2013-05-25 02:42:55 +00005473 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005474
5475 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005476 if (VT.getSizeInBits() >= 256)
5477 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005478
Chris Lattnere95d1952011-02-13 19:09:16 +00005479 return DAG.getNode(N0.getOpcode(), DL, VT,
5480 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5481 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005482 }
5483
Evan Chengf1005572010-04-28 07:10:39 +00005484 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005485}
5486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005487SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5488 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005489 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005490
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005491 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5492 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005493 return SDValue(Res, 0);
5494
Chris Lattner812646a2006-05-05 05:58:59 +00005495 // fold (aext (aext x)) -> (aext x)
5496 // fold (aext (zext x)) -> (zext x)
5497 // fold (aext (sext x)) -> (sext x)
5498 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5499 N0.getOpcode() == ISD::ZERO_EXTEND ||
5500 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005501 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005502
Evan Cheng464dc9b2007-03-22 01:54:19 +00005503 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5504 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5505 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005506 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5507 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005508 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5509 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005510 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005511 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005512 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005513 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005514 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005515 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005516 }
5517
Chris Lattner8746e2c2006-09-20 06:29:17 +00005518 // fold (aext (truncate x))
5519 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005520 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005521 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005522 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005523 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005524 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5525 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005526 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005527
Dan Gohmanad3e5492009-04-08 00:15:30 +00005528 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5529 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005530 if (N0.getOpcode() == ISD::AND &&
5531 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005532 N0.getOperand(1).getOpcode() == ISD::Constant &&
5533 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5534 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005535 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005536 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005537 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005538 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005539 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005540 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005541 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005542 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005543 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005544 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005545 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005546
Chris Lattner812646a2006-05-05 05:58:59 +00005547 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005548 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005549 // on vectors in one instruction. We only perform this transformation on
5550 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005551 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005552 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005553 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005554 bool DoXform = true;
5555 SmallVector<SDNode*, 4> SetCCs;
5556 if (!N0.hasOneUse())
5557 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5558 if (DoXform) {
5559 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005560 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005561 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005562 LN0->getBasePtr(), N0.getValueType(),
5563 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005564 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005565 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005566 N0.getValueType(), ExtLoad);
5567 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005568 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005569 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005570 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5571 }
Chris Lattner812646a2006-05-05 05:58:59 +00005572 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005573
Chris Lattner812646a2006-05-05 05:58:59 +00005574 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5575 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5576 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005577 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005578 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005579 N0.hasOneUse()) {
5580 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005581 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005582 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005583 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5584 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5585 VT, LN0->getChain(), LN0->getBasePtr(),
5586 MemVT, LN0->getMemOperand());
5587 CombineTo(N, ExtLoad);
5588 CombineTo(N0.getNode(),
5589 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5590 N0.getValueType(), ExtLoad),
5591 ExtLoad.getValue(1));
5592 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5593 }
Chris Lattner812646a2006-05-05 05:58:59 +00005594 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005595
Chris Lattner65786b02007-04-11 05:32:27 +00005596 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005597 // For vectors:
5598 // aext(setcc) -> vsetcc
5599 // aext(setcc) -> truncate(vsetcc)
5600 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005601 // Only do this before legalize for now.
5602 if (VT.isVector() && !LegalOperations) {
5603 EVT N0VT = N0.getOperand(0).getValueType();
5604 // We know that the # elements of the results is the same as the
5605 // # elements of the compare (and the # elements of the compare result
5606 // for that matter). Check to see that they are the same size. If so,
5607 // we know that the element size of the sext'd result matches the
5608 // element size of the compare operands.
5609 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005610 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005611 N0.getOperand(1),
5612 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005613 // If the desired elements are smaller or larger than the source
5614 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005615 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005616 else {
Hao Liuc636d152014-04-22 09:57:06 +00005617 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005618 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005619 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005620 N0.getOperand(1),
5621 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005622 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005623 }
5624 }
5625
5626 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005627 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005628 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005629 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005630 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005631 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005632 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005633 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005634
Evan Chengf1005572010-04-28 07:10:39 +00005635 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005636}
5637
Chris Lattner5e6fe052007-10-13 06:35:54 +00005638/// GetDemandedBits - See if the specified operand can be simplified with the
5639/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005640/// simpler operand, otherwise return a null SDValue.
5641SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005642 switch (V.getOpcode()) {
5643 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005644 case ISD::Constant: {
5645 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005646 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005647 const APInt &CVal = CV->getAPIntValue();
5648 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005649 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005650 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005651 break;
5652 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005653 case ISD::OR:
5654 case ISD::XOR:
5655 // If the LHS or RHS don't contribute bits to the or, drop them.
5656 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5657 return V.getOperand(1);
5658 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5659 return V.getOperand(0);
5660 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005661 case ISD::SRL:
5662 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005663 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005664 break;
5665 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5666 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005667 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005668
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005669 // Watch out for shift count overflow though.
5670 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005671 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005672 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005673 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005674 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005675 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005676 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005677 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005678 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005679}
5680
Evan Cheng464dc9b2007-03-22 01:54:19 +00005681/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5682/// bits and then truncated to a narrower type and where N is a multiple
5683/// of number of bits of the narrower type, transform it to a narrower load
5684/// from address + N / num of bits of new type. If the result is to be
5685/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005686SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005687 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005688
Evan Cheng464dc9b2007-03-22 01:54:19 +00005689 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005690 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005691 EVT VT = N->getValueType(0);
5692 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005693
Dan Gohman550c9af2008-08-14 20:04:46 +00005694 // This transformation isn't valid for vector loads.
5695 if (VT.isVector())
5696 return SDValue();
5697
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005698 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005699 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005700 if (Opc == ISD::SIGN_EXTEND_INREG) {
5701 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005702 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005703 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005704 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005705 ExtType = ISD::ZEXTLOAD;
5706 N0 = SDValue(N, 0);
5707 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5708 if (!N01) return SDValue();
5709 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5710 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005711 }
Richard Osborne272e0842011-01-31 17:41:44 +00005712 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5713 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005714
Owen Anderson53aa7a92009-08-10 22:56:29 +00005715 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005716
Chris Lattner9a499e92010-12-22 08:01:44 +00005717 // Do not generate loads of non-round integer types since these can
5718 // be expensive (and would be wrong if the type is not byte sized).
5719 if (!ExtVT.isRound())
5720 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005721
Evan Cheng464dc9b2007-03-22 01:54:19 +00005722 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005723 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005724 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005725 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005726 // Is the shift amount a multiple of size of VT?
5727 if ((ShAmt & (EVTBits-1)) == 0) {
5728 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005729 // Is the load width a multiple of size of VT?
5730 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005731 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005732 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005733
Chris Lattnercafc1e62010-12-22 08:02:57 +00005734 // At this point, we must have a load or else we can't do the transform.
5735 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005736
Chandler Carruthb27041c2012-12-11 00:36:57 +00005737 // Because a SRL must be assumed to *need* to zero-extend the high bits
5738 // (as opposed to anyext the high bits), we can't combine the zextload
5739 // lowering of SRL and an sextload.
5740 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5741 return SDValue();
5742
Chris Lattnera2050552010-10-01 05:36:09 +00005743 // If the shift amount is larger than the input type then we're not
5744 // accessing any of the loaded bytes. If the load was a zextload/extload
5745 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005746 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005747 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005748 }
5749 }
5750
Dan Gohman68fb0042010-11-03 01:47:46 +00005751 // If the load is shifted left (and the result isn't shifted back right),
5752 // we can fold the truncate through the shift.
5753 unsigned ShLeftAmt = 0;
5754 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005755 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005756 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5757 ShLeftAmt = N01->getZExtValue();
5758 N0 = N0.getOperand(0);
5759 }
5760 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005761
Chris Lattner222374d2010-12-22 07:36:50 +00005762 // If we haven't found a load, we can't narrow it. Don't transform one with
5763 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005764 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5765 return SDValue();
5766
5767 // Don't change the width of a volatile load.
5768 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5769 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005770 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005771
Chris Lattner9a499e92010-12-22 08:01:44 +00005772 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005773 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005774 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005775
Bill Schmidtd006c692013-01-14 22:04:38 +00005776 // For the transform to be legal, the load must produce only two values
5777 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005778 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005779 // transformation is not equivalent, and the downstream logic to replace
5780 // uses gets things wrong.
5781 if (LN0->getNumValues() > 2)
5782 return SDValue();
5783
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005784 // If the load that we're shrinking is an extload and we're not just
5785 // discarding the extension we can't simply shrink the load. Bail.
5786 // TODO: It would be possible to merge the extensions in some cases.
5787 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5788 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5789 return SDValue();
5790
Chris Lattner222374d2010-12-22 07:36:50 +00005791 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005792
Evan Cheng4c6f9172012-06-26 01:19:33 +00005793 if (PtrType == MVT::Untyped || PtrType.isExtended())
5794 // It's not possible to generate a constant of extended or untyped type.
5795 return SDValue();
5796
Chris Lattner222374d2010-12-22 07:36:50 +00005797 // For big endian targets, we need to adjust the offset to the pointer to
5798 // load the correct bytes.
5799 if (TLI.isBigEndian()) {
5800 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5801 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5802 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005803 }
5804
Chris Lattner222374d2010-12-22 07:36:50 +00005805 uint64_t PtrOff = ShAmt / 8;
5806 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005807 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005808 PtrType, LN0->getBasePtr(),
5809 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005810 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005811
Chris Lattner9a499e92010-12-22 08:01:44 +00005812 SDValue Load;
5813 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005814 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005815 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005816 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005817 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005818 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005819 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005820 LN0->getPointerInfo().getWithOffset(PtrOff),
5821 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005822 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005823
5824 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005825 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005826 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005827
5828 // Shift the result left, if we've swallowed a left shift.
5829 SDValue Result = Load;
5830 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005831 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005832 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5833 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005834 // If the shift amount is as large as the result size (but, presumably,
5835 // no larger than the source) then the useful bits of the result are
5836 // zero; we can't simply return the shortened shift, because the result
5837 // of that operation is undefined.
5838 if (ShLeftAmt >= VT.getSizeInBits())
5839 Result = DAG.getConstant(0, VT);
5840 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005841 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005842 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005843 }
5844
5845 // Return the new loaded value.
5846 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005847}
5848
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005849SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5850 SDValue N0 = N->getOperand(0);
5851 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005852 EVT VT = N->getValueType(0);
5853 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005854 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005855 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005856
Nate Begeman21158fc2005-09-01 00:19:25 +00005857 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005858 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005859 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005860
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005861 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005862 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005863 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005864
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005865 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5866 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005867 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005868 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005869 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005870
Dan Gohman345d63c2008-07-31 00:50:31 +00005871 // fold (sext_in_reg (sext x)) -> (sext x)
5872 // fold (sext_in_reg (aext x)) -> (sext x)
5873 // if x is small enough.
5874 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5875 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005876 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5877 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005878 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005879 }
5880
Chris Lattner9ad59152007-04-17 19:03:21 +00005881 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005882 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005883 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005884
Chris Lattner9ad59152007-04-17 19:03:21 +00005885 // fold operands of sext_in_reg based on knowledge that the top bits are not
5886 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005887 if (SimplifyDemandedBits(SDValue(N, 0)))
5888 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005889
Evan Cheng464dc9b2007-03-22 01:54:19 +00005890 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5891 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005892 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005893 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005894 return NarrowLoad;
5895
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005896 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005897 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005898 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5899 if (N0.getOpcode() == ISD::SRL) {
5900 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005901 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005902 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005903 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005904 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005905 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005906 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005907 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005908 }
5909 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005910
Nate Begeman02b23c62005-10-13 03:11:28 +00005911 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005912 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005913 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005914 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005915 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005916 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005917 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005918 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005919 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005920 LN0->getBasePtr(), EVT,
5921 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005922 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005923 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005924 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005926 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005927 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005928 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005929 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005930 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005931 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005932 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005935 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005936 LN0->getBasePtr(), EVT,
5937 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005938 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005939 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005940 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005941 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005942
5943 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5944 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5945 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5946 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005947 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005948 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005949 BSwap, N1);
5950 }
5951
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005952 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5953 // into a build_vector.
5954 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5955 SmallVector<SDValue, 8> Elts;
5956 unsigned NumElts = N0->getNumOperands();
5957 unsigned ShAmt = VTBits - EVTBits;
5958
5959 for (unsigned i = 0; i != NumElts; ++i) {
5960 SDValue Op = N0->getOperand(i);
5961 if (Op->getOpcode() == ISD::UNDEF) {
5962 Elts.push_back(Op);
5963 continue;
5964 }
5965
5966 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005967 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5968 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005969 Op.getValueType()));
5970 }
5971
Craig Topper48d114b2014-04-26 18:35:24 +00005972 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005973 }
5974
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005975 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005976}
5977
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005978SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5979 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005980 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005981 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005982
5983 // noop truncate
5984 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005985 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005986 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005987 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005989 // fold (truncate (truncate x)) -> (truncate x)
5990 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005991 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005992 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005993 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5994 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005995 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005996 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005997 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005998 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005999 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006000 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006001 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006002 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006003 // if the source and dest are the same type, we can drop both the extend
6004 // and the truncate.
6005 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006006 }
Evan Chengd63baea2007-03-21 20:14:05 +00006007
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006008 // Fold extract-and-trunc into a narrow extract. For example:
6009 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6010 // i32 y = TRUNCATE(i64 x)
6011 // -- becomes --
6012 // v16i8 b = BITCAST (v2i64 val)
6013 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6014 //
6015 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006016 // creates this pattern) and before operation legalization after which
6017 // we need to be more careful about the vector instructions that we generate.
6018 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006019 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006020
6021 EVT VecTy = N0.getOperand(0).getValueType();
6022 EVT ExTy = N0.getValueType();
6023 EVT TrTy = N->getValueType(0);
6024
6025 unsigned NumElem = VecTy.getVectorNumElements();
6026 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6027
6028 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6029 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6030
6031 SDValue EltNo = N0->getOperand(1);
6032 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6033 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006034 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006035 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6036
Andrew Trickef9de2a2013-05-25 02:42:55 +00006037 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006038 NVT, N0.getOperand(0));
6039
6040 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006041 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006042 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006043 }
6044 }
6045
Matt Arsenault3332b702014-07-10 18:21:04 +00006046 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6047 if (N0.getOpcode() == ISD::SELECT) {
6048 EVT SrcVT = N0.getValueType();
6049 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6050 TLI.isTruncateFree(SrcVT, VT)) {
6051 SDLoc SL(N0);
6052 SDValue Cond = N0.getOperand(0);
6053 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6054 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6055 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6056 }
6057 }
6058
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006059 // Fold a series of buildvector, bitcast, and truncate if possible.
6060 // For example fold
6061 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6062 // (2xi32 (buildvector x, y)).
6063 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6064 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6065 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6066 N0.getOperand(0).hasOneUse()) {
6067
6068 SDValue BuildVect = N0.getOperand(0);
6069 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6070 EVT TruncVecEltTy = VT.getVectorElementType();
6071
6072 // Check that the element types match.
6073 if (BuildVectEltTy == TruncVecEltTy) {
6074 // Now we only need to compute the offset of the truncated elements.
6075 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6076 unsigned TruncVecNumElts = VT.getVectorNumElements();
6077 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6078
6079 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6080 "Invalid number of elements");
6081
6082 SmallVector<SDValue, 8> Opnds;
6083 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6084 Opnds.push_back(BuildVect.getOperand(i));
6085
Craig Topper48d114b2014-04-26 18:35:24 +00006086 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006087 }
6088 }
6089
Chris Lattner5e6fe052007-10-13 06:35:54 +00006090 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006091 // only the low bits are being used.
6092 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006093 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006094 // may have different active low bits.
6095 if (!VT.isVector()) {
6096 SDValue Shorter =
6097 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6098 VT.getSizeInBits()));
6099 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006100 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006101 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006102 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006103 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006104 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6105 SDValue Reduced = ReduceLoadWidth(N);
6106 if (Reduced.getNode())
6107 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006108 // Handle the case where the load remains an extending load even
6109 // after truncation.
6110 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6111 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6112 if (!LN0->isVolatile() &&
6113 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6114 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6115 VT, LN0->getChain(), LN0->getBasePtr(),
6116 LN0->getMemoryVT(),
6117 LN0->getMemOperand());
6118 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6119 return NewLoad;
6120 }
6121 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006122 }
Michael Liao3ac82012012-10-17 23:45:54 +00006123 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6124 // where ... are all 'undef'.
6125 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6126 SmallVector<EVT, 8> VTs;
6127 SDValue V;
6128 unsigned Idx = 0;
6129 unsigned NumDefs = 0;
6130
6131 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6132 SDValue X = N0.getOperand(i);
6133 if (X.getOpcode() != ISD::UNDEF) {
6134 V = X;
6135 Idx = i;
6136 NumDefs++;
6137 }
6138 // Stop if more than one members are non-undef.
6139 if (NumDefs > 1)
6140 break;
6141 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6142 VT.getVectorElementType(),
6143 X.getValueType().getVectorNumElements()));
6144 }
6145
6146 if (NumDefs == 0)
6147 return DAG.getUNDEF(VT);
6148
6149 if (NumDefs == 1) {
6150 assert(V.getNode() && "The single defined operand is empty!");
6151 SmallVector<SDValue, 8> Opnds;
6152 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6153 if (i != Idx) {
6154 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6155 continue;
6156 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006157 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006158 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006159 Opnds.push_back(NV);
6160 }
Craig Topper48d114b2014-04-26 18:35:24 +00006161 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006162 }
6163 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006164
6165 // Simplify the operands using demanded-bits information.
6166 if (!VT.isVector() &&
6167 SimplifyDemandedBits(SDValue(N, 0)))
6168 return SDValue(N, 0);
6169
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006170 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006171}
6172
Evan Chengb980f6f2008-05-12 23:04:07 +00006173static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006174 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006175 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006176 return Elt.getNode();
6177 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006178}
6179
6180/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006181/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006182SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006183 assert(N->getOpcode() == ISD::BUILD_PAIR);
6184
Nate Begeman624690c2009-06-05 21:37:30 +00006185 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6186 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006187 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006188 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006189 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006190 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006191
Evan Chengb980f6f2008-05-12 23:04:07 +00006192 if (ISD::isNON_EXTLoad(LD2) &&
6193 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006194 // If both are volatile this would reduce the number of volatile loads.
6195 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006196 !LD1->isVolatile() &&
6197 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006198 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006199 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006200 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006201 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006202
Duncan Sands8651e9c2008-06-13 19:07:40 +00006203 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006204 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006205 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006206 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006207 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006208 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006210 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006211}
6212
Wesley Peck527da1b2010-11-23 03:31:01 +00006213SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006214 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006215 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006216
Dan Gohmana8665142007-06-25 16:23:39 +00006217 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6218 // Only do this before legalize, since afterward the target may be depending
6219 // on the bitconvert.
6220 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006221 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006222 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006223 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006224 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006225
Owen Anderson53aa7a92009-08-10 22:56:29 +00006226 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006227 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006228 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006229 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006230 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006231 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006232
Dan Gohman921ddd62008-09-05 01:58:21 +00006233 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006234 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006235 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006236 if (Res.getNode() != N) {
6237 if (!LegalOperations ||
6238 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6239 return Res;
6240
6241 // Folding it resulted in an illegal node, and it's too late to
6242 // do that. Clean up the old node and forego the transformation.
6243 // Ideally this won't happen very often, because instcombine
6244 // and the earlier dagcombine runs (where illegal nodes are
6245 // permitted) should have folded most of them already.
6246 DAG.DeleteNode(Res.getNode());
6247 }
Chris Lattnera1874602005-12-23 05:30:37 +00006248 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006249
Bill Wendling4e0a6152009-01-30 22:44:24 +00006250 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006251 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006252 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006253 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006254
Chris Lattner54560f62005-12-23 05:44:41 +00006255 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006256 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006257 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006258 // Do not change the width of a volatile load.
6259 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006260 // Do not remove the cast if the types differ in endian layout.
6261 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6262 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006263 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6264 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006265 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006266 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006267 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006268 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006269
Evan Chenga4cf58a2007-05-07 21:27:48 +00006270 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006271 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006272 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006273 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006274 LN0->isInvariant(), OrigAlign,
6275 LN0->getTBAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006276 AddToWorklist(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006277 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006278 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006279 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006280 Load.getValue(1));
6281 return Load;
6282 }
Chris Lattner54560f62005-12-23 05:44:41 +00006283 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006284
Bill Wendling4e0a6152009-01-30 22:44:24 +00006285 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6286 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006287 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006288 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6289 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006290 N0.getNode()->hasOneUse() && VT.isInteger() &&
6291 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006292 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006293 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006294 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006295
Duncan Sands13237ac2008-06-06 12:08:01 +00006296 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006297 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006298 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006299 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006300 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006301 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006302 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006303 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006304
Bill Wendling4e0a6152009-01-30 22:44:24 +00006305 // fold (bitconvert (fcopysign cst, x)) ->
6306 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6307 // Note that we don't handle (copysign x, cst) because this can always be
6308 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006309 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006310 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006311 VT.isInteger() && !VT.isVector()) {
6312 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006313 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006314 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006315 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006316 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006317 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006318
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006319 // If X has a different width than the result/lhs, sext it or truncate it.
6320 unsigned VTWidth = VT.getSizeInBits();
6321 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006322 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006323 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006324 } else if (OrigXWidth > VTWidth) {
6325 // To get the sign bit in the right place, we have to shift it right
6326 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006327 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006328 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006329 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006330 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006331 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006332 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006333 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006334
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006335 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006336 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006337 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006338 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006339
Andrew Trickef9de2a2013-05-25 02:42:55 +00006340 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006341 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006342 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006343 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006344 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006345
Andrew Trickef9de2a2013-05-25 02:42:55 +00006346 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006347 }
Chris Lattner888560d2008-01-27 17:42:27 +00006348 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006349
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006350 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006351 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006352 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6353 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006354 return CombineLD;
6355 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006356
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006357 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006358}
6359
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006360SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006361 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006362 return CombineConsecutiveLoads(N, VT);
6363}
6364
Wesley Peck527da1b2010-11-23 03:31:01 +00006365/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006366/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006367/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006368SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006369ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006370 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006371
Chris Lattnere4e64b62006-04-02 02:53:43 +00006372 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006373 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006374
Duncan Sands13237ac2008-06-06 12:08:01 +00006375 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6376 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006377
Chris Lattnere4e64b62006-04-02 02:53:43 +00006378 // If this is a conversion of N elements of one type to N elements of another
6379 // type, convert each element. This handles FP<->INT cases.
6380 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006381 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6382 BV->getValueType(0).getVectorNumElements());
6383
6384 // Due to the FP element handling below calling this routine recursively,
6385 // we can end up with a scalar-to-vector node here.
6386 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6388 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006389 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006391 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006392 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006393 SDValue Op = BV->getOperand(i);
6394 // If the vector element type is not legal, the BUILD_VECTOR operands
6395 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006396 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006397 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6398 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006399 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006400 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006401 }
Craig Topper48d114b2014-04-26 18:35:24 +00006402 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006404
Chris Lattnere4e64b62006-04-02 02:53:43 +00006405 // Otherwise, we're growing or shrinking the elements. To avoid having to
6406 // handle annoying details of growing/shrinking FP values, we convert them to
6407 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006408 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006409 // Convert the input float vector to a int vector where the elements are the
6410 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006411 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006412 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006413 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006414 SrcEltVT = IntVT;
6415 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006416
Chris Lattnere4e64b62006-04-02 02:53:43 +00006417 // Now we know the input is an integer vector. If the output is a FP type,
6418 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006419 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006420 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006421 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006422 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006423
Chris Lattnere4e64b62006-04-02 02:53:43 +00006424 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006425 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006427
Chris Lattnere4e64b62006-04-02 02:53:43 +00006428 // Okay, we know the src/dst types are both integers of differing types.
6429 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006430 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006431 if (SrcBitSize < DstBitSize) {
6432 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006434 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006435 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006436 i += NumInputsPerOutput) {
6437 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006438 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006439 bool EltIsUndef = true;
6440 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6441 // Shift the previously computed bits over.
6442 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006443 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006444 if (Op.getOpcode() == ISD::UNDEF) continue;
6445 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006446
Jay Foad583abbc2010-12-07 08:25:19 +00006447 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006448 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006450
Chris Lattnere4e64b62006-04-02 02:53:43 +00006451 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006452 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006453 else
6454 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6455 }
6456
Owen Anderson117c9e82009-08-12 00:36:31 +00006457 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006458 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006459 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006460
Chris Lattnere4e64b62006-04-02 02:53:43 +00006461 // Finally, this must be the case where we are shrinking elements: each input
6462 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006463 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006464 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006465 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6466 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006467 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006468
Dan Gohmana8665142007-06-25 16:23:39 +00006469 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006470 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6471 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006472 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006473 continue;
6474 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006475
Jay Foad583abbc2010-12-07 08:25:19 +00006476 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6477 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006478
Chris Lattnere4e64b62006-04-02 02:53:43 +00006479 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006480 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006481 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006482 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006483 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006484 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006485 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006486 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006487 }
6488
6489 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006490 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006491 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6492 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006493
Craig Topper48d114b2014-04-26 18:35:24 +00006494 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006495}
6496
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006497SDValue DAGCombiner::visitFADD(SDNode *N) {
6498 SDValue N0 = N->getOperand(0);
6499 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006500 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6501 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006502 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006503
Dan Gohmana8665142007-06-25 16:23:39 +00006504 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006505 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006506 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006507 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006508 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006509
Lang Hamesa33db652012-06-14 20:37:15 +00006510 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006511 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006512 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006513 // canonicalize constant to RHS
6514 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006515 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006516 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006517 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6518 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006519 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006520 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006521 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006522 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006523 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006524 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006525 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006526 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006527 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006528 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006529 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006530
Chris Lattner0199fd62007-01-08 23:04:05 +00006531 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006532 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6533 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6534 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006535 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6536 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006537 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006538
Shuxin Yang93b1f122013-03-25 22:52:29 +00006539 // No FP constant should be created after legalization as Instruction
6540 // Selection pass has hard time in dealing with FP constant.
6541 //
6542 // We don't need test this condition for transformation like following, as
6543 // the DAG being transformed implies it is legal to take FP constant as
6544 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006545 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006546 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006547 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006548 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6549
Owen Andersonb351c8d2012-11-01 02:00:53 +00006550 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006551 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006552 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006553 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006554
6555 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006556 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006557 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006558 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006559
Owen Andersoncc61f872012-08-30 23:35:16 +00006560 // In unsafe math mode, we can fold chains of FADD's of the same value
6561 // into multiplications. This transform is not safe in general because
6562 // we are reducing the number of rounding steps.
6563 if (DAG.getTarget().Options.UnsafeFPMath &&
6564 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6565 !N0CFP && !N1CFP) {
6566 if (N0.getOpcode() == ISD::FMUL) {
6567 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6568 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6569
Stephen Line31f2d22013-06-14 18:17:35 +00006570 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006571 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006572 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006573 SDValue(CFP00, 0),
6574 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006575 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006576 N1, NewCFP);
6577 }
6578
Stephen Line31f2d22013-06-14 18:17:35 +00006579 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006580 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006581 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006582 SDValue(CFP01, 0),
6583 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006584 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006585 N1, NewCFP);
6586 }
6587
Stephen Line31f2d22013-06-14 18:17:35 +00006588 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006589 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6590 N1.getOperand(0) == N1.getOperand(1) &&
6591 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006592 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006593 SDValue(CFP00, 0),
6594 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006596 N0.getOperand(1), NewCFP);
6597 }
6598
Stephen Line31f2d22013-06-14 18:17:35 +00006599 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006600 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6601 N1.getOperand(0) == N1.getOperand(1) &&
6602 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006603 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006604 SDValue(CFP01, 0),
6605 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006606 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006607 N0.getOperand(0), NewCFP);
6608 }
6609 }
6610
6611 if (N1.getOpcode() == ISD::FMUL) {
6612 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6613 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6614
Stephen Line31f2d22013-06-14 18:17:35 +00006615 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006616 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006617 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006618 SDValue(CFP10, 0),
6619 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006620 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006621 N0, NewCFP);
6622 }
6623
Stephen Line31f2d22013-06-14 18:17:35 +00006624 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006625 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006626 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006627 SDValue(CFP11, 0),
6628 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006629 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006630 N0, NewCFP);
6631 }
6632
Owen Andersoncc61f872012-08-30 23:35:16 +00006633
Stephen Line31f2d22013-06-14 18:17:35 +00006634 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6635 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6636 N0.getOperand(0) == N0.getOperand(1) &&
6637 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006638 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006639 SDValue(CFP10, 0),
6640 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006641 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006642 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006643 }
6644
Stephen Line31f2d22013-06-14 18:17:35 +00006645 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6646 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6647 N0.getOperand(0) == N0.getOperand(1) &&
6648 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006649 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006650 SDValue(CFP11, 0),
6651 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006652 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006653 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006654 }
6655 }
6656
Shuxin Yang93b1f122013-03-25 22:52:29 +00006657 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006658 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006659 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006660 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006661 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006662 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006663 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006664 }
6665
Shuxin Yang93b1f122013-03-25 22:52:29 +00006666 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006667 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006668 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006669 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006670 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006671 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006672 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006673 }
6674
Stephen Lin4e69d012013-06-14 21:33:58 +00006675 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006676 if (AllowNewFpConst &&
6677 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006678 N0.getOperand(0) == N0.getOperand(1) &&
6679 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006680 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006681 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006682 N0.getOperand(0),
6683 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006684 }
6685
Lang Hames39fb1d02012-06-19 22:51:23 +00006686 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006687 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006688 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006689 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6690 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006691
6692 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006693 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006694 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006695 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006696
Michael Liaoec3850122012-09-01 04:09:16 +00006697 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006698 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006699 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006700 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006701 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006702 }
6703
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006704 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006705}
6706
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006707SDValue DAGCombiner::visitFSUB(SDNode *N) {
6708 SDValue N0 = N->getOperand(0);
6709 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6711 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006712 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006713 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006714
Dan Gohmana8665142007-06-25 16:23:39 +00006715 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006716 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006717 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006718 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006719 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006720
Nate Begeman418c6e42005-10-18 00:28:13 +00006721 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006722 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006723 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006724 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006725 if (DAG.getTarget().Options.UnsafeFPMath &&
6726 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006727 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006728 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006729 if (DAG.getTarget().Options.UnsafeFPMath &&
6730 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006731 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006732 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006733 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006734 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006735 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006736 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006737 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006738 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006739 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006740
Bill Wendlingdf170db2012-03-15 05:12:00 +00006741 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006742 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006743 // (fsub x, (fadd x, y)) -> (fneg y) &
6744 // (fsub x, (fadd y, x)) -> (fneg y)
6745 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006746 if (N0 == N1)
6747 return DAG.getConstantFP(0.0f, VT);
6748
Bill Wendlingdf170db2012-03-15 05:12:00 +00006749 if (N1.getOpcode() == ISD::FADD) {
6750 SDValue N10 = N1->getOperand(0);
6751 SDValue N11 = N1->getOperand(1);
6752
6753 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6754 &DAG.getTarget().Options))
6755 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006756
Stephen Lin8e8424e2013-07-09 00:44:49 +00006757 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6758 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006759 return GetNegatedExpression(N10, DAG, LegalOperations);
6760 }
6761 }
6762
Lang Hames39fb1d02012-06-19 22:51:23 +00006763 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006764 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006765 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006766 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6767 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006768
6769 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006770 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006771 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006772 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006773 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006774
6775 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6776 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006777 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006778 return DAG.getNode(ISD::FMA, dl, VT,
6779 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006780 N1.getOperand(0)),
6781 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006782
Stephen Lin8e8424e2013-07-09 00:44:49 +00006783 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006784 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006785 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6786 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6787 SDValue N00 = N0.getOperand(0).getOperand(0);
6788 SDValue N01 = N0.getOperand(0).getOperand(1);
6789 return DAG.getNode(ISD::FMA, dl, VT,
6790 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6791 DAG.getNode(ISD::FNEG, dl, VT, N1));
6792 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006793 }
6794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006795 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006796}
6797
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006798SDValue DAGCombiner::visitFMUL(SDNode *N) {
6799 SDValue N0 = N->getOperand(0);
6800 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006801 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6802 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006803 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006805
Dan Gohmana8665142007-06-25 16:23:39 +00006806 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006807 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006808 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006809 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006810 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006811
Nate Begemanec48a1b2005-10-17 20:40:11 +00006812 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006813 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006814 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006815 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006816 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006817 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006818 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006819 if (DAG.getTarget().Options.UnsafeFPMath &&
6820 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006821 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006822 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006823 if (DAG.getTarget().Options.UnsafeFPMath &&
6824 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006825 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006826 // fold (fmul A, 1.0) -> A
6827 if (N1CFP && N1CFP->isExactlyValue(1.0))
6828 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006829 // fold (fmul X, 2.0) -> (fadd X, X)
6830 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006831 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006832 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006833 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006834 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006835 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006836
Bill Wendling3dc5d242009-01-30 22:57:07 +00006837 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006838 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006839 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006840 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006841 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006842 // Both can be negated for free, check to see if at least one is cheaper
6843 // negated.
6844 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006845 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006846 GetNegatedExpression(N0, DAG, LegalOperations),
6847 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006848 }
6849 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006850
Chris Lattner0199fd62007-01-08 23:04:05 +00006851 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006852 if (DAG.getTarget().Options.UnsafeFPMath &&
6853 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006854 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6856 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006857 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006858
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006859 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006860}
6861
Owen Anderson41b06652012-05-02 22:17:40 +00006862SDValue DAGCombiner::visitFMA(SDNode *N) {
6863 SDValue N0 = N->getOperand(0);
6864 SDValue N1 = N->getOperand(1);
6865 SDValue N2 = N->getOperand(2);
6866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6867 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6868 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006869 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006870
Owen Andersonb351c8d2012-11-01 02:00:53 +00006871 if (DAG.getTarget().Options.UnsafeFPMath) {
6872 if (N0CFP && N0CFP->isZero())
6873 return N2;
6874 if (N1CFP && N1CFP->isZero())
6875 return N2;
6876 }
Owen Anderson41b06652012-05-02 22:17:40 +00006877 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006878 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006879 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006880 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006881
Owen Andersonc7aaf522012-05-30 18:50:39 +00006882 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006883 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006884 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006885
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006886 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6887 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6888 N2.getOpcode() == ISD::FMUL &&
6889 N0 == N2.getOperand(0) &&
6890 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6891 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6892 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6893 }
6894
6895
6896 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6897 if (DAG.getTarget().Options.UnsafeFPMath &&
6898 N0.getOpcode() == ISD::FMUL && N1CFP &&
6899 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6900 return DAG.getNode(ISD::FMA, dl, VT,
6901 N0.getOperand(0),
6902 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6903 N2);
6904 }
6905
6906 // (fma x, 1, y) -> (fadd x, y)
6907 // (fma x, -1, y) -> (fadd (fneg x), y)
6908 if (N1CFP) {
6909 if (N1CFP->isExactlyValue(1.0))
6910 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6911
6912 if (N1CFP->isExactlyValue(-1.0) &&
6913 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6914 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006915 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006916 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6917 }
6918 }
6919
6920 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006921 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6922 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006923 DAG.getNode(ISD::FADD, dl, VT,
6924 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006925
6926 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6927 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006928 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6929 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006930 DAG.getNode(ISD::FADD, dl, VT,
6931 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006932
6933
Owen Anderson41b06652012-05-02 22:17:40 +00006934 return SDValue();
6935}
6936
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006937SDValue DAGCombiner::visitFDIV(SDNode *N) {
6938 SDValue N0 = N->getOperand(0);
6939 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006940 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6941 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006942 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006943 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006944
Dan Gohmana8665142007-06-25 16:23:39 +00006945 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006946 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006947 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006948 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006949 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006950
Nate Begeman569c4392006-01-18 22:35:16 +00006951 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006952 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006953 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006954
Duncan Sands2f1dc382012-04-08 18:08:12 +00006955 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006956 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006957 // Compute the reciprocal 1.0 / c2.
6958 APFloat N1APF = N1CFP->getValueAPF();
6959 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6960 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006961 // Only do the transform if the reciprocal is a legal fp immediate that
6962 // isn't too nasty (eg NaN, denormal, ...).
6963 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006964 (!LegalOperations ||
6965 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6966 // backend)... we should handle this gracefully after Legalize.
6967 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6968 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6969 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006970 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006971 DAG.getConstantFP(Recip, VT));
6972 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006973
Bill Wendling3dc5d242009-01-30 22:57:07 +00006974 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006975 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006976 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006977 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006978 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006979 // Both can be negated for free, check to see if at least one is cheaper
6980 // negated.
6981 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006982 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006983 GetNegatedExpression(N0, DAG, LegalOperations),
6984 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006985 }
6986 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006987
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006988 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006989}
6990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006991SDValue DAGCombiner::visitFREM(SDNode *N) {
6992 SDValue N0 = N->getOperand(0);
6993 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006994 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6995 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006996 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006997
Nate Begeman569c4392006-01-18 22:35:16 +00006998 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006999 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007000 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007001
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007002 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007003}
7004
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007005SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7006 SDValue N0 = N->getOperand(0);
7007 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7009 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007010 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007011
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007012 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007013 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007014
Chris Lattner3bc40502006-03-05 05:30:57 +00007015 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007016 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007017 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7018 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007019 if (!V.isNegative()) {
7020 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007021 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007022 } else {
7023 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007024 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7025 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007026 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007027 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007028
Chris Lattner3bc40502006-03-05 05:30:57 +00007029 // copysign(fabs(x), y) -> copysign(x, y)
7030 // copysign(fneg(x), y) -> copysign(x, y)
7031 // copysign(copysign(x,z), y) -> copysign(x, y)
7032 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7033 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007034 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007035 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007036
7037 // copysign(x, abs(y)) -> abs(x)
7038 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007039 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007040
Chris Lattner3bc40502006-03-05 05:30:57 +00007041 // copysign(x, copysign(y,z)) -> copysign(x, z)
7042 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007043 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007044 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007045
Chris Lattner3bc40502006-03-05 05:30:57 +00007046 // copysign(x, fp_extend(y)) -> copysign(x, y)
7047 // copysign(x, fp_round(y)) -> copysign(x, y)
7048 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007049 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007050 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007051
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007052 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007053}
7054
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007055SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7056 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007057 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007058 EVT VT = N->getValueType(0);
7059 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007060
Nate Begeman21158fc2005-09-01 00:19:25 +00007061 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007062 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007063 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007064 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007065 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007066 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007067
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007068 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7069 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007070 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7071 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007072 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007073 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007074 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007075 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007076
Alp Tokercb402912014-01-24 17:20:08 +00007077 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007078 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007079 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7080 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7081 !VT.isVector() &&
7082 (!LegalOperations ||
7083 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7084 SDValue Ops[] =
7085 { N0.getOperand(0), N0.getOperand(1),
7086 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7087 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007088 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007089 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007090
Nadav Rotem90560762012-07-23 07:59:50 +00007091 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7092 // (select_cc x, y, 1.0, 0.0,, cc)
7093 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7094 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7095 (!LegalOperations ||
7096 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7097 SDValue Ops[] =
7098 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7099 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7100 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007101 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007102 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007103 }
7104
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007105 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007106}
7107
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007108SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7109 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007110 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007111 EVT VT = N->getValueType(0);
7112 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007113
Nate Begeman21158fc2005-09-01 00:19:25 +00007114 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007115 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007116 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007117 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007118 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007119 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007120
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007121 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7122 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007123 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7124 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007125 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007126 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007127 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007128 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007129
Alp Tokercb402912014-01-24 17:20:08 +00007130 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007131 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007132 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007133
Nadav Rotem90560762012-07-23 07:59:50 +00007134 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7135 (!LegalOperations ||
7136 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7137 SDValue Ops[] =
7138 { N0.getOperand(0), N0.getOperand(1),
7139 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7140 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007141 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007142 }
7143 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007144
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007145 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007146}
7147
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007148SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7149 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007150 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007151 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007152
Nate Begeman21158fc2005-09-01 00:19:25 +00007153 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007154 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007155 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007157 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007158}
7159
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007160SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007162 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007163 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007164
Nate Begeman21158fc2005-09-01 00:19:25 +00007165 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007166 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007167 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007169 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007170}
7171
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007172SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7173 SDValue N0 = N->getOperand(0);
7174 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007175 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007176 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007177
Nate Begeman21158fc2005-09-01 00:19:25 +00007178 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007179 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007180 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007181
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007182 // fold (fp_round (fp_extend x)) -> x
7183 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7184 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007185
Chris Lattner0feb1b02008-01-24 06:45:35 +00007186 // fold (fp_round (fp_round x)) -> (fp_round x)
7187 if (N0.getOpcode() == ISD::FP_ROUND) {
7188 // This is a value preserving truncation if both round's are.
7189 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007190 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007191 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007192 DAG.getIntPtrConstant(IsTrunc));
7193 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007194
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007195 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007196 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007197 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007198 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007199 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007200 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007201 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007202 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007204 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007205}
7206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007207SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7208 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007209 EVT VT = N->getValueType(0);
7210 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007211 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007212
Nate Begeman21158fc2005-09-01 00:19:25 +00007213 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007214 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007215 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007216 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007217 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007218
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007219 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007220}
7221
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007222SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7223 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007224 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007225 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007226
Chris Lattner5919b482007-12-29 06:55:23 +00007227 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007228 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007229 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007230 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007231
Nate Begeman21158fc2005-09-01 00:19:25 +00007232 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007233 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007234 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007235
7236 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7237 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007238 if (N0.getOpcode() == ISD::FP_ROUND
7239 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007240 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007241 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007242 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007243 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007244 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007245 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007246 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007247
Chris Lattner72733e52008-01-17 07:00:52 +00007248 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007249 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007250 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007251 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007252 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007253 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007254 LN0->getBasePtr(), N0.getValueType(),
7255 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007256 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007257 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007258 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007259 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007260 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007261 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007262 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007263
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007264 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007265}
7266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007267SDValue DAGCombiner::visitFNEG(SDNode *N) {
7268 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007269 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007270
Craig Topper82384612012-09-11 01:45:21 +00007271 if (VT.isVector()) {
7272 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7273 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007274 }
7275
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007276 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7277 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007278 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007279
Chris Lattner888560d2008-01-27 17:42:27 +00007280 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7281 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007282 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007283 !VT.isVector() &&
7284 N0.getNode()->hasOneUse() &&
7285 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007286 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007287 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007288 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007290 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007291 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007292 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007293 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007294 }
7295 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007296
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007297 // (fneg (fmul c, x)) -> (fmul -c, x)
7298 if (N0.getOpcode() == ISD::FMUL) {
7299 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007300 if (CFP1) {
7301 APFloat CVal = CFP1->getValueAPF();
7302 CVal.changeSign();
7303 if (Level >= AfterLegalizeDAG &&
7304 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7305 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7306 return DAG.getNode(
7307 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7308 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7309 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007310 }
7311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007312 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007313}
7314
Owen Andersona40319b2012-08-13 23:32:49 +00007315SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7316 SDValue N0 = N->getOperand(0);
7317 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7318 EVT VT = N->getValueType(0);
7319
7320 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007321 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007322 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007323
7324 return SDValue();
7325}
7326
7327SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7328 SDValue N0 = N->getOperand(0);
7329 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7330 EVT VT = N->getValueType(0);
7331
7332 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007333 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007334 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007335
7336 return SDValue();
7337}
7338
7339SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7340 SDValue N0 = N->getOperand(0);
7341 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7342 EVT VT = N->getValueType(0);
7343
7344 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007345 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007346 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007347
7348 return SDValue();
7349}
7350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007351SDValue DAGCombiner::visitFABS(SDNode *N) {
7352 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007353 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007354 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007355
Craig Topper82384612012-09-11 01:45:21 +00007356 if (VT.isVector()) {
7357 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7358 if (FoldedVOp.getNode()) return FoldedVOp;
7359 }
7360
Nate Begeman21158fc2005-09-01 00:19:25 +00007361 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007362 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007363 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007364 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007365 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007366 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007367 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007368 // fold (fabs (fcopysign x, y)) -> (fabs x)
7369 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007370 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007371
Chris Lattner888560d2008-01-27 17:42:27 +00007372 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7373 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007374 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007375 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007376 N0.getOperand(0).getValueType().isInteger() &&
7377 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007378 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007379 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007380 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007381 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007382 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007383 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007384 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007385 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007386 }
7387 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007388
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007389 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007390}
7391
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007392SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7393 SDValue Chain = N->getOperand(0);
7394 SDValue N1 = N->getOperand(1);
7395 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007396
Dan Gohman82e80012009-11-17 00:47:23 +00007397 // If N is a constant we could fold this into a fallthrough or unconditional
7398 // branch. However that doesn't happen very often in normal code, because
7399 // Instcombine/SimplifyCFG should have handled the available opportunities.
7400 // If we did this folding here, it would be necessary to update the
7401 // MachineBasicBlock CFG, which is awkward.
7402
Nate Begeman7e7f4392006-02-01 07:19:44 +00007403 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7404 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007405 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007406 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7407 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007408 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007409 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007410 N1.getOperand(0), N1.getOperand(1), N2);
7411 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007412
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007413 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7414 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7415 (N1.getOperand(0).hasOneUse() &&
7416 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007417 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007418 if (N1.getOpcode() == ISD::TRUNCATE) {
7419 // Look pass the truncate.
7420 Trunc = N1.getNode();
7421 N1 = N1.getOperand(0);
7422 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007423
Bill Wendlingaa28be62009-03-26 06:14:09 +00007424 // Match this pattern so that we can generate simpler code:
7425 //
7426 // %a = ...
7427 // %b = and i32 %a, 2
7428 // %c = srl i32 %b, 1
7429 // brcond i32 %c ...
7430 //
7431 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007432 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007433 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007434 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007435 // %c = setcc eq %b, 0
7436 // brcond %c ...
7437 //
7438 // This applies only when the AND constant value has one bit set and the
7439 // SRL constant is equal to the log2 of the AND constant. The back-end is
7440 // smart enough to convert the result into a TEST/JMP sequence.
7441 SDValue Op0 = N1.getOperand(0);
7442 SDValue Op1 = N1.getOperand(1);
7443
7444 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007445 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007446 SDValue AndOp1 = Op0.getOperand(1);
7447
7448 if (AndOp1.getOpcode() == ISD::Constant) {
7449 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7450
7451 if (AndConst.isPowerOf2() &&
7452 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7453 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007454 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007455 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007456 Op0, DAG.getConstant(0, Op0.getValueType()),
7457 ISD::SETNE);
7458
Andrew Trickef9de2a2013-05-25 02:42:55 +00007459 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007460 MVT::Other, Chain, SetCC, N2);
7461 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7462 // will convert it back to (X & C1) >> C2.
7463 CombineTo(N, NewBRCond, false);
7464 // Truncate is dead.
7465 if (Trunc) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007466 removeFromWorklist(Trunc);
Evan Cheng166a4e62010-01-06 19:38:29 +00007467 DAG.DeleteNode(Trunc);
7468 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007469 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007470 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007471 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007472 removeFromWorklist(N1.getNode());
Bill Wendlingaa28be62009-03-26 06:14:09 +00007473 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007474 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007475 }
7476 }
7477 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007478
7479 if (Trunc)
7480 // Restore N1 if the above transformation doesn't match.
7481 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007482 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007483
Evan Cheng228c31f2010-02-27 07:36:59 +00007484 // Transform br(xor(x, y)) -> br(x != y)
7485 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7486 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7487 SDNode *TheXor = N1.getNode();
7488 SDValue Op0 = TheXor->getOperand(0);
7489 SDValue Op1 = TheXor->getOperand(1);
7490 if (Op0.getOpcode() == Op1.getOpcode()) {
7491 // Avoid missing important xor optimizations.
7492 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007493 if (Tmp.getNode()) {
7494 if (Tmp.getNode() != TheXor) {
7495 DEBUG(dbgs() << "\nReplacing.8 ";
7496 TheXor->dump(&DAG);
7497 dbgs() << "\nWith: ";
7498 Tmp.getNode()->dump(&DAG);
7499 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007500 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007501 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007502 removeFromWorklist(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007503 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007504 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007505 MVT::Other, Chain, Tmp, N2);
7506 }
7507
Benjamin Kramer93354432013-03-30 21:28:18 +00007508 // visitXOR has changed XOR's operands or replaced the XOR completely,
7509 // bail out.
7510 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007511 }
7512 }
7513
7514 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7515 bool Equal = false;
7516 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7517 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7518 Op0.getOpcode() == ISD::XOR) {
7519 TheXor = Op0.getNode();
7520 Equal = true;
7521 }
7522
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007523 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007524 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007525 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007526 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007527 SetCCVT,
7528 Op0, Op1,
7529 Equal ? ISD::SETEQ : ISD::SETNE);
7530 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007531 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007532 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007533 removeFromWorklist(N1.getNode());
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007534 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007535 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007536 MVT::Other, Chain, SetCC, N2);
7537 }
7538 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007539
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007540 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007541}
7542
Chris Lattnera49e16f2005-10-05 06:47:48 +00007543// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7544//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007545SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007546 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007547 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007548
Dan Gohman82e80012009-11-17 00:47:23 +00007549 // If N is a constant we could fold this into a fallthrough or unconditional
7550 // branch. However that doesn't happen very often in normal code, because
7551 // Instcombine/SimplifyCFG should have handled the available opportunities.
7552 // If we did this folding here, it would be necessary to update the
7553 // MachineBasicBlock CFG, which is awkward.
7554
Duncan Sands93b66092008-06-09 11:32:28 +00007555 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007556 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007557 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007558 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007559 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007560
Nate Begemanbd7df032005-10-05 21:43:42 +00007561 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007562 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007563 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007564 N->getOperand(0), Simp.getOperand(2),
7565 Simp.getOperand(0), Simp.getOperand(1),
7566 N->getOperand(4));
7567
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007568 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007569}
7570
Evan Chengfa832632012-01-13 01:37:24 +00007571/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7572/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007573/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007574static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7575 SelectionDAG &DAG,
7576 const TargetLowering &TLI) {
7577 EVT VT;
7578 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7579 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7580 return false;
7581 VT = Use->getValueType(0);
7582 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7583 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7584 return false;
7585 VT = ST->getValue().getValueType();
7586 } else
7587 return false;
7588
Chandler Carruth95f83e02013-01-07 15:14:13 +00007589 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007590 if (N->getOpcode() == ISD::ADD) {
7591 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7592 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007593 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007594 AM.BaseOffs = Offset->getSExtValue();
7595 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007596 // [reg +/- reg]
7597 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007598 } else if (N->getOpcode() == ISD::SUB) {
7599 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7600 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007601 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007602 AM.BaseOffs = -Offset->getSExtValue();
7603 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007604 // [reg +/- reg]
7605 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007606 } else
7607 return false;
7608
7609 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7610}
7611
Duncan Sands075293f2008-06-15 20:12:31 +00007612/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7613/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007614/// and it has other uses besides the load / store. After the
7615/// transformation, the new indexed load / store has effectively folded
7616/// the add / subtract in and all of its other uses are redirected to the
7617/// new load / store.
7618bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007619 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007620 return false;
7621
7622 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007623 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007624 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007625 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007626 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007627 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007628 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007629 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007630 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7631 return false;
7632 Ptr = LD->getBasePtr();
7633 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007634 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007635 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007636 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007637 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7638 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7639 return false;
7640 Ptr = ST->getBasePtr();
7641 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007642 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007643 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007644 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007645
Chris Lattnereabc15c2006-11-11 00:56:29 +00007646 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7647 // out. There is no reason to make this a preinc/predec.
7648 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007649 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007650 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007651
Chris Lattnereabc15c2006-11-11 00:56:29 +00007652 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007653 SDValue BasePtr;
7654 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007655 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7656 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7657 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007658
7659 // Backends without true r+i pre-indexed forms may need to pass a
7660 // constant base with a variable offset so that constant coercion
7661 // will work with the patterns in canonical form.
7662 bool Swapped = false;
7663 if (isa<ConstantSDNode>(BasePtr)) {
7664 std::swap(BasePtr, Offset);
7665 Swapped = true;
7666 }
7667
Evan Cheng044a0a82007-05-03 23:52:19 +00007668 // Don't create a indexed load / store with zero offset.
7669 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007670 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007671 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007672
Chris Lattnera0a80032006-11-11 01:00:15 +00007673 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007674 // 1) The new base ptr is a frame index.
7675 // 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 +00007676 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007677 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007678 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007679 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007680
Chris Lattnera0a80032006-11-11 01:00:15 +00007681 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7682 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007683 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007684 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007685
Chris Lattnera0a80032006-11-11 01:00:15 +00007686 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007687 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007688 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007689 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007690 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007691 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007692
Hal Finkel25819052013-02-08 21:35:47 +00007693 // If the offset is a constant, there may be other adds of constants that
7694 // can be folded with this one. We should do this to avoid having to keep
7695 // a copy of the original base pointer.
7696 SmallVector<SDNode *, 16> OtherUses;
7697 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007698 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007699 if (Use == Ptr.getNode())
7700 continue;
7701
7702 if (Use->isPredecessorOf(N))
7703 continue;
7704
7705 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7706 OtherUses.clear();
7707 break;
7708 }
7709
7710 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7711 if (Op1.getNode() == BasePtr.getNode())
7712 std::swap(Op0, Op1);
7713 assert(Op0.getNode() == BasePtr.getNode() &&
7714 "Use of ADD/SUB but not an operand");
7715
7716 if (!isa<ConstantSDNode>(Op1)) {
7717 OtherUses.clear();
7718 break;
7719 }
7720
7721 // FIXME: In some cases, we can be smarter about this.
7722 if (Op1.getValueType() != Offset.getValueType()) {
7723 OtherUses.clear();
7724 break;
7725 }
7726
7727 OtherUses.push_back(Use);
7728 }
7729
7730 if (Swapped)
7731 std::swap(BasePtr, Offset);
7732
Evan Chenga4d187b2007-05-24 02:35:39 +00007733 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007734 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007735
7736 // Caches for hasPredecessorHelper
7737 SmallPtrSet<const SDNode *, 32> Visited;
7738 SmallVector<const SDNode *, 16> Worklist;
7739
Jim Grosbache8160032014-04-11 01:13:13 +00007740 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007741 if (Use == N)
7742 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007743 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007744 return false;
7745
Evan Chengfa832632012-01-13 01:37:24 +00007746 // If Ptr may be folded in addressing mode of other use, then it's
7747 // not profitable to do this transformation.
7748 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007749 RealUse = true;
7750 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007751
Chris Lattnereabc15c2006-11-11 00:56:29 +00007752 if (!RealUse)
7753 return false;
7754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007755 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007756 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007757 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007758 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007759 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007760 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007761 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007762 ++PreIndexedNodes;
7763 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007764 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007765 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007766 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007767 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007768 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007769 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007770 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007771 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007773 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007774 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007775 }
7776
Chris Lattnereabc15c2006-11-11 00:56:29 +00007777 // Finally, since the node is now dead, remove it from the graph.
7778 DAG.DeleteNode(N);
7779
Hal Finkel25819052013-02-08 21:35:47 +00007780 if (Swapped)
7781 std::swap(BasePtr, Offset);
7782
7783 // Replace other uses of BasePtr that can be updated to use Ptr
7784 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7785 unsigned OffsetIdx = 1;
7786 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7787 OffsetIdx = 0;
7788 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7789 BasePtr.getNode() && "Expected BasePtr operand");
7790
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007791 // We need to replace ptr0 in the following expression:
7792 // x0 * offset0 + y0 * ptr0 = t0
7793 // knowing that
7794 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007795 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007796 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7797 // indexed load/store and the expresion that needs to be re-written.
7798 //
7799 // Therefore, we have:
7800 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007801
7802 ConstantSDNode *CN =
7803 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007804 int X0, X1, Y0, Y1;
7805 APInt Offset0 = CN->getAPIntValue();
7806 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007807
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007808 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7809 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7810 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7811 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007812
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007813 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7814
7815 APInt CNV = Offset0;
7816 if (X0 < 0) CNV = -CNV;
7817 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7818 else CNV = CNV - Offset1;
7819
7820 // We can now generate the new expression.
7821 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7822 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7823
7824 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007825 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007826 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7827 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007828 removeFromWorklist(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007829 DAG.DeleteNode(OtherUses[i]);
7830 }
7831
Chris Lattnereabc15c2006-11-11 00:56:29 +00007832 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007833 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007834 removeFromWorklist(Ptr.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00007835 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007836
7837 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007838}
7839
Duncan Sands075293f2008-06-15 20:12:31 +00007840/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007841/// add / sub of the base pointer node into a post-indexed load / store.
7842/// The transformation folded the add / subtract into the new indexed
7843/// load / store effectively and all of its uses are redirected to the
7844/// new load / store.
7845bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007846 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007847 return false;
7848
7849 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007850 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007851 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007852 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007853 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007854 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007855 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007856 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7857 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7858 return false;
7859 Ptr = LD->getBasePtr();
7860 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007861 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007862 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007863 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007864 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7865 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7866 return false;
7867 Ptr = ST->getBasePtr();
7868 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007869 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007870 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007871 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007872
Gabor Greiff304a7a2008-08-28 21:40:38 +00007873 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007874 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007875
Jim Grosbache8160032014-04-11 01:13:13 +00007876 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007877 if (Op == N ||
7878 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7879 continue;
7880
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007881 SDValue BasePtr;
7882 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007883 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7884 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007885 // Don't create a indexed load / store with zero offset.
7886 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007887 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007888 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007889
Chris Lattnereabc15c2006-11-11 00:56:29 +00007890 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007891 // 1) All uses are load / store ops that use it as base ptr (and
7892 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007893 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7894 // nor a successor of N. Otherwise, if Op is folded that would
7895 // create a cycle.
7896
Evan Chengcfc05132009-05-06 18:25:01 +00007897 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7898 continue;
7899
Chris Lattnereabc15c2006-11-11 00:56:29 +00007900 // Check for #1.
7901 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007902 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007903 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007904 continue;
7905
Chris Lattnereabc15c2006-11-11 00:56:29 +00007906 // If all the uses are load / store addresses, then don't do the
7907 // transformation.
7908 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7909 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007910 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007911 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007912 RealUse = true;
7913 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007914
Chris Lattnereabc15c2006-11-11 00:56:29 +00007915 if (!RealUse) {
7916 TryNext = true;
7917 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007918 }
7919 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007920 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007921
Chris Lattnereabc15c2006-11-11 00:56:29 +00007922 if (TryNext)
7923 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007924
Chris Lattnereabc15c2006-11-11 00:56:29 +00007925 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007926 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007927 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007928 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007929 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007930 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007931 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007932 ++PostIndexedNodes;
7933 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007934 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007935 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007936 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007937 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007938 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007939 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007940 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007941 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7942 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007943 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007944 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007945 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007946
Chris Lattnereabc15c2006-11-11 00:56:29 +00007947 // Finally, since the node is now dead, remove it from the graph.
7948 DAG.DeleteNode(N);
7949
7950 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007951 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007952 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007953 removeFromWorklist(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007954 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007955 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007956 }
7957 }
7958 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007959
Chris Lattnerffad2162006-11-11 00:39:41 +00007960 return false;
7961}
7962
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007963SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007964 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007965 SDValue Chain = LD->getChain();
7966 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007967
Evan Chenga684cd22007-05-01 00:38:21 +00007968 // If load is not volatile and there are no uses of the loaded value (and
7969 // the updated indexed value in case of indexed loads), change uses of the
7970 // chain value into uses of the chain input (i.e. delete the dead load).
7971 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007972 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007973 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007974 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007975 // It's not safe to use the two value CombineTo variant here. e.g.
7976 // v1, chain2 = load chain1, loc
7977 // v2, chain3 = load chain2, loc
7978 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007979 // Now we replace use of chain2 with chain1. This makes the second load
7980 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007981 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007982 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007983 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007984 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007985 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007986 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007987 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007988
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007989 if (N->use_empty()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007990 removeFromWorklist(N);
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007991 DAG.DeleteNode(N);
7992 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007993
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007994 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007995 }
Evan Chengb68343c2007-05-01 08:53:39 +00007996 } else {
7997 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007998 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007999 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00008000 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00008001 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008002 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008003 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008004 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008005 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008006 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008007 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00008008 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8009 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008010 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008011 removeFromWorklist(N);
Evan Cheng7be15282008-01-16 23:11:54 +00008012 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008013 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008014 }
Evan Chenga684cd22007-05-01 00:38:21 +00008015 }
8016 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008017
Chris Lattnere260ed82005-10-10 22:04:48 +00008018 // If this load is directly stored, replace the load value with the stored
8019 // value.
8020 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008021 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008022 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008023 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008024 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8025 if (PrevST->getBasePtr() == Ptr &&
8026 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008027 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008028 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008029 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008030
Evan Cheng43cd9e32010-04-01 06:04:33 +00008031 // Try to infer better alignment information than the load already has.
8032 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008033 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008034 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8035 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008036 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008037 LD->getValueType(0),
8038 Chain, Ptr, LD->getPointerInfo(),
8039 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008040 LD->isVolatile(), LD->isNonTemporal(), Align,
8041 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008042 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8043 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008044 }
8045 }
8046
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008047 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8048 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008049#ifndef NDEBUG
8050 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8051 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8052 UseAA = false;
8053#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008054 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008055 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008056 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008057
Jim Laskey708d0db2006-10-04 16:53:27 +00008058 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008059 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008060 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008061
Jim Laskeyd07be232006-09-25 16:29:54 +00008062 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008063 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008064 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008065 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008066 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008067 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008068 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008069 BetterChain, Ptr, LD->getMemoryVT(),
8070 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008071 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008072
Jim Laskey708d0db2006-10-04 16:53:27 +00008073 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008074 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008075 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008076
Nate Begeman879d8f12009-09-15 00:18:30 +00008077 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008078 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008079
Jim Laskeydcf983c2006-10-13 23:32:28 +00008080 // Replace uses with load result and token factor. Don't add users
8081 // to work list.
8082 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008083 }
8084 }
8085
Evan Cheng357017f2006-11-03 03:06:21 +00008086 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008087 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008088 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008089
Quentin Colombetde0e0622013-10-11 18:29:42 +00008090 // Try to slice up N to more direct loads if the slices are mapped to
8091 // different register banks or pairing can take place.
8092 if (SliceUpLoad(N))
8093 return SDValue(N, 0);
8094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008095 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008096}
8097
Quentin Colombetde0e0622013-10-11 18:29:42 +00008098namespace {
8099/// \brief Helper structure used to slice a load in smaller loads.
8100/// Basically a slice is obtained from the following sequence:
8101/// Origin = load Ty1, Base
8102/// Shift = srl Ty1 Origin, CstTy Amount
8103/// Inst = trunc Shift to Ty2
8104///
8105/// Then, it will be rewriten into:
8106/// Slice = load SliceTy, Base + SliceOffset
8107/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8108///
8109/// SliceTy is deduced from the number of bits that are actually used to
8110/// build Inst.
8111struct LoadedSlice {
8112 /// \brief Helper structure used to compute the cost of a slice.
8113 struct Cost {
8114 /// Are we optimizing for code size.
8115 bool ForCodeSize;
8116 /// Various cost.
8117 unsigned Loads;
8118 unsigned Truncates;
8119 unsigned CrossRegisterBanksCopies;
8120 unsigned ZExts;
8121 unsigned Shift;
8122
8123 Cost(bool ForCodeSize = false)
8124 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8125 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8126
8127 /// \brief Get the cost of one isolated slice.
8128 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8129 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8130 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8131 EVT TruncType = LS.Inst->getValueType(0);
8132 EVT LoadedType = LS.getLoadedType();
8133 if (TruncType != LoadedType &&
8134 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8135 ZExts = 1;
8136 }
8137
8138 /// \brief Account for slicing gain in the current cost.
8139 /// Slicing provide a few gains like removing a shift or a
8140 /// truncate. This method allows to grow the cost of the original
8141 /// load with the gain from this slice.
8142 void addSliceGain(const LoadedSlice &LS) {
8143 // Each slice saves a truncate.
8144 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8145 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8146 LS.Inst->getOperand(0).getValueType()))
8147 ++Truncates;
8148 // If there is a shift amount, this slice gets rid of it.
8149 if (LS.Shift)
8150 ++Shift;
8151 // If this slice can merge a cross register bank copy, account for it.
8152 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8153 ++CrossRegisterBanksCopies;
8154 }
8155
8156 Cost &operator+=(const Cost &RHS) {
8157 Loads += RHS.Loads;
8158 Truncates += RHS.Truncates;
8159 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8160 ZExts += RHS.ZExts;
8161 Shift += RHS.Shift;
8162 return *this;
8163 }
8164
8165 bool operator==(const Cost &RHS) const {
8166 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8167 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8168 ZExts == RHS.ZExts && Shift == RHS.Shift;
8169 }
8170
8171 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8172
8173 bool operator<(const Cost &RHS) const {
8174 // Assume cross register banks copies are as expensive as loads.
8175 // FIXME: Do we want some more target hooks?
8176 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8177 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8178 // Unless we are optimizing for code size, consider the
8179 // expensive operation first.
8180 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8181 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8182 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8183 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8184 }
8185
8186 bool operator>(const Cost &RHS) const { return RHS < *this; }
8187
8188 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8189
8190 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8191 };
8192 // The last instruction that represent the slice. This should be a
8193 // truncate instruction.
8194 SDNode *Inst;
8195 // The original load instruction.
8196 LoadSDNode *Origin;
8197 // The right shift amount in bits from the original load.
8198 unsigned Shift;
8199 // The DAG from which Origin came from.
8200 // This is used to get some contextual information about legal types, etc.
8201 SelectionDAG *DAG;
8202
Craig Topperc0196b12014-04-14 00:51:57 +00008203 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8204 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008205 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8206
8207 LoadedSlice(const LoadedSlice &LS)
8208 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8209
8210 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8211 /// \return Result is \p BitWidth and has used bits set to 1 and
8212 /// not used bits set to 0.
8213 APInt getUsedBits() const {
8214 // Reproduce the trunc(lshr) sequence:
8215 // - Start from the truncated value.
8216 // - Zero extend to the desired bit width.
8217 // - Shift left.
8218 assert(Origin && "No original load to compare against.");
8219 unsigned BitWidth = Origin->getValueSizeInBits(0);
8220 assert(Inst && "This slice is not bound to an instruction");
8221 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8222 "Extracted slice is bigger than the whole type!");
8223 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8224 UsedBits.setAllBits();
8225 UsedBits = UsedBits.zext(BitWidth);
8226 UsedBits <<= Shift;
8227 return UsedBits;
8228 }
8229
8230 /// \brief Get the size of the slice to be loaded in bytes.
8231 unsigned getLoadedSize() const {
8232 unsigned SliceSize = getUsedBits().countPopulation();
8233 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8234 return SliceSize / 8;
8235 }
8236
8237 /// \brief Get the type that will be loaded for this slice.
8238 /// Note: This may not be the final type for the slice.
8239 EVT getLoadedType() const {
8240 assert(DAG && "Missing context");
8241 LLVMContext &Ctxt = *DAG->getContext();
8242 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8243 }
8244
8245 /// \brief Get the alignment of the load used for this slice.
8246 unsigned getAlignment() const {
8247 unsigned Alignment = Origin->getAlignment();
8248 unsigned Offset = getOffsetFromBase();
8249 if (Offset != 0)
8250 Alignment = MinAlign(Alignment, Alignment + Offset);
8251 return Alignment;
8252 }
8253
8254 /// \brief Check if this slice can be rewritten with legal operations.
8255 bool isLegal() const {
8256 // An invalid slice is not legal.
8257 if (!Origin || !Inst || !DAG)
8258 return false;
8259
8260 // Offsets are for indexed load only, we do not handle that.
8261 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8262 return false;
8263
8264 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8265
8266 // Check that the type is legal.
8267 EVT SliceType = getLoadedType();
8268 if (!TLI.isTypeLegal(SliceType))
8269 return false;
8270
8271 // Check that the load is legal for this type.
8272 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8273 return false;
8274
8275 // Check that the offset can be computed.
8276 // 1. Check its type.
8277 EVT PtrType = Origin->getBasePtr().getValueType();
8278 if (PtrType == MVT::Untyped || PtrType.isExtended())
8279 return false;
8280
8281 // 2. Check that it fits in the immediate.
8282 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8283 return false;
8284
8285 // 3. Check that the computation is legal.
8286 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8287 return false;
8288
8289 // Check that the zext is legal if it needs one.
8290 EVT TruncateType = Inst->getValueType(0);
8291 if (TruncateType != SliceType &&
8292 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8293 return false;
8294
8295 return true;
8296 }
8297
8298 /// \brief Get the offset in bytes of this slice in the original chunk of
8299 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008300 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008301 uint64_t getOffsetFromBase() const {
8302 assert(DAG && "Missing context.");
8303 bool IsBigEndian =
8304 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8305 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8306 uint64_t Offset = Shift / 8;
8307 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8308 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8309 "The size of the original loaded type is not a multiple of a"
8310 " byte.");
8311 // If Offset is bigger than TySizeInBytes, it means we are loading all
8312 // zeros. This should have been optimized before in the process.
8313 assert(TySizeInBytes > Offset &&
8314 "Invalid shift amount for given loaded size");
8315 if (IsBigEndian)
8316 Offset = TySizeInBytes - Offset - getLoadedSize();
8317 return Offset;
8318 }
8319
8320 /// \brief Generate the sequence of instructions to load the slice
8321 /// represented by this object and redirect the uses of this slice to
8322 /// this new sequence of instructions.
8323 /// \pre this->Inst && this->Origin are valid Instructions and this
8324 /// object passed the legal check: LoadedSlice::isLegal returned true.
8325 /// \return The last instruction of the sequence used to load the slice.
8326 SDValue loadSlice() const {
8327 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8328 const SDValue &OldBaseAddr = Origin->getBasePtr();
8329 SDValue BaseAddr = OldBaseAddr;
8330 // Get the offset in that chunk of bytes w.r.t. the endianess.
8331 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8332 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8333 if (Offset) {
8334 // BaseAddr = BaseAddr + Offset.
8335 EVT ArithType = BaseAddr.getValueType();
8336 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8337 DAG->getConstant(Offset, ArithType));
8338 }
8339
8340 // Create the type of the loaded slice according to its size.
8341 EVT SliceType = getLoadedType();
8342
8343 // Create the load for the slice.
8344 SDValue LastInst = DAG->getLoad(
8345 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8346 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8347 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8348 // If the final type is not the same as the loaded type, this means that
8349 // we have to pad with zero. Create a zero extend for that.
8350 EVT FinalType = Inst->getValueType(0);
8351 if (SliceType != FinalType)
8352 LastInst =
8353 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8354 return LastInst;
8355 }
8356
8357 /// \brief Check if this slice can be merged with an expensive cross register
8358 /// bank copy. E.g.,
8359 /// i = load i32
8360 /// f = bitcast i32 i to float
8361 bool canMergeExpensiveCrossRegisterBankCopy() const {
8362 if (!Inst || !Inst->hasOneUse())
8363 return false;
8364 SDNode *Use = *Inst->use_begin();
8365 if (Use->getOpcode() != ISD::BITCAST)
8366 return false;
8367 assert(DAG && "Missing context");
8368 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8369 EVT ResVT = Use->getValueType(0);
8370 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8371 const TargetRegisterClass *ArgRC =
8372 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8373 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8374 return false;
8375
8376 // At this point, we know that we perform a cross-register-bank copy.
8377 // Check if it is expensive.
8378 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8379 // Assume bitcasts are cheap, unless both register classes do not
8380 // explicitly share a common sub class.
8381 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8382 return false;
8383
8384 // Check if it will be merged with the load.
8385 // 1. Check the alignment constraint.
8386 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8387 ResVT.getTypeForEVT(*DAG->getContext()));
8388
8389 if (RequiredAlignment > getAlignment())
8390 return false;
8391
8392 // 2. Check that the load is a legal operation for that type.
8393 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8394 return false;
8395
8396 // 3. Check that we do not have a zext in the way.
8397 if (Inst->getValueType(0) != getLoadedType())
8398 return false;
8399
8400 return true;
8401 }
8402};
8403}
8404
Quentin Colombetde0e0622013-10-11 18:29:42 +00008405/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8406/// \p UsedBits looks like 0..0 1..1 0..0.
8407static bool areUsedBitsDense(const APInt &UsedBits) {
8408 // If all the bits are one, this is dense!
8409 if (UsedBits.isAllOnesValue())
8410 return true;
8411
8412 // Get rid of the unused bits on the right.
8413 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8414 // Get rid of the unused bits on the left.
8415 if (NarrowedUsedBits.countLeadingZeros())
8416 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8417 // Check that the chunk of bits is completely used.
8418 return NarrowedUsedBits.isAllOnesValue();
8419}
8420
8421/// \brief Check whether or not \p First and \p Second are next to each other
8422/// in memory. This means that there is no hole between the bits loaded
8423/// by \p First and the bits loaded by \p Second.
8424static bool areSlicesNextToEachOther(const LoadedSlice &First,
8425 const LoadedSlice &Second) {
8426 assert(First.Origin == Second.Origin && First.Origin &&
8427 "Unable to match different memory origins.");
8428 APInt UsedBits = First.getUsedBits();
8429 assert((UsedBits & Second.getUsedBits()) == 0 &&
8430 "Slices are not supposed to overlap.");
8431 UsedBits |= Second.getUsedBits();
8432 return areUsedBitsDense(UsedBits);
8433}
8434
8435/// \brief Adjust the \p GlobalLSCost according to the target
8436/// paring capabilities and the layout of the slices.
8437/// \pre \p GlobalLSCost should account for at least as many loads as
8438/// there is in the slices in \p LoadedSlices.
8439static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8440 LoadedSlice::Cost &GlobalLSCost) {
8441 unsigned NumberOfSlices = LoadedSlices.size();
8442 // If there is less than 2 elements, no pairing is possible.
8443 if (NumberOfSlices < 2)
8444 return;
8445
8446 // Sort the slices so that elements that are likely to be next to each
8447 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008448 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8449 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8450 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8451 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8452 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008453 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8454 // First (resp. Second) is the first (resp. Second) potentially candidate
8455 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008456 const LoadedSlice *First = nullptr;
8457 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008458 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8459 // Set the beginning of the pair.
8460 First = Second) {
8461
8462 Second = &LoadedSlices[CurrSlice];
8463
8464 // If First is NULL, it means we start a new pair.
8465 // Get to the next slice.
8466 if (!First)
8467 continue;
8468
8469 EVT LoadedType = First->getLoadedType();
8470
8471 // If the types of the slices are different, we cannot pair them.
8472 if (LoadedType != Second->getLoadedType())
8473 continue;
8474
8475 // Check if the target supplies paired loads for this type.
8476 unsigned RequiredAlignment = 0;
8477 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8478 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008479 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008480 continue;
8481 }
8482 // Check if we meet the alignment requirement.
8483 if (RequiredAlignment > First->getAlignment())
8484 continue;
8485
8486 // Check that both loads are next to each other in memory.
8487 if (!areSlicesNextToEachOther(*First, *Second))
8488 continue;
8489
8490 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8491 --GlobalLSCost.Loads;
8492 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008493 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008494 }
8495}
8496
8497/// \brief Check the profitability of all involved LoadedSlice.
8498/// Currently, it is considered profitable if there is exactly two
8499/// involved slices (1) which are (2) next to each other in memory, and
8500/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8501///
8502/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8503/// the elements themselves.
8504///
8505/// FIXME: When the cost model will be mature enough, we can relax
8506/// constraints (1) and (2).
8507static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8508 const APInt &UsedBits, bool ForCodeSize) {
8509 unsigned NumberOfSlices = LoadedSlices.size();
8510 if (StressLoadSlicing)
8511 return NumberOfSlices > 1;
8512
8513 // Check (1).
8514 if (NumberOfSlices != 2)
8515 return false;
8516
8517 // Check (2).
8518 if (!areUsedBitsDense(UsedBits))
8519 return false;
8520
8521 // Check (3).
8522 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8523 // The original code has one big load.
8524 OrigCost.Loads = 1;
8525 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8526 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8527 // Accumulate the cost of all the slices.
8528 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8529 GlobalSlicingCost += SliceCost;
8530
8531 // Account as cost in the original configuration the gain obtained
8532 // with the current slices.
8533 OrigCost.addSliceGain(LS);
8534 }
8535
8536 // If the target supports paired load, adjust the cost accordingly.
8537 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8538 return OrigCost > GlobalSlicingCost;
8539}
8540
8541/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8542/// operations, split it in the various pieces being extracted.
8543///
8544/// This sort of thing is introduced by SROA.
8545/// This slicing takes care not to insert overlapping loads.
8546/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8547bool DAGCombiner::SliceUpLoad(SDNode *N) {
8548 if (Level < AfterLegalizeDAG)
8549 return false;
8550
8551 LoadSDNode *LD = cast<LoadSDNode>(N);
8552 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8553 !LD->getValueType(0).isInteger())
8554 return false;
8555
8556 // Keep track of already used bits to detect overlapping values.
8557 // In that case, we will just abort the transformation.
8558 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8559
8560 SmallVector<LoadedSlice, 4> LoadedSlices;
8561
8562 // Check if this load is used as several smaller chunks of bits.
8563 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8564 // of computation for each trunc.
8565 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8566 UI != UIEnd; ++UI) {
8567 // Skip the uses of the chain.
8568 if (UI.getUse().getResNo() != 0)
8569 continue;
8570
8571 SDNode *User = *UI;
8572 unsigned Shift = 0;
8573
8574 // Check if this is a trunc(lshr).
8575 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8576 isa<ConstantSDNode>(User->getOperand(1))) {
8577 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8578 User = *User->use_begin();
8579 }
8580
8581 // At this point, User is a Truncate, iff we encountered, trunc or
8582 // trunc(lshr).
8583 if (User->getOpcode() != ISD::TRUNCATE)
8584 return false;
8585
8586 // The width of the type must be a power of 2 and greater than 8-bits.
8587 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008588 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008589 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008590 unsigned Width = User->getValueSizeInBits(0);
8591 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8592 return 0;
8593
8594 // Build the slice for this chain of computations.
8595 LoadedSlice LS(User, LD, Shift, &DAG);
8596 APInt CurrentUsedBits = LS.getUsedBits();
8597
8598 // Check if this slice overlaps with another.
8599 if ((CurrentUsedBits & UsedBits) != 0)
8600 return false;
8601 // Update the bits used globally.
8602 UsedBits |= CurrentUsedBits;
8603
8604 // Check if the new slice would be legal.
8605 if (!LS.isLegal())
8606 return false;
8607
8608 // Record the slice.
8609 LoadedSlices.push_back(LS);
8610 }
8611
8612 // Abort slicing if it does not seem to be profitable.
8613 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8614 return false;
8615
8616 ++SlicedLoads;
8617
8618 // Rewrite each chain to use an independent load.
8619 // By construction, each chain can be represented by a unique load.
8620
8621 // Prepare the argument for the new token factor for all the slices.
8622 SmallVector<SDValue, 8> ArgChains;
8623 for (SmallVectorImpl<LoadedSlice>::const_iterator
8624 LSIt = LoadedSlices.begin(),
8625 LSItEnd = LoadedSlices.end();
8626 LSIt != LSItEnd; ++LSIt) {
8627 SDValue SliceInst = LSIt->loadSlice();
8628 CombineTo(LSIt->Inst, SliceInst, true);
8629 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8630 SliceInst = SliceInst.getOperand(0);
8631 assert(SliceInst->getOpcode() == ISD::LOAD &&
8632 "It takes more than a zext to get to the loaded slice!!");
8633 ArgChains.push_back(SliceInst.getValue(1));
8634 }
8635
8636 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008637 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008638 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8639 return true;
8640}
8641
Chris Lattner4041ab62010-04-15 04:48:01 +00008642/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8643/// load is having specific bytes cleared out. If so, return the byte size
8644/// being masked out and the shift amount.
8645static std::pair<unsigned, unsigned>
8646CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8647 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008648
Chris Lattner4041ab62010-04-15 04:48:01 +00008649 // Check for the structure we're looking for.
8650 if (V->getOpcode() != ISD::AND ||
8651 !isa<ConstantSDNode>(V->getOperand(1)) ||
8652 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8653 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008654
Chris Lattner3245afd2010-04-15 06:10:49 +00008655 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008656 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008657 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008658
Chris Lattner3245afd2010-04-15 06:10:49 +00008659 // The store should be chained directly to the load or be an operand of a
8660 // tokenfactor.
8661 if (LD == Chain.getNode())
8662 ; // ok.
8663 else if (Chain->getOpcode() != ISD::TokenFactor)
8664 return Result; // Fail.
8665 else {
8666 bool isOk = false;
8667 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8668 if (Chain->getOperand(i).getNode() == LD) {
8669 isOk = true;
8670 break;
8671 }
8672 if (!isOk) return Result;
8673 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008674
Chris Lattner4041ab62010-04-15 04:48:01 +00008675 // This only handles simple types.
8676 if (V.getValueType() != MVT::i16 &&
8677 V.getValueType() != MVT::i32 &&
8678 V.getValueType() != MVT::i64)
8679 return Result;
8680
8681 // Check the constant mask. Invert it so that the bits being masked out are
8682 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8683 // follow the sign bit for uniformity.
8684 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008685 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008686 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008687 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008688 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8689 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008690
Chris Lattner4041ab62010-04-15 04:48:01 +00008691 // See if we have a continuous run of bits. If so, we have 0*1+0*
8692 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8693 return Result;
8694
8695 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8696 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8697 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008698
Chris Lattner4041ab62010-04-15 04:48:01 +00008699 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8700 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008701 case 1:
8702 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008703 case 4: break;
8704 default: return Result; // All one mask, or 5-byte mask.
8705 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008706
Chris Lattner4041ab62010-04-15 04:48:01 +00008707 // Verify that the first bit starts at a multiple of mask so that the access
8708 // is aligned the same as the access width.
8709 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008710
Chris Lattner4041ab62010-04-15 04:48:01 +00008711 Result.first = MaskedBytes;
8712 Result.second = NotMaskTZ/8;
8713 return Result;
8714}
8715
8716
8717/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8718/// provides a value as specified by MaskInfo. If so, replace the specified
8719/// store with a narrower store of truncated IVal.
8720static SDNode *
8721ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8722 SDValue IVal, StoreSDNode *St,
8723 DAGCombiner *DC) {
8724 unsigned NumBytes = MaskInfo.first;
8725 unsigned ByteShift = MaskInfo.second;
8726 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008727
Chris Lattner4041ab62010-04-15 04:48:01 +00008728 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8729 // that uses this. If not, this is not a replacement.
8730 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8731 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008732 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008733
Chris Lattner4041ab62010-04-15 04:48:01 +00008734 // Check that it is legal on the target to do this. It is legal if the new
8735 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8736 // legalization.
8737 MVT VT = MVT::getIntegerVT(NumBytes*8);
8738 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008739 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008740
Chris Lattner4041ab62010-04-15 04:48:01 +00008741 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8742 // shifted by ByteShift and truncated down to NumBytes.
8743 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008744 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008745 DAG.getConstant(ByteShift*8,
8746 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008747
8748 // Figure out the offset for the store and the alignment of the access.
8749 unsigned StOffset;
8750 unsigned NewAlign = St->getAlignment();
8751
8752 if (DAG.getTargetLoweringInfo().isLittleEndian())
8753 StOffset = ByteShift;
8754 else
8755 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008756
Chris Lattner4041ab62010-04-15 04:48:01 +00008757 SDValue Ptr = St->getBasePtr();
8758 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008759 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008760 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8761 NewAlign = MinAlign(NewAlign, StOffset);
8762 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008763
Chris Lattner4041ab62010-04-15 04:48:01 +00008764 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008765 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008766
Chris Lattner4041ab62010-04-15 04:48:01 +00008767 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008768 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008769 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008770 false, false, NewAlign).getNode();
8771}
8772
Evan Chenga9cda8a2009-05-28 00:35:15 +00008773
8774/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8775/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8776/// of the loaded bits, try narrowing the load and store if it would end up
8777/// being a win for performance or code size.
8778SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8779 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008780 if (ST->isVolatile())
8781 return SDValue();
8782
Evan Chenga9cda8a2009-05-28 00:35:15 +00008783 SDValue Chain = ST->getChain();
8784 SDValue Value = ST->getValue();
8785 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008786 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008787
8788 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008789 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008790
8791 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008792
Chris Lattner4041ab62010-04-15 04:48:01 +00008793 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8794 // is a byte mask indicating a consecutive number of bytes, check to see if
8795 // Y is known to provide just those bytes. If so, we try to replace the
8796 // load + replace + store sequence with a single (narrower) store, which makes
8797 // the load dead.
8798 if (Opc == ISD::OR) {
8799 std::pair<unsigned, unsigned> MaskedLoad;
8800 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8801 if (MaskedLoad.first)
8802 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8803 Value.getOperand(1), ST,this))
8804 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008805
Chris Lattner4041ab62010-04-15 04:48:01 +00008806 // Or is commutative, so try swapping X and Y.
8807 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8808 if (MaskedLoad.first)
8809 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8810 Value.getOperand(0), ST,this))
8811 return SDValue(NewST, 0);
8812 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008813
Evan Chenga9cda8a2009-05-28 00:35:15 +00008814 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8815 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008816 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008817
8818 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008819 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8820 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008821 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008822 if (LD->getBasePtr() != Ptr ||
8823 LD->getPointerInfo().getAddrSpace() !=
8824 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008825 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008826
8827 // Find the type to narrow it the load / op / store to.
8828 SDValue N1 = Value.getOperand(1);
8829 unsigned BitWidth = N1.getValueSizeInBits();
8830 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8831 if (Opc == ISD::AND)
8832 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008833 if (Imm == 0 || Imm.isAllOnesValue())
8834 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008835 unsigned ShAmt = Imm.countTrailingZeros();
8836 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8837 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008838 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008839 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008840 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008841 TLI.isNarrowingProfitable(VT, NewVT))) {
8842 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008843 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008844 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008845 if (NewBW >= BitWidth)
8846 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008847
8848 // If the lsb changed does not start at the type bitwidth boundary,
8849 // start at the previous one.
8850 if (ShAmt % NewBW)
8851 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008852 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8853 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008854 if ((Imm & Mask) == Imm) {
8855 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8856 if (Opc == ISD::AND)
8857 NewImm ^= APInt::getAllOnesValue(NewBW);
8858 uint64_t PtrOff = ShAmt / 8;
8859 // For big endian targets, we need to adjust the offset to the pointer to
8860 // load the correct bytes.
8861 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008862 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008863
8864 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008865 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008866 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008867 return SDValue();
8868
Andrew Trickef9de2a2013-05-25 02:42:55 +00008869 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008870 Ptr.getValueType(), Ptr,
8871 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008872 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008873 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008874 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008875 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008876 LD->isInvariant(), NewAlign,
8877 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008878 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008879 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008880 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008881 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008882 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008883 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008884
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008885 AddToWorklist(NewPtr.getNode());
8886 AddToWorklist(NewLD.getNode());
8887 AddToWorklist(NewVal.getNode());
8888 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008889 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008890 ++OpsNarrowed;
8891 return NewST;
8892 }
8893 }
8894
Evan Cheng6673ff02009-05-28 18:41:02 +00008895 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008896}
8897
Evan Chengd42641c2011-02-02 01:06:55 +00008898/// TransformFPLoadStorePair - For a given floating point load / store pair,
8899/// if the load value isn't used by any other operations, then consider
8900/// transforming the pair to integer load / store operations if the target
8901/// deems the transformation profitable.
8902SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8903 StoreSDNode *ST = cast<StoreSDNode>(N);
8904 SDValue Chain = ST->getChain();
8905 SDValue Value = ST->getValue();
8906 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8907 Value.hasOneUse() &&
8908 Chain == SDValue(Value.getNode(), 1)) {
8909 LoadSDNode *LD = cast<LoadSDNode>(Value);
8910 EVT VT = LD->getMemoryVT();
8911 if (!VT.isFloatingPoint() ||
8912 VT != ST->getMemoryVT() ||
8913 LD->isNonTemporal() ||
8914 ST->isNonTemporal() ||
8915 LD->getPointerInfo().getAddrSpace() != 0 ||
8916 ST->getPointerInfo().getAddrSpace() != 0)
8917 return SDValue();
8918
8919 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8920 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8921 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8922 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8923 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8924 return SDValue();
8925
8926 unsigned LDAlign = LD->getAlignment();
8927 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008928 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008929 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008930 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8931 return SDValue();
8932
Andrew Trickef9de2a2013-05-25 02:42:55 +00008933 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008934 LD->getChain(), LD->getBasePtr(),
8935 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008936 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008937
Andrew Trickef9de2a2013-05-25 02:42:55 +00008938 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008939 NewLD, ST->getBasePtr(),
8940 ST->getPointerInfo(),
8941 false, false, STAlign);
8942
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008943 AddToWorklist(NewLD.getNode());
8944 AddToWorklist(NewST.getNode());
8945 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008946 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008947 ++LdStFP2Int;
8948 return NewST;
8949 }
8950
8951 return SDValue();
8952}
8953
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008954/// Helper struct to parse and store a memory address as base + index + offset.
8955/// We ignore sign extensions when it is safe to do so.
8956/// The following two expressions are not equivalent. To differentiate we need
8957/// to store whether there was a sign extension involved in the index
8958/// computation.
8959/// (load (i64 add (i64 copyfromreg %c)
8960/// (i64 signextend (add (i8 load %index)
8961/// (i8 1))))
8962/// vs
8963///
8964/// (load (i64 add (i64 copyfromreg %c)
8965/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8966/// (i32 1)))))
8967struct BaseIndexOffset {
8968 SDValue Base;
8969 SDValue Index;
8970 int64_t Offset;
8971 bool IsIndexSignExt;
8972
8973 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8974
8975 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8976 bool IsIndexSignExt) :
8977 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8978
8979 bool equalBaseIndex(const BaseIndexOffset &Other) {
8980 return Other.Base == Base && Other.Index == Index &&
8981 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008982 }
8983
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008984 /// Parses tree in Ptr for base, index, offset addresses.
8985 static BaseIndexOffset match(SDValue Ptr) {
8986 bool IsIndexSignExt = false;
8987
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008988 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8989 // instruction, then it could be just the BASE or everything else we don't
8990 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008991 if (Ptr->getOpcode() != ISD::ADD)
8992 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8993
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008994 // We know that we have at least an ADD instruction. Try to pattern match
8995 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008996 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8997 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8998 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8999 IsIndexSignExt);
9000 }
9001
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009002 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009003 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009004 // (i64 add (i64 %array_ptr)
9005 // (i64 mul (i64 %induction_var)
9006 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009007 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009008 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009009
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009010 // Look at Base + Index + Offset cases.
9011 SDValue Base = Ptr->getOperand(0);
9012 SDValue IndexOffset = Ptr->getOperand(1);
9013
9014 // Skip signextends.
9015 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9016 IndexOffset = IndexOffset->getOperand(0);
9017 IsIndexSignExt = true;
9018 }
9019
9020 // Either the case of Base + Index (no offset) or something else.
9021 if (IndexOffset->getOpcode() != ISD::ADD)
9022 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9023
9024 // Now we have the case of Base + Index + offset.
9025 SDValue Index = IndexOffset->getOperand(0);
9026 SDValue Offset = IndexOffset->getOperand(1);
9027
9028 if (!isa<ConstantSDNode>(Offset))
9029 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9030
9031 // Ignore signextends.
9032 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9033 Index = Index->getOperand(0);
9034 IsIndexSignExt = true;
9035 } else IsIndexSignExt = false;
9036
9037 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9038 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9039 }
9040};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009041
9042/// Holds a pointer to an LSBaseSDNode as well as information on where it
9043/// is located in a sequence of memory operations connected by a chain.
9044struct MemOpLink {
9045 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9046 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9047 // Ptr to the mem node.
9048 LSBaseSDNode *MemNode;
9049 // Offset from the base ptr.
9050 int64_t OffsetFromBase;
9051 // What is the sequence number of this mem node.
9052 // Lowest mem operand in the DAG starts at zero.
9053 unsigned SequenceNum;
9054};
9055
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009056bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9057 EVT MemVT = St->getMemoryVT();
9058 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009059 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9060 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009061
9062 // Don't merge vectors into wider inputs.
9063 if (MemVT.isVector() || !MemVT.isSimple())
9064 return false;
9065
9066 // Perform an early exit check. Do not bother looking at stored values that
9067 // are not constants or loads.
9068 SDValue StoredVal = St->getValue();
9069 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9070 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9071 !IsLoadSrc)
9072 return false;
9073
9074 // Only look at ends of store sequences.
9075 SDValue Chain = SDValue(St, 1);
9076 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9077 return false;
9078
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009079 // This holds the base pointer, index, and the offset in bytes from the base
9080 // pointer.
9081 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009082
9083 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009084 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009085 return false;
9086
9087 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009088 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009089 return false;
9090
Nadav Rotem307d7672012-11-29 00:00:08 +00009091 // Save the LoadSDNodes that we find in the chain.
9092 // We need to make sure that these nodes do not interfere with
9093 // any of the store nodes.
9094 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9095
9096 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009097 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009098
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009099 // Walk up the chain and look for nodes with offsets from the same
9100 // base pointer. Stop when reaching an instruction with a different kind
9101 // or instruction which has a different base pointer.
9102 unsigned Seq = 0;
9103 StoreSDNode *Index = St;
9104 while (Index) {
9105 // If the chain has more than one use, then we can't reorder the mem ops.
9106 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9107 break;
9108
9109 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009110 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009111
9112 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009113 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009114 break;
9115
9116 // Check that the alignment is the same.
9117 if (Index->getAlignment() != St->getAlignment())
9118 break;
9119
9120 // The memory operands must not be volatile.
9121 if (Index->isVolatile() || Index->isIndexed())
9122 break;
9123
9124 // No truncation.
9125 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9126 if (St->isTruncatingStore())
9127 break;
9128
9129 // The stored memory type must be the same.
9130 if (Index->getMemoryVT() != MemVT)
9131 break;
9132
9133 // We do not allow unaligned stores because we want to prevent overriding
9134 // stores.
9135 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9136 break;
9137
9138 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009139 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009140
Nadav Rotem307d7672012-11-29 00:00:08 +00009141 // Find the next memory operand in the chain. If the next operand in the
9142 // chain is a store then move up and continue the scan with the next
9143 // memory operand. If the next operand is a load save it and use alias
9144 // information to check if it interferes with anything.
9145 SDNode *NextInChain = Index->getChain().getNode();
9146 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009147 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009148 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009149 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009150 break;
9151 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009152 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009153 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009154 break;
9155 }
9156
Nadav Rotem307d7672012-11-29 00:00:08 +00009157 // Save the load node for later. Continue the scan.
9158 AliasLoadNodes.push_back(Ldn);
9159 NextInChain = Ldn->getChain().getNode();
9160 continue;
9161 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009162 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009163 break;
9164 }
9165 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009166 }
9167
9168 // Check if there is anything to merge.
9169 if (StoreNodes.size() < 2)
9170 return false;
9171
9172 // Sort the memory operands according to their distance from the base pointer.
9173 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009174 [](MemOpLink LHS, MemOpLink RHS) {
9175 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9176 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9177 LHS.SequenceNum > RHS.SequenceNum);
9178 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009179
9180 // Scan the memory operations on the chain and find the first non-consecutive
9181 // store memory address.
9182 unsigned LastConsecutiveStore = 0;
9183 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009184 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9185
9186 // Check that the addresses are consecutive starting from the second
9187 // element in the list of stores.
9188 if (i > 0) {
9189 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9190 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9191 break;
9192 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009193
Nadav Rotem307d7672012-11-29 00:00:08 +00009194 bool Alias = false;
9195 // Check if this store interferes with any of the loads that we found.
9196 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9197 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9198 Alias = true;
9199 break;
9200 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009201 // We found a load that alias with this store. Stop the sequence.
9202 if (Alias)
9203 break;
9204
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009205 // Mark this node as useful.
9206 LastConsecutiveStore = i;
9207 }
9208
9209 // The node with the lowest store address.
9210 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9211
9212 // Store the constants into memory as one consecutive store.
9213 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009214 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009215 unsigned LastLegalVectorType = 0;
9216 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009217 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9218 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9219 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009220
9221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009222 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009223 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009224 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009225 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009226 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009228 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009229
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009230 // Find a legal type for the constant store.
9231 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9232 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9233 if (TLI.isTypeLegal(StoreTy))
9234 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009235 // Or check whether a truncstore is legal.
9236 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9237 TargetLowering::TypePromoteInteger) {
9238 EVT LegalizedStoredValueTy =
9239 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9240 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9241 LastLegalType = i+1;
9242 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009243
9244 // Find a legal type for the vector store.
9245 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9246 if (TLI.isTypeLegal(Ty))
9247 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009248 }
9249
Bob Wilson3365b802012-12-20 01:36:20 +00009250 // We only use vectors if the constant is known to be zero and the
9251 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009252 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009253 LastLegalVectorType = 0;
9254
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009255 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009256 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009257 return false;
9258
Nadav Rotem495b1a42013-02-14 18:28:52 +00009259 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009260 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9261
9262 // Make sure we have something to merge.
9263 if (NumElem < 2)
9264 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009265
9266 unsigned EarliestNodeUsed = 0;
9267 for (unsigned i=0; i < NumElem; ++i) {
9268 // Find a chain for the new wide-store operand. Notice that some
9269 // of the store nodes that we found may not be selected for inclusion
9270 // in the wide store. The chain we use needs to be the chain of the
9271 // earliest store node which is *used* and replaced by the wide store.
9272 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9273 EarliestNodeUsed = i;
9274 }
9275
9276 // The earliest Node in the DAG.
9277 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009278 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009279
Nadav Rotemb27777f2012-10-04 22:35:15 +00009280 SDValue StoredVal;
9281 if (UseVector) {
9282 // Find a legal type for the vector store.
9283 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9284 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9285 StoredVal = DAG.getConstant(0, Ty);
9286 } else {
9287 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9288 APInt StoreInt(StoreBW, 0);
9289
9290 // Construct a single integer constant which is made of the smaller
9291 // constant inputs.
9292 bool IsLE = TLI.isLittleEndian();
9293 for (unsigned i = 0; i < NumElem ; ++i) {
9294 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9295 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9296 SDValue Val = St->getValue();
9297 StoreInt<<=ElementSizeBytes*8;
9298 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9299 StoreInt|=C->getAPIntValue().zext(StoreBW);
9300 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9301 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9302 } else {
9303 assert(false && "Invalid constant element type");
9304 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009305 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009306
9307 // Create the new Load and Store operations.
9308 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9309 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009310 }
9311
Nadav Rotemb27777f2012-10-04 22:35:15 +00009312 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009313 FirstInChain->getBasePtr(),
9314 FirstInChain->getPointerInfo(),
9315 false, false,
9316 FirstInChain->getAlignment());
9317
9318 // Replace the first store with the new store
9319 CombineTo(EarliestOp, NewStore);
9320 // Erase all other stores.
9321 for (unsigned i = 0; i < NumElem ; ++i) {
9322 if (StoreNodes[i].MemNode == EarliestOp)
9323 continue;
9324 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009325 // ReplaceAllUsesWith will replace all uses that existed when it was
9326 // called, but graph optimizations may cause new ones to appear. For
9327 // example, the case in pr14333 looks like
9328 //
9329 // St's chain -> St -> another store -> X
9330 //
9331 // And the only difference from St to the other store is the chain.
9332 // When we change it's chain to be St's chain they become identical,
9333 // get CSEed and the net result is that X is now a use of St.
9334 // Since we know that St is redundant, just iterate.
9335 while (!St->use_empty())
9336 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009337 removeFromWorklist(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009338 DAG.DeleteNode(St);
9339 }
9340
9341 return true;
9342 }
9343
9344 // Below we handle the case of multiple consecutive stores that
9345 // come from multiple consecutive loads. We merge them into a single
9346 // wide load and a single wide store.
9347
9348 // Look for load nodes which are used by the stored values.
9349 SmallVector<MemOpLink, 8> LoadNodes;
9350
9351 // Find acceptable loads. Loads need to have the same chain (token factor),
9352 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009353 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009354 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9355 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9356 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9357 if (!Ld) break;
9358
9359 // Loads must only have one use.
9360 if (!Ld->hasNUsesOfValue(1, 0))
9361 break;
9362
9363 // Check that the alignment is the same as the stores.
9364 if (Ld->getAlignment() != St->getAlignment())
9365 break;
9366
9367 // The memory operands must not be volatile.
9368 if (Ld->isVolatile() || Ld->isIndexed())
9369 break;
9370
9371 // We do not accept ext loads.
9372 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9373 break;
9374
9375 // The stored memory type must be the same.
9376 if (Ld->getMemoryVT() != MemVT)
9377 break;
9378
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009379 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009380 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009381 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009382 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009383 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009384 break;
9385 } else {
9386 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009387 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009388 }
9389
9390 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009391 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009392 }
9393
9394 if (LoadNodes.size() < 2)
9395 return false;
9396
9397 // Scan the memory operations on the chain and find the first non-consecutive
9398 // load memory address. These variables hold the index in the store node
9399 // array.
9400 unsigned LastConsecutiveLoad = 0;
9401 // This variable refers to the size and not index in the array.
9402 unsigned LastLegalVectorType = 0;
9403 unsigned LastLegalIntegerType = 0;
9404 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009405 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9406 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9407 // All loads much share the same chain.
9408 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9409 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009410
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009411 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9412 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9413 break;
9414 LastConsecutiveLoad = i;
9415
9416 // Find a legal type for the vector store.
9417 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9418 if (TLI.isTypeLegal(StoreTy))
9419 LastLegalVectorType = i + 1;
9420
9421 // Find a legal type for the integer store.
9422 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9423 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9424 if (TLI.isTypeLegal(StoreTy))
9425 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009426 // Or check whether a truncstore and extload is legal.
9427 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9428 TargetLowering::TypePromoteInteger) {
9429 EVT LegalizedStoredValueTy =
9430 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9431 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9432 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9433 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9434 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9435 LastLegalIntegerType = i+1;
9436 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009437 }
9438
9439 // Only use vector types if the vector type is larger than the integer type.
9440 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009441 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009442 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9443
9444 // We add +1 here because the LastXXX variables refer to location while
9445 // the NumElem refers to array/index size.
9446 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9447 NumElem = std::min(LastLegalType, NumElem);
9448
9449 if (NumElem < 2)
9450 return false;
9451
9452 // The earliest Node in the DAG.
9453 unsigned EarliestNodeUsed = 0;
9454 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9455 for (unsigned i=1; i<NumElem; ++i) {
9456 // Find a chain for the new wide-store operand. Notice that some
9457 // of the store nodes that we found may not be selected for inclusion
9458 // in the wide store. The chain we use needs to be the chain of the
9459 // earliest store node which is *used* and replaced by the wide store.
9460 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9461 EarliestNodeUsed = i;
9462 }
9463
9464 // Find if it is better to use vectors or integers to load and store
9465 // to memory.
9466 EVT JointMemOpVT;
9467 if (UseVectorTy) {
9468 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9469 } else {
9470 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9471 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9472 }
9473
Andrew Trickef9de2a2013-05-25 02:42:55 +00009474 SDLoc LoadDL(LoadNodes[0].MemNode);
9475 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009476
9477 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9478 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9479 FirstLoad->getChain(),
9480 FirstLoad->getBasePtr(),
9481 FirstLoad->getPointerInfo(),
9482 false, false, false,
9483 FirstLoad->getAlignment());
9484
9485 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9486 FirstInChain->getBasePtr(),
9487 FirstInChain->getPointerInfo(), false, false,
9488 FirstInChain->getAlignment());
9489
Nadav Rotemac920662012-10-03 19:30:31 +00009490 // Replace one of the loads with the new load.
9491 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9492 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9493 SDValue(NewLoad.getNode(), 1));
9494
9495 // Remove the rest of the load chains.
9496 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009497 // Replace all chain users of the old load nodes with the chain of the new
9498 // load node.
9499 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009500 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9501 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009502
Nadav Rotemac920662012-10-03 19:30:31 +00009503 // Replace the first store with the new store.
9504 CombineTo(EarliestOp, NewStore);
9505 // Erase all other stores.
9506 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009507 // Remove all Store nodes.
9508 if (StoreNodes[i].MemNode == EarliestOp)
9509 continue;
9510 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9511 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009512 removeFromWorklist(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009513 DAG.DeleteNode(St);
9514 }
9515
9516 return true;
9517}
9518
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009519SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009520 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009521 SDValue Chain = ST->getChain();
9522 SDValue Value = ST->getValue();
9523 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009524
Evan Chenga4cf58a2007-05-07 21:27:48 +00009525 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009526 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009527 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009528 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009529 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009530 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009531 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009532 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009533 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009534 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009535 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009536 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009537 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009538 ST->isNonTemporal(), OrigAlign,
9539 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009540 }
Owen Andersona5192842011-04-14 17:30:49 +00009541
Chris Lattner41c80e82011-04-09 02:32:02 +00009542 // Turn 'store undef, Ptr' -> nothing.
9543 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9544 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009545
Nate Begeman8e20c762006-12-11 02:23:46 +00009546 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009547 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009548 // NOTE: If the original store is volatile, this transform must not increase
9549 // the number of stores. For example, on x86-32 an f64 can be stored in one
9550 // processor operation but an i64 (which is not legal) requires two. So the
9551 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009552 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009553 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009554 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009555 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009556 case MVT::f16: // We don't do this for these yet.
9557 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009558 case MVT::f128:
9559 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009560 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009561 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009562 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009563 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009564 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009565 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009566 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009567 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009568 }
9569 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009570 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009571 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009572 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009573 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009574 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009575 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009576 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009577 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009578 }
Owen Andersona5192842011-04-14 17:30:49 +00009579
Chris Lattner41c80e82011-04-09 02:32:02 +00009580 if (!ST->isVolatile() &&
9581 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009582 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009583 // argument passing. Since this is so common, custom legalize the
9584 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009585 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009586 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9587 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009588 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009589
Dan Gohman2af30632007-07-09 22:18:38 +00009590 unsigned Alignment = ST->getAlignment();
9591 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009592 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009593 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009594
Andrew Trickef9de2a2013-05-25 02:42:55 +00009595 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009596 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009597 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009598 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009599 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009600 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009601 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009602 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009603 Ptr, ST->getPointerInfo().getWithOffset(4),
9604 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009605 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009606 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009607 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009608 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009609
Chris Lattnerb7524b62006-12-12 04:16:14 +00009610 break;
Evan Cheng21836982006-12-11 17:25:19 +00009611 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009612 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009613 }
9614
Evan Cheng43cd9e32010-04-01 06:04:33 +00009615 // Try to infer better alignment information than the store already has.
9616 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009617 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9618 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009619 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009620 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009621 ST->isVolatile(), ST->isNonTemporal(), Align,
9622 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009623 }
9624 }
9625
Evan Chengd42641c2011-02-02 01:06:55 +00009626 // Try transforming a pair floating point load / store ops to integer
9627 // load / store ops.
9628 SDValue NewST = TransformFPLoadStorePair(N);
9629 if (NewST.getNode())
9630 return NewST;
9631
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009632 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9633 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009634#ifndef NDEBUG
9635 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9636 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9637 UseAA = false;
9638#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009639 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009640 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009641 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009642
Jim Laskey708d0db2006-10-04 16:53:27 +00009643 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009644 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009645 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009646
9647 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009648 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009649 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009650 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009651 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009652 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009653 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009654 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009655
Jim Laskeyd07be232006-09-25 16:29:54 +00009656 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009657 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009658 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009659
Nate Begeman879d8f12009-09-15 00:18:30 +00009660 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009661 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009662
Jim Laskeydcf983c2006-10-13 23:32:28 +00009663 // Don't add users to work list.
9664 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009665 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009666 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009667
Evan Cheng33157702006-11-05 09:31:14 +00009668 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009669 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009670 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009671
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009672 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009673 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009674 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009675 // See if we can simplify the input to this truncstore with knowledge that
9676 // only the low bits are being used. For example:
9677 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009678 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009679 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009680 APInt::getLowBitsSet(
9681 Value.getValueType().getScalarType().getSizeInBits(),
9682 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009683 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009684 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009685 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009686 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009687
Chris Lattnerf47e3062007-10-13 06:58:48 +00009688 // Otherwise, see if we can simplify the operation with
9689 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009690 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009691 APInt::getLowBitsSet(
9692 Value.getValueType().getScalarType().getSizeInBits(),
9693 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009694 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009695 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009696
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009697 // If this is a load followed by a store to the same location, then the store
9698 // is dead/noop.
9699 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009700 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009701 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009702 // There can't be any side effects between the load and store, such as
9703 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009704 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009705 // The store is dead, remove it.
9706 return Chain;
9707 }
9708 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009709
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009710 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9711 // truncating store. We can do this even if this is already a truncstore.
9712 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009713 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009714 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009715 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009716 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009717 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009718 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009719
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009720 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009721 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009722 if (!LegalTypes) {
9723 bool EverChanged = false;
9724
9725 do {
9726 // There can be multiple store sequences on the same chain.
9727 // Keep trying to merge store sequences until we are unable to do so
9728 // or until we merge the last store on the chain.
9729 bool Changed = MergeConsecutiveStores(ST);
9730 EverChanged |= Changed;
9731 if (!Changed) break;
9732 } while (ST->getOpcode() != ISD::DELETED_NODE);
9733
9734 if (EverChanged)
9735 return SDValue(N, 0);
9736 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009737
Evan Chenga9cda8a2009-05-28 00:35:15 +00009738 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009739}
9740
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009741SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9742 SDValue InVec = N->getOperand(0);
9743 SDValue InVal = N->getOperand(1);
9744 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009745 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009746
Bob Wilson42603952010-05-19 23:42:58 +00009747 // If the inserted element is an UNDEF, just use the input vector.
9748 if (InVal.getOpcode() == ISD::UNDEF)
9749 return InVec;
9750
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009751 EVT VT = InVec.getValueType();
9752
Owen Andersonb2c80da2011-02-25 21:41:48 +00009753 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009754 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9755 return SDValue();
9756
Eli Friedmanb7910b72011-09-09 21:04:06 +00009757 // Check that we know which element is being inserted
9758 if (!isa<ConstantSDNode>(EltNo))
9759 return SDValue();
9760 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009761
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009762 // Canonicalize insert_vector_elt dag nodes.
9763 // Example:
9764 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9765 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9766 //
9767 // Do this only if the child insert_vector node has one use; also
9768 // do this only if indices are both constants and Idx1 < Idx0.
9769 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9770 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9771 unsigned OtherElt =
9772 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9773 if (Elt < OtherElt) {
9774 // Swap nodes.
9775 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9776 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009777 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009778 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9779 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9780 }
9781 }
9782
Eli Friedmanb7910b72011-09-09 21:04:06 +00009783 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9784 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9785 // vector elements.
9786 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009787 // Do not combine these two vectors if the output vector will not replace
9788 // the input vector.
9789 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009790 Ops.append(InVec.getNode()->op_begin(),
9791 InVec.getNode()->op_end());
9792 } else if (InVec.getOpcode() == ISD::UNDEF) {
9793 unsigned NElts = VT.getVectorNumElements();
9794 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9795 } else {
9796 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009797 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009798
9799 // Insert the element
9800 if (Elt < Ops.size()) {
9801 // All the operands of BUILD_VECTOR must have the same type;
9802 // we enforce that here.
9803 EVT OpVT = Ops[0].getValueType();
9804 if (InVal.getValueType() != OpVT)
9805 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9806 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9807 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9808 Ops[Elt] = InVal;
9809 }
9810
9811 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009812 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009813}
9814
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009815SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009816 // (vextract (scalar_to_vector val, 0) -> val
9817 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009818 EVT VT = InVec.getValueType();
9819 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009820
Duncan Sands6be291a2011-05-09 08:03:33 +00009821 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9822 // Check if the result type doesn't match the inserted element type. A
9823 // SCALAR_TO_VECTOR may truncate the inserted element and the
9824 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9825 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009826 if (InOp.getValueType() != NVT) {
9827 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009828 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009829 }
9830 return InOp;
9831 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009832
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009833 SDValue EltNo = N->getOperand(1);
9834 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9835
9836 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9837 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009838 // we may introduce new vector instructions which are not backed by TD
9839 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009840 // without using extract_subvector. However, if we can find an underlying
9841 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009842 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009843 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009844 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9845 int NumElem = VT.getVectorNumElements();
9846 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9847 // Find the new index to extract from.
9848 int OrigElt = SVOp->getMaskElt(Elt);
9849
9850 // Extracting an undef index is undef.
9851 if (OrigElt == -1)
9852 return DAG.getUNDEF(NVT);
9853
9854 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009855 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009856 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009857 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009858 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009859 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009860 OrigElt -= NumElem;
9861 }
9862
Hal Finkel02807592014-03-31 11:43:19 +00009863 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9864 SDValue InOp = SVInVec.getOperand(OrigElt);
9865 if (InOp.getValueType() != NVT) {
9866 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9867 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9868 }
9869
9870 return InOp;
9871 }
9872
9873 // FIXME: We should handle recursing on other vector shuffles and
9874 // scalar_to_vector here as well.
9875
9876 if (!LegalOperations) {
9877 EVT IndexTy = TLI.getVectorIdxTy();
9878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9879 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9880 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009881 }
9882
Evan Cheng1120279a2008-05-13 08:35:03 +00009883 // Perform only after legalization to ensure build_vector / vector_shuffle
9884 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009885 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009886
Mon P Wangca6d6de2009-01-17 00:07:25 +00009887 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9888 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9889 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009890
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009891 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009892 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Michael J. Spencer1eb02302014-07-18 00:15:50 +00009893 bool NewLoad = false;
9894 bool BCNumEltsChanged = false;
9895 EVT ExtVT = VT.getVectorElementType();
9896 EVT LVT = ExtVT;
9897
9898 // If the result of load has to be truncated, then it's not necessarily
9899 // profitable.
9900 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9901 return SDValue();
9902
9903 if (InVec.getOpcode() == ISD::BITCAST) {
9904 // Don't duplicate a load with other uses.
9905 if (!InVec.hasOneUse())
9906 return SDValue();
9907
9908 EVT BCVT = InVec.getOperand(0).getValueType();
9909 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9910 return SDValue();
9911 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9912 BCNumEltsChanged = true;
9913 InVec = InVec.getOperand(0);
9914 ExtVT = BCVT.getVectorElementType();
9915 NewLoad = true;
9916 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009917
Craig Topperc0196b12014-04-14 00:51:57 +00009918 LoadSDNode *LN0 = nullptr;
9919 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009920 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009921 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009922 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009923 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009924 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009925 // Don't duplicate a load with other uses.
9926 if (!InVec.hasOneUse())
9927 return SDValue();
9928
Evan Cheng1120279a2008-05-13 08:35:03 +00009929 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009930 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009931 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9932 // =>
9933 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009934
Eli Friedmane96286c2011-12-26 22:49:32 +00009935 // Don't duplicate a load with other uses.
9936 if (!InVec.hasOneUse())
9937 return SDValue();
9938
Mon P Wangb5eb7202008-12-11 00:26:16 +00009939 // If the bit convert changed the number of elements, it is unsafe
9940 // to examine the mask.
9941 if (BCNumEltsChanged)
9942 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009943
9944 // Select the input vector, guarding against out of range extract vector.
9945 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009946 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009947 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9948
Eli Friedmane96286c2011-12-26 22:49:32 +00009949 if (InVec.getOpcode() == ISD::BITCAST) {
9950 // Don't duplicate a load with other uses.
9951 if (!InVec.hasOneUse())
9952 return SDValue();
9953
Evan Cheng1120279a2008-05-13 08:35:03 +00009954 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009955 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009956 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009957 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009958 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009959 }
9960 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009961
Eli Friedmane96286c2011-12-26 22:49:32 +00009962 // Make sure we found a non-volatile load and the extractelement is
9963 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009964 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009965 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009966
Eric Christopherc6418b12010-11-03 20:44:42 +00009967 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9968 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009969 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009970
Michael J. Spencer1eb02302014-07-18 00:15:50 +00009971 unsigned Align = LN0->getAlignment();
9972 if (NewLoad) {
9973 // Check the resultant load doesn't need a higher alignment than the
9974 // original load.
9975 unsigned NewAlign =
9976 TLI.getDataLayout()
9977 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9978
9979 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9980 return SDValue();
9981
9982 Align = NewAlign;
9983 }
9984
9985 SDValue NewPtr = LN0->getBasePtr();
9986 unsigned PtrOff = 0;
9987
9988 if (Elt) {
9989 PtrOff = LVT.getSizeInBits() * Elt / 8;
9990 EVT PtrType = NewPtr.getValueType();
9991 if (TLI.isBigEndian())
9992 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9993 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9994 DAG.getConstant(PtrOff, PtrType));
9995 }
9996
9997 // The replacement we need to do here is a little tricky: we need to
9998 // replace an extractelement of a load with a load.
9999 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10000 // Note that this replacement assumes that the extractvalue is the only
10001 // use of the load; that's okay because we don't want to perform this
10002 // transformation in other cases anyway.
10003 SDValue Load;
10004 SDValue Chain;
10005 if (NVT.bitsGT(LVT)) {
10006 // If the result type of vextract is wider than the load, then issue an
10007 // extending load instead.
10008 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10009 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10010 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10011 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10012 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10013 Align, LN0->getTBAAInfo());
10014 Chain = Load.getValue(1);
10015 } else {
10016 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10017 LN0->getPointerInfo().getWithOffset(PtrOff),
10018 LN0->isVolatile(), LN0->isNonTemporal(),
10019 LN0->isInvariant(), Align, LN0->getTBAAInfo());
10020 Chain = Load.getValue(1);
10021 if (NVT.bitsLT(LVT))
10022 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10023 else
10024 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10025 }
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010026 WorklistRemover DeadNodes(*this);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010027 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10028 SDValue To[] = { Load, Chain };
10029 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10030 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10031 // worklist explicitly as well.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010032 AddToWorklist(Load.getNode());
10033 AddUsersToWorklist(Load.getNode()); // Add users too
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010034 // Make sure to revisit this node to clean it up; it will usually be dead.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010035 AddToWorklist(N);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010036 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010037 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010039 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010040}
Evan Cheng0de312d2007-10-06 08:19:55 +000010041
Michael Liao6d106b72012-10-23 23:06:52 +000010042// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10043SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10044 // We perform this optimization post type-legalization because
10045 // the type-legalizer often scalarizes integer-promoted vectors.
10046 // Performing this optimization before may create bit-casts which
10047 // will be type-legalized to complex code sequences.
10048 // We perform this optimization only before the operation legalizer because we
10049 // may introduce illegal operations.
10050 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10051 return SDValue();
10052
Dan Gohmana8665142007-06-25 16:23:39 +000010053 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010054 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010055 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010056
Nadav Rotembf6568b2011-10-29 21:23:04 +000010057 // Check to see if this is a BUILD_VECTOR of a bunch of values
10058 // which come from any_extend or zero_extend nodes. If so, we can create
10059 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010060 // optimizations. We do not handle sign-extend because we can't fill the sign
10061 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010062 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010063 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010064
Craig Topper02cb0fb2012-01-17 09:09:48 +000010065 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010066 SDValue In = N->getOperand(i);
10067 // Ignore undef inputs.
10068 if (In.getOpcode() == ISD::UNDEF) continue;
10069
10070 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10071 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10072
Nadav Rotemf3103612011-10-31 20:08:25 +000010073 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010074 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010075 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010076 break;
10077 }
10078
10079 // The input is a ZeroExt or AnyExt. Check the original type.
10080 EVT InTy = In.getOperand(0).getValueType();
10081
10082 // Check that all of the widened source types are the same.
10083 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010084 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010085 SourceType = InTy;
10086 else if (InTy != SourceType) {
10087 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010088 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010089 break;
10090 }
10091
10092 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010093 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010094 }
10095
Nadav Rotemf3103612011-10-31 20:08:25 +000010096 // In order to have valid types, all of the inputs must be extended from the
10097 // same source type and all of the inputs must be any or zero extend.
10098 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010099 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010100 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010101 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10102 isPowerOf2_32(SourceType.getSizeInBits());
10103
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010104 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10105 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010106 if (!ValidTypes)
10107 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010108
Michael Liao6d106b72012-10-23 23:06:52 +000010109 bool isLE = TLI.isLittleEndian();
10110 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10111 assert(ElemRatio > 1 && "Invalid element size ratio");
10112 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10113 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010114
Michael Liao6d106b72012-10-23 23:06:52 +000010115 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10116 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010117
Michael Liao6d106b72012-10-23 23:06:52 +000010118 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010119 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010120 SDValue Cast = N->getOperand(i);
10121 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10122 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10123 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10124 SDValue In;
10125 if (Cast.getOpcode() == ISD::UNDEF)
10126 In = DAG.getUNDEF(SourceType);
10127 else
10128 In = Cast->getOperand(0);
10129 unsigned Index = isLE ? (i * ElemRatio) :
10130 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010131
Michael Liao6d106b72012-10-23 23:06:52 +000010132 assert(Index < Ops.size() && "Invalid index");
10133 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010134 }
Chris Lattner5336a592006-03-19 01:27:56 +000010135
Michael Liao6d106b72012-10-23 23:06:52 +000010136 // The type of the new BUILD_VECTOR node.
10137 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10138 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10139 "Invalid vector size");
10140 // Check if the new vector type is legal.
10141 if (!isTypeLegal(VecVT)) return SDValue();
10142
10143 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010144 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010145
10146 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010147 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010148 // Bitcast to the desired type.
10149 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10150}
10151
Michael Liao59229792012-10-24 04:14:18 +000010152SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10153 EVT VT = N->getValueType(0);
10154
10155 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010156 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010157
10158 EVT SrcVT = MVT::Other;
10159 unsigned Opcode = ISD::DELETED_NODE;
10160 unsigned NumDefs = 0;
10161
10162 for (unsigned i = 0; i != NumInScalars; ++i) {
10163 SDValue In = N->getOperand(i);
10164 unsigned Opc = In.getOpcode();
10165
10166 if (Opc == ISD::UNDEF)
10167 continue;
10168
10169 // If all scalar values are floats and converted from integers.
10170 if (Opcode == ISD::DELETED_NODE &&
10171 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10172 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010173 }
Tom Stellard567f8862013-01-02 22:13:01 +000010174
Michael Liao59229792012-10-24 04:14:18 +000010175 if (Opc != Opcode)
10176 return SDValue();
10177
10178 EVT InVT = In.getOperand(0).getValueType();
10179
10180 // If all scalar values are typed differently, bail out. It's chosen to
10181 // simplify BUILD_VECTOR of integer types.
10182 if (SrcVT == MVT::Other)
10183 SrcVT = InVT;
10184 if (SrcVT != InVT)
10185 return SDValue();
10186 NumDefs++;
10187 }
10188
10189 // If the vector has just one element defined, it's not worth to fold it into
10190 // a vectorized one.
10191 if (NumDefs < 2)
10192 return SDValue();
10193
10194 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10195 && "Should only handle conversion from integer to float.");
10196 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10197
10198 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010199
10200 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10201 return SDValue();
10202
Michael Liao59229792012-10-24 04:14:18 +000010203 SmallVector<SDValue, 8> Opnds;
10204 for (unsigned i = 0; i != NumInScalars; ++i) {
10205 SDValue In = N->getOperand(i);
10206
10207 if (In.getOpcode() == ISD::UNDEF)
10208 Opnds.push_back(DAG.getUNDEF(SrcVT));
10209 else
10210 Opnds.push_back(In.getOperand(0));
10211 }
Craig Topper48d114b2014-04-26 18:35:24 +000010212 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010213 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010214
10215 return DAG.getNode(Opcode, dl, VT, BV);
10216}
10217
Michael Liao6d106b72012-10-23 23:06:52 +000010218SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10219 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010220 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010221 EVT VT = N->getValueType(0);
10222
10223 // A vector built entirely of undefs is undef.
10224 if (ISD::allOperandsUndef(N))
10225 return DAG.getUNDEF(VT);
10226
10227 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10228 if (V.getNode())
10229 return V;
10230
Michael Liao59229792012-10-24 04:14:18 +000010231 V = reduceBuildVecConvertToConvertBuildVec(N);
10232 if (V.getNode())
10233 return V;
10234
Dan Gohmana8665142007-06-25 16:23:39 +000010235 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10236 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10237 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010238
10239 // May only combine to shuffle after legalize if shuffle is legal.
10240 if (LegalOperations &&
10241 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10242 return SDValue();
10243
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010244 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010245 for (unsigned i = 0; i != NumInScalars; ++i) {
10246 // Ignore undef inputs.
10247 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010248
Dan Gohmana8665142007-06-25 16:23:39 +000010249 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010250 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010251 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010252 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010253 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010254 break;
10255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010256
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010257 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010258 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010259 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10260 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010261
Craig Topperc0196b12014-04-14 00:51:57 +000010262 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010263 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010264 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010265 VecIn2 = ExtractedFromVec;
10266 } else {
10267 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010268 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010269 break;
10270 }
10271 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010272
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010273 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010274 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010275 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010276 for (unsigned i = 0; i != NumInScalars; ++i) {
10277 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010278 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010279 continue;
10280 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010281
Rafael Espindolab93db662009-04-24 12:40:33 +000010282 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010283 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010284 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010285 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010286 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10287 if (ExtIndex > VT.getVectorNumElements())
10288 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010289
Nate Begeman5f829d82009-04-29 05:20:52 +000010290 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010291 continue;
10292 }
10293
10294 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010295 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010296 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010298
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010299 // We can't generate a shuffle node with mismatched input and output types.
10300 // Attempt to transform a single input vector to the correct type.
10301 if ((VT != VecIn1.getValueType())) {
10302 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010303 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010304 return SDValue();
10305
10306 // We only support widening of vectors which are half the size of the
10307 // output registers. For example XMM->YMM widening on X86 with AVX.
10308 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10309 return SDValue();
10310
James Molloy1e5c6112012-09-10 14:01:21 +000010311 // If the input vector type has a different base type to the output
10312 // vector type, bail out.
10313 if (VecIn1.getValueType().getVectorElementType() !=
10314 VT.getVectorElementType())
10315 return SDValue();
10316
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010317 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010318 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010319 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010320 }
10321
10322 // If VecIn2 is unused then change it to undef.
10323 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10324
Nadav Rotem841c9a82012-09-20 08:53:31 +000010325 // Check that we were able to transform all incoming values to the same
10326 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010327 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10328 VecIn1.getValueType() != VT)
10329 return SDValue();
10330
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010331 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010332 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010333 return SDValue();
10334
Dan Gohmana8665142007-06-25 16:23:39 +000010335 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010336 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010337 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010338 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010339 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010340 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010342 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010343}
10344
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010345SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010346 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10347 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10348 // inputs come from at most two distinct vectors, turn this into a shuffle
10349 // node.
10350
10351 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010352 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010353 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010354
Nadav Rotem01892102012-07-14 21:30:27 +000010355 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010356 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010357 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010358 return DAG.getUNDEF(VT);
10359
10360 // Optimize concat_vectors where one of the vectors is undef.
10361 if (N->getNumOperands() == 2 &&
10362 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10363 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010364 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010365
10366 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10367 if (In->getOpcode() == ISD::BITCAST &&
10368 !In->getOperand(0)->getValueType(0).isVector()) {
10369 SDValue Scalar = In->getOperand(0);
10370 EVT SclTy = Scalar->getValueType(0);
10371
10372 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10373 return SDValue();
10374
10375 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10376 VT.getSizeInBits() / SclTy.getSizeInBits());
10377 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10378 return SDValue();
10379
10380 SDLoc dl = SDLoc(N);
10381 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10382 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10383 }
10384 }
Nadav Rotem01892102012-07-14 21:30:27 +000010385
Robert Lougher7d9084f2014-02-11 15:42:46 +000010386 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10387 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10388 if (N->getNumOperands() == 2 &&
10389 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10390 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10391 EVT VT = N->getValueType(0);
10392 SDValue N0 = N->getOperand(0);
10393 SDValue N1 = N->getOperand(1);
10394 SmallVector<SDValue, 8> Opnds;
10395 unsigned BuildVecNumElts = N0.getNumOperands();
10396
Hao Liu71224b02014-07-10 03:41:50 +000010397 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10398 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10399 if (SclTy0.isFloatingPoint()) {
10400 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10401 Opnds.push_back(N0.getOperand(i));
10402 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10403 Opnds.push_back(N1.getOperand(i));
10404 } else {
10405 // If BUILD_VECTOR are from built from integer, they may have different
10406 // operand types. Get the smaller type and truncate all operands to it.
10407 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10408 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10409 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10410 N0.getOperand(i)));
10411 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10412 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10413 N1.getOperand(i)));
10414 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010415
Craig Topper48d114b2014-04-26 18:35:24 +000010416 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010417 }
10418
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010419 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10420 // nodes often generate nop CONCAT_VECTOR nodes.
10421 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10422 // place the incoming vectors at the exact same location.
10423 SDValue SingleSource = SDValue();
10424 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10425
10426 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10427 SDValue Op = N->getOperand(i);
10428
10429 if (Op.getOpcode() == ISD::UNDEF)
10430 continue;
10431
10432 // Check if this is the identity extract:
10433 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10434 return SDValue();
10435
10436 // Find the single incoming vector for the extract_subvector.
10437 if (SingleSource.getNode()) {
10438 if (Op.getOperand(0) != SingleSource)
10439 return SDValue();
10440 } else {
10441 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010442
10443 // Check the source type is the same as the type of the result.
10444 // If not, this concat may extend the vector, so we can not
10445 // optimize it away.
10446 if (SingleSource.getValueType() != N->getValueType(0))
10447 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010448 }
10449
10450 unsigned IdentityIndex = i * PartNumElem;
10451 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10452 // The extract index must be constant.
10453 if (!CS)
10454 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010455
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010456 // Check that we are reading from the identity index.
10457 if (CS->getZExtValue() != IdentityIndex)
10458 return SDValue();
10459 }
10460
10461 if (SingleSource.getNode())
10462 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010463
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010464 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010465}
10466
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010467SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10468 EVT NVT = N->getValueType(0);
10469 SDValue V = N->getOperand(0);
10470
Michael Liao7a442c802012-10-17 20:48:33 +000010471 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10472 // Combine:
10473 // (extract_subvec (concat V1, V2, ...), i)
10474 // Into:
10475 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010476 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10477 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010478 if (V->getOperand(0).getValueType() != NVT)
10479 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010480 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10481 unsigned NumElems = NVT.getVectorNumElements();
10482 assert((Idx % NumElems) == 0 &&
10483 "IDX in concat is not a multiple of the result vector length.");
10484 return V->getOperand(Idx / NumElems);
10485 }
10486
Michael Liaobb05a1d2013-03-25 23:47:35 +000010487 // Skip bitcasting
10488 if (V->getOpcode() == ISD::BITCAST)
10489 V = V.getOperand(0);
10490
10491 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010492 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010493 // Handle only simple case where vector being inserted and vector
10494 // being extracted are of same type, and are half size of larger vectors.
10495 EVT BigVT = V->getOperand(0).getValueType();
10496 EVT SmallVT = V->getOperand(1).getValueType();
10497 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10498 return SDValue();
10499
10500 // Only handle cases where both indexes are constants with the same type.
10501 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10502 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10503
10504 if (InsIdx && ExtIdx &&
10505 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10506 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10507 // Combine:
10508 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10509 // Into:
10510 // indices are equal or bit offsets are equal => V1
10511 // otherwise => (extract_subvec V1, ExtIdx)
10512 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10513 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10514 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10515 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10516 DAG.getNode(ISD::BITCAST, dl,
10517 N->getOperand(0).getValueType(),
10518 V->getOperand(0)), N->getOperand(1));
10519 }
10520 }
10521
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010522 return SDValue();
10523}
10524
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010525// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10526static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10527 EVT VT = N->getValueType(0);
10528 unsigned NumElts = VT.getVectorNumElements();
10529
10530 SDValue N0 = N->getOperand(0);
10531 SDValue N1 = N->getOperand(1);
10532 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10533
10534 SmallVector<SDValue, 4> Ops;
10535 EVT ConcatVT = N0.getOperand(0).getValueType();
10536 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10537 unsigned NumConcats = NumElts / NumElemsPerConcat;
10538
10539 // Look at every vector that's inserted. We're looking for exact
10540 // subvector-sized copies from a concatenated vector
10541 for (unsigned I = 0; I != NumConcats; ++I) {
10542 // Make sure we're dealing with a copy.
10543 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010544 bool AllUndef = true, NoUndef = true;
10545 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10546 if (SVN->getMaskElt(J) >= 0)
10547 AllUndef = false;
10548 else
10549 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010550 }
10551
Hao Liubc601962013-05-13 02:07:05 +000010552 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010553 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10554 return SDValue();
10555
10556 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10557 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10558 return SDValue();
10559
10560 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10561 if (FirstElt < N0.getNumOperands())
10562 Ops.push_back(N0.getOperand(FirstElt));
10563 else
10564 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10565
10566 } else if (AllUndef) {
10567 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10568 } else { // Mixed with general masks and undefs, can't do optimization.
10569 return SDValue();
10570 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010571 }
10572
Craig Topper48d114b2014-04-26 18:35:24 +000010573 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010574}
10575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010576SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010577 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010578 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010579
Mon P Wang25f01062008-11-10 04:46:22 +000010580 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010581 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010582
Craig Topper5894fe42012-04-09 05:16:56 +000010583 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010584
Craig Topper279c77b2012-01-04 08:07:43 +000010585 // Canonicalize shuffle undef, undef -> undef
10586 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10587 return DAG.getUNDEF(VT);
10588
10589 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10590
10591 // Canonicalize shuffle v, v -> v, undef
10592 if (N0 == N1) {
10593 SmallVector<int, 8> NewMask;
10594 for (unsigned i = 0; i != NumElts; ++i) {
10595 int Idx = SVN->getMaskElt(i);
10596 if (Idx >= (int)NumElts) Idx -= NumElts;
10597 NewMask.push_back(Idx);
10598 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010599 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010600 &NewMask[0]);
10601 }
10602
10603 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10604 if (N0.getOpcode() == ISD::UNDEF) {
10605 SmallVector<int, 8> NewMask;
10606 for (unsigned i = 0; i != NumElts; ++i) {
10607 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010608 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010609 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010610 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010611 else
10612 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010613 }
10614 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010615 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010616 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010617 &NewMask[0]);
10618 }
10619
10620 // Remove references to rhs if it is undef
10621 if (N1.getOpcode() == ISD::UNDEF) {
10622 bool Changed = false;
10623 SmallVector<int, 8> NewMask;
10624 for (unsigned i = 0; i != NumElts; ++i) {
10625 int Idx = SVN->getMaskElt(i);
10626 if (Idx >= (int)NumElts) {
10627 Idx = -1;
10628 Changed = true;
10629 }
10630 NewMask.push_back(Idx);
10631 }
10632 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010633 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010634 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010635
Bob Wilsonf63da122010-10-28 17:06:14 +000010636 // If it is a splat, check if the argument vector is another splat or a
10637 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010638 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010639 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010640
Dan Gohmana8665142007-06-25 16:23:39 +000010641 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010642 // not the number of vector elements, look through it. Be careful not to
10643 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010644 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010645 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010646 if (ConvInput.getValueType().isVector() &&
10647 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010648 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010649 }
10650
Dan Gohmana8665142007-06-25 16:23:39 +000010651 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010652 assert(V->getNumOperands() == NumElts &&
10653 "BUILD_VECTOR has wrong number of operands");
10654 SDValue Base;
10655 bool AllSame = true;
10656 for (unsigned i = 0; i != NumElts; ++i) {
10657 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10658 Base = V->getOperand(i);
10659 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010660 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010661 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010662 // Splat of <u, u, u, u>, return <u, u, u, u>
10663 if (!Base.getNode())
10664 return N0;
10665 for (unsigned i = 0; i != NumElts; ++i) {
10666 if (V->getOperand(i) != Base) {
10667 AllSame = false;
10668 break;
10669 }
10670 }
10671 // Splat of <x, x, x, x>, return <x, x, x, x>
10672 if (AllSame)
10673 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010674 }
10675 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010676
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010677 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10678 Level < AfterLegalizeVectorOps &&
10679 (N1.getOpcode() == ISD::UNDEF ||
10680 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10681 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10682 SDValue V = partitionShuffleOfConcats(N, DAG);
10683
10684 if (V.getNode())
10685 return V;
10686 }
10687
Nadav Rotemb0783502012-04-01 19:31:22 +000010688 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010689 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010690 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10691 N1.getOpcode() == ISD::UNDEF) {
10692
Nadav Rotemb0783502012-04-01 19:31:22 +000010693 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10694
Craig Topper5894fe42012-04-09 05:16:56 +000010695 // The incoming shuffle must be of the same type as the result of the
10696 // current shuffle.
10697 assert(OtherSV->getOperand(0).getValueType() == VT &&
10698 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010699
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010700 SmallVector<int, 4> Mask;
10701 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010702 for (unsigned i = 0; i != NumElts; ++i) {
10703 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010704 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010705 // Next, this index comes from the first value, which is the incoming
10706 // shuffle. Adopt the incoming index.
10707 if (Idx >= 0)
10708 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010709 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010710 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010711
10712 bool CommuteOperands = false;
10713 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10714 // To be valid, the combine shuffle mask should only reference elements
10715 // from one of the two vectors in input to the inner shufflevector.
10716 bool IsValidMask = true;
10717 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10718 // See if the combined mask only reference undefs or elements coming
10719 // from the first shufflevector operand.
10720 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010721
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010722 if (!IsValidMask) {
10723 IsValidMask = true;
10724 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10725 // Check that all the elements come from the second shuffle operand.
10726 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10727 CommuteOperands = IsValidMask;
10728 }
10729
10730 // Early exit if the combined shuffle mask is not valid.
10731 if (!IsValidMask)
10732 return SDValue();
10733 }
10734
10735 // See if this pair of shuffles can be safely folded according to either
10736 // of the following rules:
10737 // shuffle(shuffle(x, y), undef) -> x
10738 // shuffle(shuffle(x, undef), undef) -> x
10739 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010740 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010741 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010742 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10743 // Skip Undefs.
10744 if (Mask[i] < 0)
10745 continue;
10746
10747 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010748 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010749 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010750
10751 if (IsIdentityMask) {
10752 if (CommuteOperands)
10753 // optimize shuffle(shuffle(x, y), undef) -> y.
10754 return OtherSV->getOperand(1);
10755
10756 // optimize shuffle(shuffle(x, undef), undef) -> x
10757 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010758 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010759 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010760
10761 // It may still be beneficial to combine the two shuffles if the
10762 // resulting shuffle is legal.
Andrea Di Biagio67d8b2e2014-07-13 21:02:14 +000010763 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010764 if (!CommuteOperands)
10765 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10766 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10767 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10768 &Mask[0]);
10769
10770 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10771 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010772 &Mask[0]);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010773 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010774 }
10775
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010776 // Canonicalize shuffles according to rules:
10777 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10778 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10779 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10780 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10781 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10782 TLI.isTypeLegal(VT)) {
10783 // The incoming shuffle must be of the same type as the result of the
10784 // current shuffle.
10785 assert(N1->getOperand(0).getValueType() == VT &&
10786 "Shuffle types don't match");
10787
10788 SDValue SV0 = N1->getOperand(0);
10789 SDValue SV1 = N1->getOperand(1);
10790 bool HasSameOp0 = N0 == SV0;
10791 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10792 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10793 // Commute the operands of this shuffle so that next rule
10794 // will trigger.
10795 return DAG.getCommutedVectorShuffle(*SVN);
10796 }
10797
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010798 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010799 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10800 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10801 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10802 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010803 // Don't try to fold shuffles with illegal type.
10804 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010805 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010806 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10807
10808 // The incoming shuffle must be of the same type as the result of the
10809 // current shuffle.
10810 assert(OtherSV->getOperand(0).getValueType() == VT &&
10811 "Shuffle types don't match");
10812
10813 SDValue SV0 = OtherSV->getOperand(0);
10814 SDValue SV1 = OtherSV->getOperand(1);
10815 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010816 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10817 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010818 // Early exit.
10819 return SDValue();
10820
10821 SmallVector<int, 4> Mask;
10822 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10823 // operand, and SV1 as the second operand.
10824 for (unsigned i = 0; i != NumElts; ++i) {
10825 int Idx = SVN->getMaskElt(i);
10826 if (Idx < 0) {
10827 // Propagate Undef.
10828 Mask.push_back(Idx);
10829 continue;
10830 }
10831
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010832 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010833 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010834 if (IsSV1Undef && Idx >= (int) NumElts)
10835 Idx = -1; // Propagate Undef.
10836 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010837 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10838
10839 Mask.push_back(Idx);
10840 }
10841
10842 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010843 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10844 if (IsSV1Undef)
10845 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10846 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10847 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010848 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010849 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010850 }
10851
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010852 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010853}
10854
Manman Ren413a6cb2014-01-31 01:10:35 +000010855SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10856 SDValue N0 = N->getOperand(0);
10857 SDValue N2 = N->getOperand(2);
10858
10859 // If the input vector is a concatenation, and the insert replaces
10860 // one of the halves, we can optimize into a single concat_vectors.
10861 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10862 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10863 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10864 EVT VT = N->getValueType(0);
10865
10866 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10867 // (concat_vectors Z, Y)
10868 if (InsIdx == 0)
10869 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10870 N->getOperand(1), N0.getOperand(1));
10871
10872 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10873 // (concat_vectors X, Z)
10874 if (InsIdx == VT.getVectorNumElements()/2)
10875 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10876 N0.getOperand(0), N->getOperand(1));
10877 }
10878
10879 return SDValue();
10880}
10881
Evan Chenga320abc2006-04-20 08:56:16 +000010882/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010883/// an AND to a vector_shuffle with the destination vector and a zero vector.
10884/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010885/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010886SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010887 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010888 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010889 SDValue LHS = N->getOperand(0);
10890 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010891 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010892 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010893 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010894 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010895 SmallVector<int, 8> Indices;
10896 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010897 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010898 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010899 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010900 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010901
10902 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010903 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010904 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010905 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010906 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010907 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010908 }
10909
10910 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010911 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010912 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010913 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010914
Dan Gohmana8665142007-06-25 16:23:39 +000010915 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010916 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010917 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010918 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010919 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010920 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010921 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010922 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010923 }
10924 }
Bill Wendling31b50992009-01-30 23:59:18 +000010925
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010926 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010927}
10928
Dan Gohmana8665142007-06-25 16:23:39 +000010929/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010930SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010931 assert(N->getValueType(0).isVector() &&
10932 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010933
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010934 SDValue LHS = N->getOperand(0);
10935 SDValue RHS = N->getOperand(1);
10936 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010937 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010938
Dan Gohmana8665142007-06-25 16:23:39 +000010939 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010940 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010941 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010942 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010943 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010944 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10945 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010946 return SDValue();
10947
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010948 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010949 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010950 SDValue LHSOp = LHS.getOperand(i);
10951 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010952
Evan Cheng64d28462006-05-31 06:08:35 +000010953 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010954 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10955 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010956 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010957 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010958 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010959 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010960 break;
10961 }
Bill Wendling31b50992009-01-30 23:59:18 +000010962
Bob Wilson54081442010-12-17 23:06:49 +000010963 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010964 EVT RVT = RHSOp.getValueType();
10965 if (RVT != VT) {
10966 // Integer BUILD_VECTOR operands may have types larger than the element
10967 // size (e.g., when the element type is not legal). Prior to type
10968 // legalization, the types may not match between the two BUILD_VECTORS.
10969 // Truncate one of the operands to make them match.
10970 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010971 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010972 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010973 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010974 VT = RVT;
10975 }
10976 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010977 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010978 LHSOp, RHSOp);
10979 if (FoldOp.getOpcode() != ISD::UNDEF &&
10980 FoldOp.getOpcode() != ISD::Constant &&
10981 FoldOp.getOpcode() != ISD::ConstantFP)
10982 break;
10983 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010984 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010985 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010986
Bob Wilson54081442010-12-17 23:06:49 +000010987 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010988 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000010989 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010990
Andrea Di Biagio446a5272014-05-30 23:17:53 +000010991 // Type legalization might introduce new shuffles in the DAG.
10992 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10993 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10994 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10995 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10996 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10997 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10998 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10999 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11000
11001 if (SVN0->getMask().equals(SVN1->getMask())) {
11002 EVT VT = N->getValueType(0);
11003 SDValue UndefVector = LHS.getOperand(1);
11004 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11005 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011006 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011007 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11008 &SVN0->getMask()[0]);
11009 }
11010 }
11011
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011012 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011013}
11014
Craig Topper82384612012-09-11 01:45:21 +000011015/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11016SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011017 assert(N->getValueType(0).isVector() &&
11018 "SimplifyVUnaryOp only works on vectors!");
11019
11020 SDValue N0 = N->getOperand(0);
11021
11022 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11023 return SDValue();
11024
11025 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11026 SmallVector<SDValue, 8> Ops;
11027 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11028 SDValue Op = N0.getOperand(i);
11029 if (Op.getOpcode() != ISD::UNDEF &&
11030 Op.getOpcode() != ISD::ConstantFP)
11031 break;
11032 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011033 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011034 if (FoldOp.getOpcode() != ISD::UNDEF &&
11035 FoldOp.getOpcode() != ISD::ConstantFP)
11036 break;
11037 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011038 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011039 }
11040
11041 if (Ops.size() != N0.getNumOperands())
11042 return SDValue();
11043
Craig Topper48d114b2014-04-26 18:35:24 +000011044 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011045}
11046
Andrew Trickef9de2a2013-05-25 02:42:55 +000011047SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011048 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011049 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011050
Bill Wendling31b50992009-01-30 23:59:18 +000011051 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011052 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011053
Nate Begeman2042aa52005-10-08 00:29:44 +000011054 // If we got a simplified select_cc node back from SimplifySelectCC, then
11055 // break it down into a new SETCC node, and a new SELECT node, and then return
11056 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011057 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011058 // Check to see if we got a select_cc back (to turn into setcc/select).
11059 // Otherwise, just return whatever node we got back, like fabs.
11060 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011061 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011062 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011063 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011064 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011065 AddToWorklist(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011066 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11067 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011068 }
Bill Wendling31b50992009-01-30 23:59:18 +000011069
Nate Begeman2042aa52005-10-08 00:29:44 +000011070 return SCC;
11071 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011072 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011073}
11074
Chris Lattner6c14c352005-10-18 06:04:22 +000011075/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11076/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000011077/// select. Callers of this should assume that TheSelect is deleted if this
11078/// returns true. As such, they should return the appropriate thing (e.g. the
11079/// node) back to the top-level of the DAG combiner loop to avoid it being
11080/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011081bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011082 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011083
Nadav Rotema49a02a2011-02-11 19:57:47 +000011084 // Cannot simplify select with vector condition
11085 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11086
Chris Lattner6c14c352005-10-18 06:04:22 +000011087 // If this is a select from two identical things, try to pull the operation
11088 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011089 if (LHS.getOpcode() != RHS.getOpcode() ||
11090 !LHS.hasOneUse() || !RHS.hasOneUse())
11091 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011092
Chris Lattner254c4452010-09-21 15:46:59 +000011093 // If this is a load and the token chain is identical, replace the select
11094 // of two loads with a load through a select of the address to load from.
11095 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11096 // constants have been dropped into the constant pool.
11097 if (LHS.getOpcode() == ISD::LOAD) {
11098 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11099 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011100
Chris Lattner254c4452010-09-21 15:46:59 +000011101 // Token chains must be identical.
11102 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011103 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011104 LLD->isVolatile() || RLD->isVolatile() ||
11105 // If this is an EXTLOAD, the VT's must match.
11106 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011107 // If this is an EXTLOAD, the kind of extension must match.
11108 (LLD->getExtensionType() != RLD->getExtensionType() &&
11109 // The only exception is if one of the extensions is anyext.
11110 LLD->getExtensionType() != ISD::EXTLOAD &&
11111 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011112 // FIXME: this discards src value information. This is
11113 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011114 // both potential memory locations. Since we are discarding
11115 // src value info, don't do the transformation if the memory
11116 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011117 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011118 RLD->getPointerInfo().getAddrSpace() != 0 ||
11119 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11120 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011121 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011122
Chris Lattnere3267522010-09-21 15:58:55 +000011123 // Check that the select condition doesn't reach either load. If so,
11124 // folding this will induce a cycle into the DAG. If not, this is safe to
11125 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011126 SDValue Addr;
11127 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011128 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11129 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11130 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11131 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011132 // The loads must not depend on one another.
11133 if (LLD->isPredecessorOf(RLD) ||
11134 RLD->isPredecessorOf(LLD))
11135 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011136 Addr = DAG.getSelect(SDLoc(TheSelect),
11137 LLD->getBasePtr().getValueType(),
11138 TheSelect->getOperand(0), LLD->getBasePtr(),
11139 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011140 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011141 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11142 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11143
11144 if ((LLD->hasAnyUseOfValue(1) &&
11145 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011146 (RLD->hasAnyUseOfValue(1) &&
11147 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011148 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011149
Andrew Trickef9de2a2013-05-25 02:42:55 +000011150 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011151 LLD->getBasePtr().getValueType(),
11152 TheSelect->getOperand(0),
11153 TheSelect->getOperand(1),
11154 LLD->getBasePtr(), RLD->getBasePtr(),
11155 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011156 }
11157
Chris Lattnere3267522010-09-21 15:58:55 +000011158 SDValue Load;
11159 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11160 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011161 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011162 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011163 LLD->getChain(), Addr, MachinePointerInfo(),
11164 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000011165 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011166 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011167 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11168 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011169 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011170 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011171 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011172 LLD->getChain(), Addr, MachinePointerInfo(),
11173 LLD->getMemoryVT(), LLD->isVolatile(),
11174 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000011175 }
Chris Lattnere3267522010-09-21 15:58:55 +000011176
11177 // Users of the select now use the result of the load.
11178 CombineTo(TheSelect, Load);
11179
11180 // Users of the old loads now use the new load's chain. We know the
11181 // old-load value is dead now.
11182 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11183 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11184 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011186
Chris Lattner6c14c352005-10-18 06:04:22 +000011187 return false;
11188}
11189
Chris Lattner43d63772009-03-11 05:08:08 +000011190/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11191/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011192SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011193 SDValue N2, SDValue N3,
11194 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011195 // (x ? y : y) -> y.
11196 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011197
Owen Anderson53aa7a92009-08-10 22:56:29 +000011198 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011199 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11200 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11201 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011202
11203 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011204 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011205 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011206 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011207 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011208
11209 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011210 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011211 return N2;
11212 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011213 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011214 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011215
Nate Begeman2042aa52005-10-08 00:29:44 +000011216 // Check to see if we can simplify the select into an fabs node
11217 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11218 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011219 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011220 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11221 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11222 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11223 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011224 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011225
Nate Begeman2042aa52005-10-08 00:29:44 +000011226 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11227 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11228 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11229 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011230 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011231 }
11232 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011233
Chris Lattner43d63772009-03-11 05:08:08 +000011234 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11235 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11236 // in it. This is a win when the constant is not otherwise available because
11237 // it replaces two constant pool loads with one. We only do this if the FP
11238 // type is known to be legal, because if it isn't, then we are before legalize
11239 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011240 // messing with soft float) and if the ConstantFP is not legal, because if
11241 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011242 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11243 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11244 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011245 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011246 TargetLowering::Legal &&
11247 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11248 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011249 // If both constants have multiple uses, then we won't need to do an
11250 // extra load, they are likely around in registers for other users.
11251 (TV->hasOneUse() || FV->hasOneUse())) {
11252 Constant *Elts[] = {
11253 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11254 const_cast<ConstantFP*>(TV->getConstantFPValue())
11255 };
Chris Lattner229907c2011-07-18 04:54:35 +000011256 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011257 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011258
Chris Lattner43d63772009-03-11 05:08:08 +000011259 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011260 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011261 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11262 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011263 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011264
11265 // Get the offsets to the 0 and 1 element of the array so that we can
11266 // select between them.
11267 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011268 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011269 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011270
Chris Lattner43d63772009-03-11 05:08:08 +000011271 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011272 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011273 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011274 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011275 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11276 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011277 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011278 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011279 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011280 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011281 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011282 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011283 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011284
11285 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011287
Nate Begeman2042aa52005-10-08 00:29:44 +000011288 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011289 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011290 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011291 (N1C->isNullValue() || // (a < 0) ? b : 0
11292 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011293 EVT XType = N0.getValueType();
11294 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011295 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011296 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011297 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011298 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11299 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011300 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011301 SDValue ShCt = DAG.getConstant(ShCtV,
11302 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011303 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011304 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011305 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011306
Duncan Sands11dd4242008-06-08 20:54:56 +000011307 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011308 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011309 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011310 }
Bill Wendling31b50992009-01-30 23:59:18 +000011311
11312 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011313 }
Bill Wendling31b50992009-01-30 23:59:18 +000011314
Andrew Trickef9de2a2013-05-25 02:42:55 +000011315 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011316 XType, N0,
11317 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011318 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011319 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011320
Duncan Sands11dd4242008-06-08 20:54:56 +000011321 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011322 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011323 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011324 }
Bill Wendling31b50992009-01-30 23:59:18 +000011325
11326 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011327 }
11328 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011329
Owen Anderson3231d132010-09-22 22:58:22 +000011330 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11331 // where y is has a single bit set.
11332 // A plaintext description would be, we can turn the SELECT_CC into an AND
11333 // when the condition can be materialized as an all-ones register. Any
11334 // single bit-test can be materialized as an all-ones register with
11335 // shift-left and shift-right-arith.
11336 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11337 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011338 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011339 N2C && N2C->isNullValue()) {
11340 SDValue AndLHS = N0->getOperand(0);
11341 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11342 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11343 // Shift the tested bit over the sign bit.
11344 APInt AndMask = ConstAndRHS->getAPIntValue();
11345 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011346 DAG.getConstant(AndMask.countLeadingZeros(),
11347 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011348 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011349
Owen Anderson3231d132010-09-22 22:58:22 +000011350 // Now arithmetic right shift it all the way over, so the result is either
11351 // all-ones, or zero.
11352 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011353 DAG.getConstant(AndMask.getBitWidth()-1,
11354 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011355 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011356
Owen Anderson3231d132010-09-22 22:58:22 +000011357 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11358 }
11359 }
11360
Nate Begeman6828ed92005-10-10 21:26:48 +000011361 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011362 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011363 TLI.getBooleanContents(N0.getValueType()) ==
11364 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011365
Chris Lattnera083ffc2007-04-11 06:50:51 +000011366 // If the caller doesn't want us to simplify this into a zext of a compare,
11367 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011368 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011369 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011370
Nate Begeman6828ed92005-10-10 21:26:48 +000011371 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011372 // NOTE: Don't create a SETCC if it's not legal on this target.
11373 if (!LegalOperations ||
11374 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011375 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011376 SDValue Temp, SCC;
11377 // cast from setcc result type to select result type
11378 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011379 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011380 N0, N1, CC);
11381 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011382 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011383 N2.getValueType());
11384 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011385 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011386 N2.getValueType(), SCC);
11387 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011388 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11389 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011390 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011391 }
11392
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011393 AddToWorklist(SCC.getNode());
11394 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011395
11396 if (N2C->getAPIntValue() == 1)
11397 return Temp;
11398
11399 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011400 return DAG.getNode(
11401 ISD::SHL, DL, N2.getValueType(), Temp,
11402 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11403 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011404 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011405 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011406
Nate Begeman2042aa52005-10-08 00:29:44 +000011407 // Check to see if this is the equivalent of setcc
11408 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11409 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011410 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011411 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011412 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011413 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11414 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011415 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011416 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011417 return Res;
11418 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011419
Bill Wendling31b50992009-01-30 23:59:18 +000011420 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011421 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011422 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011423 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011424 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011425 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011426 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011427 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011428 }
Bill Wendling31b50992009-01-30 23:59:18 +000011429 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011430 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011431 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011432 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011433 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011434 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011435 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011436 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011437 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011438 }
Bill Wendling31b50992009-01-30 23:59:18 +000011439 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011440 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011441 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011442 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011443 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011444 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011445 }
11446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011447
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011448 // Check to see if this is an integer abs.
11449 // select_cc setg[te] X, 0, X, -X ->
11450 // select_cc setgt X, -1, X, -X ->
11451 // select_cc setl[te] X, 0, -X, X ->
11452 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011453 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011454 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011455 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011456 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11457 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11458 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11459 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11460 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11461 (N1C->isOne() && CC == ISD::SETLT)) &&
11462 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11463 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11464
Owen Anderson53aa7a92009-08-10 22:56:29 +000011465 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011466 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011467 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011468 N0,
11469 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011470 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011471 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011472 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011473 AddToWorklist(Shift.getNode());
11474 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011475 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011476 }
11477 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011479 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011480}
11481
Evan Cheng92658d52007-02-08 22:13:59 +000011482/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011483SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011484 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011485 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011486 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011487 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011488 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011489}
11490
Chad Rosier17020f92014-07-23 14:57:52 +000011491/// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11492/// a DAG expression to select that will generate the same value by multiplying
11493/// by a magic number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011494/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011495SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011496 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11497 if (!C)
11498 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011499
11500 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011501 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011502 return SDValue();
11503
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011504 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011505 SDValue S =
11506 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011507
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011508 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011509 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011510 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011511}
11512
Chad Rosier17020f92014-07-23 14:57:52 +000011513/// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11514/// power of 2, return a DAG expression to select that will generate the same
11515/// value by right shifting.
11516SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11517 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11518 if (!C)
11519 return SDValue();
11520
11521 // Avoid division by zero.
11522 if (!C->getAPIntValue())
11523 return SDValue();
11524
11525 std::vector<SDNode *> Built;
11526 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11527
11528 for (SDNode *N : Built)
11529 AddToWorklist(N);
11530 return S;
11531}
11532
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011533/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011534/// return a DAG expression to select that will generate the same value by
11535/// multiplying by a magic number. See:
11536/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011537SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011538 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11539 if (!C)
11540 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011541
11542 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011543 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011544 return SDValue();
11545
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011546 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011547 SDValue S =
11548 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011549
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011550 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011551 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011552 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011553}
11554
Nate Begeman18150d52009-09-25 06:05:26 +000011555/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011556// to alias with anything but itself. Provides base object and offset as
11557// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011558static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011559 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011560 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011561 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011562
Jim Laskey0463e082006-10-07 23:37:56 +000011563 // If it's an adding a simple constant then integrate the offset.
11564 if (Base.getOpcode() == ISD::ADD) {
11565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11566 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011567 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011568 }
11569 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011570
Nate Begeman18150d52009-09-25 06:05:26 +000011571 // Return the underlying GlobalValue, and update the Offset. Return false
11572 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11573 // by multiple nodes with different offsets.
11574 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11575 GV = G->getGlobal();
11576 Offset += G->getOffset();
11577 return false;
11578 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011579
Nate Begeman18150d52009-09-25 06:05:26 +000011580 // Return the underlying Constant value, and update the Offset. Return false
11581 // for ConstantSDNodes since the same constant pool entry may be represented
11582 // by multiple nodes with different offsets.
11583 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011584 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11585 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011586 Offset += C->getOffset();
11587 return false;
11588 }
Jim Laskey0463e082006-10-07 23:37:56 +000011589 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011590 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011591}
11592
11593/// isAlias - Return true if there is any possibility that the two addresses
11594/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011595bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011596 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011597 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011598
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011599 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011600 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011601
Jim Laskey0463e082006-10-07 23:37:56 +000011602 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011603 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011604 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011605 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011606 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011607 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11608 Base1, Offset1, GV1, CV1);
11609 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11610 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011611
Nate Begeman18150d52009-09-25 06:05:26 +000011612 // If they have a same base address then check to see if they overlap.
11613 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011614 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11615 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011616
Owen Anderson272ff942010-09-20 20:39:59 +000011617 // It is possible for different frame indices to alias each other, mostly
11618 // when tail call optimization reuses return address slots for arguments.
11619 // To catch this case, look up the actual index of frame indices to compute
11620 // the real alias relationship.
11621 if (isFrameIndex1 && isFrameIndex2) {
11622 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11623 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11624 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011625 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11626 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011627 }
11628
Wesley Peck527da1b2010-11-23 03:31:01 +000011629 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011630 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011631 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11632 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011633
Nate Begeman879d8f12009-09-15 00:18:30 +000011634 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11635 // compared to the size and offset of the access, we may be able to prove they
11636 // do not alias. This check is conservative for now to catch cases created by
11637 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011638 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11639 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11640 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11641 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11642 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11643 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11644 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011645
Nate Begeman879d8f12009-09-15 00:18:30 +000011646 // There is no overlap between these relatively aligned accesses of similar
11647 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011648 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11649 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011650 return false;
11651 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011652
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011653 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11654 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011655#ifndef NDEBUG
11656 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11657 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11658 UseAA = false;
11659#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011660 if (UseAA &&
11661 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011662 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011663 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11664 Op1->getSrcValueOffset());
11665 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11666 Op0->getSrcValueOffset() - MinOffset;
11667 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11668 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011669 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011670 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11671 Overlap1,
11672 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11673 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11674 Overlap2,
11675 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011676 if (AAResult == AliasAnalysis::NoAlias)
11677 return false;
11678 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011679
11680 // Otherwise we have to assume they alias.
11681 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011682}
11683
Jim Laskey708d0db2006-10-04 16:53:27 +000011684/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11685/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011686void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011687 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011688 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011689 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011690
Jim Laskeyd07be232006-09-25 16:29:54 +000011691 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011692 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011693
Jim Laskey708d0db2006-10-04 16:53:27 +000011694 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011695 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011696 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011697
Jim Laskey6549d222006-10-05 15:07:25 +000011698 // Look at each chain and determine if it is an alias. If so, add it to the
11699 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011700 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011701 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011702 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011703 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011704
11705 // For TokenFactor nodes, look at each operand and only continue up the
11706 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011707 // find more and revert to original chain since the xform is unlikely to be
11708 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011709 //
11710 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011711 // chain we found before we hit a tokenfactor rather than the original
11712 // chain.
11713 if (Depth > 6 || Aliases.size() == 2) {
11714 Aliases.clear();
11715 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011716 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011717 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011718
Nate Begeman879d8f12009-09-15 00:18:30 +000011719 // Don't bother if we've been before.
11720 if (!Visited.insert(Chain.getNode()))
11721 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011722
Jim Laskey6549d222006-10-05 15:07:25 +000011723 switch (Chain.getOpcode()) {
11724 case ISD::EntryToken:
11725 // Entry token is ideal chain operand, but handled in FindBetterChain.
11726 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011727
Jim Laskey6549d222006-10-05 15:07:25 +000011728 case ISD::LOAD:
11729 case ISD::STORE: {
11730 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011731 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11732 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011733
Jim Laskey6549d222006-10-05 15:07:25 +000011734 // If chain is alias then stop here.
11735 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011736 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011737 Aliases.push_back(Chain);
11738 } else {
11739 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011740 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011741 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011742 }
Jim Laskey6549d222006-10-05 15:07:25 +000011743 break;
11744 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011745
Jim Laskey6549d222006-10-05 15:07:25 +000011746 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011747 // We have to check each of the operands of the token factor for "small"
11748 // token factors, so we queue them up. Adding the operands to the queue
11749 // (stack) in reverse order maintains the original order and increases the
11750 // likelihood that getNode will find a matching token factor (CSE.)
11751 if (Chain.getNumOperands() > 16) {
11752 Aliases.push_back(Chain);
11753 break;
11754 }
Jim Laskey6549d222006-10-05 15:07:25 +000011755 for (unsigned n = Chain.getNumOperands(); n;)
11756 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011757 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011758 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011759
Jim Laskey6549d222006-10-05 15:07:25 +000011760 default:
11761 // For all other instructions we will just have to take what we can get.
11762 Aliases.push_back(Chain);
11763 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011764 }
11765 }
Hal Finkel51a98382014-01-24 20:12:02 +000011766
11767 // We need to be careful here to also search for aliases through the
11768 // value operand of a store, etc. Consider the following situation:
11769 // Token1 = ...
11770 // L1 = load Token1, %52
11771 // S1 = store Token1, L1, %51
11772 // L2 = load Token1, %52+8
11773 // S2 = store Token1, L2, %51+8
11774 // Token2 = Token(S1, S2)
11775 // L3 = load Token2, %53
11776 // S3 = store Token2, L3, %52
11777 // L4 = load Token2, %53+8
11778 // S4 = store Token2, L4, %52+8
11779 // If we search for aliases of S3 (which loads address %52), and we look
11780 // only through the chain, then we'll miss the trivial dependence on L1
11781 // (which also loads from %52). We then might change all loads and
11782 // stores to use Token1 as their chain operand, which could result in
11783 // copying %53 into %52 before copying %52 into %51 (which should
11784 // happen first).
11785 //
11786 // The problem is, however, that searching for such data dependencies
11787 // can become expensive, and the cost is not directly related to the
11788 // chain depth. Instead, we'll rule out such configurations here by
11789 // insisting that we've visited all chain users (except for users
11790 // of the original chain, which is not necessary). When doing this,
11791 // we need to look through nodes we don't care about (otherwise, things
11792 // like register copies will interfere with trivial cases).
11793
11794 SmallVector<const SDNode *, 16> Worklist;
11795 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11796 IE = Visited.end(); I != IE; ++I)
11797 if (*I != OriginalChain.getNode())
11798 Worklist.push_back(*I);
11799
11800 while (!Worklist.empty()) {
11801 const SDNode *M = Worklist.pop_back_val();
11802
11803 // We have already visited M, and want to make sure we've visited any uses
11804 // of M that we care about. For uses that we've not visisted, and don't
11805 // care about, queue them to the worklist.
11806
11807 for (SDNode::use_iterator UI = M->use_begin(),
11808 UIE = M->use_end(); UI != UIE; ++UI)
11809 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11810 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11811 // We've not visited this use, and we care about it (it could have an
11812 // ordering dependency with the original node).
11813 Aliases.clear();
11814 Aliases.push_back(OriginalChain);
11815 return;
11816 }
11817
11818 // We've not visited this use, but we don't care about it. Mark it as
11819 // visited and enqueue it to the worklist.
11820 Worklist.push_back(*UI);
11821 }
11822 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011823}
11824
11825/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11826/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011827SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11828 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011829
Jim Laskey708d0db2006-10-04 16:53:27 +000011830 // Accumulate all the aliases to this node.
11831 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011832
Dan Gohman4298df62011-05-17 22:20:36 +000011833 // If no operands then chain to entry token.
11834 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011835 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011836
11837 // If a single operand then chain to it. We don't need to revisit it.
11838 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011839 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011840
Jim Laskey708d0db2006-10-04 16:53:27 +000011841 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011842 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011843}
11844
Nate Begeman21158fc2005-09-01 00:19:25 +000011845// SelectionDAG::Combine - This is the entry point for the file.
11846//
Bill Wendling084669a2009-04-29 00:15:41 +000011847void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011848 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011849 /// run - This is the main entry point to this class.
11850 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011851 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011852}