xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonISelLowering.cpp (revision 4d3fc8b0570b29fb0d6ee9525f104d52176ff0d4)
1 //===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the interfaces that Hexagon uses to lower LLVM code
10 // into a selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "HexagonISelLowering.h"
15 #include "Hexagon.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonRegisterInfo.h"
18 #include "HexagonSubtarget.h"
19 #include "HexagonTargetMachine.h"
20 #include "HexagonTargetObjectFile.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RuntimeLibcalls.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/TargetCallingConv.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/DiagnosticInfo.h"
39 #include "llvm/IR/DiagnosticPrinter.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/InlineAsm.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/IntrinsicsHexagon.h"
47 #include "llvm/IR/IRBuilder.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/MC/MCRegisterInfo.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CodeGen.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetMachine.h"
60 #include <algorithm>
61 #include <cassert>
62 #include <cstddef>
63 #include <cstdint>
64 #include <limits>
65 #include <utility>
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "hexagon-lowering"
70 
71 static cl::opt<bool> EmitJumpTables("hexagon-emit-jump-tables",
72   cl::init(true), cl::Hidden,
73   cl::desc("Control jump table emission on Hexagon target"));
74 
75 static cl::opt<bool>
76     EnableHexSDNodeSched("enable-hexagon-sdnode-sched", cl::Hidden,
77                          cl::desc("Enable Hexagon SDNode scheduling"));
78 
79 static cl::opt<bool> EnableFastMath("ffast-math", cl::Hidden,
80                                     cl::desc("Enable Fast Math processing"));
81 
82 static cl::opt<int> MinimumJumpTables("minimum-jump-tables", cl::Hidden,
83                                       cl::init(5),
84                                       cl::desc("Set minimum jump tables"));
85 
86 static cl::opt<int>
87     MaxStoresPerMemcpyCL("max-store-memcpy", cl::Hidden, cl::init(6),
88                          cl::desc("Max #stores to inline memcpy"));
89 
90 static cl::opt<int>
91     MaxStoresPerMemcpyOptSizeCL("max-store-memcpy-Os", cl::Hidden, cl::init(4),
92                                 cl::desc("Max #stores to inline memcpy"));
93 
94 static cl::opt<int>
95     MaxStoresPerMemmoveCL("max-store-memmove", cl::Hidden, cl::init(6),
96                           cl::desc("Max #stores to inline memmove"));
97 
98 static cl::opt<int>
99     MaxStoresPerMemmoveOptSizeCL("max-store-memmove-Os", cl::Hidden,
100                                  cl::init(4),
101                                  cl::desc("Max #stores to inline memmove"));
102 
103 static cl::opt<int>
104     MaxStoresPerMemsetCL("max-store-memset", cl::Hidden, cl::init(8),
105                          cl::desc("Max #stores to inline memset"));
106 
107 static cl::opt<int>
108     MaxStoresPerMemsetOptSizeCL("max-store-memset-Os", cl::Hidden, cl::init(4),
109                                 cl::desc("Max #stores to inline memset"));
110 
111 static cl::opt<bool> AlignLoads("hexagon-align-loads",
112   cl::Hidden, cl::init(false),
113   cl::desc("Rewrite unaligned loads as a pair of aligned loads"));
114 
115 static cl::opt<bool>
116     DisableArgsMinAlignment("hexagon-disable-args-min-alignment", cl::Hidden,
117                             cl::init(false),
118                             cl::desc("Disable minimum alignment of 1 for "
119                                      "arguments passed by value on stack"));
120 
121 namespace {
122 
123   class HexagonCCState : public CCState {
124     unsigned NumNamedVarArgParams = 0;
125 
126   public:
127     HexagonCCState(CallingConv::ID CC, bool IsVarArg, MachineFunction &MF,
128                    SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
129                    unsigned NumNamedArgs)
130         : CCState(CC, IsVarArg, MF, locs, C),
131           NumNamedVarArgParams(NumNamedArgs) {}
132     unsigned getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
133   };
134 
135 } // end anonymous namespace
136 
137 
138 // Implement calling convention for Hexagon.
139 
140 static bool CC_SkipOdd(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
141                        CCValAssign::LocInfo &LocInfo,
142                        ISD::ArgFlagsTy &ArgFlags, CCState &State) {
143   static const MCPhysReg ArgRegs[] = {
144     Hexagon::R0, Hexagon::R1, Hexagon::R2,
145     Hexagon::R3, Hexagon::R4, Hexagon::R5
146   };
147   const unsigned NumArgRegs = array_lengthof(ArgRegs);
148   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
149 
150   // RegNum is an index into ArgRegs: skip a register if RegNum is odd.
151   if (RegNum != NumArgRegs && RegNum % 2 == 1)
152     State.AllocateReg(ArgRegs[RegNum]);
153 
154   // Always return false here, as this function only makes sure that the first
155   // unallocated register has an even register number and does not actually
156   // allocate a register for the current argument.
157   return false;
158 }
159 
160 #include "HexagonGenCallingConv.inc"
161 
162 
163 SDValue
164 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
165       const {
166   return SDValue();
167 }
168 
169 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
170 /// by "Src" to address "Dst" of size "Size".  Alignment information is
171 /// specified by the specific parameter attribute. The copy will be passed as
172 /// a byval function parameter.  Sometimes what we are copying is the end of a
173 /// larger object, the part that does not fit in registers.
174 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
175                                          SDValue Chain, ISD::ArgFlagsTy Flags,
176                                          SelectionDAG &DAG, const SDLoc &dl) {
177   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
178   return DAG.getMemcpy(
179       Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
180       /*isVolatile=*/false, /*AlwaysInline=*/false,
181       /*isTailCall=*/false, MachinePointerInfo(), MachinePointerInfo());
182 }
183 
184 bool
185 HexagonTargetLowering::CanLowerReturn(
186     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
187     const SmallVectorImpl<ISD::OutputArg> &Outs,
188     LLVMContext &Context) const {
189   SmallVector<CCValAssign, 16> RVLocs;
190   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
191 
192   if (MF.getSubtarget<HexagonSubtarget>().useHVXOps())
193     return CCInfo.CheckReturn(Outs, RetCC_Hexagon_HVX);
194   return CCInfo.CheckReturn(Outs, RetCC_Hexagon);
195 }
196 
197 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
198 // passed by value, the function prototype is modified to return void and
199 // the value is stored in memory pointed by a pointer passed by caller.
200 SDValue
201 HexagonTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
202                                    bool IsVarArg,
203                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
204                                    const SmallVectorImpl<SDValue> &OutVals,
205                                    const SDLoc &dl, SelectionDAG &DAG) const {
206   // CCValAssign - represent the assignment of the return value to locations.
207   SmallVector<CCValAssign, 16> RVLocs;
208 
209   // CCState - Info about the registers and stack slot.
210   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
211                  *DAG.getContext());
212 
213   // Analyze return values of ISD::RET
214   if (Subtarget.useHVXOps())
215     CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon_HVX);
216   else
217     CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
218 
219   SDValue Flag;
220   SmallVector<SDValue, 4> RetOps(1, Chain);
221 
222   // Copy the result values into the output registers.
223   for (unsigned i = 0; i != RVLocs.size(); ++i) {
224     CCValAssign &VA = RVLocs[i];
225     SDValue Val = OutVals[i];
226 
227     switch (VA.getLocInfo()) {
228       default:
229         // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
230         llvm_unreachable("Unknown loc info!");
231       case CCValAssign::Full:
232         break;
233       case CCValAssign::BCvt:
234         Val = DAG.getBitcast(VA.getLocVT(), Val);
235         break;
236       case CCValAssign::SExt:
237         Val = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Val);
238         break;
239       case CCValAssign::ZExt:
240         Val = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Val);
241         break;
242       case CCValAssign::AExt:
243         Val = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Val);
244         break;
245     }
246 
247     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Val, Flag);
248 
249     // Guarantee that all emitted copies are stuck together with flags.
250     Flag = Chain.getValue(1);
251     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
252   }
253 
254   RetOps[0] = Chain;  // Update chain.
255 
256   // Add the flag if we have it.
257   if (Flag.getNode())
258     RetOps.push_back(Flag);
259 
260   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
261 }
262 
263 bool HexagonTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
264   // If either no tail call or told not to tail call at all, don't.
265   return CI->isTailCall();
266 }
267 
268 Register HexagonTargetLowering::getRegisterByName(
269       const char* RegName, LLT VT, const MachineFunction &) const {
270   // Just support r19, the linux kernel uses it.
271   Register Reg = StringSwitch<Register>(RegName)
272                      .Case("r0", Hexagon::R0)
273                      .Case("r1", Hexagon::R1)
274                      .Case("r2", Hexagon::R2)
275                      .Case("r3", Hexagon::R3)
276                      .Case("r4", Hexagon::R4)
277                      .Case("r5", Hexagon::R5)
278                      .Case("r6", Hexagon::R6)
279                      .Case("r7", Hexagon::R7)
280                      .Case("r8", Hexagon::R8)
281                      .Case("r9", Hexagon::R9)
282                      .Case("r10", Hexagon::R10)
283                      .Case("r11", Hexagon::R11)
284                      .Case("r12", Hexagon::R12)
285                      .Case("r13", Hexagon::R13)
286                      .Case("r14", Hexagon::R14)
287                      .Case("r15", Hexagon::R15)
288                      .Case("r16", Hexagon::R16)
289                      .Case("r17", Hexagon::R17)
290                      .Case("r18", Hexagon::R18)
291                      .Case("r19", Hexagon::R19)
292                      .Case("r20", Hexagon::R20)
293                      .Case("r21", Hexagon::R21)
294                      .Case("r22", Hexagon::R22)
295                      .Case("r23", Hexagon::R23)
296                      .Case("r24", Hexagon::R24)
297                      .Case("r25", Hexagon::R25)
298                      .Case("r26", Hexagon::R26)
299                      .Case("r27", Hexagon::R27)
300                      .Case("r28", Hexagon::R28)
301                      .Case("r29", Hexagon::R29)
302                      .Case("r30", Hexagon::R30)
303                      .Case("r31", Hexagon::R31)
304                      .Case("r1:0", Hexagon::D0)
305                      .Case("r3:2", Hexagon::D1)
306                      .Case("r5:4", Hexagon::D2)
307                      .Case("r7:6", Hexagon::D3)
308                      .Case("r9:8", Hexagon::D4)
309                      .Case("r11:10", Hexagon::D5)
310                      .Case("r13:12", Hexagon::D6)
311                      .Case("r15:14", Hexagon::D7)
312                      .Case("r17:16", Hexagon::D8)
313                      .Case("r19:18", Hexagon::D9)
314                      .Case("r21:20", Hexagon::D10)
315                      .Case("r23:22", Hexagon::D11)
316                      .Case("r25:24", Hexagon::D12)
317                      .Case("r27:26", Hexagon::D13)
318                      .Case("r29:28", Hexagon::D14)
319                      .Case("r31:30", Hexagon::D15)
320                      .Case("sp", Hexagon::R29)
321                      .Case("fp", Hexagon::R30)
322                      .Case("lr", Hexagon::R31)
323                      .Case("p0", Hexagon::P0)
324                      .Case("p1", Hexagon::P1)
325                      .Case("p2", Hexagon::P2)
326                      .Case("p3", Hexagon::P3)
327                      .Case("sa0", Hexagon::SA0)
328                      .Case("lc0", Hexagon::LC0)
329                      .Case("sa1", Hexagon::SA1)
330                      .Case("lc1", Hexagon::LC1)
331                      .Case("m0", Hexagon::M0)
332                      .Case("m1", Hexagon::M1)
333                      .Case("usr", Hexagon::USR)
334                      .Case("ugp", Hexagon::UGP)
335                      .Case("cs0", Hexagon::CS0)
336                      .Case("cs1", Hexagon::CS1)
337                      .Default(Register());
338   if (Reg)
339     return Reg;
340 
341   report_fatal_error("Invalid register name global variable");
342 }
343 
344 /// LowerCallResult - Lower the result values of an ISD::CALL into the
345 /// appropriate copies out of appropriate physical registers.  This assumes that
346 /// Chain/Glue are the input chain/glue to use, and that TheCall is the call
347 /// being lowered. Returns a SDNode with the same number of values as the
348 /// ISD::CALL.
349 SDValue HexagonTargetLowering::LowerCallResult(
350     SDValue Chain, SDValue Glue, CallingConv::ID CallConv, bool IsVarArg,
351     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
352     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
353     const SmallVectorImpl<SDValue> &OutVals, SDValue Callee) const {
354   // Assign locations to each value returned by this call.
355   SmallVector<CCValAssign, 16> RVLocs;
356 
357   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
358                  *DAG.getContext());
359 
360   if (Subtarget.useHVXOps())
361     CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon_HVX);
362   else
363     CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
364 
365   // Copy all of the result registers out of their specified physreg.
366   for (unsigned i = 0; i != RVLocs.size(); ++i) {
367     SDValue RetVal;
368     if (RVLocs[i].getValVT() == MVT::i1) {
369       // Return values of type MVT::i1 require special handling. The reason
370       // is that MVT::i1 is associated with the PredRegs register class, but
371       // values of that type are still returned in R0. Generate an explicit
372       // copy into a predicate register from R0, and treat the value of the
373       // predicate register as the call result.
374       auto &MRI = DAG.getMachineFunction().getRegInfo();
375       SDValue FR0 = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
376                                        MVT::i32, Glue);
377       // FR0 = (Value, Chain, Glue)
378       Register PredR = MRI.createVirtualRegister(&Hexagon::PredRegsRegClass);
379       SDValue TPR = DAG.getCopyToReg(FR0.getValue(1), dl, PredR,
380                                      FR0.getValue(0), FR0.getValue(2));
381       // TPR = (Chain, Glue)
382       // Don't glue this CopyFromReg, because it copies from a virtual
383       // register. If it is glued to the call, InstrEmitter will add it
384       // as an implicit def to the call (EmitMachineNode).
385       RetVal = DAG.getCopyFromReg(TPR.getValue(0), dl, PredR, MVT::i1);
386       Glue = TPR.getValue(1);
387       Chain = TPR.getValue(0);
388     } else {
389       RetVal = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
390                                   RVLocs[i].getValVT(), Glue);
391       Glue = RetVal.getValue(2);
392       Chain = RetVal.getValue(1);
393     }
394     InVals.push_back(RetVal.getValue(0));
395   }
396 
397   return Chain;
398 }
399 
400 /// LowerCall - Functions arguments are copied from virtual regs to
401 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
402 SDValue
403 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
404                                  SmallVectorImpl<SDValue> &InVals) const {
405   SelectionDAG &DAG                     = CLI.DAG;
406   SDLoc &dl                             = CLI.DL;
407   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
408   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
409   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
410   SDValue Chain                         = CLI.Chain;
411   SDValue Callee                        = CLI.Callee;
412   CallingConv::ID CallConv              = CLI.CallConv;
413   bool IsVarArg                         = CLI.IsVarArg;
414   bool DoesNotReturn                    = CLI.DoesNotReturn;
415 
416   bool IsStructRet    = Outs.empty() ? false : Outs[0].Flags.isSRet();
417   MachineFunction &MF = DAG.getMachineFunction();
418   MachineFrameInfo &MFI = MF.getFrameInfo();
419   auto PtrVT = getPointerTy(MF.getDataLayout());
420 
421   unsigned NumParams = CLI.CB ? CLI.CB->getFunctionType()->getNumParams() : 0;
422   if (GlobalAddressSDNode *GAN = dyn_cast<GlobalAddressSDNode>(Callee))
423     Callee = DAG.getTargetGlobalAddress(GAN->getGlobal(), dl, MVT::i32);
424 
425   // Linux ABI treats var-arg calls the same way as regular ones.
426   bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
427 
428   // Analyze operands of the call, assigning locations to each operand.
429   SmallVector<CCValAssign, 16> ArgLocs;
430   HexagonCCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs, *DAG.getContext(),
431                         NumParams);
432 
433   if (Subtarget.useHVXOps())
434     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_HVX);
435   else if (DisableArgsMinAlignment)
436     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_Legacy);
437   else
438     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
439 
440   if (CLI.IsTailCall) {
441     bool StructAttrFlag = MF.getFunction().hasStructRetAttr();
442     CLI.IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
443                         IsVarArg, IsStructRet, StructAttrFlag, Outs,
444                         OutVals, Ins, DAG);
445     for (const CCValAssign &VA : ArgLocs) {
446       if (VA.isMemLoc()) {
447         CLI.IsTailCall = false;
448         break;
449       }
450     }
451     LLVM_DEBUG(dbgs() << (CLI.IsTailCall ? "Eligible for Tail Call\n"
452                                          : "Argument must be passed on stack. "
453                                            "Not eligible for Tail Call\n"));
454   }
455   // Get a count of how many bytes are to be pushed on the stack.
456   unsigned NumBytes = CCInfo.getNextStackOffset();
457   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
458   SmallVector<SDValue, 8> MemOpChains;
459 
460   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
461   SDValue StackPtr =
462       DAG.getCopyFromReg(Chain, dl, HRI.getStackRegister(), PtrVT);
463 
464   bool NeedsArgAlign = false;
465   Align LargestAlignSeen;
466   // Walk the register/memloc assignments, inserting copies/loads.
467   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
468     CCValAssign &VA = ArgLocs[i];
469     SDValue Arg = OutVals[i];
470     ISD::ArgFlagsTy Flags = Outs[i].Flags;
471     // Record if we need > 8 byte alignment on an argument.
472     bool ArgAlign = Subtarget.isHVXVectorType(VA.getValVT());
473     NeedsArgAlign |= ArgAlign;
474 
475     // Promote the value if needed.
476     switch (VA.getLocInfo()) {
477       default:
478         // Loc info must be one of Full, BCvt, SExt, ZExt, or AExt.
479         llvm_unreachable("Unknown loc info!");
480       case CCValAssign::Full:
481         break;
482       case CCValAssign::BCvt:
483         Arg = DAG.getBitcast(VA.getLocVT(), Arg);
484         break;
485       case CCValAssign::SExt:
486         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
487         break;
488       case CCValAssign::ZExt:
489         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
490         break;
491       case CCValAssign::AExt:
492         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
493         break;
494     }
495 
496     if (VA.isMemLoc()) {
497       unsigned LocMemOffset = VA.getLocMemOffset();
498       SDValue MemAddr = DAG.getConstant(LocMemOffset, dl,
499                                         StackPtr.getValueType());
500       MemAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, MemAddr);
501       if (ArgAlign)
502         LargestAlignSeen = std::max(
503             LargestAlignSeen, Align(VA.getLocVT().getStoreSizeInBits() / 8));
504       if (Flags.isByVal()) {
505         // The argument is a struct passed by value. According to LLVM, "Arg"
506         // is a pointer.
507         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, MemAddr, Chain,
508                                                         Flags, DAG, dl));
509       } else {
510         MachinePointerInfo LocPI = MachinePointerInfo::getStack(
511             DAG.getMachineFunction(), LocMemOffset);
512         SDValue S = DAG.getStore(Chain, dl, Arg, MemAddr, LocPI);
513         MemOpChains.push_back(S);
514       }
515       continue;
516     }
517 
518     // Arguments that can be passed on register must be kept at RegsToPass
519     // vector.
520     if (VA.isRegLoc())
521       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
522   }
523 
524   if (NeedsArgAlign && Subtarget.hasV60Ops()) {
525     LLVM_DEBUG(dbgs() << "Function needs byte stack align due to call args\n");
526     Align VecAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
527     LargestAlignSeen = std::max(LargestAlignSeen, VecAlign);
528     MFI.ensureMaxAlignment(LargestAlignSeen);
529   }
530   // Transform all store nodes into one single node because all store
531   // nodes are independent of each other.
532   if (!MemOpChains.empty())
533     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
534 
535   SDValue Glue;
536   if (!CLI.IsTailCall) {
537     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
538     Glue = Chain.getValue(1);
539   }
540 
541   // Build a sequence of copy-to-reg nodes chained together with token
542   // chain and flag operands which copy the outgoing args into registers.
543   // The Glue is necessary since all emitted instructions must be
544   // stuck together.
545   if (!CLI.IsTailCall) {
546     for (const auto &R : RegsToPass) {
547       Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
548       Glue = Chain.getValue(1);
549     }
550   } else {
551     // For tail calls lower the arguments to the 'real' stack slot.
552     //
553     // Force all the incoming stack arguments to be loaded from the stack
554     // before any new outgoing arguments are stored to the stack, because the
555     // outgoing stack slots may alias the incoming argument stack slots, and
556     // the alias isn't otherwise explicit. This is slightly more conservative
557     // than necessary, because it means that each store effectively depends
558     // on every argument instead of just those arguments it would clobber.
559     //
560     // Do not flag preceding copytoreg stuff together with the following stuff.
561     Glue = SDValue();
562     for (const auto &R : RegsToPass) {
563       Chain = DAG.getCopyToReg(Chain, dl, R.first, R.second, Glue);
564       Glue = Chain.getValue(1);
565     }
566     Glue = SDValue();
567   }
568 
569   bool LongCalls = MF.getSubtarget<HexagonSubtarget>().useLongCalls();
570   unsigned Flags = LongCalls ? HexagonII::HMOTF_ConstExtended : 0;
571 
572   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
573   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
574   // node so that legalize doesn't hack it.
575   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
576     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, PtrVT, 0, Flags);
577   } else if (ExternalSymbolSDNode *S =
578              dyn_cast<ExternalSymbolSDNode>(Callee)) {
579     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, Flags);
580   }
581 
582   // Returns a chain & a flag for retval copy to use.
583   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
584   SmallVector<SDValue, 8> Ops;
585   Ops.push_back(Chain);
586   Ops.push_back(Callee);
587 
588   // Add argument registers to the end of the list so that they are
589   // known live into the call.
590   for (const auto &R : RegsToPass)
591     Ops.push_back(DAG.getRegister(R.first, R.second.getValueType()));
592 
593   const uint32_t *Mask = HRI.getCallPreservedMask(MF, CallConv);
594   assert(Mask && "Missing call preserved mask for calling convention");
595   Ops.push_back(DAG.getRegisterMask(Mask));
596 
597   if (Glue.getNode())
598     Ops.push_back(Glue);
599 
600   if (CLI.IsTailCall) {
601     MFI.setHasTailCall();
602     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
603   }
604 
605   // Set this here because we need to know this for "hasFP" in frame lowering.
606   // The target-independent code calls getFrameRegister before setting it, and
607   // getFrameRegister uses hasFP to determine whether the function has FP.
608   MFI.setHasCalls(true);
609 
610   unsigned OpCode = DoesNotReturn ? HexagonISD::CALLnr : HexagonISD::CALL;
611   Chain = DAG.getNode(OpCode, dl, NodeTys, Ops);
612   Glue = Chain.getValue(1);
613 
614   // Create the CALLSEQ_END node.
615   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
616                              DAG.getIntPtrConstant(0, dl, true), Glue, dl);
617   Glue = Chain.getValue(1);
618 
619   // Handle result values, copying them out of physregs into vregs that we
620   // return.
621   return LowerCallResult(Chain, Glue, CallConv, IsVarArg, Ins, dl, DAG,
622                          InVals, OutVals, Callee);
623 }
624 
625 /// Returns true by value, base pointer and offset pointer and addressing
626 /// mode by reference if this node can be combined with a load / store to
627 /// form a post-indexed load / store.
628 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
629       SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM,
630       SelectionDAG &DAG) const {
631   LSBaseSDNode *LSN = dyn_cast<LSBaseSDNode>(N);
632   if (!LSN)
633     return false;
634   EVT VT = LSN->getMemoryVT();
635   if (!VT.isSimple())
636     return false;
637   bool IsLegalType = VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 ||
638                      VT == MVT::i64 || VT == MVT::f32 || VT == MVT::f64 ||
639                      VT == MVT::v2i16 || VT == MVT::v2i32 || VT == MVT::v4i8 ||
640                      VT == MVT::v4i16 || VT == MVT::v8i8 ||
641                      Subtarget.isHVXVectorType(VT.getSimpleVT());
642   if (!IsLegalType)
643     return false;
644 
645   if (Op->getOpcode() != ISD::ADD)
646     return false;
647   Base = Op->getOperand(0);
648   Offset = Op->getOperand(1);
649   if (!isa<ConstantSDNode>(Offset.getNode()))
650     return false;
651   AM = ISD::POST_INC;
652 
653   int32_t V = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
654   return Subtarget.getInstrInfo()->isValidAutoIncImm(VT, V);
655 }
656 
657 SDValue
658 HexagonTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
659   MachineFunction &MF = DAG.getMachineFunction();
660   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
661   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
662   unsigned LR = HRI.getRARegister();
663 
664   if ((Op.getOpcode() != ISD::INLINEASM &&
665        Op.getOpcode() != ISD::INLINEASM_BR) || HMFI.hasClobberLR())
666     return Op;
667 
668   unsigned NumOps = Op.getNumOperands();
669   if (Op.getOperand(NumOps-1).getValueType() == MVT::Glue)
670     --NumOps;  // Ignore the flag operand.
671 
672   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
673     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
674     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
675     ++i;  // Skip the ID value.
676 
677     switch (InlineAsm::getKind(Flags)) {
678       default:
679         llvm_unreachable("Bad flags!");
680       case InlineAsm::Kind_RegUse:
681       case InlineAsm::Kind_Imm:
682       case InlineAsm::Kind_Mem:
683         i += NumVals;
684         break;
685       case InlineAsm::Kind_Clobber:
686       case InlineAsm::Kind_RegDef:
687       case InlineAsm::Kind_RegDefEarlyClobber: {
688         for (; NumVals; --NumVals, ++i) {
689           Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
690           if (Reg != LR)
691             continue;
692           HMFI.setHasClobberLR(true);
693           return Op;
694         }
695         break;
696       }
697     }
698   }
699 
700   return Op;
701 }
702 
703 // Need to transform ISD::PREFETCH into something that doesn't inherit
704 // all of the properties of ISD::PREFETCH, specifically SDNPMayLoad and
705 // SDNPMayStore.
706 SDValue HexagonTargetLowering::LowerPREFETCH(SDValue Op,
707                                              SelectionDAG &DAG) const {
708   SDValue Chain = Op.getOperand(0);
709   SDValue Addr = Op.getOperand(1);
710   // Lower it to DCFETCH($reg, #0).  A "pat" will try to merge the offset in,
711   // if the "reg" is fed by an "add".
712   SDLoc DL(Op);
713   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
714   return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
715 }
716 
717 // Custom-handle ISD::READCYCLECOUNTER because the target-independent SDNode
718 // is marked as having side-effects, while the register read on Hexagon does
719 // not have any. TableGen refuses to accept the direct pattern from that node
720 // to the A4_tfrcpp.
721 SDValue HexagonTargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
722                                                      SelectionDAG &DAG) const {
723   SDValue Chain = Op.getOperand(0);
724   SDLoc dl(Op);
725   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
726   return DAG.getNode(HexagonISD::READCYCLE, dl, VTs, Chain);
727 }
728 
729 SDValue HexagonTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
730       SelectionDAG &DAG) const {
731   SDValue Chain = Op.getOperand(0);
732   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
733   // Lower the hexagon_prefetch builtin to DCFETCH, as above.
734   if (IntNo == Intrinsic::hexagon_prefetch) {
735     SDValue Addr = Op.getOperand(2);
736     SDLoc DL(Op);
737     SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
738     return DAG.getNode(HexagonISD::DCFETCH, DL, MVT::Other, Chain, Addr, Zero);
739   }
740   return SDValue();
741 }
742 
743 SDValue
744 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
745                                                SelectionDAG &DAG) const {
746   SDValue Chain = Op.getOperand(0);
747   SDValue Size = Op.getOperand(1);
748   SDValue Align = Op.getOperand(2);
749   SDLoc dl(Op);
750 
751   ConstantSDNode *AlignConst = dyn_cast<ConstantSDNode>(Align);
752   assert(AlignConst && "Non-constant Align in LowerDYNAMIC_STACKALLOC");
753 
754   unsigned A = AlignConst->getSExtValue();
755   auto &HFI = *Subtarget.getFrameLowering();
756   // "Zero" means natural stack alignment.
757   if (A == 0)
758     A = HFI.getStackAlign().value();
759 
760   LLVM_DEBUG({
761     dbgs () << __func__ << " Align: " << A << " Size: ";
762     Size.getNode()->dump(&DAG);
763     dbgs() << "\n";
764   });
765 
766   SDValue AC = DAG.getConstant(A, dl, MVT::i32);
767   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
768   SDValue AA = DAG.getNode(HexagonISD::ALLOCA, dl, VTs, Chain, Size, AC);
769 
770   DAG.ReplaceAllUsesOfValueWith(Op, AA);
771   return AA;
772 }
773 
774 SDValue HexagonTargetLowering::LowerFormalArguments(
775     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
776     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
777     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
778   MachineFunction &MF = DAG.getMachineFunction();
779   MachineFrameInfo &MFI = MF.getFrameInfo();
780   MachineRegisterInfo &MRI = MF.getRegInfo();
781 
782   // Linux ABI treats var-arg calls the same way as regular ones.
783   bool TreatAsVarArg = !Subtarget.isEnvironmentMusl() && IsVarArg;
784 
785   // Assign locations to all of the incoming arguments.
786   SmallVector<CCValAssign, 16> ArgLocs;
787   HexagonCCState CCInfo(CallConv, TreatAsVarArg, MF, ArgLocs,
788                         *DAG.getContext(),
789                         MF.getFunction().getFunctionType()->getNumParams());
790 
791   if (Subtarget.useHVXOps())
792     CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon_HVX);
793   else if (DisableArgsMinAlignment)
794     CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon_Legacy);
795   else
796     CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
797 
798   // For LLVM, in the case when returning a struct by value (>8byte),
799   // the first argument is a pointer that points to the location on caller's
800   // stack where the return value will be stored. For Hexagon, the location on
801   // caller's stack is passed only when the struct size is smaller than (and
802   // equal to) 8 bytes. If not, no address will be passed into callee and
803   // callee return the result direclty through R0/R1.
804   auto NextSingleReg = [] (const TargetRegisterClass &RC, unsigned Reg) {
805     switch (RC.getID()) {
806     case Hexagon::IntRegsRegClassID:
807       return Reg - Hexagon::R0 + 1;
808     case Hexagon::DoubleRegsRegClassID:
809       return (Reg - Hexagon::D0 + 1) * 2;
810     case Hexagon::HvxVRRegClassID:
811       return Reg - Hexagon::V0 + 1;
812     case Hexagon::HvxWRRegClassID:
813       return (Reg - Hexagon::W0 + 1) * 2;
814     }
815     llvm_unreachable("Unexpected register class");
816   };
817 
818   auto &HFL = const_cast<HexagonFrameLowering&>(*Subtarget.getFrameLowering());
819   auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
820   HFL.FirstVarArgSavedReg = 0;
821   HMFI.setFirstNamedArgFrameIndex(-int(MFI.getNumFixedObjects()));
822 
823   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
824     CCValAssign &VA = ArgLocs[i];
825     ISD::ArgFlagsTy Flags = Ins[i].Flags;
826     bool ByVal = Flags.isByVal();
827 
828     // Arguments passed in registers:
829     // 1. 32- and 64-bit values and HVX vectors are passed directly,
830     // 2. Large structs are passed via an address, and the address is
831     //    passed in a register.
832     if (VA.isRegLoc() && ByVal && Flags.getByValSize() <= 8)
833       llvm_unreachable("ByValSize must be bigger than 8 bytes");
834 
835     bool InReg = VA.isRegLoc() &&
836                  (!ByVal || (ByVal && Flags.getByValSize() > 8));
837 
838     if (InReg) {
839       MVT RegVT = VA.getLocVT();
840       if (VA.getLocInfo() == CCValAssign::BCvt)
841         RegVT = VA.getValVT();
842 
843       const TargetRegisterClass *RC = getRegClassFor(RegVT);
844       Register VReg = MRI.createVirtualRegister(RC);
845       SDValue Copy = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
846 
847       // Treat values of type MVT::i1 specially: they are passed in
848       // registers of type i32, but they need to remain as values of
849       // type i1 for consistency of the argument lowering.
850       if (VA.getValVT() == MVT::i1) {
851         assert(RegVT.getSizeInBits() <= 32);
852         SDValue T = DAG.getNode(ISD::AND, dl, RegVT,
853                                 Copy, DAG.getConstant(1, dl, RegVT));
854         Copy = DAG.getSetCC(dl, MVT::i1, T, DAG.getConstant(0, dl, RegVT),
855                             ISD::SETNE);
856       } else {
857 #ifndef NDEBUG
858         unsigned RegSize = RegVT.getSizeInBits();
859         assert(RegSize == 32 || RegSize == 64 ||
860                Subtarget.isHVXVectorType(RegVT));
861 #endif
862       }
863       InVals.push_back(Copy);
864       MRI.addLiveIn(VA.getLocReg(), VReg);
865       HFL.FirstVarArgSavedReg = NextSingleReg(*RC, VA.getLocReg());
866     } else {
867       assert(VA.isMemLoc() && "Argument should be passed in memory");
868 
869       // If it's a byval parameter, then we need to compute the
870       // "real" size, not the size of the pointer.
871       unsigned ObjSize = Flags.isByVal()
872                             ? Flags.getByValSize()
873                             : VA.getLocVT().getStoreSizeInBits() / 8;
874 
875       // Create the frame index object for this incoming parameter.
876       int Offset = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
877       int FI = MFI.CreateFixedObject(ObjSize, Offset, true);
878       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
879 
880       if (Flags.isByVal()) {
881         // If it's a pass-by-value aggregate, then do not dereference the stack
882         // location. Instead, we should generate a reference to the stack
883         // location.
884         InVals.push_back(FIN);
885       } else {
886         SDValue L = DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
887                                 MachinePointerInfo::getFixedStack(MF, FI, 0));
888         InVals.push_back(L);
889       }
890     }
891   }
892 
893   if (IsVarArg && Subtarget.isEnvironmentMusl()) {
894     for (int i = HFL.FirstVarArgSavedReg; i < 6; i++)
895       MRI.addLiveIn(Hexagon::R0+i);
896   }
897 
898   if (IsVarArg && Subtarget.isEnvironmentMusl()) {
899     HMFI.setFirstNamedArgFrameIndex(HMFI.getFirstNamedArgFrameIndex() - 1);
900     HMFI.setLastNamedArgFrameIndex(-int(MFI.getNumFixedObjects()));
901 
902     // Create Frame index for the start of register saved area.
903     int NumVarArgRegs = 6 - HFL.FirstVarArgSavedReg;
904     bool RequiresPadding = (NumVarArgRegs & 1);
905     int RegSaveAreaSizePlusPadding = RequiresPadding
906                                         ? (NumVarArgRegs + 1) * 4
907                                         : NumVarArgRegs * 4;
908 
909     if (RegSaveAreaSizePlusPadding > 0) {
910       // The offset to saved register area should be 8 byte aligned.
911       int RegAreaStart = HEXAGON_LRFP_SIZE + CCInfo.getNextStackOffset();
912       if (!(RegAreaStart % 8))
913         RegAreaStart = (RegAreaStart + 7) & -8;
914 
915       int RegSaveAreaFrameIndex =
916         MFI.CreateFixedObject(RegSaveAreaSizePlusPadding, RegAreaStart, true);
917       HMFI.setRegSavedAreaStartFrameIndex(RegSaveAreaFrameIndex);
918 
919       // This will point to the next argument passed via stack.
920       int Offset = RegAreaStart + RegSaveAreaSizePlusPadding;
921       int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
922       HMFI.setVarArgsFrameIndex(FI);
923     } else {
924       // This will point to the next argument passed via stack, when
925       // there is no saved register area.
926       int Offset = HEXAGON_LRFP_SIZE + CCInfo.getNextStackOffset();
927       int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
928       HMFI.setRegSavedAreaStartFrameIndex(FI);
929       HMFI.setVarArgsFrameIndex(FI);
930     }
931   }
932 
933 
934   if (IsVarArg && !Subtarget.isEnvironmentMusl()) {
935     // This will point to the next argument passed via stack.
936     int Offset = HEXAGON_LRFP_SIZE + CCInfo.getNextStackOffset();
937     int FI = MFI.CreateFixedObject(Hexagon_PointerSize, Offset, true);
938     HMFI.setVarArgsFrameIndex(FI);
939   }
940 
941   return Chain;
942 }
943 
944 SDValue
945 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
946   // VASTART stores the address of the VarArgsFrameIndex slot into the
947   // memory location argument.
948   MachineFunction &MF = DAG.getMachineFunction();
949   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
950   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
951   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
952 
953   if (!Subtarget.isEnvironmentMusl()) {
954     return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr, Op.getOperand(1),
955                         MachinePointerInfo(SV));
956   }
957   auto &FuncInfo = *MF.getInfo<HexagonMachineFunctionInfo>();
958   auto &HFL = *Subtarget.getFrameLowering();
959   SDLoc DL(Op);
960   SmallVector<SDValue, 8> MemOps;
961 
962   // Get frame index of va_list.
963   SDValue FIN = Op.getOperand(1);
964 
965   // If first Vararg register is odd, add 4 bytes to start of
966   // saved register area to point to the first register location.
967   // This is because the saved register area has to be 8 byte aligned.
968   // Incase of an odd start register, there will be 4 bytes of padding in
969   // the beginning of saved register area. If all registers area used up,
970   // the following condition will handle it correctly.
971   SDValue SavedRegAreaStartFrameIndex =
972     DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(), MVT::i32);
973 
974   auto PtrVT = getPointerTy(DAG.getDataLayout());
975 
976   if (HFL.FirstVarArgSavedReg & 1)
977     SavedRegAreaStartFrameIndex =
978       DAG.getNode(ISD::ADD, DL, PtrVT,
979                   DAG.getFrameIndex(FuncInfo.getRegSavedAreaStartFrameIndex(),
980                                     MVT::i32),
981                   DAG.getIntPtrConstant(4, DL));
982 
983   // Store the saved register area start pointer.
984   SDValue Store =
985     DAG.getStore(Op.getOperand(0), DL,
986                  SavedRegAreaStartFrameIndex,
987                  FIN, MachinePointerInfo(SV));
988   MemOps.push_back(Store);
989 
990   // Store saved register area end pointer.
991   FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
992                     FIN, DAG.getIntPtrConstant(4, DL));
993   Store = DAG.getStore(Op.getOperand(0), DL,
994                        DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
995                                          PtrVT),
996                        FIN, MachinePointerInfo(SV, 4));
997   MemOps.push_back(Store);
998 
999   // Store overflow area pointer.
1000   FIN = DAG.getNode(ISD::ADD, DL, PtrVT,
1001                     FIN, DAG.getIntPtrConstant(4, DL));
1002   Store = DAG.getStore(Op.getOperand(0), DL,
1003                        DAG.getFrameIndex(FuncInfo.getVarArgsFrameIndex(),
1004                                          PtrVT),
1005                        FIN, MachinePointerInfo(SV, 8));
1006   MemOps.push_back(Store);
1007 
1008   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1009 }
1010 
1011 SDValue
1012 HexagonTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
1013   // Assert that the linux ABI is enabled for the current compilation.
1014   assert(Subtarget.isEnvironmentMusl() && "Linux ABI should be enabled");
1015   SDValue Chain = Op.getOperand(0);
1016   SDValue DestPtr = Op.getOperand(1);
1017   SDValue SrcPtr = Op.getOperand(2);
1018   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1019   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1020   SDLoc DL(Op);
1021   // Size of the va_list is 12 bytes as it has 3 pointers. Therefore,
1022   // we need to memcopy 12 bytes from va_list to another similar list.
1023   return DAG.getMemcpy(Chain, DL, DestPtr, SrcPtr,
1024                        DAG.getIntPtrConstant(12, DL), Align(4),
1025                        /*isVolatile*/ false, false, false,
1026                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
1027 }
1028 
1029 SDValue HexagonTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1030   const SDLoc &dl(Op);
1031   SDValue LHS = Op.getOperand(0);
1032   SDValue RHS = Op.getOperand(1);
1033   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1034   MVT ResTy = ty(Op);
1035   MVT OpTy = ty(LHS);
1036 
1037   if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1038     MVT ElemTy = OpTy.getVectorElementType();
1039     assert(ElemTy.isScalarInteger());
1040     MVT WideTy = MVT::getVectorVT(MVT::getIntegerVT(2*ElemTy.getSizeInBits()),
1041                                   OpTy.getVectorNumElements());
1042     return DAG.getSetCC(dl, ResTy,
1043                         DAG.getSExtOrTrunc(LHS, SDLoc(LHS), WideTy),
1044                         DAG.getSExtOrTrunc(RHS, SDLoc(RHS), WideTy), CC);
1045   }
1046 
1047   // Treat all other vector types as legal.
1048   if (ResTy.isVector())
1049     return Op;
1050 
1051   // Comparisons of short integers should use sign-extend, not zero-extend,
1052   // since we can represent small negative values in the compare instructions.
1053   // The LLVM default is to use zero-extend arbitrarily in these cases.
1054   auto isSExtFree = [this](SDValue N) {
1055     switch (N.getOpcode()) {
1056       case ISD::TRUNCATE: {
1057         // A sign-extend of a truncate of a sign-extend is free.
1058         SDValue Op = N.getOperand(0);
1059         if (Op.getOpcode() != ISD::AssertSext)
1060           return false;
1061         EVT OrigTy = cast<VTSDNode>(Op.getOperand(1))->getVT();
1062         unsigned ThisBW = ty(N).getSizeInBits();
1063         unsigned OrigBW = OrigTy.getSizeInBits();
1064         // The type that was sign-extended to get the AssertSext must be
1065         // narrower than the type of N (so that N has still the same value
1066         // as the original).
1067         return ThisBW >= OrigBW;
1068       }
1069       case ISD::LOAD:
1070         // We have sign-extended loads.
1071         return true;
1072     }
1073     return false;
1074   };
1075 
1076   if (OpTy == MVT::i8 || OpTy == MVT::i16) {
1077     ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
1078     bool IsNegative = C && C->getAPIntValue().isNegative();
1079     if (IsNegative || isSExtFree(LHS) || isSExtFree(RHS))
1080       return DAG.getSetCC(dl, ResTy,
1081                           DAG.getSExtOrTrunc(LHS, SDLoc(LHS), MVT::i32),
1082                           DAG.getSExtOrTrunc(RHS, SDLoc(RHS), MVT::i32), CC);
1083   }
1084 
1085   return SDValue();
1086 }
1087 
1088 SDValue
1089 HexagonTargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
1090   SDValue PredOp = Op.getOperand(0);
1091   SDValue Op1 = Op.getOperand(1), Op2 = Op.getOperand(2);
1092   MVT OpTy = ty(Op1);
1093   const SDLoc &dl(Op);
1094 
1095   if (OpTy == MVT::v2i16 || OpTy == MVT::v4i8) {
1096     MVT ElemTy = OpTy.getVectorElementType();
1097     assert(ElemTy.isScalarInteger());
1098     MVT WideTy = MVT::getVectorVT(MVT::getIntegerVT(2*ElemTy.getSizeInBits()),
1099                                   OpTy.getVectorNumElements());
1100     // Generate (trunc (select (_, sext, sext))).
1101     return DAG.getSExtOrTrunc(
1102               DAG.getSelect(dl, WideTy, PredOp,
1103                             DAG.getSExtOrTrunc(Op1, dl, WideTy),
1104                             DAG.getSExtOrTrunc(Op2, dl, WideTy)),
1105               dl, OpTy);
1106   }
1107 
1108   return SDValue();
1109 }
1110 
1111 SDValue
1112 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
1113   EVT ValTy = Op.getValueType();
1114   ConstantPoolSDNode *CPN = cast<ConstantPoolSDNode>(Op);
1115   Constant *CVal = nullptr;
1116   bool isVTi1Type = false;
1117   if (auto *CV = dyn_cast<ConstantVector>(CPN->getConstVal())) {
1118     if (cast<VectorType>(CV->getType())->getElementType()->isIntegerTy(1)) {
1119       IRBuilder<> IRB(CV->getContext());
1120       SmallVector<Constant*, 128> NewConst;
1121       unsigned VecLen = CV->getNumOperands();
1122       assert(isPowerOf2_32(VecLen) &&
1123              "conversion only supported for pow2 VectorSize");
1124       for (unsigned i = 0; i < VecLen; ++i)
1125         NewConst.push_back(IRB.getInt8(CV->getOperand(i)->isZeroValue()));
1126 
1127       CVal = ConstantVector::get(NewConst);
1128       isVTi1Type = true;
1129     }
1130   }
1131   Align Alignment = CPN->getAlign();
1132   bool IsPositionIndependent = isPositionIndependent();
1133   unsigned char TF = IsPositionIndependent ? HexagonII::MO_PCREL : 0;
1134 
1135   unsigned Offset = 0;
1136   SDValue T;
1137   if (CPN->isMachineConstantPoolEntry())
1138     T = DAG.getTargetConstantPool(CPN->getMachineCPVal(), ValTy, Alignment,
1139                                   Offset, TF);
1140   else if (isVTi1Type)
1141     T = DAG.getTargetConstantPool(CVal, ValTy, Alignment, Offset, TF);
1142   else
1143     T = DAG.getTargetConstantPool(CPN->getConstVal(), ValTy, Alignment, Offset,
1144                                   TF);
1145 
1146   assert(cast<ConstantPoolSDNode>(T)->getTargetFlags() == TF &&
1147          "Inconsistent target flag encountered");
1148 
1149   if (IsPositionIndependent)
1150     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), ValTy, T);
1151   return DAG.getNode(HexagonISD::CP, SDLoc(Op), ValTy, T);
1152 }
1153 
1154 SDValue
1155 HexagonTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1156   EVT VT = Op.getValueType();
1157   int Idx = cast<JumpTableSDNode>(Op)->getIndex();
1158   if (isPositionIndependent()) {
1159     SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
1160     return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), VT, T);
1161   }
1162 
1163   SDValue T = DAG.getTargetJumpTable(Idx, VT);
1164   return DAG.getNode(HexagonISD::JT, SDLoc(Op), VT, T);
1165 }
1166 
1167 SDValue
1168 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
1169   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1170   MachineFunction &MF = DAG.getMachineFunction();
1171   MachineFrameInfo &MFI = MF.getFrameInfo();
1172   MFI.setReturnAddressIsTaken(true);
1173 
1174   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1175     return SDValue();
1176 
1177   EVT VT = Op.getValueType();
1178   SDLoc dl(Op);
1179   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1180   if (Depth) {
1181     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1182     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
1183     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
1184                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
1185                        MachinePointerInfo());
1186   }
1187 
1188   // Return LR, which contains the return address. Mark it an implicit live-in.
1189   Register Reg = MF.addLiveIn(HRI.getRARegister(), getRegClassFor(MVT::i32));
1190   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
1191 }
1192 
1193 SDValue
1194 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1195   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1196   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1197   MFI.setFrameAddressIsTaken(true);
1198 
1199   EVT VT = Op.getValueType();
1200   SDLoc dl(Op);
1201   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1202   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1203                                          HRI.getFrameRegister(), VT);
1204   while (Depth--)
1205     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1206                             MachinePointerInfo());
1207   return FrameAddr;
1208 }
1209 
1210 SDValue
1211 HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op, SelectionDAG& DAG) const {
1212   SDLoc dl(Op);
1213   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1214 }
1215 
1216 SDValue
1217 HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op, SelectionDAG &DAG) const {
1218   SDLoc dl(Op);
1219   auto *GAN = cast<GlobalAddressSDNode>(Op);
1220   auto PtrVT = getPointerTy(DAG.getDataLayout());
1221   auto *GV = GAN->getGlobal();
1222   int64_t Offset = GAN->getOffset();
1223 
1224   auto &HLOF = *HTM.getObjFileLowering();
1225   Reloc::Model RM = HTM.getRelocationModel();
1226 
1227   if (RM == Reloc::Static) {
1228     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
1229     const GlobalObject *GO = GV->getAliaseeObject();
1230     if (GO && Subtarget.useSmallData() && HLOF.isGlobalInSmallSection(GO, HTM))
1231       return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, GA);
1232     return DAG.getNode(HexagonISD::CONST32, dl, PtrVT, GA);
1233   }
1234 
1235   bool UsePCRel = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1236   if (UsePCRel) {
1237     SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset,
1238                                             HexagonII::MO_PCREL);
1239     return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, GA);
1240   }
1241 
1242   // Use GOT index.
1243   SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1244   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, HexagonII::MO_GOT);
1245   SDValue Off = DAG.getConstant(Offset, dl, MVT::i32);
1246   return DAG.getNode(HexagonISD::AT_GOT, dl, PtrVT, GOT, GA, Off);
1247 }
1248 
1249 // Specifies that for loads and stores VT can be promoted to PromotedLdStVT.
1250 SDValue
1251 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1252   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1253   SDLoc dl(Op);
1254   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1255 
1256   Reloc::Model RM = HTM.getRelocationModel();
1257   if (RM == Reloc::Static) {
1258     SDValue A = DAG.getTargetBlockAddress(BA, PtrVT);
1259     return DAG.getNode(HexagonISD::CONST32_GP, dl, PtrVT, A);
1260   }
1261 
1262   SDValue A = DAG.getTargetBlockAddress(BA, PtrVT, 0, HexagonII::MO_PCREL);
1263   return DAG.getNode(HexagonISD::AT_PCREL, dl, PtrVT, A);
1264 }
1265 
1266 SDValue
1267 HexagonTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op, SelectionDAG &DAG)
1268       const {
1269   EVT PtrVT = getPointerTy(DAG.getDataLayout());
1270   SDValue GOTSym = DAG.getTargetExternalSymbol(HEXAGON_GOT_SYM_NAME, PtrVT,
1271                                                HexagonII::MO_PCREL);
1272   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Op), PtrVT, GOTSym);
1273 }
1274 
1275 SDValue
1276 HexagonTargetLowering::GetDynamicTLSAddr(SelectionDAG &DAG, SDValue Chain,
1277       GlobalAddressSDNode *GA, SDValue Glue, EVT PtrVT, unsigned ReturnReg,
1278       unsigned char OperandFlags) const {
1279   MachineFunction &MF = DAG.getMachineFunction();
1280   MachineFrameInfo &MFI = MF.getFrameInfo();
1281   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1282   SDLoc dl(GA);
1283   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
1284                                            GA->getValueType(0),
1285                                            GA->getOffset(),
1286                                            OperandFlags);
1287   // Create Operands for the call.The Operands should have the following:
1288   // 1. Chain SDValue
1289   // 2. Callee which in this case is the Global address value.
1290   // 3. Registers live into the call.In this case its R0, as we
1291   //    have just one argument to be passed.
1292   // 4. Glue.
1293   // Note: The order is important.
1294 
1295   const auto &HRI = *Subtarget.getRegisterInfo();
1296   const uint32_t *Mask = HRI.getCallPreservedMask(MF, CallingConv::C);
1297   assert(Mask && "Missing call preserved mask for calling convention");
1298   SDValue Ops[] = { Chain, TGA, DAG.getRegister(Hexagon::R0, PtrVT),
1299                     DAG.getRegisterMask(Mask), Glue };
1300   Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
1301 
1302   // Inform MFI that function has calls.
1303   MFI.setAdjustsStack(true);
1304 
1305   Glue = Chain.getValue(1);
1306   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
1307 }
1308 
1309 //
1310 // Lower using the intial executable model for TLS addresses
1311 //
1312 SDValue
1313 HexagonTargetLowering::LowerToTLSInitialExecModel(GlobalAddressSDNode *GA,
1314       SelectionDAG &DAG) const {
1315   SDLoc dl(GA);
1316   int64_t Offset = GA->getOffset();
1317   auto PtrVT = getPointerTy(DAG.getDataLayout());
1318 
1319   // Get the thread pointer.
1320   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1321 
1322   bool IsPositionIndependent = isPositionIndependent();
1323   unsigned char TF =
1324       IsPositionIndependent ? HexagonII::MO_IEGOT : HexagonII::MO_IE;
1325 
1326   // First generate the TLS symbol address
1327   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT,
1328                                            Offset, TF);
1329 
1330   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1331 
1332   if (IsPositionIndependent) {
1333     // Generate the GOT pointer in case of position independent code
1334     SDValue GOT = LowerGLOBAL_OFFSET_TABLE(Sym, DAG);
1335 
1336     // Add the TLS Symbol address to GOT pointer.This gives
1337     // GOT relative relocation for the symbol.
1338     Sym = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1339   }
1340 
1341   // Load the offset value for TLS symbol.This offset is relative to
1342   // thread pointer.
1343   SDValue LoadOffset =
1344       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Sym, MachinePointerInfo());
1345 
1346   // Address of the thread local variable is the add of thread
1347   // pointer and the offset of the variable.
1348   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, LoadOffset);
1349 }
1350 
1351 //
1352 // Lower using the local executable model for TLS addresses
1353 //
1354 SDValue
1355 HexagonTargetLowering::LowerToTLSLocalExecModel(GlobalAddressSDNode *GA,
1356       SelectionDAG &DAG) const {
1357   SDLoc dl(GA);
1358   int64_t Offset = GA->getOffset();
1359   auto PtrVT = getPointerTy(DAG.getDataLayout());
1360 
1361   // Get the thread pointer.
1362   SDValue TP = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Hexagon::UGP, PtrVT);
1363   // Generate the TLS symbol address
1364   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1365                                            HexagonII::MO_TPREL);
1366   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1367 
1368   // Address of the thread local variable is the add of thread
1369   // pointer and the offset of the variable.
1370   return DAG.getNode(ISD::ADD, dl, PtrVT, TP, Sym);
1371 }
1372 
1373 //
1374 // Lower using the general dynamic model for TLS addresses
1375 //
1376 SDValue
1377 HexagonTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1378       SelectionDAG &DAG) const {
1379   SDLoc dl(GA);
1380   int64_t Offset = GA->getOffset();
1381   auto PtrVT = getPointerTy(DAG.getDataLayout());
1382 
1383   // First generate the TLS symbol address
1384   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, PtrVT, Offset,
1385                                            HexagonII::MO_GDGOT);
1386 
1387   // Then, generate the GOT pointer
1388   SDValue GOT = LowerGLOBAL_OFFSET_TABLE(TGA, DAG);
1389 
1390   // Add the TLS symbol and the GOT pointer
1391   SDValue Sym = DAG.getNode(HexagonISD::CONST32, dl, PtrVT, TGA);
1392   SDValue Chain = DAG.getNode(ISD::ADD, dl, PtrVT, GOT, Sym);
1393 
1394   // Copy over the argument to R0
1395   SDValue InFlag;
1396   Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, Hexagon::R0, Chain, InFlag);
1397   InFlag = Chain.getValue(1);
1398 
1399   unsigned Flags = DAG.getSubtarget<HexagonSubtarget>().useLongCalls()
1400                        ? HexagonII::MO_GDPLT | HexagonII::HMOTF_ConstExtended
1401                        : HexagonII::MO_GDPLT;
1402 
1403   return GetDynamicTLSAddr(DAG, Chain, GA, InFlag, PtrVT,
1404                            Hexagon::R0, Flags);
1405 }
1406 
1407 //
1408 // Lower TLS addresses.
1409 //
1410 // For now for dynamic models, we only support the general dynamic model.
1411 //
1412 SDValue
1413 HexagonTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1414       SelectionDAG &DAG) const {
1415   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1416 
1417   switch (HTM.getTLSModel(GA->getGlobal())) {
1418     case TLSModel::GeneralDynamic:
1419     case TLSModel::LocalDynamic:
1420       return LowerToTLSGeneralDynamicModel(GA, DAG);
1421     case TLSModel::InitialExec:
1422       return LowerToTLSInitialExecModel(GA, DAG);
1423     case TLSModel::LocalExec:
1424       return LowerToTLSLocalExecModel(GA, DAG);
1425   }
1426   llvm_unreachable("Bogus TLS model");
1427 }
1428 
1429 //===----------------------------------------------------------------------===//
1430 // TargetLowering Implementation
1431 //===----------------------------------------------------------------------===//
1432 
1433 HexagonTargetLowering::HexagonTargetLowering(const TargetMachine &TM,
1434                                              const HexagonSubtarget &ST)
1435     : TargetLowering(TM), HTM(static_cast<const HexagonTargetMachine&>(TM)),
1436       Subtarget(ST) {
1437   auto &HRI = *Subtarget.getRegisterInfo();
1438 
1439   setPrefLoopAlignment(Align(16));
1440   setMinFunctionAlignment(Align(4));
1441   setPrefFunctionAlignment(Align(16));
1442   setStackPointerRegisterToSaveRestore(HRI.getStackRegister());
1443   setBooleanContents(TargetLoweringBase::UndefinedBooleanContent);
1444   setBooleanVectorContents(TargetLoweringBase::UndefinedBooleanContent);
1445 
1446   setMaxAtomicSizeInBitsSupported(64);
1447   setMinCmpXchgSizeInBits(32);
1448 
1449   if (EnableHexSDNodeSched)
1450     setSchedulingPreference(Sched::VLIW);
1451   else
1452     setSchedulingPreference(Sched::Source);
1453 
1454   // Limits for inline expansion of memcpy/memmove
1455   MaxStoresPerMemcpy = MaxStoresPerMemcpyCL;
1456   MaxStoresPerMemcpyOptSize = MaxStoresPerMemcpyOptSizeCL;
1457   MaxStoresPerMemmove = MaxStoresPerMemmoveCL;
1458   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmoveOptSizeCL;
1459   MaxStoresPerMemset = MaxStoresPerMemsetCL;
1460   MaxStoresPerMemsetOptSize = MaxStoresPerMemsetOptSizeCL;
1461 
1462   //
1463   // Set up register classes.
1464   //
1465 
1466   addRegisterClass(MVT::i1,    &Hexagon::PredRegsRegClass);
1467   addRegisterClass(MVT::v2i1,  &Hexagon::PredRegsRegClass);  // bbbbaaaa
1468   addRegisterClass(MVT::v4i1,  &Hexagon::PredRegsRegClass);  // ddccbbaa
1469   addRegisterClass(MVT::v8i1,  &Hexagon::PredRegsRegClass);  // hgfedcba
1470   addRegisterClass(MVT::i32,   &Hexagon::IntRegsRegClass);
1471   addRegisterClass(MVT::v2i16, &Hexagon::IntRegsRegClass);
1472   addRegisterClass(MVT::v4i8,  &Hexagon::IntRegsRegClass);
1473   addRegisterClass(MVT::i64,   &Hexagon::DoubleRegsRegClass);
1474   addRegisterClass(MVT::v8i8,  &Hexagon::DoubleRegsRegClass);
1475   addRegisterClass(MVT::v4i16, &Hexagon::DoubleRegsRegClass);
1476   addRegisterClass(MVT::v2i32, &Hexagon::DoubleRegsRegClass);
1477 
1478   addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1479   addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1480 
1481   //
1482   // Handling of scalar operations.
1483   //
1484   // All operations default to "legal", except:
1485   // - indexed loads and stores (pre-/post-incremented),
1486   // - ANY_EXTEND_VECTOR_INREG, ATOMIC_CMP_SWAP_WITH_SUCCESS, CONCAT_VECTORS,
1487   //   ConstantFP, DEBUGTRAP, FCEIL, FCOPYSIGN, FEXP, FEXP2, FFLOOR, FGETSIGN,
1488   //   FLOG, FLOG2, FLOG10, FMAXNUM, FMINNUM, FNEARBYINT, FRINT, FROUND, TRAP,
1489   //   FTRUNC, PREFETCH, SIGN_EXTEND_VECTOR_INREG, ZERO_EXTEND_VECTOR_INREG,
1490   // which default to "expand" for at least one type.
1491 
1492   // Misc operations.
1493   setOperationAction(ISD::ConstantFP,           MVT::f32,   Legal);
1494   setOperationAction(ISD::ConstantFP,           MVT::f64,   Legal);
1495   setOperationAction(ISD::TRAP,                 MVT::Other, Legal);
1496   setOperationAction(ISD::ConstantPool,         MVT::i32,   Custom);
1497   setOperationAction(ISD::JumpTable,            MVT::i32,   Custom);
1498   setOperationAction(ISD::BUILD_PAIR,           MVT::i64,   Expand);
1499   setOperationAction(ISD::SIGN_EXTEND_INREG,    MVT::i1,    Expand);
1500   setOperationAction(ISD::INLINEASM,            MVT::Other, Custom);
1501   setOperationAction(ISD::INLINEASM_BR,         MVT::Other, Custom);
1502   setOperationAction(ISD::PREFETCH,             MVT::Other, Custom);
1503   setOperationAction(ISD::READCYCLECOUNTER,     MVT::i64,   Custom);
1504   setOperationAction(ISD::INTRINSIC_VOID,       MVT::Other, Custom);
1505   setOperationAction(ISD::EH_RETURN,            MVT::Other, Custom);
1506   setOperationAction(ISD::GLOBAL_OFFSET_TABLE,  MVT::i32,   Custom);
1507   setOperationAction(ISD::GlobalTLSAddress,     MVT::i32,   Custom);
1508   setOperationAction(ISD::ATOMIC_FENCE,         MVT::Other, Custom);
1509 
1510   // Custom legalize GlobalAddress nodes into CONST32.
1511   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1512   setOperationAction(ISD::GlobalAddress, MVT::i8,  Custom);
1513   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
1514 
1515   // Hexagon needs to optimize cases with negative constants.
1516   setOperationAction(ISD::SETCC, MVT::i8,    Custom);
1517   setOperationAction(ISD::SETCC, MVT::i16,   Custom);
1518   setOperationAction(ISD::SETCC, MVT::v4i8,  Custom);
1519   setOperationAction(ISD::SETCC, MVT::v2i16, Custom);
1520 
1521   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1522   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1523   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
1524   setOperationAction(ISD::VAARG,   MVT::Other, Expand);
1525   if (Subtarget.isEnvironmentMusl())
1526     setOperationAction(ISD::VACOPY, MVT::Other, Custom);
1527   else
1528     setOperationAction(ISD::VACOPY,  MVT::Other, Expand);
1529 
1530   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1531   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1532   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1533 
1534   if (EmitJumpTables)
1535     setMinimumJumpTableEntries(MinimumJumpTables);
1536   else
1537     setMinimumJumpTableEntries(std::numeric_limits<unsigned>::max());
1538   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1539 
1540   for (unsigned LegalIntOp :
1541        {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) {
1542     setOperationAction(LegalIntOp, MVT::i32, Legal);
1543     setOperationAction(LegalIntOp, MVT::i64, Legal);
1544   }
1545 
1546   // Hexagon has A4_addp_c and A4_subp_c that take and generate a carry bit,
1547   // but they only operate on i64.
1548   for (MVT VT : MVT::integer_valuetypes()) {
1549     setOperationAction(ISD::UADDO,    VT, Custom);
1550     setOperationAction(ISD::USUBO,    VT, Custom);
1551     setOperationAction(ISD::SADDO,    VT, Expand);
1552     setOperationAction(ISD::SSUBO,    VT, Expand);
1553     setOperationAction(ISD::ADDCARRY, VT, Expand);
1554     setOperationAction(ISD::SUBCARRY, VT, Expand);
1555   }
1556   setOperationAction(ISD::ADDCARRY, MVT::i64, Custom);
1557   setOperationAction(ISD::SUBCARRY, MVT::i64, Custom);
1558 
1559   setOperationAction(ISD::CTLZ, MVT::i8,  Promote);
1560   setOperationAction(ISD::CTLZ, MVT::i16, Promote);
1561   setOperationAction(ISD::CTTZ, MVT::i8,  Promote);
1562   setOperationAction(ISD::CTTZ, MVT::i16, Promote);
1563 
1564   // Popcount can count # of 1s in i64 but returns i32.
1565   setOperationAction(ISD::CTPOP, MVT::i8,  Promote);
1566   setOperationAction(ISD::CTPOP, MVT::i16, Promote);
1567   setOperationAction(ISD::CTPOP, MVT::i32, Promote);
1568   setOperationAction(ISD::CTPOP, MVT::i64, Legal);
1569 
1570   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1571   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
1572   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
1573   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
1574 
1575   setOperationAction(ISD::FSHL, MVT::i32, Legal);
1576   setOperationAction(ISD::FSHL, MVT::i64, Legal);
1577   setOperationAction(ISD::FSHR, MVT::i32, Legal);
1578   setOperationAction(ISD::FSHR, MVT::i64, Legal);
1579 
1580   for (unsigned IntExpOp :
1581        {ISD::SDIV,      ISD::UDIV,      ISD::SREM,      ISD::UREM,
1582         ISD::SDIVREM,   ISD::UDIVREM,   ISD::ROTL,      ISD::ROTR,
1583         ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
1584         ISD::SMUL_LOHI, ISD::UMUL_LOHI}) {
1585     for (MVT VT : MVT::integer_valuetypes())
1586       setOperationAction(IntExpOp, VT, Expand);
1587   }
1588 
1589   for (unsigned FPExpOp :
1590        {ISD::FDIV, ISD::FREM, ISD::FSQRT, ISD::FSIN, ISD::FCOS, ISD::FSINCOS,
1591         ISD::FPOW, ISD::FCOPYSIGN}) {
1592     for (MVT VT : MVT::fp_valuetypes())
1593       setOperationAction(FPExpOp, VT, Expand);
1594   }
1595 
1596   // No extending loads from i32.
1597   for (MVT VT : MVT::integer_valuetypes()) {
1598     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
1599     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
1600     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i32, Expand);
1601   }
1602   // Turn FP truncstore into trunc + store.
1603   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1604   // Turn FP extload into load/fpextend.
1605   for (MVT VT : MVT::fp_valuetypes())
1606     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1607 
1608   // Expand BR_CC and SELECT_CC for all integer and fp types.
1609   for (MVT VT : MVT::integer_valuetypes()) {
1610     setOperationAction(ISD::BR_CC,     VT, Expand);
1611     setOperationAction(ISD::SELECT_CC, VT, Expand);
1612   }
1613   for (MVT VT : MVT::fp_valuetypes()) {
1614     setOperationAction(ISD::BR_CC,     VT, Expand);
1615     setOperationAction(ISD::SELECT_CC, VT, Expand);
1616   }
1617   setOperationAction(ISD::BR_CC, MVT::Other, Expand);
1618 
1619   //
1620   // Handling of vector operations.
1621   //
1622 
1623   // Set the action for vector operations to "expand", then override it with
1624   // either "custom" or "legal" for specific cases.
1625   static const unsigned VectExpOps[] = {
1626     // Integer arithmetic:
1627     ISD::ADD,     ISD::SUB,     ISD::MUL,     ISD::SDIV,      ISD::UDIV,
1628     ISD::SREM,    ISD::UREM,    ISD::SDIVREM, ISD::UDIVREM,   ISD::SADDO,
1629     ISD::UADDO,   ISD::SSUBO,   ISD::USUBO,   ISD::SMUL_LOHI, ISD::UMUL_LOHI,
1630     // Logical/bit:
1631     ISD::AND,     ISD::OR,      ISD::XOR,     ISD::ROTL,    ISD::ROTR,
1632     ISD::CTPOP,   ISD::CTLZ,    ISD::CTTZ,
1633     // Floating point arithmetic/math functions:
1634     ISD::FADD,    ISD::FSUB,    ISD::FMUL,    ISD::FMA,     ISD::FDIV,
1635     ISD::FREM,    ISD::FNEG,    ISD::FABS,    ISD::FSQRT,   ISD::FSIN,
1636     ISD::FCOS,    ISD::FPOW,    ISD::FLOG,    ISD::FLOG2,
1637     ISD::FLOG10,  ISD::FEXP,    ISD::FEXP2,   ISD::FCEIL,   ISD::FTRUNC,
1638     ISD::FRINT,   ISD::FNEARBYINT,            ISD::FROUND,  ISD::FFLOOR,
1639     ISD::FMINNUM, ISD::FMAXNUM, ISD::FSINCOS,
1640     // Misc:
1641     ISD::BR_CC,   ISD::SELECT_CC,             ISD::ConstantPool,
1642     // Vector:
1643     ISD::BUILD_VECTOR,          ISD::SCALAR_TO_VECTOR,
1644     ISD::EXTRACT_VECTOR_ELT,    ISD::INSERT_VECTOR_ELT,
1645     ISD::EXTRACT_SUBVECTOR,     ISD::INSERT_SUBVECTOR,
1646     ISD::CONCAT_VECTORS,        ISD::VECTOR_SHUFFLE,
1647     ISD::SPLAT_VECTOR,
1648   };
1649 
1650   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1651     for (unsigned VectExpOp : VectExpOps)
1652       setOperationAction(VectExpOp, VT, Expand);
1653 
1654     // Expand all extending loads and truncating stores:
1655     for (MVT TargetVT : MVT::fixedlen_vector_valuetypes()) {
1656       if (TargetVT == VT)
1657         continue;
1658       setLoadExtAction(ISD::EXTLOAD, TargetVT, VT, Expand);
1659       setLoadExtAction(ISD::ZEXTLOAD, TargetVT, VT, Expand);
1660       setLoadExtAction(ISD::SEXTLOAD, TargetVT, VT, Expand);
1661       setTruncStoreAction(VT, TargetVT, Expand);
1662     }
1663 
1664     // Normalize all inputs to SELECT to be vectors of i32.
1665     if (VT.getVectorElementType() != MVT::i32) {
1666       MVT VT32 = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
1667       setOperationAction(ISD::SELECT, VT, Promote);
1668       AddPromotedToType(ISD::SELECT, VT, VT32);
1669     }
1670     setOperationAction(ISD::SRA, VT, Custom);
1671     setOperationAction(ISD::SHL, VT, Custom);
1672     setOperationAction(ISD::SRL, VT, Custom);
1673   }
1674 
1675   // Extending loads from (native) vectors of i8 into (native) vectors of i16
1676   // are legal.
1677   setLoadExtAction(ISD::EXTLOAD,  MVT::v2i16, MVT::v2i8, Legal);
1678   setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1679   setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, MVT::v2i8, Legal);
1680   setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Legal);
1681   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1682   setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Legal);
1683 
1684   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1685   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1686   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1687 
1688   // Types natively supported:
1689   for (MVT NativeVT : {MVT::v8i1, MVT::v4i1, MVT::v2i1, MVT::v4i8,
1690                        MVT::v8i8, MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1691     setOperationAction(ISD::BUILD_VECTOR,       NativeVT, Custom);
1692     setOperationAction(ISD::EXTRACT_VECTOR_ELT, NativeVT, Custom);
1693     setOperationAction(ISD::INSERT_VECTOR_ELT,  NativeVT, Custom);
1694     setOperationAction(ISD::EXTRACT_SUBVECTOR,  NativeVT, Custom);
1695     setOperationAction(ISD::INSERT_SUBVECTOR,   NativeVT, Custom);
1696     setOperationAction(ISD::CONCAT_VECTORS,     NativeVT, Custom);
1697 
1698     setOperationAction(ISD::ADD, NativeVT, Legal);
1699     setOperationAction(ISD::SUB, NativeVT, Legal);
1700     setOperationAction(ISD::MUL, NativeVT, Legal);
1701     setOperationAction(ISD::AND, NativeVT, Legal);
1702     setOperationAction(ISD::OR,  NativeVT, Legal);
1703     setOperationAction(ISD::XOR, NativeVT, Legal);
1704 
1705     if (NativeVT.getVectorElementType() != MVT::i1)
1706       setOperationAction(ISD::SPLAT_VECTOR, NativeVT, Legal);
1707   }
1708 
1709   for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32}) {
1710     setOperationAction(ISD::SMIN, VT, Legal);
1711     setOperationAction(ISD::SMAX, VT, Legal);
1712     setOperationAction(ISD::UMIN, VT, Legal);
1713     setOperationAction(ISD::UMAX, VT, Legal);
1714   }
1715 
1716   // Custom lower unaligned loads.
1717   // Also, for both loads and stores, verify the alignment of the address
1718   // in case it is a compile-time constant. This is a usability feature to
1719   // provide a meaningful error message to users.
1720   for (MVT VT : {MVT::i16, MVT::i32, MVT::v4i8, MVT::i64, MVT::v8i8,
1721                  MVT::v2i16, MVT::v4i16, MVT::v2i32}) {
1722     setOperationAction(ISD::LOAD,  VT, Custom);
1723     setOperationAction(ISD::STORE, VT, Custom);
1724   }
1725 
1726   // Custom-lower load/stores of boolean vectors.
1727   for (MVT VT : {MVT::v2i1, MVT::v4i1, MVT::v8i1}) {
1728     setOperationAction(ISD::LOAD,  VT, Custom);
1729     setOperationAction(ISD::STORE, VT, Custom);
1730   }
1731 
1732   for (MVT VT : {MVT::v2i16, MVT::v4i8, MVT::v8i8, MVT::v2i32, MVT::v4i16,
1733                  MVT::v2i32}) {
1734     setCondCodeAction(ISD::SETNE,  VT, Expand);
1735     setCondCodeAction(ISD::SETLE,  VT, Expand);
1736     setCondCodeAction(ISD::SETGE,  VT, Expand);
1737     setCondCodeAction(ISD::SETLT,  VT, Expand);
1738     setCondCodeAction(ISD::SETULE, VT, Expand);
1739     setCondCodeAction(ISD::SETUGE, VT, Expand);
1740     setCondCodeAction(ISD::SETULT, VT, Expand);
1741   }
1742 
1743   // Custom-lower bitcasts from i8 to v8i1.
1744   setOperationAction(ISD::BITCAST,        MVT::i8,    Custom);
1745   setOperationAction(ISD::SETCC,          MVT::v2i16, Custom);
1746   setOperationAction(ISD::VSELECT,        MVT::v4i8,  Custom);
1747   setOperationAction(ISD::VSELECT,        MVT::v2i16, Custom);
1748   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i8,  Custom);
1749   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
1750   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8,  Custom);
1751 
1752   // V5+.
1753   setOperationAction(ISD::FMA,  MVT::f64, Expand);
1754   setOperationAction(ISD::FADD, MVT::f64, Expand);
1755   setOperationAction(ISD::FSUB, MVT::f64, Expand);
1756   setOperationAction(ISD::FMUL, MVT::f64, Expand);
1757 
1758   setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1759   setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1760 
1761   setOperationAction(ISD::FP_TO_UINT, MVT::i1,  Promote);
1762   setOperationAction(ISD::FP_TO_UINT, MVT::i8,  Promote);
1763   setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1764   setOperationAction(ISD::FP_TO_SINT, MVT::i1,  Promote);
1765   setOperationAction(ISD::FP_TO_SINT, MVT::i8,  Promote);
1766   setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1767   setOperationAction(ISD::UINT_TO_FP, MVT::i1,  Promote);
1768   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Promote);
1769   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1770   setOperationAction(ISD::SINT_TO_FP, MVT::i1,  Promote);
1771   setOperationAction(ISD::SINT_TO_FP, MVT::i8,  Promote);
1772   setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1773 
1774   // Special handling for half-precision floating point conversions.
1775   // Lower half float conversions into library calls.
1776   setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1777   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1778   setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1779   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1780 
1781   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
1782   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
1783   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1784   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1785 
1786   // Handling of indexed loads/stores: default is "expand".
1787   //
1788   for (MVT VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64, MVT::f32, MVT::f64,
1789                  MVT::v2i16, MVT::v2i32, MVT::v4i8, MVT::v4i16, MVT::v8i8}) {
1790     setIndexedLoadAction(ISD::POST_INC, VT, Legal);
1791     setIndexedStoreAction(ISD::POST_INC, VT, Legal);
1792   }
1793 
1794   // Subtarget-specific operation actions.
1795   //
1796   if (Subtarget.hasV60Ops()) {
1797     setOperationAction(ISD::ROTL, MVT::i32, Legal);
1798     setOperationAction(ISD::ROTL, MVT::i64, Legal);
1799     setOperationAction(ISD::ROTR, MVT::i32, Legal);
1800     setOperationAction(ISD::ROTR, MVT::i64, Legal);
1801   }
1802   if (Subtarget.hasV66Ops()) {
1803     setOperationAction(ISD::FADD, MVT::f64, Legal);
1804     setOperationAction(ISD::FSUB, MVT::f64, Legal);
1805   }
1806   if (Subtarget.hasV67Ops()) {
1807     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1808     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1809     setOperationAction(ISD::FMUL,    MVT::f64, Legal);
1810   }
1811 
1812   setTargetDAGCombine(ISD::VSELECT);
1813 
1814   if (Subtarget.useHVXOps())
1815     initializeHVXLowering();
1816 
1817   computeRegisterProperties(&HRI);
1818 
1819   //
1820   // Library calls for unsupported operations
1821   //
1822   bool FastMath  = EnableFastMath;
1823 
1824   setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1825   setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1826   setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1827   setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1828   setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1829   setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1830   setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1831   setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1832 
1833   setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1834   setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1835   setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1836   setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1837   setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1838   setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1839 
1840   // This is the only fast library function for sqrtd.
1841   if (FastMath)
1842     setLibcallName(RTLIB::SQRT_F64, "__hexagon_fast2_sqrtdf2");
1843 
1844   // Prefix is: nothing  for "slow-math",
1845   //            "fast2_" for V5+ fast-math double-precision
1846   // (actually, keep fast-math and fast-math2 separate for now)
1847   if (FastMath) {
1848     setLibcallName(RTLIB::ADD_F64, "__hexagon_fast_adddf3");
1849     setLibcallName(RTLIB::SUB_F64, "__hexagon_fast_subdf3");
1850     setLibcallName(RTLIB::MUL_F64, "__hexagon_fast_muldf3");
1851     setLibcallName(RTLIB::DIV_F64, "__hexagon_fast_divdf3");
1852     setLibcallName(RTLIB::DIV_F32, "__hexagon_fast_divsf3");
1853   } else {
1854     setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1855     setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1856     setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1857     setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1858     setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1859   }
1860 
1861   if (FastMath)
1862     setLibcallName(RTLIB::SQRT_F32, "__hexagon_fast2_sqrtf");
1863   else
1864     setLibcallName(RTLIB::SQRT_F32, "__hexagon_sqrtf");
1865 
1866   // Routines to handle fp16 storage type.
1867   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1868   setLibcallName(RTLIB::FPROUND_F64_F16, "__truncdfhf2");
1869   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1870 
1871   // These cause problems when the shift amount is non-constant.
1872   setLibcallName(RTLIB::SHL_I128, nullptr);
1873   setLibcallName(RTLIB::SRL_I128, nullptr);
1874   setLibcallName(RTLIB::SRA_I128, nullptr);
1875 }
1876 
1877 const char* HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1878   switch ((HexagonISD::NodeType)Opcode) {
1879   case HexagonISD::ADDC:          return "HexagonISD::ADDC";
1880   case HexagonISD::SUBC:          return "HexagonISD::SUBC";
1881   case HexagonISD::ALLOCA:        return "HexagonISD::ALLOCA";
1882   case HexagonISD::AT_GOT:        return "HexagonISD::AT_GOT";
1883   case HexagonISD::AT_PCREL:      return "HexagonISD::AT_PCREL";
1884   case HexagonISD::BARRIER:       return "HexagonISD::BARRIER";
1885   case HexagonISD::CALL:          return "HexagonISD::CALL";
1886   case HexagonISD::CALLnr:        return "HexagonISD::CALLnr";
1887   case HexagonISD::CALLR:         return "HexagonISD::CALLR";
1888   case HexagonISD::COMBINE:       return "HexagonISD::COMBINE";
1889   case HexagonISD::CONST32_GP:    return "HexagonISD::CONST32_GP";
1890   case HexagonISD::CONST32:       return "HexagonISD::CONST32";
1891   case HexagonISD::CP:            return "HexagonISD::CP";
1892   case HexagonISD::DCFETCH:       return "HexagonISD::DCFETCH";
1893   case HexagonISD::EH_RETURN:     return "HexagonISD::EH_RETURN";
1894   case HexagonISD::TSTBIT:        return "HexagonISD::TSTBIT";
1895   case HexagonISD::EXTRACTU:      return "HexagonISD::EXTRACTU";
1896   case HexagonISD::INSERT:        return "HexagonISD::INSERT";
1897   case HexagonISD::JT:            return "HexagonISD::JT";
1898   case HexagonISD::RET_FLAG:      return "HexagonISD::RET_FLAG";
1899   case HexagonISD::TC_RETURN:     return "HexagonISD::TC_RETURN";
1900   case HexagonISD::VASL:          return "HexagonISD::VASL";
1901   case HexagonISD::VASR:          return "HexagonISD::VASR";
1902   case HexagonISD::VLSR:          return "HexagonISD::VLSR";
1903   case HexagonISD::VEXTRACTW:     return "HexagonISD::VEXTRACTW";
1904   case HexagonISD::VINSERTW0:     return "HexagonISD::VINSERTW0";
1905   case HexagonISD::VROR:          return "HexagonISD::VROR";
1906   case HexagonISD::READCYCLE:     return "HexagonISD::READCYCLE";
1907   case HexagonISD::PTRUE:         return "HexagonISD::PTRUE";
1908   case HexagonISD::PFALSE:        return "HexagonISD::PFALSE";
1909   case HexagonISD::D2P:           return "HexagonISD::D2P";
1910   case HexagonISD::P2D:           return "HexagonISD::P2D";
1911   case HexagonISD::V2Q:           return "HexagonISD::V2Q";
1912   case HexagonISD::Q2V:           return "HexagonISD::Q2V";
1913   case HexagonISD::QCAT:          return "HexagonISD::QCAT";
1914   case HexagonISD::QTRUE:         return "HexagonISD::QTRUE";
1915   case HexagonISD::QFALSE:        return "HexagonISD::QFALSE";
1916   case HexagonISD::TYPECAST:      return "HexagonISD::TYPECAST";
1917   case HexagonISD::VALIGN:        return "HexagonISD::VALIGN";
1918   case HexagonISD::VALIGNADDR:    return "HexagonISD::VALIGNADDR";
1919   case HexagonISD::VPACKL:        return "HexagonISD::VPACKL";
1920   case HexagonISD::VUNPACK:       return "HexagonISD::VUNPACK";
1921   case HexagonISD::VUNPACKU:      return "HexagonISD::VUNPACKU";
1922   case HexagonISD::ISEL:          return "HexagonISD::ISEL";
1923   case HexagonISD::OP_END:        break;
1924   }
1925   return nullptr;
1926 }
1927 
1928 bool
1929 HexagonTargetLowering::validateConstPtrAlignment(SDValue Ptr, Align NeedAlign,
1930       const SDLoc &dl, SelectionDAG &DAG) const {
1931   auto *CA = dyn_cast<ConstantSDNode>(Ptr);
1932   if (!CA)
1933     return true;
1934   unsigned Addr = CA->getZExtValue();
1935   Align HaveAlign =
1936       Addr != 0 ? Align(1ull << countTrailingZeros(Addr)) : NeedAlign;
1937   if (HaveAlign >= NeedAlign)
1938     return true;
1939 
1940   static int DK_MisalignedTrap = llvm::getNextAvailablePluginDiagnosticKind();
1941 
1942   struct DiagnosticInfoMisalignedTrap : public DiagnosticInfo {
1943     DiagnosticInfoMisalignedTrap(StringRef M)
1944       : DiagnosticInfo(DK_MisalignedTrap, DS_Remark), Msg(M) {}
1945     void print(DiagnosticPrinter &DP) const override {
1946       DP << Msg;
1947     }
1948     static bool classof(const DiagnosticInfo *DI) {
1949       return DI->getKind() == DK_MisalignedTrap;
1950     }
1951     StringRef Msg;
1952   };
1953 
1954   std::string ErrMsg;
1955   raw_string_ostream O(ErrMsg);
1956   O << "Misaligned constant address: " << format_hex(Addr, 10)
1957     << " has alignment " << HaveAlign.value()
1958     << ", but the memory access requires " << NeedAlign.value();
1959   if (DebugLoc DL = dl.getDebugLoc())
1960     DL.print(O << ", at ");
1961   O << ". The instruction has been replaced with a trap.";
1962 
1963   DAG.getContext()->diagnose(DiagnosticInfoMisalignedTrap(O.str()));
1964   return false;
1965 }
1966 
1967 SDValue
1968 HexagonTargetLowering::replaceMemWithUndef(SDValue Op, SelectionDAG &DAG)
1969       const {
1970   const SDLoc &dl(Op);
1971   auto *LS = cast<LSBaseSDNode>(Op.getNode());
1972   assert(!LS->isIndexed() && "Not expecting indexed ops on constant address");
1973 
1974   SDValue Chain = LS->getChain();
1975   SDValue Trap = DAG.getNode(ISD::TRAP, dl, MVT::Other, Chain);
1976   if (LS->getOpcode() == ISD::LOAD)
1977     return DAG.getMergeValues({DAG.getUNDEF(ty(Op)), Trap}, dl);
1978   return Trap;
1979 }
1980 
1981 // Bit-reverse Load Intrinsic: Check if the instruction is a bit reverse load
1982 // intrinsic.
1983 static bool isBrevLdIntrinsic(const Value *Inst) {
1984   unsigned ID = cast<IntrinsicInst>(Inst)->getIntrinsicID();
1985   return (ID == Intrinsic::hexagon_L2_loadrd_pbr ||
1986           ID == Intrinsic::hexagon_L2_loadri_pbr ||
1987           ID == Intrinsic::hexagon_L2_loadrh_pbr ||
1988           ID == Intrinsic::hexagon_L2_loadruh_pbr ||
1989           ID == Intrinsic::hexagon_L2_loadrb_pbr ||
1990           ID == Intrinsic::hexagon_L2_loadrub_pbr);
1991 }
1992 
1993 // Bit-reverse Load Intrinsic :Crawl up and figure out the object from previous
1994 // instruction. So far we only handle bitcast, extract value and bit reverse
1995 // load intrinsic instructions. Should we handle CGEP ?
1996 static Value *getBrevLdObject(Value *V) {
1997   if (Operator::getOpcode(V) == Instruction::ExtractValue ||
1998       Operator::getOpcode(V) == Instruction::BitCast)
1999     V = cast<Operator>(V)->getOperand(0);
2000   else if (isa<IntrinsicInst>(V) && isBrevLdIntrinsic(V))
2001     V = cast<Instruction>(V)->getOperand(0);
2002   return V;
2003 }
2004 
2005 // Bit-reverse Load Intrinsic: For a PHI Node return either an incoming edge or
2006 // a back edge. If the back edge comes from the intrinsic itself, the incoming
2007 // edge is returned.
2008 static Value *returnEdge(const PHINode *PN, Value *IntrBaseVal) {
2009   const BasicBlock *Parent = PN->getParent();
2010   int Idx = -1;
2011   for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
2012     BasicBlock *Blk = PN->getIncomingBlock(i);
2013     // Determine if the back edge is originated from intrinsic.
2014     if (Blk == Parent) {
2015       Value *BackEdgeVal = PN->getIncomingValue(i);
2016       Value *BaseVal;
2017       // Loop over till we return the same Value or we hit the IntrBaseVal.
2018       do {
2019         BaseVal = BackEdgeVal;
2020         BackEdgeVal = getBrevLdObject(BackEdgeVal);
2021       } while ((BaseVal != BackEdgeVal) && (IntrBaseVal != BackEdgeVal));
2022       // If the getBrevLdObject returns IntrBaseVal, we should return the
2023       // incoming edge.
2024       if (IntrBaseVal == BackEdgeVal)
2025         continue;
2026       Idx = i;
2027       break;
2028     } else // Set the node to incoming edge.
2029       Idx = i;
2030   }
2031   assert(Idx >= 0 && "Unexpected index to incoming argument in PHI");
2032   return PN->getIncomingValue(Idx);
2033 }
2034 
2035 // Bit-reverse Load Intrinsic: Figure out the underlying object the base
2036 // pointer points to, for the bit-reverse load intrinsic. Setting this to
2037 // memoperand might help alias analysis to figure out the dependencies.
2038 static Value *getUnderLyingObjectForBrevLdIntr(Value *V) {
2039   Value *IntrBaseVal = V;
2040   Value *BaseVal;
2041   // Loop over till we return the same Value, implies we either figure out
2042   // the object or we hit a PHI
2043   do {
2044     BaseVal = V;
2045     V = getBrevLdObject(V);
2046   } while (BaseVal != V);
2047 
2048   // Identify the object from PHINode.
2049   if (const PHINode *PN = dyn_cast<PHINode>(V))
2050     return returnEdge(PN, IntrBaseVal);
2051   // For non PHI nodes, the object is the last value returned by getBrevLdObject
2052   else
2053     return V;
2054 }
2055 
2056 /// Given an intrinsic, checks if on the target the intrinsic will need to map
2057 /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
2058 /// true and store the intrinsic information into the IntrinsicInfo that was
2059 /// passed to the function.
2060 bool HexagonTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
2061                                                const CallInst &I,
2062                                                MachineFunction &MF,
2063                                                unsigned Intrinsic) const {
2064   switch (Intrinsic) {
2065   case Intrinsic::hexagon_L2_loadrd_pbr:
2066   case Intrinsic::hexagon_L2_loadri_pbr:
2067   case Intrinsic::hexagon_L2_loadrh_pbr:
2068   case Intrinsic::hexagon_L2_loadruh_pbr:
2069   case Intrinsic::hexagon_L2_loadrb_pbr:
2070   case Intrinsic::hexagon_L2_loadrub_pbr: {
2071     Info.opc = ISD::INTRINSIC_W_CHAIN;
2072     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
2073     auto &Cont = I.getCalledFunction()->getParent()->getContext();
2074     // The intrinsic function call is of the form { ElTy, i8* }
2075     // @llvm.hexagon.L2.loadXX.pbr(i8*, i32). The pointer and memory access type
2076     // should be derived from ElTy.
2077     Type *ElTy = I.getCalledFunction()->getReturnType()->getStructElementType(0);
2078     Info.memVT = MVT::getVT(ElTy);
2079     llvm::Value *BasePtrVal = I.getOperand(0);
2080     Info.ptrVal = getUnderLyingObjectForBrevLdIntr(BasePtrVal);
2081     // The offset value comes through Modifier register. For now, assume the
2082     // offset is 0.
2083     Info.offset = 0;
2084     Info.align = DL.getABITypeAlign(Info.memVT.getTypeForEVT(Cont));
2085     Info.flags = MachineMemOperand::MOLoad;
2086     return true;
2087   }
2088   case Intrinsic::hexagon_V6_vgathermw:
2089   case Intrinsic::hexagon_V6_vgathermw_128B:
2090   case Intrinsic::hexagon_V6_vgathermh:
2091   case Intrinsic::hexagon_V6_vgathermh_128B:
2092   case Intrinsic::hexagon_V6_vgathermhw:
2093   case Intrinsic::hexagon_V6_vgathermhw_128B:
2094   case Intrinsic::hexagon_V6_vgathermwq:
2095   case Intrinsic::hexagon_V6_vgathermwq_128B:
2096   case Intrinsic::hexagon_V6_vgathermhq:
2097   case Intrinsic::hexagon_V6_vgathermhq_128B:
2098   case Intrinsic::hexagon_V6_vgathermhwq:
2099   case Intrinsic::hexagon_V6_vgathermhwq_128B: {
2100     const Module &M = *I.getParent()->getParent()->getParent();
2101     Info.opc = ISD::INTRINSIC_W_CHAIN;
2102     Type *VecTy = I.getArgOperand(1)->getType();
2103     Info.memVT = MVT::getVT(VecTy);
2104     Info.ptrVal = I.getArgOperand(0);
2105     Info.offset = 0;
2106     Info.align =
2107         MaybeAlign(M.getDataLayout().getTypeAllocSizeInBits(VecTy) / 8);
2108     Info.flags = MachineMemOperand::MOLoad |
2109                  MachineMemOperand::MOStore |
2110                  MachineMemOperand::MOVolatile;
2111     return true;
2112   }
2113   default:
2114     break;
2115   }
2116   return false;
2117 }
2118 
2119 bool HexagonTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
2120   return X.getValueType().isScalarInteger(); // 'tstbit'
2121 }
2122 
2123 bool HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
2124   return isTruncateFree(EVT::getEVT(Ty1), EVT::getEVT(Ty2));
2125 }
2126 
2127 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
2128   if (!VT1.isSimple() || !VT2.isSimple())
2129     return false;
2130   return VT1.getSimpleVT() == MVT::i64 && VT2.getSimpleVT() == MVT::i32;
2131 }
2132 
2133 bool HexagonTargetLowering::isFMAFasterThanFMulAndFAdd(
2134     const MachineFunction &MF, EVT VT) const {
2135   return isOperationLegalOrCustom(ISD::FMA, VT);
2136 }
2137 
2138 // Should we expand the build vector with shuffles?
2139 bool HexagonTargetLowering::shouldExpandBuildVectorWithShuffles(EVT VT,
2140       unsigned DefinedValues) const {
2141   return false;
2142 }
2143 
2144 bool HexagonTargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask,
2145                                                EVT VT) const {
2146   return true;
2147 }
2148 
2149 TargetLoweringBase::LegalizeTypeAction
2150 HexagonTargetLowering::getPreferredVectorAction(MVT VT) const {
2151   unsigned VecLen = VT.getVectorMinNumElements();
2152   MVT ElemTy = VT.getVectorElementType();
2153 
2154   if (VecLen == 1 || VT.isScalableVector())
2155     return TargetLoweringBase::TypeScalarizeVector;
2156 
2157   if (Subtarget.useHVXOps()) {
2158     unsigned Action = getPreferredHvxVectorAction(VT);
2159     if (Action != ~0u)
2160       return static_cast<TargetLoweringBase::LegalizeTypeAction>(Action);
2161   }
2162 
2163   // Always widen (remaining) vectors of i1.
2164   if (ElemTy == MVT::i1)
2165     return TargetLoweringBase::TypeWidenVector;
2166   // Widen non-power-of-2 vectors. Such types cannot be split right now,
2167   // and computeRegisterProperties will override "split" with "widen",
2168   // which can cause other issues.
2169   if (!isPowerOf2_32(VecLen))
2170     return TargetLoweringBase::TypeWidenVector;
2171 
2172   return TargetLoweringBase::TypeSplitVector;
2173 }
2174 
2175 std::pair<SDValue, int>
2176 HexagonTargetLowering::getBaseAndOffset(SDValue Addr) const {
2177   if (Addr.getOpcode() == ISD::ADD) {
2178     SDValue Op1 = Addr.getOperand(1);
2179     if (auto *CN = dyn_cast<const ConstantSDNode>(Op1.getNode()))
2180       return { Addr.getOperand(0), CN->getSExtValue() };
2181   }
2182   return { Addr, 0 };
2183 }
2184 
2185 // Lower a vector shuffle (V1, V2, V3).  V1 and V2 are the two vectors
2186 // to select data from, V3 is the permutation.
2187 SDValue
2188 HexagonTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG)
2189       const {
2190   const auto *SVN = cast<ShuffleVectorSDNode>(Op);
2191   ArrayRef<int> AM = SVN->getMask();
2192   assert(AM.size() <= 8 && "Unexpected shuffle mask");
2193   unsigned VecLen = AM.size();
2194 
2195   MVT VecTy = ty(Op);
2196   assert(!Subtarget.isHVXVectorType(VecTy, true) &&
2197          "HVX shuffles should be legal");
2198   assert(VecTy.getSizeInBits() <= 64 && "Unexpected vector length");
2199 
2200   SDValue Op0 = Op.getOperand(0);
2201   SDValue Op1 = Op.getOperand(1);
2202   const SDLoc &dl(Op);
2203 
2204   // If the inputs are not the same as the output, bail. This is not an
2205   // error situation, but complicates the handling and the default expansion
2206   // (into BUILD_VECTOR) should be adequate.
2207   if (ty(Op0) != VecTy || ty(Op1) != VecTy)
2208     return SDValue();
2209 
2210   // Normalize the mask so that the first non-negative index comes from
2211   // the first operand.
2212   SmallVector<int,8> Mask(AM.begin(), AM.end());
2213   unsigned F = llvm::find_if(AM, [](int M) { return M >= 0; }) - AM.data();
2214   if (F == AM.size())
2215     return DAG.getUNDEF(VecTy);
2216   if (AM[F] >= int(VecLen)) {
2217     ShuffleVectorSDNode::commuteMask(Mask);
2218     std::swap(Op0, Op1);
2219   }
2220 
2221   // Express the shuffle mask in terms of bytes.
2222   SmallVector<int,8> ByteMask;
2223   unsigned ElemBytes = VecTy.getVectorElementType().getSizeInBits() / 8;
2224   for (int M : Mask) {
2225     if (M < 0) {
2226       for (unsigned j = 0; j != ElemBytes; ++j)
2227         ByteMask.push_back(-1);
2228     } else {
2229       for (unsigned j = 0; j != ElemBytes; ++j)
2230         ByteMask.push_back(M*ElemBytes + j);
2231     }
2232   }
2233   assert(ByteMask.size() <= 8);
2234 
2235   // All non-undef (non-negative) indexes are well within [0..127], so they
2236   // fit in a single byte. Build two 64-bit words:
2237   // - MaskIdx where each byte is the corresponding index (for non-negative
2238   //   indexes), and 0xFF for negative indexes, and
2239   // - MaskUnd that has 0xFF for each negative index.
2240   uint64_t MaskIdx = 0;
2241   uint64_t MaskUnd = 0;
2242   for (unsigned i = 0, e = ByteMask.size(); i != e; ++i) {
2243     unsigned S = 8*i;
2244     uint64_t M = ByteMask[i] & 0xFF;
2245     if (M == 0xFF)
2246       MaskUnd |= M << S;
2247     MaskIdx |= M << S;
2248   }
2249 
2250   if (ByteMask.size() == 4) {
2251     // Identity.
2252     if (MaskIdx == (0x03020100 | MaskUnd))
2253       return Op0;
2254     // Byte swap.
2255     if (MaskIdx == (0x00010203 | MaskUnd)) {
2256       SDValue T0 = DAG.getBitcast(MVT::i32, Op0);
2257       SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i32, T0);
2258       return DAG.getBitcast(VecTy, T1);
2259     }
2260 
2261     // Byte packs.
2262     SDValue Concat10 = DAG.getNode(HexagonISD::COMBINE, dl,
2263                                    typeJoin({ty(Op1), ty(Op0)}), {Op1, Op0});
2264     if (MaskIdx == (0x06040200 | MaskUnd))
2265       return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat10}, DAG);
2266     if (MaskIdx == (0x07050301 | MaskUnd))
2267       return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat10}, DAG);
2268 
2269     SDValue Concat01 = DAG.getNode(HexagonISD::COMBINE, dl,
2270                                    typeJoin({ty(Op0), ty(Op1)}), {Op0, Op1});
2271     if (MaskIdx == (0x02000604 | MaskUnd))
2272       return getInstr(Hexagon::S2_vtrunehb, dl, VecTy, {Concat01}, DAG);
2273     if (MaskIdx == (0x03010705 | MaskUnd))
2274       return getInstr(Hexagon::S2_vtrunohb, dl, VecTy, {Concat01}, DAG);
2275   }
2276 
2277   if (ByteMask.size() == 8) {
2278     // Identity.
2279     if (MaskIdx == (0x0706050403020100ull | MaskUnd))
2280       return Op0;
2281     // Byte swap.
2282     if (MaskIdx == (0x0001020304050607ull | MaskUnd)) {
2283       SDValue T0 = DAG.getBitcast(MVT::i64, Op0);
2284       SDValue T1 = DAG.getNode(ISD::BSWAP, dl, MVT::i64, T0);
2285       return DAG.getBitcast(VecTy, T1);
2286     }
2287 
2288     // Halfword picks.
2289     if (MaskIdx == (0x0d0c050409080100ull | MaskUnd))
2290       return getInstr(Hexagon::S2_shuffeh, dl, VecTy, {Op1, Op0}, DAG);
2291     if (MaskIdx == (0x0f0e07060b0a0302ull | MaskUnd))
2292       return getInstr(Hexagon::S2_shuffoh, dl, VecTy, {Op1, Op0}, DAG);
2293     if (MaskIdx == (0x0d0c090805040100ull | MaskUnd))
2294       return getInstr(Hexagon::S2_vtrunewh, dl, VecTy, {Op1, Op0}, DAG);
2295     if (MaskIdx == (0x0f0e0b0a07060302ull | MaskUnd))
2296       return getInstr(Hexagon::S2_vtrunowh, dl, VecTy, {Op1, Op0}, DAG);
2297     if (MaskIdx == (0x0706030205040100ull | MaskUnd)) {
2298       VectorPair P = opSplit(Op0, dl, DAG);
2299       return getInstr(Hexagon::S2_packhl, dl, VecTy, {P.second, P.first}, DAG);
2300     }
2301 
2302     // Byte packs.
2303     if (MaskIdx == (0x0e060c040a020800ull | MaskUnd))
2304       return getInstr(Hexagon::S2_shuffeb, dl, VecTy, {Op1, Op0}, DAG);
2305     if (MaskIdx == (0x0f070d050b030901ull | MaskUnd))
2306       return getInstr(Hexagon::S2_shuffob, dl, VecTy, {Op1, Op0}, DAG);
2307   }
2308 
2309   return SDValue();
2310 }
2311 
2312 // Create a Hexagon-specific node for shifting a vector by an integer.
2313 SDValue
2314 HexagonTargetLowering::getVectorShiftByInt(SDValue Op, SelectionDAG &DAG)
2315       const {
2316   unsigned NewOpc;
2317   switch (Op.getOpcode()) {
2318     case ISD::SHL:
2319       NewOpc = HexagonISD::VASL;
2320       break;
2321     case ISD::SRA:
2322       NewOpc = HexagonISD::VASR;
2323       break;
2324     case ISD::SRL:
2325       NewOpc = HexagonISD::VLSR;
2326       break;
2327     default:
2328       llvm_unreachable("Unexpected shift opcode");
2329   }
2330 
2331   SDValue Op0 = Op.getOperand(0);
2332   SDValue Op1 = Op.getOperand(1);
2333   const SDLoc &dl(Op);
2334 
2335   switch (Op1.getOpcode()) {
2336     case ISD::BUILD_VECTOR:
2337       if (SDValue S = cast<BuildVectorSDNode>(Op1)->getSplatValue())
2338         return DAG.getNode(NewOpc, dl, ty(Op), Op0, S);
2339       break;
2340     case ISD::SPLAT_VECTOR:
2341       return DAG.getNode(NewOpc, dl, ty(Op), Op0, Op1.getOperand(0));
2342   }
2343   return SDValue();
2344 }
2345 
2346 SDValue
2347 HexagonTargetLowering::LowerVECTOR_SHIFT(SDValue Op, SelectionDAG &DAG) const {
2348   return getVectorShiftByInt(Op, DAG);
2349 }
2350 
2351 SDValue
2352 HexagonTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
2353   if (isa<ConstantSDNode>(Op.getOperand(1).getNode()))
2354     return Op;
2355   return SDValue();
2356 }
2357 
2358 SDValue
2359 HexagonTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
2360   MVT ResTy = ty(Op);
2361   SDValue InpV = Op.getOperand(0);
2362   MVT InpTy = ty(InpV);
2363   assert(ResTy.getSizeInBits() == InpTy.getSizeInBits());
2364   const SDLoc &dl(Op);
2365 
2366   // Handle conversion from i8 to v8i1.
2367   if (InpTy == MVT::i8) {
2368     if (ResTy == MVT::v8i1) {
2369       SDValue Sc = DAG.getBitcast(tyScalar(InpTy), InpV);
2370       SDValue Ext = DAG.getZExtOrTrunc(Sc, dl, MVT::i32);
2371       return getInstr(Hexagon::C2_tfrrp, dl, ResTy, Ext, DAG);
2372     }
2373     return SDValue();
2374   }
2375 
2376   return Op;
2377 }
2378 
2379 bool
2380 HexagonTargetLowering::getBuildVectorConstInts(ArrayRef<SDValue> Values,
2381       MVT VecTy, SelectionDAG &DAG,
2382       MutableArrayRef<ConstantInt*> Consts) const {
2383   MVT ElemTy = VecTy.getVectorElementType();
2384   unsigned ElemWidth = ElemTy.getSizeInBits();
2385   IntegerType *IntTy = IntegerType::get(*DAG.getContext(), ElemWidth);
2386   bool AllConst = true;
2387 
2388   for (unsigned i = 0, e = Values.size(); i != e; ++i) {
2389     SDValue V = Values[i];
2390     if (V.isUndef()) {
2391       Consts[i] = ConstantInt::get(IntTy, 0);
2392       continue;
2393     }
2394     // Make sure to always cast to IntTy.
2395     if (auto *CN = dyn_cast<ConstantSDNode>(V.getNode())) {
2396       const ConstantInt *CI = CN->getConstantIntValue();
2397       Consts[i] = ConstantInt::get(IntTy, CI->getValue().getSExtValue());
2398     } else if (auto *CN = dyn_cast<ConstantFPSDNode>(V.getNode())) {
2399       const ConstantFP *CF = CN->getConstantFPValue();
2400       APInt A = CF->getValueAPF().bitcastToAPInt();
2401       Consts[i] = ConstantInt::get(IntTy, A.getZExtValue());
2402     } else {
2403       AllConst = false;
2404     }
2405   }
2406   return AllConst;
2407 }
2408 
2409 SDValue
2410 HexagonTargetLowering::buildVector32(ArrayRef<SDValue> Elem, const SDLoc &dl,
2411                                      MVT VecTy, SelectionDAG &DAG) const {
2412   MVT ElemTy = VecTy.getVectorElementType();
2413   assert(VecTy.getVectorNumElements() == Elem.size());
2414 
2415   SmallVector<ConstantInt*,4> Consts(Elem.size());
2416   bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2417 
2418   unsigned First, Num = Elem.size();
2419   for (First = 0; First != Num; ++First) {
2420     if (!isUndef(Elem[First]))
2421       break;
2422   }
2423   if (First == Num)
2424     return DAG.getUNDEF(VecTy);
2425 
2426   if (AllConst &&
2427       llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2428     return getZero(dl, VecTy, DAG);
2429 
2430   if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2431     assert(Elem.size() == 2);
2432     if (AllConst) {
2433       // The 'Consts' array will have all values as integers regardless
2434       // of the vector element type.
2435       uint32_t V = (Consts[0]->getZExtValue() & 0xFFFF) |
2436                    Consts[1]->getZExtValue() << 16;
2437       return DAG.getBitcast(VecTy, DAG.getConstant(V, dl, MVT::i32));
2438     }
2439     SDValue E0, E1;
2440     if (ElemTy == MVT::f16) {
2441       E0 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[0]), dl, MVT::i32);
2442       E1 = DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Elem[1]), dl, MVT::i32);
2443     } else {
2444       E0 = Elem[0];
2445       E1 = Elem[1];
2446     }
2447     SDValue N = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {E1, E0}, DAG);
2448     return DAG.getBitcast(VecTy, N);
2449   }
2450 
2451   if (ElemTy == MVT::i8) {
2452     // First try generating a constant.
2453     if (AllConst) {
2454       int32_t V = (Consts[0]->getZExtValue() & 0xFF) |
2455                   (Consts[1]->getZExtValue() & 0xFF) << 8 |
2456                   (Consts[2]->getZExtValue() & 0xFF) << 16 |
2457                   Consts[3]->getZExtValue() << 24;
2458       return DAG.getBitcast(MVT::v4i8, DAG.getConstant(V, dl, MVT::i32));
2459     }
2460 
2461     // Then try splat.
2462     bool IsSplat = true;
2463     for (unsigned i = First+1; i != Num; ++i) {
2464       if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2465         continue;
2466       IsSplat = false;
2467       break;
2468     }
2469     if (IsSplat) {
2470       // Legalize the operand of SPLAT_VECTOR.
2471       SDValue Ext = DAG.getZExtOrTrunc(Elem[First], dl, MVT::i32);
2472       return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2473     }
2474 
2475     // Generate
2476     //   (zxtb(Elem[0]) | (zxtb(Elem[1]) << 8)) |
2477     //   (zxtb(Elem[2]) | (zxtb(Elem[3]) << 8)) << 16
2478     assert(Elem.size() == 4);
2479     SDValue Vs[4];
2480     for (unsigned i = 0; i != 4; ++i) {
2481       Vs[i] = DAG.getZExtOrTrunc(Elem[i], dl, MVT::i32);
2482       Vs[i] = DAG.getZeroExtendInReg(Vs[i], dl, MVT::i8);
2483     }
2484     SDValue S8 = DAG.getConstant(8, dl, MVT::i32);
2485     SDValue T0 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[1], S8});
2486     SDValue T1 = DAG.getNode(ISD::SHL, dl, MVT::i32, {Vs[3], S8});
2487     SDValue B0 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[0], T0});
2488     SDValue B1 = DAG.getNode(ISD::OR, dl, MVT::i32, {Vs[2], T1});
2489 
2490     SDValue R = getInstr(Hexagon::A2_combine_ll, dl, MVT::i32, {B1, B0}, DAG);
2491     return DAG.getBitcast(MVT::v4i8, R);
2492   }
2493 
2494 #ifndef NDEBUG
2495   dbgs() << "VecTy: " << EVT(VecTy).getEVTString() << '\n';
2496 #endif
2497   llvm_unreachable("Unexpected vector element type");
2498 }
2499 
2500 SDValue
2501 HexagonTargetLowering::buildVector64(ArrayRef<SDValue> Elem, const SDLoc &dl,
2502                                      MVT VecTy, SelectionDAG &DAG) const {
2503   MVT ElemTy = VecTy.getVectorElementType();
2504   assert(VecTy.getVectorNumElements() == Elem.size());
2505 
2506   SmallVector<ConstantInt*,8> Consts(Elem.size());
2507   bool AllConst = getBuildVectorConstInts(Elem, VecTy, DAG, Consts);
2508 
2509   unsigned First, Num = Elem.size();
2510   for (First = 0; First != Num; ++First) {
2511     if (!isUndef(Elem[First]))
2512       break;
2513   }
2514   if (First == Num)
2515     return DAG.getUNDEF(VecTy);
2516 
2517   if (AllConst &&
2518       llvm::all_of(Consts, [](ConstantInt *CI) { return CI->isZero(); }))
2519     return getZero(dl, VecTy, DAG);
2520 
2521   // First try splat if possible.
2522   if (ElemTy == MVT::i16 || ElemTy == MVT::f16) {
2523     bool IsSplat = true;
2524     for (unsigned i = First+1; i != Num; ++i) {
2525       if (Elem[i] == Elem[First] || isUndef(Elem[i]))
2526         continue;
2527       IsSplat = false;
2528       break;
2529     }
2530     if (IsSplat) {
2531       // Legalize the operand of SPLAT_VECTOR
2532       SDValue S = ElemTy == MVT::f16 ? DAG.getBitcast(MVT::i16, Elem[First])
2533                                      : Elem[First];
2534       SDValue Ext = DAG.getZExtOrTrunc(S, dl, MVT::i32);
2535       return DAG.getNode(ISD::SPLAT_VECTOR, dl, VecTy, Ext);
2536     }
2537   }
2538 
2539   // Then try constant.
2540   if (AllConst) {
2541     uint64_t Val = 0;
2542     unsigned W = ElemTy.getSizeInBits();
2543     uint64_t Mask = (1ull << W) - 1;
2544     for (unsigned i = 0; i != Num; ++i)
2545       Val = (Val << W) | (Consts[Num-1-i]->getZExtValue() & Mask);
2546     SDValue V0 = DAG.getConstant(Val, dl, MVT::i64);
2547     return DAG.getBitcast(VecTy, V0);
2548   }
2549 
2550   // Build two 32-bit vectors and concatenate.
2551   MVT HalfTy = MVT::getVectorVT(ElemTy, Num/2);
2552   SDValue L = (ElemTy == MVT::i32)
2553                 ? Elem[0]
2554                 : buildVector32(Elem.take_front(Num/2), dl, HalfTy, DAG);
2555   SDValue H = (ElemTy == MVT::i32)
2556                 ? Elem[1]
2557                 : buildVector32(Elem.drop_front(Num/2), dl, HalfTy, DAG);
2558   return DAG.getNode(HexagonISD::COMBINE, dl, VecTy, {H, L});
2559 }
2560 
2561 SDValue
2562 HexagonTargetLowering::extractVector(SDValue VecV, SDValue IdxV,
2563                                      const SDLoc &dl, MVT ValTy, MVT ResTy,
2564                                      SelectionDAG &DAG) const {
2565   MVT VecTy = ty(VecV);
2566   assert(!ValTy.isVector() ||
2567          VecTy.getVectorElementType() == ValTy.getVectorElementType());
2568   unsigned VecWidth = VecTy.getSizeInBits();
2569   unsigned ValWidth = ValTy.getSizeInBits();
2570   unsigned ElemWidth = VecTy.getVectorElementType().getSizeInBits();
2571   assert((VecWidth % ElemWidth) == 0);
2572   auto *IdxN = dyn_cast<ConstantSDNode>(IdxV);
2573 
2574   // Special case for v{8,4,2}i1 (the only boolean vectors legal in Hexagon
2575   // without any coprocessors).
2576   if (ElemWidth == 1) {
2577     assert(VecWidth == VecTy.getVectorNumElements() &&
2578            "Vector elements should equal vector width size");
2579     assert(VecWidth == 8 || VecWidth == 4 || VecWidth == 2);
2580     // Check if this is an extract of the lowest bit.
2581     if (IdxN) {
2582       // Extracting the lowest bit is a no-op, but it changes the type,
2583       // so it must be kept as an operation to avoid errors related to
2584       // type mismatches.
2585       if (IdxN->isZero() && ValTy.getSizeInBits() == 1)
2586         return DAG.getNode(HexagonISD::TYPECAST, dl, MVT::i1, VecV);
2587     }
2588 
2589     // If the value extracted is a single bit, use tstbit.
2590     if (ValWidth == 1) {
2591       SDValue A0 = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32, {VecV}, DAG);
2592       SDValue M0 = DAG.getConstant(8 / VecWidth, dl, MVT::i32);
2593       SDValue I0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, M0);
2594       return DAG.getNode(HexagonISD::TSTBIT, dl, MVT::i1, A0, I0);
2595     }
2596 
2597     // Each bool vector (v2i1, v4i1, v8i1) always occupies 8 bits in
2598     // a predicate register. The elements of the vector are repeated
2599     // in the register (if necessary) so that the total number is 8.
2600     // The extracted subvector will need to be expanded in such a way.
2601     unsigned Scale = VecWidth / ValWidth;
2602 
2603     // Generate (p2d VecV) >> 8*Idx to move the interesting bytes to
2604     // position 0.
2605     assert(ty(IdxV) == MVT::i32);
2606     unsigned VecRep = 8 / VecWidth;
2607     SDValue S0 = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2608                              DAG.getConstant(8*VecRep, dl, MVT::i32));
2609     SDValue T0 = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2610     SDValue T1 = DAG.getNode(ISD::SRL, dl, MVT::i64, T0, S0);
2611     while (Scale > 1) {
2612       // The longest possible subvector is at most 32 bits, so it is always
2613       // contained in the low subregister.
2614       T1 = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, T1);
2615       T1 = expandPredicate(T1, dl, DAG);
2616       Scale /= 2;
2617     }
2618 
2619     return DAG.getNode(HexagonISD::D2P, dl, ResTy, T1);
2620   }
2621 
2622   assert(VecWidth == 32 || VecWidth == 64);
2623 
2624   // Cast everything to scalar integer types.
2625   MVT ScalarTy = tyScalar(VecTy);
2626   VecV = DAG.getBitcast(ScalarTy, VecV);
2627 
2628   SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2629   SDValue ExtV;
2630 
2631   if (IdxN) {
2632     unsigned Off = IdxN->getZExtValue() * ElemWidth;
2633     if (VecWidth == 64 && ValWidth == 32) {
2634       assert(Off == 0 || Off == 32);
2635       unsigned SubIdx = Off == 0 ? Hexagon::isub_lo : Hexagon::isub_hi;
2636       ExtV = DAG.getTargetExtractSubreg(SubIdx, dl, MVT::i32, VecV);
2637     } else if (Off == 0 && (ValWidth % 8) == 0) {
2638       ExtV = DAG.getZeroExtendInReg(VecV, dl, tyScalar(ValTy));
2639     } else {
2640       SDValue OffV = DAG.getConstant(Off, dl, MVT::i32);
2641       // The return type of EXTRACTU must be the same as the type of the
2642       // input vector.
2643       ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2644                          {VecV, WidthV, OffV});
2645     }
2646   } else {
2647     if (ty(IdxV) != MVT::i32)
2648       IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2649     SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2650                                DAG.getConstant(ElemWidth, dl, MVT::i32));
2651     ExtV = DAG.getNode(HexagonISD::EXTRACTU, dl, ScalarTy,
2652                        {VecV, WidthV, OffV});
2653   }
2654 
2655   // Cast ExtV to the requested result type.
2656   ExtV = DAG.getZExtOrTrunc(ExtV, dl, tyScalar(ResTy));
2657   ExtV = DAG.getBitcast(ResTy, ExtV);
2658   return ExtV;
2659 }
2660 
2661 SDValue
2662 HexagonTargetLowering::insertVector(SDValue VecV, SDValue ValV, SDValue IdxV,
2663                                     const SDLoc &dl, MVT ValTy,
2664                                     SelectionDAG &DAG) const {
2665   MVT VecTy = ty(VecV);
2666   if (VecTy.getVectorElementType() == MVT::i1) {
2667     MVT ValTy = ty(ValV);
2668     assert(ValTy.getVectorElementType() == MVT::i1);
2669     SDValue ValR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, ValV);
2670     unsigned VecLen = VecTy.getVectorNumElements();
2671     unsigned Scale = VecLen / ValTy.getVectorNumElements();
2672     assert(Scale > 1);
2673 
2674     for (unsigned R = Scale; R > 1; R /= 2) {
2675       ValR = contractPredicate(ValR, dl, DAG);
2676       ValR = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2677                          DAG.getUNDEF(MVT::i32), ValR);
2678     }
2679     // The longest possible subvector is at most 32 bits, so it is always
2680     // contained in the low subregister.
2681     ValR = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, ValR);
2682 
2683     unsigned ValBytes = 64 / Scale;
2684     SDValue Width = DAG.getConstant(ValBytes*8, dl, MVT::i32);
2685     SDValue Idx = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV,
2686                               DAG.getConstant(8, dl, MVT::i32));
2687     SDValue VecR = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, VecV);
2688     SDValue Ins = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
2689                               {VecR, ValR, Width, Idx});
2690     return DAG.getNode(HexagonISD::D2P, dl, VecTy, Ins);
2691   }
2692 
2693   unsigned VecWidth = VecTy.getSizeInBits();
2694   unsigned ValWidth = ValTy.getSizeInBits();
2695   assert(VecWidth == 32 || VecWidth == 64);
2696   assert((VecWidth % ValWidth) == 0);
2697 
2698   // Cast everything to scalar integer types.
2699   MVT ScalarTy = MVT::getIntegerVT(VecWidth);
2700   // The actual type of ValV may be different than ValTy (which is related
2701   // to the vector type).
2702   unsigned VW = ty(ValV).getSizeInBits();
2703   ValV = DAG.getBitcast(MVT::getIntegerVT(VW), ValV);
2704   VecV = DAG.getBitcast(ScalarTy, VecV);
2705   if (VW != VecWidth)
2706     ValV = DAG.getAnyExtOrTrunc(ValV, dl, ScalarTy);
2707 
2708   SDValue WidthV = DAG.getConstant(ValWidth, dl, MVT::i32);
2709   SDValue InsV;
2710 
2711   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(IdxV)) {
2712     unsigned W = C->getZExtValue() * ValWidth;
2713     SDValue OffV = DAG.getConstant(W, dl, MVT::i32);
2714     InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2715                        {VecV, ValV, WidthV, OffV});
2716   } else {
2717     if (ty(IdxV) != MVT::i32)
2718       IdxV = DAG.getZExtOrTrunc(IdxV, dl, MVT::i32);
2719     SDValue OffV = DAG.getNode(ISD::MUL, dl, MVT::i32, IdxV, WidthV);
2720     InsV = DAG.getNode(HexagonISD::INSERT, dl, ScalarTy,
2721                        {VecV, ValV, WidthV, OffV});
2722   }
2723 
2724   return DAG.getNode(ISD::BITCAST, dl, VecTy, InsV);
2725 }
2726 
2727 SDValue
2728 HexagonTargetLowering::expandPredicate(SDValue Vec32, const SDLoc &dl,
2729                                        SelectionDAG &DAG) const {
2730   assert(ty(Vec32).getSizeInBits() == 32);
2731   if (isUndef(Vec32))
2732     return DAG.getUNDEF(MVT::i64);
2733   return getInstr(Hexagon::S2_vsxtbh, dl, MVT::i64, {Vec32}, DAG);
2734 }
2735 
2736 SDValue
2737 HexagonTargetLowering::contractPredicate(SDValue Vec64, const SDLoc &dl,
2738                                          SelectionDAG &DAG) const {
2739   assert(ty(Vec64).getSizeInBits() == 64);
2740   if (isUndef(Vec64))
2741     return DAG.getUNDEF(MVT::i32);
2742   return getInstr(Hexagon::S2_vtrunehb, dl, MVT::i32, {Vec64}, DAG);
2743 }
2744 
2745 SDValue
2746 HexagonTargetLowering::getZero(const SDLoc &dl, MVT Ty, SelectionDAG &DAG)
2747       const {
2748   if (Ty.isVector()) {
2749     unsigned W = Ty.getSizeInBits();
2750     if (W <= 64)
2751       return DAG.getBitcast(Ty, DAG.getConstant(0, dl, MVT::getIntegerVT(W)));
2752     return DAG.getNode(ISD::SPLAT_VECTOR, dl, Ty, getZero(dl, MVT::i32, DAG));
2753   }
2754 
2755   if (Ty.isInteger())
2756     return DAG.getConstant(0, dl, Ty);
2757   if (Ty.isFloatingPoint())
2758     return DAG.getConstantFP(0.0, dl, Ty);
2759   llvm_unreachable("Invalid type for zero");
2760 }
2761 
2762 SDValue
2763 HexagonTargetLowering::appendUndef(SDValue Val, MVT ResTy, SelectionDAG &DAG)
2764       const {
2765   MVT ValTy = ty(Val);
2766   assert(ValTy.getVectorElementType() == ResTy.getVectorElementType());
2767 
2768   unsigned ValLen = ValTy.getVectorNumElements();
2769   unsigned ResLen = ResTy.getVectorNumElements();
2770   if (ValLen == ResLen)
2771     return Val;
2772 
2773   const SDLoc &dl(Val);
2774   assert(ValLen < ResLen);
2775   assert(ResLen % ValLen == 0);
2776 
2777   SmallVector<SDValue, 4> Concats = {Val};
2778   for (unsigned i = 1, e = ResLen / ValLen; i < e; ++i)
2779     Concats.push_back(DAG.getUNDEF(ValTy));
2780 
2781   return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, Concats);
2782 }
2783 
2784 SDValue
2785 HexagonTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
2786   MVT VecTy = ty(Op);
2787   unsigned BW = VecTy.getSizeInBits();
2788   const SDLoc &dl(Op);
2789   SmallVector<SDValue,8> Ops;
2790   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i)
2791     Ops.push_back(Op.getOperand(i));
2792 
2793   if (BW == 32)
2794     return buildVector32(Ops, dl, VecTy, DAG);
2795   if (BW == 64)
2796     return buildVector64(Ops, dl, VecTy, DAG);
2797 
2798   if (VecTy == MVT::v8i1 || VecTy == MVT::v4i1 || VecTy == MVT::v2i1) {
2799     // Check if this is a special case or all-0 or all-1.
2800     bool All0 = true, All1 = true;
2801     for (SDValue P : Ops) {
2802       auto *CN = dyn_cast<ConstantSDNode>(P.getNode());
2803       if (CN == nullptr) {
2804         All0 = All1 = false;
2805         break;
2806       }
2807       uint32_t C = CN->getZExtValue();
2808       All0 &= (C == 0);
2809       All1 &= (C == 1);
2810     }
2811     if (All0)
2812       return DAG.getNode(HexagonISD::PFALSE, dl, VecTy);
2813     if (All1)
2814       return DAG.getNode(HexagonISD::PTRUE, dl, VecTy);
2815 
2816     // For each i1 element in the resulting predicate register, put 1
2817     // shifted by the index of the element into a general-purpose register,
2818     // then or them together and transfer it back into a predicate register.
2819     SDValue Rs[8];
2820     SDValue Z = getZero(dl, MVT::i32, DAG);
2821     // Always produce 8 bits, repeat inputs if necessary.
2822     unsigned Rep = 8 / VecTy.getVectorNumElements();
2823     for (unsigned i = 0; i != 8; ++i) {
2824       SDValue S = DAG.getConstant(1ull << i, dl, MVT::i32);
2825       Rs[i] = DAG.getSelect(dl, MVT::i32, Ops[i/Rep], S, Z);
2826     }
2827     for (ArrayRef<SDValue> A(Rs); A.size() != 1; A = A.drop_back(A.size()/2)) {
2828       for (unsigned i = 0, e = A.size()/2; i != e; ++i)
2829         Rs[i] = DAG.getNode(ISD::OR, dl, MVT::i32, Rs[2*i], Rs[2*i+1]);
2830     }
2831     // Move the value directly to a predicate register.
2832     return getInstr(Hexagon::C2_tfrrp, dl, VecTy, {Rs[0]}, DAG);
2833   }
2834 
2835   return SDValue();
2836 }
2837 
2838 SDValue
2839 HexagonTargetLowering::LowerCONCAT_VECTORS(SDValue Op,
2840                                            SelectionDAG &DAG) const {
2841   MVT VecTy = ty(Op);
2842   const SDLoc &dl(Op);
2843   if (VecTy.getSizeInBits() == 64) {
2844     assert(Op.getNumOperands() == 2);
2845     return DAG.getNode(HexagonISD::COMBINE, dl, VecTy, Op.getOperand(1),
2846                        Op.getOperand(0));
2847   }
2848 
2849   MVT ElemTy = VecTy.getVectorElementType();
2850   if (ElemTy == MVT::i1) {
2851     assert(VecTy == MVT::v2i1 || VecTy == MVT::v4i1 || VecTy == MVT::v8i1);
2852     MVT OpTy = ty(Op.getOperand(0));
2853     // Scale is how many times the operands need to be contracted to match
2854     // the representation in the target register.
2855     unsigned Scale = VecTy.getVectorNumElements() / OpTy.getVectorNumElements();
2856     assert(Scale == Op.getNumOperands() && Scale > 1);
2857 
2858     // First, convert all bool vectors to integers, then generate pairwise
2859     // inserts to form values of doubled length. Up until there are only
2860     // two values left to concatenate, all of these values will fit in a
2861     // 32-bit integer, so keep them as i32 to use 32-bit inserts.
2862     SmallVector<SDValue,4> Words[2];
2863     unsigned IdxW = 0;
2864 
2865     for (SDValue P : Op.getNode()->op_values()) {
2866       SDValue W = DAG.getNode(HexagonISD::P2D, dl, MVT::i64, P);
2867       for (unsigned R = Scale; R > 1; R /= 2) {
2868         W = contractPredicate(W, dl, DAG);
2869         W = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2870                         DAG.getUNDEF(MVT::i32), W);
2871       }
2872       W = DAG.getTargetExtractSubreg(Hexagon::isub_lo, dl, MVT::i32, W);
2873       Words[IdxW].push_back(W);
2874     }
2875 
2876     while (Scale > 2) {
2877       SDValue WidthV = DAG.getConstant(64 / Scale, dl, MVT::i32);
2878       Words[IdxW ^ 1].clear();
2879 
2880       for (unsigned i = 0, e = Words[IdxW].size(); i != e; i += 2) {
2881         SDValue W0 = Words[IdxW][i], W1 = Words[IdxW][i+1];
2882         // Insert W1 into W0 right next to the significant bits of W0.
2883         SDValue T = DAG.getNode(HexagonISD::INSERT, dl, MVT::i32,
2884                                 {W0, W1, WidthV, WidthV});
2885         Words[IdxW ^ 1].push_back(T);
2886       }
2887       IdxW ^= 1;
2888       Scale /= 2;
2889     }
2890 
2891     // At this point there should only be two words left, and Scale should be 2.
2892     assert(Scale == 2 && Words[IdxW].size() == 2);
2893 
2894     SDValue WW = DAG.getNode(HexagonISD::COMBINE, dl, MVT::i64,
2895                              Words[IdxW][1], Words[IdxW][0]);
2896     return DAG.getNode(HexagonISD::D2P, dl, VecTy, WW);
2897   }
2898 
2899   return SDValue();
2900 }
2901 
2902 SDValue
2903 HexagonTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
2904                                                SelectionDAG &DAG) const {
2905   SDValue Vec = Op.getOperand(0);
2906   MVT ElemTy = ty(Vec).getVectorElementType();
2907   return extractVector(Vec, Op.getOperand(1), SDLoc(Op), ElemTy, ty(Op), DAG);
2908 }
2909 
2910 SDValue
2911 HexagonTargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
2912                                               SelectionDAG &DAG) const {
2913   return extractVector(Op.getOperand(0), Op.getOperand(1), SDLoc(Op),
2914                        ty(Op), ty(Op), DAG);
2915 }
2916 
2917 SDValue
2918 HexagonTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
2919                                               SelectionDAG &DAG) const {
2920   return insertVector(Op.getOperand(0), Op.getOperand(1), Op.getOperand(2),
2921                       SDLoc(Op), ty(Op).getVectorElementType(), DAG);
2922 }
2923 
2924 SDValue
2925 HexagonTargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
2926                                              SelectionDAG &DAG) const {
2927   SDValue ValV = Op.getOperand(1);
2928   return insertVector(Op.getOperand(0), ValV, Op.getOperand(2),
2929                       SDLoc(Op), ty(ValV), DAG);
2930 }
2931 
2932 bool
2933 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
2934   // Assuming the caller does not have either a signext or zeroext modifier, and
2935   // only one value is accepted, any reasonable truncation is allowed.
2936   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
2937     return false;
2938 
2939   // FIXME: in principle up to 64-bit could be made safe, but it would be very
2940   // fragile at the moment: any support for multiple value returns would be
2941   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
2942   return Ty1->getPrimitiveSizeInBits() <= 32;
2943 }
2944 
2945 SDValue
2946 HexagonTargetLowering::LowerLoad(SDValue Op, SelectionDAG &DAG) const {
2947   MVT Ty = ty(Op);
2948   const SDLoc &dl(Op);
2949   // Lower loads of scalar predicate vectors (v2i1, v4i1, v8i1) to loads of i1
2950   // followed by a TYPECAST.
2951   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
2952   bool DoCast = (Ty == MVT::v2i1 || Ty == MVT::v4i1 || Ty == MVT::v8i1);
2953   if (DoCast) {
2954     SDValue NL = DAG.getLoad(
2955         LN->getAddressingMode(), LN->getExtensionType(), MVT::i1, dl,
2956         LN->getChain(), LN->getBasePtr(), LN->getOffset(), LN->getPointerInfo(),
2957         /*MemoryVT*/ MVT::i1, LN->getAlign(), LN->getMemOperand()->getFlags(),
2958         LN->getAAInfo(), LN->getRanges());
2959     LN = cast<LoadSDNode>(NL.getNode());
2960   }
2961 
2962   Align ClaimAlign = LN->getAlign();
2963   if (!validateConstPtrAlignment(LN->getBasePtr(), ClaimAlign, dl, DAG))
2964     return replaceMemWithUndef(Op, DAG);
2965 
2966   // Call LowerUnalignedLoad for all loads, it recognizes loads that
2967   // don't need extra aligning.
2968   SDValue LU = LowerUnalignedLoad(SDValue(LN, 0), DAG);
2969   if (DoCast) {
2970     SDValue TC = DAG.getNode(HexagonISD::TYPECAST, dl, Ty, LU);
2971     SDValue Ch = cast<LoadSDNode>(LU.getNode())->getChain();
2972     return DAG.getMergeValues({TC, Ch}, dl);
2973   }
2974   return LU;
2975 }
2976 
2977 SDValue
2978 HexagonTargetLowering::LowerStore(SDValue Op, SelectionDAG &DAG) const {
2979   const SDLoc &dl(Op);
2980   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
2981   SDValue Val = SN->getValue();
2982   MVT Ty = ty(Val);
2983 
2984   bool DoCast = (Ty == MVT::v2i1 || Ty == MVT::v4i1 || Ty == MVT::v8i1);
2985   if (DoCast) {
2986     SDValue TC = DAG.getNode(HexagonISD::TYPECAST, dl, MVT::i1, Val);
2987     SDValue NS = DAG.getStore(SN->getChain(), dl, TC, SN->getBasePtr(),
2988                               SN->getMemOperand());
2989     if (SN->isIndexed()) {
2990       NS = DAG.getIndexedStore(NS, dl, SN->getBasePtr(), SN->getOffset(),
2991                                SN->getAddressingMode());
2992     }
2993     SN = cast<StoreSDNode>(NS.getNode());
2994   }
2995 
2996   Align ClaimAlign = SN->getAlign();
2997   if (!validateConstPtrAlignment(SN->getBasePtr(), ClaimAlign, dl, DAG))
2998     return replaceMemWithUndef(Op, DAG);
2999 
3000   MVT StoreTy = SN->getMemoryVT().getSimpleVT();
3001   Align NeedAlign = Subtarget.getTypeAlignment(StoreTy);
3002   if (ClaimAlign < NeedAlign)
3003     return expandUnalignedStore(SN, DAG);
3004   return SDValue(SN, 0);
3005 }
3006 
3007 SDValue
3008 HexagonTargetLowering::LowerUnalignedLoad(SDValue Op, SelectionDAG &DAG)
3009       const {
3010   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
3011   MVT LoadTy = ty(Op);
3012   unsigned NeedAlign = Subtarget.getTypeAlignment(LoadTy).value();
3013   unsigned HaveAlign = LN->getAlign().value();
3014   if (HaveAlign >= NeedAlign)
3015     return Op;
3016 
3017   const SDLoc &dl(Op);
3018   const DataLayout &DL = DAG.getDataLayout();
3019   LLVMContext &Ctx = *DAG.getContext();
3020 
3021   // If the load aligning is disabled or the load can be broken up into two
3022   // smaller legal loads, do the default (target-independent) expansion.
3023   bool DoDefault = false;
3024   // Handle it in the default way if this is an indexed load.
3025   if (!LN->isUnindexed())
3026     DoDefault = true;
3027 
3028   if (!AlignLoads) {
3029     if (allowsMemoryAccessForAlignment(Ctx, DL, LN->getMemoryVT(),
3030                                        *LN->getMemOperand()))
3031       return Op;
3032     DoDefault = true;
3033   }
3034   if (!DoDefault && (2 * HaveAlign) == NeedAlign) {
3035     // The PartTy is the equivalent of "getLoadableTypeOfSize(HaveAlign)".
3036     MVT PartTy = HaveAlign <= 8 ? MVT::getIntegerVT(8 * HaveAlign)
3037                                 : MVT::getVectorVT(MVT::i8, HaveAlign);
3038     DoDefault =
3039         allowsMemoryAccessForAlignment(Ctx, DL, PartTy, *LN->getMemOperand());
3040   }
3041   if (DoDefault) {
3042     std::pair<SDValue, SDValue> P = expandUnalignedLoad(LN, DAG);
3043     return DAG.getMergeValues({P.first, P.second}, dl);
3044   }
3045 
3046   // The code below generates two loads, both aligned as NeedAlign, and
3047   // with the distance of NeedAlign between them. For that to cover the
3048   // bits that need to be loaded (and without overlapping), the size of
3049   // the loads should be equal to NeedAlign. This is true for all loadable
3050   // types, but add an assertion in case something changes in the future.
3051   assert(LoadTy.getSizeInBits() == 8*NeedAlign);
3052 
3053   unsigned LoadLen = NeedAlign;
3054   SDValue Base = LN->getBasePtr();
3055   SDValue Chain = LN->getChain();
3056   auto BO = getBaseAndOffset(Base);
3057   unsigned BaseOpc = BO.first.getOpcode();
3058   if (BaseOpc == HexagonISD::VALIGNADDR && BO.second % LoadLen == 0)
3059     return Op;
3060 
3061   if (BO.second % LoadLen != 0) {
3062     BO.first = DAG.getNode(ISD::ADD, dl, MVT::i32, BO.first,
3063                            DAG.getConstant(BO.second % LoadLen, dl, MVT::i32));
3064     BO.second -= BO.second % LoadLen;
3065   }
3066   SDValue BaseNoOff = (BaseOpc != HexagonISD::VALIGNADDR)
3067       ? DAG.getNode(HexagonISD::VALIGNADDR, dl, MVT::i32, BO.first,
3068                     DAG.getConstant(NeedAlign, dl, MVT::i32))
3069       : BO.first;
3070   SDValue Base0 =
3071       DAG.getMemBasePlusOffset(BaseNoOff, TypeSize::Fixed(BO.second), dl);
3072   SDValue Base1 = DAG.getMemBasePlusOffset(
3073       BaseNoOff, TypeSize::Fixed(BO.second + LoadLen), dl);
3074 
3075   MachineMemOperand *WideMMO = nullptr;
3076   if (MachineMemOperand *MMO = LN->getMemOperand()) {
3077     MachineFunction &MF = DAG.getMachineFunction();
3078     WideMMO = MF.getMachineMemOperand(
3079         MMO->getPointerInfo(), MMO->getFlags(), 2 * LoadLen, Align(LoadLen),
3080         MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
3081         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
3082   }
3083 
3084   SDValue Load0 = DAG.getLoad(LoadTy, dl, Chain, Base0, WideMMO);
3085   SDValue Load1 = DAG.getLoad(LoadTy, dl, Chain, Base1, WideMMO);
3086 
3087   SDValue Aligned = DAG.getNode(HexagonISD::VALIGN, dl, LoadTy,
3088                                 {Load1, Load0, BaseNoOff.getOperand(0)});
3089   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3090                                  Load0.getValue(1), Load1.getValue(1));
3091   SDValue M = DAG.getMergeValues({Aligned, NewChain}, dl);
3092   return M;
3093 }
3094 
3095 SDValue
3096 HexagonTargetLowering::LowerUAddSubO(SDValue Op, SelectionDAG &DAG) const {
3097   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
3098   auto *CY = dyn_cast<ConstantSDNode>(Y);
3099   if (!CY)
3100     return SDValue();
3101 
3102   const SDLoc &dl(Op);
3103   SDVTList VTs = Op.getNode()->getVTList();
3104   assert(VTs.NumVTs == 2);
3105   assert(VTs.VTs[1] == MVT::i1);
3106   unsigned Opc = Op.getOpcode();
3107 
3108   if (CY) {
3109     uint32_t VY = CY->getZExtValue();
3110     assert(VY != 0 && "This should have been folded");
3111     // X +/- 1
3112     if (VY != 1)
3113       return SDValue();
3114 
3115     if (Opc == ISD::UADDO) {
3116       SDValue Op = DAG.getNode(ISD::ADD, dl, VTs.VTs[0], {X, Y});
3117       SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op, getZero(dl, ty(Op), DAG),
3118                                 ISD::SETEQ);
3119       return DAG.getMergeValues({Op, Ov}, dl);
3120     }
3121     if (Opc == ISD::USUBO) {
3122       SDValue Op = DAG.getNode(ISD::SUB, dl, VTs.VTs[0], {X, Y});
3123       SDValue Ov = DAG.getSetCC(dl, MVT::i1, Op,
3124                                 DAG.getConstant(-1, dl, ty(Op)), ISD::SETEQ);
3125       return DAG.getMergeValues({Op, Ov}, dl);
3126     }
3127   }
3128 
3129   return SDValue();
3130 }
3131 
3132 SDValue
3133 HexagonTargetLowering::LowerAddSubCarry(SDValue Op, SelectionDAG &DAG) const {
3134   const SDLoc &dl(Op);
3135   unsigned Opc = Op.getOpcode();
3136   SDValue X = Op.getOperand(0), Y = Op.getOperand(1), C = Op.getOperand(2);
3137 
3138   if (Opc == ISD::ADDCARRY)
3139     return DAG.getNode(HexagonISD::ADDC, dl, Op.getNode()->getVTList(),
3140                        { X, Y, C });
3141 
3142   EVT CarryTy = C.getValueType();
3143   SDValue SubC = DAG.getNode(HexagonISD::SUBC, dl, Op.getNode()->getVTList(),
3144                              { X, Y, DAG.getLogicalNOT(dl, C, CarryTy) });
3145   SDValue Out[] = { SubC.getValue(0),
3146                     DAG.getLogicalNOT(dl, SubC.getValue(1), CarryTy) };
3147   return DAG.getMergeValues(Out, dl);
3148 }
3149 
3150 SDValue
3151 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
3152   SDValue Chain     = Op.getOperand(0);
3153   SDValue Offset    = Op.getOperand(1);
3154   SDValue Handler   = Op.getOperand(2);
3155   SDLoc dl(Op);
3156   auto PtrVT = getPointerTy(DAG.getDataLayout());
3157 
3158   // Mark function as containing a call to EH_RETURN.
3159   HexagonMachineFunctionInfo *FuncInfo =
3160     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
3161   FuncInfo->setHasEHReturn();
3162 
3163   unsigned OffsetReg = Hexagon::R28;
3164 
3165   SDValue StoreAddr =
3166       DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getRegister(Hexagon::R30, PtrVT),
3167                   DAG.getIntPtrConstant(4, dl));
3168   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
3169   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
3170 
3171   // Not needed we already use it as explict input to EH_RETURN.
3172   // MF.getRegInfo().addLiveOut(OffsetReg);
3173 
3174   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
3175 }
3176 
3177 SDValue
3178 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3179   unsigned Opc = Op.getOpcode();
3180 
3181   // Handle INLINEASM first.
3182   if (Opc == ISD::INLINEASM || Opc == ISD::INLINEASM_BR)
3183     return LowerINLINEASM(Op, DAG);
3184 
3185   if (isHvxOperation(Op.getNode(), DAG)) {
3186     // If HVX lowering returns nothing, try the default lowering.
3187     if (SDValue V = LowerHvxOperation(Op, DAG))
3188       return V;
3189   }
3190 
3191   switch (Opc) {
3192     default:
3193 #ifndef NDEBUG
3194       Op.getNode()->dumpr(&DAG);
3195       if (Opc > HexagonISD::OP_BEGIN && Opc < HexagonISD::OP_END)
3196         errs() << "Error: check for a non-legal type in this operation\n";
3197 #endif
3198       llvm_unreachable("Should not custom lower this!");
3199     case ISD::CONCAT_VECTORS:       return LowerCONCAT_VECTORS(Op, DAG);
3200     case ISD::INSERT_SUBVECTOR:     return LowerINSERT_SUBVECTOR(Op, DAG);
3201     case ISD::INSERT_VECTOR_ELT:    return LowerINSERT_VECTOR_ELT(Op, DAG);
3202     case ISD::EXTRACT_SUBVECTOR:    return LowerEXTRACT_SUBVECTOR(Op, DAG);
3203     case ISD::EXTRACT_VECTOR_ELT:   return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3204     case ISD::BUILD_VECTOR:         return LowerBUILD_VECTOR(Op, DAG);
3205     case ISD::VECTOR_SHUFFLE:       return LowerVECTOR_SHUFFLE(Op, DAG);
3206     case ISD::BITCAST:              return LowerBITCAST(Op, DAG);
3207     case ISD::LOAD:                 return LowerLoad(Op, DAG);
3208     case ISD::STORE:                return LowerStore(Op, DAG);
3209     case ISD::UADDO:
3210     case ISD::USUBO:                return LowerUAddSubO(Op, DAG);
3211     case ISD::ADDCARRY:
3212     case ISD::SUBCARRY:             return LowerAddSubCarry(Op, DAG);
3213     case ISD::SRA:
3214     case ISD::SHL:
3215     case ISD::SRL:                  return LowerVECTOR_SHIFT(Op, DAG);
3216     case ISD::ROTL:                 return LowerROTL(Op, DAG);
3217     case ISD::ConstantPool:         return LowerConstantPool(Op, DAG);
3218     case ISD::JumpTable:            return LowerJumpTable(Op, DAG);
3219     case ISD::EH_RETURN:            return LowerEH_RETURN(Op, DAG);
3220     case ISD::RETURNADDR:           return LowerRETURNADDR(Op, DAG);
3221     case ISD::FRAMEADDR:            return LowerFRAMEADDR(Op, DAG);
3222     case ISD::GlobalTLSAddress:     return LowerGlobalTLSAddress(Op, DAG);
3223     case ISD::ATOMIC_FENCE:         return LowerATOMIC_FENCE(Op, DAG);
3224     case ISD::GlobalAddress:        return LowerGLOBALADDRESS(Op, DAG);
3225     case ISD::BlockAddress:         return LowerBlockAddress(Op, DAG);
3226     case ISD::GLOBAL_OFFSET_TABLE:  return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
3227     case ISD::VACOPY:               return LowerVACOPY(Op, DAG);
3228     case ISD::VASTART:              return LowerVASTART(Op, DAG);
3229     case ISD::DYNAMIC_STACKALLOC:   return LowerDYNAMIC_STACKALLOC(Op, DAG);
3230     case ISD::SETCC:                return LowerSETCC(Op, DAG);
3231     case ISD::VSELECT:              return LowerVSELECT(Op, DAG);
3232     case ISD::INTRINSIC_WO_CHAIN:   return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3233     case ISD::INTRINSIC_VOID:       return LowerINTRINSIC_VOID(Op, DAG);
3234     case ISD::PREFETCH:             return LowerPREFETCH(Op, DAG);
3235     case ISD::READCYCLECOUNTER:     return LowerREADCYCLECOUNTER(Op, DAG);
3236       break;
3237   }
3238 
3239   return SDValue();
3240 }
3241 
3242 void
3243 HexagonTargetLowering::LowerOperationWrapper(SDNode *N,
3244                                              SmallVectorImpl<SDValue> &Results,
3245                                              SelectionDAG &DAG) const {
3246   if (isHvxOperation(N, DAG)) {
3247     LowerHvxOperationWrapper(N, Results, DAG);
3248     if (!Results.empty())
3249       return;
3250   }
3251 
3252   // We are only custom-lowering stores to verify the alignment of the
3253   // address if it is a compile-time constant. Since a store can be modified
3254   // during type-legalization (the value being stored may need legalization),
3255   // return empty Results here to indicate that we don't really make any
3256   // changes in the custom lowering.
3257   if (N->getOpcode() != ISD::STORE)
3258     return TargetLowering::LowerOperationWrapper(N, Results, DAG);
3259 }
3260 
3261 void
3262 HexagonTargetLowering::ReplaceNodeResults(SDNode *N,
3263                                           SmallVectorImpl<SDValue> &Results,
3264                                           SelectionDAG &DAG) const {
3265   if (isHvxOperation(N, DAG)) {
3266     ReplaceHvxNodeResults(N, Results, DAG);
3267     if (!Results.empty())
3268       return;
3269   }
3270 
3271   const SDLoc &dl(N);
3272   switch (N->getOpcode()) {
3273     case ISD::SRL:
3274     case ISD::SRA:
3275     case ISD::SHL:
3276       return;
3277     case ISD::BITCAST:
3278       // Handle a bitcast from v8i1 to i8.
3279       if (N->getValueType(0) == MVT::i8) {
3280         if (N->getOperand(0).getValueType() == MVT::v8i1) {
3281           SDValue P = getInstr(Hexagon::C2_tfrpr, dl, MVT::i32,
3282                                N->getOperand(0), DAG);
3283           SDValue T = DAG.getAnyExtOrTrunc(P, dl, MVT::i8);
3284           Results.push_back(T);
3285         }
3286       }
3287       break;
3288   }
3289 }
3290 
3291 SDValue
3292 HexagonTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
3293       const {
3294   if (isHvxOperation(N, DCI.DAG)) {
3295     if (SDValue V = PerformHvxDAGCombine(N, DCI))
3296       return V;
3297     return SDValue();
3298   }
3299 
3300   if (DCI.isBeforeLegalizeOps())
3301     return SDValue();
3302 
3303   SDValue Op(N, 0);
3304   const SDLoc &dl(Op);
3305   unsigned Opc = Op.getOpcode();
3306 
3307   if (Opc == HexagonISD::P2D) {
3308     SDValue P = Op.getOperand(0);
3309     switch (P.getOpcode()) {
3310       case HexagonISD::PTRUE:
3311         return DCI.DAG.getConstant(-1, dl, ty(Op));
3312       case HexagonISD::PFALSE:
3313         return getZero(dl, ty(Op), DCI.DAG);
3314       default:
3315         break;
3316     }
3317   } else if (Opc == ISD::VSELECT) {
3318     // This is pretty much duplicated in HexagonISelLoweringHVX...
3319     //
3320     // (vselect (xor x, ptrue), v0, v1) -> (vselect x, v1, v0)
3321     SDValue Cond = Op.getOperand(0);
3322     if (Cond->getOpcode() == ISD::XOR) {
3323       SDValue C0 = Cond.getOperand(0), C1 = Cond.getOperand(1);
3324       if (C1->getOpcode() == HexagonISD::PTRUE) {
3325         SDValue VSel = DCI.DAG.getNode(ISD::VSELECT, dl, ty(Op), C0,
3326                                        Op.getOperand(2), Op.getOperand(1));
3327         return VSel;
3328       }
3329     }
3330   }
3331 
3332   return SDValue();
3333 }
3334 
3335 /// Returns relocation base for the given PIC jumptable.
3336 SDValue
3337 HexagonTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3338                                                 SelectionDAG &DAG) const {
3339   int Idx = cast<JumpTableSDNode>(Table)->getIndex();
3340   EVT VT = Table.getValueType();
3341   SDValue T = DAG.getTargetJumpTable(Idx, VT, HexagonII::MO_PCREL);
3342   return DAG.getNode(HexagonISD::AT_PCREL, SDLoc(Table), VT, T);
3343 }
3344 
3345 //===----------------------------------------------------------------------===//
3346 // Inline Assembly Support
3347 //===----------------------------------------------------------------------===//
3348 
3349 TargetLowering::ConstraintType
3350 HexagonTargetLowering::getConstraintType(StringRef Constraint) const {
3351   if (Constraint.size() == 1) {
3352     switch (Constraint[0]) {
3353       case 'q':
3354       case 'v':
3355         if (Subtarget.useHVXOps())
3356           return C_RegisterClass;
3357         break;
3358       case 'a':
3359         return C_RegisterClass;
3360       default:
3361         break;
3362     }
3363   }
3364   return TargetLowering::getConstraintType(Constraint);
3365 }
3366 
3367 std::pair<unsigned, const TargetRegisterClass*>
3368 HexagonTargetLowering::getRegForInlineAsmConstraint(
3369     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
3370 
3371   if (Constraint.size() == 1) {
3372     switch (Constraint[0]) {
3373     case 'r':   // R0-R31
3374       switch (VT.SimpleTy) {
3375       default:
3376         return {0u, nullptr};
3377       case MVT::i1:
3378       case MVT::i8:
3379       case MVT::i16:
3380       case MVT::i32:
3381       case MVT::f32:
3382         return {0u, &Hexagon::IntRegsRegClass};
3383       case MVT::i64:
3384       case MVT::f64:
3385         return {0u, &Hexagon::DoubleRegsRegClass};
3386       }
3387       break;
3388     case 'a': // M0-M1
3389       if (VT != MVT::i32)
3390         return {0u, nullptr};
3391       return {0u, &Hexagon::ModRegsRegClass};
3392     case 'q': // q0-q3
3393       switch (VT.getSizeInBits()) {
3394       default:
3395         return {0u, nullptr};
3396       case 64:
3397       case 128:
3398         return {0u, &Hexagon::HvxQRRegClass};
3399       }
3400       break;
3401     case 'v': // V0-V31
3402       switch (VT.getSizeInBits()) {
3403       default:
3404         return {0u, nullptr};
3405       case 512:
3406         return {0u, &Hexagon::HvxVRRegClass};
3407       case 1024:
3408         if (Subtarget.hasV60Ops() && Subtarget.useHVX128BOps())
3409           return {0u, &Hexagon::HvxVRRegClass};
3410         return {0u, &Hexagon::HvxWRRegClass};
3411       case 2048:
3412         return {0u, &Hexagon::HvxWRRegClass};
3413       }
3414       break;
3415     default:
3416       return {0u, nullptr};
3417     }
3418   }
3419 
3420   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3421 }
3422 
3423 /// isFPImmLegal - Returns true if the target can instruction select the
3424 /// specified FP immediate natively. If false, the legalizer will
3425 /// materialize the FP immediate as a load from a constant pool.
3426 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
3427                                          bool ForCodeSize) const {
3428   return true;
3429 }
3430 
3431 /// isLegalAddressingMode - Return true if the addressing mode represented by
3432 /// AM is legal for this target, for a load/store of the specified type.
3433 bool HexagonTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3434                                                   const AddrMode &AM, Type *Ty,
3435                                                   unsigned AS, Instruction *I) const {
3436   if (Ty->isSized()) {
3437     // When LSR detects uses of the same base address to access different
3438     // types (e.g. unions), it will assume a conservative type for these
3439     // uses:
3440     //   LSR Use: Kind=Address of void in addrspace(4294967295), ...
3441     // The type Ty passed here would then be "void". Skip the alignment
3442     // checks, but do not return false right away, since that confuses
3443     // LSR into crashing.
3444     Align A = DL.getABITypeAlign(Ty);
3445     // The base offset must be a multiple of the alignment.
3446     if (!isAligned(A, AM.BaseOffs))
3447       return false;
3448     // The shifted offset must fit in 11 bits.
3449     if (!isInt<11>(AM.BaseOffs >> Log2(A)))
3450       return false;
3451   }
3452 
3453   // No global is ever allowed as a base.
3454   if (AM.BaseGV)
3455     return false;
3456 
3457   int Scale = AM.Scale;
3458   if (Scale < 0)
3459     Scale = -Scale;
3460   switch (Scale) {
3461   case 0:  // No scale reg, "r+i", "r", or just "i".
3462     break;
3463   default: // No scaled addressing mode.
3464     return false;
3465   }
3466   return true;
3467 }
3468 
3469 /// Return true if folding a constant offset with the given GlobalAddress is
3470 /// legal.  It is frequently not legal in PIC relocation models.
3471 bool HexagonTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA)
3472       const {
3473   return HTM.getRelocationModel() == Reloc::Static;
3474 }
3475 
3476 /// isLegalICmpImmediate - Return true if the specified immediate is legal
3477 /// icmp immediate, that is the target has icmp instructions which can compare
3478 /// a register against the immediate without having to materialize the
3479 /// immediate into a register.
3480 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
3481   return Imm >= -512 && Imm <= 511;
3482 }
3483 
3484 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3485 /// for tail call optimization. Targets which want to do tail call
3486 /// optimization should implement this function.
3487 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
3488                                  SDValue Callee,
3489                                  CallingConv::ID CalleeCC,
3490                                  bool IsVarArg,
3491                                  bool IsCalleeStructRet,
3492                                  bool IsCallerStructRet,
3493                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
3494                                  const SmallVectorImpl<SDValue> &OutVals,
3495                                  const SmallVectorImpl<ISD::InputArg> &Ins,
3496                                  SelectionDAG& DAG) const {
3497   const Function &CallerF = DAG.getMachineFunction().getFunction();
3498   CallingConv::ID CallerCC = CallerF.getCallingConv();
3499   bool CCMatch = CallerCC == CalleeCC;
3500 
3501   // ***************************************************************************
3502   //  Look for obvious safe cases to perform tail call optimization that do not
3503   //  require ABI changes.
3504   // ***************************************************************************
3505 
3506   // If this is a tail call via a function pointer, then don't do it!
3507   if (!isa<GlobalAddressSDNode>(Callee) &&
3508       !isa<ExternalSymbolSDNode>(Callee)) {
3509     return false;
3510   }
3511 
3512   // Do not optimize if the calling conventions do not match and the conventions
3513   // used are not C or Fast.
3514   if (!CCMatch) {
3515     bool R = (CallerCC == CallingConv::C || CallerCC == CallingConv::Fast);
3516     bool E = (CalleeCC == CallingConv::C || CalleeCC == CallingConv::Fast);
3517     // If R & E, then ok.
3518     if (!R || !E)
3519       return false;
3520   }
3521 
3522   // Do not tail call optimize vararg calls.
3523   if (IsVarArg)
3524     return false;
3525 
3526   // Also avoid tail call optimization if either caller or callee uses struct
3527   // return semantics.
3528   if (IsCalleeStructRet || IsCallerStructRet)
3529     return false;
3530 
3531   // In addition to the cases above, we also disable Tail Call Optimization if
3532   // the calling convention code that at least one outgoing argument needs to
3533   // go on the stack. We cannot check that here because at this point that
3534   // information is not available.
3535   return true;
3536 }
3537 
3538 /// Returns the target specific optimal type for load and store operations as
3539 /// a result of memset, memcpy, and memmove lowering.
3540 ///
3541 /// If DstAlign is zero that means it's safe to destination alignment can
3542 /// satisfy any constraint. Similarly if SrcAlign is zero it means there isn't
3543 /// a need to check it against alignment requirement, probably because the
3544 /// source does not need to be loaded. If 'IsMemset' is true, that means it's
3545 /// expanding a memset. If 'ZeroMemset' is true, that means it's a memset of
3546 /// zero. 'MemcpyStrSrc' indicates whether the memcpy source is constant so it
3547 /// does not need to be loaded.  It returns EVT::Other if the type should be
3548 /// determined using generic target-independent logic.
3549 EVT HexagonTargetLowering::getOptimalMemOpType(
3550     const MemOp &Op, const AttributeList &FuncAttributes) const {
3551   if (Op.size() >= 8 && Op.isAligned(Align(8)))
3552     return MVT::i64;
3553   if (Op.size() >= 4 && Op.isAligned(Align(4)))
3554     return MVT::i32;
3555   if (Op.size() >= 2 && Op.isAligned(Align(2)))
3556     return MVT::i16;
3557   return MVT::Other;
3558 }
3559 
3560 bool HexagonTargetLowering::allowsMemoryAccess(
3561     LLVMContext &Context, const DataLayout &DL, EVT VT, unsigned AddrSpace,
3562     Align Alignment, MachineMemOperand::Flags Flags, bool *Fast) const {
3563   MVT SVT = VT.getSimpleVT();
3564   if (Subtarget.isHVXVectorType(SVT, true))
3565     return allowsHvxMemoryAccess(SVT, Flags, Fast);
3566   return TargetLoweringBase::allowsMemoryAccess(
3567               Context, DL, VT, AddrSpace, Alignment, Flags, Fast);
3568 }
3569 
3570 bool HexagonTargetLowering::allowsMisalignedMemoryAccesses(
3571     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
3572     bool *Fast) const {
3573   MVT SVT = VT.getSimpleVT();
3574   if (Subtarget.isHVXVectorType(SVT, true))
3575     return allowsHvxMisalignedMemoryAccesses(SVT, Flags, Fast);
3576   if (Fast)
3577     *Fast = false;
3578   return false;
3579 }
3580 
3581 std::pair<const TargetRegisterClass*, uint8_t>
3582 HexagonTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
3583       MVT VT) const {
3584   if (Subtarget.isHVXVectorType(VT, true)) {
3585     unsigned BitWidth = VT.getSizeInBits();
3586     unsigned VecWidth = Subtarget.getVectorLength() * 8;
3587 
3588     if (VT.getVectorElementType() == MVT::i1)
3589       return std::make_pair(&Hexagon::HvxQRRegClass, 1);
3590     if (BitWidth == VecWidth)
3591       return std::make_pair(&Hexagon::HvxVRRegClass, 1);
3592     assert(BitWidth == 2 * VecWidth);
3593     return std::make_pair(&Hexagon::HvxWRRegClass, 1);
3594   }
3595 
3596   return TargetLowering::findRepresentativeClass(TRI, VT);
3597 }
3598 
3599 bool HexagonTargetLowering::shouldReduceLoadWidth(SDNode *Load,
3600       ISD::LoadExtType ExtTy, EVT NewVT) const {
3601   // TODO: This may be worth removing. Check regression tests for diffs.
3602   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
3603     return false;
3604 
3605   auto *L = cast<LoadSDNode>(Load);
3606   std::pair<SDValue,int> BO = getBaseAndOffset(L->getBasePtr());
3607   // Small-data object, do not shrink.
3608   if (BO.first.getOpcode() == HexagonISD::CONST32_GP)
3609     return false;
3610   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(BO.first)) {
3611     auto &HTM = static_cast<const HexagonTargetMachine&>(getTargetMachine());
3612     const auto *GO = dyn_cast_or_null<const GlobalObject>(GA->getGlobal());
3613     return !GO || !HTM.getObjFileLowering()->isGlobalInSmallSection(GO, HTM);
3614   }
3615   return true;
3616 }
3617 
3618 Value *HexagonTargetLowering::emitLoadLinked(IRBuilderBase &Builder,
3619                                              Type *ValueTy, Value *Addr,
3620                                              AtomicOrdering Ord) const {
3621   BasicBlock *BB = Builder.GetInsertBlock();
3622   Module *M = BB->getParent()->getParent();
3623   unsigned SZ = ValueTy->getPrimitiveSizeInBits();
3624   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic loads supported");
3625   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_L2_loadw_locked
3626                                    : Intrinsic::hexagon_L4_loadd_locked;
3627   Function *Fn = Intrinsic::getDeclaration(M, IntID);
3628 
3629   auto PtrTy = cast<PointerType>(Addr->getType());
3630   PointerType *NewPtrTy =
3631       Builder.getIntNTy(SZ)->getPointerTo(PtrTy->getAddressSpace());
3632   Addr = Builder.CreateBitCast(Addr, NewPtrTy);
3633 
3634   Value *Call = Builder.CreateCall(Fn, Addr, "larx");
3635 
3636   return Builder.CreateBitCast(Call, ValueTy);
3637 }
3638 
3639 /// Perform a store-conditional operation to Addr. Return the status of the
3640 /// store. This should be 0 if the store succeeded, non-zero otherwise.
3641 Value *HexagonTargetLowering::emitStoreConditional(IRBuilderBase &Builder,
3642                                                    Value *Val, Value *Addr,
3643                                                    AtomicOrdering Ord) const {
3644   BasicBlock *BB = Builder.GetInsertBlock();
3645   Module *M = BB->getParent()->getParent();
3646   Type *Ty = Val->getType();
3647   unsigned SZ = Ty->getPrimitiveSizeInBits();
3648 
3649   Type *CastTy = Builder.getIntNTy(SZ);
3650   assert((SZ == 32 || SZ == 64) && "Only 32/64-bit atomic stores supported");
3651   Intrinsic::ID IntID = (SZ == 32) ? Intrinsic::hexagon_S2_storew_locked
3652                                    : Intrinsic::hexagon_S4_stored_locked;
3653   Function *Fn = Intrinsic::getDeclaration(M, IntID);
3654 
3655   unsigned AS = Addr->getType()->getPointerAddressSpace();
3656   Addr = Builder.CreateBitCast(Addr, CastTy->getPointerTo(AS));
3657   Val = Builder.CreateBitCast(Val, CastTy);
3658 
3659   Value *Call = Builder.CreateCall(Fn, {Addr, Val}, "stcx");
3660   Value *Cmp = Builder.CreateICmpEQ(Call, Builder.getInt32(0), "");
3661   Value *Ext = Builder.CreateZExt(Cmp, Type::getInt32Ty(M->getContext()));
3662   return Ext;
3663 }
3664 
3665 TargetLowering::AtomicExpansionKind
3666 HexagonTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
3667   // Do not expand loads and stores that don't exceed 64 bits.
3668   return LI->getType()->getPrimitiveSizeInBits() > 64
3669              ? AtomicExpansionKind::LLOnly
3670              : AtomicExpansionKind::None;
3671 }
3672 
3673 TargetLowering::AtomicExpansionKind
3674 HexagonTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
3675   // Do not expand loads and stores that don't exceed 64 bits.
3676   return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() > 64
3677              ? AtomicExpansionKind::Expand
3678              : AtomicExpansionKind::None;
3679 }
3680 
3681 TargetLowering::AtomicExpansionKind
3682 HexagonTargetLowering::shouldExpandAtomicCmpXchgInIR(
3683     AtomicCmpXchgInst *AI) const {
3684   return AtomicExpansionKind::LLSC;
3685 }
3686