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