Reduce indentation.
[oota-llvm.git] / lib / Target / Hexagon / HexagonISelLowering.cpp
1 //===-- HexagonISelLowering.cpp - Hexagon DAG Lowering Implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Hexagon uses to lower LLVM code
11 // into a selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "HexagonISelLowering.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonSubtarget.h"
18 #include "HexagonTargetMachine.h"
19 #include "HexagonTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39
40 using namespace llvm;
41
42 #define DEBUG_TYPE "hexagon-lowering"
43
44 static cl::opt<bool>
45 EmitJumpTables("hexagon-emit-jump-tables", cl::init(true), cl::Hidden,
46                cl::desc("Control jump table emission on Hexagon target"));
47
48 namespace {
49 class HexagonCCState : public CCState {
50   int NumNamedVarArgParams;
51
52 public:
53   HexagonCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
54                  const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
55                  LLVMContext &C, int NumNamedVarArgParams)
56       : CCState(CC, isVarArg, MF, TM, locs, C),
57         NumNamedVarArgParams(NumNamedVarArgParams) {}
58
59   int getNumNamedVarArgParams() const { return NumNamedVarArgParams; }
60 };
61 }
62
63 // Implement calling convention for Hexagon.
64 static bool
65 CC_Hexagon(unsigned ValNo, MVT ValVT,
66            MVT LocVT, CCValAssign::LocInfo LocInfo,
67            ISD::ArgFlagsTy ArgFlags, CCState &State);
68
69 static bool
70 CC_Hexagon32(unsigned ValNo, MVT ValVT,
71              MVT LocVT, CCValAssign::LocInfo LocInfo,
72              ISD::ArgFlagsTy ArgFlags, CCState &State);
73
74 static bool
75 CC_Hexagon64(unsigned ValNo, MVT ValVT,
76              MVT LocVT, CCValAssign::LocInfo LocInfo,
77              ISD::ArgFlagsTy ArgFlags, CCState &State);
78
79 static bool
80 RetCC_Hexagon(unsigned ValNo, MVT ValVT,
81               MVT LocVT, CCValAssign::LocInfo LocInfo,
82               ISD::ArgFlagsTy ArgFlags, CCState &State);
83
84 static bool
85 RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
86                 MVT LocVT, CCValAssign::LocInfo LocInfo,
87                 ISD::ArgFlagsTy ArgFlags, CCState &State);
88
89 static bool
90 RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
91                 MVT LocVT, CCValAssign::LocInfo LocInfo,
92                 ISD::ArgFlagsTy ArgFlags, CCState &State);
93
94 static bool
95 CC_Hexagon_VarArg (unsigned ValNo, MVT ValVT,
96             MVT LocVT, CCValAssign::LocInfo LocInfo,
97             ISD::ArgFlagsTy ArgFlags, CCState &State) {
98   HexagonCCState &HState = static_cast<HexagonCCState &>(State);
99
100   // NumNamedVarArgParams can not be zero for a VarArg function.
101   assert((HState.getNumNamedVarArgParams() > 0) &&
102          "NumNamedVarArgParams is not bigger than zero.");
103
104   if ((int)ValNo < HState.getNumNamedVarArgParams()) {
105     // Deal with named arguments.
106     return CC_Hexagon(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State);
107   }
108
109   // Deal with un-named arguments.
110   unsigned ofst;
111   if (ArgFlags.isByVal()) {
112     // If pass-by-value, the size allocated on stack is decided
113     // by ArgFlags.getByValSize(), not by the size of LocVT.
114     assert ((ArgFlags.getByValSize() > 8) &&
115             "ByValSize must be bigger than 8 bytes");
116     ofst = State.AllocateStack(ArgFlags.getByValSize(), 4);
117     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
118     return false;
119   }
120   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
121     LocVT = MVT::i32;
122     ValVT = MVT::i32;
123     if (ArgFlags.isSExt())
124       LocInfo = CCValAssign::SExt;
125     else if (ArgFlags.isZExt())
126       LocInfo = CCValAssign::ZExt;
127     else
128       LocInfo = CCValAssign::AExt;
129   }
130   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
131     ofst = State.AllocateStack(4, 4);
132     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
133     return false;
134   }
135   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
136     ofst = State.AllocateStack(8, 8);
137     State.addLoc(CCValAssign::getMem(ValNo, ValVT, ofst, LocVT, LocInfo));
138     return false;
139   }
140   llvm_unreachable(nullptr);
141 }
142
143
144 static bool
145 CC_Hexagon (unsigned ValNo, MVT ValVT,
146             MVT LocVT, CCValAssign::LocInfo LocInfo,
147             ISD::ArgFlagsTy ArgFlags, CCState &State) {
148
149   if (ArgFlags.isByVal()) {
150     // Passed on stack.
151     assert ((ArgFlags.getByValSize() > 8) &&
152             "ByValSize must be bigger than 8 bytes");
153     unsigned Offset = State.AllocateStack(ArgFlags.getByValSize(), 4);
154     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
155     return false;
156   }
157
158   if (LocVT == MVT::i1 || LocVT == MVT::i8 || LocVT == MVT::i16) {
159     LocVT = MVT::i32;
160     ValVT = MVT::i32;
161     if (ArgFlags.isSExt())
162       LocInfo = CCValAssign::SExt;
163     else if (ArgFlags.isZExt())
164       LocInfo = CCValAssign::ZExt;
165     else
166       LocInfo = CCValAssign::AExt;
167   }
168
169   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
170     if (!CC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
171       return false;
172   }
173
174   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
175     if (!CC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
176       return false;
177   }
178
179   return true;  // CC didn't match.
180 }
181
182
183 static bool CC_Hexagon32(unsigned ValNo, MVT ValVT,
184                          MVT LocVT, CCValAssign::LocInfo LocInfo,
185                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
186
187   static const MCPhysReg RegList[] = {
188     Hexagon::R0, Hexagon::R1, Hexagon::R2, Hexagon::R3, Hexagon::R4,
189     Hexagon::R5
190   };
191   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
192     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
193     return false;
194   }
195
196   unsigned Offset = State.AllocateStack(4, 4);
197   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
198   return false;
199 }
200
201 static bool CC_Hexagon64(unsigned ValNo, MVT ValVT,
202                          MVT LocVT, CCValAssign::LocInfo LocInfo,
203                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
204
205   if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
206     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
207     return false;
208   }
209
210   static const MCPhysReg RegList1[] = {
211     Hexagon::D1, Hexagon::D2
212   };
213   static const MCPhysReg RegList2[] = {
214     Hexagon::R1, Hexagon::R3
215   };
216   if (unsigned Reg = State.AllocateReg(RegList1, RegList2, 2)) {
217     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
218     return false;
219   }
220
221   unsigned Offset = State.AllocateStack(8, 8, Hexagon::D2);
222   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
223   return false;
224 }
225
226 static bool RetCC_Hexagon(unsigned ValNo, MVT ValVT,
227                           MVT LocVT, CCValAssign::LocInfo LocInfo,
228                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
229
230
231   if (LocVT == MVT::i1 ||
232       LocVT == MVT::i8 ||
233       LocVT == MVT::i16) {
234     LocVT = MVT::i32;
235     ValVT = MVT::i32;
236     if (ArgFlags.isSExt())
237       LocInfo = CCValAssign::SExt;
238     else if (ArgFlags.isZExt())
239       LocInfo = CCValAssign::ZExt;
240     else
241       LocInfo = CCValAssign::AExt;
242   }
243
244   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
245     if (!RetCC_Hexagon32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
246     return false;
247   }
248
249   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
250     if (!RetCC_Hexagon64(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))
251     return false;
252   }
253
254   return true;  // CC didn't match.
255 }
256
257 static bool RetCC_Hexagon32(unsigned ValNo, MVT ValVT,
258                             MVT LocVT, CCValAssign::LocInfo LocInfo,
259                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
260
261   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
262     if (unsigned Reg = State.AllocateReg(Hexagon::R0)) {
263       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
264       return false;
265     }
266   }
267
268   unsigned Offset = State.AllocateStack(4, 4);
269   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
270   return false;
271 }
272
273 static bool RetCC_Hexagon64(unsigned ValNo, MVT ValVT,
274                             MVT LocVT, CCValAssign::LocInfo LocInfo,
275                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
276   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
277     if (unsigned Reg = State.AllocateReg(Hexagon::D0)) {
278       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
279       return false;
280     }
281   }
282
283   unsigned Offset = State.AllocateStack(8, 8);
284   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
285   return false;
286 }
287
288 SDValue
289 HexagonTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG)
290 const {
291   return SDValue();
292 }
293
294 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
295 /// by "Src" to address "Dst" of size "Size".  Alignment information is
296 /// specified by the specific parameter attribute. The copy will be passed as
297 /// a byval function parameter.  Sometimes what we are copying is the end of a
298 /// larger object, the part that does not fit in registers.
299 static SDValue
300 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
301                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
302                           SDLoc dl) {
303
304   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
305   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
306                        /*isVolatile=*/false, /*AlwaysInline=*/false,
307                        MachinePointerInfo(), MachinePointerInfo());
308 }
309
310
311 // LowerReturn - Lower ISD::RET. If a struct is larger than 8 bytes and is
312 // passed by value, the function prototype is modified to return void and
313 // the value is stored in memory pointed by a pointer passed by caller.
314 SDValue
315 HexagonTargetLowering::LowerReturn(SDValue Chain,
316                                    CallingConv::ID CallConv, bool isVarArg,
317                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
318                                    const SmallVectorImpl<SDValue> &OutVals,
319                                    SDLoc dl, SelectionDAG &DAG) const {
320
321   // CCValAssign - represent the assignment of the return value to locations.
322   SmallVector<CCValAssign, 16> RVLocs;
323
324   // CCState - Info about the registers and stack slot.
325   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
326                  getTargetMachine(), RVLocs, *DAG.getContext());
327
328   // Analyze return values of ISD::RET
329   CCInfo.AnalyzeReturn(Outs, RetCC_Hexagon);
330
331   SDValue Flag;
332   SmallVector<SDValue, 4> RetOps(1, Chain);
333
334   // Copy the result values into the output registers.
335   for (unsigned i = 0; i != RVLocs.size(); ++i) {
336     CCValAssign &VA = RVLocs[i];
337
338     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
339
340     // Guarantee that all emitted copies are stuck together with flags.
341     Flag = Chain.getValue(1);
342     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
343   }
344
345   RetOps[0] = Chain;  // Update chain.
346
347   // Add the flag if we have it.
348   if (Flag.getNode())
349     RetOps.push_back(Flag);
350
351   return DAG.getNode(HexagonISD::RET_FLAG, dl, MVT::Other, RetOps);
352 }
353
354
355
356
357 /// LowerCallResult - Lower the result values of an ISD::CALL into the
358 /// appropriate copies out of appropriate physical registers.  This assumes that
359 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
360 /// being lowered. Returns a SDNode with the same number of values as the
361 /// ISD::CALL.
362 SDValue
363 HexagonTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
364                                        CallingConv::ID CallConv, bool isVarArg,
365                                        const
366                                        SmallVectorImpl<ISD::InputArg> &Ins,
367                                        SDLoc dl, SelectionDAG &DAG,
368                                        SmallVectorImpl<SDValue> &InVals,
369                                        const SmallVectorImpl<SDValue> &OutVals,
370                                        SDValue Callee) const {
371
372   // Assign locations to each value returned by this call.
373   SmallVector<CCValAssign, 16> RVLocs;
374
375   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
376                  getTargetMachine(), RVLocs, *DAG.getContext());
377
378   CCInfo.AnalyzeCallResult(Ins, RetCC_Hexagon);
379
380   // Copy all of the result registers out of their specified physreg.
381   for (unsigned i = 0; i != RVLocs.size(); ++i) {
382     Chain = DAG.getCopyFromReg(Chain, dl,
383                                RVLocs[i].getLocReg(),
384                                RVLocs[i].getValVT(), InFlag).getValue(1);
385     InFlag = Chain.getValue(2);
386     InVals.push_back(Chain.getValue(0));
387   }
388
389   return Chain;
390 }
391
392 /// LowerCall - Functions arguments are copied from virtual regs to
393 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
394 SDValue
395 HexagonTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
396                                  SmallVectorImpl<SDValue> &InVals) const {
397   SelectionDAG &DAG                     = CLI.DAG;
398   SDLoc &dl                             = CLI.DL;
399   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
400   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
401   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
402   SDValue Chain                         = CLI.Chain;
403   SDValue Callee                        = CLI.Callee;
404   bool &isTailCall                      = CLI.IsTailCall;
405   CallingConv::ID CallConv              = CLI.CallConv;
406   bool isVarArg                         = CLI.IsVarArg;
407
408   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
409
410   // Check for varargs.
411   int NumNamedVarArgParams = -1;
412   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee))
413   {
414     const Function* CalleeFn = nullptr;
415     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, MVT::i32);
416     if ((CalleeFn = dyn_cast<Function>(GA->getGlobal())))
417     {
418       // If a function has zero args and is a vararg function, that's
419       // disallowed so it must be an undeclared function.  Do not assume
420       // varargs if the callee is undefined.
421       if (CalleeFn->isVarArg() &&
422           CalleeFn->getFunctionType()->getNumParams() != 0) {
423         NumNamedVarArgParams = CalleeFn->getFunctionType()->getNumParams();
424       }
425     }
426   }
427
428   // Analyze operands of the call, assigning locations to each operand.
429   SmallVector<CCValAssign, 16> ArgLocs;
430   HexagonCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
431                         getTargetMachine(), ArgLocs, *DAG.getContext(),
432                         NumNamedVarArgParams);
433
434   if (NumNamedVarArgParams > 0)
435     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon_VarArg);
436   else
437     CCInfo.AnalyzeCallOperands(Outs, CC_Hexagon);
438
439
440   if(isTailCall) {
441     bool StructAttrFlag =
442       DAG.getMachineFunction().getFunction()->hasStructRetAttr();
443     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
444                                                    isVarArg, IsStructRet,
445                                                    StructAttrFlag,
446                                                    Outs, OutVals, Ins, DAG);
447     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i){
448       CCValAssign &VA = ArgLocs[i];
449       if (VA.isMemLoc()) {
450         isTailCall = false;
451         break;
452       }
453     }
454     if (isTailCall) {
455       DEBUG(dbgs () << "Eligible for Tail Call\n");
456     } else {
457       DEBUG(dbgs () <<
458             "Argument must be passed on stack. Not eligible for Tail Call\n");
459     }
460   }
461   // Get a count of how many bytes are to be pushed on the stack.
462   unsigned NumBytes = CCInfo.getNextStackOffset();
463   SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
464   SmallVector<SDValue, 8> MemOpChains;
465
466   SDValue StackPtr =
467     DAG.getCopyFromReg(Chain, dl, TM.getRegisterInfo()->getStackRegister(),
468                        getPointerTy());
469
470   // Walk the register/memloc assignments, inserting copies/loads.
471   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
472     CCValAssign &VA = ArgLocs[i];
473     SDValue Arg = OutVals[i];
474     ISD::ArgFlagsTy Flags = Outs[i].Flags;
475
476     // Promote the value if needed.
477     switch (VA.getLocInfo()) {
478       default:
479         // Loc info must be one of Full, SExt, ZExt, or AExt.
480         llvm_unreachable("Unknown loc info!");
481       case CCValAssign::Full:
482         break;
483       case CCValAssign::SExt:
484         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
485         break;
486       case CCValAssign::ZExt:
487         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
488         break;
489       case CCValAssign::AExt:
490         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
491         break;
492     }
493
494     if (VA.isMemLoc()) {
495       unsigned LocMemOffset = VA.getLocMemOffset();
496       SDValue PtrOff = DAG.getConstant(LocMemOffset, StackPtr.getValueType());
497       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
498
499       if (Flags.isByVal()) {
500         // The argument is a struct passed by value. According to LLVM, "Arg"
501         // is is pointer.
502         MemOpChains.push_back(CreateCopyOfByValArgument(Arg, PtrOff, Chain,
503                                                         Flags, DAG, dl));
504       } else {
505         // The argument is not passed by value. "Arg" is a buildin type. It is
506         // not a pointer.
507         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
508                                            MachinePointerInfo(),false, false,
509                                            0));
510       }
511       continue;
512     }
513
514     // Arguments that can be passed on register must be kept at RegsToPass
515     // vector.
516     if (VA.isRegLoc()) {
517       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
518     }
519   }
520
521   // Transform all store nodes into one single node because all store
522   // nodes are independent of each other.
523   if (!MemOpChains.empty()) {
524     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
525   }
526
527   if (!isTailCall)
528     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes,
529                                                         getPointerTy(), true),
530                                  dl);
531
532   // Build a sequence of copy-to-reg nodes chained together with token
533   // chain and flag operands which copy the outgoing args into registers.
534   // The InFlag in necessary since all emitted instructions must be
535   // stuck together.
536   SDValue InFlag;
537   if (!isTailCall) {
538     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
539       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
540                                RegsToPass[i].second, InFlag);
541       InFlag = Chain.getValue(1);
542     }
543   }
544
545   // For tail calls lower the arguments to the 'real' stack slot.
546   if (isTailCall) {
547     // Force all the incoming stack arguments to be loaded from the stack
548     // before any new outgoing arguments are stored to the stack, because the
549     // outgoing stack slots may alias the incoming argument stack slots, and
550     // the alias isn't otherwise explicit. This is slightly more conservative
551     // than necessary, because it means that each store effectively depends
552     // on every argument instead of just those arguments it would clobber.
553     //
554     // Do not flag preceding copytoreg stuff together with the following stuff.
555     InFlag = SDValue();
556     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
557       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
558                                RegsToPass[i].second, InFlag);
559       InFlag = Chain.getValue(1);
560     }
561     InFlag =SDValue();
562   }
563
564   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
565   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
566   // node so that legalize doesn't hack it.
567   if (flag_aligned_memcpy) {
568     const char *MemcpyName =
569       "__hexagon_memcpy_likely_aligned_min32bytes_mult8bytes";
570     Callee =
571       DAG.getTargetExternalSymbol(MemcpyName, getPointerTy());
572     flag_aligned_memcpy = false;
573   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
574     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy());
575   } else if (ExternalSymbolSDNode *S =
576              dyn_cast<ExternalSymbolSDNode>(Callee)) {
577     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
578   }
579
580   // Returns a chain & a flag for retval copy to use.
581   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
582   SmallVector<SDValue, 8> Ops;
583   Ops.push_back(Chain);
584   Ops.push_back(Callee);
585
586   // Add argument registers to the end of the list so that they are
587   // known live into the call.
588   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
589     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
590                                   RegsToPass[i].second.getValueType()));
591   }
592
593   if (InFlag.getNode()) {
594     Ops.push_back(InFlag);
595   }
596
597   if (isTailCall)
598     return DAG.getNode(HexagonISD::TC_RETURN, dl, NodeTys, Ops);
599
600   Chain = DAG.getNode(HexagonISD::CALL, dl, NodeTys, Ops);
601   InFlag = Chain.getValue(1);
602
603   // Create the CALLSEQ_END node.
604   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
605                              DAG.getIntPtrConstant(0, true), InFlag, dl);
606   InFlag = Chain.getValue(1);
607
608   // Handle result values, copying them out of physregs into vregs that we
609   // return.
610   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
611                          InVals, OutVals, Callee);
612 }
613
614 static bool getIndexedAddressParts(SDNode *Ptr, EVT VT,
615                                    bool isSEXTLoad, SDValue &Base,
616                                    SDValue &Offset, bool &isInc,
617                                    SelectionDAG &DAG) {
618   if (Ptr->getOpcode() != ISD::ADD)
619   return false;
620
621   if (VT == MVT::i64 || VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
622     isInc = (Ptr->getOpcode() == ISD::ADD);
623     Base = Ptr->getOperand(0);
624     Offset = Ptr->getOperand(1);
625     // Ensure that Offset is a constant.
626     return (isa<ConstantSDNode>(Offset));
627   }
628
629   return false;
630 }
631
632 // TODO: Put this function along with the other isS* functions in
633 // HexagonISelDAGToDAG.cpp into a common file. Or better still, use the
634 // functions defined in HexagonOperands.td.
635 static bool Is_PostInc_S4_Offset(SDNode * S, int ShiftAmount) {
636   ConstantSDNode *N = cast<ConstantSDNode>(S);
637
638   // immS4 predicate - True if the immediate fits in a 4-bit sign extended.
639   // field.
640   int64_t v = (int64_t)N->getSExtValue();
641   int64_t m = 0;
642   if (ShiftAmount > 0) {
643     m = v % ShiftAmount;
644     v = v >> ShiftAmount;
645   }
646   return (v <= 7) && (v >= -8) && (m == 0);
647 }
648
649 /// getPostIndexedAddressParts - returns true by value, base pointer and
650 /// offset pointer and addressing mode by reference if this node can be
651 /// combined with a load / store to form a post-indexed load / store.
652 bool HexagonTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
653                                                        SDValue &Base,
654                                                        SDValue &Offset,
655                                                        ISD::MemIndexedMode &AM,
656                                                        SelectionDAG &DAG) const
657 {
658   EVT VT;
659   SDValue Ptr;
660   bool isSEXTLoad = false;
661
662   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
663     VT  = LD->getMemoryVT();
664     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
665   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
666     VT  = ST->getMemoryVT();
667     if (ST->getValue().getValueType() == MVT::i64 && ST->isTruncatingStore()) {
668       return false;
669     }
670   } else {
671     return false;
672   }
673
674   bool isInc = false;
675   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
676                                         isInc, DAG);
677   // ShiftAmount = number of left-shifted bits in the Hexagon instruction.
678   int ShiftAmount = VT.getSizeInBits() / 16;
679   if (isLegal && Is_PostInc_S4_Offset(Offset.getNode(), ShiftAmount)) {
680     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
681     return true;
682   }
683
684   return false;
685 }
686
687 SDValue HexagonTargetLowering::LowerINLINEASM(SDValue Op,
688                                               SelectionDAG &DAG) const {
689   SDNode *Node = Op.getNode();
690   MachineFunction &MF = DAG.getMachineFunction();
691   HexagonMachineFunctionInfo *FuncInfo =
692     MF.getInfo<HexagonMachineFunctionInfo>();
693   switch (Node->getOpcode()) {
694     case ISD::INLINEASM: {
695       unsigned NumOps = Node->getNumOperands();
696       if (Node->getOperand(NumOps-1).getValueType() == MVT::Glue)
697         --NumOps;  // Ignore the flag operand.
698
699       for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
700         if (FuncInfo->hasClobberLR())
701           break;
702         unsigned Flags =
703           cast<ConstantSDNode>(Node->getOperand(i))->getZExtValue();
704         unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
705         ++i;  // Skip the ID value.
706
707         switch (InlineAsm::getKind(Flags)) {
708         default: llvm_unreachable("Bad flags!");
709           case InlineAsm::Kind_RegDef:
710           case InlineAsm::Kind_RegUse:
711           case InlineAsm::Kind_Imm:
712           case InlineAsm::Kind_Clobber:
713           case InlineAsm::Kind_Mem: {
714             for (; NumVals; --NumVals, ++i) {}
715             break;
716           }
717           case InlineAsm::Kind_RegDefEarlyClobber: {
718             for (; NumVals; --NumVals, ++i) {
719               unsigned Reg =
720                 cast<RegisterSDNode>(Node->getOperand(i))->getReg();
721
722               // Check it to be lr
723               if (Reg == TM.getRegisterInfo()->getRARegister()) {
724                 FuncInfo->setHasClobberLR(true);
725                 break;
726               }
727             }
728             break;
729           }
730         }
731       }
732     }
733   } // Node->getOpcode
734   return Op;
735 }
736
737
738 //
739 // Taken from the XCore backend.
740 //
741 SDValue HexagonTargetLowering::
742 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
743 {
744   SDValue Chain = Op.getOperand(0);
745   SDValue Table = Op.getOperand(1);
746   SDValue Index = Op.getOperand(2);
747   SDLoc dl(Op);
748   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
749   unsigned JTI = JT->getIndex();
750   MachineFunction &MF = DAG.getMachineFunction();
751   const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
752   SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
753
754   // Mark all jump table targets as address taken.
755   const std::vector<MachineJumpTableEntry> &JTE = MJTI->getJumpTables();
756   const std::vector<MachineBasicBlock*> &JTBBs = JTE[JTI].MBBs;
757   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
758     MachineBasicBlock *MBB = JTBBs[i];
759     MBB->setHasAddressTaken();
760     // This line is needed to set the hasAddressTaken flag on the BasicBlock
761     // object.
762     BlockAddress::get(const_cast<BasicBlock *>(MBB->getBasicBlock()));
763   }
764
765   SDValue JumpTableBase = DAG.getNode(HexagonISD::WrapperJT, dl,
766                                       getPointerTy(), TargetJT);
767   SDValue ShiftIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
768                                    DAG.getConstant(2, MVT::i32));
769   SDValue JTAddress = DAG.getNode(ISD::ADD, dl, MVT::i32, JumpTableBase,
770                                   ShiftIndex);
771   SDValue LoadTarget = DAG.getLoad(MVT::i32, dl, Chain, JTAddress,
772                                    MachinePointerInfo(), false, false, false,
773                                    0);
774   return DAG.getNode(HexagonISD::BR_JT, dl, MVT::Other, Chain, LoadTarget);
775 }
776
777
778 SDValue
779 HexagonTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
780                                                SelectionDAG &DAG) const {
781   SDValue Chain = Op.getOperand(0);
782   SDValue Size = Op.getOperand(1);
783   SDLoc dl(Op);
784
785   unsigned SPReg = getStackPointerRegisterToSaveRestore();
786
787   // Get a reference to the stack pointer.
788   SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
789
790   // Subtract the dynamic size from the actual stack size to
791   // obtain the new stack size.
792   SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
793
794   //
795   // For Hexagon, the outgoing memory arguments area should be on top of the
796   // alloca area on the stack i.e., the outgoing memory arguments should be
797   // at a lower address than the alloca area. Move the alloca area down the
798   // stack by adding back the space reserved for outgoing arguments to SP
799   // here.
800   //
801   // We do not know what the size of the outgoing args is at this point.
802   // So, we add a pseudo instruction ADJDYNALLOC that will adjust the
803   // stack pointer. We patch this instruction with the correct, known
804   // offset in emitPrologue().
805   //
806   // Use a placeholder immediate (zero) for now. This will be patched up
807   // by emitPrologue().
808   SDValue ArgAdjust = DAG.getNode(HexagonISD::ADJDYNALLOC, dl,
809                                   MVT::i32,
810                                   Sub,
811                                   DAG.getConstant(0, MVT::i32));
812
813   // The Sub result contains the new stack start address, so it
814   // must be placed in the stack pointer register.
815   SDValue CopyChain = DAG.getCopyToReg(Chain, dl,
816                                        TM.getRegisterInfo()->getStackRegister(),
817                                        Sub);
818
819   SDValue Ops[2] = { ArgAdjust, CopyChain };
820   return DAG.getMergeValues(Ops, dl);
821 }
822
823 SDValue
824 HexagonTargetLowering::LowerFormalArguments(SDValue Chain,
825                                             CallingConv::ID CallConv,
826                                             bool isVarArg,
827                                             const
828                                             SmallVectorImpl<ISD::InputArg> &Ins,
829                                             SDLoc dl, SelectionDAG &DAG,
830                                             SmallVectorImpl<SDValue> &InVals)
831 const {
832
833   MachineFunction &MF = DAG.getMachineFunction();
834   MachineFrameInfo *MFI = MF.getFrameInfo();
835   MachineRegisterInfo &RegInfo = MF.getRegInfo();
836   HexagonMachineFunctionInfo *FuncInfo =
837     MF.getInfo<HexagonMachineFunctionInfo>();
838
839
840   // Assign locations to all of the incoming arguments.
841   SmallVector<CCValAssign, 16> ArgLocs;
842   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
843                  getTargetMachine(), ArgLocs, *DAG.getContext());
844
845   CCInfo.AnalyzeFormalArguments(Ins, CC_Hexagon);
846
847   // For LLVM, in the case when returning a struct by value (>8byte),
848   // the first argument is a pointer that points to the location on caller's
849   // stack where the return value will be stored. For Hexagon, the location on
850   // caller's stack is passed only when the struct size is smaller than (and
851   // equal to) 8 bytes. If not, no address will be passed into callee and
852   // callee return the result direclty through R0/R1.
853
854   SmallVector<SDValue, 4> MemOps;
855
856   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
857     CCValAssign &VA = ArgLocs[i];
858     ISD::ArgFlagsTy Flags = Ins[i].Flags;
859     unsigned ObjSize;
860     unsigned StackLocation;
861     int FI;
862
863     if (   (VA.isRegLoc() && !Flags.isByVal())
864         || (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() > 8)) {
865       // Arguments passed in registers
866       // 1. int, long long, ptr args that get allocated in register.
867       // 2. Large struct that gets an register to put its address in.
868       EVT RegVT = VA.getLocVT();
869       if (RegVT == MVT::i8 || RegVT == MVT::i16 ||
870           RegVT == MVT::i32 || RegVT == MVT::f32) {
871         unsigned VReg =
872           RegInfo.createVirtualRegister(&Hexagon::IntRegsRegClass);
873         RegInfo.addLiveIn(VA.getLocReg(), VReg);
874         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
875       } else if (RegVT == MVT::i64) {
876         unsigned VReg =
877           RegInfo.createVirtualRegister(&Hexagon::DoubleRegsRegClass);
878         RegInfo.addLiveIn(VA.getLocReg(), VReg);
879         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
880       } else {
881         assert (0);
882       }
883     } else if (VA.isRegLoc() && Flags.isByVal() && Flags.getByValSize() <= 8) {
884       assert (0 && "ByValSize must be bigger than 8 bytes");
885     } else {
886       // Sanity check.
887       assert(VA.isMemLoc());
888
889       if (Flags.isByVal()) {
890         // If it's a byval parameter, then we need to compute the
891         // "real" size, not the size of the pointer.
892         ObjSize = Flags.getByValSize();
893       } else {
894         ObjSize = VA.getLocVT().getStoreSizeInBits() >> 3;
895       }
896
897       StackLocation = HEXAGON_LRFP_SIZE + VA.getLocMemOffset();
898       // Create the frame index object for this incoming parameter...
899       FI = MFI->CreateFixedObject(ObjSize, StackLocation, true);
900
901       // Create the SelectionDAG nodes cordl, responding to a load
902       // from this parameter.
903       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
904
905       if (Flags.isByVal()) {
906         // If it's a pass-by-value aggregate, then do not dereference the stack
907         // location. Instead, we should generate a reference to the stack
908         // location.
909         InVals.push_back(FIN);
910       } else {
911         InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
912                                      MachinePointerInfo(), false, false,
913                                      false, 0));
914       }
915     }
916   }
917
918   if (!MemOps.empty())
919     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
920
921   if (isVarArg) {
922     // This will point to the next argument passed via stack.
923     int FrameIndex = MFI->CreateFixedObject(Hexagon_PointerSize,
924                                             HEXAGON_LRFP_SIZE +
925                                             CCInfo.getNextStackOffset(),
926                                             true);
927     FuncInfo->setVarArgsFrameIndex(FrameIndex);
928   }
929
930   return Chain;
931 }
932
933 SDValue
934 HexagonTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
935   // VASTART stores the address of the VarArgsFrameIndex slot into the
936   // memory location argument.
937   MachineFunction &MF = DAG.getMachineFunction();
938   HexagonMachineFunctionInfo *QFI = MF.getInfo<HexagonMachineFunctionInfo>();
939   SDValue Addr = DAG.getFrameIndex(QFI->getVarArgsFrameIndex(), MVT::i32);
940   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
941   return DAG.getStore(Op.getOperand(0), SDLoc(Op), Addr,
942                       Op.getOperand(1), MachinePointerInfo(SV), false,
943                       false, 0);
944 }
945
946 SDValue
947 HexagonTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
948   EVT ValTy = Op.getValueType();
949   SDLoc dl(Op);
950   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
951   SDValue Res;
952   if (CP->isMachineConstantPoolEntry())
953     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), ValTy,
954                                     CP->getAlignment());
955   else
956     Res = DAG.getTargetConstantPool(CP->getConstVal(), ValTy,
957                                     CP->getAlignment());
958   return DAG.getNode(HexagonISD::CONST32, dl, ValTy, Res);
959 }
960
961 SDValue
962 HexagonTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
963   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
964   MachineFunction &MF = DAG.getMachineFunction();
965   MachineFrameInfo *MFI = MF.getFrameInfo();
966   MFI->setReturnAddressIsTaken(true);
967
968   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   SDLoc dl(Op);
973   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
974   if (Depth) {
975     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
976     SDValue Offset = DAG.getConstant(4, MVT::i32);
977     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
978                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
979                        MachinePointerInfo(), false, false, false, 0);
980   }
981
982   // Return LR, which contains the return address. Mark it an implicit live-in.
983   unsigned Reg = MF.addLiveIn(TRI->getRARegister(), getRegClassFor(MVT::i32));
984   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
985 }
986
987 SDValue
988 HexagonTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
989   const HexagonRegisterInfo  *TRI = TM.getRegisterInfo();
990   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
991   MFI->setFrameAddressIsTaken(true);
992
993   EVT VT = Op.getValueType();
994   SDLoc dl(Op);
995   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
996   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
997                                          TRI->getFrameRegister(), VT);
998   while (Depth--)
999     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1000                             MachinePointerInfo(),
1001                             false, false, false, 0);
1002   return FrameAddr;
1003 }
1004
1005 SDValue HexagonTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1006                                                  SelectionDAG& DAG) const {
1007   SDLoc dl(Op);
1008   return DAG.getNode(HexagonISD::BARRIER, dl, MVT::Other, Op.getOperand(0));
1009 }
1010
1011
1012 SDValue HexagonTargetLowering::LowerGLOBALADDRESS(SDValue Op,
1013                                                   SelectionDAG &DAG) const {
1014   SDValue Result;
1015   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1016   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
1017   SDLoc dl(Op);
1018   Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
1019
1020   const HexagonTargetObjectFile &TLOF =
1021       static_cast<const HexagonTargetObjectFile &>(getObjFileLowering());
1022   if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1023     return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), Result);
1024   }
1025
1026   return DAG.getNode(HexagonISD::CONST32, dl, getPointerTy(), Result);
1027 }
1028
1029 SDValue
1030 HexagonTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1031   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1032   SDValue BA_SD =  DAG.getTargetBlockAddress(BA, MVT::i32);
1033   SDLoc dl(Op);
1034   return DAG.getNode(HexagonISD::CONST32_GP, dl, getPointerTy(), BA_SD);
1035 }
1036
1037 //===----------------------------------------------------------------------===//
1038 // TargetLowering Implementation
1039 //===----------------------------------------------------------------------===//
1040
1041 HexagonTargetLowering::HexagonTargetLowering(
1042     HexagonTargetMachine &targetmachine)
1043     : TargetLowering(targetmachine, new HexagonTargetObjectFile()),
1044       TM(targetmachine) {
1045
1046   const HexagonRegisterInfo *QRI = TM.getRegisterInfo();
1047
1048   // Set up the register classes.
1049   addRegisterClass(MVT::i32, &Hexagon::IntRegsRegClass);
1050   addRegisterClass(MVT::i64, &Hexagon::DoubleRegsRegClass);
1051
1052   if (QRI->Subtarget.hasV5TOps()) {
1053     addRegisterClass(MVT::f32, &Hexagon::IntRegsRegClass);
1054     addRegisterClass(MVT::f64, &Hexagon::DoubleRegsRegClass);
1055   }
1056
1057   addRegisterClass(MVT::i1, &Hexagon::PredRegsRegClass);
1058
1059   computeRegisterProperties();
1060
1061   // Align loop entry
1062   setPrefLoopAlignment(4);
1063
1064   // Limits for inline expansion of memcpy/memmove
1065   MaxStoresPerMemcpy = 6;
1066   MaxStoresPerMemmove = 6;
1067
1068   //
1069   // Library calls for unsupported operations
1070   //
1071
1072   setLibcallName(RTLIB::SINTTOFP_I128_F64, "__hexagon_floattidf");
1073   setLibcallName(RTLIB::SINTTOFP_I128_F32, "__hexagon_floattisf");
1074
1075   setLibcallName(RTLIB::FPTOUINT_F32_I128, "__hexagon_fixunssfti");
1076   setLibcallName(RTLIB::FPTOUINT_F64_I128, "__hexagon_fixunsdfti");
1077
1078   setLibcallName(RTLIB::FPTOSINT_F32_I128, "__hexagon_fixsfti");
1079   setLibcallName(RTLIB::FPTOSINT_F64_I128, "__hexagon_fixdfti");
1080
1081   setLibcallName(RTLIB::SDIV_I32, "__hexagon_divsi3");
1082   setOperationAction(ISD::SDIV, MVT::i32, Expand);
1083   setLibcallName(RTLIB::SREM_I32, "__hexagon_umodsi3");
1084   setOperationAction(ISD::SREM, MVT::i32, Expand);
1085
1086   setLibcallName(RTLIB::SDIV_I64, "__hexagon_divdi3");
1087   setOperationAction(ISD::SDIV, MVT::i64, Expand);
1088   setLibcallName(RTLIB::SREM_I64, "__hexagon_moddi3");
1089   setOperationAction(ISD::SREM, MVT::i64, Expand);
1090
1091   setLibcallName(RTLIB::UDIV_I32, "__hexagon_udivsi3");
1092   setOperationAction(ISD::UDIV, MVT::i32, Expand);
1093
1094   setLibcallName(RTLIB::UDIV_I64, "__hexagon_udivdi3");
1095   setOperationAction(ISD::UDIV, MVT::i64, Expand);
1096
1097   setLibcallName(RTLIB::UREM_I32, "__hexagon_umodsi3");
1098   setOperationAction(ISD::UREM, MVT::i32, Expand);
1099
1100   setLibcallName(RTLIB::UREM_I64, "__hexagon_umoddi3");
1101   setOperationAction(ISD::UREM, MVT::i64, Expand);
1102
1103   setLibcallName(RTLIB::DIV_F32, "__hexagon_divsf3");
1104   setOperationAction(ISD::FDIV, MVT::f32, Expand);
1105
1106   setLibcallName(RTLIB::DIV_F64, "__hexagon_divdf3");
1107   setOperationAction(ISD::FDIV, MVT::f64, Expand);
1108
1109   setOperationAction(ISD::FSQRT, MVT::f32, Expand);
1110   setOperationAction(ISD::FSQRT, MVT::f64, Expand);
1111   setOperationAction(ISD::FSIN, MVT::f32, Expand);
1112   setOperationAction(ISD::FSIN, MVT::f64, Expand);
1113
1114   if (QRI->Subtarget.hasV5TOps()) {
1115     // Hexagon V5 Support.
1116     setOperationAction(ISD::FADD, MVT::f32, Legal);
1117     setOperationAction(ISD::FADD, MVT::f64, Legal);
1118     setOperationAction(ISD::FP_EXTEND, MVT::f32, Legal);
1119     setCondCodeAction(ISD::SETOEQ, MVT::f32, Legal);
1120     setCondCodeAction(ISD::SETOEQ, MVT::f64, Legal);
1121     setCondCodeAction(ISD::SETUEQ, MVT::f32, Legal);
1122     setCondCodeAction(ISD::SETUEQ, MVT::f64, Legal);
1123
1124     setCondCodeAction(ISD::SETOGE, MVT::f32, Legal);
1125     setCondCodeAction(ISD::SETOGE, MVT::f64, Legal);
1126     setCondCodeAction(ISD::SETUGE, MVT::f32, Legal);
1127     setCondCodeAction(ISD::SETUGE, MVT::f64, Legal);
1128
1129     setCondCodeAction(ISD::SETOGT, MVT::f32, Legal);
1130     setCondCodeAction(ISD::SETOGT, MVT::f64, Legal);
1131     setCondCodeAction(ISD::SETUGT, MVT::f32, Legal);
1132     setCondCodeAction(ISD::SETUGT, MVT::f64, Legal);
1133
1134     setCondCodeAction(ISD::SETOLE, MVT::f32, Legal);
1135     setCondCodeAction(ISD::SETOLE, MVT::f64, Legal);
1136     setCondCodeAction(ISD::SETOLT, MVT::f32, Legal);
1137     setCondCodeAction(ISD::SETOLT, MVT::f64, Legal);
1138
1139     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
1140     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
1141
1142     setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
1143     setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
1144     setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
1145     setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
1146
1147     setOperationAction(ISD::FP_TO_UINT, MVT::i8, Promote);
1148     setOperationAction(ISD::FP_TO_SINT, MVT::i8, Promote);
1149     setOperationAction(ISD::UINT_TO_FP, MVT::i8, Promote);
1150     setOperationAction(ISD::SINT_TO_FP, MVT::i8, Promote);
1151
1152     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
1153     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
1154     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
1155     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
1156
1157     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1158     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1159     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1160     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1161
1162     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1163     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1164     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1165     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1166
1167     setOperationAction(ISD::FABS, MVT::f32, Legal);
1168     setOperationAction(ISD::FABS, MVT::f64, Expand);
1169
1170     setOperationAction(ISD::FNEG, MVT::f32, Legal);
1171     setOperationAction(ISD::FNEG, MVT::f64, Expand);
1172   } else {
1173
1174     // Expand fp<->uint.
1175     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Expand);
1176     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
1177
1178     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
1179     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
1180
1181     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__hexagon_floatdisf");
1182     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__hexagon_floatundisf");
1183
1184     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__hexagon_floatunsisf");
1185     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__hexagon_floatsisf");
1186
1187     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__hexagon_floatdidf");
1188     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__hexagon_floatundidf");
1189
1190     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__hexagon_floatunsidf");
1191     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__hexagon_floatsidf");
1192
1193     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__hexagon_fixunssfsi");
1194     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__hexagon_fixunssfdi");
1195
1196     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__hexagon_fixdfdi");
1197     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__hexagon_fixsfdi");
1198
1199     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__hexagon_fixunsdfsi");
1200     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__hexagon_fixunsdfdi");
1201
1202     setLibcallName(RTLIB::ADD_F64, "__hexagon_adddf3");
1203     setOperationAction(ISD::FADD, MVT::f64, Expand);
1204
1205     setLibcallName(RTLIB::ADD_F32, "__hexagon_addsf3");
1206     setOperationAction(ISD::FADD, MVT::f32, Expand);
1207
1208     setLibcallName(RTLIB::FPEXT_F32_F64, "__hexagon_extendsfdf2");
1209     setOperationAction(ISD::FP_EXTEND, MVT::f32, Expand);
1210
1211     setLibcallName(RTLIB::OEQ_F32, "__hexagon_eqsf2");
1212     setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
1213
1214     setLibcallName(RTLIB::OEQ_F64, "__hexagon_eqdf2");
1215     setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
1216
1217     setLibcallName(RTLIB::OGE_F32, "__hexagon_gesf2");
1218     setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
1219
1220     setLibcallName(RTLIB::OGE_F64, "__hexagon_gedf2");
1221     setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
1222
1223     setLibcallName(RTLIB::OGT_F32, "__hexagon_gtsf2");
1224     setCondCodeAction(ISD::SETOGT, MVT::f32, Expand);
1225
1226     setLibcallName(RTLIB::OGT_F64, "__hexagon_gtdf2");
1227     setCondCodeAction(ISD::SETOGT, MVT::f64, Expand);
1228
1229     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__hexagon_fixdfsi");
1230     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Expand);
1231
1232     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__hexagon_fixsfsi");
1233     setOperationAction(ISD::FP_TO_SINT, MVT::f32, Expand);
1234
1235     setLibcallName(RTLIB::OLE_F64, "__hexagon_ledf2");
1236     setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
1237
1238     setLibcallName(RTLIB::OLE_F32, "__hexagon_lesf2");
1239     setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
1240
1241     setLibcallName(RTLIB::OLT_F64, "__hexagon_ltdf2");
1242     setCondCodeAction(ISD::SETOLT, MVT::f64, Expand);
1243
1244     setLibcallName(RTLIB::OLT_F32, "__hexagon_ltsf2");
1245     setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
1246
1247     setLibcallName(RTLIB::MUL_F64, "__hexagon_muldf3");
1248     setOperationAction(ISD::FMUL, MVT::f64, Expand);
1249
1250     setLibcallName(RTLIB::MUL_F32, "__hexagon_mulsf3");
1251     setOperationAction(ISD::MUL, MVT::f32, Expand);
1252
1253     setLibcallName(RTLIB::UNE_F64, "__hexagon_nedf2");
1254     setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
1255
1256     setLibcallName(RTLIB::UNE_F32, "__hexagon_nesf2");
1257
1258     setLibcallName(RTLIB::SUB_F64, "__hexagon_subdf3");
1259     setOperationAction(ISD::SUB, MVT::f64, Expand);
1260
1261     setLibcallName(RTLIB::SUB_F32, "__hexagon_subsf3");
1262     setOperationAction(ISD::SUB, MVT::f32, Expand);
1263
1264     setLibcallName(RTLIB::FPROUND_F64_F32, "__hexagon_truncdfsf2");
1265     setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
1266
1267     setLibcallName(RTLIB::UO_F64, "__hexagon_unorddf2");
1268     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
1269
1270     setLibcallName(RTLIB::O_F64, "__hexagon_unorddf2");
1271     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
1272
1273     setLibcallName(RTLIB::O_F32, "__hexagon_unordsf2");
1274     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
1275
1276     setLibcallName(RTLIB::UO_F32, "__hexagon_unordsf2");
1277     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
1278
1279     setOperationAction(ISD::FABS, MVT::f32, Expand);
1280     setOperationAction(ISD::FABS, MVT::f64, Expand);
1281     setOperationAction(ISD::FNEG, MVT::f32, Expand);
1282     setOperationAction(ISD::FNEG, MVT::f64, Expand);
1283   }
1284
1285   setLibcallName(RTLIB::SREM_I32, "__hexagon_modsi3");
1286   setOperationAction(ISD::SREM, MVT::i32, Expand);
1287
1288   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
1289   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
1290   setIndexedLoadAction(ISD::POST_INC, MVT::i32, Legal);
1291   setIndexedLoadAction(ISD::POST_INC, MVT::i64, Legal);
1292
1293   setIndexedStoreAction(ISD::POST_INC, MVT::i8, Legal);
1294   setIndexedStoreAction(ISD::POST_INC, MVT::i16, Legal);
1295   setIndexedStoreAction(ISD::POST_INC, MVT::i32, Legal);
1296   setIndexedStoreAction(ISD::POST_INC, MVT::i64, Legal);
1297
1298   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
1299
1300   // Turn FP extload into load/fextend.
1301   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1302   // Hexagon has a i1 sign extending load.
1303   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
1304   // Turn FP truncstore into trunc + store.
1305   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1306
1307   // Custom legalize GlobalAddress nodes into CONST32.
1308   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1309   setOperationAction(ISD::GlobalAddress, MVT::i8, Custom);
1310   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1311   // Truncate action?
1312   setOperationAction(ISD::TRUNCATE, MVT::i64, Expand);
1313
1314   // Hexagon doesn't have sext_inreg, replace them with shl/sra.
1315   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1316
1317   // Hexagon has no REM or DIVREM operations.
1318   setOperationAction(ISD::UREM, MVT::i32, Expand);
1319   setOperationAction(ISD::SREM, MVT::i32, Expand);
1320   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1321   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1322   setOperationAction(ISD::SREM, MVT::i64, Expand);
1323   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1324   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1325
1326   setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1327
1328   // Lower SELECT_CC to SETCC and SELECT.
1329   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1330   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
1331   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
1332
1333   if (QRI->Subtarget.hasV5TOps()) {
1334
1335     // We need to make the operation type of SELECT node to be Custom,
1336     // such that we don't go into the infinite loop of
1337     // select ->  setcc -> select_cc -> select loop.
1338     setOperationAction(ISD::SELECT, MVT::f32, Custom);
1339     setOperationAction(ISD::SELECT, MVT::f64, Custom);
1340
1341     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
1342     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
1343
1344   } else {
1345
1346     // Hexagon has no select or setcc: expand to SELECT_CC.
1347     setOperationAction(ISD::SELECT, MVT::f32, Expand);
1348     setOperationAction(ISD::SELECT, MVT::f64, Expand);
1349   }
1350
1351   if (EmitJumpTables) {
1352     setOperationAction(ISD::BR_JT, MVT::Other, Custom);
1353   } else {
1354     setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1355   }
1356   // Increase jump tables cutover to 5, was 4.
1357   setMinimumJumpTableEntries(5);
1358
1359   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
1360   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
1361   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1362   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
1363   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
1364
1365   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
1366
1367   setOperationAction(ISD::FSIN, MVT::f64, Expand);
1368   setOperationAction(ISD::FCOS, MVT::f64, Expand);
1369   setOperationAction(ISD::FREM, MVT::f64, Expand);
1370   setOperationAction(ISD::FSIN, MVT::f32, Expand);
1371   setOperationAction(ISD::FCOS, MVT::f32, Expand);
1372   setOperationAction(ISD::FREM, MVT::f32, Expand);
1373   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1374   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1375
1376   // In V4, we have double word add/sub with carry. The problem with
1377   // modelling this instruction is that it produces 2 results - Rdd and Px.
1378   // To model update of Px, we will have to use Defs[p0..p3] which will
1379   // cause any predicate live range to spill. So, we pretend we dont't
1380   // have these instructions.
1381   setOperationAction(ISD::ADDE, MVT::i8, Expand);
1382   setOperationAction(ISD::ADDE, MVT::i16, Expand);
1383   setOperationAction(ISD::ADDE, MVT::i32, Expand);
1384   setOperationAction(ISD::ADDE, MVT::i64, Expand);
1385   setOperationAction(ISD::SUBE, MVT::i8, Expand);
1386   setOperationAction(ISD::SUBE, MVT::i16, Expand);
1387   setOperationAction(ISD::SUBE, MVT::i32, Expand);
1388   setOperationAction(ISD::SUBE, MVT::i64, Expand);
1389   setOperationAction(ISD::ADDC, MVT::i8, Expand);
1390   setOperationAction(ISD::ADDC, MVT::i16, Expand);
1391   setOperationAction(ISD::ADDC, MVT::i32, Expand);
1392   setOperationAction(ISD::ADDC, MVT::i64, Expand);
1393   setOperationAction(ISD::SUBC, MVT::i8, Expand);
1394   setOperationAction(ISD::SUBC, MVT::i16, Expand);
1395   setOperationAction(ISD::SUBC, MVT::i32, Expand);
1396   setOperationAction(ISD::SUBC, MVT::i64, Expand);
1397
1398   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1399   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
1400   setOperationAction(ISD::CTTZ, MVT::i32, Expand);
1401   setOperationAction(ISD::CTTZ, MVT::i64, Expand);
1402   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1403   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
1404   setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1405   setOperationAction(ISD::CTLZ, MVT::i64, Expand);
1406   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1407   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
1408   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1409   setOperationAction(ISD::ROTR, MVT::i32, Expand);
1410   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1411   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1412   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1413   setOperationAction(ISD::FPOW, MVT::f64, Expand);
1414   setOperationAction(ISD::FPOW, MVT::f32, Expand);
1415
1416   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1417   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1418   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1419
1420   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1421   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1422
1423   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1424   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1425
1426   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
1427
1428   if (TM.getSubtargetImpl()->isSubtargetV2()) {
1429     setExceptionPointerRegister(Hexagon::R20);
1430     setExceptionSelectorRegister(Hexagon::R21);
1431   } else {
1432     setExceptionPointerRegister(Hexagon::R0);
1433     setExceptionSelectorRegister(Hexagon::R1);
1434   }
1435
1436   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1437   setOperationAction(ISD::VASTART, MVT::Other, Custom);
1438
1439   // Use the default implementation.
1440   setOperationAction(ISD::VAARG, MVT::Other, Expand);
1441   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
1442   setOperationAction(ISD::VAEND, MVT::Other, Expand);
1443   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
1444   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
1445
1446   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1447   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
1448
1449   setMinFunctionAlignment(2);
1450
1451   // Needed for DYNAMIC_STACKALLOC expansion.
1452   unsigned StackRegister = TM.getRegisterInfo()->getStackRegister();
1453   setStackPointerRegisterToSaveRestore(StackRegister);
1454   setSchedulingPreference(Sched::VLIW);
1455 }
1456
1457 const char*
1458 HexagonTargetLowering::getTargetNodeName(unsigned Opcode) const {
1459   switch (Opcode) {
1460     default: return nullptr;
1461     case HexagonISD::CONST32:     return "HexagonISD::CONST32";
1462     case HexagonISD::CONST32_GP: return "HexagonISD::CONST32_GP";
1463     case HexagonISD::CONST32_Int_Real: return "HexagonISD::CONST32_Int_Real";
1464     case HexagonISD::ADJDYNALLOC: return "HexagonISD::ADJDYNALLOC";
1465     case HexagonISD::CMPICC:      return "HexagonISD::CMPICC";
1466     case HexagonISD::CMPFCC:      return "HexagonISD::CMPFCC";
1467     case HexagonISD::BRICC:       return "HexagonISD::BRICC";
1468     case HexagonISD::BRFCC:       return "HexagonISD::BRFCC";
1469     case HexagonISD::SELECT_ICC:  return "HexagonISD::SELECT_ICC";
1470     case HexagonISD::SELECT_FCC:  return "HexagonISD::SELECT_FCC";
1471     case HexagonISD::Hi:          return "HexagonISD::Hi";
1472     case HexagonISD::Lo:          return "HexagonISD::Lo";
1473     case HexagonISD::FTOI:        return "HexagonISD::FTOI";
1474     case HexagonISD::ITOF:        return "HexagonISD::ITOF";
1475     case HexagonISD::CALL:        return "HexagonISD::CALL";
1476     case HexagonISD::RET_FLAG:    return "HexagonISD::RET_FLAG";
1477     case HexagonISD::BR_JT:       return "HexagonISD::BR_JT";
1478     case HexagonISD::TC_RETURN:   return "HexagonISD::TC_RETURN";
1479   case HexagonISD::EH_RETURN: return "HexagonISD::EH_RETURN";
1480   }
1481 }
1482
1483 bool
1484 HexagonTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
1485   EVT MTy1 = EVT::getEVT(Ty1);
1486   EVT MTy2 = EVT::getEVT(Ty2);
1487   if (!MTy1.isSimple() || !MTy2.isSimple()) {
1488     return false;
1489   }
1490   return ((MTy1.getSimpleVT() == MVT::i64) && (MTy2.getSimpleVT() == MVT::i32));
1491 }
1492
1493 bool HexagonTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1494   if (!VT1.isSimple() || !VT2.isSimple()) {
1495     return false;
1496   }
1497   return ((VT1.getSimpleVT() == MVT::i64) && (VT2.getSimpleVT() == MVT::i32));
1498 }
1499
1500 bool
1501 HexagonTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
1502   // Assuming the caller does not have either a signext or zeroext modifier, and
1503   // only one value is accepted, any reasonable truncation is allowed.
1504   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1505     return false;
1506
1507   // FIXME: in principle up to 64-bit could be made safe, but it would be very
1508   // fragile at the moment: any support for multiple value returns would be
1509   // liable to disallow tail calls involving i64 -> iN truncation in many cases.
1510   return Ty1->getPrimitiveSizeInBits() <= 32;
1511 }
1512
1513 SDValue
1514 HexagonTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
1515   SDValue Chain     = Op.getOperand(0);
1516   SDValue Offset    = Op.getOperand(1);
1517   SDValue Handler   = Op.getOperand(2);
1518   SDLoc dl(Op);
1519
1520   // Mark function as containing a call to EH_RETURN.
1521   HexagonMachineFunctionInfo *FuncInfo =
1522     DAG.getMachineFunction().getInfo<HexagonMachineFunctionInfo>();
1523   FuncInfo->setHasEHReturn();
1524
1525   unsigned OffsetReg = Hexagon::R28;
1526
1527   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(),
1528                                   DAG.getRegister(Hexagon::R30, getPointerTy()),
1529                                   DAG.getIntPtrConstant(4));
1530   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
1531                        false, false, 0);
1532   Chain = DAG.getCopyToReg(Chain, dl, OffsetReg, Offset);
1533
1534   // Not needed we already use it as explict input to EH_RETURN.
1535   // MF.getRegInfo().addLiveOut(OffsetReg);
1536
1537   return DAG.getNode(HexagonISD::EH_RETURN, dl, MVT::Other, Chain);
1538 }
1539
1540 SDValue
1541 HexagonTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1542   switch (Op.getOpcode()) {
1543     default: llvm_unreachable("Should not custom lower this!");
1544     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1545     case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
1546       // Frame & Return address.  Currently unimplemented.
1547     case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1548     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1549     case ISD::GlobalTLSAddress:
1550                           llvm_unreachable("TLS not implemented for Hexagon.");
1551     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
1552     case ISD::GlobalAddress:      return LowerGLOBALADDRESS(Op, DAG);
1553     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
1554     case ISD::VASTART:            return LowerVASTART(Op, DAG);
1555     case ISD::BR_JT:              return LowerBR_JT(Op, DAG);
1556
1557     case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1558     case ISD::SELECT:             return Op;
1559     case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1560     case ISD::INLINEASM:          return LowerINLINEASM(Op, DAG);
1561
1562   }
1563 }
1564
1565
1566
1567 //===----------------------------------------------------------------------===//
1568 //                           Hexagon Scheduler Hooks
1569 //===----------------------------------------------------------------------===//
1570 MachineBasicBlock *
1571 HexagonTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1572                                                    MachineBasicBlock *BB)
1573 const {
1574   switch (MI->getOpcode()) {
1575     case Hexagon::ADJDYNALLOC: {
1576       MachineFunction *MF = BB->getParent();
1577       HexagonMachineFunctionInfo *FuncInfo =
1578         MF->getInfo<HexagonMachineFunctionInfo>();
1579       FuncInfo->addAllocaAdjustInst(MI);
1580       return BB;
1581     }
1582     default: llvm_unreachable("Unexpected instr type to insert");
1583   } // switch
1584 }
1585
1586 //===----------------------------------------------------------------------===//
1587 // Inline Assembly Support
1588 //===----------------------------------------------------------------------===//
1589
1590 std::pair<unsigned, const TargetRegisterClass*>
1591 HexagonTargetLowering::getRegForInlineAsmConstraint(const
1592                                                     std::string &Constraint,
1593                                                     MVT VT) const {
1594   if (Constraint.size() == 1) {
1595     switch (Constraint[0]) {
1596     case 'r':   // R0-R31
1597        switch (VT.SimpleTy) {
1598        default:
1599          llvm_unreachable("getRegForInlineAsmConstraint Unhandled data type");
1600        case MVT::i32:
1601        case MVT::i16:
1602        case MVT::i8:
1603        case MVT::f32:
1604          return std::make_pair(0U, &Hexagon::IntRegsRegClass);
1605        case MVT::i64:
1606        case MVT::f64:
1607          return std::make_pair(0U, &Hexagon::DoubleRegsRegClass);
1608       }
1609     default:
1610       llvm_unreachable("Unknown asm register class");
1611     }
1612   }
1613
1614   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1615 }
1616
1617 /// isFPImmLegal - Returns true if the target can instruction select the
1618 /// specified FP immediate natively. If false, the legalizer will
1619 /// materialize the FP immediate as a load from a constant pool.
1620 bool HexagonTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1621   const HexagonRegisterInfo* QRI = TM.getRegisterInfo();
1622   return QRI->Subtarget.hasV5TOps();
1623 }
1624
1625 /// isLegalAddressingMode - Return true if the addressing mode represented by
1626 /// AM is legal for this target, for a load/store of the specified type.
1627 bool HexagonTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1628                                                   Type *Ty) const {
1629   // Allows a signed-extended 11-bit immediate field.
1630   if (AM.BaseOffs <= -(1LL << 13) || AM.BaseOffs >= (1LL << 13)-1) {
1631     return false;
1632   }
1633
1634   // No global is ever allowed as a base.
1635   if (AM.BaseGV) {
1636     return false;
1637   }
1638
1639   int Scale = AM.Scale;
1640   if (Scale < 0) Scale = -Scale;
1641   switch (Scale) {
1642   case 0:  // No scale reg, "r+i", "r", or just "i".
1643     break;
1644   default: // No scaled addressing mode.
1645     return false;
1646   }
1647   return true;
1648 }
1649
1650 /// isLegalICmpImmediate - Return true if the specified immediate is legal
1651 /// icmp immediate, that is the target has icmp instructions which can compare
1652 /// a register against the immediate without having to materialize the
1653 /// immediate into a register.
1654 bool HexagonTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1655   return Imm >= -512 && Imm <= 511;
1656 }
1657
1658 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1659 /// for tail call optimization. Targets which want to do tail call
1660 /// optimization should implement this function.
1661 bool HexagonTargetLowering::IsEligibleForTailCallOptimization(
1662                                  SDValue Callee,
1663                                  CallingConv::ID CalleeCC,
1664                                  bool isVarArg,
1665                                  bool isCalleeStructRet,
1666                                  bool isCallerStructRet,
1667                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
1668                                  const SmallVectorImpl<SDValue> &OutVals,
1669                                  const SmallVectorImpl<ISD::InputArg> &Ins,
1670                                  SelectionDAG& DAG) const {
1671   const Function *CallerF = DAG.getMachineFunction().getFunction();
1672   CallingConv::ID CallerCC = CallerF->getCallingConv();
1673   bool CCMatch = CallerCC == CalleeCC;
1674
1675   // ***************************************************************************
1676   //  Look for obvious safe cases to perform tail call optimization that do not
1677   //  require ABI changes.
1678   // ***************************************************************************
1679
1680   // If this is a tail call via a function pointer, then don't do it!
1681   if (!(dyn_cast<GlobalAddressSDNode>(Callee))
1682       && !(dyn_cast<ExternalSymbolSDNode>(Callee))) {
1683     return false;
1684   }
1685
1686   // Do not optimize if the calling conventions do not match.
1687   if (!CCMatch)
1688     return false;
1689
1690   // Do not tail call optimize vararg calls.
1691   if (isVarArg)
1692     return false;
1693
1694   // Also avoid tail call optimization if either caller or callee uses struct
1695   // return semantics.
1696   if (isCalleeStructRet || isCallerStructRet)
1697     return false;
1698
1699   // In addition to the cases above, we also disable Tail Call Optimization if
1700   // the calling convention code that at least one outgoing argument needs to
1701   // go on the stack. We cannot check that here because at this point that
1702   // information is not available.
1703   return true;
1704 }