blob: eb8fab1362654ba347a063320231fcb3beb1dcbc [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines an instruction selector for the Hexagon target.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "Hexagon.h"
Krzysztof Parzyszeke8926432017-11-10 20:09:46 +000015#include "HexagonISelDAGToDAG.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000016#include "HexagonISelLowering.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000017#include "HexagonMachineFunctionInfo.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000018#include "HexagonTargetMachine.h"
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +000019#include "llvm/CodeGen/FunctionLoweringInfo.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000021#include "llvm/CodeGen/SelectionDAGISel.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000022#include "llvm/IR/Intrinsics.h"
Jyotsna Vermad9225242013-02-13 21:38:46 +000023#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000024#include "llvm/Support/Debug.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000025using namespace llvm;
26
Chandler Carruth84e68b22014-04-22 02:41:26 +000027#define DEBUG_TYPE "hexagon-isel"
28
Jyotsna Vermad9225242013-02-13 21:38:46 +000029static
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +000030cl::opt<bool>
31EnableAddressRebalancing("isel-rebalance-addr", cl::Hidden, cl::init(true),
32 cl::desc("Rebalance address calculation trees to improve "
33 "instruction selection"));
34
35// Rebalance only if this allows e.g. combining a GA with an offset or
36// factoring out a shift.
37static
38cl::opt<bool>
39RebalanceOnlyForOptimizations("rebalance-only-opt", cl::Hidden, cl::init(false),
40 cl::desc("Rebalance address tree only if this allows optimizations"));
41
42static
43cl::opt<bool>
44RebalanceOnlyImbalancedTrees("rebalance-only-imbal", cl::Hidden,
45 cl::init(false), cl::desc("Rebalance address tree only if it is imbalanced"));
46
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +000047static cl::opt<bool> CheckSingleUse("hexagon-isel-su", cl::Hidden,
48 cl::init(true), cl::desc("Enable checking of SDNode's single-use status"));
49
Tony Linthicum1213a7a2011-12-12 21:14:40 +000050//===----------------------------------------------------------------------===//
51// Instruction Selector Implementation
52//===----------------------------------------------------------------------===//
53
Krzysztof Parzyszeke8926432017-11-10 20:09:46 +000054#define GET_DAGISEL_BODY HexagonDAGToDAGISel
55#include "HexagonGenDAGISel.inc"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000056
57/// createHexagonISelDag - This pass converts a legalized DAG into a
58/// Hexagon-specific DAG, ready for instruction scheduling.
59///
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000060namespace llvm {
61FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
62 CodeGenOpt::Level OptLevel) {
Jyotsna Vermad9225242013-02-13 21:38:46 +000063 return new HexagonDAGToDAGISel(TM, OptLevel);
Tony Linthicum1213a7a2011-12-12 21:14:40 +000064}
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000065}
Tony Linthicum1213a7a2011-12-12 21:14:40 +000066
Benjamin Kramerbdc49562016-06-12 15:39:02 +000067void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000068 SDValue Chain = LD->getChain();
69 SDValue Base = LD->getBasePtr();
70 SDValue Offset = LD->getOffset();
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000071 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000072 EVT LoadedVT = LD->getMemoryVT();
73 unsigned Opcode = 0;
74
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +000075 // Check for zero extended loads. Treat any-extend loads as zero extended
76 // loads.
77 ISD::LoadExtType ExtType = LD->getExtensionType();
78 bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000079 bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +000080
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000081 assert(LoadedVT.isSimple());
82 switch (LoadedVT.getSimpleVT().SimpleTy) {
83 case MVT::i8:
84 if (IsZeroExt)
85 Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000086 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000087 Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
88 break;
89 case MVT::i16:
90 if (IsZeroExt)
91 Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000092 else
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000093 Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
94 break;
95 case MVT::i32:
96 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
97 break;
98 case MVT::i64:
99 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
100 break;
101 // 64B
102 case MVT::v64i8:
103 case MVT::v32i16:
104 case MVT::v16i32:
105 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000106 case MVT::v128i8:
107 case MVT::v64i16:
108 case MVT::v32i32:
109 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000110 if (isAlignedMemNode(LD)) {
111 if (LD->isNonTemporal())
112 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
113 else
114 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
115 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000116 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000117 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000118 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000119 default:
120 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000121 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000122
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000123 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
124 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
125 MemOp[0] = LD->getMemOperand();
126
127 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
128 -> MachineSDNode* {
129 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
130 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
131 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
132 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000133 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000134 if (ExtType == ISD::SEXTLOAD)
135 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
136 SDValue(N, 0));
137 return N;
138 };
139
140 // Loaded value Next address Chain
141 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
142 SDValue To[3];
143
144 EVT ValueVT = LD->getValueType(0);
145 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
146 // A load extending to i64 will actually produce i32, which will then
147 // need to be extended to i64.
148 assert(LoadedVT.getSizeInBits() <= 32);
149 ValueVT = MVT::i32;
150 }
151
152 if (IsValidInc) {
153 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
154 MVT::i32, MVT::Other, Base,
155 IncV, Chain);
156 L->setMemRefs(MemOp, MemOp+1);
157 To[1] = SDValue(L, 1); // Next address.
158 To[2] = SDValue(L, 2); // Chain.
159 // Handle special case for extension to i64.
160 if (LD->getValueType(0) == MVT::i64)
161 L = getExt64(L, dl);
162 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000163 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000164 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
165 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
166 Base, Zero, Chain);
167 L->setMemRefs(MemOp, MemOp+1);
168 To[2] = SDValue(L, 1); // Chain.
169 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
170 Base, IncV);
171 To[1] = SDValue(A, 0); // Next address.
172 // Handle special case for extension to i64.
173 if (LD->getValueType(0) == MVT::i64)
174 L = getExt64(L, dl);
175 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000176 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000177 ReplaceUses(From, To, 3);
178 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000179}
180
181
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000182MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
183 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
184 return nullptr;
185
186 SDLoc dl(IntN);
187 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
188
189 static std::map<unsigned,unsigned> LoadPciMap = {
190 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
191 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
192 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
193 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
194 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
195 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
196 };
197 auto FLC = LoadPciMap.find(IntNo);
198 if (FLC != LoadPciMap.end()) {
199 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
200 IntN->getOperand(4));
201 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
202 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
203 // Operands: { Base, Increment, Modifier, Chain }
204 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
205 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
206 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
207 { IntN->getOperand(2), I, SDValue(Mod,0), IntN->getOperand(0) });
208 return Res;
209 }
210
211 static std::map<unsigned,unsigned> LoadPbrMap = {
212 { Intrinsic::hexagon_brev_ldb, Hexagon::L2_loadrb_pbr },
213 { Intrinsic::hexagon_brev_ldub, Hexagon::L2_loadrub_pbr },
214 { Intrinsic::hexagon_brev_ldh, Hexagon::L2_loadrh_pbr },
215 { Intrinsic::hexagon_brev_lduh, Hexagon::L2_loadruh_pbr },
216 { Intrinsic::hexagon_brev_ldw, Hexagon::L2_loadri_pbr },
217 { Intrinsic::hexagon_brev_ldd, Hexagon::L2_loadrd_pbr },
218 };
219 auto FLB = LoadPbrMap.find(IntNo);
220 if (FLB != LoadPbrMap.end()) {
221 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
222 IntN->getOperand(4));
223 EVT ValTy = (IntNo == Intrinsic::hexagon_brev_ldd) ? MVT::i64 : MVT::i32;
224 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
225 // Operands: { Base, Modifier, Chain }
226 MachineSDNode *Res = CurDAG->getMachineNode(FLB->second, dl, RTys,
227 { IntN->getOperand(2), SDValue(Mod,0), IntN->getOperand(0) });
228 return Res;
229 }
230
231 return nullptr;
232}
233
234SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
235 SDNode *IntN) {
236 // The "LoadN" is just a machine load instruction. The intrinsic also
237 // involves storing it. Generate an appropriate store to the location
238 // given in the intrinsic's operand(3).
239 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
240 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
241 HexagonII::MemAccesSizeMask;
242 unsigned Size = 1U << (SizeBits-1);
243
244 SDLoc dl(IntN);
245 MachinePointerInfo PI;
246 SDValue TS;
247 SDValue Loc = IntN->getOperand(3);
248
249 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000250 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
251 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000252 else
Justin Lebar9c375812016-07-15 18:27:10 +0000253 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
254 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000255
256 SDNode *StoreN;
257 {
258 HandleSDNode Handle(TS);
259 SelectStore(TS.getNode());
260 StoreN = Handle.getValue().getNode();
261 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000262
263 // Load's results are { Loaded value, Updated pointer, Chain }
264 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
265 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
266 return StoreN;
267}
268
Justin Bognerec37a022016-05-12 21:46:18 +0000269bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000270 // The intrinsics for load circ/brev perform two operations:
271 // 1. Load a value V from the specified location, using the addressing
272 // mode corresponding to the intrinsic.
273 // 2. Store V into a specified location. This location is typically a
274 // local, temporary object.
275 // In many cases, the program using these intrinsics will immediately
276 // load V again from the local object. In those cases, when certain
277 // conditions are met, the last load can be removed.
278 // This function identifies and optimizes this pattern. If the pattern
279 // cannot be optimized, it returns nullptr, which will cause the load
280 // to be selected separately from the intrinsic (which will be handled
281 // in SelectIntrinsicWChain).
282
283 SDValue Ch = N->getOperand(0);
284 SDValue Loc = N->getOperand(1);
285
286 // Assume that the load and the intrinsic are connected directly with a
287 // chain:
288 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
289 // t2: i32,ch = load t1:1, Loc, ...
290 SDNode *C = Ch.getNode();
291
292 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000293 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000294
295 // The second load can only be eliminated if its extension type matches
296 // that of the load instruction corresponding to the intrinsic. The user
297 // can provide an address of an unsigned variable to store the result of
298 // a sign-extending intrinsic into (or the other way around).
299 ISD::LoadExtType IntExt;
300 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
301 case Intrinsic::hexagon_brev_ldub:
302 case Intrinsic::hexagon_brev_lduh:
303 case Intrinsic::hexagon_circ_ldub:
304 case Intrinsic::hexagon_circ_lduh:
305 IntExt = ISD::ZEXTLOAD;
306 break;
307 case Intrinsic::hexagon_brev_ldw:
308 case Intrinsic::hexagon_brev_ldd:
309 case Intrinsic::hexagon_circ_ldw:
310 case Intrinsic::hexagon_circ_ldd:
311 IntExt = ISD::NON_EXTLOAD;
312 break;
313 default:
314 IntExt = ISD::SEXTLOAD;
315 break;
316 }
317 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000318 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000319
320 // Make sure the target location for the loaded value in the load intrinsic
321 // is the location from which LD (or N) is loading.
322 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000323 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000324
325 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
326 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
327 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
328 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
329 ReplaceUses(F, T, array_lengthof(T));
330 // This transformation will leave the intrinsic dead. If it remains in
331 // the DAG, the selection code will see it again, but without the load,
332 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000333 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000334 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000335 }
336
Justin Bognerec37a022016-05-12 21:46:18 +0000337 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000338}
339
Justin Bognerec37a022016-05-12 21:46:18 +0000340void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000341 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000342 LoadSDNode *LD = cast<LoadSDNode>(N);
343 ISD::MemIndexedMode AM = LD->getAddressingMode();
344
345 // Handle indexed loads.
Justin Bognerec37a022016-05-12 21:46:18 +0000346 if (AM != ISD::UNINDEXED) {
347 SelectIndexedLoad(LD, dl);
348 return;
349 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000350
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000351 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000352 if (tryLoadOfLoadIntrinsic(LD))
353 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000354
Justin Bognerec37a022016-05-12 21:46:18 +0000355 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000356}
357
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000358void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000359 SDValue Chain = ST->getChain();
360 SDValue Base = ST->getBasePtr();
361 SDValue Offset = ST->getOffset();
362 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000363 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000364 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000365 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000366 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000367
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000368 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000369 unsigned Opcode = 0;
370
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000371 assert(StoredVT.isSimple());
372 switch (StoredVT.getSimpleVT().SimpleTy) {
373 case MVT::i8:
374 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
375 break;
376 case MVT::i16:
377 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
378 break;
379 case MVT::i32:
380 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
381 break;
382 case MVT::i64:
383 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
384 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000385 case MVT::v64i8:
386 case MVT::v32i16:
387 case MVT::v16i32:
388 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000389 case MVT::v128i8:
390 case MVT::v64i16:
391 case MVT::v32i32:
392 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000393 if (isAlignedMemNode(ST)) {
394 if (ST->isNonTemporal())
395 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
396 else
397 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
398 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000399 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000400 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000401 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000402 default:
403 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000404 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000405
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000406 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
407 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000408 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000409 dl, MVT::i32, Value);
410 }
411
412 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000413 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
414 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000415
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000416 // Next address Chain
417 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
418 SDValue To[2];
419
420 if (IsValidInc) {
421 // Build post increment store.
422 SDValue Ops[] = { Base, IncV, Value, Chain };
423 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
424 Ops);
425 S->setMemRefs(MemOp, MemOp + 1);
426 To[0] = SDValue(S, 0);
427 To[1] = SDValue(S, 1);
428 } else {
429 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
430 SDValue Ops[] = { Base, Zero, Value, Chain };
431 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
432 S->setMemRefs(MemOp, MemOp + 1);
433 To[1] = SDValue(S, 0);
434 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
435 Base, IncV);
436 To[0] = SDValue(A, 0);
437 }
438
439 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000440 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000441}
442
Justin Bognerec37a022016-05-12 21:46:18 +0000443void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000444 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000445 StoreSDNode *ST = cast<StoreSDNode>(N);
446 ISD::MemIndexedMode AM = ST->getAddressingMode();
447
448 // Handle indexed stores.
449 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000450 SelectIndexedStore(ST, dl);
451 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000452 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000453
Justin Bognerec37a022016-05-12 21:46:18 +0000454 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000455}
456
Justin Bognerec37a022016-05-12 21:46:18 +0000457void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000458 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000459 SDValue Shl_0 = N->getOperand(0);
460 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000461
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000462 auto Default = [this,N] () -> void { SelectCode(N); };
463
464 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
465 return Default();
466
467 // RHS is const.
468 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
469
470 if (Shl_0.getOpcode() == ISD::MUL) {
471 SDValue Mul_0 = Shl_0.getOperand(0); // Val
472 SDValue Mul_1 = Shl_0.getOperand(1); // Const
473 // RHS of mul is const.
474 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
475 int32_t ValConst = C->getSExtValue() << ShlConst;
476 if (isInt<9>(ValConst)) {
477 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
478 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
479 MVT::i32, Mul_0, Val);
480 ReplaceNode(N, Result);
481 return;
482 }
483 }
484 return Default();
485 }
486
487 if (Shl_0.getOpcode() == ISD::SUB) {
488 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
489 SDValue Sub_1 = Shl_0.getOperand(1); // Val
490 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
491 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
492 return Default();
493 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
494 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
495 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
496 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
497 if (isInt<9>(-ValConst)) {
498 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
499 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
500 MVT::i32, Shl2_0, Val);
501 ReplaceNode(N, Result);
502 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000503 }
504 }
505 }
506 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000507
508 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000509}
510
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000511//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000512// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000513//
Justin Bognerec37a022016-05-12 21:46:18 +0000514void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
515 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
516 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000517 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000518 return;
519 }
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000520
521 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
522 if (IntNo == Intrinsic::hexagon_V6_vgathermw ||
523 IntNo == Intrinsic::hexagon_V6_vgathermw_128B ||
524 IntNo == Intrinsic::hexagon_V6_vgathermh ||
525 IntNo == Intrinsic::hexagon_V6_vgathermh_128B ||
526 IntNo == Intrinsic::hexagon_V6_vgathermhw ||
527 IntNo == Intrinsic::hexagon_V6_vgathermhw_128B) {
528 SelectV65Gather(N);
529 return;
530 }
531 if (IntNo == Intrinsic::hexagon_V6_vgathermwq ||
532 IntNo == Intrinsic::hexagon_V6_vgathermwq_128B ||
533 IntNo == Intrinsic::hexagon_V6_vgathermhq ||
534 IntNo == Intrinsic::hexagon_V6_vgathermhq_128B ||
535 IntNo == Intrinsic::hexagon_V6_vgathermhwq ||
536 IntNo == Intrinsic::hexagon_V6_vgathermhwq_128B) {
537 SelectV65GatherPred(N);
538 return;
539 }
540
Justin Bognerec37a022016-05-12 21:46:18 +0000541 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000542}
543
Justin Bognerec37a022016-05-12 21:46:18 +0000544void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000545 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
546 unsigned Bits;
547 switch (IID) {
548 case Intrinsic::hexagon_S2_vsplatrb:
549 Bits = 8;
550 break;
551 case Intrinsic::hexagon_S2_vsplatrh:
552 Bits = 16;
553 break;
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000554 case Intrinsic::hexagon_V6_vaddcarry:
555 case Intrinsic::hexagon_V6_vaddcarry_128B:
556 case Intrinsic::hexagon_V6_vsubcarry:
557 case Intrinsic::hexagon_V6_vsubcarry_128B:
558 SelectHVXDualOutput(N);
559 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000560 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000561 SelectCode(N);
562 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000563 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000564
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000565 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000566 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000567 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000568 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000569 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000570 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000571 SelectCode(R.getNode());
572 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000573 }
Justin Bognerec37a022016-05-12 21:46:18 +0000574 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000575}
576
Sirish Pande69295b82012-05-10 20:20:25 +0000577//
578// Map floating point constant values.
579//
Justin Bognerec37a022016-05-12 21:46:18 +0000580void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000581 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000582 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000583 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000584 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000585 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
586 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000587 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000588 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000589 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000590 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
591 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000592 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000593 }
594
Justin Bognerec37a022016-05-12 21:46:18 +0000595 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000596}
597
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000598//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000599// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000600//
Justin Bognerec37a022016-05-12 21:46:18 +0000601void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000602 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000603 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
604 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
605 ? Hexagon::PS_true
606 : Hexagon::PS_false;
607 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
608 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000609 }
610
Justin Bognerec37a022016-05-12 21:46:18 +0000611 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000612}
613
614
Justin Bognerec37a022016-05-12 21:46:18 +0000615void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000616 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000617 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000618 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000619 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000620 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000621 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000622 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000623 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000624 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000625
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000626 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000627 // - the object is fixed, or
628 // - there are no objects with higher-than-default alignment, or
629 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000630 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000631 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000632 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000633 } else {
634 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
635 unsigned AR = HMFI.getStackAlignBaseVReg();
636 SDValue CH = CurDAG->getEntryNode();
637 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000638 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000639 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000640
Justin Bognerec37a022016-05-12 21:46:18 +0000641 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000642}
643
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000644
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000645void HexagonDAGToDAGISel::SelectBitcast(SDNode *N) {
646 EVT SVT = N->getOperand(0).getValueType();
647 EVT DVT = N->getValueType(0);
648 if (!SVT.isVector() || !DVT.isVector() ||
649 SVT.getVectorElementType() == MVT::i1 ||
650 DVT.getVectorElementType() == MVT::i1 ||
651 SVT.getSizeInBits() != DVT.getSizeInBits()) {
652 SelectCode(N);
653 return;
654 }
655
656 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N,0), N->getOperand(0));
657 CurDAG->RemoveDeadNode(N);
658}
659
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000660// Handle these nodes here to avoid having to write patterns for all
661// combinations of input/output types. In all cases, the resulting
662// instruction is the same.
663void HexagonDAGToDAGISel::SelectTypecast(SDNode *N) {
664 SDValue Op = N->getOperand(0);
665 MVT OpTy = Op.getValueType().getSimpleVT();
666 SDNode *T = CurDAG->MorphNodeTo(N, N->getOpcode(),
667 CurDAG->getVTList(OpTy), {Op});
668 ReplaceNode(T, Op.getNode());
669 CurDAG->RemoveDeadNode(T);
670}
671
672void HexagonDAGToDAGISel::SelectP2D(SDNode *N) {
673 MVT ResTy = N->getValueType(0).getSimpleVT();
674 SDNode *T = CurDAG->getMachineNode(Hexagon::C2_mask, SDLoc(N), ResTy,
675 N->getOperand(0));
676 ReplaceNode(N, T);
677}
678
679void HexagonDAGToDAGISel::SelectD2P(SDNode *N) {
680 const SDLoc &dl(N);
681 MVT ResTy = N->getValueType(0).getSimpleVT();
682 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
683 SDNode *T = CurDAG->getMachineNode(Hexagon::A4_vcmpbgtui, dl, ResTy,
684 N->getOperand(0), Zero);
685 ReplaceNode(N, T);
686}
687
688void HexagonDAGToDAGISel::SelectV2Q(SDNode *N) {
689 const SDLoc &dl(N);
690 MVT ResTy = N->getValueType(0).getSimpleVT();
691
692 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
693 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
694 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandvrt, dl, ResTy,
695 N->getOperand(0), SDValue(R,0));
696 ReplaceNode(N, T);
697}
698
699void HexagonDAGToDAGISel::SelectQ2V(SDNode *N) {
700 const SDLoc &dl(N);
701 MVT ResTy = N->getValueType(0).getSimpleVT();
702
703 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
704 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
705 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandqrt, dl, ResTy,
706 N->getOperand(0), SDValue(R,0));
707 ReplaceNode(N, T);
708}
709
Justin Bognerec37a022016-05-12 21:46:18 +0000710void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000711 if (N->isMachineOpcode())
712 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000713
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000714 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000715 case ISD::Constant: return SelectConstant(N);
716 case ISD::ConstantFP: return SelectConstantFP(N);
717 case ISD::FrameIndex: return SelectFrameIndex(N);
718 case ISD::BITCAST: return SelectBitcast(N);
719 case ISD::SHL: return SelectSHL(N);
720 case ISD::LOAD: return SelectLoad(N);
721 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000722 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
723 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000724 case HexagonISD::TYPECAST: return SelectTypecast(N);
725 case HexagonISD::P2D: return SelectP2D(N);
726 case HexagonISD::D2P: return SelectD2P(N);
727 case HexagonISD::Q2V: return SelectQ2V(N);
728 case HexagonISD::V2Q: return SelectV2Q(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000729 }
730
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000731 if (HST->useHVXOps()) {
732 switch (N->getOpcode()) {
733 case ISD::VECTOR_SHUFFLE: return SelectHvxShuffle(N);
734 case HexagonISD::VROR: return SelectHvxRor(N);
735 }
736 }
737
Justin Bognerec37a022016-05-12 21:46:18 +0000738 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000739}
740
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000741bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000742SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000743 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000744 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000745
Daniel Sanders60f1db02015-03-13 12:45:09 +0000746 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000747 default:
748 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000749 case InlineAsm::Constraint_i:
750 case InlineAsm::Constraint_o: // Offsetable.
751 case InlineAsm::Constraint_v: // Not offsetable.
752 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000753 if (SelectAddrFI(Inp, Res))
754 OutOps.push_back(Res);
755 else
756 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000757 break;
758 }
759
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000760 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000761 return false;
762}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000763
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000764
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000765static bool isMemOPCandidate(SDNode *I, SDNode *U) {
766 // I is an operand of U. Check if U is an arithmetic (binary) operation
767 // usable in a memop, where the other operand is a loaded value, and the
768 // result of U is stored in the same location.
769
770 if (!U->hasOneUse())
771 return false;
772 unsigned Opc = U->getOpcode();
773 switch (Opc) {
774 case ISD::ADD:
775 case ISD::SUB:
776 case ISD::AND:
777 case ISD::OR:
778 break;
779 default:
780 return false;
781 }
782
783 SDValue S0 = U->getOperand(0);
784 SDValue S1 = U->getOperand(1);
785 SDValue SY = (S0.getNode() == I) ? S1 : S0;
786
787 SDNode *UUse = *U->use_begin();
788 if (UUse->getNumValues() != 1)
789 return false;
790
791 // Check if one of the inputs to U is a load instruction and the output
792 // is used by a store instruction. If so and they also have the same
793 // base pointer, then don't preoprocess this node sequence as it
794 // can be matched to a memop.
795 SDNode *SYNode = SY.getNode();
796 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
797 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
798 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
799 if (LDBasePtr == STBasePtr)
800 return true;
801 }
802 return false;
803}
804
805
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000806// Transform: (or (select c x 0) z) -> (select c (or x z) z)
807// (or (select c 0 y) z) -> (select c z (or y z))
808void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000809 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000810
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000811 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000812 if (I->getOpcode() != ISD::OR)
813 continue;
814
815 auto IsZero = [] (const SDValue &V) -> bool {
816 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
817 return SC->isNullValue();
818 return false;
819 };
820 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
821 if (Op.getOpcode() != ISD::SELECT)
822 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000823 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000824 };
825
826 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
827 EVT VT = I->getValueType(0);
828 bool SelN0 = IsSelect0(N0);
829 SDValue SOp = SelN0 ? N0 : N1;
830 SDValue VOp = SelN0 ? N1 : N0;
831
832 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
833 SDValue SC = SOp.getOperand(0);
834 SDValue SX = SOp.getOperand(1);
835 SDValue SY = SOp.getOperand(2);
836 SDLoc DLS = SOp;
837 if (IsZero(SY)) {
838 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
839 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
840 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
841 } else if (IsZero(SX)) {
842 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
843 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
844 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
845 }
846 }
847 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000848}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000849
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000850// Transform: (store ch val (add x (add (shl y c) e)))
851// to: (store ch val (add x (shl (add y d) c))),
852// where e = (shl d c) for some integer d.
853// The purpose of this is to enable generation of loads/stores with
854// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
855// value c must be 0, 1 or 2.
856void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
857 SelectionDAG &DAG = *CurDAG;
858
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000859 for (auto I : Nodes) {
860 if (I->getOpcode() != ISD::STORE)
861 continue;
862
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000863 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000864 SDValue Off = I->getOperand(2);
865 // Off needs to match: (add x (add (shl y c) (shl d c))))
866 if (Off.getOpcode() != ISD::ADD)
867 continue;
868 // Off matched: (add x T0)
869 SDValue T0 = Off.getOperand(1);
870 // T0 needs to match: (add T1 T2):
871 if (T0.getOpcode() != ISD::ADD)
872 continue;
873 // T0 matched: (add T1 T2)
874 SDValue T1 = T0.getOperand(0);
875 SDValue T2 = T0.getOperand(1);
876 // T1 needs to match: (shl y c)
877 if (T1.getOpcode() != ISD::SHL)
878 continue;
879 SDValue C = T1.getOperand(1);
880 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
881 if (CN == nullptr)
882 continue;
883 unsigned CV = CN->getZExtValue();
884 if (CV > 2)
885 continue;
886 // T2 needs to match e, where e = (shl d c) for some d.
887 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
888 if (EN == nullptr)
889 continue;
890 unsigned EV = EN->getZExtValue();
891 if (EV % (1 << CV) != 0)
892 continue;
893 unsigned DV = EV / (1 << CV);
894
895 // Replace T0 with: (shl (add y d) c)
896 SDLoc DL = SDLoc(I);
897 EVT VT = T0.getValueType();
898 SDValue D = DAG.getConstant(DV, DL, VT);
899 // NewAdd = (add y d)
900 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
901 // NewShl = (shl NewAdd c)
902 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
903 ReplaceNode(T0.getNode(), NewShl.getNode());
904 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000905}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +0000906
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000907// Transform: (load ch (add x (and (srl y c) Mask)))
908// to: (load ch (add x (shl (srl y d) d-c)))
909// where
910// Mask = 00..0 111..1 0.0
911// | | +-- d-c 0s, and d-c is 0, 1 or 2.
912// | +-------- 1s
913// +-------------- at most c 0s
914// Motivating example:
915// DAG combiner optimizes (add x (shl (srl y 5) 2))
916// to (add x (and (srl y 3) 1FFFFFFC))
917// which results in a constant-extended and(##...,lsr). This transformation
918// undoes this simplification for cases where the shl can be folded into
919// an addressing mode.
920void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
921 SelectionDAG &DAG = *CurDAG;
922
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000923 for (SDNode *N : Nodes) {
924 unsigned Opc = N->getOpcode();
925 if (Opc != ISD::LOAD && Opc != ISD::STORE)
926 continue;
927 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
928 // Addr must match: (add x T0)
929 if (Addr.getOpcode() != ISD::ADD)
930 continue;
931 SDValue T0 = Addr.getOperand(1);
932 // T0 must match: (and T1 Mask)
933 if (T0.getOpcode() != ISD::AND)
934 continue;
935
936 // We have an AND.
937 //
938 // Check the first operand. It must be: (srl y c).
939 SDValue S = T0.getOperand(0);
940 if (S.getOpcode() != ISD::SRL)
941 continue;
942 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
943 if (SN == nullptr)
944 continue;
945 if (SN->getAPIntValue().getBitWidth() != 32)
946 continue;
947 uint32_t CV = SN->getZExtValue();
948
949 // Check the second operand: the supposed mask.
950 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
951 if (MN == nullptr)
952 continue;
953 if (MN->getAPIntValue().getBitWidth() != 32)
954 continue;
955 uint32_t Mask = MN->getZExtValue();
956 // Examine the mask.
957 uint32_t TZ = countTrailingZeros(Mask);
958 uint32_t M1 = countTrailingOnes(Mask >> TZ);
959 uint32_t LZ = countLeadingZeros(Mask);
960 // Trailing zeros + middle ones + leading zeros must equal the width.
961 if (TZ + M1 + LZ != 32)
962 continue;
963 // The number of trailing zeros will be encoded in the addressing mode.
964 if (TZ > 2)
965 continue;
966 // The number of leading zeros must be at most c.
967 if (LZ > CV)
968 continue;
969
970 // All looks good.
971 SDValue Y = S.getOperand(0);
972 EVT VT = Addr.getValueType();
973 SDLoc dl(S);
974 // TZ = D-C, so D = TZ+C.
975 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
976 SDValue DC = DAG.getConstant(TZ, dl, VT);
977 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
978 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
979 ReplaceNode(T0.getNode(), NewShl.getNode());
980 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000981}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +0000982
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000983// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
984// (op ... 1 ...))
985void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
986 SelectionDAG &DAG = *CurDAG;
987
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000988 for (SDNode *N : Nodes) {
989 unsigned Opc = N->getOpcode();
990 if (Opc != ISD::ZERO_EXTEND)
991 continue;
992 SDValue OpI1 = N->getOperand(0);
993 EVT OpVT = OpI1.getValueType();
994 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
995 continue;
996 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
997 SDNode *U = *I;
998 if (U->getNumValues() != 1)
999 continue;
1000 EVT UVT = U->getValueType(0);
1001 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1002 continue;
1003 if (isMemOPCandidate(N, U))
1004 continue;
1005
1006 // Potentially simplifiable operation.
1007 unsigned I1N = I.getOperandNo();
1008 SmallVector<SDValue,2> Ops(U->getNumOperands());
1009 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1010 Ops[i] = U->getOperand(i);
1011 EVT BVT = Ops[I1N].getValueType();
1012
1013 SDLoc dl(U);
1014 SDValue C0 = DAG.getConstant(0, dl, BVT);
1015 SDValue C1 = DAG.getConstant(1, dl, BVT);
1016 SDValue If0, If1;
1017
1018 if (isa<MachineSDNode>(U)) {
1019 unsigned UseOpc = U->getMachineOpcode();
1020 Ops[I1N] = C0;
1021 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1022 Ops[I1N] = C1;
1023 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1024 } else {
1025 unsigned UseOpc = U->getOpcode();
1026 Ops[I1N] = C0;
1027 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1028 Ops[I1N] = C1;
1029 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1030 }
1031 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1032 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1033 }
1034 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001035}
1036
1037void HexagonDAGToDAGISel::PreprocessISelDAG() {
1038 // Repack all nodes before calling each preprocessing function,
1039 // because each of them can modify the set of nodes.
1040 auto getNodes = [this] () -> std::vector<SDNode*> {
1041 std::vector<SDNode*> T;
1042 T.reserve(CurDAG->allnodes_size());
1043 for (SDNode &N : CurDAG->allnodes())
1044 T.push_back(&N);
1045 return T;
1046 };
1047
1048 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1049 // (or (select c 0 y) z) -> (select c z (or y z))
1050 ppSimplifyOrSelect0(getNodes());
1051
1052 // Transform: (store ch val (add x (add (shl y c) e)))
1053 // to: (store ch val (add x (shl (add y d) c))),
1054 // where e = (shl d c) for some integer d.
1055 // The purpose of this is to enable generation of loads/stores with
1056 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1057 // value c must be 0, 1 or 2.
1058 ppAddrReorderAddShl(getNodes());
1059
1060 // Transform: (load ch (add x (and (srl y c) Mask)))
1061 // to: (load ch (add x (shl (srl y d) d-c)))
1062 // where
1063 // Mask = 00..0 111..1 0.0
1064 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1065 // | +-------- 1s
1066 // +-------------- at most c 0s
1067 // Motivating example:
1068 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1069 // to (add x (and (srl y 3) 1FFFFFFC))
1070 // which results in a constant-extended and(##...,lsr). This transformation
1071 // undoes this simplification for cases where the shl can be folded into
1072 // an addressing mode.
1073 ppAddrRewriteAndSrl(getNodes());
1074
1075 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1076 // (op ... 1 ...))
1077 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001078
1079 DEBUG_WITH_TYPE("isel", {
1080 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1081 CurDAG->dump();
1082 });
1083
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001084 if (EnableAddressRebalancing) {
1085 rebalanceAddressTrees();
1086
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001087 DEBUG_WITH_TYPE("isel", {
1088 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001089 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001090 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001091 }
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001092}
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001093
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001094void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1095 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1096 auto &HFI = *HST.getFrameLowering();
1097 if (!HFI.needsAligna(*MF))
1098 return;
1099
1100 MachineFrameInfo &MFI = MF->getFrameInfo();
1101 MachineBasicBlock *EntryBB = &MF->front();
1102 unsigned AR = FuncInfo->CreateReg(MVT::i32);
1103 unsigned MaxA = MFI.getMaxAlignment();
1104 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
1105 .addImm(MaxA);
1106 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001107}
1108
1109// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001110bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001111 if (N.getOpcode() != ISD::FrameIndex)
1112 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001113 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001114 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001115 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001116 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001117 return false;
1118 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001119 return true;
1120}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001121
Colin LeMahieu987b0942015-02-04 20:38:01 +00001122inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001123 return SelectGlobalAddress(N, R, false, 0);
Colin LeMahieu987b0942015-02-04 20:38:01 +00001124}
1125
Colin LeMahieu51491352015-02-04 22:36:28 +00001126inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001127 return SelectGlobalAddress(N, R, true, 0);
1128}
1129
1130inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1131 return SelectAnyImmediate(N, R, 0);
1132}
1133
1134inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1135 return SelectAnyImmediate(N, R, 0);
1136}
1137inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1138 return SelectAnyImmediate(N, R, 1);
1139}
1140inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1141 return SelectAnyImmediate(N, R, 2);
1142}
1143inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1144 return SelectAnyImmediate(N, R, 3);
1145}
1146
1147inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1148 EVT T = N.getValueType();
1149 if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1150 return false;
1151 R = N;
1152 return true;
1153}
1154
1155bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1156 uint32_t LogAlign) {
1157 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001158 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001159 };
1160
1161 switch (N.getOpcode()) {
1162 case ISD::Constant: {
1163 if (N.getValueType() != MVT::i32)
1164 return false;
1165 int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1166 if (!IsAligned(V))
1167 return false;
1168 R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1169 return true;
1170 }
1171 case HexagonISD::JT:
1172 case HexagonISD::CP:
1173 // These are assumed to always be aligned at at least 8-byte boundary.
1174 if (LogAlign > 3)
1175 return false;
1176 R = N.getOperand(0);
1177 return true;
1178 case ISD::ExternalSymbol:
1179 // Symbols may be aligned at any boundary.
1180 if (LogAlign > 0)
1181 return false;
1182 R = N;
1183 return true;
1184 case ISD::BlockAddress:
1185 // Block address is always aligned at at least 4-byte boundary.
1186 if (LogAlign > 2 || !IsAligned(cast<BlockAddressSDNode>(N)->getOffset()))
1187 return false;
1188 R = N;
1189 return true;
1190 }
1191
1192 if (SelectGlobalAddress(N, R, false, LogAlign) ||
1193 SelectGlobalAddress(N, R, true, LogAlign))
1194 return true;
1195
1196 return false;
Colin LeMahieu51491352015-02-04 22:36:28 +00001197}
1198
Colin LeMahieu987b0942015-02-04 20:38:01 +00001199bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001200 bool UseGP, uint32_t LogAlign) {
1201 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001202 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001203 };
1204
Colin LeMahieu987b0942015-02-04 20:38:01 +00001205 switch (N.getOpcode()) {
1206 case ISD::ADD: {
1207 SDValue N0 = N.getOperand(0);
1208 SDValue N1 = N.getOperand(1);
1209 unsigned GAOpc = N0.getOpcode();
1210 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1211 return false;
1212 if (!UseGP && GAOpc != HexagonISD::CONST32)
1213 return false;
1214 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1215 SDValue Addr = N0.getOperand(0);
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001216 // For the purpose of alignment, sextvalue and zextvalue are the same.
1217 if (!IsAligned(Const->getZExtValue()))
1218 return false;
Colin LeMahieu987b0942015-02-04 20:38:01 +00001219 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1220 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1221 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1222 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1223 N.getValueType(), NewOff);
1224 return true;
1225 }
1226 }
1227 }
1228 break;
1229 }
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001230 case HexagonISD::CP:
1231 case HexagonISD::JT:
Colin LeMahieu987b0942015-02-04 20:38:01 +00001232 case HexagonISD::CONST32:
1233 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1234 // want in the instruction.
1235 if (!UseGP)
1236 R = N.getOperand(0);
1237 return !UseGP;
1238 case HexagonISD::CONST32_GP:
1239 if (UseGP)
1240 R = N.getOperand(0);
1241 return UseGP;
1242 default:
1243 return false;
1244 }
1245
1246 return false;
1247}
1248
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001249bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1250 // This (complex pattern) function is meant to detect a sign-extension
1251 // i32->i64 on a per-operand basis. This would allow writing single
1252 // patterns that would cover a number of combinations of different ways
1253 // a sign-extensions could be written. For example:
1254 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1255 // could match either one of these:
1256 // (mul (sext x) (sext_inreg y))
1257 // (mul (sext-load *p) (sext_inreg y))
1258 // (mul (sext_inreg x) (sext y))
1259 // etc.
1260 //
1261 // The returned value will have type i64 and its low word will
1262 // contain the value being extended. The high bits are not specified.
1263 // The returned type is i64 because the original type of N was i64,
1264 // but the users of this function should only use the low-word of the
1265 // result, e.g.
1266 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1267
1268 if (N.getValueType() != MVT::i64)
1269 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001270 unsigned Opc = N.getOpcode();
1271 switch (Opc) {
1272 case ISD::SIGN_EXTEND:
1273 case ISD::SIGN_EXTEND_INREG: {
1274 // sext_inreg has the source type as a separate operand.
1275 EVT T = Opc == ISD::SIGN_EXTEND
1276 ? N.getOperand(0).getValueType()
1277 : cast<VTSDNode>(N.getOperand(1))->getVT();
1278 if (T.getSizeInBits() != 32)
1279 return false;
1280 R = N.getOperand(0);
1281 break;
1282 }
1283 case ISD::LOAD: {
1284 LoadSDNode *L = cast<LoadSDNode>(N);
1285 if (L->getExtensionType() != ISD::SEXTLOAD)
1286 return false;
1287 // All extending loads extend to i32, so even if the value in
1288 // memory is shorter than 32 bits, it will be i32 after the load.
1289 if (L->getMemoryVT().getSizeInBits() > 32)
1290 return false;
1291 R = N;
1292 break;
1293 }
1294 default:
1295 return false;
1296 }
1297 EVT RT = R.getValueType();
1298 if (RT == MVT::i64)
1299 return true;
1300 assert(RT == MVT::i32);
1301 // This is only to produce a value of type i64. Do not rely on the
1302 // high bits produced by this.
1303 const SDLoc &dl(N);
1304 SDValue Ops[] = {
1305 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1306 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1307 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1308 };
1309 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1310 MVT::i64, Ops);
1311 R = SDValue(T, 0);
1312 return true;
1313}
1314
1315bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1316 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001317 unsigned Opc = Val.getOpcode();
1318 switch (Opc) {
1319 case ISD::SIGN_EXTEND:
1320 case ISD::ZERO_EXTEND:
1321 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001322 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001323 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001324 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001325 Src = Op0;
1326 return true;
1327 }
1328 break;
1329 }
1330 case ISD::SIGN_EXTEND_INREG:
1331 case ISD::AssertSext:
1332 case ISD::AssertZext:
1333 if (Val.getOperand(0).getValueType().isInteger()) {
1334 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001335 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001336 Src = Val.getOperand(0);
1337 return true;
1338 }
1339 }
1340 break;
1341 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001342 // Check if this is an AND with NumBits of lower bits set to 1.
1343 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001345 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001346 Src = Val.getOperand(1);
1347 return true;
1348 }
1349 }
1350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001351 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001352 Src = Val.getOperand(0);
1353 return true;
1354 }
1355 }
1356 break;
1357 }
1358 case ISD::OR:
1359 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001360 // OR/XOR with the lower NumBits bits set to 0.
1361 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001363 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001364 Src = Val.getOperand(1);
1365 return true;
1366 }
1367 }
1368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001369 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001370 Src = Val.getOperand(0);
1371 return true;
1372 }
1373 }
1374 }
1375 default:
1376 break;
1377 }
1378 return false;
1379}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001380
1381bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1382 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1383}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001384
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001385bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1386 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1387 switch (N->getMemoryVT().getStoreSize()) {
1388 case 1:
1389 return StackSize <= 56; // 1*2^6 - 8
1390 case 2:
1391 return StackSize <= 120; // 2*2^6 - 8
1392 case 4:
1393 return StackSize <= 248; // 4*2^6 - 8
1394 default:
1395 return false;
1396 }
1397}
1398
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001399// Return true when the given node fits in a positive half word.
1400bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1401 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1402 int64_t V = CN->getSExtValue();
1403 return V > 0 && isInt<16>(V);
1404 }
1405 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1406 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1407 return VN->getVT().getSizeInBits() <= 16;
1408 }
1409 return false;
1410}
1411
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001412bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1413 return !CheckSingleUse || N->hasOneUse();
1414}
1415
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001416////////////////////////////////////////////////////////////////////////////////
1417// Rebalancing of address calculation trees
1418
1419static bool isOpcodeHandled(const SDNode *N) {
1420 switch (N->getOpcode()) {
1421 case ISD::ADD:
1422 case ISD::MUL:
1423 return true;
1424 case ISD::SHL:
1425 // We only handle constant shifts because these can be easily flattened
1426 // into multiplications by 2^Op1.
1427 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1428 default:
1429 return false;
1430 }
1431}
1432
1433/// \brief Return the weight of an SDNode
1434int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1435 if (!isOpcodeHandled(N))
1436 return 1;
1437 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1438 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1439 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1440 return RootWeights[N];
1441}
1442
1443int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1444 if (!isOpcodeHandled(N))
1445 return 0;
1446 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1447 "Cannot query height of unvisited/RAUW'd node!");
1448 return RootHeights[N];
1449}
1450
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001451namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001452struct WeightedLeaf {
1453 SDValue Value;
1454 int Weight;
1455 int InsertionOrder;
1456
1457 WeightedLeaf() : Value(SDValue()) { }
1458
1459 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1460 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1461 assert(Weight >= 0 && "Weight must be >= 0");
1462 }
1463
1464 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1465 assert(A.Value.getNode() && B.Value.getNode());
1466 return A.Weight == B.Weight ?
1467 (A.InsertionOrder > B.InsertionOrder) :
1468 (A.Weight > B.Weight);
1469 }
1470};
1471
1472/// A specialized priority queue for WeigthedLeaves. It automatically folds
1473/// constants and allows removal of non-top elements while maintaining the
1474/// priority order.
1475class LeafPrioQueue {
1476 SmallVector<WeightedLeaf, 8> Q;
1477 bool HaveConst;
1478 WeightedLeaf ConstElt;
1479 unsigned Opcode;
1480
1481public:
1482 bool empty() {
1483 return (!HaveConst && Q.empty());
1484 }
1485
1486 size_t size() {
1487 return Q.size() + HaveConst;
1488 }
1489
1490 bool hasConst() {
1491 return HaveConst;
1492 }
1493
1494 const WeightedLeaf &top() {
1495 if (HaveConst)
1496 return ConstElt;
1497 return Q.front();
1498 }
1499
1500 WeightedLeaf pop() {
1501 if (HaveConst) {
1502 HaveConst = false;
1503 return ConstElt;
1504 }
1505 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1506 return Q.pop_back_val();
1507 }
1508
1509 void push(WeightedLeaf L, bool SeparateConst=true) {
1510 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1511 if (Opcode == ISD::MUL &&
1512 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1513 return;
1514 if (Opcode == ISD::ADD &&
1515 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1516 return;
1517
1518 HaveConst = true;
1519 ConstElt = L;
1520 } else {
1521 Q.push_back(L);
1522 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1523 }
1524 }
1525
1526 /// Push L to the bottom of the queue regardless of its weight. If L is
1527 /// constant, it will not be folded with other constants in the queue.
1528 void pushToBottom(WeightedLeaf L) {
1529 L.Weight = 1000;
1530 push(L, false);
1531 }
1532
1533 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1534 /// lowest weight and remove it from the queue.
1535 WeightedLeaf findSHL(uint64_t MaxAmount);
1536
1537 WeightedLeaf findMULbyConst();
1538
1539 LeafPrioQueue(unsigned Opcode) :
1540 HaveConst(false), Opcode(Opcode) { }
1541};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001542} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001543
1544WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1545 int ResultPos;
1546 WeightedLeaf Result;
1547
1548 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1549 const WeightedLeaf &L = Q[Pos];
1550 const SDValue &Val = L.Value;
1551 if (Val.getOpcode() != ISD::SHL ||
1552 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1553 Val.getConstantOperandVal(1) > MaxAmount)
1554 continue;
1555 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1556 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1557 {
1558 Result = L;
1559 ResultPos = Pos;
1560 }
1561 }
1562
1563 if (Result.Value.getNode()) {
1564 Q.erase(&Q[ResultPos]);
1565 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1566 }
1567
1568 return Result;
1569}
1570
1571WeightedLeaf LeafPrioQueue::findMULbyConst() {
1572 int ResultPos;
1573 WeightedLeaf Result;
1574
1575 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1576 const WeightedLeaf &L = Q[Pos];
1577 const SDValue &Val = L.Value;
1578 if (Val.getOpcode() != ISD::MUL ||
1579 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1580 Val.getConstantOperandVal(1) > 127)
1581 continue;
1582 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1583 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1584 {
1585 Result = L;
1586 ResultPos = Pos;
1587 }
1588 }
1589
1590 if (Result.Value.getNode()) {
1591 Q.erase(&Q[ResultPos]);
1592 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1593 }
1594
1595 return Result;
1596}
1597
1598SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001599 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001600 return CurDAG->getConstant(MulFactor, SDLoc(N),
1601 N->getOperand(1).getValueType());
1602}
1603
1604/// @returns the value x for which 2^x is a factor of Val
1605static unsigned getPowerOf2Factor(SDValue Val) {
1606 if (Val.getOpcode() == ISD::MUL) {
1607 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001608 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001609 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1610 if (!C)
1611 continue;
1612 const APInt &CInt = C->getAPIntValue();
1613 if (CInt.getBoolValue())
1614 MaxFactor = CInt.countTrailingZeros();
1615 }
1616 return MaxFactor;
1617 }
1618 if (Val.getOpcode() == ISD::SHL) {
1619 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1620 return 0;
1621 return (unsigned) Val.getConstantOperandVal(1);
1622 }
1623
1624 return 0;
1625}
1626
1627/// @returns true if V>>Amount will eliminate V's operation on its child
1628static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1629 if (V.getOpcode() == ISD::MUL) {
1630 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001631 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001632 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001633 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001634 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1635 return (NewConst == 1);
1636 }
1637 } else if (V.getOpcode() == ISD::SHL) {
1638 return (Amount == V.getConstantOperandVal(1));
1639 }
1640
1641 return false;
1642}
1643
1644SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1645 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1646 if (V.getOpcode() == ISD::MUL) {
1647 for (int i=0; i < 2; ++i) {
1648 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1649 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1650 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1651 if (NewConst == 1)
1652 return Ops[!i];
1653 Ops[i] = CurDAG->getConstant(NewConst,
1654 SDLoc(V), V.getValueType());
1655 break;
1656 }
1657 }
1658 } else if (V.getOpcode() == ISD::SHL) {
1659 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1660 if (ShiftAmount == Power)
1661 return Ops[0];
1662 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1663 SDLoc(V), V.getValueType());
1664 }
1665
1666 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1667}
1668
1669static bool isTargetConstant(const SDValue &V) {
1670 return V.getOpcode() == HexagonISD::CONST32 ||
1671 V.getOpcode() == HexagonISD::CONST32_GP;
1672}
1673
1674unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1675 if (GAUsesInFunction.count(V))
1676 return GAUsesInFunction[V];
1677
1678 unsigned Result = 0;
Matthias Braunf1caa282017-12-15 22:22:58 +00001679 const Function &CurF = CurDAG->getMachineFunction().getFunction();
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001680 for (const User *U : V->users()) {
1681 if (isa<Instruction>(U) &&
Matthias Braunf1caa282017-12-15 22:22:58 +00001682 cast<Instruction>(U)->getParent()->getParent() == &CurF)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001683 ++Result;
1684 }
1685
1686 GAUsesInFunction[V] = Result;
1687
1688 return Result;
1689}
1690
1691/// Note - After calling this, N may be dead. It may have been replaced by a
1692/// new node, so always use the returned value in place of N.
1693///
1694/// @returns The SDValue taking the place of N (which could be N if it is
1695/// unchanged)
1696SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1697 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1698 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1699 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1700
1701 // Return early if this node was already visited
1702 if (RootWeights[N] != -1)
1703 return SDValue(N, 0);
1704
1705 assert(isOpcodeHandled(N));
1706
1707 SDValue Op0 = N->getOperand(0);
1708 SDValue Op1 = N->getOperand(1);
1709
1710 // Return early if the operands will remain unchanged or are all roots
1711 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1712 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1713 SDNode *Op0N = Op0.getNode();
1714 int Weight;
1715 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1716 Weight = getWeight(balanceSubTree(Op0N).getNode());
1717 // Weight = calculateWeight(Op0N);
1718 } else
1719 Weight = getWeight(Op0N);
1720
1721 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1722 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1723 Weight += getWeight(balanceSubTree(Op1N).getNode());
1724 // Weight += calculateWeight(Op1N);
1725 } else
1726 Weight += getWeight(Op1N);
1727
1728 RootWeights[N] = Weight;
1729 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1730 getHeight(N->getOperand(1).getNode())) + 1;
1731
1732 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1733 << " Height=" << RootHeights[N] << "): ");
1734 DEBUG(N->dump());
1735
1736 return SDValue(N, 0);
1737 }
1738
1739 DEBUG(dbgs() << "** Balancing root node: ");
1740 DEBUG(N->dump());
1741
1742 unsigned NOpcode = N->getOpcode();
1743
1744 LeafPrioQueue Leaves(NOpcode);
1745 SmallVector<SDValue, 4> Worklist;
1746 Worklist.push_back(SDValue(N, 0));
1747
1748 // SHL nodes will be converted to MUL nodes
1749 if (NOpcode == ISD::SHL)
1750 NOpcode = ISD::MUL;
1751
1752 bool CanFactorize = false;
1753 WeightedLeaf Mul1, Mul2;
1754 unsigned MaxPowerOf2 = 0;
1755 WeightedLeaf GA;
1756
1757 // Do not try to factor out a shift if there is already a shift at the tip of
1758 // the tree.
1759 bool HaveTopLevelShift = false;
1760 if (TopLevel &&
1761 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1762 Op0.getConstantOperandVal(1) < 4) ||
1763 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1764 Op1.getConstantOperandVal(1) < 4)))
1765 HaveTopLevelShift = true;
1766
1767 // Flatten the subtree into an ordered list of leaves; at the same time
1768 // determine whether the tree is already balanced.
1769 int InsertionOrder = 0;
1770 SmallDenseMap<SDValue, int> NodeHeights;
1771 bool Imbalanced = false;
1772 int CurrentWeight = 0;
1773 while (!Worklist.empty()) {
1774 SDValue Child = Worklist.pop_back_val();
1775
1776 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1777 // CASE 1: Child is a root note
1778
1779 int Weight = RootWeights[Child.getNode()];
1780 if (Weight == -1) {
1781 Child = balanceSubTree(Child.getNode());
1782 // calculateWeight(Child.getNode());
1783 Weight = getWeight(Child.getNode());
1784 } else if (Weight == -2) {
1785 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1786 // made. Our worklist isn't up to date anymore.
1787 // Restart the whole process.
1788 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1789 return balanceSubTree(N, TopLevel);
1790 }
1791
1792 NodeHeights[Child] = 1;
1793 CurrentWeight += Weight;
1794
1795 unsigned PowerOf2;
1796 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1797 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1798 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1799 // Try to identify two factorizable MUL/SHL children greedily. Leave
1800 // them out of the priority queue for now so we can deal with them
1801 // after.
1802 if (!Mul1.Value.getNode()) {
1803 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1804 MaxPowerOf2 = PowerOf2;
1805 } else {
1806 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1807 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1808
1809 // Our addressing modes can only shift by a maximum of 3
1810 if (MaxPowerOf2 > 3)
1811 MaxPowerOf2 = 3;
1812
1813 CanFactorize = true;
1814 }
1815 } else
1816 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1817 } else if (!isOpcodeHandled(Child.getNode())) {
1818 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1819 int Weight = getWeight(Child.getNode());
1820
1821 NodeHeights[Child] = getHeight(Child.getNode());
1822 CurrentWeight += Weight;
1823
1824 if (isTargetConstant(Child) && !GA.Value.getNode())
1825 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1826 else
1827 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1828 } else {
1829 // CASE 3: Child is a subtree of same opcode
1830 // Visit children first, then flatten.
1831 unsigned ChildOpcode = Child.getOpcode();
1832 assert(ChildOpcode == NOpcode ||
1833 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1834
1835 // Convert SHL to MUL
1836 SDValue Op1;
1837 if (ChildOpcode == ISD::SHL)
1838 Op1 = getMultiplierForSHL(Child.getNode());
1839 else
1840 Op1 = Child->getOperand(1);
1841
1842 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
1843 assert(!NodeHeights.count(Child) && "Parent visited before children?");
1844 // Visit children first, then re-visit this node
1845 Worklist.push_back(Child);
1846 Worklist.push_back(Op1);
1847 Worklist.push_back(Child->getOperand(0));
1848 } else {
1849 // Back at this node after visiting the children
1850 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
1851 Imbalanced = true;
1852
1853 NodeHeights[Child] = std::max(NodeHeights[Op1],
1854 NodeHeights[Child->getOperand(0)]) + 1;
1855 }
1856 }
1857 }
1858
1859 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
1860 << " weight=" << CurrentWeight << " imbalanced="
1861 << Imbalanced << "\n");
1862
1863 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
1864 // This factors out a shift in order to match memw(a<<Y+b).
1865 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
1866 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
1867 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
1868 int Weight = Mul1.Weight + Mul2.Weight;
1869 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
1870 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
1871 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
1872 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
1873 Mul1Factored, Mul2Factored);
1874 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
1875 Mul1.Value.getValueType());
1876 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
1877 Sum, Const);
1878 NodeHeights[New] = Height;
1879 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
1880 } else if (Mul1.Value.getNode()) {
1881 // We failed to factorize two MULs, so now the Muls are left outside the
1882 // queue... add them back.
1883 Leaves.push(Mul1);
1884 if (Mul2.Value.getNode())
1885 Leaves.push(Mul2);
1886 CanFactorize = false;
1887 }
1888
1889 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
1890 // and the root node itself is not used more than twice. This reduces the
1891 // amount of additional constant extenders introduced by this optimization.
1892 bool CombinedGA = false;
1893 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
1894 GA.Value.hasOneUse() && N->use_size() < 3) {
1895 GlobalAddressSDNode *GANode =
1896 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
1897 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
1898
1899 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
1900 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
1901 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
1902 << "): ");
1903 DEBUG(GANode->dump());
1904
1905 SDValue NewTGA =
1906 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
1907 GANode->getValueType(0),
1908 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
1909 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
1910 GA.Value.getValueType(), NewTGA);
1911 GA.Weight += Leaves.top().Weight;
1912
1913 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
1914 CombinedGA = true;
1915
1916 Leaves.pop(); // Remove the offset constant from the queue
1917 }
1918 }
1919
1920 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
1921 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
1922 RootWeights[N] = CurrentWeight;
1923 RootHeights[N] = NodeHeights[SDValue(N, 0)];
1924
1925 return SDValue(N, 0);
1926 }
1927
1928 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
1929 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
1930 WeightedLeaf SHL = Leaves.findSHL(31);
1931 if (SHL.Value.getNode()) {
1932 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
1933 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
1934 GA.Value.getValueType(),
1935 GA.Value, SHL.Value);
1936 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
1937 NodeHeights[GA.Value] = Height;
1938 }
1939 }
1940
1941 if (GA.Value.getNode())
1942 Leaves.push(GA);
1943
1944 // If this is the top level and we haven't factored out a shift, we should try
1945 // to move a constant to the bottom to match addressing modes like memw(rX+C)
1946 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
1947 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
1948 Leaves.pushToBottom(Leaves.pop());
1949 }
1950
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001951 const DataLayout &DL = CurDAG->getDataLayout();
1952 const TargetLowering &TLI = *getTargetLowering();
1953
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001954 // Rebuild the tree using Huffman's algorithm
1955 while (Leaves.size() > 1) {
1956 WeightedLeaf L0 = Leaves.pop();
1957
1958 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
1959 // otherwise just get the next leaf
1960 WeightedLeaf L1 = Leaves.findMULbyConst();
1961 if (!L1.Value.getNode())
1962 L1 = Leaves.pop();
1963
1964 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
1965
1966 SDValue V0 = L0.Value;
1967 int V0Weight = L0.Weight;
1968 SDValue V1 = L1.Value;
1969 int V1Weight = L1.Weight;
1970
1971 // Make sure that none of these nodes have been RAUW'd
1972 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
1973 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
1974 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1975 return balanceSubTree(N, TopLevel);
1976 }
1977
1978 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
1979 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
1980 EVT VT = N->getValueType(0);
1981 SDValue NewNode;
1982
1983 if (V0C && !V1C) {
1984 std::swap(V0, V1);
1985 std::swap(V0C, V1C);
1986 }
1987
1988 // Calculate height of this node
1989 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
1990 "Children must have been visited before re-combining them!");
1991 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
1992
1993 // Rebuild this node (and restore SHL from MUL if needed)
1994 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
1995 NewNode = CurDAG->getNode(
1996 ISD::SHL, SDLoc(V0), VT, V0,
1997 CurDAG->getConstant(
1998 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001999 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002000 else
2001 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2002
2003 NodeHeights[NewNode] = Height;
2004
2005 int Weight = V0Weight + V1Weight;
2006 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2007
2008 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2009 << Height << "):\n");
2010 DEBUG(NewNode.dump());
2011 }
2012
2013 assert(Leaves.size() == 1);
2014 SDValue NewRoot = Leaves.top().Value;
2015
2016 assert(NodeHeights.count(NewRoot));
2017 int Height = NodeHeights[NewRoot];
2018
2019 // Restore SHL if we earlier converted it to a MUL
2020 if (NewRoot.getOpcode() == ISD::MUL) {
2021 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2022 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2023 EVT VT = NewRoot.getValueType();
2024 SDValue V0 = NewRoot.getOperand(0);
2025 NewRoot = CurDAG->getNode(
2026 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002027 CurDAG->getConstant(
2028 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2029 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002030 }
2031 }
2032
2033 if (N != NewRoot.getNode()) {
2034 DEBUG(dbgs() << "--> Root is now: ");
2035 DEBUG(NewRoot.dump());
2036
2037 // Replace all uses of old root by new root
2038 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2039 // Mark that we have RAUW'd N
2040 RootWeights[N] = -2;
2041 } else {
2042 DEBUG(dbgs() << "--> Root unchanged.\n");
2043 }
2044
2045 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2046 RootHeights[NewRoot.getNode()] = Height;
2047
2048 return NewRoot;
2049}
2050
2051void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002052 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002053 SDNode *N = &*I++;
2054 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2055 continue;
2056
2057 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2058 if (BasePtr.getOpcode() != ISD::ADD)
2059 continue;
2060
2061 // We've already processed this node
2062 if (RootWeights.count(BasePtr.getNode()))
2063 continue;
2064
2065 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2066 DEBUG(N->dump());
2067
2068 // FindRoots
2069 SmallVector<SDNode *, 4> Worklist;
2070
2071 Worklist.push_back(BasePtr.getOperand(0).getNode());
2072 Worklist.push_back(BasePtr.getOperand(1).getNode());
2073
2074 while (!Worklist.empty()) {
2075 SDNode *N = Worklist.pop_back_val();
2076 unsigned Opcode = N->getOpcode();
2077
2078 if (!isOpcodeHandled(N))
2079 continue;
2080
2081 Worklist.push_back(N->getOperand(0).getNode());
2082 Worklist.push_back(N->getOperand(1).getNode());
2083
2084 // Not a root if it has only one use and same opcode as its parent
2085 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2086 continue;
2087
2088 // This root node has already been processed
2089 if (RootWeights.count(N))
2090 continue;
2091
2092 RootWeights[N] = -1;
2093 }
2094
2095 // Balance node itself
2096 RootWeights[BasePtr.getNode()] = -1;
2097 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2098
2099 if (N->getOpcode() == ISD::LOAD)
2100 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2101 NewBasePtr, N->getOperand(2));
2102 else
2103 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2104 NewBasePtr, N->getOperand(3));
2105
2106 DEBUG(dbgs() << "--> Final node: ");
2107 DEBUG(N->dump());
2108 }
2109
2110 CurDAG->RemoveDeadNodes();
2111 GAUsesInFunction.clear();
2112 RootHeights.clear();
2113 RootWeights.clear();
2114}
2115