Mips16ISelLowering.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- Mips16ISelLowering.h - Mips16 DAG Lowering Interface ----*- C++ -*-===//
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// Subclass of MipsTargetLowering specialized for mips16.
11//
12//===----------------------------------------------------------------------===//
13#include "Mips16ISelLowering.h"
14#include "MCTargetDesc/MipsBaseInfo.h"
15#include "MipsRegisterInfo.h"
16#include "MipsTargetMachine.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/CodeGen/MachineInstrBuilder.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Target/TargetInstrInfo.h"
21#include <string>
22
23using namespace llvm;
24
25#define DEBUG_TYPE "mips-lower"
26
27static cl::opt<bool> DontExpandCondPseudos16(
28  "mips16-dont-expand-cond-pseudo",
29  cl::init(false),
30  cl::desc("Dont expand conditional move related "
31           "pseudos for Mips 16"),
32  cl::Hidden);
33
34namespace {
35struct Mips16Libcall {
36  RTLIB::Libcall Libcall;
37  const char *Name;
38
39  bool operator<(const Mips16Libcall &RHS) const {
40    return std::strcmp(Name, RHS.Name) < 0;
41  }
42};
43
44struct Mips16IntrinsicHelperType{
45  const char* Name;
46  const char* Helper;
47
48  bool operator<(const Mips16IntrinsicHelperType &RHS) const {
49    return std::strcmp(Name, RHS.Name) < 0;
50  }
51  bool operator==(const Mips16IntrinsicHelperType &RHS) const {
52    return std::strcmp(Name, RHS.Name) == 0;
53  }
54};
55}
56
57// Libcalls for which no helper is generated. Sorted by name for binary search.
58static const Mips16Libcall HardFloatLibCalls[] = {
59  { RTLIB::ADD_F64, "__mips16_adddf3" },
60  { RTLIB::ADD_F32, "__mips16_addsf3" },
61  { RTLIB::DIV_F64, "__mips16_divdf3" },
62  { RTLIB::DIV_F32, "__mips16_divsf3" },
63  { RTLIB::OEQ_F64, "__mips16_eqdf2" },
64  { RTLIB::OEQ_F32, "__mips16_eqsf2" },
65  { RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2" },
66  { RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi" },
67  { RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi" },
68  { RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf" },
69  { RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf" },
70  { RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf" },
71  { RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf" },
72  { RTLIB::OGE_F64, "__mips16_gedf2" },
73  { RTLIB::OGE_F32, "__mips16_gesf2" },
74  { RTLIB::OGT_F64, "__mips16_gtdf2" },
75  { RTLIB::OGT_F32, "__mips16_gtsf2" },
76  { RTLIB::OLE_F64, "__mips16_ledf2" },
77  { RTLIB::OLE_F32, "__mips16_lesf2" },
78  { RTLIB::OLT_F64, "__mips16_ltdf2" },
79  { RTLIB::OLT_F32, "__mips16_ltsf2" },
80  { RTLIB::MUL_F64, "__mips16_muldf3" },
81  { RTLIB::MUL_F32, "__mips16_mulsf3" },
82  { RTLIB::UNE_F64, "__mips16_nedf2" },
83  { RTLIB::UNE_F32, "__mips16_nesf2" },
84  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_dc" }, // No associated libcall.
85  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_df" }, // No associated libcall.
86  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_sc" }, // No associated libcall.
87  { RTLIB::UNKNOWN_LIBCALL, "__mips16_ret_sf" }, // No associated libcall.
88  { RTLIB::SUB_F64, "__mips16_subdf3" },
89  { RTLIB::SUB_F32, "__mips16_subsf3" },
90  { RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2" },
91  { RTLIB::UO_F64, "__mips16_unorddf2" },
92  { RTLIB::UO_F32, "__mips16_unordsf2" }
93};
94
95static const Mips16IntrinsicHelperType Mips16IntrinsicHelper[] = {
96  {"__fixunsdfsi", "__mips16_call_stub_2" },
97  {"ceil",  "__mips16_call_stub_df_2"},
98  {"ceilf", "__mips16_call_stub_sf_1"},
99  {"copysign",  "__mips16_call_stub_df_10"},
100  {"copysignf", "__mips16_call_stub_sf_5"},
101  {"cos",  "__mips16_call_stub_df_2"},
102  {"cosf", "__mips16_call_stub_sf_1"},
103  {"exp2",  "__mips16_call_stub_df_2"},
104  {"exp2f", "__mips16_call_stub_sf_1"},
105  {"floor",  "__mips16_call_stub_df_2"},
106  {"floorf", "__mips16_call_stub_sf_1"},
107  {"log2",  "__mips16_call_stub_df_2"},
108  {"log2f", "__mips16_call_stub_sf_1"},
109  {"nearbyint",  "__mips16_call_stub_df_2"},
110  {"nearbyintf", "__mips16_call_stub_sf_1"},
111  {"rint",  "__mips16_call_stub_df_2"},
112  {"rintf", "__mips16_call_stub_sf_1"},
113  {"sin",  "__mips16_call_stub_df_2"},
114  {"sinf", "__mips16_call_stub_sf_1"},
115  {"sqrt",  "__mips16_call_stub_df_2"},
116  {"sqrtf", "__mips16_call_stub_sf_1"},
117  {"trunc",  "__mips16_call_stub_df_2"},
118  {"truncf", "__mips16_call_stub_sf_1"},
119};
120
121Mips16TargetLowering::Mips16TargetLowering(MipsTargetMachine &TM)
122  : MipsTargetLowering(TM) {
123  //
124  // set up as if mips32 and then revert so we can test the mechanism
125  // for switching
126  addRegisterClass(MVT::i32, &Mips::GPR32RegClass);
127  addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
128  computeRegisterProperties();
129  clearRegisterClasses();
130
131  // Set up the register classes
132  addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
133
134  if (Subtarget->inMips16HardFloat())
135    setMips16HardFloatLibCalls();
136
137  setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Expand);
138  setOperationAction(ISD::ATOMIC_CMP_SWAP,    MVT::i32,   Expand);
139  setOperationAction(ISD::ATOMIC_SWAP,        MVT::i32,   Expand);
140  setOperationAction(ISD::ATOMIC_LOAD_ADD,    MVT::i32,   Expand);
141  setOperationAction(ISD::ATOMIC_LOAD_SUB,    MVT::i32,   Expand);
142  setOperationAction(ISD::ATOMIC_LOAD_AND,    MVT::i32,   Expand);
143  setOperationAction(ISD::ATOMIC_LOAD_OR,     MVT::i32,   Expand);
144  setOperationAction(ISD::ATOMIC_LOAD_XOR,    MVT::i32,   Expand);
145  setOperationAction(ISD::ATOMIC_LOAD_NAND,   MVT::i32,   Expand);
146  setOperationAction(ISD::ATOMIC_LOAD_MIN,    MVT::i32,   Expand);
147  setOperationAction(ISD::ATOMIC_LOAD_MAX,    MVT::i32,   Expand);
148  setOperationAction(ISD::ATOMIC_LOAD_UMIN,   MVT::i32,   Expand);
149  setOperationAction(ISD::ATOMIC_LOAD_UMAX,   MVT::i32,   Expand);
150
151  setOperationAction(ISD::ROTR, MVT::i32,  Expand);
152  setOperationAction(ISD::ROTR, MVT::i64,  Expand);
153  setOperationAction(ISD::BSWAP, MVT::i32, Expand);
154  setOperationAction(ISD::BSWAP, MVT::i64, Expand);
155
156  computeRegisterProperties();
157}
158
159const MipsTargetLowering *
160llvm::createMips16TargetLowering(MipsTargetMachine &TM) {
161  return new Mips16TargetLowering(TM);
162}
163
164bool
165Mips16TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
166                                                    unsigned,
167                                                    bool *Fast) const {
168  return false;
169}
170
171MachineBasicBlock *
172Mips16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
173                                                  MachineBasicBlock *BB) const {
174  switch (MI->getOpcode()) {
175  default:
176    return MipsTargetLowering::EmitInstrWithCustomInserter(MI, BB);
177  case Mips::SelBeqZ:
178    return emitSel16(Mips::BeqzRxImm16, MI, BB);
179  case Mips::SelBneZ:
180    return emitSel16(Mips::BnezRxImm16, MI, BB);
181  case Mips::SelTBteqZCmpi:
182    return emitSeliT16(Mips::Bteqz16, Mips::CmpiRxImmX16, MI, BB);
183  case Mips::SelTBteqZSlti:
184    return emitSeliT16(Mips::Bteqz16, Mips::SltiRxImmX16, MI, BB);
185  case Mips::SelTBteqZSltiu:
186    return emitSeliT16(Mips::Bteqz16, Mips::SltiuRxImmX16, MI, BB);
187  case Mips::SelTBtneZCmpi:
188    return emitSeliT16(Mips::Btnez16, Mips::CmpiRxImmX16, MI, BB);
189  case Mips::SelTBtneZSlti:
190    return emitSeliT16(Mips::Btnez16, Mips::SltiRxImmX16, MI, BB);
191  case Mips::SelTBtneZSltiu:
192    return emitSeliT16(Mips::Btnez16, Mips::SltiuRxImmX16, MI, BB);
193  case Mips::SelTBteqZCmp:
194    return emitSelT16(Mips::Bteqz16, Mips::CmpRxRy16, MI, BB);
195  case Mips::SelTBteqZSlt:
196    return emitSelT16(Mips::Bteqz16, Mips::SltRxRy16, MI, BB);
197  case Mips::SelTBteqZSltu:
198    return emitSelT16(Mips::Bteqz16, Mips::SltuRxRy16, MI, BB);
199  case Mips::SelTBtneZCmp:
200    return emitSelT16(Mips::Btnez16, Mips::CmpRxRy16, MI, BB);
201  case Mips::SelTBtneZSlt:
202    return emitSelT16(Mips::Btnez16, Mips::SltRxRy16, MI, BB);
203  case Mips::SelTBtneZSltu:
204    return emitSelT16(Mips::Btnez16, Mips::SltuRxRy16, MI, BB);
205  case Mips::BteqzT8CmpX16:
206    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::CmpRxRy16, MI, BB);
207  case Mips::BteqzT8SltX16:
208    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::SltRxRy16, MI, BB);
209  case Mips::BteqzT8SltuX16:
210    // TBD: figure out a way to get this or remove the instruction
211    // altogether.
212    return emitFEXT_T8I816_ins(Mips::Bteqz16, Mips::SltuRxRy16, MI, BB);
213  case Mips::BtnezT8CmpX16:
214    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::CmpRxRy16, MI, BB);
215  case Mips::BtnezT8SltX16:
216    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::SltRxRy16, MI, BB);
217  case Mips::BtnezT8SltuX16:
218    // TBD: figure out a way to get this or remove the instruction
219    // altogether.
220    return emitFEXT_T8I816_ins(Mips::Btnez16, Mips::SltuRxRy16, MI, BB);
221  case Mips::BteqzT8CmpiX16: return emitFEXT_T8I8I16_ins(
222    Mips::Bteqz16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, false, MI, BB);
223  case Mips::BteqzT8SltiX16: return emitFEXT_T8I8I16_ins(
224    Mips::Bteqz16, Mips::SltiRxImm16, Mips::SltiRxImmX16, true, MI, BB);
225  case Mips::BteqzT8SltiuX16: return emitFEXT_T8I8I16_ins(
226    Mips::Bteqz16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, false, MI, BB);
227  case Mips::BtnezT8CmpiX16: return emitFEXT_T8I8I16_ins(
228    Mips::Btnez16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, false, MI, BB);
229  case Mips::BtnezT8SltiX16: return emitFEXT_T8I8I16_ins(
230    Mips::Btnez16, Mips::SltiRxImm16, Mips::SltiRxImmX16, true, MI, BB);
231  case Mips::BtnezT8SltiuX16: return emitFEXT_T8I8I16_ins(
232    Mips::Btnez16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, false, MI, BB);
233    break;
234  case Mips::SltCCRxRy16:
235    return emitFEXT_CCRX16_ins(Mips::SltRxRy16, MI, BB);
236    break;
237  case Mips::SltiCCRxImmX16:
238    return emitFEXT_CCRXI16_ins
239      (Mips::SltiRxImm16, Mips::SltiRxImmX16, MI, BB);
240  case Mips::SltiuCCRxImmX16:
241    return emitFEXT_CCRXI16_ins
242      (Mips::SltiuRxImm16, Mips::SltiuRxImmX16, MI, BB);
243  case Mips::SltuCCRxRy16:
244    return emitFEXT_CCRX16_ins
245      (Mips::SltuRxRy16, MI, BB);
246  }
247}
248
249bool Mips16TargetLowering::
250isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
251                                  unsigned NextStackOffset,
252                                  const MipsFunctionInfo& FI) const {
253  // No tail call optimization for mips16.
254  return false;
255}
256
257void Mips16TargetLowering::setMips16HardFloatLibCalls() {
258  for (unsigned I = 0; I != array_lengthof(HardFloatLibCalls); ++I) {
259    assert((I == 0 || HardFloatLibCalls[I - 1] < HardFloatLibCalls[I]) &&
260           "Array not sorted!");
261    if (HardFloatLibCalls[I].Libcall != RTLIB::UNKNOWN_LIBCALL)
262      setLibcallName(HardFloatLibCalls[I].Libcall, HardFloatLibCalls[I].Name);
263  }
264
265  setLibcallName(RTLIB::O_F64, "__mips16_unorddf2");
266  setLibcallName(RTLIB::O_F32, "__mips16_unordsf2");
267}
268
269//
270// The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
271// cleaner way to do all of this but it will have to wait until the traditional
272// gcc mechanism is completed.
273//
274// For Pic, in order for Mips16 code to call Mips32 code which according the abi
275// have either arguments or returned values placed in floating point registers,
276// we use a set of helper functions. (This includes functions which return type
277//  complex which on Mips are returned in a pair of floating point registers).
278//
279// This is an encoding that we inherited from gcc.
280// In Mips traditional O32, N32 ABI, floating point numbers are passed in
281// floating point argument registers 1,2 only when the first and optionally
282// the second arguments are float (sf) or double (df).
283// For Mips16 we are only concerned with the situations where floating point
284// arguments are being passed in floating point registers by the ABI, because
285// Mips16 mode code cannot execute floating point instructions to load those
286// values and hence helper functions are needed.
287// The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
288// the helper function suffixs for these are:
289//                        0,  1,    5,        9,         2,   6,        10
290// this suffix can then be calculated as follows:
291// for a given argument Arg:
292//     Arg1x, Arg2x = 1 :  Arg is sf
293//                    2 :  Arg is df
294//                    0:   Arg is neither sf or df
295// So this stub is the string for number Arg1x + Arg2x*4.
296// However not all numbers between 0 and 10 are possible, we check anyway and
297// assert if the impossible exists.
298//
299
300unsigned int Mips16TargetLowering::getMips16HelperFunctionStubNumber
301  (ArgListTy &Args) const {
302  unsigned int resultNum = 0;
303  if (Args.size() >= 1) {
304    Type *t = Args[0].Ty;
305    if (t->isFloatTy()) {
306      resultNum = 1;
307    }
308    else if (t->isDoubleTy()) {
309      resultNum = 2;
310    }
311  }
312  if (resultNum) {
313    if (Args.size() >=2) {
314      Type *t = Args[1].Ty;
315      if (t->isFloatTy()) {
316        resultNum += 4;
317      }
318      else if (t->isDoubleTy()) {
319        resultNum += 8;
320      }
321    }
322  }
323  return resultNum;
324}
325
326//
327// prefixs are attached to stub numbers depending on the return type .
328// return type: float  sf_
329//              double df_
330//              single complex sc_
331//              double complext dc_
332//              others  NO PREFIX
333//
334//
335// The full name of a helper function is__mips16_call_stub +
336//    return type dependent prefix + stub number
337//
338//
339// This is something that probably should be in a different source file and
340// perhaps done differently but my main purpose is to not waste runtime
341// on something that we can enumerate in the source. Another possibility is
342// to have a python script to generate these mapping tables. This will do
343// for now. There are a whole series of helper function mapping arrays, one
344// for each return type class as outlined above. There there are 11 possible
345//  entries. Ones with 0 are ones which should never be selected
346//
347// All the arrays are similar except for ones which return neither
348// sf, df, sc, dc, in which only care about ones which have sf or df as a
349// first parameter.
350//
351#define P_ "__mips16_call_stub_"
352#define MAX_STUB_NUMBER 10
353#define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
354#define T P "0" , T1
355#define P P_
356static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
357  {nullptr, T1 };
358#undef P
359#define P P_ "sf_"
360static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
361  { T };
362#undef P
363#define P P_ "df_"
364static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
365  { T };
366#undef P
367#define P P_ "sc_"
368static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
369  { T };
370#undef P
371#define P P_ "dc_"
372static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
373  { T };
374#undef P
375#undef P_
376
377
378const char* Mips16TargetLowering::
379  getMips16HelperFunction
380    (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
381  const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
382#ifndef NDEBUG
383  const unsigned int maxStubNum = 10;
384  assert(stubNum <= maxStubNum);
385  const bool validStubNum[maxStubNum+1] =
386    {true, true, true, false, false, true, true, false, false, true, true};
387  assert(validStubNum[stubNum]);
388#endif
389  const char *result;
390  if (RetTy->isFloatTy()) {
391    result = sfMips16Helper[stubNum];
392  }
393  else if (RetTy ->isDoubleTy()) {
394    result = dfMips16Helper[stubNum];
395  }
396  else if (RetTy->isStructTy()) {
397    // check if it's complex
398    if (RetTy->getNumContainedTypes() == 2) {
399      if ((RetTy->getContainedType(0)->isFloatTy()) &&
400          (RetTy->getContainedType(1)->isFloatTy())) {
401        result = scMips16Helper[stubNum];
402      }
403      else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
404               (RetTy->getContainedType(1)->isDoubleTy())) {
405        result = dcMips16Helper[stubNum];
406      }
407      else {
408        llvm_unreachable("Uncovered condition");
409      }
410    }
411    else {
412      llvm_unreachable("Uncovered condition");
413    }
414  }
415  else {
416    if (stubNum == 0) {
417      needHelper = false;
418      return "";
419    }
420    result = vMips16Helper[stubNum];
421  }
422  needHelper = true;
423  return result;
424}
425
426void Mips16TargetLowering::
427getOpndList(SmallVectorImpl<SDValue> &Ops,
428            std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
429            bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
430            CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
431  SelectionDAG &DAG = CLI.DAG;
432  MachineFunction &MF = DAG.getMachineFunction();
433  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
434  const char* Mips16HelperFunction = nullptr;
435  bool NeedMips16Helper = false;
436
437  if (Subtarget->inMips16HardFloat()) {
438    //
439    // currently we don't have symbols tagged with the mips16 or mips32
440    // qualifier so we will assume that we don't know what kind it is.
441    // and generate the helper
442    //
443    bool LookupHelper = true;
444    if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(CLI.Callee)) {
445      Mips16Libcall Find = { RTLIB::UNKNOWN_LIBCALL, S->getSymbol() };
446
447      if (std::binary_search(std::begin(HardFloatLibCalls),
448                             std::end(HardFloatLibCalls), Find))
449        LookupHelper = false;
450      else {
451        const char *Symbol = S->getSymbol();
452        Mips16IntrinsicHelperType IntrinsicFind = { Symbol, "" };
453        const Mips16HardFloatInfo::FuncSignature *Signature =
454            Mips16HardFloatInfo::findFuncSignature(Symbol);
455        if (!IsPICCall && (Signature && (FuncInfo->StubsNeeded.find(Symbol) ==
456                                         FuncInfo->StubsNeeded.end()))) {
457          FuncInfo->StubsNeeded[Symbol] = Signature;
458          //
459          // S2 is normally saved if the stub is for a function which
460          // returns a float or double value and is not otherwise. This is
461          // because more work is required after the function the stub
462          // is calling completes, and so the stub cannot directly return
463          // and the stub has no stack space to store the return address so
464          // S2 is used for that purpose.
465          // In order to take advantage of not saving S2, we need to also
466          // optimize the call in the stub and this requires some further
467          // functionality in MipsAsmPrinter which we don't have yet.
468          // So for now we always save S2. The optimization will be done
469          // in a follow-on patch.
470          //
471          if (1 || (Signature->RetSig != Mips16HardFloatInfo::NoFPRet))
472            FuncInfo->setSaveS2();
473        }
474        // one more look at list of intrinsics
475        const Mips16IntrinsicHelperType *Helper =
476            std::lower_bound(std::begin(Mips16IntrinsicHelper),
477                             std::end(Mips16IntrinsicHelper), IntrinsicFind);
478        if (Helper != std::end(Mips16IntrinsicHelper) &&
479            *Helper == IntrinsicFind) {
480          Mips16HelperFunction = Helper->Helper;
481          NeedMips16Helper = true;
482          LookupHelper = false;
483        }
484
485      }
486    } else if (GlobalAddressSDNode *G =
487                   dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
488      Mips16Libcall Find = { RTLIB::UNKNOWN_LIBCALL,
489                             G->getGlobal()->getName().data() };
490
491      if (std::binary_search(std::begin(HardFloatLibCalls),
492                             std::end(HardFloatLibCalls), Find))
493        LookupHelper = false;
494    }
495    if (LookupHelper)
496      Mips16HelperFunction =
497        getMips16HelperFunction(CLI.RetTy, CLI.getArgs(), NeedMips16Helper);
498  }
499
500  SDValue JumpTarget = Callee;
501
502  // T9 should contain the address of the callee function if
503  // -reloction-model=pic or it is an indirect call.
504  if (IsPICCall || !GlobalOrExternal) {
505    unsigned V0Reg = Mips::V0;
506    if (NeedMips16Helper) {
507      RegsToPass.push_front(std::make_pair(V0Reg, Callee));
508      JumpTarget = DAG.getExternalSymbol(Mips16HelperFunction, getPointerTy());
509      ExternalSymbolSDNode *S = cast<ExternalSymbolSDNode>(JumpTarget);
510      JumpTarget = getAddrGlobal(S, JumpTarget.getValueType(), DAG,
511                                 MipsII::MO_GOT, Chain,
512                                 FuncInfo->callPtrInfo(S->getSymbol()));
513    } else
514      RegsToPass.push_front(std::make_pair((unsigned)Mips::T9, Callee));
515  }
516
517  Ops.push_back(JumpTarget);
518
519  MipsTargetLowering::getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal,
520                                  InternalLinkage, CLI, Callee, Chain);
521}
522
523MachineBasicBlock *Mips16TargetLowering::
524emitSel16(unsigned Opc, MachineInstr *MI, MachineBasicBlock *BB) const {
525  if (DontExpandCondPseudos16)
526    return BB;
527  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
528  DebugLoc DL = MI->getDebugLoc();
529  // To "insert" a SELECT_CC instruction, we actually have to insert the
530  // diamond control-flow pattern.  The incoming instruction knows the
531  // destination vreg to set, the condition code register to branch on, the
532  // true/false values to select between, and a branch opcode to use.
533  const BasicBlock *LLVM_BB = BB->getBasicBlock();
534  MachineFunction::iterator It = BB;
535  ++It;
536
537  //  thisMBB:
538  //  ...
539  //   TrueVal = ...
540  //   setcc r1, r2, r3
541  //   bNE   r1, r0, copy1MBB
542  //   fallthrough --> copy0MBB
543  MachineBasicBlock *thisMBB  = BB;
544  MachineFunction *F = BB->getParent();
545  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
546  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
547  F->insert(It, copy0MBB);
548  F->insert(It, sinkMBB);
549
550  // Transfer the remainder of BB and its successor edges to sinkMBB.
551  sinkMBB->splice(sinkMBB->begin(), BB,
552                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
553  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
554
555  // Next, add the true and fallthrough blocks as its successors.
556  BB->addSuccessor(copy0MBB);
557  BB->addSuccessor(sinkMBB);
558
559  BuildMI(BB, DL, TII->get(Opc)).addReg(MI->getOperand(3).getReg())
560    .addMBB(sinkMBB);
561
562  //  copy0MBB:
563  //   %FalseValue = ...
564  //   # fallthrough to sinkMBB
565  BB = copy0MBB;
566
567  // Update machine-CFG edges
568  BB->addSuccessor(sinkMBB);
569
570  //  sinkMBB:
571  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
572  //  ...
573  BB = sinkMBB;
574
575  BuildMI(*BB, BB->begin(), DL,
576          TII->get(Mips::PHI), MI->getOperand(0).getReg())
577    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
578    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
579
580  MI->eraseFromParent();   // The pseudo instruction is gone now.
581  return BB;
582}
583
584MachineBasicBlock *Mips16TargetLowering::emitSelT16
585  (unsigned Opc1, unsigned Opc2,
586   MachineInstr *MI, MachineBasicBlock *BB) const {
587  if (DontExpandCondPseudos16)
588    return BB;
589  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
590  DebugLoc DL = MI->getDebugLoc();
591  // To "insert" a SELECT_CC instruction, we actually have to insert the
592  // diamond control-flow pattern.  The incoming instruction knows the
593  // destination vreg to set, the condition code register to branch on, the
594  // true/false values to select between, and a branch opcode to use.
595  const BasicBlock *LLVM_BB = BB->getBasicBlock();
596  MachineFunction::iterator It = BB;
597  ++It;
598
599  //  thisMBB:
600  //  ...
601  //   TrueVal = ...
602  //   setcc r1, r2, r3
603  //   bNE   r1, r0, copy1MBB
604  //   fallthrough --> copy0MBB
605  MachineBasicBlock *thisMBB  = BB;
606  MachineFunction *F = BB->getParent();
607  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
608  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
609  F->insert(It, copy0MBB);
610  F->insert(It, sinkMBB);
611
612  // Transfer the remainder of BB and its successor edges to sinkMBB.
613  sinkMBB->splice(sinkMBB->begin(), BB,
614                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
615  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
616
617  // Next, add the true and fallthrough blocks as its successors.
618  BB->addSuccessor(copy0MBB);
619  BB->addSuccessor(sinkMBB);
620
621  BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
622    .addReg(MI->getOperand(4).getReg());
623  BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
624
625  //  copy0MBB:
626  //   %FalseValue = ...
627  //   # fallthrough to sinkMBB
628  BB = copy0MBB;
629
630  // Update machine-CFG edges
631  BB->addSuccessor(sinkMBB);
632
633  //  sinkMBB:
634  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
635  //  ...
636  BB = sinkMBB;
637
638  BuildMI(*BB, BB->begin(), DL,
639          TII->get(Mips::PHI), MI->getOperand(0).getReg())
640    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
641    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
642
643  MI->eraseFromParent();   // The pseudo instruction is gone now.
644  return BB;
645
646}
647
648MachineBasicBlock *Mips16TargetLowering::emitSeliT16
649  (unsigned Opc1, unsigned Opc2,
650   MachineInstr *MI, MachineBasicBlock *BB) const {
651  if (DontExpandCondPseudos16)
652    return BB;
653  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
654  DebugLoc DL = MI->getDebugLoc();
655  // To "insert" a SELECT_CC instruction, we actually have to insert the
656  // diamond control-flow pattern.  The incoming instruction knows the
657  // destination vreg to set, the condition code register to branch on, the
658  // true/false values to select between, and a branch opcode to use.
659  const BasicBlock *LLVM_BB = BB->getBasicBlock();
660  MachineFunction::iterator It = BB;
661  ++It;
662
663  //  thisMBB:
664  //  ...
665  //   TrueVal = ...
666  //   setcc r1, r2, r3
667  //   bNE   r1, r0, copy1MBB
668  //   fallthrough --> copy0MBB
669  MachineBasicBlock *thisMBB  = BB;
670  MachineFunction *F = BB->getParent();
671  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
672  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
673  F->insert(It, copy0MBB);
674  F->insert(It, sinkMBB);
675
676  // Transfer the remainder of BB and its successor edges to sinkMBB.
677  sinkMBB->splice(sinkMBB->begin(), BB,
678                  std::next(MachineBasicBlock::iterator(MI)), BB->end());
679  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
680
681  // Next, add the true and fallthrough blocks as its successors.
682  BB->addSuccessor(copy0MBB);
683  BB->addSuccessor(sinkMBB);
684
685  BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
686    .addImm(MI->getOperand(4).getImm());
687  BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
688
689  //  copy0MBB:
690  //   %FalseValue = ...
691  //   # fallthrough to sinkMBB
692  BB = copy0MBB;
693
694  // Update machine-CFG edges
695  BB->addSuccessor(sinkMBB);
696
697  //  sinkMBB:
698  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
699  //  ...
700  BB = sinkMBB;
701
702  BuildMI(*BB, BB->begin(), DL,
703          TII->get(Mips::PHI), MI->getOperand(0).getReg())
704    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
705    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
706
707  MI->eraseFromParent();   // The pseudo instruction is gone now.
708  return BB;
709
710}
711
712MachineBasicBlock
713  *Mips16TargetLowering::emitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
714                                             MachineInstr *MI,
715                                             MachineBasicBlock *BB) const {
716  if (DontExpandCondPseudos16)
717    return BB;
718  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
719  unsigned regX = MI->getOperand(0).getReg();
720  unsigned regY = MI->getOperand(1).getReg();
721  MachineBasicBlock *target = MI->getOperand(2).getMBB();
722  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX)
723    .addReg(regY);
724  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
725  MI->eraseFromParent();   // The pseudo instruction is gone now.
726  return BB;
727}
728
729MachineBasicBlock *Mips16TargetLowering::emitFEXT_T8I8I16_ins(
730  unsigned BtOpc, unsigned CmpiOpc, unsigned CmpiXOpc, bool ImmSigned,
731  MachineInstr *MI,  MachineBasicBlock *BB) const {
732  if (DontExpandCondPseudos16)
733    return BB;
734  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
735  unsigned regX = MI->getOperand(0).getReg();
736  int64_t imm = MI->getOperand(1).getImm();
737  MachineBasicBlock *target = MI->getOperand(2).getMBB();
738  unsigned CmpOpc;
739  if (isUInt<8>(imm))
740    CmpOpc = CmpiOpc;
741  else if ((!ImmSigned && isUInt<16>(imm)) ||
742           (ImmSigned && isInt<16>(imm)))
743    CmpOpc = CmpiXOpc;
744  else
745    llvm_unreachable("immediate field not usable");
746  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX)
747    .addImm(imm);
748  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
749  MI->eraseFromParent();   // The pseudo instruction is gone now.
750  return BB;
751}
752
753static unsigned Mips16WhichOp8uOr16simm
754  (unsigned shortOp, unsigned longOp, int64_t Imm) {
755  if (isUInt<8>(Imm))
756    return shortOp;
757  else if (isInt<16>(Imm))
758    return longOp;
759  else
760    llvm_unreachable("immediate field not usable");
761}
762
763MachineBasicBlock *Mips16TargetLowering::emitFEXT_CCRX16_ins(
764  unsigned SltOpc,
765  MachineInstr *MI,  MachineBasicBlock *BB) const {
766  if (DontExpandCondPseudos16)
767    return BB;
768  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
769  unsigned CC = MI->getOperand(0).getReg();
770  unsigned regX = MI->getOperand(1).getReg();
771  unsigned regY = MI->getOperand(2).getReg();
772  BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(SltOpc)).addReg(regX).addReg(
773      regY);
774  BuildMI(*BB, MI, MI->getDebugLoc(),
775          TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
776  MI->eraseFromParent();   // The pseudo instruction is gone now.
777  return BB;
778}
779
780MachineBasicBlock *Mips16TargetLowering::emitFEXT_CCRXI16_ins(
781  unsigned SltiOpc, unsigned SltiXOpc,
782  MachineInstr *MI,  MachineBasicBlock *BB )const {
783  if (DontExpandCondPseudos16)
784    return BB;
785  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
786  unsigned CC = MI->getOperand(0).getReg();
787  unsigned regX = MI->getOperand(1).getReg();
788  int64_t Imm = MI->getOperand(2).getImm();
789  unsigned SltOpc = Mips16WhichOp8uOr16simm(SltiOpc, SltiXOpc, Imm);
790  BuildMI(*BB, MI, MI->getDebugLoc(),
791          TII->get(SltOpc)).addReg(regX).addImm(Imm);
792  BuildMI(*BB, MI, MI->getDebugLoc(),
793          TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
794  MI->eraseFromParent();   // The pseudo instruction is gone now.
795  return BB;
796
797}
798