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