1 //===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
2 //
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 implements the interfaces that Hexagon uses to lower LLVM code
11 // into a selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "HexagonISelLowering.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "HexagonTargetMachine.h"
19 #include "HexagonTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "hexagon-lowering"
43 
44 static cl::opt<bool> EmitJumpTables("hexagon-emit-jump-tables",
45   cl::init(true), cl::Hidden,
46   cl::desc("Control jump table emission on Hexagon target"));
47 
48 static cl::opt<bool> EnableHexSDNodeSched("enable-hexagon-sdnode-sched",
49   cl::Hidden, cl::ZeroOrMore, cl::init(false),
50   cl::desc("Enable Hexagon SDNode scheduling"));
51 
52 static cl::opt<bool> EnableFastMath("ffast-math",
53   cl::Hidden, cl::ZeroOrMore, cl::init(false),
54   cl::desc("Enable Fast Math processing"));
55 
56 static cl::opt<int> MinimumJumpTables("minimum-jump-tables",
57   cl::Hidden, cl::ZeroOrMore, cl::init(5),
58   cl::desc("Set minimum jump tables"));
59 
60 static cl::opt<int> MaxStoresPerMemcpyCL("max-store-memcpy",
61   cl::Hidden, cl::ZeroOrMore, cl::init(6),
62   cl::desc("Max #stores to inline memcpy"));
63 
64 static cl::opt<int> MaxStoresPerMemcpyOptSizeCL("max-store-memcpy-Os",
65   cl::Hidden, cl::ZeroOrMore, cl::init(4),
66   cl::desc("Max #stores to inline memcpy"));
67 
68 static cl::opt<int> MaxStoresPerMemmoveCL("max-store-memmove",
69   cl::Hidden, cl::ZeroOrMore, cl::init(6),
70   cl::desc("Max #stores to inline memmove"));
71 
72 static cl::opt<int> MaxStoresPerMemmoveOptSizeCL("max-store-memmove-Os",
73   cl::Hidden, cl::ZeroOrMore, cl::init(4),
74   cl::desc("Max #stores to inline memmove"));
75 
76 static cl::opt<int> MaxStoresPerMemsetCL("max-store-memset",
77   cl::Hidden, cl::ZeroOrMore, cl::init(8),
78   cl::desc("Max #stores to inline memset"));
79 
80 static cl::opt<int> MaxStoresPerMemsetOptSizeCL("max-store-memset-Os",
81   cl::Hidden, cl::ZeroOrMore, cl::init(4),
82   cl::desc("Max #stores to inline memset"));
83 
84 
85 namespace {
86   class HexagonCCState : public CCState {
87     unsigned NumNamedVarArgParams;
88 
89   public:
90     HexagonCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
91                    SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
92                    int NumNamedVarArgParams)
93         : CCState(CC, isVarArg, MF, locs, C),
94           NumNamedVarArgParams(NumNamedVarArgParams) {}
95 
96     unsigned getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
97   };
98 
99   enum StridedLoadKind {
100     Even = 0,
101     Odd,
102     NoPattern
103   };
104 }
105 
106 // Implement calling convention for Hexagon.
107 
108 static bool isHvxVectorType(MVT ty);
109 
110 static bool
111 CC_Hexagon(unsigned ValNo, MVT ValVT,
112            MVT LocVT, CCValAssign::LocInfo LocInfo,
113            ISD::ArgFlagsTy ArgFlags, CCState &State);
114 
115 static bool
116 CC_Hexagon32(unsigned ValNo, MVT ValVT,
117              MVT LocVT, CCValAssign::LocInfo LocInfo,
118              ISD::ArgFlagsTy ArgFlags, CCState &State);
119 
120 static bool
121 CC_Hexagon64(unsigned ValNo, MVT ValVT,
122              MVT LocVT, CCValAssign::LocInfo LocInfo,
123              ISD::ArgFlagsTy ArgFlags, CCState &State);
124 
125 static bool
126 CC_HexagonVector(unsigned ValNo, MVT ValVT,
127                  MVT LocVT, CCValAssign::LocInfo LocInfo,
128                  ISD::ArgFlagsTy ArgFlags, CCState &State);
129 
130 static bool
131 RetCC_Hexagon(unsigned ValNo, MVT ValVT,
132               MVT LocVT, CCValAssign::LocInfo LocInfo,
133               ISD::ArgFlagsTy ArgFlags, CCState &State);
134 
135 static bool
136 RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
137                 MVT LocVT, CCValAssign::LocInfo LocInfo,
138                 ISD::ArgFlagsTy ArgFlags, CCState &State);
139 
140 static bool
141 RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
142                 MVT LocVT, CCValAssign::LocInfo LocInfo,
143                 ISD::ArgFlagsTy ArgFlags, CCState &State);
144 
145 static bool
146 RetCC_HexagonVector(unsigned ValNo, MVT ValVT,
147                     MVT LocVT, CCValAssign::LocInfo LocInfo,
148                     ISD::ArgFlagsTy ArgFlags, CCState &State);
149 
150 static bool
151 CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
152             MVT LocVT, CCValAssign::LocInfo LocInfo,
153             ISD::ArgFlagsTy ArgFlags, CCState &State) {
154   HexagonCCState &HState = static_cast<HexagonCCState &>(State);
155 
156   if (ValNo < HState.getNumNamedVarArgParams()) {
157     // Deal with named arguments.
158     return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
159   }
160 
161   // Deal with un-named arguments.
162   unsigned Offset;
163   if (ArgFlags.isByVal()) {
164     // If pass-by-value, the size allocated on stack is decided
165     // by ArgFlags.getByValSize(), not by the size of LocVT.
166     Offset = State.AllocateStack(ArgFlags.getByValSize(),
167                                  ArgFlags.getByValAlign());
168     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
169     return false;
170   }
171   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
172     LocVT = MVT::i32;
173     ValVT = MVT::i32;
174     if (ArgFlags.isSExt())
175       LocInfo = CCValAssign::SExt;
176     else if (ArgFlags.isZExt())
177       LocInfo = CCValAssign::ZExt;
178     else
179       LocInfo = CCValAssign::AExt;
180   }
181   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
182     Offset = State.AllocateStack(4, 4);
183     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
184     return false;
185   }
186   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
187     Offset = State.AllocateStack(8, 8);
188     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
189     return false;
190   }
191   if (LocVT == MVT::v2i64 || LocVT == MVT::v4i32 || LocVT == MVT::v8i16 ||
192       LocVT == MVT::v16i8) {
193     Offset = State.AllocateStack(16, 16);
194     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
195     return false;
196   }
197   if (LocVT == MVT::v4i64 || LocVT == MVT::v8i32 || LocVT == MVT::v16i16 ||
198       LocVT == MVT::v32i8) {
199     Offset = State.AllocateStack(32, 32);
200     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
201     return false;
202   }
203   if (LocVT == MVT::v8i64 || LocVT == MVT::v16i32 || LocVT == MVT::v32i16 ||
204       LocVT == MVT::v64i8 || LocVT == MVT::v512i1) {
205     Offset = State.AllocateStack(64, 64);
206     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
207     return false;
208   }
209   if (LocVT == MVT::v16i64 || LocVT == MVT::v32i32 || LocVT == MVT::v64i16 ||
210       LocVT == MVT::v128i8 || LocVT == MVT::v1024i1) {
211     Offset = State.AllocateStack(128, 128);
212     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
213     return false;
214   }
215   if (LocVT == MVT::v32i64 || LocVT == MVT::v64i32 || LocVT == MVT::v128i16 ||
216       LocVT == MVT::v256i8) {
217     Offset = State.AllocateStack(256, 256);
218     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
219     return false;
220   }
221 
222   llvm_unreachable(nullptr);
223 }
224 
225 
226 static bool CC_Hexagon (unsigned ValNo, MVT ValVT, MVT LocVT,
227       CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State) {
228   if (ArgFlags.isByVal()) {
229     // Passed on stack.
230     unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(),
231                                           ArgFlags.getByValAlign());
232     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
233     return false;
234   }
235 
236   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
237     LocVT = MVT::i32;
238     ValVT = MVT::i32;
239     if (ArgFlags.isSExt())
240       LocInfo = CCValAssign::SExt;
241     else if (ArgFlags.isZExt())
242       LocInfo = CCValAssign::ZExt;
243     else
244       LocInfo = CCValAssign::AExt;
245   } else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
246     LocVT = MVT::i32;
247     LocInfo = CCValAssign::BCvt;
248   } else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
249     LocVT = MVT::i64;
250     LocInfo = CCValAssign::BCvt;
251   }
252 
253   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
254     if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
255       return false;
256   }
257 
258   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
259     if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
260       return false;
261   }
262 
263   if (LocVT == MVT::v8i32 || LocVT == MVT::v16i16 || LocVT == MVT::v32i8) {
264     unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 32);
265     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
266     return false;
267   }
268 
269   if (isHvxVectorType(LocVT)) {
270     if (!CC_HexagonVector(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
271       return false;
272   }
273 
274   return true;  // CC didn't match.
275 }
276 
277 
278 static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
279                          MVT LocVT, CCValAssign::LocInfo LocInfo,
280                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
281 
282   static const MCPhysReg RegList[] = {
283     Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
284     Hexagon::R5
285   };
286   if (unsigned Reg = State.AllocateReg(RegList)) {
287     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
288     return false;
289   }
290 
291   unsigned Offset = State.AllocateStack(4, 4);
292   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
293   return false;
294 }
295 
296 static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
297                          MVT LocVT, CCValAssign::LocInfo LocInfo,
298                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
299 
300   if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
301     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
302     return false;
303   }
304 
305   static const MCPhysReg RegList1[] = {
306     Hexagon::D1, Hexagon::D2
307   };
308   static const MCPhysReg RegList2[] = {
309     Hexagon::R1, Hexagon::R3
310   };
311   if (unsigned Reg = State.AllocateReg(RegList1, RegList2)) {
312     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
313     return false;
314   }
315 
316   unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
317   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
318   return false;
319 }
320 
321 static bool CC_HexagonVector(unsigned ValNo, MVT ValVT,
322                              MVT LocVT, CCValAssign::LocInfo LocInfo,
323                              ISD::ArgFlagsTy ArgFlags, CCState &State) {
324 
325   static const MCPhysReg VecLstS[] = {
326       Hexagon::V0, Hexagon::V1, Hexagon::V2, Hexagon::V3, Hexagon::V4,
327       Hexagon::V5, Hexagon::V6, Hexagon::V7, Hexagon::V8, Hexagon::V9,
328       Hexagon::V10, Hexagon::V11, Hexagon::V12, Hexagon::V13, Hexagon::V14,
329       Hexagon::V15
330   };
331   static const MCPhysReg VecLstD[] = {
332       Hexagon::W0, Hexagon::W1, Hexagon::W2, Hexagon::W3, Hexagon::W4,
333       Hexagon::W5, Hexagon::W6, Hexagon::W7
334   };
335   auto &MF = State.getMachineFunction();
336   auto &HST = MF.getSubtarget<HexagonSubtarget>();
337   bool UseHVX = HST.useHVXOps();
338   bool UseHVXDbl = HST.useHVXDblOps();
339 
340   if ((UseHVX && !UseHVXDbl) &&
341       (LocVT == MVT::v8i64 || LocVT == MVT::v16i32 || LocVT == MVT::v32i16 ||
342        LocVT == MVT::v64i8 || LocVT == MVT::v512i1)) {
343     if (unsigned Reg = State.AllocateReg(VecLstS)) {
344       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
345       return false;
346     }
347     unsigned Offset = State.AllocateStack(64, 64);
348     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
349     return false;
350   }
351   if ((UseHVX && !UseHVXDbl) &&
352       (LocVT == MVT::v16i64 || LocVT == MVT::v32i32 || LocVT == MVT::v64i16 ||
353        LocVT == MVT::v128i8)) {
354     if (unsigned Reg = State.AllocateReg(VecLstD)) {
355       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
356       return false;
357     }
358     unsigned Offset = State.AllocateStack(128, 128);
359     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
360     return false;
361   }
362   // 128B Mode
363   if ((UseHVX && UseHVXDbl) &&
364       (LocVT == MVT::v32i64 || LocVT == MVT::v64i32 || LocVT == MVT::v128i16 ||
365        LocVT == MVT::v256i8)) {
366     if (unsigned Reg = State.AllocateReg(VecLstD)) {
367       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
368       return false;
369     }
370     unsigned Offset = State.AllocateStack(256, 256);
371     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
372     return false;
373   }
374   if ((UseHVX && UseHVXDbl) &&
375       (LocVT == MVT::v16i64 || LocVT == MVT::v32i32 || LocVT == MVT::v64i16 ||
376        LocVT == MVT::v128i8 || LocVT == MVT::v1024i1)) {
377     if (unsigned Reg = State.AllocateReg(VecLstS)) {
378       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
379       return false;
380     }
381     unsigned Offset = State.AllocateStack(128, 128);
382     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
383     return false;
384   }
385   return true;
386 }
387 
388 static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
389                           MVT LocVT, CCValAssign::LocInfo LocInfo,
390                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
391   auto &MF = State.getMachineFunction();
392   auto &HST = MF.getSubtarget<HexagonSubtarget>();
393   bool UseHVX = HST.useHVXOps();
394   bool UseHVXDbl = HST.useHVXDblOps();
395 
396   if (LocVT == MVT::i1) {
397     // Return values of type MVT::i1 still need to be assigned to R0, but
398     // the value type needs to remain i1. LowerCallResult will deal with it,
399     // but it needs to recognize i1 as the value type.
400     LocVT = MVT::i32;
401   } else if (LocVT == MVT::i8 || LocVT == MVT::i16) {
402     LocVT = MVT::i32;
403     ValVT = MVT::i32;
404     if (ArgFlags.isSExt())
405       LocInfo = CCValAssign::SExt;
406     else if (ArgFlags.isZExt())
407       LocInfo = CCValAssign::ZExt;
408     else
409       LocInfo = CCValAssign::AExt;
410   } else if (LocVT == MVT::v4i8 || LocVT == MVT::v2i16) {
411     LocVT = MVT::i32;
412     LocInfo = CCValAssign::BCvt;
413   } else if (LocVT == MVT::v8i8 || LocVT == MVT::v4i16 || LocVT == MVT::v2i32) {
414     LocVT = MVT::i64;
415     LocInfo = CCValAssign::BCvt;
416   } else if (LocVT == MVT::v64i8 || LocVT == MVT::v32i16 ||
417              LocVT == MVT::v16i32 || LocVT == MVT::v8i64 ||
418              LocVT == MVT::v512i1) {
419     LocVT = MVT::v16i32;
420     ValVT = MVT::v16i32;
421     LocInfo = CCValAssign::Full;
422   } else if (LocVT == MVT::v128i8 || LocVT == MVT::v64i16 ||
423              LocVT == MVT::v32i32 || LocVT == MVT::v16i64 ||
424              (LocVT == MVT::v1024i1 && UseHVX && UseHVXDbl)) {
425     LocVT = MVT::v32i32;
426     ValVT = MVT::v32i32;
427     LocInfo = CCValAssign::Full;
428   } else if (LocVT == MVT::v256i8 || LocVT == MVT::v128i16 ||
429              LocVT == MVT::v64i32 || LocVT == MVT::v32i64) {
430     LocVT = MVT::v64i32;
431     ValVT = MVT::v64i32;
432     LocInfo = CCValAssign::Full;
433   }
434   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
435     if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
436       return false;
437   }
438 
439   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
440     if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
441       return false;
442   }
443   if (LocVT == MVT::v16i32 || LocVT == MVT::v32i32 || LocVT == MVT::v64i32) {
444     if (!RetCC_HexagonVector(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
445       return false;
446   }
447   return true;  // CC didn't match.
448 }
449 
450 static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
451                             MVT LocVT, CCValAssign::LocInfo LocInfo,
452                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
453   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
454     // Note that use of registers beyond R1 is not ABI compliant. However there
455     // are (experimental) IR passes which generate internal functions that
456     // return structs using these additional registers.
457     static const uint16_t RegList[] = { Hexagon::R0, Hexagon::R1,
458                                         Hexagon::R2, Hexagon::R3,
459                                         Hexagon::R4, Hexagon::R5 };
460     if (unsigned Reg = State.AllocateReg(RegList)) {
461       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
462       return false;
463     }
464   }
465 
466   unsigned Offset = State.AllocateStack(4, 4);
467   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
468   return false;
469 }
470 
471 static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
472                             MVT LocVT, CCValAssign::LocInfo LocInfo,
473                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
474   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
475     if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
476       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
477       return false;
478     }
479   }
480 
481   unsigned Offset = State.AllocateStack(8, 8);
482   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
483   return false;
484 }
485 
486 static bool RetCC_HexagonVector(unsigned ValNo, MVT ValVT,
487                                 MVT LocVT, CCValAssign::LocInfo LocInfo,
488                                 ISD::ArgFlagsTy ArgFlags, CCState &State) {
489   auto &MF = State.getMachineFunction();
490   auto &HST = MF.getSubtarget<HexagonSubtarget>();
491   bool UseHVX = HST.useHVXOps();
492   bool UseHVXDbl = HST.useHVXDblOps();
493 
494   unsigned OffSiz = 64;
495   if (LocVT == MVT::v16i32) {
496     if (unsigned Reg = State.AllocateReg(Hexagon::V0)) {
497       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
498       return false;
499     }
500   } else if (LocVT == MVT::v32i32) {
501     unsigned Req = (UseHVX && UseHVXDbl) ? Hexagon::V0 : Hexagon::W0;
502     if (unsigned Reg = State.AllocateReg(Req)) {
503       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
504       return false;
505     }
506     OffSiz = 128;
507   } else if (LocVT == MVT::v64i32) {
508     if (unsigned Reg = State.AllocateReg(Hexagon::W0)) {
509       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
510       return false;
511     }
512     OffSiz = 256;
513   }
514 
515   unsigned Offset = State.AllocateStack(OffSiz, OffSiz);
516   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
517   return false;
518 }
519 
520 void HexagonTargetLowering::promoteLdStType(MVT VT, MVT PromotedLdStVT) {
521   if (VT != PromotedLdStVT) {
522     setOperationAction(ISD::LOAD, VT, Promote);
523     AddPromotedToType(ISD::LOAD, VT, PromotedLdStVT);
524 
525     setOperationAction(ISD::STORE, VT, Promote);
526     AddPromotedToType(ISD::STORE, VT, PromotedLdStVT);
527   }
528 }
529 
530 SDValue
531 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
532       const {
533   return SDValue();
534 }
535 
536 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
537 /// by "Src" to address "Dst" of size "Size".  Alignment information is
538 /// specified by the specific parameter attribute. The copy will be passed as
539 /// a byval function parameter.  Sometimes what we are copying is the end of a
540 /// larger object, the part that does not fit in registers.
541 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
542                                          SDValue Chain, ISD::ArgFlagsTy Flags,
543                                          SelectionDAG &DAG, const SDLoc &dl) {
544   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
545   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
546                        /*isVolatile=*/false, /*AlwaysInline=*/false,
547                        /*isTailCall=*/false,
548                        MachinePointerInfo(), MachinePointerInfo());
549 }
550 
551 static bool isHvxVectorType(MVT Ty) {
552   switch (Ty.SimpleTy) {
553   case MVT::v8i64:
554   case MVT::v16i32:
555   case MVT::v32i16:
556   case MVT::v64i8:
557   case MVT::v16i64:
558   case MVT::v32i32:
559   case MVT::v64i16:
560   case MVT::v128i8:
561   case MVT::v32i64:
562   case MVT::v64i32:
563   case MVT::v128i16:
564   case MVT::v256i8:
565   case MVT::v512i1:
566   case MVT::v1024i1:
567     return true;
568   default:
569     return false;
570   }
571 }
572 
573 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
574 // passed by value, the function prototype is modified to return void and
575 // the value is stored in memory pointed by a pointer passed by caller.
576 SDValue
577 HexagonTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
578                                    bool isVarArg,
579                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
580                                    const SmallVectorImpl<SDValue> &OutVals,
581                                    const SDLoc &dl, SelectionDAG &DAG) const {
582 
583   // CCValAssign - represent the assignment of the return value to locations.
584   SmallVector<CCValAssign, 16> RVLocs;
585 
586   // CCState - Info about the registers and stack slot.
587   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
588                  *DAG.getContext());
589 
590   // Analyze return values of ISD::RET
591   CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
592 
593   SDValue Flag;
594   SmallVector<SDValue, 4> RetOps(1, Chain);
595 
596   // Copy the result values into the output registers.
597   for (unsigned i = 0; i != RVLocs.size(); ++i) {
598     CCValAssign &VA = RVLocs[i];
599 
600     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
601 
602     // Guarantee that all emitted copies are stuck together with flags.
603     Flag = Chain.getValue(1);
604     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
605   }
606 
607   RetOps[0] = Chain;  // Update chain.
608 
609   // Add the flag if we have it.
610   if (Flag.getNode())
611     RetOps.push_back(Flag);
612 
613   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
614 }
615 
616 bool HexagonTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
617   // If either no tail call or told not to tail call at all, don't.
618   auto Attr =
619       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
620   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
621     return false;
622 
623   return true;
624 }
625 
626 /// LowerCallResult - Lower the result values of an ISD::CALL into the
627 /// appropriate copies out of appropriate physical registers.  This assumes that
628 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
629 /// being lowered. Returns a SDNode with the same number of values as the
630 /// ISD::CALL.
631 SDValue HexagonTargetLowering::LowerCallResult(
632     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
633     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
634     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
635     const SmallVectorImpl<SDValue> &OutVals, SDValue Callee) const {
636   // Assign locations to each value returned by this call.
637   SmallVector<CCValAssign, 16> RVLocs;
638 
639   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
640                  *DAG.getContext());
641 
642   CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
643 
644   // Copy all of the result registers out of their specified physreg.
645   for (unsigned i = 0; i != RVLocs.size(); ++i) {
646     SDValue RetVal;
647     if (RVLocs[i].getValVT() == MVT::i1) {
648       // Return values of type MVT::i1 require special handling. The reason
649       // is that MVT::i1 is associated with the PredRegs register class, but
650       // values of that type are still returned in R0. Generate an explicit
651       // copy into a predicate register from R0, and treat the value of the
652       // predicate register as the call result.
653       auto &MRI = DAG.getMachineFunction().getRegInfo();
654       SDValue FR0 = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
655                                        MVT::i32, InFlag);
656       // FR0 = (Value, Chain, Glue)
657       unsigned PredR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
658       SDValue TPR = DAG.getCopyToReg(FR0.getValue(1), dl, PredR,
659                                      FR0.getValue(0), FR0.getValue(2));
660       // TPR = (Chain, Glue)
661       RetVal = DAG.getCopyFromReg(TPR.getValue(0), dl, PredR, MVT::i1,
662                                   TPR.getValue(1));
663     } else {
664       RetVal = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
665                                   RVLocs[i].getValVT(), InFlag);
666     }
667     InVals.push_back(RetVal.getValue(0));
668     Chain = RetVal.getValue(1);
669     InFlag = RetVal.getValue(2);
670   }
671 
672   return Chain;
673 }
674 
675 /// LowerCall - Functions arguments are copied from virtual regs to
676 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
677 SDValue
678 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
679                                  SmallVectorImpl<SDValue> &InVals) const {
680   SelectionDAG &DAG                     = CLI.DAG;
681   SDLoc &dl                             = CLI.DL;
682   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
683   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
684   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
685   SDValue Chain                         = CLI.Chain;
686   SDValue Callee                        = CLI.Callee;
687   bool &IsTailCall                      = CLI.IsTailCall;
688   CallingConv::ID CallConv              = CLI.CallConv;
689   bool IsVarArg                         = CLI.IsVarArg;
690   bool DoesNotReturn                    = CLI.DoesNotReturn;
691 
692   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
693   MachineFunction &MF = DAG.getMachineFunction();
694   auto PtrVT = getPointerTy(MF.getDataLayout());
695 
696   // Check for varargs.
697   unsigned NumNamedVarArgParams = -1U;
698   if (GlobalAddressSDNode *GAN = dyn_cast<GlobalAddressSDNode>(Callee)) {
699     const GlobalValue *GV = GAN->getGlobal();
700     Callee = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
701     if (const Function* F = dyn_cast<Function>(GV)) {
702       // If a function has zero args and is a vararg function, that's
703       // disallowed so it must be an undeclared function.  Do not assume
704       // varargs if the callee is undefined.
705       if (F->isVarArg() && F->getFunctionType()->getNumParams() != 0)
706         NumNamedVarArgParams = F->getFunctionType()->getNumParams();
707     }
708   }
709 
710   // Analyze operands of the call, assigning locations to each operand.
711   SmallVector<CCValAssign, 16> ArgLocs;
712   HexagonCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
713                         *DAG.getContext(), NumNamedVarArgParams);
714 
715   if (IsVarArg)
716     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
717   else
718     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
719 
720   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
721   if (Attr.getValueAsString() == "true")
722     IsTailCall = false;
723 
724   if (IsTailCall) {
725     bool StructAttrFlag = MF.getFunction()->hasStructRetAttr();
726     IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
727                                                    IsVarArg, IsStructRet,
728                                                    StructAttrFlag,
729                                                    Outs, OutVals, Ins, DAG);
730     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
731       CCValAssign &VA = ArgLocs[i];
732       if (VA.isMemLoc()) {
733         IsTailCall = false;
734         break;
735       }
736     }
737     DEBUG(dbgs() << (IsTailCall ? "Eligible for Tail Call\n"
738                                 : "Argument must be passed on stack. "
739                                   "Not eligible for Tail Call\n"));
740   }
741   // Get a count of how many bytes are to be pushed on the stack.
742   unsigned NumBytes = CCInfo.getNextStackOffset();
743   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
744   SmallVector<SDValue, 8> MemOpChains;
745 
746   auto &HRI = *Subtarget.getRegisterInfo();
747   SDValue StackPtr =
748       DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(), PtrVT);
749 
750   bool NeedsArgAlign = false;
751   unsigned LargestAlignSeen = 0;
752   // Walk the register/memloc assignments, inserting copies/loads.
753   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
754     CCValAssign &VA = ArgLocs[i];
755     SDValue Arg = OutVals[i];
756     ISD::ArgFlagsTy Flags = Outs[i].Flags;
757     // Record if we need > 8 byte alignment on an argument.
758     bool ArgAlign = isHvxVectorType(VA.getValVT());
759     NeedsArgAlign |= ArgAlign;
760 
761     // Promote the value if needed.
762     switch (VA.getLocInfo()) {
763       default:
764         // Loc info must be one of Full, SExt, ZExt, or AExt.
765         llvm_unreachable("Unknown loc info!");
766       case CCValAssign::BCvt:
767       case CCValAssign::Full:
768         break;
769       case CCValAssign::SExt:
770         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
771         break;
772       case CCValAssign::ZExt:
773         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
774         break;
775       case CCValAssign::AExt:
776         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
777         break;
778     }
779 
780     if (VA.isMemLoc()) {
781       unsigned LocMemOffset = VA.getLocMemOffset();
782       SDValue MemAddr = DAG.getConstant(LocMemOffset, dl,
783                                         StackPtr.getValueType());
784       MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, MemAddr);
785       if (ArgAlign)
786         LargestAlignSeen = std::max(LargestAlignSeen,
787                                     VA.getLocVT().getStoreSizeInBits() >> 3);
788       if (Flags.isByVal()) {
789         // The argument is a struct passed by value. According to LLVM, "Arg"
790         // is is pointer.
791         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
792                                                         Flags, DAG, dl));
793       } else {
794         MachinePointerInfo LocPI = MachinePointerInfo::getStack(
795             DAG.getMachineFunction(), LocMemOffset);
796         SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI);
797         MemOpChains.push_back(S);
798       }
799       continue;
800     }
801 
802     // Arguments that can be passed on register must be kept at RegsToPass
803     // vector.
804     if (VA.isRegLoc())
805       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
806   }
807 
808   if (NeedsArgAlign && Subtarget.hasV60TOps()) {
809     DEBUG(dbgs() << "Function needs byte stack align due to call args\n");
810     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
811     // V6 vectors passed by value have 64 or 128 byte alignment depending
812     // on whether we are 64 byte vector mode or 128 byte.
813     bool UseHVXDbl = Subtarget.useHVXDblOps();
814     assert(Subtarget.useHVXOps());
815     const unsigned ObjAlign = UseHVXDbl ? 128 : 64;
816     LargestAlignSeen = std::max(LargestAlignSeen, ObjAlign);
817     MFI.ensureMaxAlignment(LargestAlignSeen);
818   }
819   // Transform all store nodes into one single node because all store
820   // nodes are independent of each other.
821   if (!MemOpChains.empty())
822     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
823 
824   if (!IsTailCall) {
825     SDValue C = DAG.getConstant(NumBytes, dl, PtrVT, true);
826     Chain = DAG.getCALLSEQ_START(Chain, C, dl);
827   }
828 
829   // Build a sequence of copy-to-reg nodes chained together with token
830   // chain and flag operands which copy the outgoing args into registers.
831   // The Glue is necessary since all emitted instructions must be
832   // stuck together.
833   SDValue Glue;
834   if (!IsTailCall) {
835     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
836       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
837                                RegsToPass[i].second, Glue);
838       Glue = Chain.getValue(1);
839     }
840   } else {
841     // For tail calls lower the arguments to the 'real' stack slot.
842     //
843     // Force all the incoming stack arguments to be loaded from the stack
844     // before any new outgoing arguments are stored to the stack, because the
845     // outgoing stack slots may alias the incoming argument stack slots, and
846     // the alias isn't otherwise explicit. This is slightly more conservative
847     // than necessary, because it means that each store effectively depends
848     // on every argument instead of just those arguments it would clobber.
849     //
850     // Do not flag preceding copytoreg stuff together with the following stuff.
851     Glue = SDValue();
852     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
853       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
854                                RegsToPass[i].second, Glue);
855       Glue = Chain.getValue(1);
856     }
857     Glue = SDValue();
858   }
859 
860   bool LongCalls = MF.getSubtarget<HexagonSubtarget>().useLongCalls();
861   unsigned Flags = LongCalls ? HexagonII::HMOTF_ConstExtended : 0;
862 
863   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
864   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
865   // node so that legalize doesn't hack it.
866   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
867     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, PtrVT, 0, Flags);
868   } else if (ExternalSymbolSDNode *S =
869              dyn_cast<ExternalSymbolSDNode>(Callee)) {
870     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, Flags);
871   }
872 
873   // Returns a chain & a flag for retval copy to use.
874   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
875   SmallVector<SDValue, 8> Ops;
876   Ops.push_back(Chain);
877   Ops.push_back(Callee);
878 
879   // Add argument registers to the end of the list so that they are
880   // known live into the call.
881   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
882     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
883                                   RegsToPass[i].second.getValueType()));
884   }
885 
886   if (Glue.getNode())
887     Ops.push_back(Glue);
888 
889   if (IsTailCall) {
890     MF.getFrameInfo().setHasTailCall();
891     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
892   }
893 
894   unsigned OpCode = DoesNotReturn ? HexagonISD::CALLnr : HexagonISD::CALL;
895   Chain = DAG.getNode(OpCode, dl, NodeTys, Ops);
896   Glue = Chain.getValue(1);
897 
898   // Create the CALLSEQ_END node.
899   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
900                              DAG.getIntPtrConstant(0, dl, true), Glue, dl);
901   Glue = Chain.getValue(1);
902 
903   // Handle result values, copying them out of physregs into vregs that we
904   // return.
905   return LowerCallResult(Chain, Glue, CallConv, IsVarArg, Ins, dl, DAG,
906                          InVals, OutVals, Callee);
907 }
908 
909 static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
910                                    SDValue &Base, SDValue &Offset,
911                                    bool &IsInc, SelectionDAG &DAG) {
912   if (Ptr->getOpcode() != ISD::ADD)
913     return false;
914 
915   auto &HST = static_cast<const HexagonSubtarget&>(DAG.getSubtarget());
916   bool UseHVX = HST.useHVXOps();
917   bool UseHVXDbl = HST.useHVXDblOps();
918 
919   bool ValidHVXDblType =
920     (UseHVX && UseHVXDbl) && (VT == MVT::v32i32 || VT == MVT::v16i64 ||
921                               VT == MVT::v64i16 || VT == MVT::v128i8);
922   bool ValidHVXType =
923     UseHVX && !UseHVXDbl && (VT == MVT::v16i32 || VT == MVT::v8i64 ||
924                              VT == MVT::v32i16 || VT == MVT::v64i8);
925 
926   if (ValidHVXDblType || ValidHVXType ||
927       VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
928     IsInc = (Ptr->getOpcode() == ISD::ADD);
929     Base = Ptr->getOperand(0);
930     Offset = Ptr->getOperand(1);
931     // Ensure that Offset is a constant.
932     return isa<ConstantSDNode>(Offset);
933   }
934 
935   return false;
936 }
937 
938 /// getPostIndexedAddressParts - returns true by value, base pointer and
939 /// offset pointer and addressing mode by reference if this node can be
940 /// combined with a load / store to form a post-indexed load / store.
941 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
942                                                        SDValue &Base,
943                                                        SDValue &Offset,
944                                                        ISD::MemIndexedMode &AM,
945                                                        SelectionDAG &DAG) const
946 {
947   EVT VT;
948   SDValue Ptr;
949 
950   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
951     VT  = LD->getMemoryVT();
952   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
953     VT  = ST->getMemoryVT();
954     if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore())
955       return false;
956   } else {
957     return false;
958   }
959 
960   bool IsInc = false;
961   bool isLegal = getIndexedAddressParts(Op, VT, Base, Offset, IsInc, DAG);
962   if (isLegal) {
963     auto &HII = *Subtarget.getInstrInfo();
964     int32_t OffsetVal = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
965     if (HII.isValidAutoIncImm(VT, OffsetVal)) {
966       AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
967       return true;
968     }
969   }
970 
971   return false;
972 }
973 
974 SDValue
975 HexagonTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
976   SDNode *Node = Op.getNode();
977   MachineFunction &MF = DAG.getMachineFunction();
978   auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
979   switch (Node->getOpcode()) {
980     case ISD::INLINEASM: {
981       unsigned NumOps = Node->getNumOperands();
982       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
983         --NumOps;  // Ignore the flag operand.
984 
985       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
986         if (FuncInfo.hasClobberLR())
987           break;
988         unsigned Flags =
989           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
990         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
991         ++i;  // Skip the ID value.
992 
993         switch (InlineAsm::getKind(Flags)) {
994         default: llvm_unreachable("Bad flags!");
995           case InlineAsm::Kind_RegDef:
996           case InlineAsm::Kind_RegUse:
997           case InlineAsm::Kind_Imm:
998           case InlineAsm::Kind_Clobber:
999           case InlineAsm::Kind_Mem: {
1000             for (; NumVals; --NumVals, ++i) {}
1001             break;
1002           }
1003           case InlineAsm::Kind_RegDefEarlyClobber: {
1004             for (; NumVals; --NumVals, ++i) {
1005               unsigned Reg =
1006                 cast<RegisterSDNode>(Node->getOperand(i))->getReg();
1007 
1008               // Check it to be lr
1009               const HexagonRegisterInfo *QRI = Subtarget.getRegisterInfo();
1010               if (Reg == QRI->getRARegister()) {
1011                 FuncInfo.setHasClobberLR(true);
1012                 break;
1013               }
1014             }
1015             break;
1016           }
1017         }
1018       }
1019     }
1020   } // Node->getOpcode
1021   return Op;
1022 }
1023 
1024 // Need to transform ISD::PREFETCH into something that doesn't inherit
1025 // all of the properties of ISD::PREFETCH, specifically SDNPMayLoad and
1026 // SDNPMayStore.
1027 SDValue HexagonTargetLowering::LowerPREFETCH(SDValue Op,
1028                                              SelectionDAG &DAG) const {
1029   SDValue Chain = Op.getOperand(0);
1030   SDValue Addr = Op.getOperand(1);
1031   // Lower it to DCFETCH($reg, #0).  A "pat" will try to merge the offset in,
1032   // if the "reg" is fed by an "add".
1033   SDLoc DL(Op);
1034   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1035   return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
1036 }
1037 
1038 SDValue HexagonTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1039       SelectionDAG &DAG) const {
1040   SDValue Chain = Op.getOperand(0);
1041   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1042   // Lower the hexagon_prefetch builtin to DCFETCH, as above.
1043   if (IntNo == Intrinsic::hexagon_prefetch) {
1044     SDValue Addr = Op.getOperand(2);
1045     SDLoc DL(Op);
1046     SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1047     return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
1048   }
1049   return SDValue();
1050 }
1051 
1052 SDValue
1053 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
1054                                                SelectionDAG &DAG) const {
1055   SDValue Chain = Op.getOperand(0);
1056   SDValue Size = Op.getOperand(1);
1057   SDValue Align = Op.getOperand(2);
1058   SDLoc dl(Op);
1059 
1060   ConstantSDNode *AlignConst = dyn_cast<ConstantSDNode>(Align);
1061   assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
1062 
1063   unsigned A = AlignConst->getSExtValue();
1064   auto &HFI = *Subtarget.getFrameLowering();
1065   // "Zero" means natural stack alignment.
1066   if (A == 0)
1067     A = HFI.getStackAlignment();
1068 
1069   DEBUG({
1070     dbgs () << __func__ << " Align: " << A << " Size: ";
1071     Size.getNode()->dump(&DAG);
1072     dbgs() << "\n";
1073   });
1074 
1075   SDValue AC = DAG.getConstant(A, dl, MVT::i32);
1076   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1077   SDValue AA = DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
1078 
1079   DAG.ReplaceAllUsesOfValueWith(Op, AA);
1080   return AA;
1081 }
1082 
1083 SDValue HexagonTargetLowering::LowerFormalArguments(
1084     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1085     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1086     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1087 
1088   MachineFunction &MF = DAG.getMachineFunction();
1089   MachineFrameInfo &MFI = MF.getFrameInfo();
1090   MachineRegisterInfo &RegInfo = MF.getRegInfo();
1091   auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
1092 
1093   // Assign locations to all of the incoming arguments.
1094   SmallVector<CCValAssign, 16> ArgLocs;
1095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1096                  *DAG.getContext());
1097 
1098   CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
1099 
1100   // For LLVM, in the case when returning a struct by value (>8byte),
1101   // the first argument is a pointer that points to the location on caller's
1102   // stack where the return value will be stored. For Hexagon, the location on
1103   // caller's stack is passed only when the struct size is smaller than (and
1104   // equal to) 8 bytes. If not, no address will be passed into callee and
1105   // callee return the result direclty through R0/R1.
1106 
1107   SmallVector<SDValue, 8> MemOps;
1108   bool UseHVX = Subtarget.useHVXOps(), UseHVXDbl = Subtarget.useHVXDblOps();
1109 
1110   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1111     CCValAssign &VA = ArgLocs[i];
1112     ISD::ArgFlagsTy Flags = Ins[i].Flags;
1113     unsigned ObjSize;
1114     unsigned StackLocation;
1115     int FI;
1116 
1117     if (   (VA.isRegLoc() && !Flags.isByVal())
1118         || (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
1119       // Arguments passed in registers
1120       // 1. int, long long, ptr args that get allocated in register.
1121       // 2. Large struct that gets an register to put its address in.
1122       EVT RegVT = VA.getLocVT();
1123       if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
1124           RegVT == MVT::i32 || RegVT == MVT::f32) {
1125         unsigned VReg =
1126           RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
1127         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1128         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1129       } else if (RegVT == MVT::i64 || RegVT == MVT::f64) {
1130         unsigned VReg =
1131           RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
1132         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1133         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1134 
1135       // Single Vector
1136       } else if ((RegVT == MVT::v8i64 || RegVT == MVT::v16i32 ||
1137                   RegVT == MVT::v32i16 || RegVT == MVT::v64i8)) {
1138         unsigned VReg =
1139           RegInfo.createVirtualRegister(&Hexagon::VectorRegsRegClass);
1140         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1141         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1142     } else if (UseHVX && UseHVXDbl &&
1143                ((RegVT == MVT::v16i64 || RegVT == MVT::v32i32 ||
1144                  RegVT == MVT::v64i16 || RegVT == MVT::v128i8))) {
1145         unsigned VReg =
1146           RegInfo.createVirtualRegister(&Hexagon::VectorRegs128BRegClass);
1147         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1148         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1149 
1150       // Double Vector
1151       } else if ((RegVT == MVT::v16i64 || RegVT == MVT::v32i32 ||
1152                   RegVT == MVT::v64i16 || RegVT == MVT::v128i8)) {
1153         unsigned VReg =
1154           RegInfo.createVirtualRegister(&Hexagon::VecDblRegsRegClass);
1155         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1156         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1157       } else if (UseHVX && UseHVXDbl &&
1158                 ((RegVT == MVT::v32i64 || RegVT == MVT::v64i32 ||
1159                   RegVT == MVT::v128i16 || RegVT == MVT::v256i8))) {
1160         unsigned VReg =
1161           RegInfo.createVirtualRegister(&Hexagon::VecDblRegs128BRegClass);
1162         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1163         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1164       } else if (RegVT == MVT::v512i1 || RegVT == MVT::v1024i1) {
1165         assert(0 && "need to support VecPred regs");
1166         unsigned VReg =
1167           RegInfo.createVirtualRegister(&Hexagon::VecPredRegsRegClass);
1168         RegInfo.addLiveIn(VA.getLocReg(), VReg);
1169         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1170       } else {
1171         assert (0);
1172       }
1173     } else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
1174       assert (0 && "ByValSize must be bigger than 8 bytes");
1175     } else {
1176       // Sanity check.
1177       assert(VA.isMemLoc());
1178 
1179       if (Flags.isByVal()) {
1180         // If it's a byval parameter, then we need to compute the
1181         // "real" size, not the size of the pointer.
1182         ObjSize = Flags.getByValSize();
1183       } else {
1184         ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
1185       }
1186 
1187       StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
1188       // Create the frame index object for this incoming parameter...
1189       FI = MFI.CreateFixedObject(ObjSize, StackLocation, true);
1190 
1191       // Create the SelectionDAG nodes cordl, responding to a load
1192       // from this parameter.
1193       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1194 
1195       if (Flags.isByVal()) {
1196         // If it's a pass-by-value aggregate, then do not dereference the stack
1197         // location. Instead, we should generate a reference to the stack
1198         // location.
1199         InVals.push_back(FIN);
1200       } else {
1201         InVals.push_back(
1202             DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, MachinePointerInfo()));
1203       }
1204     }
1205   }
1206 
1207   if (!MemOps.empty())
1208     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1209 
1210   if (isVarArg) {
1211     // This will point to the next argument passed via stack.
1212     int FrameIndex = MFI.CreateFixedObject(Hexagon_PointerSize,
1213                                            HEXAGON_LRFP_SIZE +
1214                                            CCInfo.getNextStackOffset(),
1215                                            true);
1216     FuncInfo.setVarArgsFrameIndex(FrameIndex);
1217   }
1218 
1219   return Chain;
1220 }
1221 
1222 SDValue
1223 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1224   // VASTART stores the address of the VarArgsFrameIndex slot into the
1225   // memory location argument.
1226   MachineFunction &MF = DAG.getMachineFunction();
1227   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
1228   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
1229   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1230   return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr, Op.getOperand(1),
1231                       MachinePointerInfo(SV));
1232 }
1233 
1234 // Creates a SPLAT instruction for a constant value VAL.
1235 static SDValue createSplat(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
1236                            SDValue Val) {
1237   if (VT.getSimpleVT() == MVT::v4i8)
1238     return DAG.getNode(HexagonISD::VSPLATB, dl, VT, Val);
1239 
1240   if (VT.getSimpleVT() == MVT::v4i16)
1241     return DAG.getNode(HexagonISD::VSPLATH, dl, VT, Val);
1242 
1243   return SDValue();
1244 }
1245 
1246 static bool isSExtFree(SDValue N) {
1247   // A sign-extend of a truncate of a sign-extend is free.
1248   if (N.getOpcode() == ISD::TRUNCATE &&
1249       N.getOperand(0).getOpcode() == ISD::AssertSext)
1250     return true;
1251   // We have sign-extended loads.
1252   if (N.getOpcode() == ISD::LOAD)
1253     return true;
1254   return false;
1255 }
1256 
1257 SDValue HexagonTargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
1258   SDLoc dl(Op);
1259   SDValue InpVal = Op.getOperand(0);
1260   if (isa<ConstantSDNode>(InpVal)) {
1261     uint64_t V = cast<ConstantSDNode>(InpVal)->getZExtValue();
1262     return DAG.getTargetConstant(countPopulation(V), dl, MVT::i64);
1263   }
1264   SDValue PopOut = DAG.getNode(HexagonISD::POPCOUNT, dl, MVT::i32, InpVal);
1265   return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, PopOut);
1266 }
1267 
1268 SDValue HexagonTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1269   SDLoc dl(Op);
1270 
1271   SDValue LHS = Op.getOperand(0);
1272   SDValue RHS = Op.getOperand(1);
1273   SDValue Cmp = Op.getOperand(2);
1274   ISD::CondCode CC = cast<CondCodeSDNode>(Cmp)->get();
1275 
1276   EVT VT = Op.getValueType();
1277   EVT LHSVT = LHS.getValueType();
1278   EVT RHSVT = RHS.getValueType();
1279 
1280   if (LHSVT == MVT::v2i16) {
1281     assert(ISD::isSignedIntSetCC(CC) || ISD::isUnsignedIntSetCC(CC));
1282     unsigned ExtOpc = ISD::isSignedIntSetCC(CC) ? ISD::SIGN_EXTEND
1283                                                 : ISD::ZERO_EXTEND;
1284     SDValue LX = DAG.getNode(ExtOpc, dl, MVT::v2i32, LHS);
1285     SDValue RX = DAG.getNode(ExtOpc, dl, MVT::v2i32, RHS);
1286     SDValue SC = DAG.getNode(ISD::SETCC, dl, MVT::v2i1, LX, RX, Cmp);
1287     return SC;
1288   }
1289 
1290   // Treat all other vector types as legal.
1291   if (VT.isVector())
1292     return Op;
1293 
1294   // Equals and not equals should use sign-extend, not zero-extend, since
1295   // we can represent small negative values in the compare instructions.
1296   // The LLVM default is to use zero-extend arbitrarily in these cases.
1297   if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
1298       (RHSVT == MVT::i8 || RHSVT == MVT::i16) &&
1299       (LHSVT == MVT::i8 || LHSVT == MVT::i16)) {
1300     ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
1301     if (C && C->getAPIntValue().isNegative()) {
1302       LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
1303       RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
1304       return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
1305                          LHS, RHS, Op.getOperand(2));
1306     }
1307     if (isSExtFree(LHS) || isSExtFree(RHS)) {
1308       LHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, LHS);
1309       RHS = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, RHS);
1310       return DAG.getNode(ISD::SETCC, dl, Op.getValueType(),
1311                          LHS, RHS, Op.getOperand(2));
1312     }
1313   }
1314   return SDValue();
1315 }
1316 
1317 SDValue
1318 HexagonTargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
1319   SDValue PredOp = Op.getOperand(0);
1320   SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
1321   EVT OpVT = Op1.getValueType();
1322   SDLoc DL(Op);
1323 
1324   if (OpVT == MVT::v2i16) {
1325     SDValue X1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op1);
1326     SDValue X2 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i32, Op2);
1327     SDValue SL = DAG.getNode(ISD::VSELECT, DL, MVT::v2i32, PredOp, X1, X2);
1328     SDValue TR = DAG.getNode(ISD::TRUNCATE, DL, MVT::v2i16, SL);
1329     return TR;
1330   }
1331 
1332   return SDValue();
1333 }
1334 
1335 // Handle only specific vector loads.
1336 SDValue HexagonTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1337   EVT VT = Op.getValueType();
1338   SDLoc DL(Op);
1339   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
1340   SDValue Chain = LoadNode->getChain();
1341   SDValue Ptr = Op.getOperand(1);
1342   SDValue LoweredLoad;
1343   SDValue Result;
1344   SDValue Base = LoadNode->getBasePtr();
1345   ISD::LoadExtType Ext = LoadNode->getExtensionType();
1346   unsigned Alignment = LoadNode->getAlignment();
1347   SDValue LoadChain;
1348 
1349   if(Ext == ISD::NON_EXTLOAD)
1350     Ext = ISD::ZEXTLOAD;
1351 
1352   if (VT == MVT::v4i16) {
1353     if (Alignment == 2) {
1354       SDValue Loads[4];
1355       // Base load.
1356       Loads[0] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Base,
1357                                 LoadNode->getPointerInfo(), MVT::i16, Alignment,
1358                                 LoadNode->getMemOperand()->getFlags());
1359       // Base+2 load.
1360       SDValue Increment = DAG.getConstant(2, DL, MVT::i32);
1361       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1362       Loads[1] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1363                                 LoadNode->getPointerInfo(), MVT::i16, Alignment,
1364                                 LoadNode->getMemOperand()->getFlags());
1365       // SHL 16, then OR base and base+2.
1366       SDValue ShiftAmount = DAG.getConstant(16, DL, MVT::i32);
1367       SDValue Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[1], ShiftAmount);
1368       SDValue Tmp2 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[0]);
1369       // Base + 4.
1370       Increment = DAG.getConstant(4, DL, MVT::i32);
1371       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1372       Loads[2] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1373                                 LoadNode->getPointerInfo(), MVT::i16, Alignment,
1374                                 LoadNode->getMemOperand()->getFlags());
1375       // Base + 6.
1376       Increment = DAG.getConstant(6, DL, MVT::i32);
1377       Ptr = DAG.getNode(ISD::ADD, DL, Base.getValueType(), Base, Increment);
1378       Loads[3] = DAG.getExtLoad(Ext, DL, MVT::i32, Chain, Ptr,
1379                                 LoadNode->getPointerInfo(), MVT::i16, Alignment,
1380                                 LoadNode->getMemOperand()->getFlags());
1381       // SHL 16, then OR base+4 and base+6.
1382       Tmp1 = DAG.getNode(ISD::SHL, DL, MVT::i32, Loads[3], ShiftAmount);
1383       SDValue Tmp4 = DAG.getNode(ISD::OR, DL, MVT::i32, Tmp1, Loads[2]);
1384       // Combine to i64. This could be optimised out later if we can
1385       // affect reg allocation of this code.
1386       Result = DAG.getNode(HexagonISD::COMBINE, DL, MVT::i64, Tmp4, Tmp2);
1387       LoadChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1388                               Loads[0].getValue(1), Loads[1].getValue(1),
1389                               Loads[2].getValue(1), Loads[3].getValue(1));
1390     } else {
1391       // Perform default type expansion.
1392       Result = DAG.getLoad(MVT::i64, DL, Chain, Ptr, LoadNode->getPointerInfo(),
1393                            LoadNode->getAlignment(),
1394                            LoadNode->getMemOperand()->getFlags());
1395       LoadChain = Result.getValue(1);
1396     }
1397   } else
1398     llvm_unreachable("Custom lowering unsupported load");
1399 
1400   Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
1401   // Since we pretend to lower a load, we need the original chain
1402   // info attached to the result.
1403   SDValue Ops[] = { Result, LoadChain };
1404 
1405   return DAG.getMergeValues(Ops, DL);
1406 }
1407 
1408 
1409 SDValue
1410 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
1411   EVT ValTy = Op.getValueType();
1412   ConstantPoolSDNode *CPN = cast<ConstantPoolSDNode>(Op);
1413   unsigned Align = CPN->getAlignment();
1414   bool IsPositionIndependent = isPositionIndependent();
1415   unsigned char TF = IsPositionIndependent ? HexagonII::MO_PCREL : 0;
1416 
1417   unsigned Offset = 0;
1418   SDValue T;
1419   if (CPN->isMachineConstantPoolEntry())
1420     T = DAG.getTargetConstantPool(CPN->getMachineCPVal(), ValTy, Align, Offset,
1421                                   TF);
1422   else
1423     T = DAG.getTargetConstantPool(CPN->getConstVal(), ValTy, Align, Offset,
1424                                   TF);
1425 
1426   assert(cast<ConstantPoolSDNode>(T)->getTargetFlags() == TF &&
1427          "Inconsistent target flag encountered");
1428 
1429   if (IsPositionIndependent)
1430     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), ValTy, T);
1431   return DAG.getNode(HexagonISD::CP, SDLoc(Op), ValTy, T);
1432 }
1433 
1434 SDValue
1435 HexagonTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1436   EVT VT = Op.getValueType();
1437   int Idx = cast<JumpTableSDNode>(Op)->getIndex();
1438   if (isPositionIndependent()) {
1439     SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
1440     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), VT, T);
1441   }
1442 
1443   SDValue T = DAG.getTargetJumpTable(Idx, VT);
1444   return DAG.getNode(HexagonISD::JT, SDLoc(Op), VT, T);
1445 }
1446 
1447 SDValue
1448 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
1449   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1450   MachineFunction &MF = DAG.getMachineFunction();
1451   MachineFrameInfo &MFI = MF.getFrameInfo();
1452   MFI.setReturnAddressIsTaken(true);
1453 
1454   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1455     return SDValue();
1456 
1457   EVT VT = Op.getValueType();
1458   SDLoc dl(Op);
1459   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1460   if (Depth) {
1461     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1462     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
1463     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
1464                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
1465                        MachinePointerInfo());
1466   }
1467 
1468   // Return LR, which contains the return address. Mark it an implicit live-in.
1469   unsigned Reg = MF.addLiveIn(HRI.getRARegister(), getRegClassFor(MVT::i32));
1470   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1471 }
1472 
1473 SDValue
1474 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1475   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1476   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1477   MFI.setFrameAddressIsTaken(true);
1478 
1479   EVT VT = Op.getValueType();
1480   SDLoc dl(Op);
1481   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1482   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1483                                          HRI.getFrameRegister(), VT);
1484   while (Depth--)
1485     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1486                             MachinePointerInfo());
1487   return FrameAddr;
1488 }
1489 
1490 SDValue
1491 HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op, SelectionDAG& DAG) const {
1492   SDLoc dl(Op);
1493   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1494 }
1495 
1496 
1497 SDValue
1498 HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op, SelectionDAG &DAG) const {
1499   SDLoc dl(Op);
1500   auto *GAN = cast<GlobalAddressSDNode>(Op);
1501   auto PtrVT = getPointerTy(DAG.getDataLayout());
1502   auto *GV = GAN->getGlobal();
1503   int64_t Offset = GAN->getOffset();
1504 
1505   auto &HLOF = *HTM.getObjFileLowering();
1506   Reloc::Model RM = HTM.getRelocationModel();
1507 
1508   if (RM == Reloc::Static) {
1509     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
1510     const GlobalObject *GO = GV->getBaseObject();
1511     if (GO && HLOF.isGlobalInSmallSection(GO, HTM))
1512       return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, GA);
1513     return DAG.getNode(HexagonISD::CONST32, dl, PtrVT, GA);
1514   }
1515 
1516   bool UsePCRel = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1517   if (UsePCRel) {
1518     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset,
1519                                             HexagonII::MO_PCREL);
1520     return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, GA);
1521   }
1522 
1523   // Use GOT index.
1524   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1525   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, HexagonII::MO_GOT);
1526   SDValue Off = DAG.getConstant(Offset, dl, MVT::i32);
1527   return DAG.getNode(HexagonISD::AT_GOT, dl, PtrVT, GOT, GA, Off);
1528 }
1529 
1530 // Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
1531 SDValue
1532 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1533   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1534   SDLoc dl(Op);
1535   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1536 
1537   Reloc::Model RM = HTM.getRelocationModel();
1538   if (RM == Reloc::Static) {
1539     SDValue A = DAG.getTargetBlockAddress(BA, PtrVT);
1540     return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, A);
1541   }
1542 
1543   SDValue A = DAG.getTargetBlockAddress(BA, PtrVT, 0, HexagonII::MO_PCREL);
1544   return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, A);
1545 }
1546 
1547 SDValue
1548 HexagonTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, SelectionDAG &DAG)
1549       const {
1550   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1551   SDValue GOTSym = DAG.getTargetExternalSymbol(HEXAGON_GOT_SYM_NAME, PtrVT,
1552                                                HexagonII::MO_PCREL);
1553   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), PtrVT, GOTSym);
1554 }
1555 
1556 SDValue
1557 HexagonTargetLowering::GetDynamicTLSAddr(SelectionDAG &DAG, SDValue Chain,
1558       GlobalAddressSDNode *GA, SDValue *InFlag, EVT PtrVT, unsigned ReturnReg,
1559       unsigned char OperandFlags) const {
1560   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1561   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1562   SDLoc dl(GA);
1563   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
1564                                            GA->getValueType(0),
1565                                            GA->getOffset(),
1566                                            OperandFlags);
1567   // Create Operands for the call.The Operands should have the following:
1568   // 1. Chain SDValue
1569   // 2. Callee which in this case is the Global address value.
1570   // 3. Registers live into the call.In this case its R0, as we
1571   //    have just one argument to be passed.
1572   // 4. InFlag if there is any.
1573   // Note: The order is important.
1574 
1575   if (InFlag) {
1576     SDValue Ops[] = { Chain, TGA,
1577                       DAG.getRegister(Hexagon::R0, PtrVT), *InFlag };
1578     Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
1579   } else {
1580     SDValue Ops[]  = { Chain, TGA, DAG.getRegister(Hexagon::R0, PtrVT)};
1581     Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
1582   }
1583 
1584   // Inform MFI that function has calls.
1585   MFI.setAdjustsStack(true);
1586 
1587   SDValue Flag = Chain.getValue(1);
1588   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
1589 }
1590 
1591 //
1592 // Lower using the intial executable model for TLS addresses
1593 //
1594 SDValue
1595 HexagonTargetLowering::LowerToTLSInitialExecModel(GlobalAddressSDNode *GA,
1596       SelectionDAG &DAG) const {
1597   SDLoc dl(GA);
1598   int64_t Offset = GA->getOffset();
1599   auto PtrVT = getPointerTy(DAG.getDataLayout());
1600 
1601   // Get the thread pointer.
1602   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1603 
1604   bool IsPositionIndependent = isPositionIndependent();
1605   unsigned char TF =
1606       IsPositionIndependent ? HexagonII::MO_IEGOT : HexagonII::MO_IE;
1607 
1608   // First generate the TLS symbol address
1609   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT,
1610                                            Offset, TF);
1611 
1612   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1613 
1614   if (IsPositionIndependent) {
1615     // Generate the GOT pointer in case of position independent code
1616     SDValue GOT = LowerGLOBAL_OFFSET_TABLE(Sym, DAG);
1617 
1618     // Add the TLS Symbol address to GOT pointer.This gives
1619     // GOT relative relocation for the symbol.
1620     Sym = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1621   }
1622 
1623   // Load the offset value for TLS symbol.This offset is relative to
1624   // thread pointer.
1625   SDValue LoadOffset =
1626       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Sym, MachinePointerInfo());
1627 
1628   // Address of the thread local variable is the add of thread
1629   // pointer and the offset of the variable.
1630   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, LoadOffset);
1631 }
1632 
1633 //
1634 // Lower using the local executable model for TLS addresses
1635 //
1636 SDValue
1637 HexagonTargetLowering::LowerToTLSLocalExecModel(GlobalAddressSDNode *GA,
1638       SelectionDAG &DAG) const {
1639   SDLoc dl(GA);
1640   int64_t Offset = GA->getOffset();
1641   auto PtrVT = getPointerTy(DAG.getDataLayout());
1642 
1643   // Get the thread pointer.
1644   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1645   // Generate the TLS symbol address
1646   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1647                                            HexagonII::MO_TPREL);
1648   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1649 
1650   // Address of the thread local variable is the add of thread
1651   // pointer and the offset of the variable.
1652   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, Sym);
1653 }
1654 
1655 //
1656 // Lower using the general dynamic model for TLS addresses
1657 //
1658 SDValue
1659 HexagonTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1660       SelectionDAG &DAG) const {
1661   SDLoc dl(GA);
1662   int64_t Offset = GA->getOffset();
1663   auto PtrVT = getPointerTy(DAG.getDataLayout());
1664 
1665   // First generate the TLS symbol address
1666   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1667                                            HexagonII::MO_GDGOT);
1668 
1669   // Then, generate the GOT pointer
1670   SDValue GOT = LowerGLOBAL_OFFSET_TABLE(TGA, DAG);
1671 
1672   // Add the TLS symbol and the GOT pointer
1673   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1674   SDValue Chain = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1675 
1676   // Copy over the argument to R0
1677   SDValue InFlag;
1678   Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, Hexagon::R0, Chain, InFlag);
1679   InFlag = Chain.getValue(1);
1680 
1681   return GetDynamicTLSAddr(DAG, Chain, GA, &InFlag, PtrVT,
1682                            Hexagon::R0, HexagonII::MO_GDPLT);
1683 }
1684 
1685 //
1686 // Lower TLS addresses.
1687 //
1688 // For now for dynamic models, we only support the general dynamic model.
1689 //
1690 SDValue
1691 HexagonTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1692       SelectionDAG &DAG) const {
1693   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1694 
1695   switch (HTM.getTLSModel(GA->getGlobal())) {
1696     case TLSModel::GeneralDynamic:
1697     case TLSModel::LocalDynamic:
1698       return LowerToTLSGeneralDynamicModel(GA, DAG);
1699     case TLSModel::InitialExec:
1700       return LowerToTLSInitialExecModel(GA, DAG);
1701     case TLSModel::LocalExec:
1702       return LowerToTLSLocalExecModel(GA, DAG);
1703   }
1704   llvm_unreachable("Bogus TLS model");
1705 }
1706 
1707 //===----------------------------------------------------------------------===//
1708 // TargetLowering Implementation
1709 //===----------------------------------------------------------------------===//
1710 
1711 HexagonTargetLowering::HexagonTargetLowering(const TargetMachine &TM,
1712                                              const HexagonSubtarget &ST)
1713     : TargetLowering(TM), HTM(static_cast<const HexagonTargetMachine&>(TM)),
1714       Subtarget(ST) {
1715   bool IsV4 = !Subtarget.hasV5TOps();
1716   auto &HRI = *Subtarget.getRegisterInfo();
1717   bool UseHVX = Subtarget.useHVXOps();
1718   bool UseHVXSgl = Subtarget.useHVXSglOps();
1719   bool UseHVXDbl = Subtarget.useHVXDblOps();
1720 
1721   setPrefLoopAlignment(4);
1722   setPrefFunctionAlignment(4);
1723   setMinFunctionAlignment(2);
1724   setStackPointerRegisterToSaveRestore(HRI.getStackRegister());
1725 
1726   setMaxAtomicSizeInBitsSupported(64);
1727   setMinCmpXchgSizeInBits(32);
1728 
1729   if (EnableHexSDNodeSched)
1730     setSchedulingPreference(Sched::VLIW);
1731   else
1732     setSchedulingPreference(Sched::Source);
1733 
1734   // Limits for inline expansion of memcpy/memmove
1735   MaxStoresPerMemcpy = MaxStoresPerMemcpyCL;
1736   MaxStoresPerMemcpyOptSize = MaxStoresPerMemcpyOptSizeCL;
1737   MaxStoresPerMemmove = MaxStoresPerMemmoveCL;
1738   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmoveOptSizeCL;
1739   MaxStoresPerMemset = MaxStoresPerMemsetCL;
1740   MaxStoresPerMemsetOptSize = MaxStoresPerMemsetOptSizeCL;
1741 
1742   //
1743   // Set up register classes.
1744   //
1745 
1746   addRegisterClass(MVT::i1,    &Hexagon::PredRegsRegClass);
1747   addRegisterClass(MVT::v2i1,  &Hexagon::PredRegsRegClass);  // bbbbaaaa
1748   addRegisterClass(MVT::v4i1,  &Hexagon::PredRegsRegClass);  // ddccbbaa
1749   addRegisterClass(MVT::v8i1,  &Hexagon::PredRegsRegClass);  // hgfedcba
1750   addRegisterClass(MVT::i32,   &Hexagon::IntRegsRegClass);
1751   addRegisterClass(MVT::v4i8,  &Hexagon::IntRegsRegClass);
1752   addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
1753   addRegisterClass(MVT::i64,   &Hexagon::DoubleRegsRegClass);
1754   addRegisterClass(MVT::v8i8,  &Hexagon::DoubleRegsRegClass);
1755   addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
1756   addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
1757 
1758   if (Subtarget.hasV5TOps()) {
1759     addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1760     addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1761   }
1762 
1763   if (Subtarget.hasV60TOps()) {
1764     if (Subtarget.useHVXSglOps()) {
1765       addRegisterClass(MVT::v64i8,  &Hexagon::VectorRegsRegClass);
1766       addRegisterClass(MVT::v32i16, &Hexagon::VectorRegsRegClass);
1767       addRegisterClass(MVT::v16i32, &Hexagon::VectorRegsRegClass);
1768       addRegisterClass(MVT::v8i64,  &Hexagon::VectorRegsRegClass);
1769       addRegisterClass(MVT::v128i8, &Hexagon::VecDblRegsRegClass);
1770       addRegisterClass(MVT::v64i16, &Hexagon::VecDblRegsRegClass);
1771       addRegisterClass(MVT::v32i32, &Hexagon::VecDblRegsRegClass);
1772       addRegisterClass(MVT::v16i64, &Hexagon::VecDblRegsRegClass);
1773       addRegisterClass(MVT::v512i1, &Hexagon::VecPredRegsRegClass);
1774     } else if (Subtarget.useHVXDblOps()) {
1775       addRegisterClass(MVT::v128i8,  &Hexagon::VectorRegs128BRegClass);
1776       addRegisterClass(MVT::v64i16,  &Hexagon::VectorRegs128BRegClass);
1777       addRegisterClass(MVT::v32i32,  &Hexagon::VectorRegs128BRegClass);
1778       addRegisterClass(MVT::v16i64,  &Hexagon::VectorRegs128BRegClass);
1779       addRegisterClass(MVT::v256i8,  &Hexagon::VecDblRegs128BRegClass);
1780       addRegisterClass(MVT::v128i16, &Hexagon::VecDblRegs128BRegClass);
1781       addRegisterClass(MVT::v64i32,  &Hexagon::VecDblRegs128BRegClass);
1782       addRegisterClass(MVT::v32i64,  &Hexagon::VecDblRegs128BRegClass);
1783       addRegisterClass(MVT::v1024i1, &Hexagon::VecPredRegs128BRegClass);
1784     }
1785 
1786   }
1787 
1788   //
1789   // Handling of scalar operations.
1790   //
1791   // All operations default to "legal", except:
1792   // - indexed loads and stores (pre-/post-incremented),
1793   // - ANY_EXTEND_VECTOR_INREG, ATOMIC_CMP_SWAP_WITH_SUCCESS, CONCAT_VECTORS,
1794   //   ConstantFP, DEBUGTRAP, FCEIL, FCOPYSIGN, FEXP, FEXP2, FFLOOR, FGETSIGN,
1795   //   FLOG, FLOG2, FLOG10, FMAXNUM, FMINNUM, FNEARBYINT, FRINT, FROUND, TRAP,
1796   //   FTRUNC, PREFETCH, SIGN_EXTEND_VECTOR_INREG, ZERO_EXTEND_VECTOR_INREG,
1797   // which default to "expand" for at least one type.
1798 
1799   // Misc operations.
1800   setOperationAction(ISD::ConstantFP, MVT::f32, Legal); // Default: expand
1801   setOperationAction(ISD::ConstantFP, MVT::f64, Legal); // Default: expand
1802 
1803   setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
1804   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
1805   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
1806   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1807   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
1808   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
1809   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1810   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
1811   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
1812   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1813   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1814 
1815   // Custom legalize GlobalAddress nodes into CONST32.
1816   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1817   setOperationAction(ISD::GlobalAddress, MVT::i8,  Custom);
1818   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
1819 
1820   // Hexagon needs to optimize cases with negative constants.
1821   setOperationAction(ISD::SETCC, MVT::i8,  Custom);
1822   setOperationAction(ISD::SETCC, MVT::i16, Custom);
1823 
1824   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1825   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1826   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
1827   setOperationAction(ISD::VAARG,   MVT::Other, Expand);
1828 
1829   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1830   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1831   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1832 
1833   if (EmitJumpTables)
1834     setMinimumJumpTableEntries(MinimumJumpTables);
1835   else
1836     setMinimumJumpTableEntries(INT_MAX);
1837   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1838 
1839   // Hexagon has instructions for add/sub with carry. The problem with
1840   // modeling these instructions is that they produce 2 results: Rdd and Px.
1841   // To model the update of Px, we will have to use Defs[p0..p3] which will
1842   // cause any predicate live range to spill. So, we pretend we dont't have
1843   // these instructions.
1844   setOperationAction(ISD::ADDE, MVT::i8,  Expand);
1845   setOperationAction(ISD::ADDE, MVT::i16, Expand);
1846   setOperationAction(ISD::ADDE, MVT::i32, Expand);
1847   setOperationAction(ISD::ADDE, MVT::i64, Expand);
1848   setOperationAction(ISD::SUBE, MVT::i8,  Expand);
1849   setOperationAction(ISD::SUBE, MVT::i16, Expand);
1850   setOperationAction(ISD::SUBE, MVT::i32, Expand);
1851   setOperationAction(ISD::SUBE, MVT::i64, Expand);
1852   setOperationAction(ISD::ADDC, MVT::i8,  Expand);
1853   setOperationAction(ISD::ADDC, MVT::i16, Expand);
1854   setOperationAction(ISD::ADDC, MVT::i32, Expand);
1855   setOperationAction(ISD::ADDC, MVT::i64, Expand);
1856   setOperationAction(ISD::SUBC, MVT::i8,  Expand);
1857   setOperationAction(ISD::SUBC, MVT::i16, Expand);
1858   setOperationAction(ISD::SUBC, MVT::i32, Expand);
1859   setOperationAction(ISD::SUBC, MVT::i64, Expand);
1860 
1861   // Only add and sub that detect overflow are the saturating ones.
1862   for (MVT VT : MVT::integer_valuetypes()) {
1863     setOperationAction(ISD::UADDO, VT, Expand);
1864     setOperationAction(ISD::SADDO, VT, Expand);
1865     setOperationAction(ISD::USUBO, VT, Expand);
1866     setOperationAction(ISD::SSUBO, VT, Expand);
1867   }
1868 
1869   setOperationAction(ISD::CTLZ, MVT::i8,  Promote);
1870   setOperationAction(ISD::CTLZ, MVT::i16, Promote);
1871   setOperationAction(ISD::CTTZ, MVT::i8,  Promote);
1872   setOperationAction(ISD::CTTZ, MVT::i16, Promote);
1873 
1874   // In V5, popcount can count # of 1s in i64 but returns i32.
1875   // On V4 it will be expanded (set later).
1876   setOperationAction(ISD::CTPOP, MVT::i8,  Promote);
1877   setOperationAction(ISD::CTPOP, MVT::i16, Promote);
1878   setOperationAction(ISD::CTPOP, MVT::i32, Promote);
1879   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
1880 
1881   // We custom lower i64 to i64 mul, so that it is not considered as a legal
1882   // operation. There is a pattern that will match i64 mul and transform it
1883   // to a series of instructions.
1884   setOperationAction(ISD::MUL,   MVT::i64, Expand);
1885 
1886   for (unsigned IntExpOp :
1887        { ISD::SDIV,      ISD::UDIV,      ISD::SREM,      ISD::UREM,
1888          ISD::SDIVREM,   ISD::UDIVREM,   ISD::ROTL,      ISD::ROTR,
1889          ISD::BSWAP,     ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
1890          ISD::SMUL_LOHI, ISD::UMUL_LOHI }) {
1891     setOperationAction(IntExpOp, MVT::i32, Expand);
1892     setOperationAction(IntExpOp, MVT::i64, Expand);
1893   }
1894 
1895   for (unsigned FPExpOp :
1896        {ISD::FDIV, ISD::FREM, ISD::FSQRT, ISD::FSIN, ISD::FCOS, ISD::FSINCOS,
1897         ISD::FPOW, ISD::FCOPYSIGN}) {
1898     setOperationAction(FPExpOp, MVT::f32, Expand);
1899     setOperationAction(FPExpOp, MVT::f64, Expand);
1900   }
1901 
1902   // No extending loads from i32.
1903   for (MVT VT : MVT::integer_valuetypes()) {
1904     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
1905     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
1906     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i32, Expand);
1907   }
1908   // Turn FP truncstore into trunc + store.
1909   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1910   // Turn FP extload into load/fpextend.
1911   for (MVT VT : MVT::fp_valuetypes())
1912     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1913 
1914   // Expand BR_CC and SELECT_CC for all integer and fp types.
1915   for (MVT VT : MVT::integer_valuetypes()) {
1916     setOperationAction(ISD::BR_CC,     VT, Expand);
1917     setOperationAction(ISD::SELECT_CC, VT, Expand);
1918   }
1919   for (MVT VT : MVT::fp_valuetypes()) {
1920     setOperationAction(ISD::BR_CC,     VT, Expand);
1921     setOperationAction(ISD::SELECT_CC, VT, Expand);
1922   }
1923   setOperationAction(ISD::BR_CC, MVT::Other, Expand);
1924 
1925   //
1926   // Handling of vector operations.
1927   //
1928 
1929   // Custom lower v4i16 load only. Let v4i16 store to be
1930   // promoted for now.
1931   promoteLdStType(MVT::v4i8,  MVT::i32);
1932   promoteLdStType(MVT::v2i16, MVT::i32);
1933   promoteLdStType(MVT::v8i8,  MVT::i64);
1934   promoteLdStType(MVT::v2i32, MVT::i64);
1935 
1936   setOperationAction(ISD::LOAD,  MVT::v4i16, Custom);
1937   setOperationAction(ISD::STORE, MVT::v4i16, Promote);
1938   AddPromotedToType(ISD::LOAD,  MVT::v4i16, MVT::i64);
1939   AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::i64);
1940 
1941   // Set the action for vector operations to "expand", then override it with
1942   // either "custom" or "legal" for specific cases.
1943   static const unsigned VectExpOps[] = {
1944     // Integer arithmetic:
1945     ISD::ADD,     ISD::SUB,     ISD::MUL,     ISD::SDIV,    ISD::UDIV,
1946     ISD::SREM,    ISD::UREM,    ISD::SDIVREM, ISD::UDIVREM, ISD::ADDC,
1947     ISD::SUBC,    ISD::SADDO,   ISD::UADDO,   ISD::SSUBO,   ISD::USUBO,
1948     ISD::SMUL_LOHI,             ISD::UMUL_LOHI,
1949     // Logical/bit:
1950     ISD::AND,     ISD::OR,      ISD::XOR,     ISD::ROTL,    ISD::ROTR,
1951     ISD::CTPOP,   ISD::CTLZ,    ISD::CTTZ,
1952     // Floating point arithmetic/math functions:
1953     ISD::FADD,    ISD::FSUB,    ISD::FMUL,    ISD::FMA,     ISD::FDIV,
1954     ISD::FREM,    ISD::FNEG,    ISD::FABS,    ISD::FSQRT,   ISD::FSIN,
1955     ISD::FCOS,    ISD::FPOWI,   ISD::FPOW,    ISD::FLOG,    ISD::FLOG2,
1956     ISD::FLOG10,  ISD::FEXP,    ISD::FEXP2,   ISD::FCEIL,   ISD::FTRUNC,
1957     ISD::FRINT,   ISD::FNEARBYINT,            ISD::FROUND,  ISD::FFLOOR,
1958     ISD::FMINNUM, ISD::FMAXNUM, ISD::FSINCOS,
1959     // Misc:
1960     ISD::BR_CC,   ISD::SELECT_CC,             ISD::ConstantPool,
1961     // Vector:
1962     ISD::BUILD_VECTOR,          ISD::SCALAR_TO_VECTOR,
1963     ISD::EXTRACT_VECTOR_ELT,    ISD::INSERT_VECTOR_ELT,
1964     ISD::EXTRACT_SUBVECTOR,     ISD::INSERT_SUBVECTOR,
1965     ISD::CONCAT_VECTORS,        ISD::VECTOR_SHUFFLE
1966   };
1967 
1968   for (MVT VT : MVT::vector_valuetypes()) {
1969     for (unsigned VectExpOp : VectExpOps)
1970       setOperationAction(VectExpOp, VT, Expand);
1971 
1972     // Expand all extending loads and truncating stores:
1973     for (MVT TargetVT : MVT::vector_valuetypes()) {
1974       if (TargetVT == VT)
1975         continue;
1976       setLoadExtAction(ISD::EXTLOAD, TargetVT, VT, Expand);
1977       setLoadExtAction(ISD::ZEXTLOAD, TargetVT, VT, Expand);
1978       setLoadExtAction(ISD::SEXTLOAD, TargetVT, VT, Expand);
1979       setTruncStoreAction(VT, TargetVT, Expand);
1980     }
1981 
1982     // Normalize all inputs to SELECT to be vectors of i32.
1983     if (VT.getVectorElementType() != MVT::i32) {
1984       MVT VT32 = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
1985       setOperationAction(ISD::SELECT, VT, Promote);
1986       AddPromotedToType(ISD::SELECT, VT, VT32);
1987     }
1988     setOperationAction(ISD::SRA, VT, Custom);
1989     setOperationAction(ISD::SHL, VT, Custom);
1990     setOperationAction(ISD::SRL, VT, Custom);
1991   }
1992 
1993   // Types natively supported:
1994   for (MVT NativeVT : {MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v32i1, MVT::v64i1,
1995                        MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16, MVT::v1i32,
1996                        MVT::v2i32, MVT::v1i64}) {
1997     setOperationAction(ISD::BUILD_VECTOR,       NativeVT, Custom);
1998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, NativeVT, Custom);
1999     setOperationAction(ISD::INSERT_VECTOR_ELT,  NativeVT, Custom);
2000     setOperationAction(ISD::EXTRACT_SUBVECTOR,  NativeVT, Custom);
2001     setOperationAction(ISD::INSERT_SUBVECTOR,   NativeVT, Custom);
2002     setOperationAction(ISD::CONCAT_VECTORS,     NativeVT, Custom);
2003 
2004     setOperationAction(ISD::ADD, NativeVT, Legal);
2005     setOperationAction(ISD::SUB, NativeVT, Legal);
2006     setOperationAction(ISD::MUL, NativeVT, Legal);
2007     setOperationAction(ISD::AND, NativeVT, Legal);
2008     setOperationAction(ISD::OR,  NativeVT, Legal);
2009     setOperationAction(ISD::XOR, NativeVT, Legal);
2010   }
2011 
2012   setOperationAction(ISD::SETCC,          MVT::v2i16, Custom);
2013   setOperationAction(ISD::VSELECT,        MVT::v2i16, Custom);
2014   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
2015   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8,  Custom);
2016 
2017   if (UseHVX) {
2018     if (UseHVXSgl) {
2019       setOperationAction(ISD::CONCAT_VECTORS, MVT::v128i8,  Custom);
2020       setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i16,  Custom);
2021       setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i32,  Custom);
2022       setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i64,  Custom);
2023       // We try to generate the vpack{e/o} instructions. If we fail
2024       // we fall back upon ExpandOp.
2025       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8,  Custom);
2026       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
2027       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v64i8, Custom);
2028       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32i16, Custom);
2029       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v16i32, Custom);
2030     } else if (UseHVXDbl) {
2031       setOperationAction(ISD::CONCAT_VECTORS, MVT::v256i8,  Custom);
2032       setOperationAction(ISD::CONCAT_VECTORS, MVT::v128i16, Custom);
2033       setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i32,  Custom);
2034       setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i64,  Custom);
2035       // We try to generate the vpack{e/o} instructions. If we fail
2036       // we fall back upon ExpandOp.
2037       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v128i8,  Custom);
2038       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i16,  Custom);
2039       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v4i32, Custom);
2040       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v128i8, Custom);
2041       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v64i16, Custom);
2042       setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v32i32, Custom);
2043     } else {
2044       llvm_unreachable("Unrecognized HVX mode");
2045     }
2046   }
2047   // Subtarget-specific operation actions.
2048   //
2049   if (Subtarget.hasV5TOps()) {
2050     setOperationAction(ISD::FMA,  MVT::f64, Expand);
2051     setOperationAction(ISD::FADD, MVT::f64, Expand);
2052     setOperationAction(ISD::FSUB, MVT::f64, Expand);
2053     setOperationAction(ISD::FMUL, MVT::f64, Expand);
2054 
2055     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
2056     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
2057 
2058     setOperationAction(ISD::FP_TO_UINT, MVT::i1,  Promote);
2059     setOperationAction(ISD::FP_TO_UINT, MVT::i8,  Promote);
2060     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
2061     setOperationAction(ISD::FP_TO_SINT, MVT::i1,  Promote);
2062     setOperationAction(ISD::FP_TO_SINT, MVT::i8,  Promote);
2063     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
2064     setOperationAction(ISD::UINT_TO_FP, MVT::i1,  Promote);
2065     setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Promote);
2066     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
2067     setOperationAction(ISD::SINT_TO_FP, MVT::i1,  Promote);
2068     setOperationAction(ISD::SINT_TO_FP, MVT::i8,  Promote);
2069     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
2070 
2071   } else { // V4
2072     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
2073     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Expand);
2074     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
2075     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
2076     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
2077     setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
2078     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Expand);
2079     setOperationAction(ISD::FP_ROUND,   MVT::f64, Expand);
2080     setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
2081 
2082     setOperationAction(ISD::CTPOP, MVT::i8,  Expand);
2083     setOperationAction(ISD::CTPOP, MVT::i16, Expand);
2084     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
2085     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
2086 
2087     // Expand these operations for both f32 and f64:
2088     for (unsigned FPExpOpV4 :
2089          {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FABS, ISD::FNEG, ISD::FMA}) {
2090       setOperationAction(FPExpOpV4, MVT::f32, Expand);
2091       setOperationAction(FPExpOpV4, MVT::f64, Expand);
2092     }
2093 
2094     for (ISD::CondCode FPExpCCV4 :
2095          {ISD::SETOEQ, ISD::SETOGT, ISD::SETOLT, ISD::SETOGE, ISD::SETOLE,
2096           ISD::SETUO,  ISD::SETO}) {
2097       setCondCodeAction(FPExpCCV4, MVT::f32, Expand);
2098       setCondCodeAction(FPExpCCV4, MVT::f64, Expand);
2099     }
2100   }
2101 
2102   // Handling of indexed loads/stores: default is "expand".
2103   //
2104   for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
2105     setIndexedLoadAction(ISD::POST_INC, VT, Legal);
2106     setIndexedStoreAction(ISD::POST_INC, VT, Legal);
2107   }
2108 
2109   if (UseHVXSgl) {
2110     for (MVT VT : {MVT::v64i8,  MVT::v32i16, MVT::v16i32, MVT::v8i64,
2111                    MVT::v128i8, MVT::v64i16, MVT::v32i32, MVT::v16i64}) {
2112       setIndexedLoadAction(ISD::POST_INC, VT, Legal);
2113       setIndexedStoreAction(ISD::POST_INC, VT, Legal);
2114     }
2115   } else if (UseHVXDbl) {
2116     for (MVT VT : {MVT::v128i8, MVT::v64i16,  MVT::v32i32, MVT::v16i64,
2117                    MVT::v256i8, MVT::v128i16, MVT::v64i32, MVT::v32i64}) {
2118       setIndexedLoadAction(ISD::POST_INC, VT, Legal);
2119       setIndexedStoreAction(ISD::POST_INC, VT, Legal);
2120     }
2121   }
2122 
2123   computeRegisterProperties(&HRI);
2124 
2125   //
2126   // Library calls for unsupported operations
2127   //
2128   bool FastMath  = EnableFastMath;
2129 
2130   setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
2131   setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
2132   setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
2133   setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
2134   setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
2135   setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
2136   setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
2137   setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
2138 
2139   setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
2140   setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
2141   setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
2142   setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
2143   setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
2144   setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
2145 
2146   if (IsV4) {
2147     // Handle single-precision floating point operations on V4.
2148     if (FastMath) {
2149       setLibcallName(RTLIB::ADD_F32, "__hexagon_fast_addsf3");
2150       setLibcallName(RTLIB::SUB_F32, "__hexagon_fast_subsf3");
2151       setLibcallName(RTLIB::MUL_F32, "__hexagon_fast_mulsf3");
2152       setLibcallName(RTLIB::OGT_F32, "__hexagon_fast_gtsf2");
2153       setLibcallName(RTLIB::OLT_F32, "__hexagon_fast_ltsf2");
2154       // Double-precision compares.
2155       setLibcallName(RTLIB::OGT_F64, "__hexagon_fast_gtdf2");
2156       setLibcallName(RTLIB::OLT_F64, "__hexagon_fast_ltdf2");
2157     } else {
2158       setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
2159       setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
2160       setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
2161       setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
2162       setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
2163       // Double-precision compares.
2164       setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
2165       setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
2166     }
2167   }
2168 
2169   // This is the only fast library function for sqrtd.
2170   if (FastMath)
2171     setLibcallName(RTLIB::SQRT_F64, "__hexagon_fast2_sqrtdf2");
2172 
2173   // Prefix is: nothing  for "slow-math",
2174   //            "fast2_" for V4 fast-math and V5+ fast-math double-precision
2175   // (actually, keep fast-math and fast-math2 separate for now)
2176   if (FastMath) {
2177     setLibcallName(RTLIB::ADD_F64, "__hexagon_fast_adddf3");
2178     setLibcallName(RTLIB::SUB_F64, "__hexagon_fast_subdf3");
2179     setLibcallName(RTLIB::MUL_F64, "__hexagon_fast_muldf3");
2180     setLibcallName(RTLIB::DIV_F64, "__hexagon_fast_divdf3");
2181     // Calling __hexagon_fast2_divsf3 with fast-math on V5 (ok).
2182     setLibcallName(RTLIB::DIV_F32, "__hexagon_fast_divsf3");
2183   } else {
2184     setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
2185     setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
2186     setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
2187     setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
2188     setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
2189   }
2190 
2191   if (Subtarget.hasV5TOps()) {
2192     if (FastMath)
2193       setLibcallName(RTLIB::SQRT_F32, "__hexagon_fast2_sqrtf");
2194     else
2195       setLibcallName(RTLIB::SQRT_F32, "__hexagon_sqrtf");
2196   } else {
2197     // V4
2198     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
2199     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
2200     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
2201     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
2202     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
2203     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
2204     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
2205     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
2206     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
2207     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
2208     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
2209     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
2210     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
2211     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
2212     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
2213     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
2214     setLibcallName(RTLIB::FPEXT_F32_F64,    "__hexagon_extendsfdf2");
2215     setLibcallName(RTLIB::FPROUND_F64_F32,  "__hexagon_truncdfsf2");
2216     setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
2217     setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
2218     setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
2219     setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
2220     setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
2221     setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
2222     setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
2223     setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
2224     setLibcallName(RTLIB::UO_F32,  "__hexagon_unordsf2");
2225     setLibcallName(RTLIB::UO_F64,  "__hexagon_unorddf2");
2226     setLibcallName(RTLIB::O_F32,   "__hexagon_unordsf2");
2227     setLibcallName(RTLIB::O_F64,   "__hexagon_unorddf2");
2228   }
2229 
2230   // These cause problems when the shift amount is non-constant.
2231   setLibcallName(RTLIB::SHL_I128, nullptr);
2232   setLibcallName(RTLIB::SRL_I128, nullptr);
2233   setLibcallName(RTLIB::SRA_I128, nullptr);
2234 }
2235 
2236 
2237 const char* HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
2238   switch ((HexagonISD::NodeType)Opcode) {
2239   case HexagonISD::ALLOCA:        return "HexagonISD::ALLOCA";
2240   case HexagonISD::AT_GOT:        return "HexagonISD::AT_GOT";
2241   case HexagonISD::AT_PCREL:      return "HexagonISD::AT_PCREL";
2242   case HexagonISD::BARRIER:       return "HexagonISD::BARRIER";
2243   case HexagonISD::CALL:          return "HexagonISD::CALL";
2244   case HexagonISD::CALLnr:        return "HexagonISD::CALLnr";
2245   case HexagonISD::CALLR:         return "HexagonISD::CALLR";
2246   case HexagonISD::COMBINE:       return "HexagonISD::COMBINE";
2247   case HexagonISD::CONST32_GP:    return "HexagonISD::CONST32_GP";
2248   case HexagonISD::CONST32:       return "HexagonISD::CONST32";
2249   case HexagonISD::CP:            return "HexagonISD::CP";
2250   case HexagonISD::DCFETCH:       return "HexagonISD::DCFETCH";
2251   case HexagonISD::EH_RETURN:     return "HexagonISD::EH_RETURN";
2252   case HexagonISD::EXTRACTU:      return "HexagonISD::EXTRACTU";
2253   case HexagonISD::EXTRACTURP:    return "HexagonISD::EXTRACTURP";
2254   case HexagonISD::INSERT:        return "HexagonISD::INSERT";
2255   case HexagonISD::INSERTRP:      return "HexagonISD::INSERTRP";
2256   case HexagonISD::JT:            return "HexagonISD::JT";
2257   case HexagonISD::PACKHL:        return "HexagonISD::PACKHL";
2258   case HexagonISD::POPCOUNT:      return "HexagonISD::POPCOUNT";
2259   case HexagonISD::RET_FLAG:      return "HexagonISD::RET_FLAG";
2260   case HexagonISD::SHUFFEB:       return "HexagonISD::SHUFFEB";
2261   case HexagonISD::SHUFFEH:       return "HexagonISD::SHUFFEH";
2262   case HexagonISD::SHUFFOB:       return "HexagonISD::SHUFFOB";
2263   case HexagonISD::SHUFFOH:       return "HexagonISD::SHUFFOH";
2264   case HexagonISD::TC_RETURN:     return "HexagonISD::TC_RETURN";
2265   case HexagonISD::VCMPBEQ:       return "HexagonISD::VCMPBEQ";
2266   case HexagonISD::VCMPBGT:       return "HexagonISD::VCMPBGT";
2267   case HexagonISD::VCMPBGTU:      return "HexagonISD::VCMPBGTU";
2268   case HexagonISD::VCMPHEQ:       return "HexagonISD::VCMPHEQ";
2269   case HexagonISD::VCMPHGT:       return "HexagonISD::VCMPHGT";
2270   case HexagonISD::VCMPHGTU:      return "HexagonISD::VCMPHGTU";
2271   case HexagonISD::VCMPWEQ:       return "HexagonISD::VCMPWEQ";
2272   case HexagonISD::VCMPWGT:       return "HexagonISD::VCMPWGT";
2273   case HexagonISD::VCMPWGTU:      return "HexagonISD::VCMPWGTU";
2274   case HexagonISD::VCOMBINE:      return "HexagonISD::VCOMBINE";
2275   case HexagonISD::VPACK:         return "HexagonISD::VPACK";
2276   case HexagonISD::VSHLH:         return "HexagonISD::VSHLH";
2277   case HexagonISD::VSHLW:         return "HexagonISD::VSHLW";
2278   case HexagonISD::VSPLATB:       return "HexagonISD::VSPLTB";
2279   case HexagonISD::VSPLATH:       return "HexagonISD::VSPLATH";
2280   case HexagonISD::VSRAH:         return "HexagonISD::VSRAH";
2281   case HexagonISD::VSRAW:         return "HexagonISD::VSRAW";
2282   case HexagonISD::VSRLH:         return "HexagonISD::VSRLH";
2283   case HexagonISD::VSRLW:         return "HexagonISD::VSRLW";
2284   case HexagonISD::VSXTBH:        return "HexagonISD::VSXTBH";
2285   case HexagonISD::VSXTBW:        return "HexagonISD::VSXTBW";
2286   case HexagonISD::OP_END:        break;
2287   }
2288   return nullptr;
2289 }
2290 
2291 bool HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
2292   EVT MTy1 = EVT::getEVT(Ty1);
2293   EVT MTy2 = EVT::getEVT(Ty2);
2294   if (!MTy1.isSimple() || !MTy2.isSimple())
2295     return false;
2296   return (MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32);
2297 }
2298 
2299 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
2300   if (!VT1.isSimple() || !VT2.isSimple())
2301     return false;
2302   return (VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32);
2303 }
2304 
2305 bool HexagonTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2306   return isOperationLegalOrCustom(ISD::FMA, VT);
2307 }
2308 
2309 // Should we expand the build vector with shuffles?
2310 bool HexagonTargetLowering::shouldExpandBuildVectorWithShuffles(EVT VT,
2311       unsigned DefinedValues) const {
2312   // Hexagon vector shuffle operates on element sizes of bytes or halfwords
2313   EVT EltVT = VT.getVectorElementType();
2314   int EltBits = EltVT.getSizeInBits();
2315   if ((EltBits != 8) && (EltBits != 16))
2316     return false;
2317 
2318   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
2319 }
2320 
2321 static StridedLoadKind isStridedLoad(const ArrayRef<int> &Mask) {
2322   int even_start = -2;
2323   int odd_start = -1;
2324   size_t mask_len = Mask.size();
2325   for (auto idx : Mask) {
2326     if ((idx - even_start) == 2)
2327       even_start = idx;
2328     else
2329       break;
2330   }
2331   if (even_start == (int)(mask_len * 2) - 2)
2332     return StridedLoadKind::Even;
2333   for (auto idx : Mask) {
2334     if ((idx - odd_start) == 2)
2335       odd_start = idx;
2336     else
2337       break;
2338   }
2339   if (odd_start == (int)(mask_len * 2) - 1)
2340     return StridedLoadKind::Odd;
2341 
2342   return StridedLoadKind::NoPattern;
2343 }
2344 
2345 bool HexagonTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &Mask,
2346       EVT VT) const {
2347   if (Subtarget.useHVXOps())
2348     return isStridedLoad(Mask) != StridedLoadKind::NoPattern;
2349   return true;
2350 }
2351 
2352 // Lower a vector shuffle (V1, V2, V3).  V1 and V2 are the two vectors
2353 // to select data from, V3 is the permutation.
2354 SDValue
2355 HexagonTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG)
2356       const {
2357   const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2358   SDValue V1 = Op.getOperand(0);
2359   SDValue V2 = Op.getOperand(1);
2360   SDLoc dl(Op);
2361   EVT VT = Op.getValueType();
2362   bool UseHVX = Subtarget.useHVXOps();
2363 
2364   if (V2.isUndef())
2365     V2 = V1;
2366 
2367   if (SVN->isSplat()) {
2368     int Lane = SVN->getSplatIndex();
2369     if (Lane == -1) Lane = 0;
2370 
2371     // Test if V1 is a SCALAR_TO_VECTOR.
2372     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
2373       return createSplat(DAG, dl, VT, V1.getOperand(0));
2374 
2375     // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
2376     // (and probably will turn into a SCALAR_TO_VECTOR once legalization
2377     // reaches it).
2378     if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
2379         !isa<ConstantSDNode>(V1.getOperand(0))) {
2380       bool IsScalarToVector = true;
2381       for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i) {
2382         if (!V1.getOperand(i).isUndef()) {
2383           IsScalarToVector = false;
2384           break;
2385         }
2386       }
2387       if (IsScalarToVector)
2388         return createSplat(DAG, dl, VT, V1.getOperand(0));
2389     }
2390     return createSplat(DAG, dl, VT, DAG.getConstant(Lane, dl, MVT::i32));
2391   }
2392 
2393   if (UseHVX) {
2394     ArrayRef<int> Mask = SVN->getMask();
2395     size_t MaskLen = Mask.size();
2396     int ElemSizeInBits = VT.getScalarSizeInBits();
2397     if ((Subtarget.useHVXSglOps() && (ElemSizeInBits * MaskLen) == 64 * 8) ||
2398         (Subtarget.useHVXDblOps() && (ElemSizeInBits * MaskLen) == 128 * 8)) {
2399       // Return 1 for odd and 2 of even
2400       StridedLoadKind Pattern = isStridedLoad(Mask);
2401 
2402       if (Pattern == StridedLoadKind::NoPattern)
2403         return SDValue();
2404 
2405       SDValue Vec0 = Op.getOperand(0);
2406       SDValue Vec1 = Op.getOperand(1);
2407       SDValue StridePattern = DAG.getConstant(Pattern, dl, MVT::i32);
2408       SDValue Ops[] = { Vec1, Vec0, StridePattern };
2409       return DAG.getNode(HexagonISD::VPACK, dl, VT, Ops);
2410     }
2411     // We used to assert in the "else" part here, but that is bad for Halide
2412     // Halide creates intermediate double registers by interleaving two
2413     // concatenated vector registers. The interleaving requires vector_shuffle
2414     // nodes and we shouldn't barf on a double register result of a
2415     // vector_shuffle because it is most likely an intermediate result.
2416   }
2417   // FIXME: We need to support more general vector shuffles.  See
2418   // below the comment from the ARM backend that deals in the general
2419   // case with the vector shuffles.  For now, let expand handle these.
2420   return SDValue();
2421 
2422   // If the shuffle is not directly supported and it has 4 elements, use
2423   // the PerfectShuffle-generated table to synthesize it from other shuffles.
2424 }
2425 
2426 // If BUILD_VECTOR has same base element repeated several times,
2427 // report true.
2428 static bool isCommonSplatElement(BuildVectorSDNode *BVN) {
2429   unsigned NElts = BVN->getNumOperands();
2430   SDValue V0 = BVN->getOperand(0);
2431 
2432   for (unsigned i = 1, e = NElts; i != e; ++i) {
2433     if (BVN->getOperand(i) != V0)
2434       return false;
2435   }
2436   return true;
2437 }
2438 
2439 // Lower a vector shift. Try to convert
2440 // <VT> = SHL/SRA/SRL <VT> by <VT> to Hexagon specific
2441 // <VT> = SHL/SRA/SRL <VT> by <IT/i32>.
2442 SDValue
2443 HexagonTargetLowering::LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) const {
2444   BuildVectorSDNode *BVN = 0;
2445   SDValue V1 = Op.getOperand(0);
2446   SDValue V2 = Op.getOperand(1);
2447   SDValue V3;
2448   SDLoc dl(Op);
2449   EVT VT = Op.getValueType();
2450 
2451   if ((BVN = dyn_cast<BuildVectorSDNode>(V1.getNode())) &&
2452       isCommonSplatElement(BVN))
2453     V3 = V2;
2454   else if ((BVN = dyn_cast<BuildVectorSDNode>(V2.getNode())) &&
2455            isCommonSplatElement(BVN))
2456     V3 = V1;
2457   else
2458     return SDValue();
2459 
2460   SDValue CommonSplat = BVN->getOperand(0);
2461   SDValue Result;
2462 
2463   if (VT.getSimpleVT() == MVT::v4i16) {
2464     switch (Op.getOpcode()) {
2465     case ISD::SRA:
2466       Result = DAG.getNode(HexagonISD::VSRAH, dl, VT, V3, CommonSplat);
2467       break;
2468     case ISD::SHL:
2469       Result = DAG.getNode(HexagonISD::VSHLH, dl, VT, V3, CommonSplat);
2470       break;
2471     case ISD::SRL:
2472       Result = DAG.getNode(HexagonISD::VSRLH, dl, VT, V3, CommonSplat);
2473       break;
2474     default:
2475       return SDValue();
2476     }
2477   } else if (VT.getSimpleVT() == MVT::v2i32) {
2478     switch (Op.getOpcode()) {
2479     case ISD::SRA:
2480       Result = DAG.getNode(HexagonISD::VSRAW, dl, VT, V3, CommonSplat);
2481       break;
2482     case ISD::SHL:
2483       Result = DAG.getNode(HexagonISD::VSHLW, dl, VT, V3, CommonSplat);
2484       break;
2485     case ISD::SRL:
2486       Result = DAG.getNode(HexagonISD::VSRLW, dl, VT, V3, CommonSplat);
2487       break;
2488     default:
2489       return SDValue();
2490     }
2491   } else {
2492     return SDValue();
2493   }
2494 
2495   return DAG.getNode(ISD::BITCAST, dl, VT, Result);
2496 }
2497 
2498 SDValue
2499 HexagonTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
2500   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
2501   SDLoc dl(Op);
2502   EVT VT = Op.getValueType();
2503 
2504   unsigned Size = VT.getSizeInBits();
2505 
2506   // Only handle vectors of 64 bits or shorter.
2507   if (Size > 64)
2508     return SDValue();
2509 
2510   APInt APSplatBits, APSplatUndef;
2511   unsigned SplatBitSize;
2512   bool HasAnyUndefs;
2513   unsigned NElts = BVN->getNumOperands();
2514 
2515   // Try to generate a SPLAT instruction.
2516   if ((VT.getSimpleVT() == MVT::v4i8 || VT.getSimpleVT() == MVT::v4i16) &&
2517       (BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
2518                             HasAnyUndefs, 0, true) && SplatBitSize <= 16)) {
2519     unsigned SplatBits = APSplatBits.getZExtValue();
2520     int32_t SextVal = ((int32_t) (SplatBits << (32 - SplatBitSize)) >>
2521                        (32 - SplatBitSize));
2522     return createSplat(DAG, dl, VT, DAG.getConstant(SextVal, dl, MVT::i32));
2523   }
2524 
2525   // Try to generate COMBINE to build v2i32 vectors.
2526   if (VT.getSimpleVT() == MVT::v2i32) {
2527     SDValue V0 = BVN->getOperand(0);
2528     SDValue V1 = BVN->getOperand(1);
2529 
2530     if (V0.isUndef())
2531       V0 = DAG.getConstant(0, dl, MVT::i32);
2532     if (V1.isUndef())
2533       V1 = DAG.getConstant(0, dl, MVT::i32);
2534 
2535     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(V0);
2536     ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(V1);
2537     // If the element isn't a constant, it is in a register:
2538     // generate a COMBINE Register Register instruction.
2539     if (!C0 || !C1)
2540       return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
2541 
2542     // If one of the operands is an 8 bit integer constant, generate
2543     // a COMBINE Immediate Immediate instruction.
2544     if (isInt<8>(C0->getSExtValue()) ||
2545         isInt<8>(C1->getSExtValue()))
2546       return DAG.getNode(HexagonISD::COMBINE, dl, VT, V1, V0);
2547   }
2548 
2549   // Try to generate a S2_packhl to build v2i16 vectors.
2550   if (VT.getSimpleVT() == MVT::v2i16) {
2551     for (unsigned i = 0, e = NElts; i != e; ++i) {
2552       if (BVN->getOperand(i).isUndef())
2553         continue;
2554       ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(BVN->getOperand(i));
2555       // If the element isn't a constant, it is in a register:
2556       // generate a S2_packhl instruction.
2557       if (!Cst) {
2558         SDValue pack = DAG.getNode(HexagonISD::PACKHL, dl, MVT::v4i16,
2559                                    BVN->getOperand(1), BVN->getOperand(0));
2560 
2561         return DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::v2i16,
2562                                           pack);
2563       }
2564     }
2565   }
2566 
2567   // In the general case, generate a CONST32 or a CONST64 for constant vectors,
2568   // and insert_vector_elt for all the other cases.
2569   uint64_t Res = 0;
2570   unsigned EltSize = Size / NElts;
2571   SDValue ConstVal;
2572   uint64_t Mask = ~uint64_t(0ULL) >> (64 - EltSize);
2573   bool HasNonConstantElements = false;
2574 
2575   for (unsigned i = 0, e = NElts; i != e; ++i) {
2576     // LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon's
2577     // combine, const64, etc. are Big Endian.
2578     unsigned OpIdx = NElts - i - 1;
2579     SDValue Operand = BVN->getOperand(OpIdx);
2580     if (Operand.isUndef())
2581       continue;
2582 
2583     int64_t Val = 0;
2584     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Operand))
2585       Val = Cst->getSExtValue();
2586     else
2587       HasNonConstantElements = true;
2588 
2589     Val &= Mask;
2590     Res = (Res << EltSize) | Val;
2591   }
2592 
2593   if (Size > 64)
2594     return SDValue();
2595 
2596   if (Size == 64)
2597     ConstVal = DAG.getConstant(Res, dl, MVT::i64);
2598   else
2599     ConstVal = DAG.getConstant(Res, dl, MVT::i32);
2600 
2601   // When there are non constant operands, add them with INSERT_VECTOR_ELT to
2602   // ConstVal, the constant part of the vector.
2603   if (HasNonConstantElements) {
2604     EVT EltVT = VT.getVectorElementType();
2605     SDValue Width = DAG.getConstant(EltVT.getSizeInBits(), dl, MVT::i64);
2606     SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2607                                   DAG.getConstant(32, dl, MVT::i64));
2608 
2609     for (unsigned i = 0, e = NElts; i != e; ++i) {
2610       // LLVM's BUILD_VECTOR operands are in Little Endian mode, whereas Hexagon
2611       // is Big Endian.
2612       unsigned OpIdx = NElts - i - 1;
2613       SDValue Operand = BVN->getOperand(OpIdx);
2614       if (isa<ConstantSDNode>(Operand))
2615         // This operand is already in ConstVal.
2616         continue;
2617 
2618       if (VT.getSizeInBits() == 64 &&
2619           Operand.getValueSizeInBits() == 32) {
2620         SDValue C = DAG.getConstant(0, dl, MVT::i32);
2621         Operand = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Operand);
2622       }
2623 
2624       SDValue Idx = DAG.getConstant(OpIdx, dl, MVT::i64);
2625       SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, Width);
2626       SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2627       const SDValue Ops[] = {ConstVal, Operand, Combined};
2628 
2629       if (VT.getSizeInBits() == 32)
2630         ConstVal = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i32, Ops);
2631       else
2632         ConstVal = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i64, Ops);
2633     }
2634   }
2635 
2636   return DAG.getNode(ISD::BITCAST, dl, VT, ConstVal);
2637 }
2638 
2639 SDValue
2640 HexagonTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
2641                                            SelectionDAG &DAG) const {
2642   SDLoc dl(Op);
2643   bool UseHVX = Subtarget.useHVXOps();
2644   EVT VT = Op.getValueType();
2645   unsigned NElts = Op.getNumOperands();
2646   SDValue Vec0 = Op.getOperand(0);
2647   EVT VecVT = Vec0.getValueType();
2648   unsigned Width = VecVT.getSizeInBits();
2649 
2650   if (NElts == 2) {
2651     MVT ST = VecVT.getSimpleVT();
2652     // We are trying to concat two v2i16 to a single v4i16, or two v4i8
2653     // into a single v8i8.
2654     if (ST == MVT::v2i16 || ST == MVT::v4i8)
2655       return DAG.getNode(HexagonISD::COMBINE, dl, VT, Op.getOperand(1), Vec0);
2656 
2657     if (UseHVX) {
2658       assert((Width ==  64*8 && Subtarget.useHVXSglOps()) ||
2659              (Width == 128*8 && Subtarget.useHVXDblOps()));
2660       SDValue Vec1 = Op.getOperand(1);
2661       MVT OpTy = Subtarget.useHVXSglOps() ? MVT::v16i32 : MVT::v32i32;
2662       MVT ReTy = Subtarget.useHVXSglOps() ? MVT::v32i32 : MVT::v64i32;
2663       SDValue B0 = DAG.getNode(ISD::BITCAST, dl, OpTy, Vec0);
2664       SDValue B1 = DAG.getNode(ISD::BITCAST, dl, OpTy, Vec1);
2665       SDValue VC = DAG.getNode(HexagonISD::VCOMBINE, dl, ReTy, B1, B0);
2666       return DAG.getNode(ISD::BITCAST, dl, VT, VC);
2667     }
2668   }
2669 
2670   if (VT.getSizeInBits() != 32 && VT.getSizeInBits() != 64)
2671     return SDValue();
2672 
2673   SDValue C0 = DAG.getConstant(0, dl, MVT::i64);
2674   SDValue C32 = DAG.getConstant(32, dl, MVT::i64);
2675   SDValue W = DAG.getConstant(Width, dl, MVT::i64);
2676   // Create the "width" part of the argument to insert_rp/insertp_rp.
2677   SDValue S = DAG.getNode(ISD::SHL, dl, MVT::i64, W, C32);
2678   SDValue V = C0;
2679 
2680   for (unsigned i = 0, e = NElts; i != e; ++i) {
2681     unsigned N = NElts-i-1;
2682     SDValue OpN = Op.getOperand(N);
2683 
2684     if (VT.getSizeInBits() == 64 && OpN.getValueSizeInBits() == 32) {
2685       SDValue C = DAG.getConstant(0, dl, MVT::i32);
2686       OpN = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, OpN);
2687     }
2688     SDValue Idx = DAG.getConstant(N, dl, MVT::i64);
2689     SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i64, Idx, W);
2690     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, S, Offset);
2691     if (VT.getSizeInBits() == 32)
2692       V = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i32, {V, OpN, Or});
2693     else if (VT.getSizeInBits() == 64)
2694       V = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i64, {V, OpN, Or});
2695     else
2696       return SDValue();
2697   }
2698 
2699   return DAG.getNode(ISD::BITCAST, dl, VT, V);
2700 }
2701 
2702 SDValue
2703 HexagonTargetLowering::LowerEXTRACT_SUBVECTOR_HVX(SDValue Op,
2704                                                   SelectionDAG &DAG) const {
2705   EVT VT = Op.getOperand(0).getValueType();
2706   SDLoc dl(Op);
2707   bool UseHVX = Subtarget.useHVXOps();
2708   bool UseHVXSgl = Subtarget.useHVXSglOps();
2709   // Just in case...
2710 
2711   if (!VT.isVector() || !UseHVX)
2712     return SDValue();
2713 
2714   EVT ResVT = Op.getValueType();
2715   unsigned ResSize = ResVT.getSizeInBits();
2716   unsigned VectorSizeInBits = UseHVXSgl ? (64 * 8) : (128 * 8);
2717   unsigned OpSize = VT.getSizeInBits();
2718 
2719   // We deal only with cases where the result is the vector size
2720   // and the vector operand is a double register.
2721   if (!(ResVT.isByteSized() && ResSize == VectorSizeInBits) ||
2722       !(VT.isByteSized() && OpSize == 2 * VectorSizeInBits))
2723     return SDValue();
2724 
2725   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2726   if (!Cst)
2727     return SDValue();
2728   unsigned Val = Cst->getZExtValue();
2729 
2730   // These two will get lowered to an appropriate EXTRACT_SUBREG in ISel.
2731   if (Val == 0) {
2732     SDValue Vec = Op.getOperand(0);
2733     return DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, ResVT, Vec);
2734   }
2735 
2736   if (ResVT.getVectorNumElements() == Val) {
2737     SDValue Vec = Op.getOperand(0);
2738     return DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, ResVT, Vec);
2739   }
2740 
2741   return SDValue();
2742 }
2743 
2744 SDValue
2745 HexagonTargetLowering::LowerEXTRACT_VECTOR(SDValue Op,
2746                                            SelectionDAG &DAG) const {
2747   // If we are dealing with EXTRACT_SUBVECTOR on a HVX type, we may
2748   // be able to simplify it to an EXTRACT_SUBREG.
2749   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR && Subtarget.useHVXOps() &&
2750       isHvxVectorType(Op.getValueType().getSimpleVT()))
2751     return LowerEXTRACT_SUBVECTOR_HVX(Op, DAG);
2752 
2753   EVT VT = Op.getValueType();
2754   int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
2755   SDLoc dl(Op);
2756   SDValue Idx = Op.getOperand(1);
2757   SDValue Vec = Op.getOperand(0);
2758   EVT VecVT = Vec.getValueType();
2759   EVT EltVT = VecVT.getVectorElementType();
2760   int EltSize = EltVT.getSizeInBits();
2761   SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT ?
2762                                   EltSize : VTN * EltSize, dl, MVT::i64);
2763 
2764   // Constant element number.
2765   if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Idx)) {
2766     uint64_t X = CI->getZExtValue();
2767     SDValue Offset = DAG.getConstant(X * EltSize, dl, MVT::i32);
2768     const SDValue Ops[] = {Vec, Width, Offset};
2769 
2770     ConstantSDNode *CW = dyn_cast<ConstantSDNode>(Width);
2771     assert(CW && "Non constant width in LowerEXTRACT_VECTOR");
2772 
2773     SDValue N;
2774     MVT SVT = VecVT.getSimpleVT();
2775     uint64_t W = CW->getZExtValue();
2776 
2777     if (W == 32) {
2778       // Translate this node into EXTRACT_SUBREG.
2779       unsigned Subreg = (X == 0) ? Hexagon::isub_lo : 0;
2780 
2781       if (X == 0)
2782         Subreg = Hexagon::isub_lo;
2783       else if (SVT == MVT::v2i32 && X == 1)
2784         Subreg = Hexagon::isub_hi;
2785       else if (SVT == MVT::v4i16 && X == 2)
2786         Subreg = Hexagon::isub_hi;
2787       else if (SVT == MVT::v8i8 && X == 4)
2788         Subreg = Hexagon::isub_hi;
2789       else
2790         llvm_unreachable("Bad offset");
2791       N = DAG.getTargetExtractSubreg(Subreg, dl, MVT::i32, Vec);
2792 
2793     } else if (SVT.getSizeInBits() == 32) {
2794       N = DAG.getNode(HexagonISD::EXTRACTU, dl, MVT::i32, Ops);
2795     } else if (SVT.getSizeInBits() == 64) {
2796       N = DAG.getNode(HexagonISD::EXTRACTU, dl, MVT::i64, Ops);
2797       if (VT.getSizeInBits() == 32)
2798         N = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, N);
2799     } else
2800       return SDValue();
2801 
2802     return DAG.getNode(ISD::BITCAST, dl, VT, N);
2803   }
2804 
2805   // Variable element number.
2806   SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
2807                                DAG.getConstant(EltSize, dl, MVT::i32));
2808   SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2809                                 DAG.getConstant(32, dl, MVT::i64));
2810   SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2811 
2812   const SDValue Ops[] = {Vec, Combined};
2813 
2814   SDValue N;
2815   if (VecVT.getSizeInBits() == 32) {
2816     N = DAG.getNode(HexagonISD::EXTRACTURP, dl, MVT::i32, Ops);
2817   } else {
2818     N = DAG.getNode(HexagonISD::EXTRACTURP, dl, MVT::i64, Ops);
2819     if (VT.getSizeInBits() == 32)
2820       N = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, N);
2821   }
2822   return DAG.getNode(ISD::BITCAST, dl, VT, N);
2823 }
2824 
2825 SDValue
2826 HexagonTargetLowering::LowerINSERT_VECTOR(SDValue Op,
2827                                           SelectionDAG &DAG) const {
2828   EVT VT = Op.getValueType();
2829   int VTN = VT.isVector() ? VT.getVectorNumElements() : 1;
2830   SDLoc dl(Op);
2831   SDValue Vec = Op.getOperand(0);
2832   SDValue Val = Op.getOperand(1);
2833   SDValue Idx = Op.getOperand(2);
2834   EVT VecVT = Vec.getValueType();
2835   EVT EltVT = VecVT.getVectorElementType();
2836   int EltSize = EltVT.getSizeInBits();
2837   SDValue Width = DAG.getConstant(Op.getOpcode() == ISD::INSERT_VECTOR_ELT ?
2838                                   EltSize : VTN * EltSize, dl, MVT::i64);
2839 
2840   if (ConstantSDNode *C = cast<ConstantSDNode>(Idx)) {
2841     SDValue Offset = DAG.getConstant(C->getSExtValue() * EltSize, dl, MVT::i32);
2842     const SDValue Ops[] = {Vec, Val, Width, Offset};
2843 
2844     SDValue N;
2845     if (VT.getSizeInBits() == 32)
2846       N = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32, Ops);
2847     else if (VT.getSizeInBits() == 64)
2848       N = DAG.getNode(HexagonISD::INSERT, dl, MVT::i64, Ops);
2849     else
2850       return SDValue();
2851 
2852     return DAG.getNode(ISD::BITCAST, dl, VT, N);
2853   }
2854 
2855   // Variable element number.
2856   SDValue Offset = DAG.getNode(ISD::MUL, dl, MVT::i32, Idx,
2857                                DAG.getConstant(EltSize, dl, MVT::i32));
2858   SDValue Shifted = DAG.getNode(ISD::SHL, dl, MVT::i64, Width,
2859                                 DAG.getConstant(32, dl, MVT::i64));
2860   SDValue Combined = DAG.getNode(ISD::OR, dl, MVT::i64, Shifted, Offset);
2861 
2862   if (VT.getSizeInBits() == 64 && Val.getValueSizeInBits() == 32) {
2863     SDValue C = DAG.getConstant(0, dl, MVT::i32);
2864     Val = DAG.getNode(HexagonISD::COMBINE, dl, VT, C, Val);
2865   }
2866 
2867   const SDValue Ops[] = {Vec, Val, Combined};
2868 
2869   SDValue N;
2870   if (VT.getSizeInBits() == 32)
2871     N = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i32, Ops);
2872   else if (VT.getSizeInBits() == 64)
2873     N = DAG.getNode(HexagonISD::INSERTRP, dl, MVT::i64, Ops);
2874   else
2875     return SDValue();
2876 
2877   return DAG.getNode(ISD::BITCAST, dl, VT, N);
2878 }
2879 
2880 bool
2881 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
2882   // Assuming the caller does not have either a signext or zeroext modifier, and
2883   // only one value is accepted, any reasonable truncation is allowed.
2884   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
2885     return false;
2886 
2887   // FIXME: in principle up to 64-bit could be made safe, but it would be very
2888   // fragile at the moment: any support for multiple value returns would be
2889   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
2890   return Ty1->getPrimitiveSizeInBits() <= 32;
2891 }
2892 
2893 SDValue
2894 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
2895   SDValue Chain     = Op.getOperand(0);
2896   SDValue Offset    = Op.getOperand(1);
2897   SDValue Handler   = Op.getOperand(2);
2898   SDLoc dl(Op);
2899   auto PtrVT = getPointerTy(DAG.getDataLayout());
2900 
2901   // Mark function as containing a call to EH_RETURN.
2902   HexagonMachineFunctionInfo *FuncInfo =
2903     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
2904   FuncInfo->setHasEHReturn();
2905 
2906   unsigned OffsetReg = Hexagon::R28;
2907 
2908   SDValue StoreAddr =
2909       DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getRegister(Hexagon::R30, PtrVT),
2910                   DAG.getIntPtrConstant(4, dl));
2911   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
2912   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
2913 
2914   // Not needed we already use it as explict input to EH_RETURN.
2915   // MF.getRegInfo().addLiveOut(OffsetReg);
2916 
2917   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
2918 }
2919 
2920 SDValue
2921 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2922   unsigned Opc = Op.getOpcode();
2923   switch (Opc) {
2924     default:
2925 #ifndef NDEBUG
2926       Op.getNode()->dumpr(&DAG);
2927       if (Opc > HexagonISD::OP_BEGIN && Opc < HexagonISD::OP_END)
2928         errs() << "Check for a non-legal type in this operation\n";
2929 #endif
2930       llvm_unreachable("Should not custom lower this!");
2931     case ISD::CONCAT_VECTORS:       return LowerCONCAT_VECTORS(Op, DAG);
2932     case ISD::INSERT_SUBVECTOR:     return LowerINSERT_VECTOR(Op, DAG);
2933     case ISD::INSERT_VECTOR_ELT:    return LowerINSERT_VECTOR(Op, DAG);
2934     case ISD::EXTRACT_SUBVECTOR:    return LowerEXTRACT_VECTOR(Op, DAG);
2935     case ISD::EXTRACT_VECTOR_ELT:   return LowerEXTRACT_VECTOR(Op, DAG);
2936     case ISD::BUILD_VECTOR:         return LowerBUILD_VECTOR(Op, DAG);
2937     case ISD::VECTOR_SHUFFLE:       return LowerVECTOR_SHUFFLE(Op, DAG);
2938     case ISD::SRA:
2939     case ISD::SHL:
2940     case ISD::SRL:                  return LowerVECTOR_SHIFT(Op, DAG);
2941     case ISD::ConstantPool:         return LowerConstantPool(Op, DAG);
2942     case ISD::JumpTable:            return LowerJumpTable(Op, DAG);
2943     case ISD::EH_RETURN:            return LowerEH_RETURN(Op, DAG);
2944       // Frame & Return address. Currently unimplemented.
2945     case ISD::RETURNADDR:           return LowerRETURNADDR(Op, DAG);
2946     case ISD::FRAMEADDR:            return LowerFRAMEADDR(Op, DAG);
2947     case ISD::GlobalTLSAddress:     return LowerGlobalTLSAddress(Op, DAG);
2948     case ISD::ATOMIC_FENCE:         return LowerATOMIC_FENCE(Op, DAG);
2949     case ISD::GlobalAddress:        return LowerGLOBALADDRESS(Op, DAG);
2950     case ISD::BlockAddress:         return LowerBlockAddress(Op, DAG);
2951     case ISD::GLOBAL_OFFSET_TABLE:  return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2952     case ISD::VASTART:              return LowerVASTART(Op, DAG);
2953     // Custom lower some vector loads.
2954     case ISD::LOAD:                 return LowerLOAD(Op, DAG);
2955     case ISD::DYNAMIC_STACKALLOC:   return LowerDYNAMIC_STACKALLOC(Op, DAG);
2956     case ISD::SETCC:                return LowerSETCC(Op, DAG);
2957     case ISD::VSELECT:              return LowerVSELECT(Op, DAG);
2958     case ISD::CTPOP:                return LowerCTPOP(Op, DAG);
2959     case ISD::INTRINSIC_WO_CHAIN:   return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2960     case ISD::INTRINSIC_VOID:       return LowerINTRINSIC_VOID(Op, DAG);
2961     case ISD::INLINEASM:            return LowerINLINEASM(Op, DAG);
2962     case ISD::PREFETCH:             return LowerPREFETCH(Op, DAG);
2963   }
2964 }
2965 
2966 /// Returns relocation base for the given PIC jumptable.
2967 SDValue
2968 HexagonTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2969                                                 SelectionDAG &DAG) const {
2970   int Idx = cast<JumpTableSDNode>(Table)->getIndex();
2971   EVT VT = Table.getValueType();
2972   SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
2973   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Table), VT, T);
2974 }
2975 
2976 //===----------------------------------------------------------------------===//
2977 // Inline Assembly Support
2978 //===----------------------------------------------------------------------===//
2979 
2980 TargetLowering::ConstraintType
2981 HexagonTargetLowering::getConstraintType(StringRef Constraint) const {
2982   if (Constraint.size() == 1) {
2983     switch (Constraint[0]) {
2984       case 'q':
2985       case 'v':
2986         if (Subtarget.useHVXOps())
2987           return C_Register;
2988         break;
2989     }
2990   }
2991   return TargetLowering::getConstraintType(Constraint);
2992 }
2993 
2994 std::pair<unsigned, const TargetRegisterClass*>
2995 HexagonTargetLowering::getRegForInlineAsmConstraint(
2996     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
2997   bool UseHVX = Subtarget.useHVXOps(), UseHVXDbl = Subtarget.useHVXDblOps();
2998 
2999   if (Constraint.size() == 1) {
3000     switch (Constraint[0]) {
3001     case 'r':   // R0-R31
3002       switch (VT.SimpleTy) {
3003       default:
3004         llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
3005       case MVT::i1:
3006       case MVT::i8:
3007       case MVT::i16:
3008       case MVT::i32:
3009       case MVT::f32:
3010         return std::make_pair(0U, &Hexagon::IntRegsRegClass);
3011       case MVT::i64:
3012       case MVT::f64:
3013         return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
3014       }
3015     case 'q': // q0-q3
3016       switch (VT.SimpleTy) {
3017       default:
3018         llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
3019       case MVT::v1024i1:
3020       case MVT::v512i1:
3021       case MVT::v32i16:
3022       case MVT::v16i32:
3023       case MVT::v64i8:
3024       case MVT::v8i64:
3025         return std::make_pair(0U, &Hexagon::VecPredRegsRegClass);
3026       }
3027     case 'v': // V0-V31
3028       switch (VT.SimpleTy) {
3029       default:
3030         llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
3031       case MVT::v16i32:
3032       case MVT::v32i16:
3033       case MVT::v64i8:
3034       case MVT::v8i64:
3035         return std::make_pair(0U, &Hexagon::VectorRegsRegClass);
3036       case MVT::v32i32:
3037       case MVT::v64i16:
3038       case MVT::v16i64:
3039       case MVT::v128i8:
3040         if (Subtarget.hasV60TOps() && UseHVX && UseHVXDbl)
3041           return std::make_pair(0U, &Hexagon::VectorRegs128BRegClass);
3042         return std::make_pair(0U, &Hexagon::VecDblRegsRegClass);
3043       case MVT::v256i8:
3044       case MVT::v128i16:
3045       case MVT::v64i32:
3046       case MVT::v32i64:
3047         return std::make_pair(0U, &Hexagon::VecDblRegs128BRegClass);
3048       }
3049 
3050     default:
3051       llvm_unreachable("Unknown asm register class");
3052     }
3053   }
3054 
3055   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3056 }
3057 
3058 /// isFPImmLegal - Returns true if the target can instruction select the
3059 /// specified FP immediate natively. If false, the legalizer will
3060 /// materialize the FP immediate as a load from a constant pool.
3061 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3062   return Subtarget.hasV5TOps();
3063 }
3064 
3065 /// isLegalAddressingMode - Return true if the addressing mode represented by
3066 /// AM is legal for this target, for a load/store of the specified type.
3067 bool HexagonTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3068                                                   const AddrMode &AM, Type *Ty,
3069                                                   unsigned AS) const {
3070   if (Ty->isSized()) {
3071     // When LSR detects uses of the same base address to access different
3072     // types (e.g. unions), it will assume a conservative type for these
3073     // uses:
3074     //   LSR Use: Kind=Address of void in addrspace(4294967295), ...
3075     // The type Ty passed here would then be "void". Skip the alignment
3076     // checks, but do not return false right away, since that confuses
3077     // LSR into crashing.
3078     unsigned A = DL.getABITypeAlignment(Ty);
3079     // The base offset must be a multiple of the alignment.
3080     if ((AM.BaseOffs % A) != 0)
3081       return false;
3082     // The shifted offset must fit in 11 bits.
3083     if (!isInt<11>(AM.BaseOffs >> Log2_32(A)))
3084       return false;
3085   }
3086 
3087   // No global is ever allowed as a base.
3088   if (AM.BaseGV)
3089     return false;
3090 
3091   int Scale = AM.Scale;
3092   if (Scale < 0)
3093     Scale = -Scale;
3094   switch (Scale) {
3095   case 0:  // No scale reg, "r+i", "r", or just "i".
3096     break;
3097   default: // No scaled addressing mode.
3098     return false;
3099   }
3100   return true;
3101 }
3102 
3103 /// Return true if folding a constant offset with the given GlobalAddress is
3104 /// legal.  It is frequently not legal in PIC relocation models.
3105 bool HexagonTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA)
3106       const {
3107   return HTM.getRelocationModel() == Reloc::Static;
3108 }
3109 
3110 
3111 /// isLegalICmpImmediate - Return true if the specified immediate is legal
3112 /// icmp immediate, that is the target has icmp instructions which can compare
3113 /// a register against the immediate without having to materialize the
3114 /// immediate into a register.
3115 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
3116   return Imm >= -512 && Imm <= 511;
3117 }
3118 
3119 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3120 /// for tail call optimization. Targets which want to do tail call
3121 /// optimization should implement this function.
3122 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
3123                                  SDValue Callee,
3124                                  CallingConv::ID CalleeCC,
3125                                  bool isVarArg,
3126                                  bool isCalleeStructRet,
3127                                  bool isCallerStructRet,
3128                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
3129                                  const SmallVectorImpl<SDValue> &OutVals,
3130                                  const SmallVectorImpl<ISD::InputArg> &Ins,
3131                                  SelectionDAG& DAG) const {
3132   const Function *CallerF = DAG.getMachineFunction().getFunction();
3133   CallingConv::ID CallerCC = CallerF->getCallingConv();
3134   bool CCMatch = CallerCC == CalleeCC;
3135 
3136   // ***************************************************************************
3137   //  Look for obvious safe cases to perform tail call optimization that do not
3138   //  require ABI changes.
3139   // ***************************************************************************
3140 
3141   // If this is a tail call via a function pointer, then don't do it!
3142   if (!isa<GlobalAddressSDNode>(Callee) &&
3143       !isa<ExternalSymbolSDNode>(Callee)) {
3144     return false;
3145   }
3146 
3147   // Do not optimize if the calling conventions do not match and the conventions
3148   // used are not C or Fast.
3149   if (!CCMatch) {
3150     bool R = (CallerCC == CallingConv::C || CallerCC == CallingConv::Fast);
3151     bool E = (CalleeCC == CallingConv::C || CalleeCC == CallingConv::Fast);
3152     // If R & E, then ok.
3153     if (!R || !E)
3154       return false;
3155   }
3156 
3157   // Do not tail call optimize vararg calls.
3158   if (isVarArg)
3159     return false;
3160 
3161   // Also avoid tail call optimization if either caller or callee uses struct
3162   // return semantics.
3163   if (isCalleeStructRet || isCallerStructRet)
3164     return false;
3165 
3166   // In addition to the cases above, we also disable Tail Call Optimization if
3167   // the calling convention code that at least one outgoing argument needs to
3168   // go on the stack. We cannot check that here because at this point that
3169   // information is not available.
3170   return true;
3171 }
3172 
3173 /// Returns the target specific optimal type for load and store operations as
3174 /// a result of memset, memcpy, and memmove lowering.
3175 ///
3176 /// If DstAlign is zero that means it's safe to destination alignment can
3177 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
3178 /// a need to check it against alignment requirement, probably because the
3179 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
3180 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
3181 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
3182 /// does not need to be loaded.  It returns EVT::Other if the type should be
3183 /// determined using generic target-independent logic.
3184 EVT HexagonTargetLowering::getOptimalMemOpType(uint64_t Size,
3185       unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset,
3186       bool MemcpyStrSrc, MachineFunction &MF) const {
3187 
3188   auto Aligned = [](unsigned GivenA, unsigned MinA) -> bool {
3189     return (GivenA % MinA) == 0;
3190   };
3191 
3192   if (Size >= 8 && Aligned(DstAlign, 8) && (IsMemset || Aligned(SrcAlign, 8)))
3193     return MVT::i64;
3194   if (Size >= 4 && Aligned(DstAlign, 4) && (IsMemset || Aligned(SrcAlign, 4)))
3195     return MVT::i32;
3196   if (Size >= 2 && Aligned(DstAlign, 2) && (IsMemset || Aligned(SrcAlign, 2)))
3197     return MVT::i16;
3198 
3199   return MVT::Other;
3200 }
3201 
3202 bool HexagonTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
3203       unsigned AS, unsigned Align, bool *Fast) const {
3204   if (Fast)
3205     *Fast = false;
3206 
3207   switch (VT.getSimpleVT().SimpleTy) {
3208   default:
3209     return false;
3210   case MVT::v64i8:
3211   case MVT::v128i8:
3212   case MVT::v256i8:
3213   case MVT::v32i16:
3214   case MVT::v64i16:
3215   case MVT::v128i16:
3216   case MVT::v16i32:
3217   case MVT::v32i32:
3218   case MVT::v64i32:
3219   case MVT::v8i64:
3220   case MVT::v16i64:
3221   case MVT::v32i64:
3222     return true;
3223   }
3224   return false;
3225 }
3226 
3227 
3228 std::pair<const TargetRegisterClass*, uint8_t>
3229 HexagonTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
3230       MVT VT) const {
3231   const TargetRegisterClass *RRC = nullptr;
3232 
3233   uint8_t Cost = 1;
3234   switch (VT.SimpleTy) {
3235   default:
3236     return TargetLowering::findRepresentativeClass(TRI, VT);
3237   case MVT::v64i8:
3238   case MVT::v32i16:
3239   case MVT::v16i32:
3240   case MVT::v8i64:
3241     RRC = &Hexagon::VectorRegsRegClass;
3242     break;
3243   case MVT::v128i8:
3244   case MVT::v64i16:
3245   case MVT::v32i32:
3246   case MVT::v16i64:
3247     if (Subtarget.hasV60TOps() && Subtarget.useHVXOps() &&
3248         Subtarget.useHVXDblOps())
3249       RRC = &Hexagon::VectorRegs128BRegClass;
3250     else
3251       RRC = &Hexagon::VecDblRegsRegClass;
3252     break;
3253   case MVT::v256i8:
3254   case MVT::v128i16:
3255   case MVT::v64i32:
3256   case MVT::v32i64:
3257     RRC = &Hexagon::VecDblRegs128BRegClass;
3258     break;
3259   }
3260   return std::make_pair(RRC, Cost);
3261 }
3262 
3263 Value *HexagonTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
3264       AtomicOrdering Ord) const {
3265   BasicBlock *BB = Builder.GetInsertBlock();
3266   Module *M = BB->getParent()->getParent();
3267   Type *Ty = cast<PointerType>(Addr->getType())->getElementType();
3268   unsigned SZ = Ty->getPrimitiveSizeInBits();
3269   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic loads supported");
3270   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_L2_loadw_locked
3271                                    : Intrinsic::hexagon_L4_loadd_locked;
3272   Value *Fn = Intrinsic::getDeclaration(M, IntID);
3273   return Builder.CreateCall(Fn, Addr, "larx");
3274 }
3275 
3276 /// Perform a store-conditional operation to Addr. Return the status of the
3277 /// store. This should be 0 if the store succeeded, non-zero otherwise.
3278 Value *HexagonTargetLowering::emitStoreConditional(IRBuilder<> &Builder,
3279       Value *Val, Value *Addr, AtomicOrdering Ord) const {
3280   BasicBlock *BB = Builder.GetInsertBlock();
3281   Module *M = BB->getParent()->getParent();
3282   Type *Ty = Val->getType();
3283   unsigned SZ = Ty->getPrimitiveSizeInBits();
3284   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic stores supported");
3285   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_S2_storew_locked
3286                                    : Intrinsic::hexagon_S4_stored_locked;
3287   Value *Fn = Intrinsic::getDeclaration(M, IntID);
3288   Value *Call = Builder.CreateCall(Fn, {Addr, Val}, "stcx");
3289   Value *Cmp = Builder.CreateICmpEQ(Call, Builder.getInt32(0), "");
3290   Value *Ext = Builder.CreateZExt(Cmp, Type::getInt32Ty(M->getContext()));
3291   return Ext;
3292 }
3293 
3294 TargetLowering::AtomicExpansionKind
3295 HexagonTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
3296   // Do not expand loads and stores that don't exceed 64 bits.
3297   return LI->getType()->getPrimitiveSizeInBits() > 64
3298              ? AtomicExpansionKind::LLOnly
3299              : AtomicExpansionKind::None;
3300 }
3301 
3302 bool HexagonTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
3303   // Do not expand loads and stores that don't exceed 64 bits.
3304   return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() > 64;
3305 }
3306 
3307 bool HexagonTargetLowering::shouldExpandAtomicCmpXchgInIR(
3308       AtomicCmpXchgInst *AI) const {
3309   const DataLayout &DL = AI->getModule()->getDataLayout();
3310   unsigned Size = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
3311   return Size >= 4 && Size <= 8;
3312 }
3313