blob: a6744d15403d606f1f2b67cfb8d98b2df873ed07 [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:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +000096 case MVT::v2i16:
97 case MVT::v4i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +000098 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
99 break;
100 case MVT::i64:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000101 case MVT::v2i32:
102 case MVT::v4i16:
103 case MVT::v8i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000104 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
105 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000106 case MVT::v64i8:
107 case MVT::v32i16:
108 case MVT::v16i32:
109 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000110 case MVT::v128i8:
111 case MVT::v64i16:
112 case MVT::v32i32:
113 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000114 if (isAlignedMemNode(LD)) {
115 if (LD->isNonTemporal())
116 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
117 else
118 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
119 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000120 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000121 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000122 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000123 default:
124 llvm_unreachable("Unexpected memory type in indexed load");
Justin Bognerec37a022016-05-12 21:46:18 +0000125 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000126
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000127 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
128 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
129 MemOp[0] = LD->getMemOperand();
130
131 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
132 -> MachineSDNode* {
133 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
134 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
135 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
136 Zero, SDValue(N, 0));
Krzysztof Parzyszek08ff8882015-11-26 18:38:27 +0000137 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000138 if (ExtType == ISD::SEXTLOAD)
139 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
140 SDValue(N, 0));
141 return N;
142 };
143
144 // Loaded value Next address Chain
145 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
146 SDValue To[3];
147
148 EVT ValueVT = LD->getValueType(0);
149 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
150 // A load extending to i64 will actually produce i32, which will then
151 // need to be extended to i64.
152 assert(LoadedVT.getSizeInBits() <= 32);
153 ValueVT = MVT::i32;
154 }
155
156 if (IsValidInc) {
157 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
158 MVT::i32, MVT::Other, Base,
159 IncV, Chain);
160 L->setMemRefs(MemOp, MemOp+1);
161 To[1] = SDValue(L, 1); // Next address.
162 To[2] = SDValue(L, 2); // Chain.
163 // Handle special case for extension to i64.
164 if (LD->getValueType(0) == MVT::i64)
165 L = getExt64(L, dl);
166 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000167 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000168 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
169 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
170 Base, Zero, Chain);
171 L->setMemRefs(MemOp, MemOp+1);
172 To[2] = SDValue(L, 1); // Chain.
173 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
174 Base, IncV);
175 To[1] = SDValue(A, 0); // Next address.
176 // Handle special case for extension to i64.
177 if (LD->getValueType(0) == MVT::i64)
178 L = getExt64(L, dl);
179 To[0] = SDValue(L, 0); // Loaded (extended) value.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000180 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000181 ReplaceUses(From, To, 3);
182 CurDAG->RemoveDeadNode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000183}
184
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000185MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
186 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
187 return nullptr;
188
189 SDLoc dl(IntN);
190 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
191
192 static std::map<unsigned,unsigned> LoadPciMap = {
193 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
194 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
195 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
196 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
197 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
198 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
199 };
200 auto FLC = LoadPciMap.find(IntNo);
201 if (FLC != LoadPciMap.end()) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000202 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
203 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
204 // Operands: { Base, Increment, Modifier, Chain }
205 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
206 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
207 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000208 { IntN->getOperand(2), I, IntN->getOperand(4),
209 IntN->getOperand(0) });
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000210 return Res;
211 }
212
213 static std::map<unsigned,unsigned> LoadPbrMap = {
214 { Intrinsic::hexagon_brev_ldb, Hexagon::L2_loadrb_pbr },
215 { Intrinsic::hexagon_brev_ldub, Hexagon::L2_loadrub_pbr },
216 { Intrinsic::hexagon_brev_ldh, Hexagon::L2_loadrh_pbr },
217 { Intrinsic::hexagon_brev_lduh, Hexagon::L2_loadruh_pbr },
218 { Intrinsic::hexagon_brev_ldw, Hexagon::L2_loadri_pbr },
219 { Intrinsic::hexagon_brev_ldd, Hexagon::L2_loadrd_pbr },
220 };
221 auto FLB = LoadPbrMap.find(IntNo);
222 if (FLB != LoadPbrMap.end()) {
223 SDNode *Mod = CurDAG->getMachineNode(Hexagon::A2_tfrrcr, dl, MVT::i32,
224 IntN->getOperand(4));
225 EVT ValTy = (IntNo == Intrinsic::hexagon_brev_ldd) ? MVT::i64 : MVT::i32;
226 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
227 // Operands: { Base, Modifier, Chain }
228 MachineSDNode *Res = CurDAG->getMachineNode(FLB->second, dl, RTys,
229 { IntN->getOperand(2), SDValue(Mod,0), IntN->getOperand(0) });
230 return Res;
231 }
232
233 return nullptr;
234}
235
236SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
237 SDNode *IntN) {
238 // The "LoadN" is just a machine load instruction. The intrinsic also
239 // involves storing it. Generate an appropriate store to the location
240 // given in the intrinsic's operand(3).
241 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
242 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
243 HexagonII::MemAccesSizeMask;
244 unsigned Size = 1U << (SizeBits-1);
245
246 SDLoc dl(IntN);
247 MachinePointerInfo PI;
248 SDValue TS;
249 SDValue Loc = IntN->getOperand(3);
250
251 if (Size >= 4)
Justin Lebar9c375812016-07-15 18:27:10 +0000252 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
253 Size);
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000254 else
Justin Lebar9c375812016-07-15 18:27:10 +0000255 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
256 PI, MVT::getIntegerVT(Size * 8), Size);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000257
258 SDNode *StoreN;
259 {
260 HandleSDNode Handle(TS);
261 SelectStore(TS.getNode());
262 StoreN = Handle.getValue().getNode();
263 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000264
265 // Load's results are { Loaded value, Updated pointer, Chain }
266 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
267 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
268 return StoreN;
269}
270
Justin Bognerec37a022016-05-12 21:46:18 +0000271bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000272 // The intrinsics for load circ/brev perform two operations:
273 // 1. Load a value V from the specified location, using the addressing
274 // mode corresponding to the intrinsic.
275 // 2. Store V into a specified location. This location is typically a
276 // local, temporary object.
277 // In many cases, the program using these intrinsics will immediately
278 // load V again from the local object. In those cases, when certain
279 // conditions are met, the last load can be removed.
280 // This function identifies and optimizes this pattern. If the pattern
281 // cannot be optimized, it returns nullptr, which will cause the load
282 // to be selected separately from the intrinsic (which will be handled
283 // in SelectIntrinsicWChain).
284
285 SDValue Ch = N->getOperand(0);
286 SDValue Loc = N->getOperand(1);
287
288 // Assume that the load and the intrinsic are connected directly with a
289 // chain:
290 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
291 // t2: i32,ch = load t1:1, Loc, ...
292 SDNode *C = Ch.getNode();
293
294 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
Justin Bognerec37a022016-05-12 21:46:18 +0000295 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000296
297 // The second load can only be eliminated if its extension type matches
298 // that of the load instruction corresponding to the intrinsic. The user
299 // can provide an address of an unsigned variable to store the result of
300 // a sign-extending intrinsic into (or the other way around).
301 ISD::LoadExtType IntExt;
302 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
303 case Intrinsic::hexagon_brev_ldub:
304 case Intrinsic::hexagon_brev_lduh:
305 case Intrinsic::hexagon_circ_ldub:
306 case Intrinsic::hexagon_circ_lduh:
307 IntExt = ISD::ZEXTLOAD;
308 break;
309 case Intrinsic::hexagon_brev_ldw:
310 case Intrinsic::hexagon_brev_ldd:
311 case Intrinsic::hexagon_circ_ldw:
312 case Intrinsic::hexagon_circ_ldd:
313 IntExt = ISD::NON_EXTLOAD;
314 break;
315 default:
316 IntExt = ISD::SEXTLOAD;
317 break;
318 }
319 if (N->getExtensionType() != IntExt)
Justin Bognerec37a022016-05-12 21:46:18 +0000320 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000321
322 // Make sure the target location for the loaded value in the load intrinsic
323 // is the location from which LD (or N) is loading.
324 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
Justin Bognerec37a022016-05-12 21:46:18 +0000325 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000326
327 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
328 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
329 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
330 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
331 ReplaceUses(F, T, array_lengthof(T));
332 // This transformation will leave the intrinsic dead. If it remains in
333 // the DAG, the selection code will see it again, but without the load,
334 // and it will generate a store that is normally required for it.
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000335 CurDAG->RemoveDeadNode(C);
Justin Bognerec37a022016-05-12 21:46:18 +0000336 return true;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000337 }
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000338 return false;
339}
340
341/// Generate a machine instruction node for the new circlar buffer intrinsics.
342/// The new versions use a CSx register instead of the K field.
343bool HexagonDAGToDAGISel::SelectNewCircIntrinsic(SDNode *IntN) {
344 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
345 return false;
346
347 SDLoc DL(IntN);
348 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
349 SmallVector<SDValue, 7> Ops;
350
351 static std::map<unsigned,unsigned> LoadNPcMap = {
352 { Intrinsic::hexagon_L2_loadrub_pci, Hexagon::PS_loadrub_pci },
353 { Intrinsic::hexagon_L2_loadrb_pci, Hexagon::PS_loadrb_pci },
354 { Intrinsic::hexagon_L2_loadruh_pci, Hexagon::PS_loadruh_pci },
355 { Intrinsic::hexagon_L2_loadrh_pci, Hexagon::PS_loadrh_pci },
356 { Intrinsic::hexagon_L2_loadri_pci, Hexagon::PS_loadri_pci },
357 { Intrinsic::hexagon_L2_loadrd_pci, Hexagon::PS_loadrd_pci },
358 { Intrinsic::hexagon_L2_loadrub_pcr, Hexagon::PS_loadrub_pcr },
359 { Intrinsic::hexagon_L2_loadrb_pcr, Hexagon::PS_loadrb_pcr },
360 { Intrinsic::hexagon_L2_loadruh_pcr, Hexagon::PS_loadruh_pcr },
361 { Intrinsic::hexagon_L2_loadrh_pcr, Hexagon::PS_loadrh_pcr },
362 { Intrinsic::hexagon_L2_loadri_pcr, Hexagon::PS_loadri_pcr },
363 { Intrinsic::hexagon_L2_loadrd_pcr, Hexagon::PS_loadrd_pcr }
364 };
365 auto FLI = LoadNPcMap.find (IntNo);
366 if (FLI != LoadNPcMap.end()) {
367 EVT ValTy = MVT::i32;
368 if (IntNo == Intrinsic::hexagon_L2_loadrd_pci ||
369 IntNo == Intrinsic::hexagon_L2_loadrd_pcr)
370 ValTy = MVT::i64;
371 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
372 // Handle load.*_pci case which has 6 operands.
373 if (IntN->getNumOperands() == 6) {
374 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
375 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
376 // Operands: { Base, Increment, Modifier, Start, Chain }.
377 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
378 IntN->getOperand(0) };
379 } else
380 // Handle load.*_pcr case which has 5 operands.
381 // Operands: { Base, Modifier, Start, Chain }.
382 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
383 IntN->getOperand(0) };
384 MachineSDNode *Res = CurDAG->getMachineNode(FLI->second, DL, RTys, Ops);
385 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
386 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
387 ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
388 CurDAG->RemoveDeadNode(IntN);
389 return true;
390 }
391
392 static std::map<unsigned,unsigned> StoreNPcMap = {
393 { Intrinsic::hexagon_S2_storerb_pci, Hexagon::PS_storerb_pci },
394 { Intrinsic::hexagon_S2_storerh_pci, Hexagon::PS_storerh_pci },
395 { Intrinsic::hexagon_S2_storerf_pci, Hexagon::PS_storerf_pci },
396 { Intrinsic::hexagon_S2_storeri_pci, Hexagon::PS_storeri_pci },
397 { Intrinsic::hexagon_S2_storerd_pci, Hexagon::PS_storerd_pci },
398 { Intrinsic::hexagon_S2_storerb_pcr, Hexagon::PS_storerb_pcr },
399 { Intrinsic::hexagon_S2_storerh_pcr, Hexagon::PS_storerh_pcr },
400 { Intrinsic::hexagon_S2_storerf_pcr, Hexagon::PS_storerf_pcr },
401 { Intrinsic::hexagon_S2_storeri_pcr, Hexagon::PS_storeri_pcr },
402 { Intrinsic::hexagon_S2_storerd_pcr, Hexagon::PS_storerd_pcr }
403 };
404 auto FSI = StoreNPcMap.find (IntNo);
405 if (FSI != StoreNPcMap.end()) {
406 EVT RTys[] = { MVT::i32, MVT::Other };
407 // Handle store.*_pci case which has 7 operands.
408 if (IntN->getNumOperands() == 7) {
409 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
410 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
411 // Operands: { Base, Increment, Modifier, Value, Start, Chain }.
412 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
413 IntN->getOperand(6), IntN->getOperand(0) };
414 } else
415 // Handle store.*_pcr case which has 6 operands.
416 // Operands: { Base, Modifier, Value, Start, Chain }.
417 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
418 IntN->getOperand(5), IntN->getOperand(0) };
419 MachineSDNode *Res = CurDAG->getMachineNode(FSI->second, DL, RTys, Ops);
420 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
421 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
422 CurDAG->RemoveDeadNode(IntN);
423 return true;
424 }
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000425
Justin Bognerec37a022016-05-12 21:46:18 +0000426 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000427}
428
Justin Bognerec37a022016-05-12 21:46:18 +0000429void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000430 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000431 LoadSDNode *LD = cast<LoadSDNode>(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000432
433 // Handle indexed loads.
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000434 ISD::MemIndexedMode AM = LD->getAddressingMode();
Justin Bognerec37a022016-05-12 21:46:18 +0000435 if (AM != ISD::UNINDEXED) {
436 SelectIndexedLoad(LD, dl);
437 return;
438 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000439
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000440 // Handle patterns using circ/brev load intrinsics.
Justin Bognerec37a022016-05-12 21:46:18 +0000441 if (tryLoadOfLoadIntrinsic(LD))
442 return;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000443
Justin Bognerec37a022016-05-12 21:46:18 +0000444 SelectCode(LD);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000445}
446
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000447void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000448 SDValue Chain = ST->getChain();
449 SDValue Base = ST->getBasePtr();
450 SDValue Offset = ST->getOffset();
451 SDValue Value = ST->getValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000452 // Get the constant value.
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000453 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000454 EVT StoredVT = ST->getMemoryVT();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000455 EVT ValueVT = Value.getValueType();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000456
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000457 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000458 unsigned Opcode = 0;
459
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000460 assert(StoredVT.isSimple());
461 switch (StoredVT.getSimpleVT().SimpleTy) {
462 case MVT::i8:
463 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
464 break;
465 case MVT::i16:
466 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
467 break;
468 case MVT::i32:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000469 case MVT::v2i16:
470 case MVT::v4i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000471 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
472 break;
473 case MVT::i64:
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000474 case MVT::v2i32:
475 case MVT::v4i16:
476 case MVT::v8i8:
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000477 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
478 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000479 case MVT::v64i8:
480 case MVT::v32i16:
481 case MVT::v16i32:
482 case MVT::v8i64:
Krzysztof Parzyszek55772972017-09-15 15:46:05 +0000483 case MVT::v128i8:
484 case MVT::v64i16:
485 case MVT::v32i32:
486 case MVT::v16i64:
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000487 if (isAlignedMemNode(ST)) {
488 if (ST->isNonTemporal())
489 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
490 else
491 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
492 } else {
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000493 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
Krzysztof Parzyszekc86e2ef2017-07-11 16:39:33 +0000494 }
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000495 break;
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000496 default:
497 llvm_unreachable("Unexpected memory type in indexed store");
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +0000498 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000499
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000500 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
501 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +0000502 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000503 dl, MVT::i32, Value);
504 }
505
506 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000507 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
508 MemOp[0] = ST->getMemOperand();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000509
Krzysztof Parzyszek709a6262016-06-24 21:27:17 +0000510 // Next address Chain
511 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
512 SDValue To[2];
513
514 if (IsValidInc) {
515 // Build post increment store.
516 SDValue Ops[] = { Base, IncV, Value, Chain };
517 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
518 Ops);
519 S->setMemRefs(MemOp, MemOp + 1);
520 To[0] = SDValue(S, 0);
521 To[1] = SDValue(S, 1);
522 } else {
523 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
524 SDValue Ops[] = { Base, Zero, Value, Chain };
525 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
526 S->setMemRefs(MemOp, MemOp + 1);
527 To[1] = SDValue(S, 0);
528 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
529 Base, IncV);
530 To[0] = SDValue(A, 0);
531 }
532
533 ReplaceUses(From, To, 2);
Justin Bognerdcb7a822016-05-10 20:31:53 +0000534 CurDAG->RemoveDeadNode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000535}
536
Justin Bognerec37a022016-05-12 21:46:18 +0000537void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000538 SDLoc dl(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000539 StoreSDNode *ST = cast<StoreSDNode>(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000540
541 // Handle indexed stores.
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000542 ISD::MemIndexedMode AM = ST->getAddressingMode();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000543 if (AM != ISD::UNINDEXED) {
Justin Bognerec37a022016-05-12 21:46:18 +0000544 SelectIndexedStore(ST, dl);
545 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000546 }
Sirish Pandec92c3162012-05-03 16:18:50 +0000547
Justin Bognerec37a022016-05-12 21:46:18 +0000548 SelectCode(ST);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000549}
550
Justin Bognerec37a022016-05-12 21:46:18 +0000551void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000552 SDLoc dl(N);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000553 SDValue Shl_0 = N->getOperand(0);
554 SDValue Shl_1 = N->getOperand(1);
Krzysztof Parzyszekd978ae22016-08-01 20:00:33 +0000555
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000556 auto Default = [this,N] () -> void { SelectCode(N); };
557
558 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
559 return Default();
560
561 // RHS is const.
562 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
563
564 if (Shl_0.getOpcode() == ISD::MUL) {
565 SDValue Mul_0 = Shl_0.getOperand(0); // Val
566 SDValue Mul_1 = Shl_0.getOperand(1); // Const
567 // RHS of mul is const.
568 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
569 int32_t ValConst = C->getSExtValue() << ShlConst;
570 if (isInt<9>(ValConst)) {
571 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
572 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
573 MVT::i32, Mul_0, Val);
574 ReplaceNode(N, Result);
575 return;
576 }
577 }
578 return Default();
579 }
580
581 if (Shl_0.getOpcode() == ISD::SUB) {
582 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
583 SDValue Sub_1 = Shl_0.getOperand(1); // Val
584 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
585 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
586 return Default();
587 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
588 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
589 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
590 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
591 if (isInt<9>(-ValConst)) {
592 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
593 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
594 MVT::i32, Shl2_0, Val);
595 ReplaceNode(N, Result);
596 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000597 }
598 }
599 }
600 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000601
602 return Default();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000603}
604
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000605//
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000606// Handling intrinsics for circular load and bitreverse load.
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000607//
Justin Bognerec37a022016-05-12 21:46:18 +0000608void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
609 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
610 StoreInstrForLoadIntrinsic(L, N);
Krzysztof Parzyszek0f791f42016-05-13 18:48:15 +0000611 CurDAG->RemoveDeadNode(N);
Justin Bognerec37a022016-05-12 21:46:18 +0000612 return;
613 }
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000614
Krzysztof Parzyszek440ba3a2018-03-28 19:38:29 +0000615 if (SelectNewCircIntrinsic(N))
616 return;
617
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000618 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
619 if (IntNo == Intrinsic::hexagon_V6_vgathermw ||
620 IntNo == Intrinsic::hexagon_V6_vgathermw_128B ||
621 IntNo == Intrinsic::hexagon_V6_vgathermh ||
622 IntNo == Intrinsic::hexagon_V6_vgathermh_128B ||
623 IntNo == Intrinsic::hexagon_V6_vgathermhw ||
624 IntNo == Intrinsic::hexagon_V6_vgathermhw_128B) {
625 SelectV65Gather(N);
626 return;
627 }
628 if (IntNo == Intrinsic::hexagon_V6_vgathermwq ||
629 IntNo == Intrinsic::hexagon_V6_vgathermwq_128B ||
630 IntNo == Intrinsic::hexagon_V6_vgathermhq ||
631 IntNo == Intrinsic::hexagon_V6_vgathermhq_128B ||
632 IntNo == Intrinsic::hexagon_V6_vgathermhwq ||
633 IntNo == Intrinsic::hexagon_V6_vgathermhwq_128B) {
634 SelectV65GatherPred(N);
635 return;
636 }
637
Justin Bognerec37a022016-05-12 21:46:18 +0000638 SelectCode(N);
Krzysztof Parzyszek47ab1f22015-03-18 16:23:44 +0000639}
640
Justin Bognerec37a022016-05-12 21:46:18 +0000641void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000642 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
643 unsigned Bits;
644 switch (IID) {
645 case Intrinsic::hexagon_S2_vsplatrb:
646 Bits = 8;
647 break;
648 case Intrinsic::hexagon_S2_vsplatrh:
649 Bits = 16;
650 break;
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +0000651 case Intrinsic::hexagon_V6_vaddcarry:
652 case Intrinsic::hexagon_V6_vaddcarry_128B:
653 case Intrinsic::hexagon_V6_vsubcarry:
654 case Intrinsic::hexagon_V6_vsubcarry_128B:
655 SelectHVXDualOutput(N);
656 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000657 default:
Justin Bognerec37a022016-05-12 21:46:18 +0000658 SelectCode(N);
659 return;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000660 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000661
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000662 SDValue V = N->getOperand(1);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000663 SDValue U;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +0000664 if (keepsLowBits(V, Bits, U)) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +0000665 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
Krzysztof Parzyszeke60e5fe2016-05-12 17:21:40 +0000666 N->getOperand(0), U);
Justin Bognerd82025b2016-05-12 21:24:23 +0000667 ReplaceNode(N, R.getNode());
Justin Bognerec37a022016-05-12 21:46:18 +0000668 SelectCode(R.getNode());
669 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000670 }
Justin Bognerec37a022016-05-12 21:46:18 +0000671 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000672}
673
Sirish Pande69295b82012-05-10 20:20:25 +0000674//
675// Map floating point constant values.
676//
Justin Bognerec37a022016-05-12 21:46:18 +0000677void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000678 SDLoc dl(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000679 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000680 APInt A = CN->getValueAPF().bitcastToAPInt();
Sirish Pande69295b82012-05-10 20:20:25 +0000681 if (N->getValueType(0) == MVT::f32) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000682 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
683 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000684 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000685 }
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000686 if (N->getValueType(0) == MVT::f64) {
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +0000687 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
688 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
Justin Bognerec37a022016-05-12 21:46:18 +0000689 return;
Sirish Pande69295b82012-05-10 20:20:25 +0000690 }
691
Justin Bognerec37a022016-05-12 21:46:18 +0000692 SelectCode(N);
Sirish Pande69295b82012-05-10 20:20:25 +0000693}
694
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000695//
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000696// Map boolean values.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000697//
Justin Bognerec37a022016-05-12 21:46:18 +0000698void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000699 if (N->getValueType(0) == MVT::i1) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000700 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1));
701 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
702 ? Hexagon::PS_true
703 : Hexagon::PS_false;
704 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
705 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000706 }
707
Justin Bognerec37a022016-05-12 21:46:18 +0000708 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000709}
710
Justin Bognerec37a022016-05-12 21:46:18 +0000711void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
Matthias Braun941a7052016-07-28 18:40:00 +0000712 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000713 const HexagonFrameLowering *HFI = HST->getFrameLowering();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000714 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000715 unsigned StkA = HFI->getStackAlignment();
Matthias Braun941a7052016-07-28 18:40:00 +0000716 unsigned MaxA = MFI.getMaxAlignment();
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000717 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000718 SDLoc DL(N);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000719 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +0000720 SDNode *R = nullptr;
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000721
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000722 // Use PS_fi when:
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000723 // - the object is fixed, or
724 // - there are no objects with higher-than-default alignment, or
725 // - there are no dynamically allocated objects.
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000726 // Otherwise, use PS_fia.
Matthias Braun941a7052016-07-28 18:40:00 +0000727 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000728 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000729 } else {
730 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
731 unsigned AR = HMFI.getStackAlignBaseVReg();
732 SDValue CH = CurDAG->getEntryNode();
733 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
Krzysztof Parzyszek1d01a792016-08-16 18:08:40 +0000734 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +0000735 }
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000736
Justin Bognerec37a022016-05-12 21:46:18 +0000737 ReplaceNode(N, R);
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000738}
739
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000740
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000741void HexagonDAGToDAGISel::SelectBitcast(SDNode *N) {
742 EVT SVT = N->getOperand(0).getValueType();
743 EVT DVT = N->getValueType(0);
744 if (!SVT.isVector() || !DVT.isVector() ||
745 SVT.getVectorElementType() == MVT::i1 ||
746 DVT.getVectorElementType() == MVT::i1 ||
747 SVT.getSizeInBits() != DVT.getSizeInBits()) {
748 SelectCode(N);
749 return;
750 }
751
Nirav Dave3264c1b2018-03-19 20:19:46 +0000752 ReplaceUses(SDValue(N, 0), N->getOperand(0));
Krzysztof Parzyszek5da24e52016-06-27 15:08:22 +0000753 CurDAG->RemoveDeadNode(N);
754}
755
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000756void HexagonDAGToDAGISel::SelectVAlign(SDNode *N) {
757 MVT ResTy = N->getValueType(0).getSimpleVT();
758 if (HST->isHVXVectorType(ResTy, true))
759 return SelectHvxVAlign(N);
760
761 const SDLoc &dl(N);
762 unsigned VecLen = ResTy.getSizeInBits();
763 if (VecLen == 32) {
764 SDValue Ops[] = {
765 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
766 N->getOperand(0),
767 CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
768 N->getOperand(1),
769 CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
770 };
771 SDNode *R = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
772 MVT::i64, Ops);
773
774 // Shift right by "(Addr & 0x3) * 8" bytes.
775 SDValue M0 = CurDAG->getTargetConstant(0x18, dl, MVT::i32);
776 SDValue M1 = CurDAG->getTargetConstant(0x03, dl, MVT::i32);
777 SDNode *C = CurDAG->getMachineNode(Hexagon::S4_andi_asl_ri, dl, MVT::i32,
778 M0, N->getOperand(2), M1);
779 SDNode *S = CurDAG->getMachineNode(Hexagon::S2_lsr_r_p, dl, MVT::i64,
780 SDValue(R, 0), SDValue(C, 0));
781 SDValue E = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo, dl, ResTy,
782 SDValue(S, 0));
783 ReplaceNode(N, E.getNode());
784 } else {
785 assert(VecLen == 64);
786 SDNode *Pu = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::v8i1,
787 N->getOperand(2));
788 SDNode *VA = CurDAG->getMachineNode(Hexagon::S2_valignrb, dl, ResTy,
789 N->getOperand(0), N->getOperand(1),
790 SDValue(Pu,0));
791 ReplaceNode(N, VA);
792 }
793}
794
795void HexagonDAGToDAGISel::SelectVAlignAddr(SDNode *N) {
796 const SDLoc &dl(N);
797 SDValue A = N->getOperand(1);
798 int Mask = -cast<ConstantSDNode>(A.getNode())->getSExtValue();
799 assert(isPowerOf2_32(-Mask));
800
801 SDValue M = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
802 SDNode *AA = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
803 N->getOperand(0), M);
804 ReplaceNode(N, AA);
805}
806
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000807// Handle these nodes here to avoid having to write patterns for all
808// combinations of input/output types. In all cases, the resulting
809// instruction is the same.
810void HexagonDAGToDAGISel::SelectTypecast(SDNode *N) {
811 SDValue Op = N->getOperand(0);
812 MVT OpTy = Op.getValueType().getSimpleVT();
813 SDNode *T = CurDAG->MorphNodeTo(N, N->getOpcode(),
814 CurDAG->getVTList(OpTy), {Op});
815 ReplaceNode(T, Op.getNode());
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000816}
817
818void HexagonDAGToDAGISel::SelectP2D(SDNode *N) {
819 MVT ResTy = N->getValueType(0).getSimpleVT();
820 SDNode *T = CurDAG->getMachineNode(Hexagon::C2_mask, SDLoc(N), ResTy,
821 N->getOperand(0));
822 ReplaceNode(N, T);
823}
824
825void HexagonDAGToDAGISel::SelectD2P(SDNode *N) {
826 const SDLoc &dl(N);
827 MVT ResTy = N->getValueType(0).getSimpleVT();
828 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
829 SDNode *T = CurDAG->getMachineNode(Hexagon::A4_vcmpbgtui, dl, ResTy,
830 N->getOperand(0), Zero);
831 ReplaceNode(N, T);
832}
833
834void HexagonDAGToDAGISel::SelectV2Q(SDNode *N) {
835 const SDLoc &dl(N);
836 MVT ResTy = N->getValueType(0).getSimpleVT();
837
838 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
839 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
840 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandvrt, dl, ResTy,
841 N->getOperand(0), SDValue(R,0));
842 ReplaceNode(N, T);
843}
844
845void HexagonDAGToDAGISel::SelectQ2V(SDNode *N) {
846 const SDLoc &dl(N);
847 MVT ResTy = N->getValueType(0).getSimpleVT();
848
849 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
850 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
851 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandqrt, dl, ResTy,
852 N->getOperand(0), SDValue(R,0));
853 ReplaceNode(N, T);
854}
855
Justin Bognerec37a022016-05-12 21:46:18 +0000856void HexagonDAGToDAGISel::Select(SDNode *N) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000857 if (N->isMachineOpcode())
858 return N->setNodeId(-1); // Already selected.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000859
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000860 switch (N->getOpcode()) {
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000861 case ISD::Constant: return SelectConstant(N);
862 case ISD::ConstantFP: return SelectConstantFP(N);
863 case ISD::FrameIndex: return SelectFrameIndex(N);
864 case ISD::BITCAST: return SelectBitcast(N);
865 case ISD::SHL: return SelectSHL(N);
866 case ISD::LOAD: return SelectLoad(N);
867 case ISD::STORE: return SelectStore(N);
Krzysztof Parzyszekbe5028a2017-02-24 23:00:40 +0000868 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
869 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000870 case HexagonISD::VALIGN: return SelectVAlign(N);
871 case HexagonISD::VALIGNADDR: return SelectVAlignAddr(N);
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +0000872 case HexagonISD::TYPECAST: return SelectTypecast(N);
873 case HexagonISD::P2D: return SelectP2D(N);
874 case HexagonISD::D2P: return SelectD2P(N);
875 case HexagonISD::Q2V: return SelectQ2V(N);
876 case HexagonISD::V2Q: return SelectV2Q(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000877 }
878
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000879 if (HST->useHVXOps()) {
880 switch (N->getOpcode()) {
881 case ISD::VECTOR_SHUFFLE: return SelectHvxShuffle(N);
882 case HexagonISD::VROR: return SelectHvxRor(N);
883 }
884 }
885
Justin Bognerec37a022016-05-12 21:46:18 +0000886 SelectCode(N);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000887}
888
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000889bool HexagonDAGToDAGISel::
Daniel Sanders60f1db02015-03-13 12:45:09 +0000890SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000891 std::vector<SDValue> &OutOps) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000892 SDValue Inp = Op, Res;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000893
Daniel Sanders60f1db02015-03-13 12:45:09 +0000894 switch (ConstraintID) {
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000895 default:
896 return true;
Daniel Sanders49f643c2015-03-17 14:37:39 +0000897 case InlineAsm::Constraint_i:
898 case InlineAsm::Constraint_o: // Offsetable.
899 case InlineAsm::Constraint_v: // Not offsetable.
900 case InlineAsm::Constraint_m: // Memory.
Krzysztof Parzyszeka29622a2015-03-12 16:44:50 +0000901 if (SelectAddrFI(Inp, Res))
902 OutOps.push_back(Res);
903 else
904 OutOps.push_back(Inp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000905 break;
906 }
907
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000908 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
Jyotsna Vermad9225242013-02-13 21:38:46 +0000909 return false;
910}
Colin LeMahieuc7522f32015-01-14 23:07:36 +0000911
Colin LeMahieu79ec0652015-06-12 19:57:32 +0000912
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +0000913static bool isMemOPCandidate(SDNode *I, SDNode *U) {
914 // I is an operand of U. Check if U is an arithmetic (binary) operation
915 // usable in a memop, where the other operand is a loaded value, and the
916 // result of U is stored in the same location.
917
918 if (!U->hasOneUse())
919 return false;
920 unsigned Opc = U->getOpcode();
921 switch (Opc) {
922 case ISD::ADD:
923 case ISD::SUB:
924 case ISD::AND:
925 case ISD::OR:
926 break;
927 default:
928 return false;
929 }
930
931 SDValue S0 = U->getOperand(0);
932 SDValue S1 = U->getOperand(1);
933 SDValue SY = (S0.getNode() == I) ? S1 : S0;
934
935 SDNode *UUse = *U->use_begin();
936 if (UUse->getNumValues() != 1)
937 return false;
938
939 // Check if one of the inputs to U is a load instruction and the output
940 // is used by a store instruction. If so and they also have the same
941 // base pointer, then don't preoprocess this node sequence as it
942 // can be matched to a memop.
943 SDNode *SYNode = SY.getNode();
944 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
945 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
946 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
947 if (LDBasePtr == STBasePtr)
948 return true;
949 }
950 return false;
951}
952
953
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000954// Transform: (or (select c x 0) z) -> (select c (or x z) z)
955// (or (select c 0 y) z) -> (select c z (or y z))
956void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000957 SelectionDAG &DAG = *CurDAG;
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000958
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000959 for (auto I : Nodes) {
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000960 if (I->getOpcode() != ISD::OR)
961 continue;
962
963 auto IsZero = [] (const SDValue &V) -> bool {
964 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
965 return SC->isNullValue();
966 return false;
967 };
968 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
969 if (Op.getOpcode() != ISD::SELECT)
970 return false;
Krzysztof Parzyszek7d5b4db2016-02-12 17:01:51 +0000971 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +0000972 };
973
974 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
975 EVT VT = I->getValueType(0);
976 bool SelN0 = IsSelect0(N0);
977 SDValue SOp = SelN0 ? N0 : N1;
978 SDValue VOp = SelN0 ? N1 : N0;
979
980 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
981 SDValue SC = SOp.getOperand(0);
982 SDValue SX = SOp.getOperand(1);
983 SDValue SY = SOp.getOperand(2);
984 SDLoc DLS = SOp;
985 if (IsZero(SY)) {
986 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
987 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
988 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
989 } else if (IsZero(SX)) {
990 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
991 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
992 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
993 }
994 }
995 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000996}
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +0000997
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +0000998// Transform: (store ch val (add x (add (shl y c) e)))
999// to: (store ch val (add x (shl (add y d) c))),
1000// where e = (shl d c) for some integer d.
1001// The purpose of this is to enable generation of loads/stores with
1002// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1003// value c must be 0, 1 or 2.
1004void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
1005 SelectionDAG &DAG = *CurDAG;
1006
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001007 for (auto I : Nodes) {
1008 if (I->getOpcode() != ISD::STORE)
1009 continue;
1010
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001011 // I matched: (store ch val Off)
Krzysztof Parzyszekf7f70682016-06-22 20:08:27 +00001012 SDValue Off = I->getOperand(2);
1013 // Off needs to match: (add x (add (shl y c) (shl d c))))
1014 if (Off.getOpcode() != ISD::ADD)
1015 continue;
1016 // Off matched: (add x T0)
1017 SDValue T0 = Off.getOperand(1);
1018 // T0 needs to match: (add T1 T2):
1019 if (T0.getOpcode() != ISD::ADD)
1020 continue;
1021 // T0 matched: (add T1 T2)
1022 SDValue T1 = T0.getOperand(0);
1023 SDValue T2 = T0.getOperand(1);
1024 // T1 needs to match: (shl y c)
1025 if (T1.getOpcode() != ISD::SHL)
1026 continue;
1027 SDValue C = T1.getOperand(1);
1028 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1029 if (CN == nullptr)
1030 continue;
1031 unsigned CV = CN->getZExtValue();
1032 if (CV > 2)
1033 continue;
1034 // T2 needs to match e, where e = (shl d c) for some d.
1035 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1036 if (EN == nullptr)
1037 continue;
1038 unsigned EV = EN->getZExtValue();
1039 if (EV % (1 << CV) != 0)
1040 continue;
1041 unsigned DV = EV / (1 << CV);
1042
1043 // Replace T0 with: (shl (add y d) c)
1044 SDLoc DL = SDLoc(I);
1045 EVT VT = T0.getValueType();
1046 SDValue D = DAG.getConstant(DV, DL, VT);
1047 // NewAdd = (add y d)
1048 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1049 // NewShl = (shl NewAdd c)
1050 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1051 ReplaceNode(T0.getNode(), NewShl.getNode());
1052 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001053}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001054
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001055// Transform: (load ch (add x (and (srl y c) Mask)))
1056// to: (load ch (add x (shl (srl y d) d-c)))
1057// where
1058// Mask = 00..0 111..1 0.0
1059// | | +-- d-c 0s, and d-c is 0, 1 or 2.
1060// | +-------- 1s
1061// +-------------- at most c 0s
1062// Motivating example:
1063// DAG combiner optimizes (add x (shl (srl y 5) 2))
1064// to (add x (and (srl y 3) 1FFFFFFC))
1065// which results in a constant-extended and(##...,lsr). This transformation
1066// undoes this simplification for cases where the shl can be folded into
1067// an addressing mode.
1068void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1069 SelectionDAG &DAG = *CurDAG;
1070
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001071 for (SDNode *N : Nodes) {
1072 unsigned Opc = N->getOpcode();
1073 if (Opc != ISD::LOAD && Opc != ISD::STORE)
1074 continue;
1075 SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
1076 // Addr must match: (add x T0)
1077 if (Addr.getOpcode() != ISD::ADD)
1078 continue;
1079 SDValue T0 = Addr.getOperand(1);
1080 // T0 must match: (and T1 Mask)
1081 if (T0.getOpcode() != ISD::AND)
1082 continue;
1083
1084 // We have an AND.
1085 //
1086 // Check the first operand. It must be: (srl y c).
1087 SDValue S = T0.getOperand(0);
1088 if (S.getOpcode() != ISD::SRL)
1089 continue;
1090 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
1091 if (SN == nullptr)
1092 continue;
1093 if (SN->getAPIntValue().getBitWidth() != 32)
1094 continue;
1095 uint32_t CV = SN->getZExtValue();
1096
1097 // Check the second operand: the supposed mask.
1098 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
1099 if (MN == nullptr)
1100 continue;
1101 if (MN->getAPIntValue().getBitWidth() != 32)
1102 continue;
1103 uint32_t Mask = MN->getZExtValue();
1104 // Examine the mask.
1105 uint32_t TZ = countTrailingZeros(Mask);
1106 uint32_t M1 = countTrailingOnes(Mask >> TZ);
1107 uint32_t LZ = countLeadingZeros(Mask);
1108 // Trailing zeros + middle ones + leading zeros must equal the width.
1109 if (TZ + M1 + LZ != 32)
1110 continue;
1111 // The number of trailing zeros will be encoded in the addressing mode.
1112 if (TZ > 2)
1113 continue;
1114 // The number of leading zeros must be at most c.
1115 if (LZ > CV)
1116 continue;
1117
1118 // All looks good.
1119 SDValue Y = S.getOperand(0);
1120 EVT VT = Addr.getValueType();
1121 SDLoc dl(S);
1122 // TZ = D-C, so D = TZ+C.
1123 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1124 SDValue DC = DAG.getConstant(TZ, dl, VT);
1125 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1126 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1127 ReplaceNode(T0.getNode(), NewShl.getNode());
1128 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001129}
Krzysztof Parzyszek0d67b102017-02-24 23:34:24 +00001130
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001131// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1132// (op ... 1 ...))
1133void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1134 SelectionDAG &DAG = *CurDAG;
1135
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001136 for (SDNode *N : Nodes) {
1137 unsigned Opc = N->getOpcode();
1138 if (Opc != ISD::ZERO_EXTEND)
1139 continue;
1140 SDValue OpI1 = N->getOperand(0);
1141 EVT OpVT = OpI1.getValueType();
1142 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1143 continue;
1144 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1145 SDNode *U = *I;
1146 if (U->getNumValues() != 1)
1147 continue;
1148 EVT UVT = U->getValueType(0);
1149 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1150 continue;
1151 if (isMemOPCandidate(N, U))
1152 continue;
1153
1154 // Potentially simplifiable operation.
1155 unsigned I1N = I.getOperandNo();
1156 SmallVector<SDValue,2> Ops(U->getNumOperands());
1157 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1158 Ops[i] = U->getOperand(i);
1159 EVT BVT = Ops[I1N].getValueType();
1160
1161 SDLoc dl(U);
1162 SDValue C0 = DAG.getConstant(0, dl, BVT);
1163 SDValue C1 = DAG.getConstant(1, dl, BVT);
1164 SDValue If0, If1;
1165
1166 if (isa<MachineSDNode>(U)) {
1167 unsigned UseOpc = U->getMachineOpcode();
1168 Ops[I1N] = C0;
1169 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1170 Ops[I1N] = C1;
1171 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1172 } else {
1173 unsigned UseOpc = U->getOpcode();
1174 Ops[I1N] = C0;
1175 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1176 Ops[I1N] = C1;
1177 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1178 }
1179 SDValue Sel = DAG.getNode(ISD::SELECT, dl, UVT, OpI1, If1, If0);
1180 DAG.ReplaceAllUsesWith(U, Sel.getNode());
1181 }
1182 }
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001183}
1184
1185void HexagonDAGToDAGISel::PreprocessISelDAG() {
1186 // Repack all nodes before calling each preprocessing function,
1187 // because each of them can modify the set of nodes.
1188 auto getNodes = [this] () -> std::vector<SDNode*> {
1189 std::vector<SDNode*> T;
1190 T.reserve(CurDAG->allnodes_size());
1191 for (SDNode &N : CurDAG->allnodes())
1192 T.push_back(&N);
1193 return T;
1194 };
1195
1196 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1197 // (or (select c 0 y) z) -> (select c z (or y z))
1198 ppSimplifyOrSelect0(getNodes());
1199
1200 // Transform: (store ch val (add x (add (shl y c) e)))
1201 // to: (store ch val (add x (shl (add y d) c))),
1202 // where e = (shl d c) for some integer d.
1203 // The purpose of this is to enable generation of loads/stores with
1204 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1205 // value c must be 0, 1 or 2.
1206 ppAddrReorderAddShl(getNodes());
1207
1208 // Transform: (load ch (add x (and (srl y c) Mask)))
1209 // to: (load ch (add x (shl (srl y d) d-c)))
1210 // where
1211 // Mask = 00..0 111..1 0.0
1212 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1213 // | +-------- 1s
1214 // +-------------- at most c 0s
1215 // Motivating example:
1216 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1217 // to (add x (and (srl y 3) 1FFFFFFC))
1218 // which results in a constant-extended and(##...,lsr). This transformation
1219 // undoes this simplification for cases where the shl can be folded into
1220 // an addressing mode.
1221 ppAddrRewriteAndSrl(getNodes());
1222
1223 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1224 // (op ... 1 ...))
1225 ppHoistZextI1(getNodes());
Krzysztof Parzyszek78c4fcf2017-03-09 16:29:30 +00001226
1227 DEBUG_WITH_TYPE("isel", {
1228 dbgs() << "Preprocessed (Hexagon) selection DAG:";
1229 CurDAG->dump();
1230 });
1231
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001232 if (EnableAddressRebalancing) {
1233 rebalanceAddressTrees();
1234
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001235 DEBUG_WITH_TYPE("isel", {
1236 dbgs() << "Address tree balanced selection DAG:";
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001237 CurDAG->dump();
Krzysztof Parzyszekfe267a32017-03-09 19:14:23 +00001238 });
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001239 }
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001240}
Krzysztof Parzyszekae14e7b2015-03-17 21:47:16 +00001241
Krzysztof Parzyszek16610b02018-01-25 16:36:53 +00001242void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1243 auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1244 auto &HFI = *HST.getFrameLowering();
1245 if (!HFI.needsAligna(*MF))
1246 return;
1247
1248 MachineFrameInfo &MFI = MF->getFrameInfo();
1249 MachineBasicBlock *EntryBB = &MF->front();
1250 unsigned AR = FuncInfo->CreateReg(MVT::i32);
1251 unsigned MaxA = MFI.getMaxAlignment();
1252 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
1253 .addImm(MaxA);
1254 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001255}
1256
1257// Match a frame index that can be used in an addressing mode.
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001258bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001259 if (N.getOpcode() != ISD::FrameIndex)
1260 return false;
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001261 auto &HFI = *HST->getFrameLowering();
Matthias Braun941a7052016-07-28 18:40:00 +00001262 MachineFrameInfo &MFI = MF->getFrameInfo();
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001263 int FX = cast<FrameIndexSDNode>(N)->getIndex();
Matthias Braun941a7052016-07-28 18:40:00 +00001264 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
Krzysztof Parzyszek4fa2a9f2015-04-22 16:43:53 +00001265 return false;
1266 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
Colin LeMahieuc7522f32015-01-14 23:07:36 +00001267 return true;
1268}
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001269
Colin LeMahieu987b0942015-02-04 20:38:01 +00001270inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001271 return SelectGlobalAddress(N, R, false, 0);
Colin LeMahieu987b0942015-02-04 20:38:01 +00001272}
1273
Colin LeMahieu51491352015-02-04 22:36:28 +00001274inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001275 return SelectGlobalAddress(N, R, true, 0);
1276}
1277
1278inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1279 return SelectAnyImmediate(N, R, 0);
1280}
1281
1282inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1283 return SelectAnyImmediate(N, R, 0);
1284}
1285inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1286 return SelectAnyImmediate(N, R, 1);
1287}
1288inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1289 return SelectAnyImmediate(N, R, 2);
1290}
1291inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1292 return SelectAnyImmediate(N, R, 3);
1293}
1294
1295inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1296 EVT T = N.getValueType();
1297 if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1298 return false;
1299 R = N;
1300 return true;
1301}
1302
1303bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1304 uint32_t LogAlign) {
1305 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001306 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001307 };
1308
1309 switch (N.getOpcode()) {
1310 case ISD::Constant: {
1311 if (N.getValueType() != MVT::i32)
1312 return false;
1313 int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1314 if (!IsAligned(V))
1315 return false;
1316 R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1317 return true;
1318 }
1319 case HexagonISD::JT:
1320 case HexagonISD::CP:
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001321 // These are assumed to always be aligned at least 8-byte boundary.
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001322 if (LogAlign > 3)
1323 return false;
1324 R = N.getOperand(0);
1325 return true;
1326 case ISD::ExternalSymbol:
1327 // Symbols may be aligned at any boundary.
1328 if (LogAlign > 0)
1329 return false;
1330 R = N;
1331 return true;
1332 case ISD::BlockAddress:
Hiroshi Inoue0909ca12018-01-26 08:15:29 +00001333 // Block address is always aligned at least 4-byte boundary.
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001334 if (LogAlign > 2 || !IsAligned(cast<BlockAddressSDNode>(N)->getOffset()))
1335 return false;
1336 R = N;
1337 return true;
1338 }
1339
1340 if (SelectGlobalAddress(N, R, false, LogAlign) ||
1341 SelectGlobalAddress(N, R, true, LogAlign))
1342 return true;
1343
1344 return false;
Colin LeMahieu51491352015-02-04 22:36:28 +00001345}
1346
Colin LeMahieu987b0942015-02-04 20:38:01 +00001347bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001348 bool UseGP, uint32_t LogAlign) {
1349 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
Simon Pilgrimcb028c72017-10-21 17:23:04 +00001350 return alignTo(V, (uint64_t)1 << LogAlign) == V;
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001351 };
1352
Colin LeMahieu987b0942015-02-04 20:38:01 +00001353 switch (N.getOpcode()) {
1354 case ISD::ADD: {
1355 SDValue N0 = N.getOperand(0);
1356 SDValue N1 = N.getOperand(1);
1357 unsigned GAOpc = N0.getOpcode();
1358 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1359 return false;
1360 if (!UseGP && GAOpc != HexagonISD::CONST32)
1361 return false;
1362 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1363 SDValue Addr = N0.getOperand(0);
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001364 // For the purpose of alignment, sextvalue and zextvalue are the same.
1365 if (!IsAligned(Const->getZExtValue()))
1366 return false;
Colin LeMahieu987b0942015-02-04 20:38:01 +00001367 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1368 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1369 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1370 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1371 N.getValueType(), NewOff);
1372 return true;
1373 }
1374 }
1375 }
1376 break;
1377 }
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001378 case HexagonISD::CP:
1379 case HexagonISD::JT:
Colin LeMahieu987b0942015-02-04 20:38:01 +00001380 case HexagonISD::CONST32:
1381 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1382 // want in the instruction.
1383 if (!UseGP)
1384 R = N.getOperand(0);
1385 return !UseGP;
1386 case HexagonISD::CONST32_GP:
1387 if (UseGP)
1388 R = N.getOperand(0);
1389 return UseGP;
1390 default:
1391 return false;
1392 }
1393
1394 return false;
1395}
1396
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001397bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1398 // This (complex pattern) function is meant to detect a sign-extension
1399 // i32->i64 on a per-operand basis. This would allow writing single
1400 // patterns that would cover a number of combinations of different ways
1401 // a sign-extensions could be written. For example:
1402 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1403 // could match either one of these:
1404 // (mul (sext x) (sext_inreg y))
1405 // (mul (sext-load *p) (sext_inreg y))
1406 // (mul (sext_inreg x) (sext y))
1407 // etc.
1408 //
1409 // The returned value will have type i64 and its low word will
1410 // contain the value being extended. The high bits are not specified.
1411 // The returned type is i64 because the original type of N was i64,
1412 // but the users of this function should only use the low-word of the
1413 // result, e.g.
1414 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1415
1416 if (N.getValueType() != MVT::i64)
1417 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001418 unsigned Opc = N.getOpcode();
1419 switch (Opc) {
1420 case ISD::SIGN_EXTEND:
1421 case ISD::SIGN_EXTEND_INREG: {
1422 // sext_inreg has the source type as a separate operand.
1423 EVT T = Opc == ISD::SIGN_EXTEND
1424 ? N.getOperand(0).getValueType()
1425 : cast<VTSDNode>(N.getOperand(1))->getVT();
Krzysztof Parzyszek2373f8f2018-02-27 22:44:41 +00001426 unsigned SW = T.getSizeInBits();
1427 if (SW == 32)
1428 R = N.getOperand(0);
1429 else if (SW < 32)
1430 R = N;
1431 else
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001432 return false;
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001433 break;
1434 }
1435 case ISD::LOAD: {
1436 LoadSDNode *L = cast<LoadSDNode>(N);
1437 if (L->getExtensionType() != ISD::SEXTLOAD)
1438 return false;
1439 // All extending loads extend to i32, so even if the value in
1440 // memory is shorter than 32 bits, it will be i32 after the load.
1441 if (L->getMemoryVT().getSizeInBits() > 32)
1442 return false;
1443 R = N;
1444 break;
1445 }
Krzysztof Parzyszek2373f8f2018-02-27 22:44:41 +00001446 case ISD::SRA: {
1447 auto *S = dyn_cast<ConstantSDNode>(N.getOperand(1));
1448 if (!S || S->getZExtValue() != 32)
1449 return false;
1450 R = N;
1451 break;
1452 }
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001453 default:
1454 return false;
1455 }
1456 EVT RT = R.getValueType();
1457 if (RT == MVT::i64)
1458 return true;
1459 assert(RT == MVT::i32);
1460 // This is only to produce a value of type i64. Do not rely on the
1461 // high bits produced by this.
1462 const SDLoc &dl(N);
1463 SDValue Ops[] = {
1464 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1465 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1466 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1467 };
1468 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1469 MVT::i64, Ops);
1470 R = SDValue(T, 0);
1471 return true;
1472}
1473
1474bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1475 SDValue &Src) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001476 unsigned Opc = Val.getOpcode();
1477 switch (Opc) {
1478 case ISD::SIGN_EXTEND:
1479 case ISD::ZERO_EXTEND:
1480 case ISD::ANY_EXTEND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001481 const SDValue &Op0 = Val.getOperand(0);
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001482 EVT T = Op0.getValueType();
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001483 if (T.isInteger() && T.getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001484 Src = Op0;
1485 return true;
1486 }
1487 break;
1488 }
1489 case ISD::SIGN_EXTEND_INREG:
1490 case ISD::AssertSext:
1491 case ISD::AssertZext:
1492 if (Val.getOperand(0).getValueType().isInteger()) {
1493 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001494 if (T->getVT().getSizeInBits() == NumBits) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001495 Src = Val.getOperand(0);
1496 return true;
1497 }
1498 }
1499 break;
1500 case ISD::AND: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001501 // Check if this is an AND with NumBits of lower bits set to 1.
1502 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001504 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001505 Src = Val.getOperand(1);
1506 return true;
1507 }
1508 }
1509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001510 if (C->getZExtValue() == Mask) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001511 Src = Val.getOperand(0);
1512 return true;
1513 }
1514 }
1515 break;
1516 }
1517 case ISD::OR:
1518 case ISD::XOR: {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001519 // OR/XOR with the lower NumBits bits set to 0.
1520 uint64_t Mask = (1 << NumBits) - 1;
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001522 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001523 Src = Val.getOperand(1);
1524 return true;
1525 }
1526 }
1527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
Krzysztof Parzyszekef580172017-05-30 17:47:51 +00001528 if ((C->getZExtValue() & Mask) == 0) {
Colin LeMahieu0ee02fc2015-01-19 20:31:18 +00001529 Src = Val.getOperand(0);
1530 return true;
1531 }
1532 }
1533 }
1534 default:
1535 break;
1536 }
1537 return false;
1538}
Krzysztof Parzyszek2d65ea72016-03-28 15:43:03 +00001539
1540bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1541 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1542}
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001543
Krzysztof Parzyszekb3a8d202017-06-13 17:10:16 +00001544bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1545 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1546 switch (N->getMemoryVT().getStoreSize()) {
1547 case 1:
1548 return StackSize <= 56; // 1*2^6 - 8
1549 case 2:
1550 return StackSize <= 120; // 2*2^6 - 8
1551 case 4:
1552 return StackSize <= 248; // 4*2^6 - 8
1553 default:
1554 return false;
1555 }
1556}
1557
Krzysztof Parzyszek2839b292016-11-05 21:44:50 +00001558// Return true when the given node fits in a positive half word.
1559bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1560 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1561 int64_t V = CN->getSExtValue();
1562 return V > 0 && isInt<16>(V);
1563 }
1564 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1565 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1566 return VN->getVT().getSizeInBits() <= 16;
1567 }
1568 return false;
1569}
1570
Krzysztof Parzyszek64e5d7d2017-10-20 19:33:12 +00001571bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1572 return !CheckSingleUse || N->hasOneUse();
1573}
1574
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001575////////////////////////////////////////////////////////////////////////////////
1576// Rebalancing of address calculation trees
1577
1578static bool isOpcodeHandled(const SDNode *N) {
1579 switch (N->getOpcode()) {
1580 case ISD::ADD:
1581 case ISD::MUL:
1582 return true;
1583 case ISD::SHL:
1584 // We only handle constant shifts because these can be easily flattened
1585 // into multiplications by 2^Op1.
1586 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1587 default:
1588 return false;
1589 }
1590}
1591
1592/// \brief Return the weight of an SDNode
1593int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1594 if (!isOpcodeHandled(N))
1595 return 1;
1596 assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1597 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1598 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1599 return RootWeights[N];
1600}
1601
1602int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1603 if (!isOpcodeHandled(N))
1604 return 0;
1605 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1606 "Cannot query height of unvisited/RAUW'd node!");
1607 return RootHeights[N];
1608}
1609
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001610namespace {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001611struct WeightedLeaf {
1612 SDValue Value;
1613 int Weight;
1614 int InsertionOrder;
1615
1616 WeightedLeaf() : Value(SDValue()) { }
1617
1618 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1619 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1620 assert(Weight >= 0 && "Weight must be >= 0");
1621 }
1622
1623 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1624 assert(A.Value.getNode() && B.Value.getNode());
1625 return A.Weight == B.Weight ?
1626 (A.InsertionOrder > B.InsertionOrder) :
1627 (A.Weight > B.Weight);
1628 }
1629};
1630
1631/// A specialized priority queue for WeigthedLeaves. It automatically folds
1632/// constants and allows removal of non-top elements while maintaining the
1633/// priority order.
1634class LeafPrioQueue {
1635 SmallVector<WeightedLeaf, 8> Q;
1636 bool HaveConst;
1637 WeightedLeaf ConstElt;
1638 unsigned Opcode;
1639
1640public:
1641 bool empty() {
1642 return (!HaveConst && Q.empty());
1643 }
1644
1645 size_t size() {
1646 return Q.size() + HaveConst;
1647 }
1648
1649 bool hasConst() {
1650 return HaveConst;
1651 }
1652
1653 const WeightedLeaf &top() {
1654 if (HaveConst)
1655 return ConstElt;
1656 return Q.front();
1657 }
1658
1659 WeightedLeaf pop() {
1660 if (HaveConst) {
1661 HaveConst = false;
1662 return ConstElt;
1663 }
1664 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1665 return Q.pop_back_val();
1666 }
1667
1668 void push(WeightedLeaf L, bool SeparateConst=true) {
1669 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1670 if (Opcode == ISD::MUL &&
1671 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1672 return;
1673 if (Opcode == ISD::ADD &&
1674 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1675 return;
1676
1677 HaveConst = true;
1678 ConstElt = L;
1679 } else {
1680 Q.push_back(L);
1681 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1682 }
1683 }
1684
1685 /// Push L to the bottom of the queue regardless of its weight. If L is
1686 /// constant, it will not be folded with other constants in the queue.
1687 void pushToBottom(WeightedLeaf L) {
1688 L.Weight = 1000;
1689 push(L, false);
1690 }
1691
1692 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1693 /// lowest weight and remove it from the queue.
1694 WeightedLeaf findSHL(uint64_t MaxAmount);
1695
1696 WeightedLeaf findMULbyConst();
1697
1698 LeafPrioQueue(unsigned Opcode) :
1699 HaveConst(false), Opcode(Opcode) { }
1700};
Benjamin Kramerb7d33112016-08-06 11:13:10 +00001701} // end anonymous namespace
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001702
1703WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1704 int ResultPos;
1705 WeightedLeaf Result;
1706
1707 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1708 const WeightedLeaf &L = Q[Pos];
1709 const SDValue &Val = L.Value;
1710 if (Val.getOpcode() != ISD::SHL ||
1711 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1712 Val.getConstantOperandVal(1) > MaxAmount)
1713 continue;
1714 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1715 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1716 {
1717 Result = L;
1718 ResultPos = Pos;
1719 }
1720 }
1721
1722 if (Result.Value.getNode()) {
1723 Q.erase(&Q[ResultPos]);
1724 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1725 }
1726
1727 return Result;
1728}
1729
1730WeightedLeaf LeafPrioQueue::findMULbyConst() {
1731 int ResultPos;
1732 WeightedLeaf Result;
1733
1734 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1735 const WeightedLeaf &L = Q[Pos];
1736 const SDValue &Val = L.Value;
1737 if (Val.getOpcode() != ISD::MUL ||
1738 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1739 Val.getConstantOperandVal(1) > 127)
1740 continue;
1741 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1742 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1743 {
1744 Result = L;
1745 ResultPos = Pos;
1746 }
1747 }
1748
1749 if (Result.Value.getNode()) {
1750 Q.erase(&Q[ResultPos]);
1751 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1752 }
1753
1754 return Result;
1755}
1756
1757SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
Simon Pilgrim7c858622016-07-29 18:43:59 +00001758 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001759 return CurDAG->getConstant(MulFactor, SDLoc(N),
1760 N->getOperand(1).getValueType());
1761}
1762
1763/// @returns the value x for which 2^x is a factor of Val
1764static unsigned getPowerOf2Factor(SDValue Val) {
1765 if (Val.getOpcode() == ISD::MUL) {
1766 unsigned MaxFactor = 0;
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001767 for (int i = 0; i < 2; ++i) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001768 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1769 if (!C)
1770 continue;
1771 const APInt &CInt = C->getAPIntValue();
1772 if (CInt.getBoolValue())
1773 MaxFactor = CInt.countTrailingZeros();
1774 }
1775 return MaxFactor;
1776 }
1777 if (Val.getOpcode() == ISD::SHL) {
1778 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1779 return 0;
1780 return (unsigned) Val.getConstantOperandVal(1);
1781 }
1782
1783 return 0;
1784}
1785
1786/// @returns true if V>>Amount will eliminate V's operation on its child
1787static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1788 if (V.getOpcode() == ISD::MUL) {
1789 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001790 for (int i = 0; i < 2; ++i)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001791 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00001792 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001793 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1794 return (NewConst == 1);
1795 }
1796 } else if (V.getOpcode() == ISD::SHL) {
1797 return (Amount == V.getConstantOperandVal(1));
1798 }
1799
1800 return false;
1801}
1802
1803SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1804 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1805 if (V.getOpcode() == ISD::MUL) {
1806 for (int i=0; i < 2; ++i) {
1807 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1808 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1809 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1810 if (NewConst == 1)
1811 return Ops[!i];
1812 Ops[i] = CurDAG->getConstant(NewConst,
1813 SDLoc(V), V.getValueType());
1814 break;
1815 }
1816 }
1817 } else if (V.getOpcode() == ISD::SHL) {
1818 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1819 if (ShiftAmount == Power)
1820 return Ops[0];
1821 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1822 SDLoc(V), V.getValueType());
1823 }
1824
1825 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1826}
1827
1828static bool isTargetConstant(const SDValue &V) {
1829 return V.getOpcode() == HexagonISD::CONST32 ||
1830 V.getOpcode() == HexagonISD::CONST32_GP;
1831}
1832
1833unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1834 if (GAUsesInFunction.count(V))
1835 return GAUsesInFunction[V];
1836
1837 unsigned Result = 0;
Matthias Braunf1caa282017-12-15 22:22:58 +00001838 const Function &CurF = CurDAG->getMachineFunction().getFunction();
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001839 for (const User *U : V->users()) {
1840 if (isa<Instruction>(U) &&
Matthias Braunf1caa282017-12-15 22:22:58 +00001841 cast<Instruction>(U)->getParent()->getParent() == &CurF)
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00001842 ++Result;
1843 }
1844
1845 GAUsesInFunction[V] = Result;
1846
1847 return Result;
1848}
1849
1850/// Note - After calling this, N may be dead. It may have been replaced by a
1851/// new node, so always use the returned value in place of N.
1852///
1853/// @returns The SDValue taking the place of N (which could be N if it is
1854/// unchanged)
1855SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1856 assert(RootWeights.count(N) && "Cannot balance non-root node.");
1857 assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1858 assert(!TopLevel || N->getOpcode() == ISD::ADD);
1859
1860 // Return early if this node was already visited
1861 if (RootWeights[N] != -1)
1862 return SDValue(N, 0);
1863
1864 assert(isOpcodeHandled(N));
1865
1866 SDValue Op0 = N->getOperand(0);
1867 SDValue Op1 = N->getOperand(1);
1868
1869 // Return early if the operands will remain unchanged or are all roots
1870 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1871 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1872 SDNode *Op0N = Op0.getNode();
1873 int Weight;
1874 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1875 Weight = getWeight(balanceSubTree(Op0N).getNode());
1876 // Weight = calculateWeight(Op0N);
1877 } else
1878 Weight = getWeight(Op0N);
1879
1880 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1881 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1882 Weight += getWeight(balanceSubTree(Op1N).getNode());
1883 // Weight += calculateWeight(Op1N);
1884 } else
1885 Weight += getWeight(Op1N);
1886
1887 RootWeights[N] = Weight;
1888 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1889 getHeight(N->getOperand(1).getNode())) + 1;
1890
1891 DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1892 << " Height=" << RootHeights[N] << "): ");
1893 DEBUG(N->dump());
1894
1895 return SDValue(N, 0);
1896 }
1897
1898 DEBUG(dbgs() << "** Balancing root node: ");
1899 DEBUG(N->dump());
1900
1901 unsigned NOpcode = N->getOpcode();
1902
1903 LeafPrioQueue Leaves(NOpcode);
1904 SmallVector<SDValue, 4> Worklist;
1905 Worklist.push_back(SDValue(N, 0));
1906
1907 // SHL nodes will be converted to MUL nodes
1908 if (NOpcode == ISD::SHL)
1909 NOpcode = ISD::MUL;
1910
1911 bool CanFactorize = false;
1912 WeightedLeaf Mul1, Mul2;
1913 unsigned MaxPowerOf2 = 0;
1914 WeightedLeaf GA;
1915
1916 // Do not try to factor out a shift if there is already a shift at the tip of
1917 // the tree.
1918 bool HaveTopLevelShift = false;
1919 if (TopLevel &&
1920 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1921 Op0.getConstantOperandVal(1) < 4) ||
1922 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1923 Op1.getConstantOperandVal(1) < 4)))
1924 HaveTopLevelShift = true;
1925
1926 // Flatten the subtree into an ordered list of leaves; at the same time
1927 // determine whether the tree is already balanced.
1928 int InsertionOrder = 0;
1929 SmallDenseMap<SDValue, int> NodeHeights;
1930 bool Imbalanced = false;
1931 int CurrentWeight = 0;
1932 while (!Worklist.empty()) {
1933 SDValue Child = Worklist.pop_back_val();
1934
1935 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1936 // CASE 1: Child is a root note
1937
1938 int Weight = RootWeights[Child.getNode()];
1939 if (Weight == -1) {
1940 Child = balanceSubTree(Child.getNode());
1941 // calculateWeight(Child.getNode());
1942 Weight = getWeight(Child.getNode());
1943 } else if (Weight == -2) {
1944 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1945 // made. Our worklist isn't up to date anymore.
1946 // Restart the whole process.
1947 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
1948 return balanceSubTree(N, TopLevel);
1949 }
1950
1951 NodeHeights[Child] = 1;
1952 CurrentWeight += Weight;
1953
1954 unsigned PowerOf2;
1955 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
1956 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
1957 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
1958 // Try to identify two factorizable MUL/SHL children greedily. Leave
1959 // them out of the priority queue for now so we can deal with them
1960 // after.
1961 if (!Mul1.Value.getNode()) {
1962 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
1963 MaxPowerOf2 = PowerOf2;
1964 } else {
1965 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
1966 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
1967
1968 // Our addressing modes can only shift by a maximum of 3
1969 if (MaxPowerOf2 > 3)
1970 MaxPowerOf2 = 3;
1971
1972 CanFactorize = true;
1973 }
1974 } else
1975 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1976 } else if (!isOpcodeHandled(Child.getNode())) {
1977 // CASE 2: Child is an unhandled kind of node (e.g. constant)
1978 int Weight = getWeight(Child.getNode());
1979
1980 NodeHeights[Child] = getHeight(Child.getNode());
1981 CurrentWeight += Weight;
1982
1983 if (isTargetConstant(Child) && !GA.Value.getNode())
1984 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
1985 else
1986 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
1987 } else {
1988 // CASE 3: Child is a subtree of same opcode
1989 // Visit children first, then flatten.
1990 unsigned ChildOpcode = Child.getOpcode();
1991 assert(ChildOpcode == NOpcode ||
1992 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
1993
1994 // Convert SHL to MUL
1995 SDValue Op1;
1996 if (ChildOpcode == ISD::SHL)
1997 Op1 = getMultiplierForSHL(Child.getNode());
1998 else
1999 Op1 = Child->getOperand(1);
2000
2001 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
2002 assert(!NodeHeights.count(Child) && "Parent visited before children?");
2003 // Visit children first, then re-visit this node
2004 Worklist.push_back(Child);
2005 Worklist.push_back(Op1);
2006 Worklist.push_back(Child->getOperand(0));
2007 } else {
2008 // Back at this node after visiting the children
2009 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
2010 Imbalanced = true;
2011
2012 NodeHeights[Child] = std::max(NodeHeights[Op1],
2013 NodeHeights[Child->getOperand(0)]) + 1;
2014 }
2015 }
2016 }
2017
2018 DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
2019 << " weight=" << CurrentWeight << " imbalanced="
2020 << Imbalanced << "\n");
2021
2022 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
2023 // This factors out a shift in order to match memw(a<<Y+b).
2024 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
2025 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
2026 DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
2027 int Weight = Mul1.Weight + Mul2.Weight;
2028 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
2029 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
2030 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
2031 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
2032 Mul1Factored, Mul2Factored);
2033 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
2034 Mul1.Value.getValueType());
2035 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
2036 Sum, Const);
2037 NodeHeights[New] = Height;
2038 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
2039 } else if (Mul1.Value.getNode()) {
2040 // We failed to factorize two MULs, so now the Muls are left outside the
2041 // queue... add them back.
2042 Leaves.push(Mul1);
2043 if (Mul2.Value.getNode())
2044 Leaves.push(Mul2);
2045 CanFactorize = false;
2046 }
2047
2048 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
2049 // and the root node itself is not used more than twice. This reduces the
2050 // amount of additional constant extenders introduced by this optimization.
2051 bool CombinedGA = false;
2052 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
2053 GA.Value.hasOneUse() && N->use_size() < 3) {
2054 GlobalAddressSDNode *GANode =
2055 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
2056 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
2057
2058 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
2059 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
2060 DEBUG(dbgs() << "--> Combining GA and offset (" << Offset->getSExtValue()
2061 << "): ");
2062 DEBUG(GANode->dump());
2063
2064 SDValue NewTGA =
2065 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
2066 GANode->getValueType(0),
2067 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
2068 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
2069 GA.Value.getValueType(), NewTGA);
2070 GA.Weight += Leaves.top().Weight;
2071
2072 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
2073 CombinedGA = true;
2074
2075 Leaves.pop(); // Remove the offset constant from the queue
2076 }
2077 }
2078
2079 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
2080 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
2081 RootWeights[N] = CurrentWeight;
2082 RootHeights[N] = NodeHeights[SDValue(N, 0)];
2083
2084 return SDValue(N, 0);
2085 }
2086
2087 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
2088 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
2089 WeightedLeaf SHL = Leaves.findSHL(31);
2090 if (SHL.Value.getNode()) {
2091 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2092 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2093 GA.Value.getValueType(),
2094 GA.Value, SHL.Value);
2095 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2096 NodeHeights[GA.Value] = Height;
2097 }
2098 }
2099
2100 if (GA.Value.getNode())
2101 Leaves.push(GA);
2102
2103 // If this is the top level and we haven't factored out a shift, we should try
2104 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2105 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2106 DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2107 Leaves.pushToBottom(Leaves.pop());
2108 }
2109
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002110 const DataLayout &DL = CurDAG->getDataLayout();
2111 const TargetLowering &TLI = *getTargetLowering();
2112
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002113 // Rebuild the tree using Huffman's algorithm
2114 while (Leaves.size() > 1) {
2115 WeightedLeaf L0 = Leaves.pop();
2116
2117 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2118 // otherwise just get the next leaf
2119 WeightedLeaf L1 = Leaves.findMULbyConst();
2120 if (!L1.Value.getNode())
2121 L1 = Leaves.pop();
2122
2123 assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2124
2125 SDValue V0 = L0.Value;
2126 int V0Weight = L0.Weight;
2127 SDValue V1 = L1.Value;
2128 int V1Weight = L1.Weight;
2129
2130 // Make sure that none of these nodes have been RAUW'd
2131 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2132 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2133 DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2134 return balanceSubTree(N, TopLevel);
2135 }
2136
2137 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2138 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2139 EVT VT = N->getValueType(0);
2140 SDValue NewNode;
2141
2142 if (V0C && !V1C) {
2143 std::swap(V0, V1);
2144 std::swap(V0C, V1C);
2145 }
2146
2147 // Calculate height of this node
2148 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2149 "Children must have been visited before re-combining them!");
2150 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2151
2152 // Rebuild this node (and restore SHL from MUL if needed)
2153 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2154 NewNode = CurDAG->getNode(
2155 ISD::SHL, SDLoc(V0), VT, V0,
2156 CurDAG->getConstant(
2157 V1C->getAPIntValue().logBase2(), SDLoc(N),
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002158 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002159 else
2160 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2161
2162 NodeHeights[NewNode] = Height;
2163
2164 int Weight = V0Weight + V1Weight;
2165 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2166
2167 DEBUG(dbgs() << "--> Built new node (Weight=" << Weight << ",Height="
2168 << Height << "):\n");
2169 DEBUG(NewNode.dump());
2170 }
2171
2172 assert(Leaves.size() == 1);
2173 SDValue NewRoot = Leaves.top().Value;
2174
2175 assert(NodeHeights.count(NewRoot));
2176 int Height = NodeHeights[NewRoot];
2177
2178 // Restore SHL if we earlier converted it to a MUL
2179 if (NewRoot.getOpcode() == ISD::MUL) {
2180 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2181 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2182 EVT VT = NewRoot.getValueType();
2183 SDValue V0 = NewRoot.getOperand(0);
2184 NewRoot = CurDAG->getNode(
2185 ISD::SHL, SDLoc(NewRoot), VT, V0,
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002186 CurDAG->getConstant(
2187 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2188 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002189 }
2190 }
2191
2192 if (N != NewRoot.getNode()) {
2193 DEBUG(dbgs() << "--> Root is now: ");
2194 DEBUG(NewRoot.dump());
2195
2196 // Replace all uses of old root by new root
2197 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2198 // Mark that we have RAUW'd N
2199 RootWeights[N] = -2;
2200 } else {
2201 DEBUG(dbgs() << "--> Root unchanged.\n");
2202 }
2203
2204 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2205 RootHeights[NewRoot.getNode()] = Height;
2206
2207 return NewRoot;
2208}
2209
2210void HexagonDAGToDAGISel::rebalanceAddressTrees() {
Krzysztof Parzyszek317d42c2016-08-01 20:31:50 +00002211 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
Krzysztof Parzyszek0006e1a2016-07-29 15:15:35 +00002212 SDNode *N = &*I++;
2213 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2214 continue;
2215
2216 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2217 if (BasePtr.getOpcode() != ISD::ADD)
2218 continue;
2219
2220 // We've already processed this node
2221 if (RootWeights.count(BasePtr.getNode()))
2222 continue;
2223
2224 DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2225 DEBUG(N->dump());
2226
2227 // FindRoots
2228 SmallVector<SDNode *, 4> Worklist;
2229
2230 Worklist.push_back(BasePtr.getOperand(0).getNode());
2231 Worklist.push_back(BasePtr.getOperand(1).getNode());
2232
2233 while (!Worklist.empty()) {
2234 SDNode *N = Worklist.pop_back_val();
2235 unsigned Opcode = N->getOpcode();
2236
2237 if (!isOpcodeHandled(N))
2238 continue;
2239
2240 Worklist.push_back(N->getOperand(0).getNode());
2241 Worklist.push_back(N->getOperand(1).getNode());
2242
2243 // Not a root if it has only one use and same opcode as its parent
2244 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2245 continue;
2246
2247 // This root node has already been processed
2248 if (RootWeights.count(N))
2249 continue;
2250
2251 RootWeights[N] = -1;
2252 }
2253
2254 // Balance node itself
2255 RootWeights[BasePtr.getNode()] = -1;
2256 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2257
2258 if (N->getOpcode() == ISD::LOAD)
2259 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2260 NewBasePtr, N->getOperand(2));
2261 else
2262 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2263 NewBasePtr, N->getOperand(3));
2264
2265 DEBUG(dbgs() << "--> Final node: ");
2266 DEBUG(N->dump());
2267 }
2268
2269 CurDAG->RemoveDeadNodes();
2270 GAUsesInFunction.clear();
2271 RootHeights.clear();
2272 RootWeights.clear();
2273}