1//===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an instruction selector for the Hexagon target.
10//
11//===----------------------------------------------------------------------===//
12
13#include "HexagonISelDAGToDAG.h"
14#include "Hexagon.h"
15#include "HexagonISelLowering.h"
16#include "HexagonMachineFunctionInfo.h"
17#include "HexagonTargetMachine.h"
18#include "llvm/CodeGen/FunctionLoweringInfo.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/SelectionDAGISel.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/IntrinsicsHexagon.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
25using namespace llvm;
26
27#define DEBUG_TYPE "hexagon-isel"
28#define PASS_NAME "Hexagon DAG->DAG Pattern Instruction Selection"
29
30static
31cl::opt<bool>
32EnableAddressRebalancing("isel-rebalance-addr", cl::Hidden, cl::init(true),
33  cl::desc("Rebalance address calculation trees to improve "
34          "instruction selection"));
35
36// Rebalance only if this allows e.g. combining a GA with an offset or
37// factoring out a shift.
38static
39cl::opt<bool>
40RebalanceOnlyForOptimizations("rebalance-only-opt", cl::Hidden, cl::init(false),
41  cl::desc("Rebalance address tree only if this allows optimizations"));
42
43static
44cl::opt<bool>
45RebalanceOnlyImbalancedTrees("rebalance-only-imbal", cl::Hidden,
46  cl::init(false), cl::desc("Rebalance address tree only if it is imbalanced"));
47
48static cl::opt<bool> CheckSingleUse("hexagon-isel-su", cl::Hidden,
49  cl::init(true), cl::desc("Enable checking of SDNode's single-use status"));
50
51//===----------------------------------------------------------------------===//
52// Instruction Selector Implementation
53//===----------------------------------------------------------------------===//
54
55#define GET_DAGISEL_BODY HexagonDAGToDAGISel
56#include "HexagonGenDAGISel.inc"
57
58namespace llvm {
59/// createHexagonISelDag - This pass converts a legalized DAG into a
60/// Hexagon-specific DAG, ready for instruction scheduling.
61FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
62                                   CodeGenOptLevel OptLevel) {
63  return new HexagonDAGToDAGISel(TM, OptLevel);
64}
65}
66
67char HexagonDAGToDAGISel::ID = 0;
68
69INITIALIZE_PASS(HexagonDAGToDAGISel, DEBUG_TYPE, PASS_NAME, false, false)
70
71void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
72  SDValue Chain = LD->getChain();
73  SDValue Base = LD->getBasePtr();
74  SDValue Offset = LD->getOffset();
75  int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
76  EVT LoadedVT = LD->getMemoryVT();
77  unsigned Opcode = 0;
78
79  // Check for zero extended loads. Treat any-extend loads as zero extended
80  // loads.
81  ISD::LoadExtType ExtType = LD->getExtensionType();
82  bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
83  bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
84
85  assert(LoadedVT.isSimple());
86  switch (LoadedVT.getSimpleVT().SimpleTy) {
87  case MVT::i8:
88    if (IsZeroExt)
89      Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
90    else
91      Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
92    break;
93  case MVT::i16:
94    if (IsZeroExt)
95      Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
96    else
97      Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
98    break;
99  case MVT::i32:
100  case MVT::f32:
101  case MVT::v2i16:
102  case MVT::v4i8:
103    Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
104    break;
105  case MVT::i64:
106  case MVT::f64:
107  case MVT::v2i32:
108  case MVT::v4i16:
109  case MVT::v8i8:
110    Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
111    break;
112  case MVT::v64i8:
113  case MVT::v32i16:
114  case MVT::v16i32:
115  case MVT::v8i64:
116  case MVT::v128i8:
117  case MVT::v64i16:
118  case MVT::v32i32:
119  case MVT::v16i64:
120    if (isAlignedMemNode(LD)) {
121      if (LD->isNonTemporal())
122        Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
123      else
124        Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
125    } else {
126      Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
127    }
128    break;
129  default:
130    llvm_unreachable("Unexpected memory type in indexed load");
131  }
132
133  SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
134  MachineMemOperand *MemOp = LD->getMemOperand();
135
136  auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
137        -> MachineSDNode* {
138    if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
139      SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
140      return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
141                                    Zero, SDValue(N, 0));
142    }
143    if (ExtType == ISD::SEXTLOAD)
144      return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
145                                    SDValue(N, 0));
146    return N;
147  };
148
149  //                  Loaded value   Next address   Chain
150  SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
151  SDValue To[3];
152
153  EVT ValueVT = LD->getValueType(0);
154  if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
155    // A load extending to i64 will actually produce i32, which will then
156    // need to be extended to i64.
157    assert(LoadedVT.getSizeInBits() <= 32);
158    ValueVT = MVT::i32;
159  }
160
161  if (IsValidInc) {
162    MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
163                                              MVT::i32, MVT::Other, Base,
164                                              IncV, Chain);
165    CurDAG->setNodeMemRefs(L, {MemOp});
166    To[1] = SDValue(L, 1); // Next address.
167    To[2] = SDValue(L, 2); // Chain.
168    // Handle special case for extension to i64.
169    if (LD->getValueType(0) == MVT::i64)
170      L = getExt64(L, dl);
171    To[0] = SDValue(L, 0); // Loaded (extended) value.
172  } else {
173    SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
174    MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
175                                              Base, Zero, Chain);
176    CurDAG->setNodeMemRefs(L, {MemOp});
177    To[2] = SDValue(L, 1); // Chain.
178    MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
179                                              Base, IncV);
180    To[1] = SDValue(A, 0); // Next address.
181    // Handle special case for extension to i64.
182    if (LD->getValueType(0) == MVT::i64)
183      L = getExt64(L, dl);
184    To[0] = SDValue(L, 0); // Loaded (extended) value.
185  }
186  ReplaceUses(From, To, 3);
187  CurDAG->RemoveDeadNode(LD);
188}
189
190MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
191  if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
192    return nullptr;
193
194  SDLoc dl(IntN);
195  unsigned IntNo = IntN->getConstantOperandVal(1);
196
197  static std::map<unsigned,unsigned> LoadPciMap = {
198    { Intrinsic::hexagon_circ_ldb,  Hexagon::L2_loadrb_pci  },
199    { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
200    { Intrinsic::hexagon_circ_ldh,  Hexagon::L2_loadrh_pci  },
201    { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
202    { Intrinsic::hexagon_circ_ldw,  Hexagon::L2_loadri_pci  },
203    { Intrinsic::hexagon_circ_ldd,  Hexagon::L2_loadrd_pci  },
204  };
205  auto FLC = LoadPciMap.find(IntNo);
206  if (FLC != LoadPciMap.end()) {
207    EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
208    EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
209    // Operands: { Base, Increment, Modifier, Chain }
210    auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
211    SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
212    MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
213          { IntN->getOperand(2), I, IntN->getOperand(4),
214            IntN->getOperand(0) });
215    return Res;
216  }
217
218  return nullptr;
219}
220
221SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
222      SDNode *IntN) {
223  // The "LoadN" is just a machine load instruction. The intrinsic also
224  // involves storing it. Generate an appropriate store to the location
225  // given in the intrinsic's operand(3).
226  uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
227  unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
228                      HexagonII::MemAccesSizeMask;
229  unsigned Size = 1U << (SizeBits-1);
230
231  SDLoc dl(IntN);
232  MachinePointerInfo PI;
233  SDValue TS;
234  SDValue Loc = IntN->getOperand(3);
235
236  if (Size >= 4)
237    TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
238                          Align(Size));
239  else
240    TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
241                               PI, MVT::getIntegerVT(Size * 8), Align(Size));
242
243  SDNode *StoreN;
244  {
245    HandleSDNode Handle(TS);
246    SelectStore(TS.getNode());
247    StoreN = Handle.getValue().getNode();
248  }
249
250  // Load's results are { Loaded value, Updated pointer, Chain }
251  ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
252  ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
253  return StoreN;
254}
255
256bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
257  // The intrinsics for load circ/brev perform two operations:
258  // 1. Load a value V from the specified location, using the addressing
259  //    mode corresponding to the intrinsic.
260  // 2. Store V into a specified location. This location is typically a
261  //    local, temporary object.
262  // In many cases, the program using these intrinsics will immediately
263  // load V again from the local object. In those cases, when certain
264  // conditions are met, the last load can be removed.
265  // This function identifies and optimizes this pattern. If the pattern
266  // cannot be optimized, it returns nullptr, which will cause the load
267  // to be selected separately from the intrinsic (which will be handled
268  // in SelectIntrinsicWChain).
269
270  SDValue Ch = N->getOperand(0);
271  SDValue Loc = N->getOperand(1);
272
273  // Assume that the load and the intrinsic are connected directly with a
274  // chain:
275  //   t1: i32,ch = int.load ..., ..., ..., Loc, ...    // <-- C
276  //   t2: i32,ch = load t1:1, Loc, ...
277  SDNode *C = Ch.getNode();
278
279  if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
280    return false;
281
282  // The second load can only be eliminated if its extension type matches
283  // that of the load instruction corresponding to the intrinsic. The user
284  // can provide an address of an unsigned variable to store the result of
285  // a sign-extending intrinsic into (or the other way around).
286  ISD::LoadExtType IntExt;
287  switch (C->getConstantOperandVal(1)) {
288  case Intrinsic::hexagon_circ_ldub:
289  case Intrinsic::hexagon_circ_lduh:
290    IntExt = ISD::ZEXTLOAD;
291    break;
292  case Intrinsic::hexagon_circ_ldw:
293  case Intrinsic::hexagon_circ_ldd:
294    IntExt = ISD::NON_EXTLOAD;
295    break;
296  default:
297    IntExt = ISD::SEXTLOAD;
298    break;
299  }
300  if (N->getExtensionType() != IntExt)
301    return false;
302
303  // Make sure the target location for the loaded value in the load intrinsic
304  // is the location from which LD (or N) is loading.
305  if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
306    return false;
307
308  if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
309    SDNode *S = StoreInstrForLoadIntrinsic(L, C);
310    SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
311    SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
312    ReplaceUses(F, T, std::size(T));
313    // This transformation will leave the intrinsic dead. If it remains in
314    // the DAG, the selection code will see it again, but without the load,
315    // and it will generate a store that is normally required for it.
316    CurDAG->RemoveDeadNode(C);
317    return true;
318  }
319  return false;
320}
321
322// Convert the bit-reverse load intrinsic to appropriate target instruction.
323bool HexagonDAGToDAGISel::SelectBrevLdIntrinsic(SDNode *IntN) {
324  if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
325    return false;
326
327  const SDLoc &dl(IntN);
328  unsigned IntNo = IntN->getConstantOperandVal(1);
329
330  static const std::map<unsigned, unsigned> LoadBrevMap = {
331    { Intrinsic::hexagon_L2_loadrb_pbr, Hexagon::L2_loadrb_pbr },
332    { Intrinsic::hexagon_L2_loadrub_pbr, Hexagon::L2_loadrub_pbr },
333    { Intrinsic::hexagon_L2_loadrh_pbr, Hexagon::L2_loadrh_pbr },
334    { Intrinsic::hexagon_L2_loadruh_pbr, Hexagon::L2_loadruh_pbr },
335    { Intrinsic::hexagon_L2_loadri_pbr, Hexagon::L2_loadri_pbr },
336    { Intrinsic::hexagon_L2_loadrd_pbr, Hexagon::L2_loadrd_pbr }
337  };
338  auto FLI = LoadBrevMap.find(IntNo);
339  if (FLI != LoadBrevMap.end()) {
340    EVT ValTy =
341        (IntNo == Intrinsic::hexagon_L2_loadrd_pbr) ? MVT::i64 : MVT::i32;
342    EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
343    // Operands of Intrinsic: {chain, enum ID of intrinsic, baseptr,
344    // modifier}.
345    // Operands of target instruction: { Base, Modifier, Chain }.
346    MachineSDNode *Res = CurDAG->getMachineNode(
347        FLI->second, dl, RTys,
348        {IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(0)});
349
350    MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(IntN)->getMemOperand();
351    CurDAG->setNodeMemRefs(Res, {MemOp});
352
353    ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
354    ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
355    ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
356    CurDAG->RemoveDeadNode(IntN);
357    return true;
358  }
359  return false;
360}
361
362/// Generate a machine instruction node for the new circular buffer intrinsics.
363/// The new versions use a CSx register instead of the K field.
364bool HexagonDAGToDAGISel::SelectNewCircIntrinsic(SDNode *IntN) {
365  if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
366    return false;
367
368  SDLoc DL(IntN);
369  unsigned IntNo = IntN->getConstantOperandVal(1);
370  SmallVector<SDValue, 7> Ops;
371
372  static std::map<unsigned,unsigned> LoadNPcMap = {
373    { Intrinsic::hexagon_L2_loadrub_pci, Hexagon::PS_loadrub_pci },
374    { Intrinsic::hexagon_L2_loadrb_pci, Hexagon::PS_loadrb_pci },
375    { Intrinsic::hexagon_L2_loadruh_pci, Hexagon::PS_loadruh_pci },
376    { Intrinsic::hexagon_L2_loadrh_pci, Hexagon::PS_loadrh_pci },
377    { Intrinsic::hexagon_L2_loadri_pci, Hexagon::PS_loadri_pci },
378    { Intrinsic::hexagon_L2_loadrd_pci, Hexagon::PS_loadrd_pci },
379    { Intrinsic::hexagon_L2_loadrub_pcr, Hexagon::PS_loadrub_pcr },
380    { Intrinsic::hexagon_L2_loadrb_pcr, Hexagon::PS_loadrb_pcr },
381    { Intrinsic::hexagon_L2_loadruh_pcr, Hexagon::PS_loadruh_pcr },
382    { Intrinsic::hexagon_L2_loadrh_pcr, Hexagon::PS_loadrh_pcr },
383    { Intrinsic::hexagon_L2_loadri_pcr, Hexagon::PS_loadri_pcr },
384    { Intrinsic::hexagon_L2_loadrd_pcr, Hexagon::PS_loadrd_pcr }
385  };
386  auto FLI = LoadNPcMap.find (IntNo);
387  if (FLI != LoadNPcMap.end()) {
388    EVT ValTy = MVT::i32;
389    if (IntNo == Intrinsic::hexagon_L2_loadrd_pci ||
390        IntNo == Intrinsic::hexagon_L2_loadrd_pcr)
391      ValTy = MVT::i64;
392    EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
393    // Handle load.*_pci case which has 6 operands.
394    if (IntN->getNumOperands() == 6) {
395      auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
396      SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
397      // Operands: { Base, Increment, Modifier, Start, Chain }.
398      Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
399              IntN->getOperand(0) };
400    } else
401      // Handle load.*_pcr case which has 5 operands.
402      // Operands: { Base, Modifier, Start, Chain }.
403      Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
404              IntN->getOperand(0) };
405    MachineSDNode *Res = CurDAG->getMachineNode(FLI->second, DL, RTys, Ops);
406    ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
407    ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
408    ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
409    CurDAG->RemoveDeadNode(IntN);
410    return true;
411  }
412
413  static std::map<unsigned,unsigned> StoreNPcMap = {
414    { Intrinsic::hexagon_S2_storerb_pci, Hexagon::PS_storerb_pci },
415    { Intrinsic::hexagon_S2_storerh_pci, Hexagon::PS_storerh_pci },
416    { Intrinsic::hexagon_S2_storerf_pci, Hexagon::PS_storerf_pci },
417    { Intrinsic::hexagon_S2_storeri_pci, Hexagon::PS_storeri_pci },
418    { Intrinsic::hexagon_S2_storerd_pci, Hexagon::PS_storerd_pci },
419    { Intrinsic::hexagon_S2_storerb_pcr, Hexagon::PS_storerb_pcr },
420    { Intrinsic::hexagon_S2_storerh_pcr, Hexagon::PS_storerh_pcr },
421    { Intrinsic::hexagon_S2_storerf_pcr, Hexagon::PS_storerf_pcr },
422    { Intrinsic::hexagon_S2_storeri_pcr, Hexagon::PS_storeri_pcr },
423    { Intrinsic::hexagon_S2_storerd_pcr, Hexagon::PS_storerd_pcr }
424  };
425  auto FSI = StoreNPcMap.find (IntNo);
426  if (FSI != StoreNPcMap.end()) {
427    EVT RTys[] = { MVT::i32, MVT::Other };
428    // Handle store.*_pci case which has 7 operands.
429    if (IntN->getNumOperands() == 7) {
430      auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
431      SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
432      // Operands: { Base, Increment, Modifier, Value, Start, Chain }.
433      Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
434              IntN->getOperand(6), IntN->getOperand(0) };
435    } else
436      // Handle store.*_pcr case which has 6 operands.
437      // Operands: { Base, Modifier, Value, Start, Chain }.
438      Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
439              IntN->getOperand(5), IntN->getOperand(0) };
440    MachineSDNode *Res = CurDAG->getMachineNode(FSI->second, DL, RTys, Ops);
441    ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
442    ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
443    CurDAG->RemoveDeadNode(IntN);
444    return true;
445  }
446
447  return false;
448}
449
450void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
451  SDLoc dl(N);
452  LoadSDNode *LD = cast<LoadSDNode>(N);
453
454  // Handle indexed loads.
455  ISD::MemIndexedMode AM = LD->getAddressingMode();
456  if (AM != ISD::UNINDEXED) {
457    SelectIndexedLoad(LD, dl);
458    return;
459  }
460
461  // Handle patterns using circ/brev load intrinsics.
462  if (tryLoadOfLoadIntrinsic(LD))
463    return;
464
465  SelectCode(LD);
466}
467
468void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
469  SDValue Chain = ST->getChain();
470  SDValue Base = ST->getBasePtr();
471  SDValue Offset = ST->getOffset();
472  SDValue Value = ST->getValue();
473  // Get the constant value.
474  int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
475  EVT StoredVT = ST->getMemoryVT();
476  EVT ValueVT = Value.getValueType();
477
478  bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
479  unsigned Opcode = 0;
480
481  assert(StoredVT.isSimple());
482  switch (StoredVT.getSimpleVT().SimpleTy) {
483  case MVT::i8:
484    Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
485    break;
486  case MVT::i16:
487    Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
488    break;
489  case MVT::i32:
490  case MVT::f32:
491  case MVT::v2i16:
492  case MVT::v4i8:
493    Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
494    break;
495  case MVT::i64:
496  case MVT::f64:
497  case MVT::v2i32:
498  case MVT::v4i16:
499  case MVT::v8i8:
500    Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
501    break;
502  case MVT::v64i8:
503  case MVT::v32i16:
504  case MVT::v16i32:
505  case MVT::v8i64:
506  case MVT::v128i8:
507  case MVT::v64i16:
508  case MVT::v32i32:
509  case MVT::v16i64:
510    if (isAlignedMemNode(ST)) {
511      if (ST->isNonTemporal())
512        Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
513      else
514        Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
515    } else {
516      Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
517    }
518    break;
519  default:
520    llvm_unreachable("Unexpected memory type in indexed store");
521  }
522
523  if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
524    assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
525    Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
526                                           dl, MVT::i32, Value);
527  }
528
529  SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
530  MachineMemOperand *MemOp = ST->getMemOperand();
531
532  //                  Next address   Chain
533  SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
534  SDValue To[2];
535
536  if (IsValidInc) {
537    // Build post increment store.
538    SDValue Ops[] = { Base, IncV, Value, Chain };
539    MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
540                                              Ops);
541    CurDAG->setNodeMemRefs(S, {MemOp});
542    To[0] = SDValue(S, 0);
543    To[1] = SDValue(S, 1);
544  } else {
545    SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
546    SDValue Ops[] = { Base, Zero, Value, Chain };
547    MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
548    CurDAG->setNodeMemRefs(S, {MemOp});
549    To[1] = SDValue(S, 0);
550    MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
551                                              Base, IncV);
552    To[0] = SDValue(A, 0);
553  }
554
555  ReplaceUses(From, To, 2);
556  CurDAG->RemoveDeadNode(ST);
557}
558
559void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
560  SDLoc dl(N);
561  StoreSDNode *ST = cast<StoreSDNode>(N);
562
563  // Handle indexed stores.
564  ISD::MemIndexedMode AM = ST->getAddressingMode();
565  if (AM != ISD::UNINDEXED) {
566    SelectIndexedStore(ST, dl);
567    return;
568  }
569
570  SelectCode(ST);
571}
572
573void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
574  SDLoc dl(N);
575  SDValue Shl_0 = N->getOperand(0);
576  SDValue Shl_1 = N->getOperand(1);
577
578  auto Default = [this,N] () -> void { SelectCode(N); };
579
580  if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
581    return Default();
582
583  // RHS is const.
584  int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
585
586  if (Shl_0.getOpcode() == ISD::MUL) {
587    SDValue Mul_0 = Shl_0.getOperand(0); // Val
588    SDValue Mul_1 = Shl_0.getOperand(1); // Const
589    // RHS of mul is const.
590    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
591      int32_t ValConst = C->getSExtValue() << ShlConst;
592      if (isInt<9>(ValConst)) {
593        SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
594        SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
595                                                MVT::i32, Mul_0, Val);
596        ReplaceNode(N, Result);
597        return;
598      }
599    }
600    return Default();
601  }
602
603  if (Shl_0.getOpcode() == ISD::SUB) {
604    SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
605    SDValue Sub_1 = Shl_0.getOperand(1); // Val
606    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
607      if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
608        return Default();
609      SDValue Shl2_0 = Sub_1.getOperand(0); // Val
610      SDValue Shl2_1 = Sub_1.getOperand(1); // Const
611      if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
612        int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
613        if (isInt<9>(-ValConst)) {
614          SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
615          SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
616                                                  MVT::i32, Shl2_0, Val);
617          ReplaceNode(N, Result);
618          return;
619        }
620      }
621    }
622  }
623
624  return Default();
625}
626
627//
628// Handling intrinsics for circular load and bitreverse load.
629//
630void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
631  if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
632    StoreInstrForLoadIntrinsic(L, N);
633    CurDAG->RemoveDeadNode(N);
634    return;
635  }
636
637  // Handle bit-reverse load intrinsics.
638  if (SelectBrevLdIntrinsic(N))
639    return;
640
641  if (SelectNewCircIntrinsic(N))
642    return;
643
644  unsigned IntNo = N->getConstantOperandVal(1);
645  if (IntNo == Intrinsic::hexagon_V6_vgathermw ||
646      IntNo == Intrinsic::hexagon_V6_vgathermw_128B ||
647      IntNo == Intrinsic::hexagon_V6_vgathermh ||
648      IntNo == Intrinsic::hexagon_V6_vgathermh_128B ||
649      IntNo == Intrinsic::hexagon_V6_vgathermhw ||
650      IntNo == Intrinsic::hexagon_V6_vgathermhw_128B) {
651    SelectV65Gather(N);
652    return;
653  }
654  if (IntNo == Intrinsic::hexagon_V6_vgathermwq ||
655      IntNo == Intrinsic::hexagon_V6_vgathermwq_128B ||
656      IntNo == Intrinsic::hexagon_V6_vgathermhq ||
657      IntNo == Intrinsic::hexagon_V6_vgathermhq_128B ||
658      IntNo == Intrinsic::hexagon_V6_vgathermhwq ||
659      IntNo == Intrinsic::hexagon_V6_vgathermhwq_128B) {
660    SelectV65GatherPred(N);
661    return;
662  }
663
664  SelectCode(N);
665}
666
667void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
668  unsigned IID = N->getConstantOperandVal(0);
669  unsigned Bits;
670  switch (IID) {
671  case Intrinsic::hexagon_S2_vsplatrb:
672    Bits = 8;
673    break;
674  case Intrinsic::hexagon_S2_vsplatrh:
675    Bits = 16;
676    break;
677  case Intrinsic::hexagon_V6_vaddcarry:
678  case Intrinsic::hexagon_V6_vaddcarry_128B:
679  case Intrinsic::hexagon_V6_vsubcarry:
680  case Intrinsic::hexagon_V6_vsubcarry_128B:
681    SelectHVXDualOutput(N);
682    return;
683  default:
684    SelectCode(N);
685    return;
686  }
687
688  SDValue V = N->getOperand(1);
689  SDValue U;
690  // Splat intrinsics.
691  if (keepsLowBits(V, Bits, U)) {
692    SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
693                                N->getOperand(0), U);
694    ReplaceNode(N, R.getNode());
695    SelectCode(R.getNode());
696    return;
697  }
698  SelectCode(N);
699}
700
701void HexagonDAGToDAGISel::SelectExtractSubvector(SDNode *N) {
702  SDValue Inp = N->getOperand(0);
703  MVT ResTy = N->getValueType(0).getSimpleVT();
704  unsigned Idx = N->getConstantOperandVal(1);
705
706  [[maybe_unused]] MVT InpTy = Inp.getValueType().getSimpleVT();
707  [[maybe_unused]] unsigned ResLen = ResTy.getVectorNumElements();
708  assert(InpTy.getVectorElementType() == ResTy.getVectorElementType());
709  assert(2 * ResLen == InpTy.getVectorNumElements());
710  assert(ResTy.getSizeInBits() == 32);
711  assert(Idx == 0 || Idx == ResLen);
712
713  unsigned SubReg = Idx == 0 ? Hexagon::isub_lo : Hexagon::isub_hi;
714  SDValue Ext = CurDAG->getTargetExtractSubreg(SubReg, SDLoc(N), ResTy, Inp);
715
716  ReplaceNode(N, Ext.getNode());
717}
718
719//
720// Map floating point constant values.
721//
722void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
723  SDLoc dl(N);
724  auto *CN = cast<ConstantFPSDNode>(N);
725  APInt A = CN->getValueAPF().bitcastToAPInt();
726  if (N->getValueType(0) == MVT::f32) {
727    SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
728    ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
729    return;
730  }
731  if (N->getValueType(0) == MVT::f64) {
732    SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
733    ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
734    return;
735  }
736
737  SelectCode(N);
738}
739
740//
741// Map boolean values.
742//
743void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
744  if (N->getValueType(0) == MVT::i1) {
745    assert(!(N->getAsZExtVal() >> 1));
746    unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
747                      ? Hexagon::PS_true
748                      : Hexagon::PS_false;
749    ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
750    return;
751  }
752
753  SelectCode(N);
754}
755
756void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
757  MachineFrameInfo &MFI = MF->getFrameInfo();
758  const HexagonFrameLowering *HFI = HST->getFrameLowering();
759  int FX = cast<FrameIndexSDNode>(N)->getIndex();
760  Align StkA = HFI->getStackAlign();
761  Align MaxA = MFI.getMaxAlign();
762  SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
763  SDLoc DL(N);
764  SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
765  SDNode *R = nullptr;
766
767  // Use PS_fi when:
768  // - the object is fixed, or
769  // - there are no objects with higher-than-default alignment, or
770  // - there are no dynamically allocated objects.
771  // Otherwise, use PS_fia.
772  if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
773    R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
774  } else {
775    auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
776    Register AR = HMFI.getStackAlignBaseReg();
777    SDValue CH = CurDAG->getEntryNode();
778    SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
779    R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
780  }
781
782  ReplaceNode(N, R);
783}
784
785void HexagonDAGToDAGISel::SelectAddSubCarry(SDNode *N) {
786  unsigned OpcCarry = N->getOpcode() == HexagonISD::ADDC ? Hexagon::A4_addp_c
787                                                         : Hexagon::A4_subp_c;
788  SDNode *C = CurDAG->getMachineNode(OpcCarry, SDLoc(N), N->getVTList(),
789                                     { N->getOperand(0), N->getOperand(1),
790                                       N->getOperand(2) });
791  ReplaceNode(N, C);
792}
793
794void HexagonDAGToDAGISel::SelectVAlign(SDNode *N) {
795  MVT ResTy = N->getValueType(0).getSimpleVT();
796  if (HST->isHVXVectorType(ResTy, true))
797    return SelectHvxVAlign(N);
798
799  const SDLoc &dl(N);
800  unsigned VecLen = ResTy.getSizeInBits();
801  if (VecLen == 32) {
802    SDValue Ops[] = {
803      CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
804      N->getOperand(0),
805      CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
806      N->getOperand(1),
807      CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
808    };
809    SDNode *R = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
810                                       MVT::i64, Ops);
811
812    // Shift right by "(Addr & 0x3) * 8" bytes.
813    SDNode *C;
814    SDValue M0 = CurDAG->getTargetConstant(0x18, dl, MVT::i32);
815    SDValue M1 = CurDAG->getTargetConstant(0x03, dl, MVT::i32);
816    if (HST->useCompound()) {
817      C = CurDAG->getMachineNode(Hexagon::S4_andi_asl_ri, dl, MVT::i32,
818                                 M0, N->getOperand(2), M1);
819    } else {
820      SDNode *T = CurDAG->getMachineNode(Hexagon::S2_asl_i_r, dl, MVT::i32,
821                                         N->getOperand(2), M1);
822      C = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
823                                 SDValue(T, 0), M0);
824    }
825    SDNode *S = CurDAG->getMachineNode(Hexagon::S2_lsr_r_p, dl, MVT::i64,
826                                       SDValue(R, 0), SDValue(C, 0));
827    SDValue E = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo, dl, ResTy,
828                                               SDValue(S, 0));
829    ReplaceNode(N, E.getNode());
830  } else {
831    assert(VecLen == 64);
832    SDNode *Pu = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::v8i1,
833                                        N->getOperand(2));
834    SDNode *VA = CurDAG->getMachineNode(Hexagon::S2_valignrb, dl, ResTy,
835                                        N->getOperand(0), N->getOperand(1),
836                                        SDValue(Pu,0));
837    ReplaceNode(N, VA);
838  }
839}
840
841void HexagonDAGToDAGISel::SelectVAlignAddr(SDNode *N) {
842  const SDLoc &dl(N);
843  SDValue A = N->getOperand(1);
844  int Mask = -cast<ConstantSDNode>(A.getNode())->getSExtValue();
845  assert(isPowerOf2_32(-Mask));
846
847  SDValue M = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
848  SDNode *AA = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
849                                      N->getOperand(0), M);
850  ReplaceNode(N, AA);
851}
852
853// Handle these nodes here to avoid having to write patterns for all
854// combinations of input/output types. In all cases, the resulting
855// instruction is the same.
856void HexagonDAGToDAGISel::SelectTypecast(SDNode *N) {
857  SDValue Op = N->getOperand(0);
858  MVT OpTy = Op.getValueType().getSimpleVT();
859  SDNode *T = CurDAG->MorphNodeTo(N, N->getOpcode(),
860                                  CurDAG->getVTList(OpTy), {Op});
861  ReplaceNode(T, Op.getNode());
862}
863
864void HexagonDAGToDAGISel::SelectP2D(SDNode *N) {
865  MVT ResTy = N->getValueType(0).getSimpleVT();
866  SDNode *T = CurDAG->getMachineNode(Hexagon::C2_mask, SDLoc(N), ResTy,
867                                     N->getOperand(0));
868  ReplaceNode(N, T);
869}
870
871void HexagonDAGToDAGISel::SelectD2P(SDNode *N) {
872  const SDLoc &dl(N);
873  MVT ResTy = N->getValueType(0).getSimpleVT();
874  SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
875  SDNode *T = CurDAG->getMachineNode(Hexagon::A4_vcmpbgtui, dl, ResTy,
876                                     N->getOperand(0), Zero);
877  ReplaceNode(N, T);
878}
879
880void HexagonDAGToDAGISel::SelectV2Q(SDNode *N) {
881  const SDLoc &dl(N);
882  MVT ResTy = N->getValueType(0).getSimpleVT();
883  // The argument to V2Q should be a single vector.
884  MVT OpTy = N->getOperand(0).getValueType().getSimpleVT(); (void)OpTy;
885  assert(HST->getVectorLength() * 8 == OpTy.getSizeInBits());
886
887  SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
888  SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
889  SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandvrt, dl, ResTy,
890                                     N->getOperand(0), SDValue(R,0));
891  ReplaceNode(N, T);
892}
893
894void HexagonDAGToDAGISel::SelectQ2V(SDNode *N) {
895  const SDLoc &dl(N);
896  MVT ResTy = N->getValueType(0).getSimpleVT();
897  // The result of V2Q should be a single vector.
898  assert(HST->getVectorLength() * 8 == ResTy.getSizeInBits());
899
900  SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
901  SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
902  SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandqrt, dl, ResTy,
903                                     N->getOperand(0), SDValue(R,0));
904  ReplaceNode(N, T);
905}
906
907void HexagonDAGToDAGISel::Select(SDNode *N) {
908  if (N->isMachineOpcode())
909    return N->setNodeId(-1);  // Already selected.
910
911  auto isHvxOp = [this](SDNode *N) {
912    for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
913      if (HST->isHVXVectorType(N->getValueType(i), true))
914        return true;
915    }
916    for (SDValue I : N->ops()) {
917      if (HST->isHVXVectorType(I.getValueType(), true))
918        return true;
919    }
920    return false;
921  };
922
923  if (HST->useHVXOps() && isHvxOp(N)) {
924    switch (N->getOpcode()) {
925    case ISD::EXTRACT_SUBVECTOR:  return SelectHvxExtractSubvector(N);
926    case ISD::VECTOR_SHUFFLE:     return SelectHvxShuffle(N);
927
928    case HexagonISD::VROR:        return SelectHvxRor(N);
929    }
930  }
931
932  switch (N->getOpcode()) {
933  case ISD::Constant:             return SelectConstant(N);
934  case ISD::ConstantFP:           return SelectConstantFP(N);
935  case ISD::FrameIndex:           return SelectFrameIndex(N);
936  case ISD::SHL:                  return SelectSHL(N);
937  case ISD::LOAD:                 return SelectLoad(N);
938  case ISD::STORE:                return SelectStore(N);
939  case ISD::INTRINSIC_W_CHAIN:    return SelectIntrinsicWChain(N);
940  case ISD::INTRINSIC_WO_CHAIN:   return SelectIntrinsicWOChain(N);
941  case ISD::EXTRACT_SUBVECTOR:    return SelectExtractSubvector(N);
942
943  case HexagonISD::ADDC:
944  case HexagonISD::SUBC:          return SelectAddSubCarry(N);
945  case HexagonISD::VALIGN:        return SelectVAlign(N);
946  case HexagonISD::VALIGNADDR:    return SelectVAlignAddr(N);
947  case HexagonISD::TYPECAST:      return SelectTypecast(N);
948  case HexagonISD::P2D:           return SelectP2D(N);
949  case HexagonISD::D2P:           return SelectD2P(N);
950  case HexagonISD::Q2V:           return SelectQ2V(N);
951  case HexagonISD::V2Q:           return SelectV2Q(N);
952  }
953
954  SelectCode(N);
955}
956
957bool HexagonDAGToDAGISel::SelectInlineAsmMemoryOperand(
958    const SDValue &Op, InlineAsm::ConstraintCode ConstraintID,
959    std::vector<SDValue> &OutOps) {
960  SDValue Inp = Op, Res;
961
962  switch (ConstraintID) {
963  default:
964    return true;
965  case InlineAsm::ConstraintCode::o: // Offsetable.
966  case InlineAsm::ConstraintCode::v: // Not offsetable.
967  case InlineAsm::ConstraintCode::m: // Memory.
968    if (SelectAddrFI(Inp, Res))
969      OutOps.push_back(Res);
970    else
971      OutOps.push_back(Inp);
972    break;
973  }
974
975  OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
976  return false;
977}
978
979static bool isMemOPCandidate(SDNode *I, SDNode *U) {
980  // I is an operand of U. Check if U is an arithmetic (binary) operation
981  // usable in a memop, where the other operand is a loaded value, and the
982  // result of U is stored in the same location.
983
984  if (!U->hasOneUse())
985    return false;
986  unsigned Opc = U->getOpcode();
987  switch (Opc) {
988    case ISD::ADD:
989    case ISD::SUB:
990    case ISD::AND:
991    case ISD::OR:
992      break;
993    default:
994      return false;
995  }
996
997  SDValue S0 = U->getOperand(0);
998  SDValue S1 = U->getOperand(1);
999  SDValue SY = (S0.getNode() == I) ? S1 : S0;
1000
1001  SDNode *UUse = *U->use_begin();
1002  if (UUse->getNumValues() != 1)
1003    return false;
1004
1005  // Check if one of the inputs to U is a load instruction and the output
1006  // is used by a store instruction. If so and they also have the same
1007  // base pointer, then don't preoprocess this node sequence as it
1008  // can be matched to a memop.
1009  SDNode *SYNode = SY.getNode();
1010  if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
1011    SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
1012    SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
1013    if (LDBasePtr == STBasePtr)
1014      return true;
1015  }
1016  return false;
1017}
1018
1019
1020// Transform: (or (select c x 0) z)  ->  (select c (or x z) z)
1021//            (or (select c 0 y) z)  ->  (select c z (or y z))
1022void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
1023  SelectionDAG &DAG = *CurDAG;
1024
1025  for (auto *I : Nodes) {
1026    if (I->getOpcode() != ISD::OR)
1027      continue;
1028
1029    auto IsSelect0 = [](const SDValue &Op) -> bool {
1030      if (Op.getOpcode() != ISD::SELECT)
1031        return false;
1032      return isNullConstant(Op.getOperand(1)) ||
1033             isNullConstant(Op.getOperand(2));
1034    };
1035
1036    SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
1037    EVT VT = I->getValueType(0);
1038    bool SelN0 = IsSelect0(N0);
1039    SDValue SOp = SelN0 ? N0 : N1;
1040    SDValue VOp = SelN0 ? N1 : N0;
1041
1042    if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
1043      SDValue SC = SOp.getOperand(0);
1044      SDValue SX = SOp.getOperand(1);
1045      SDValue SY = SOp.getOperand(2);
1046      SDLoc DLS = SOp;
1047      if (isNullConstant(SY)) {
1048        SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
1049        SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
1050        DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1051      } else if (isNullConstant(SX)) {
1052        SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1053        SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1054        DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1055      }
1056    }
1057  }
1058}
1059
1060// Transform: (store ch val (add x (add (shl y c) e)))
1061//        to: (store ch val (add x (shl (add y d) c))),
1062// where e = (shl d c) for some integer d.
1063// The purpose of this is to enable generation of loads/stores with
1064// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1065// value c must be 0, 1 or 2.
1066void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
1067  SelectionDAG &DAG = *CurDAG;
1068
1069  for (auto *I : Nodes) {
1070    if (I->getOpcode() != ISD::STORE)
1071      continue;
1072
1073    // I matched: (store ch val Off)
1074    SDValue Off = I->getOperand(2);
1075    // Off needs to match: (add x (add (shl y c) (shl d c))))
1076    if (Off.getOpcode() != ISD::ADD)
1077      continue;
1078    // Off matched: (add x T0)
1079    SDValue T0 = Off.getOperand(1);
1080    // T0 needs to match: (add T1 T2):
1081    if (T0.getOpcode() != ISD::ADD)
1082      continue;
1083    // T0 matched: (add T1 T2)
1084    SDValue T1 = T0.getOperand(0);
1085    SDValue T2 = T0.getOperand(1);
1086    // T1 needs to match: (shl y c)
1087    if (T1.getOpcode() != ISD::SHL)
1088      continue;
1089    SDValue C = T1.getOperand(1);
1090    ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1091    if (CN == nullptr)
1092      continue;
1093    unsigned CV = CN->getZExtValue();
1094    if (CV > 2)
1095      continue;
1096    // T2 needs to match e, where e = (shl d c) for some d.
1097    ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1098    if (EN == nullptr)
1099      continue;
1100    unsigned EV = EN->getZExtValue();
1101    if (EV % (1 << CV) != 0)
1102      continue;
1103    unsigned DV = EV / (1 << CV);
1104
1105    // Replace T0 with: (shl (add y d) c)
1106    SDLoc DL = SDLoc(I);
1107    EVT VT = T0.getValueType();
1108    SDValue D = DAG.getConstant(DV, DL, VT);
1109    // NewAdd = (add y d)
1110    SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1111    // NewShl = (shl NewAdd c)
1112    SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1113    ReplaceNode(T0.getNode(), NewShl.getNode());
1114  }
1115}
1116
1117// Transform: (load ch (add x (and (srl y c) Mask)))
1118//        to: (load ch (add x (shl (srl y d) d-c)))
1119// where
1120// Mask = 00..0 111..1 0.0
1121//          |     |     +-- d-c 0s, and d-c is 0, 1 or 2.
1122//          |     +-------- 1s
1123//          +-------------- at most c 0s
1124// Motivating example:
1125// DAG combiner optimizes (add x (shl (srl y 5) 2))
1126//                     to (add x (and (srl y 3) 1FFFFFFC))
1127// which results in a constant-extended and(##...,lsr). This transformation
1128// undoes this simplification for cases where the shl can be folded into
1129// an addressing mode.
1130void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1131  SelectionDAG &DAG = *CurDAG;
1132
1133  for (SDNode *N : Nodes) {
1134    unsigned Opc = N->getOpcode();
1135    if (Opc != ISD::LOAD && Opc != ISD::STORE)
1136      continue;
1137    SDValue Addr = Opc == ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
1138    // Addr must match: (add x T0)
1139    if (Addr.getOpcode() != ISD::ADD)
1140      continue;
1141    SDValue T0 = Addr.getOperand(1);
1142    // T0 must match: (and T1 Mask)
1143    if (T0.getOpcode() != ISD::AND)
1144      continue;
1145
1146    // We have an AND.
1147    //
1148    // Check the first operand. It must be: (srl y c).
1149    SDValue S = T0.getOperand(0);
1150    if (S.getOpcode() != ISD::SRL)
1151      continue;
1152    ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
1153    if (SN == nullptr)
1154      continue;
1155    if (SN->getAPIntValue().getBitWidth() != 32)
1156      continue;
1157    uint32_t CV = SN->getZExtValue();
1158
1159    // Check the second operand: the supposed mask.
1160    ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
1161    if (MN == nullptr)
1162      continue;
1163    if (MN->getAPIntValue().getBitWidth() != 32)
1164      continue;
1165    uint32_t Mask = MN->getZExtValue();
1166    // Examine the mask.
1167    uint32_t TZ = llvm::countr_zero(Mask);
1168    uint32_t M1 = llvm::countr_one(Mask >> TZ);
1169    uint32_t LZ = llvm::countl_zero(Mask);
1170    // Trailing zeros + middle ones + leading zeros must equal the width.
1171    if (TZ + M1 + LZ != 32)
1172      continue;
1173    // The number of trailing zeros will be encoded in the addressing mode.
1174    if (TZ > 2)
1175      continue;
1176    // The number of leading zeros must be at most c.
1177    if (LZ > CV)
1178      continue;
1179
1180    // All looks good.
1181    SDValue Y = S.getOperand(0);
1182    EVT VT = Addr.getValueType();
1183    SDLoc dl(S);
1184    // TZ = D-C, so D = TZ+C.
1185    SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1186    SDValue DC = DAG.getConstant(TZ, dl, VT);
1187    SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1188    SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1189    ReplaceNode(T0.getNode(), NewShl.getNode());
1190  }
1191}
1192
1193// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1194//                                                  (op ... 1 ...))
1195void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1196  SelectionDAG &DAG = *CurDAG;
1197
1198  for (SDNode *N : Nodes) {
1199    unsigned Opc = N->getOpcode();
1200    if (Opc != ISD::ZERO_EXTEND)
1201      continue;
1202    SDValue OpI1 = N->getOperand(0);
1203    EVT OpVT = OpI1.getValueType();
1204    if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1205      continue;
1206    for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1207      SDNode *U = *I;
1208      if (U->getNumValues() != 1)
1209        continue;
1210      EVT UVT = U->getValueType(0);
1211      if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1212        continue;
1213      // Do not generate select for all i1 vector type.
1214      if (UVT.isVector() && UVT.getVectorElementType() == MVT::i1)
1215        continue;
1216      if (isMemOPCandidate(N, U))
1217        continue;
1218
1219      // Potentially simplifiable operation.
1220      unsigned I1N = I.getOperandNo();
1221      SmallVector<SDValue,2> Ops(U->getNumOperands());
1222      for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1223        Ops[i] = U->getOperand(i);
1224      EVT BVT = Ops[I1N].getValueType();
1225
1226      const SDLoc &dl(U);
1227      SDValue C0 = DAG.getConstant(0, dl, BVT);
1228      SDValue C1 = DAG.getConstant(1, dl, BVT);
1229      SDValue If0, If1;
1230
1231      if (isa<MachineSDNode>(U)) {
1232        unsigned UseOpc = U->getMachineOpcode();
1233        Ops[I1N] = C0;
1234        If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1235        Ops[I1N] = C1;
1236        If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1237      } else {
1238        unsigned UseOpc = U->getOpcode();
1239        Ops[I1N] = C0;
1240        If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1241        Ops[I1N] = C1;
1242        If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1243      }
1244      // We're generating a SELECT way after legalization, so keep the types
1245      // simple.
1246      unsigned UW = UVT.getSizeInBits();
1247      EVT SVT = (UW == 32 || UW == 64) ? MVT::getIntegerVT(UW) : UVT;
1248      SDValue Sel = DAG.getNode(ISD::SELECT, dl, SVT, OpI1,
1249                                DAG.getBitcast(SVT, If1),
1250                                DAG.getBitcast(SVT, If0));
1251      SDValue Ret = DAG.getBitcast(UVT, Sel);
1252      DAG.ReplaceAllUsesWith(U, Ret.getNode());
1253    }
1254  }
1255}
1256
1257void HexagonDAGToDAGISel::PreprocessISelDAG() {
1258  // Repack all nodes before calling each preprocessing function,
1259  // because each of them can modify the set of nodes.
1260  auto getNodes = [this]() -> std::vector<SDNode *> {
1261    std::vector<SDNode *> T;
1262    T.reserve(CurDAG->allnodes_size());
1263    for (SDNode &N : CurDAG->allnodes())
1264      T.push_back(&N);
1265    return T;
1266  };
1267
1268  if (HST->useHVXOps())
1269    PreprocessHvxISelDAG();
1270
1271  // Transform: (or (select c x 0) z)  ->  (select c (or x z) z)
1272  //            (or (select c 0 y) z)  ->  (select c z (or y z))
1273  ppSimplifyOrSelect0(getNodes());
1274
1275  // Transform: (store ch val (add x (add (shl y c) e)))
1276  //        to: (store ch val (add x (shl (add y d) c))),
1277  // where e = (shl d c) for some integer d.
1278  // The purpose of this is to enable generation of loads/stores with
1279  // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1280  // value c must be 0, 1 or 2.
1281  ppAddrReorderAddShl(getNodes());
1282
1283  // Transform: (load ch (add x (and (srl y c) Mask)))
1284  //        to: (load ch (add x (shl (srl y d) d-c)))
1285  // where
1286  // Mask = 00..0 111..1 0.0
1287  //          |     |     +-- d-c 0s, and d-c is 0, 1 or 2.
1288  //          |     +-------- 1s
1289  //          +-------------- at most c 0s
1290  // Motivating example:
1291  // DAG combiner optimizes (add x (shl (srl y 5) 2))
1292  //                     to (add x (and (srl y 3) 1FFFFFFC))
1293  // which results in a constant-extended and(##...,lsr). This transformation
1294  // undoes this simplification for cases where the shl can be folded into
1295  // an addressing mode.
1296  ppAddrRewriteAndSrl(getNodes());
1297
1298  // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1299  //                                                  (op ... 1 ...))
1300  ppHoistZextI1(getNodes());
1301
1302  DEBUG_WITH_TYPE("isel", {
1303    dbgs() << "Preprocessed (Hexagon) selection DAG:";
1304    CurDAG->dump();
1305  });
1306
1307  if (EnableAddressRebalancing) {
1308    rebalanceAddressTrees();
1309
1310    DEBUG_WITH_TYPE("isel", {
1311      dbgs() << "Address tree balanced selection DAG:";
1312      CurDAG->dump();
1313    });
1314  }
1315}
1316
1317void HexagonDAGToDAGISel::emitFunctionEntryCode() {
1318  auto &HST = MF->getSubtarget<HexagonSubtarget>();
1319  auto &HFI = *HST.getFrameLowering();
1320  if (!HFI.needsAligna(*MF))
1321    return;
1322
1323  MachineFrameInfo &MFI = MF->getFrameInfo();
1324  MachineBasicBlock *EntryBB = &MF->front();
1325  Align EntryMaxA = MFI.getMaxAlign();
1326
1327  // Reserve the first non-volatile register.
1328  Register AP = 0;
1329  auto &HRI = *HST.getRegisterInfo();
1330  BitVector Reserved = HRI.getReservedRegs(*MF);
1331  for (const MCPhysReg *R = HRI.getCalleeSavedRegs(MF); *R; ++R) {
1332    if (Reserved[*R])
1333      continue;
1334    AP = *R;
1335    break;
1336  }
1337  assert(AP.isValid() && "Couldn't reserve stack align register");
1338  BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AP)
1339      .addImm(EntryMaxA.value());
1340  MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseReg(AP);
1341}
1342
1343void HexagonDAGToDAGISel::updateAligna() {
1344  auto &HFI = *MF->getSubtarget<HexagonSubtarget>().getFrameLowering();
1345  if (!HFI.needsAligna(*MF))
1346    return;
1347  auto *AlignaI = const_cast<MachineInstr*>(HFI.getAlignaInstr(*MF));
1348  assert(AlignaI != nullptr);
1349  unsigned MaxA = MF->getFrameInfo().getMaxAlign().value();
1350  if (AlignaI->getOperand(1).getImm() < MaxA)
1351    AlignaI->getOperand(1).setImm(MaxA);
1352}
1353
1354// Match a frame index that can be used in an addressing mode.
1355bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
1356  if (N.getOpcode() != ISD::FrameIndex)
1357    return false;
1358  auto &HFI = *HST->getFrameLowering();
1359  MachineFrameInfo &MFI = MF->getFrameInfo();
1360  int FX = cast<FrameIndexSDNode>(N)->getIndex();
1361  if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
1362    return false;
1363  R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1364  return true;
1365}
1366
1367inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1368  return SelectGlobalAddress(N, R, false, Align(1));
1369}
1370
1371inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1372  return SelectGlobalAddress(N, R, true, Align(1));
1373}
1374
1375inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1376  return SelectAnyImmediate(N, R, Align(1));
1377}
1378
1379inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1380  return SelectAnyImmediate(N, R, Align(1));
1381}
1382inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1383  return SelectAnyImmediate(N, R, Align(2));
1384}
1385inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1386  return SelectAnyImmediate(N, R, Align(4));
1387}
1388inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1389  return SelectAnyImmediate(N, R, Align(8));
1390}
1391
1392inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1393  EVT T = N.getValueType();
1394  if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1395    return false;
1396  int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1397  R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1398  return true;
1399}
1400
1401bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1402                                             Align Alignment) {
1403  switch (N.getOpcode()) {
1404  case ISD::Constant: {
1405    if (N.getValueType() != MVT::i32)
1406      return false;
1407    int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1408    if (!isAligned(Alignment, V))
1409      return false;
1410    R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1411    return true;
1412  }
1413  case HexagonISD::JT:
1414  case HexagonISD::CP:
1415    // These are assumed to always be aligned at least 8-byte boundary.
1416    if (Alignment > Align(8))
1417      return false;
1418    R = N.getOperand(0);
1419    return true;
1420  case ISD::ExternalSymbol:
1421    // Symbols may be aligned at any boundary.
1422    if (Alignment > Align(1))
1423      return false;
1424    R = N;
1425    return true;
1426  case ISD::BlockAddress:
1427    // Block address is always aligned at least 4-byte boundary.
1428    if (Alignment > Align(4) ||
1429        !isAligned(Alignment, cast<BlockAddressSDNode>(N)->getOffset()))
1430      return false;
1431    R = N;
1432    return true;
1433  }
1434
1435  if (SelectGlobalAddress(N, R, false, Alignment) ||
1436      SelectGlobalAddress(N, R, true, Alignment))
1437    return true;
1438
1439  return false;
1440}
1441
1442bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1443                                              bool UseGP, Align Alignment) {
1444  switch (N.getOpcode()) {
1445  case ISD::ADD: {
1446    SDValue N0 = N.getOperand(0);
1447    SDValue N1 = N.getOperand(1);
1448    unsigned GAOpc = N0.getOpcode();
1449    if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1450      return false;
1451    if (!UseGP && GAOpc != HexagonISD::CONST32)
1452      return false;
1453    if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1454      if (!isAligned(Alignment, Const->getZExtValue()))
1455        return false;
1456      SDValue Addr = N0.getOperand(0);
1457      if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1458        if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1459          uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1460          R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1461                                             N.getValueType(), NewOff);
1462          return true;
1463        }
1464      }
1465    }
1466    break;
1467  }
1468  case HexagonISD::CP:
1469  case HexagonISD::JT:
1470  case HexagonISD::CONST32:
1471    // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1472    // want in the instruction.
1473    if (!UseGP)
1474      R = N.getOperand(0);
1475    return !UseGP;
1476  case HexagonISD::CONST32_GP:
1477    if (UseGP)
1478      R = N.getOperand(0);
1479    return UseGP;
1480  default:
1481    return false;
1482  }
1483
1484  return false;
1485}
1486
1487bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1488  // This (complex pattern) function is meant to detect a sign-extension
1489  // i32->i64 on a per-operand basis. This would allow writing single
1490  // patterns that would cover a number of combinations of different ways
1491  // a sign-extensions could be written. For example:
1492  //   (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1493  // could match either one of these:
1494  //   (mul (sext x) (sext_inreg y))
1495  //   (mul (sext-load *p) (sext_inreg y))
1496  //   (mul (sext_inreg x) (sext y))
1497  // etc.
1498  //
1499  // The returned value will have type i64 and its low word will
1500  // contain the value being extended. The high bits are not specified.
1501  // The returned type is i64 because the original type of N was i64,
1502  // but the users of this function should only use the low-word of the
1503  // result, e.g.
1504  //  (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1505
1506  if (N.getValueType() != MVT::i64)
1507    return false;
1508  unsigned Opc = N.getOpcode();
1509  switch (Opc) {
1510    case ISD::SIGN_EXTEND:
1511    case ISD::SIGN_EXTEND_INREG: {
1512      // sext_inreg has the source type as a separate operand.
1513      EVT T = Opc == ISD::SIGN_EXTEND
1514                ? N.getOperand(0).getValueType()
1515                : cast<VTSDNode>(N.getOperand(1))->getVT();
1516      unsigned SW = T.getSizeInBits();
1517      if (SW == 32)
1518        R = N.getOperand(0);
1519      else if (SW < 32)
1520        R = N;
1521      else
1522        return false;
1523      break;
1524    }
1525    case ISD::LOAD: {
1526      LoadSDNode *L = cast<LoadSDNode>(N);
1527      if (L->getExtensionType() != ISD::SEXTLOAD)
1528        return false;
1529      // All extending loads extend to i32, so even if the value in
1530      // memory is shorter than 32 bits, it will be i32 after the load.
1531      if (L->getMemoryVT().getSizeInBits() > 32)
1532        return false;
1533      R = N;
1534      break;
1535    }
1536    case ISD::SRA: {
1537      auto *S = dyn_cast<ConstantSDNode>(N.getOperand(1));
1538      if (!S || S->getZExtValue() != 32)
1539        return false;
1540      R = N;
1541      break;
1542    }
1543    default:
1544      return false;
1545  }
1546  EVT RT = R.getValueType();
1547  if (RT == MVT::i64)
1548    return true;
1549  assert(RT == MVT::i32);
1550  // This is only to produce a value of type i64. Do not rely on the
1551  // high bits produced by this.
1552  const SDLoc &dl(N);
1553  SDValue Ops[] = {
1554    CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1555    R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1556    R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1557  };
1558  SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1559                                     MVT::i64, Ops);
1560  R = SDValue(T, 0);
1561  return true;
1562}
1563
1564bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1565      SDValue &Src) {
1566  unsigned Opc = Val.getOpcode();
1567  switch (Opc) {
1568  case ISD::SIGN_EXTEND:
1569  case ISD::ZERO_EXTEND:
1570  case ISD::ANY_EXTEND: {
1571    const SDValue &Op0 = Val.getOperand(0);
1572    EVT T = Op0.getValueType();
1573    if (T.isInteger() && T.getSizeInBits() == NumBits) {
1574      Src = Op0;
1575      return true;
1576    }
1577    break;
1578  }
1579  case ISD::SIGN_EXTEND_INREG:
1580  case ISD::AssertSext:
1581  case ISD::AssertZext:
1582    if (Val.getOperand(0).getValueType().isInteger()) {
1583      VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1584      if (T->getVT().getSizeInBits() == NumBits) {
1585        Src = Val.getOperand(0);
1586        return true;
1587      }
1588    }
1589    break;
1590  case ISD::AND: {
1591    // Check if this is an AND with NumBits of lower bits set to 1.
1592    uint64_t Mask = (1ULL << NumBits) - 1;
1593    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1594      if (C->getZExtValue() == Mask) {
1595        Src = Val.getOperand(1);
1596        return true;
1597      }
1598    }
1599    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1600      if (C->getZExtValue() == Mask) {
1601        Src = Val.getOperand(0);
1602        return true;
1603      }
1604    }
1605    break;
1606  }
1607  case ISD::OR:
1608  case ISD::XOR: {
1609    // OR/XOR with the lower NumBits bits set to 0.
1610    uint64_t Mask = (1ULL << NumBits) - 1;
1611    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1612      if ((C->getZExtValue() & Mask) == 0) {
1613        Src = Val.getOperand(1);
1614        return true;
1615      }
1616    }
1617    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1618      if ((C->getZExtValue() & Mask) == 0) {
1619        Src = Val.getOperand(0);
1620        return true;
1621      }
1622    }
1623    break;
1624  }
1625  default:
1626    break;
1627  }
1628  return false;
1629}
1630
1631bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1632  return N->getAlign().value() >= N->getMemoryVT().getStoreSize();
1633}
1634
1635bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1636  unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1637  switch (N->getMemoryVT().getStoreSize()) {
1638    case 1:
1639      return StackSize <= 56;   // 1*2^6 - 8
1640    case 2:
1641      return StackSize <= 120;  // 2*2^6 - 8
1642    case 4:
1643      return StackSize <= 248;  // 4*2^6 - 8
1644    default:
1645      return false;
1646  }
1647}
1648
1649// Return true when the given node fits in a positive half word.
1650bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1651  if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1652    int64_t V = CN->getSExtValue();
1653    return V > 0 && isInt<16>(V);
1654  }
1655  if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1656    const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1657    return VN->getVT().getSizeInBits() <= 16;
1658  }
1659  return false;
1660}
1661
1662bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1663  return !CheckSingleUse || N->hasOneUse();
1664}
1665
1666////////////////////////////////////////////////////////////////////////////////
1667// Rebalancing of address calculation trees
1668
1669static bool isOpcodeHandled(const SDNode *N) {
1670  switch (N->getOpcode()) {
1671    case ISD::ADD:
1672    case ISD::MUL:
1673      return true;
1674    case ISD::SHL:
1675      // We only handle constant shifts because these can be easily flattened
1676      // into multiplications by 2^Op1.
1677      return isa<ConstantSDNode>(N->getOperand(1).getNode());
1678    default:
1679      return false;
1680  }
1681}
1682
1683/// Return the weight of an SDNode
1684int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1685  if (!isOpcodeHandled(N))
1686    return 1;
1687  assert(RootWeights.count(N) && "Cannot get weight of unseen root!");
1688  assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!");
1689  assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!");
1690  return RootWeights[N];
1691}
1692
1693int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1694  if (!isOpcodeHandled(N))
1695    return 0;
1696  assert(RootWeights.count(N) && RootWeights[N] >= 0 &&
1697      "Cannot query height of unvisited/RAUW'd node!");
1698  return RootHeights[N];
1699}
1700
1701namespace {
1702struct WeightedLeaf {
1703  SDValue Value;
1704  int Weight;
1705  int InsertionOrder;
1706
1707  WeightedLeaf() {}
1708
1709  WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1710    Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1711    assert(Weight >= 0 && "Weight must be >= 0");
1712  }
1713
1714  static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1715    assert(A.Value.getNode() && B.Value.getNode());
1716    return A.Weight == B.Weight ?
1717            (A.InsertionOrder > B.InsertionOrder) :
1718            (A.Weight > B.Weight);
1719  }
1720};
1721
1722/// A specialized priority queue for WeigthedLeaves. It automatically folds
1723/// constants and allows removal of non-top elements while maintaining the
1724/// priority order.
1725class LeafPrioQueue {
1726  SmallVector<WeightedLeaf, 8> Q;
1727  bool HaveConst;
1728  WeightedLeaf ConstElt;
1729  unsigned Opcode;
1730
1731public:
1732  bool empty() {
1733    return (!HaveConst && Q.empty());
1734  }
1735
1736  size_t size() {
1737    return Q.size() + HaveConst;
1738  }
1739
1740  bool hasConst() {
1741    return HaveConst;
1742  }
1743
1744  const WeightedLeaf &top() {
1745    if (HaveConst)
1746      return ConstElt;
1747    return Q.front();
1748  }
1749
1750  WeightedLeaf pop() {
1751    if (HaveConst) {
1752      HaveConst = false;
1753      return ConstElt;
1754    }
1755    std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1756    return Q.pop_back_val();
1757  }
1758
1759  void push(WeightedLeaf L, bool SeparateConst=true) {
1760    if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1761      if (Opcode == ISD::MUL &&
1762          cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1763        return;
1764      if (Opcode == ISD::ADD &&
1765          cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1766        return;
1767
1768      HaveConst = true;
1769      ConstElt = L;
1770    } else {
1771      Q.push_back(L);
1772      std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1773    }
1774  }
1775
1776  /// Push L to the bottom of the queue regardless of its weight. If L is
1777  /// constant, it will not be folded with other constants in the queue.
1778  void pushToBottom(WeightedLeaf L) {
1779    L.Weight = 1000;
1780    push(L, false);
1781  }
1782
1783  /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1784  /// lowest weight and remove it from the queue.
1785  WeightedLeaf findSHL(uint64_t MaxAmount);
1786
1787  WeightedLeaf findMULbyConst();
1788
1789  LeafPrioQueue(unsigned Opcode) :
1790    HaveConst(false), Opcode(Opcode) { }
1791};
1792} // end anonymous namespace
1793
1794WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1795  int ResultPos;
1796  WeightedLeaf Result;
1797
1798  for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1799    const WeightedLeaf &L = Q[Pos];
1800    const SDValue &Val = L.Value;
1801    if (Val.getOpcode() != ISD::SHL ||
1802        !isa<ConstantSDNode>(Val.getOperand(1)) ||
1803        Val.getConstantOperandVal(1) > MaxAmount)
1804      continue;
1805    if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1806        (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1807    {
1808      Result = L;
1809      ResultPos = Pos;
1810    }
1811  }
1812
1813  if (Result.Value.getNode()) {
1814    Q.erase(&Q[ResultPos]);
1815    std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1816  }
1817
1818  return Result;
1819}
1820
1821WeightedLeaf LeafPrioQueue::findMULbyConst() {
1822  int ResultPos;
1823  WeightedLeaf Result;
1824
1825  for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1826    const WeightedLeaf &L = Q[Pos];
1827    const SDValue &Val = L.Value;
1828    if (Val.getOpcode() != ISD::MUL ||
1829        !isa<ConstantSDNode>(Val.getOperand(1)) ||
1830        Val.getConstantOperandVal(1) > 127)
1831      continue;
1832    if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1833        (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1834    {
1835      Result = L;
1836      ResultPos = Pos;
1837    }
1838  }
1839
1840  if (Result.Value.getNode()) {
1841    Q.erase(&Q[ResultPos]);
1842    std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1843  }
1844
1845  return Result;
1846}
1847
1848SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
1849  uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
1850  return CurDAG->getConstant(MulFactor, SDLoc(N),
1851                             N->getOperand(1).getValueType());
1852}
1853
1854/// @returns the value x for which 2^x is a factor of Val
1855static unsigned getPowerOf2Factor(SDValue Val) {
1856  if (Val.getOpcode() == ISD::MUL) {
1857    unsigned MaxFactor = 0;
1858    for (int i = 0; i < 2; ++i) {
1859      ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1860      if (!C)
1861        continue;
1862      const APInt &CInt = C->getAPIntValue();
1863      if (CInt.getBoolValue())
1864        MaxFactor = CInt.countr_zero();
1865    }
1866    return MaxFactor;
1867  }
1868  if (Val.getOpcode() == ISD::SHL) {
1869    if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1870      return 0;
1871    return (unsigned) Val.getConstantOperandVal(1);
1872  }
1873
1874  return 0;
1875}
1876
1877/// @returns true if V>>Amount will eliminate V's operation on its child
1878static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1879  if (V.getOpcode() == ISD::MUL) {
1880    SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1881    for (int i = 0; i < 2; ++i)
1882      if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1883          V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
1884        uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1885        return (NewConst == 1);
1886      }
1887  } else if (V.getOpcode() == ISD::SHL) {
1888    return (Amount == V.getConstantOperandVal(1));
1889  }
1890
1891  return false;
1892}
1893
1894SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1895  SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1896  if (V.getOpcode() == ISD::MUL) {
1897    for (int i=0; i < 2; ++i) {
1898      if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1899          V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1900        uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1901        if (NewConst == 1)
1902          return Ops[!i];
1903        Ops[i] = CurDAG->getConstant(NewConst,
1904                                     SDLoc(V), V.getValueType());
1905        break;
1906      }
1907    }
1908  } else if (V.getOpcode() == ISD::SHL) {
1909    uint64_t ShiftAmount = V.getConstantOperandVal(1);
1910    if (ShiftAmount == Power)
1911      return Ops[0];
1912    Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1913                                 SDLoc(V), V.getValueType());
1914  }
1915
1916  return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1917}
1918
1919static bool isTargetConstant(const SDValue &V) {
1920  return V.getOpcode() == HexagonISD::CONST32 ||
1921         V.getOpcode() == HexagonISD::CONST32_GP;
1922}
1923
1924unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1925  if (GAUsesInFunction.count(V))
1926    return GAUsesInFunction[V];
1927
1928  unsigned Result = 0;
1929  const Function &CurF = CurDAG->getMachineFunction().getFunction();
1930  for (const User *U : V->users()) {
1931    if (isa<Instruction>(U) &&
1932        cast<Instruction>(U)->getParent()->getParent() == &CurF)
1933      ++Result;
1934  }
1935
1936  GAUsesInFunction[V] = Result;
1937
1938  return Result;
1939}
1940
1941/// Note - After calling this, N may be dead. It may have been replaced by a
1942/// new node, so always use the returned value in place of N.
1943///
1944/// @returns The SDValue taking the place of N (which could be N if it is
1945/// unchanged)
1946SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1947  assert(RootWeights.count(N) && "Cannot balance non-root node.");
1948  assert(RootWeights[N] != -2 && "This node was RAUW'd!");
1949  assert(!TopLevel || N->getOpcode() == ISD::ADD);
1950
1951  // Return early if this node was already visited
1952  if (RootWeights[N] != -1)
1953    return SDValue(N, 0);
1954
1955  assert(isOpcodeHandled(N));
1956
1957  SDValue Op0 = N->getOperand(0);
1958  SDValue Op1 = N->getOperand(1);
1959
1960  // Return early if the operands will remain unchanged or are all roots
1961  if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1962      (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1963    SDNode *Op0N = Op0.getNode();
1964    int Weight;
1965    if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1966      Weight = getWeight(balanceSubTree(Op0N).getNode());
1967      // Weight = calculateWeight(Op0N);
1968    } else
1969      Weight = getWeight(Op0N);
1970
1971    SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1972    if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1973      Weight += getWeight(balanceSubTree(Op1N).getNode());
1974      // Weight += calculateWeight(Op1N);
1975    } else
1976      Weight += getWeight(Op1N);
1977
1978    RootWeights[N] = Weight;
1979    RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1980                              getHeight(N->getOperand(1).getNode())) + 1;
1981
1982    LLVM_DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weight
1983                      << " Height=" << RootHeights[N] << "): ");
1984    LLVM_DEBUG(N->dump(CurDAG));
1985
1986    return SDValue(N, 0);
1987  }
1988
1989  LLVM_DEBUG(dbgs() << "** Balancing root node: ");
1990  LLVM_DEBUG(N->dump(CurDAG));
1991
1992  unsigned NOpcode = N->getOpcode();
1993
1994  LeafPrioQueue Leaves(NOpcode);
1995  SmallVector<SDValue, 4> Worklist;
1996  Worklist.push_back(SDValue(N, 0));
1997
1998  // SHL nodes will be converted to MUL nodes
1999  if (NOpcode == ISD::SHL)
2000    NOpcode = ISD::MUL;
2001
2002  bool CanFactorize = false;
2003  WeightedLeaf Mul1, Mul2;
2004  unsigned MaxPowerOf2 = 0;
2005  WeightedLeaf GA;
2006
2007  // Do not try to factor out a shift if there is already a shift at the tip of
2008  // the tree.
2009  bool HaveTopLevelShift = false;
2010  if (TopLevel &&
2011      ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
2012                        Op0.getConstantOperandVal(1) < 4) ||
2013       (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
2014                        Op1.getConstantOperandVal(1) < 4)))
2015    HaveTopLevelShift = true;
2016
2017  // Flatten the subtree into an ordered list of leaves; at the same time
2018  // determine whether the tree is already balanced.
2019  int InsertionOrder = 0;
2020  SmallDenseMap<SDValue, int> NodeHeights;
2021  bool Imbalanced = false;
2022  int CurrentWeight = 0;
2023  while (!Worklist.empty()) {
2024    SDValue Child = Worklist.pop_back_val();
2025
2026    if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
2027      // CASE 1: Child is a root note
2028
2029      int Weight = RootWeights[Child.getNode()];
2030      if (Weight == -1) {
2031        Child = balanceSubTree(Child.getNode());
2032        // calculateWeight(Child.getNode());
2033        Weight = getWeight(Child.getNode());
2034      } else if (Weight == -2) {
2035        // Whoops, this node was RAUWd by one of the balanceSubTree calls we
2036        // made. Our worklist isn't up to date anymore.
2037        // Restart the whole process.
2038        LLVM_DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2039        return balanceSubTree(N, TopLevel);
2040      }
2041
2042      NodeHeights[Child] = 1;
2043      CurrentWeight += Weight;
2044
2045      unsigned PowerOf2;
2046      if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
2047          (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
2048          Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
2049        // Try to identify two factorizable MUL/SHL children greedily. Leave
2050        // them out of the priority queue for now so we can deal with them
2051        // after.
2052        if (!Mul1.Value.getNode()) {
2053          Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
2054          MaxPowerOf2 = PowerOf2;
2055        } else {
2056          Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
2057          MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
2058
2059          // Our addressing modes can only shift by a maximum of 3
2060          if (MaxPowerOf2 > 3)
2061            MaxPowerOf2 = 3;
2062
2063          CanFactorize = true;
2064        }
2065      } else
2066        Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
2067    } else if (!isOpcodeHandled(Child.getNode())) {
2068      // CASE 2: Child is an unhandled kind of node (e.g. constant)
2069      int Weight = getWeight(Child.getNode());
2070
2071      NodeHeights[Child] = getHeight(Child.getNode());
2072      CurrentWeight += Weight;
2073
2074      if (isTargetConstant(Child) && !GA.Value.getNode())
2075        GA = WeightedLeaf(Child, Weight, InsertionOrder++);
2076      else
2077        Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
2078    } else {
2079      // CASE 3: Child is a subtree of same opcode
2080      // Visit children first, then flatten.
2081      unsigned ChildOpcode = Child.getOpcode();
2082      assert(ChildOpcode == NOpcode ||
2083             (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL));
2084
2085      // Convert SHL to MUL
2086      SDValue Op1;
2087      if (ChildOpcode == ISD::SHL)
2088        Op1 = getMultiplierForSHL(Child.getNode());
2089      else
2090        Op1 = Child->getOperand(1);
2091
2092      if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
2093        assert(!NodeHeights.count(Child) && "Parent visited before children?");
2094        // Visit children first, then re-visit this node
2095        Worklist.push_back(Child);
2096        Worklist.push_back(Op1);
2097        Worklist.push_back(Child->getOperand(0));
2098      } else {
2099        // Back at this node after visiting the children
2100        if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
2101          Imbalanced = true;
2102
2103        NodeHeights[Child] = std::max(NodeHeights[Op1],
2104                                      NodeHeights[Child->getOperand(0)]) + 1;
2105      }
2106    }
2107  }
2108
2109  LLVM_DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]
2110                    << " weight=" << CurrentWeight
2111                    << " imbalanced=" << Imbalanced << "\n");
2112
2113  // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
2114  //  This factors out a shift in order to match memw(a<<Y+b).
2115  if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
2116                       willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
2117    LLVM_DEBUG(dbgs() << "--> Found common factor for two MUL children!\n");
2118    int Weight = Mul1.Weight + Mul2.Weight;
2119    int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
2120    SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
2121    SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
2122    SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
2123                                  Mul1Factored, Mul2Factored);
2124    SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
2125                                        Mul1.Value.getValueType());
2126    SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
2127                                  Sum, Const);
2128    NodeHeights[New] = Height;
2129    Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
2130  } else if (Mul1.Value.getNode()) {
2131    // We failed to factorize two MULs, so now the Muls are left outside the
2132    // queue... add them back.
2133    Leaves.push(Mul1);
2134    if (Mul2.Value.getNode())
2135      Leaves.push(Mul2);
2136    CanFactorize = false;
2137  }
2138
2139  // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
2140  // and the root node itself is not used more than twice. This reduces the
2141  // amount of additional constant extenders introduced by this optimization.
2142  bool CombinedGA = false;
2143  if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
2144      GA.Value.hasOneUse() && N->use_size() < 3) {
2145    GlobalAddressSDNode *GANode =
2146      cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
2147    ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
2148
2149    if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
2150        getTargetLowering()->isOffsetFoldingLegal(GANode)) {
2151      LLVM_DEBUG(dbgs() << "--> Combining GA and offset ("
2152                        << Offset->getSExtValue() << "): ");
2153      LLVM_DEBUG(GANode->dump(CurDAG));
2154
2155      SDValue NewTGA =
2156        CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
2157            GANode->getValueType(0),
2158            GANode->getOffset() + (uint64_t)Offset->getSExtValue());
2159      GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
2160          GA.Value.getValueType(), NewTGA);
2161      GA.Weight += Leaves.top().Weight;
2162
2163      NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
2164      CombinedGA = true;
2165
2166      Leaves.pop(); // Remove the offset constant from the queue
2167    }
2168  }
2169
2170  if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
2171      (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
2172    RootWeights[N] = CurrentWeight;
2173    RootHeights[N] = NodeHeights[SDValue(N, 0)];
2174
2175    return SDValue(N, 0);
2176  }
2177
2178  // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
2179  if (NOpcode == ISD::ADD && GA.Value.getNode()) {
2180    WeightedLeaf SHL = Leaves.findSHL(31);
2181    if (SHL.Value.getNode()) {
2182      int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2183      GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2184                                 GA.Value.getValueType(),
2185                                 GA.Value, SHL.Value);
2186      GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2187      NodeHeights[GA.Value] = Height;
2188    }
2189  }
2190
2191  if (GA.Value.getNode())
2192    Leaves.push(GA);
2193
2194  // If this is the top level and we haven't factored out a shift, we should try
2195  // to move a constant to the bottom to match addressing modes like memw(rX+C)
2196  if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2197    LLVM_DEBUG(dbgs() << "--> Pushing constant to tip of tree.");
2198    Leaves.pushToBottom(Leaves.pop());
2199  }
2200
2201  const DataLayout &DL = CurDAG->getDataLayout();
2202  const TargetLowering &TLI = *getTargetLowering();
2203
2204  // Rebuild the tree using Huffman's algorithm
2205  while (Leaves.size() > 1) {
2206    WeightedLeaf L0 = Leaves.pop();
2207
2208    // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2209    // otherwise just get the next leaf
2210    WeightedLeaf L1 = Leaves.findMULbyConst();
2211    if (!L1.Value.getNode())
2212      L1 = Leaves.pop();
2213
2214    assert(L0.Weight <= L1.Weight && "Priority queue is broken!");
2215
2216    SDValue V0 = L0.Value;
2217    int V0Weight = L0.Weight;
2218    SDValue V1 = L1.Value;
2219    int V1Weight = L1.Weight;
2220
2221    // Make sure that none of these nodes have been RAUW'd
2222    if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2223        (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2224      LLVM_DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n");
2225      return balanceSubTree(N, TopLevel);
2226    }
2227
2228    ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2229    ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2230    EVT VT = N->getValueType(0);
2231    SDValue NewNode;
2232
2233    if (V0C && !V1C) {
2234      std::swap(V0, V1);
2235      std::swap(V0C, V1C);
2236    }
2237
2238    // Calculate height of this node
2239    assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&
2240           "Children must have been visited before re-combining them!");
2241    int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2242
2243    // Rebuild this node (and restore SHL from MUL if needed)
2244    if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2245      NewNode = CurDAG->getNode(
2246          ISD::SHL, SDLoc(V0), VT, V0,
2247          CurDAG->getConstant(
2248              V1C->getAPIntValue().logBase2(), SDLoc(N),
2249              TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
2250    else
2251      NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2252
2253    NodeHeights[NewNode] = Height;
2254
2255    int Weight = V0Weight + V1Weight;
2256    Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2257
2258    LLVM_DEBUG(dbgs() << "--> Built new node (Weight=" << Weight
2259                      << ",Height=" << Height << "):\n");
2260    LLVM_DEBUG(NewNode.dump());
2261  }
2262
2263  assert(Leaves.size() == 1);
2264  SDValue NewRoot = Leaves.top().Value;
2265
2266  assert(NodeHeights.count(NewRoot));
2267  int Height = NodeHeights[NewRoot];
2268
2269  // Restore SHL if we earlier converted it to a MUL
2270  if (NewRoot.getOpcode() == ISD::MUL) {
2271    ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2272    if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2273      EVT VT = NewRoot.getValueType();
2274      SDValue V0 = NewRoot.getOperand(0);
2275      NewRoot = CurDAG->getNode(
2276          ISD::SHL, SDLoc(NewRoot), VT, V0,
2277          CurDAG->getConstant(
2278              V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2279              TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
2280    }
2281  }
2282
2283  if (N != NewRoot.getNode()) {
2284    LLVM_DEBUG(dbgs() << "--> Root is now: ");
2285    LLVM_DEBUG(NewRoot.dump());
2286
2287    // Replace all uses of old root by new root
2288    CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2289    // Mark that we have RAUW'd N
2290    RootWeights[N] = -2;
2291  } else {
2292    LLVM_DEBUG(dbgs() << "--> Root unchanged.\n");
2293  }
2294
2295  RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2296  RootHeights[NewRoot.getNode()] = Height;
2297
2298  return NewRoot;
2299}
2300
2301void HexagonDAGToDAGISel::rebalanceAddressTrees() {
2302  for (SDNode &Node : llvm::make_early_inc_range(CurDAG->allnodes())) {
2303    SDNode *N = &Node;
2304    if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2305      continue;
2306
2307    SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2308    if (BasePtr.getOpcode() != ISD::ADD)
2309      continue;
2310
2311    // We've already processed this node
2312    if (RootWeights.count(BasePtr.getNode()))
2313      continue;
2314
2315    LLVM_DEBUG(dbgs() << "** Rebalancing address calculation in node: ");
2316    LLVM_DEBUG(N->dump(CurDAG));
2317
2318    // FindRoots
2319    SmallVector<SDNode *, 4> Worklist;
2320
2321    Worklist.push_back(BasePtr.getOperand(0).getNode());
2322    Worklist.push_back(BasePtr.getOperand(1).getNode());
2323
2324    while (!Worklist.empty()) {
2325      SDNode *N = Worklist.pop_back_val();
2326      unsigned Opcode = N->getOpcode();
2327
2328      if (!isOpcodeHandled(N))
2329        continue;
2330
2331      Worklist.push_back(N->getOperand(0).getNode());
2332      Worklist.push_back(N->getOperand(1).getNode());
2333
2334      // Not a root if it has only one use and same opcode as its parent
2335      if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2336        continue;
2337
2338      // This root node has already been processed
2339      if (RootWeights.count(N))
2340        continue;
2341
2342      RootWeights[N] = -1;
2343    }
2344
2345    // Balance node itself
2346    RootWeights[BasePtr.getNode()] = -1;
2347    SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2348
2349    if (N->getOpcode() == ISD::LOAD)
2350      N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2351            NewBasePtr, N->getOperand(2));
2352    else
2353      N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2354            NewBasePtr, N->getOperand(3));
2355
2356    LLVM_DEBUG(dbgs() << "--> Final node: ");
2357    LLVM_DEBUG(N->dump(CurDAG));
2358  }
2359
2360  CurDAG->RemoveDeadNodes();
2361  GAUsesInFunction.clear();
2362  RootHeights.clear();
2363  RootWeights.clear();
2364}
2365