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