The ADD and ADDK (and all variants) instructions where flip-flopped in the MBlaze...
[oota-llvm.git] / lib / Target / MBlaze / MBlazeISelLowering.cpp
1 //===-- MBlazeISelLowering.cpp - MBlaze 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 defines the interfaces that MBlaze uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mblaze-lower"
16 #include "MBlazeISelLowering.h"
17 #include "MBlazeMachineFunction.h"
18 #include "MBlazeTargetMachine.h"
19 #include "MBlazeTargetObjectFile.h"
20 #include "MBlazeSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37
38 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
39                                 CCValAssign::LocInfo &LocInfo,
40                                 ISD::ArgFlagsTy &ArgFlags,
41                                 CCState &State);
42
43 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
44   switch (Opcode) {
45     case MBlazeISD::JmpLink    : return "MBlazeISD::JmpLink";
46     case MBlazeISD::GPRel      : return "MBlazeISD::GPRel";
47     case MBlazeISD::Wrap       : return "MBlazeISD::Wrap";
48     case MBlazeISD::ICmp       : return "MBlazeISD::ICmp";
49     case MBlazeISD::Ret        : return "MBlazeISD::Ret";
50     case MBlazeISD::Select_CC  : return "MBlazeISD::Select_CC";
51     default                    : return NULL;
52   }
53 }
54
55 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
56   : TargetLowering(TM, new MBlazeTargetObjectFile()) {
57   Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
58
59   // MBlaze does not have i1 type, so use i32 for
60   // setcc operations results (slt, sgt, ...).
61   setBooleanContents(ZeroOrOneBooleanContent);
62
63   // Set up the register classes
64   addRegisterClass(MVT::i32, MBlaze::GPRRegisterClass);
65   if (Subtarget->hasFPU()) {
66     addRegisterClass(MVT::f32, MBlaze::GPRRegisterClass);
67     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
68   }
69
70   // Floating point operations which are not supported
71   setOperationAction(ISD::FREM,       MVT::f32, Expand);
72   setOperationAction(ISD::UINT_TO_FP, MVT::i8,  Expand);
73   setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
74   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
75   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
76   setOperationAction(ISD::FP_ROUND,   MVT::f32, Expand);
77   setOperationAction(ISD::FP_ROUND,   MVT::f64, Expand);
78   setOperationAction(ISD::FCOPYSIGN,  MVT::f32, Expand);
79   setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
80   setOperationAction(ISD::FSIN,       MVT::f32, Expand);
81   setOperationAction(ISD::FCOS,       MVT::f32, Expand);
82   setOperationAction(ISD::FPOWI,      MVT::f32, Expand);
83   setOperationAction(ISD::FPOW,       MVT::f32, Expand);
84   setOperationAction(ISD::FLOG,       MVT::f32, Expand);
85   setOperationAction(ISD::FLOG2,      MVT::f32, Expand);
86   setOperationAction(ISD::FLOG10,     MVT::f32, Expand);
87   setOperationAction(ISD::FEXP,       MVT::f32, Expand);
88
89   // Load extented operations for i1 types must be promoted
90   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
91   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
93
94   // Sign extended loads must be expanded
95   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
96   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
97
98   // MBlaze has no REM or DIVREM operations.
99   setOperationAction(ISD::UREM,    MVT::i32, Expand);
100   setOperationAction(ISD::SREM,    MVT::i32, Expand);
101   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
102   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
103
104   // If the processor doesn't support multiply then expand it
105   if (!Subtarget->hasMul()) {
106     setOperationAction(ISD::MUL, MVT::i32, Expand);
107   }
108
109   // If the processor doesn't support 64-bit multiply then expand
110   if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
111     setOperationAction(ISD::MULHS, MVT::i32, Expand);
112     setOperationAction(ISD::MULHS, MVT::i64, Expand);
113     setOperationAction(ISD::MULHU, MVT::i32, Expand);
114     setOperationAction(ISD::MULHU, MVT::i64, Expand);
115   }
116
117   // If the processor doesn't support division then expand
118   if (!Subtarget->hasDiv()) {
119     setOperationAction(ISD::UDIV, MVT::i32, Expand);
120     setOperationAction(ISD::SDIV, MVT::i32, Expand);
121   }
122
123   // Expand unsupported conversions
124   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
125   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
126
127   // Expand SELECT_CC
128   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
129
130   // MBlaze doesn't have MUL_LOHI
131   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
132   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
133   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
134   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
135
136   // Used by legalize types to correctly generate the setcc result.
137   // Without this, every float setcc comes with a AND/OR with the result,
138   // we don't want this, since the fpcmp result goes to a flag register,
139   // which is used implicitly by brcond and select operations.
140   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
141   AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
142   AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
143
144   // MBlaze Custom Operations
145   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
146   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
147   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
148   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
149
150   // Variable Argument support
151   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
152   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
153   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
154   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
155
156
157   // Operations not directly supported by MBlaze.
158   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
159   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
160   setOperationAction(ISD::BR_CC,              MVT::Other, Expand);
161   setOperationAction(ISD::SIGN_EXTEND_INREG,  MVT::i1,    Expand);
162   setOperationAction(ISD::ROTL,               MVT::i32,   Expand);
163   setOperationAction(ISD::ROTR,               MVT::i32,   Expand);
164   setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Expand);
165   setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Expand);
166   setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Expand);
167   setOperationAction(ISD::CTLZ,               MVT::i32,   Expand);
168   setOperationAction(ISD::CTTZ,               MVT::i32,   Expand);
169   setOperationAction(ISD::CTPOP,              MVT::i32,   Expand);
170   setOperationAction(ISD::BSWAP,              MVT::i32,   Expand);
171
172   // We don't have line number support yet.
173   setOperationAction(ISD::EH_LABEL,          MVT::Other, Expand);
174
175   // Use the default for now
176   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
177   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
178   setOperationAction(ISD::MEMBARRIER,        MVT::Other, Expand);
179
180   // MBlaze doesn't have extending float->double load/store
181   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
182   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
183
184   setStackPointerRegisterToSaveRestore(MBlaze::R1);
185   computeRegisterProperties();
186 }
187
188 MVT::SimpleValueType MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
189   return MVT::i32;
190 }
191
192 /// getFunctionAlignment - Return the Log2 alignment of this function.
193 unsigned MBlazeTargetLowering::getFunctionAlignment(const Function *) const {
194   return 2;
195 }
196
197 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
198                                              SelectionDAG &DAG) const {
199   switch (Op.getOpcode())
200   {
201     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
202     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
203     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
204     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
205     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
206     case ISD::VASTART:            return LowerVASTART(Op, DAG);
207   }
208   return SDValue();
209 }
210
211 //===----------------------------------------------------------------------===//
212 //  Lower helper functions
213 //===----------------------------------------------------------------------===//
214 MachineBasicBlock*
215 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
216                                                   MachineBasicBlock *BB) const {
217   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
218   DebugLoc dl = MI->getDebugLoc();
219
220   switch (MI->getOpcode()) {
221   default: assert(false && "Unexpected instr type to insert");
222   case MBlaze::ShiftRL:
223   case MBlaze::ShiftRA:
224   case MBlaze::ShiftL: {
225     // To "insert" a shift left instruction, we actually have to insert a
226     // simple loop.  The incoming instruction knows the destination vreg to
227     // set, the source vreg to operate over and the shift amount.
228     const BasicBlock *LLVM_BB = BB->getBasicBlock();
229     MachineFunction::iterator It = BB;
230     ++It;
231
232     // start:
233     //   andi     samt, samt, 31
234     //   beqid    samt, finish
235     //   add      dst, src, r0
236     // loop:
237     //   addik    samt, samt, -1
238     //   sra      dst, dst
239     //   bneid    samt, loop
240     //   nop
241     // finish:
242     MachineFunction *F = BB->getParent();
243     MachineRegisterInfo &R = F->getRegInfo();
244     MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
245     MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
246     F->insert(It, loop);
247     F->insert(It, finish);
248
249     // Update machine-CFG edges by transfering adding all successors and
250     // remaining instructions from the current block to the new block which
251     // will contain the Phi node for the select.
252     finish->splice(finish->begin(), BB,
253                    llvm::next(MachineBasicBlock::iterator(MI)),
254                    BB->end());
255     finish->transferSuccessorsAndUpdatePHIs(BB);
256
257     // Add the true and fallthrough blocks as its successors.
258     BB->addSuccessor(loop);
259     BB->addSuccessor(finish);
260
261     // Next, add the finish block as a successor of the loop block
262     loop->addSuccessor(finish);
263     loop->addSuccessor(loop);
264
265     unsigned IAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
266     BuildMI(BB, dl, TII->get(MBlaze::ANDI), IAMT)
267       .addReg(MI->getOperand(2).getReg())
268       .addImm(31);
269
270     unsigned IVAL = R.createVirtualRegister(MBlaze::GPRRegisterClass);
271     BuildMI(BB, dl, TII->get(MBlaze::ADDIK), IVAL)
272       .addReg(MI->getOperand(1).getReg())
273       .addImm(0);
274
275     BuildMI(BB, dl, TII->get(MBlaze::BEQID))
276       .addReg(IAMT)
277       .addMBB(finish);
278
279     unsigned DST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
280     unsigned NDST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
281     BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
282       .addReg(IVAL).addMBB(BB)
283       .addReg(NDST).addMBB(loop);
284
285     unsigned SAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
286     unsigned NAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
287     BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
288       .addReg(IAMT).addMBB(BB)
289       .addReg(NAMT).addMBB(loop);
290
291     if (MI->getOpcode() == MBlaze::ShiftL)
292       BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
293     else if (MI->getOpcode() == MBlaze::ShiftRA)
294       BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
295     else if (MI->getOpcode() == MBlaze::ShiftRL)
296       BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
297     else
298         llvm_unreachable("Cannot lower unknown shift instruction");
299
300     BuildMI(loop, dl, TII->get(MBlaze::ADDIK), NAMT)
301       .addReg(SAMT)
302       .addImm(-1);
303
304     BuildMI(loop, dl, TII->get(MBlaze::BNEID))
305       .addReg(NAMT)
306       .addMBB(loop);
307
308     BuildMI(*finish, finish->begin(), dl,
309             TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
310       .addReg(IVAL).addMBB(BB)
311       .addReg(NDST).addMBB(loop);
312
313     // The pseudo instruction is no longer needed so remove it
314     MI->eraseFromParent();
315     return finish;
316     }
317
318   case MBlaze::Select_FCC:
319   case MBlaze::Select_CC: {
320     // To "insert" a SELECT_CC instruction, we actually have to insert the
321     // diamond control-flow pattern.  The incoming instruction knows the
322     // destination vreg to set, the condition code register to branch on, the
323     // true/false values to select between, and a branch opcode to use.
324     const BasicBlock *LLVM_BB = BB->getBasicBlock();
325     MachineFunction::iterator It = BB;
326     ++It;
327
328     //  thisMBB:
329     //  ...
330     //   TrueVal = ...
331     //   setcc r1, r2, r3
332     //   bNE   r1, r0, copy1MBB
333     //   fallthrough --> copy0MBB
334     MachineFunction *F = BB->getParent();
335     MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
336     MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
337
338     unsigned Opc;
339     switch (MI->getOperand(4).getImm()) {
340     default: llvm_unreachable("Unknown branch condition");
341     case MBlazeCC::EQ: Opc = MBlaze::BEQID; break;
342     case MBlazeCC::NE: Opc = MBlaze::BNEID; break;
343     case MBlazeCC::GT: Opc = MBlaze::BGTID; break;
344     case MBlazeCC::LT: Opc = MBlaze::BLTID; break;
345     case MBlazeCC::GE: Opc = MBlaze::BGEID; break;
346     case MBlazeCC::LE: Opc = MBlaze::BLEID; break;
347     }
348
349     F->insert(It, flsBB);
350     F->insert(It, dneBB);
351
352     // Transfer the remainder of BB and its successor edges to dneBB.
353     dneBB->splice(dneBB->begin(), BB,
354                   llvm::next(MachineBasicBlock::iterator(MI)),
355                   BB->end());
356     dneBB->transferSuccessorsAndUpdatePHIs(BB);
357
358     BB->addSuccessor(flsBB);
359     BB->addSuccessor(dneBB);
360     flsBB->addSuccessor(dneBB);
361
362     BuildMI(BB, dl, TII->get(Opc))
363       .addReg(MI->getOperand(3).getReg())
364       .addMBB(dneBB);
365
366     //  sinkMBB:
367     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
368     //  ...
369     //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
370     //  .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
371     //  .addReg(MI->getOperand(2).getReg()).addMBB(BB);
372
373     BuildMI(*dneBB, dneBB->begin(), dl,
374             TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
375       .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
376       .addReg(MI->getOperand(1).getReg()).addMBB(BB);
377
378     MI->eraseFromParent();   // The pseudo instruction is gone now.
379     return dneBB;
380   }
381   }
382 }
383
384 //===----------------------------------------------------------------------===//
385 //  Misc Lower Operation implementation
386 //===----------------------------------------------------------------------===//
387 //
388
389 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op,
390                                              SelectionDAG &DAG) const {
391   SDValue LHS = Op.getOperand(0);
392   SDValue RHS = Op.getOperand(1);
393   SDValue TrueVal = Op.getOperand(2);
394   SDValue FalseVal = Op.getOperand(3);
395   DebugLoc dl = Op.getDebugLoc();
396   unsigned Opc;
397
398   SDValue CompareFlag;
399   if (LHS.getValueType() == MVT::i32) {
400     Opc = MBlazeISD::Select_CC;
401     CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
402                     .getValue(1);
403   } else {
404     llvm_unreachable("Cannot lower select_cc with unknown type");
405   }
406
407   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
408                      CompareFlag);
409 }
410
411 SDValue MBlazeTargetLowering::
412 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
413   // FIXME there isn't actually debug info here
414   DebugLoc dl = Op.getDebugLoc();
415   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
416   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
417
418   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
419 }
420
421 SDValue MBlazeTargetLowering::
422 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
423   llvm_unreachable("TLS not implemented for MicroBlaze.");
424   return SDValue(); // Not reached
425 }
426
427 SDValue MBlazeTargetLowering::
428 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
429   SDValue ResNode;
430   SDValue HiPart;
431   // FIXME there isn't actually debug info here
432   DebugLoc dl = Op.getDebugLoc();
433
434   EVT PtrVT = Op.getValueType();
435   JumpTableSDNode *JT  = cast<JumpTableSDNode>(Op);
436
437   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0);
438   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
439 }
440
441 SDValue MBlazeTargetLowering::
442 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
443   SDValue ResNode;
444   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
445   const Constant *C = N->getConstVal();
446   DebugLoc dl = Op.getDebugLoc();
447
448   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
449                                          N->getOffset(), 0);
450   return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
451 }
452
453 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
454                                            SelectionDAG &DAG) const {
455   MachineFunction &MF = DAG.getMachineFunction();
456   MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
457
458   DebugLoc dl = Op.getDebugLoc();
459   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
460                                  getPointerTy());
461
462   // vastart just stores the address of the VarArgsFrameIndex slot into the
463   // memory location argument.
464   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
465   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
466                       MachinePointerInfo(SV),
467                       false, false, 0);
468 }
469
470 //===----------------------------------------------------------------------===//
471 //                      Calling Convention Implementation
472 //===----------------------------------------------------------------------===//
473
474 #include "MBlazeGenCallingConv.inc"
475
476 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
477                                 CCValAssign::LocInfo &LocInfo,
478                                 ISD::ArgFlagsTy &ArgFlags,
479                                 CCState &State) {
480   static const unsigned ArgRegs[] = {
481     MBlaze::R5, MBlaze::R6, MBlaze::R7,
482     MBlaze::R8, MBlaze::R9, MBlaze::R10
483   };
484
485   const unsigned NumArgRegs = array_lengthof(ArgRegs);
486   unsigned Reg = State.AllocateReg(ArgRegs, NumArgRegs);
487   if (!Reg) return false;
488
489   unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
490   State.AllocateStack(SizeInBytes, SizeInBytes);
491   State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
492
493   return true;
494 }
495
496 //===----------------------------------------------------------------------===//
497 //                  Call Calling Convention Implementation
498 //===----------------------------------------------------------------------===//
499
500 /// LowerCall - functions arguments are copied from virtual regs to
501 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
502 /// TODO: isVarArg, isTailCall.
503 SDValue MBlazeTargetLowering::
504 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
505           bool isVarArg, bool &isTailCall,
506           const SmallVectorImpl<ISD::OutputArg> &Outs,
507           const SmallVectorImpl<SDValue> &OutVals,
508           const SmallVectorImpl<ISD::InputArg> &Ins,
509           DebugLoc dl, SelectionDAG &DAG,
510           SmallVectorImpl<SDValue> &InVals) const {
511   // MBlaze does not yet support tail call optimization
512   isTailCall = false;
513
514   // The MBlaze requires stack slots for arguments passed to var arg
515   // functions even if they are passed in registers.
516   bool needsRegArgSlots = isVarArg;
517
518   MachineFunction &MF = DAG.getMachineFunction();
519   MachineFrameInfo *MFI = MF.getFrameInfo();
520   const TargetFrameInfo &TFI = *MF.getTarget().getFrameInfo();
521
522   // Analyze operands of the call, assigning locations to each operand.
523   SmallVector<CCValAssign, 16> ArgLocs;
524   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
525                  *DAG.getContext());
526   CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
527
528   // Get a count of how many bytes are to be pushed on the stack.
529   unsigned NumBytes = CCInfo.getNextStackOffset();
530
531   // Variable argument function calls require a minimum of 24-bytes of stack
532   if (isVarArg && NumBytes < 24) NumBytes = 24;
533
534   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
535
536   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
537   SmallVector<SDValue, 8> MemOpChains;
538
539   // Walk the register/memloc assignments, inserting copies/loads.
540   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
541     CCValAssign &VA = ArgLocs[i];
542     MVT RegVT = VA.getLocVT();
543     SDValue Arg = OutVals[i];
544
545     // Promote the value if needed.
546     switch (VA.getLocInfo()) {
547     default: llvm_unreachable("Unknown loc info!");
548     case CCValAssign::Full: break;
549     case CCValAssign::SExt:
550       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
551       break;
552     case CCValAssign::ZExt:
553       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
554       break;
555     case CCValAssign::AExt:
556       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
557       break;
558     }
559
560     // Arguments that can be passed on register must be kept at
561     // RegsToPass vector
562     if (VA.isRegLoc()) {
563       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
564     } else {
565       // Register can't get to this point...
566       assert(VA.isMemLoc());
567
568       // Since we are alread passing values on the stack we don't
569       // need to worry about creating additional slots for the
570       // values passed via registers.
571       needsRegArgSlots = false;
572
573       // Create the frame index object for this incoming parameter
574       unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
575       unsigned StackLoc = VA.getLocMemOffset() + 4;
576       int FI = MFI->CreateFixedObject(ArgSize, StackLoc, true);
577
578       SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
579
580       // emit ISD::STORE whichs stores the
581       // parameter value to a stack Location
582       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
583                                          MachinePointerInfo(),
584                                          false, false, 0));
585     }
586   }
587
588   // If we need to reserve stack space for the arguments passed via registers
589   // then create a fixed stack object at the beginning of the stack.
590   if (needsRegArgSlots && TFI.hasReservedCallFrame(MF))
591     MFI->CreateFixedObject(28,0,true);
592
593   // Transform all store nodes into one single node because all store
594   // nodes are independent of each other.
595   if (!MemOpChains.empty())
596     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
597                         &MemOpChains[0], MemOpChains.size());
598
599   // Build a sequence of copy-to-reg nodes chained together with token
600   // chain and flag operands which copy the outgoing args into registers.
601   // The InFlag in necessary since all emited instructions must be
602   // stuck together.
603   SDValue InFlag;
604   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
605     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
606                              RegsToPass[i].second, InFlag);
607     InFlag = Chain.getValue(1);
608   }
609
610   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
611   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
612   // node so that legalize doesn't hack it.
613   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
614     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
615                                 getPointerTy(), 0, 0);
616   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
617     Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
618                                 getPointerTy(), 0);
619
620   // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
621   //             = Chain, Callee, Reg#1, Reg#2, ...
622   //
623   // Returns a chain & a flag for retval copy to use.
624   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
625   SmallVector<SDValue, 8> Ops;
626   Ops.push_back(Chain);
627   Ops.push_back(Callee);
628
629   // Add argument registers to the end of the list so that they are
630   // known live into the call.
631   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
632     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
633                                   RegsToPass[i].second.getValueType()));
634   }
635
636   if (InFlag.getNode())
637     Ops.push_back(InFlag);
638
639   Chain  = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
640   InFlag = Chain.getValue(1);
641
642   // Create the CALLSEQ_END node.
643   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
644                              DAG.getIntPtrConstant(0, true), InFlag);
645   if (!Ins.empty())
646     InFlag = Chain.getValue(1);
647
648   // Handle result values, copying them out of physregs into vregs that we
649   // return.
650   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
651                          Ins, dl, DAG, InVals);
652 }
653
654 /// LowerCallResult - Lower the result values of a call into the
655 /// appropriate copies out of appropriate physical registers.
656 SDValue MBlazeTargetLowering::
657 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
658                 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
659                 DebugLoc dl, SelectionDAG &DAG,
660                 SmallVectorImpl<SDValue> &InVals) const {
661   // Assign locations to each value returned by this call.
662   SmallVector<CCValAssign, 16> RVLocs;
663   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
664                  RVLocs, *DAG.getContext());
665
666   CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
667
668   // Copy all of the result registers out of their specified physreg.
669   for (unsigned i = 0; i != RVLocs.size(); ++i) {
670     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
671                                RVLocs[i].getValVT(), InFlag).getValue(1);
672     InFlag = Chain.getValue(2);
673     InVals.push_back(Chain.getValue(0));
674   }
675
676   return Chain;
677 }
678
679 //===----------------------------------------------------------------------===//
680 //             Formal Arguments Calling Convention Implementation
681 //===----------------------------------------------------------------------===//
682
683 /// LowerFormalArguments - transform physical registers into
684 /// virtual registers and generate load operations for
685 /// arguments places on the stack.
686 SDValue MBlazeTargetLowering::
687 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
688                      const SmallVectorImpl<ISD::InputArg> &Ins,
689                      DebugLoc dl, SelectionDAG &DAG,
690                      SmallVectorImpl<SDValue> &InVals) const {
691   MachineFunction &MF = DAG.getMachineFunction();
692   MachineFrameInfo *MFI = MF.getFrameInfo();
693   MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
694
695   unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
696   MBlazeFI->setVarArgsFrameIndex(0);
697
698   // Used with vargs to acumulate store chains.
699   std::vector<SDValue> OutChains;
700
701   // Keep track of the last register used for arguments
702   unsigned ArgRegEnd = 0;
703
704   // Assign locations to all of the incoming arguments.
705   SmallVector<CCValAssign, 16> ArgLocs;
706   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
707                  ArgLocs, *DAG.getContext());
708
709   CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
710   SDValue StackPtr;
711
712   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
713     CCValAssign &VA = ArgLocs[i];
714
715     // Arguments stored on registers
716     if (VA.isRegLoc()) {
717       MVT RegVT = VA.getLocVT();
718       ArgRegEnd = VA.getLocReg();
719       TargetRegisterClass *RC = 0;
720
721       if (RegVT == MVT::i32)
722         RC = MBlaze::GPRRegisterClass;
723       else if (RegVT == MVT::f32)
724         RC = MBlaze::GPRRegisterClass;
725       else
726         llvm_unreachable("RegVT not supported by LowerFormalArguments");
727
728       // Transform the arguments stored on
729       // physical registers into virtual ones
730       unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
731       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
732
733       // If this is an 8 or 16-bit value, it has been passed promoted
734       // to 32 bits.  Insert an assert[sz]ext to capture this, then
735       // truncate to the right size. If if is a floating point value
736       // then convert to the correct type.
737       if (VA.getLocInfo() != CCValAssign::Full) {
738         unsigned Opcode = 0;
739         if (VA.getLocInfo() == CCValAssign::SExt)
740           Opcode = ISD::AssertSext;
741         else if (VA.getLocInfo() == CCValAssign::ZExt)
742           Opcode = ISD::AssertZext;
743         if (Opcode)
744           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
745                                  DAG.getValueType(VA.getValVT()));
746         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
747       }
748
749       InVals.push_back(ArgValue);
750     } else { // VA.isRegLoc()
751       // sanity check
752       assert(VA.isMemLoc());
753
754       // The last argument is not a register
755       ArgRegEnd = 0;
756
757       // The stack pointer offset is relative to the caller stack frame.
758       // Since the real stack size is unknown here, a negative SPOffset
759       // is used so there's a way to adjust these offsets when the stack
760       // size get known (on EliminateFrameIndex). A dummy SPOffset is
761       // used instead of a direct negative address (which is recorded to
762       // be used on emitPrologue) to avoid mis-calc of the first stack
763       // offset on PEI::calculateFrameObjectOffsets.
764       // Arguments are always 32-bit.
765       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
766       unsigned StackLoc = VA.getLocMemOffset() + 4;
767       int FI = MFI->CreateFixedObject(ArgSize, 0, true);
768       MBlazeFI->recordLoadArgsFI(FI, -StackLoc);
769       MBlazeFI->recordLiveIn(FI);
770
771       // Create load nodes to retrieve arguments from the stack
772       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
773       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
774                                    MachinePointerInfo::getFixedStack(FI),
775                                    false, false, 0));
776     }
777   }
778
779   // To meet ABI, when VARARGS are passed on registers, the registers
780   // must have their values written to the caller stack frame. If the last
781   // argument was placed in the stack, there's no need to save any register.
782   if ((isVarArg) && ArgRegEnd) {
783     if (StackPtr.getNode() == 0)
784       StackPtr = DAG.getRegister(StackReg, getPointerTy());
785
786     // The last register argument that must be saved is MBlaze::R10
787     TargetRegisterClass *RC = MBlaze::GPRRegisterClass;
788
789     unsigned Begin = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R5);
790     unsigned Start = MBlazeRegisterInfo::getRegisterNumbering(ArgRegEnd+1);
791     unsigned End   = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R10);
792     unsigned StackLoc = Start - Begin + 1;
793
794     for (; Start <= End; ++Start, ++StackLoc) {
795       unsigned Reg = MBlazeRegisterInfo::getRegisterFromNumbering(Start);
796       unsigned LiveReg = MF.addLiveIn(Reg, RC);
797       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
798
799       int FI = MFI->CreateFixedObject(4, 0, true);
800       MBlazeFI->recordStoreVarArgsFI(FI, -(StackLoc*4));
801       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
802       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
803                                        MachinePointerInfo(),
804                                        false, false, 0));
805
806       // Record the frame index of the first variable argument
807       // which is a value necessary to VASTART.
808       if (!MBlazeFI->getVarArgsFrameIndex())
809         MBlazeFI->setVarArgsFrameIndex(FI);
810     }
811   }
812
813   // All stores are grouped in one node to allow the matching between
814   // the size of Ins and InVals. This only happens when on varg functions
815   if (!OutChains.empty()) {
816     OutChains.push_back(Chain);
817     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
818                         &OutChains[0], OutChains.size());
819   }
820
821   return Chain;
822 }
823
824 //===----------------------------------------------------------------------===//
825 //               Return Value Calling Convention Implementation
826 //===----------------------------------------------------------------------===//
827
828 SDValue MBlazeTargetLowering::
829 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
830             const SmallVectorImpl<ISD::OutputArg> &Outs,
831             const SmallVectorImpl<SDValue> &OutVals,
832             DebugLoc dl, SelectionDAG &DAG) const {
833   // CCValAssign - represent the assignment of
834   // the return value to a location
835   SmallVector<CCValAssign, 16> RVLocs;
836
837   // CCState - Info about the registers and stack slot.
838   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
839                  RVLocs, *DAG.getContext());
840
841   // Analize return values.
842   CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
843
844   // If this is the first return lowered for this function, add
845   // the regs to the liveout set for the function.
846   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
847     for (unsigned i = 0; i != RVLocs.size(); ++i)
848       if (RVLocs[i].isRegLoc())
849         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
850   }
851
852   SDValue Flag;
853
854   // Copy the result values into the output registers.
855   for (unsigned i = 0; i != RVLocs.size(); ++i) {
856     CCValAssign &VA = RVLocs[i];
857     assert(VA.isRegLoc() && "Can only return in registers!");
858
859     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
860                              OutVals[i], Flag);
861
862     // guarantee that all emitted copies are
863     // stuck together, avoiding something bad
864     Flag = Chain.getValue(1);
865   }
866
867   // Return on MBlaze is always a "rtsd R15, 8"
868   if (Flag.getNode())
869     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
870                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32), Flag);
871   else // Return Void
872     return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
873                        Chain, DAG.getRegister(MBlaze::R15, MVT::i32));
874 }
875
876 //===----------------------------------------------------------------------===//
877 //                           MBlaze Inline Assembly Support
878 //===----------------------------------------------------------------------===//
879
880 /// getConstraintType - Given a constraint letter, return the type of
881 /// constraint it is for this target.
882 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
883 getConstraintType(const std::string &Constraint) const
884 {
885   // MBlaze specific constrainy
886   //
887   // 'd' : An address register. Equivalent to r.
888   // 'y' : Equivalent to r; retained for
889   //       backwards compatibility.
890   // 'f' : Floating Point registers.
891   if (Constraint.size() == 1) {
892     switch (Constraint[0]) {
893       default : break;
894       case 'd':
895       case 'y':
896       case 'f':
897         return C_RegisterClass;
898         break;
899     }
900   }
901   return TargetLowering::getConstraintType(Constraint);
902 }
903
904 /// Examine constraint type and operand type and determine a weight value.
905 /// This object must already have been set up with the operand type
906 /// and the current alternative constraint selected.
907 TargetLowering::ConstraintWeight
908 MBlazeTargetLowering::getSingleConstraintMatchWeight(
909     AsmOperandInfo &info, const char *constraint) const {
910   ConstraintWeight weight = CW_Invalid;
911   Value *CallOperandVal = info.CallOperandVal;
912     // If we don't have a value, we can't do a match,
913     // but allow it at the lowest weight.
914   if (CallOperandVal == NULL)
915     return CW_Default;
916   const Type *type = CallOperandVal->getType();
917   // Look at the constraint type.
918   switch (*constraint) {
919   default:
920     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
921     break;\r
922   case 'd':
923   case 'y':
924     if (type->isIntegerTy())
925       weight = CW_Register;
926     break;
927   case 'f':
928     if (type->isFloatTy())
929       weight = CW_Register;
930     break;
931   }
932   return weight;
933 }
934
935 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
936 /// return a list of registers that can be used to satisfy the constraint.
937 /// This should only be used for C_RegisterClass constraints.
938 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
939 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
940   if (Constraint.size() == 1) {
941     switch (Constraint[0]) {
942     case 'r':
943       return std::make_pair(0U, MBlaze::GPRRegisterClass);
944     case 'f':
945       if (VT == MVT::f32)
946         return std::make_pair(0U, MBlaze::GPRRegisterClass);
947     }
948   }
949   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
950 }
951
952 /// Given a register class constraint, like 'r', if this corresponds directly
953 /// to an LLVM register class, return a register of 0 and the register class
954 /// pointer.
955 std::vector<unsigned> MBlazeTargetLowering::
956 getRegClassForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
957   if (Constraint.size() != 1)
958     return std::vector<unsigned>();
959
960   switch (Constraint[0]) {
961     default : break;
962     case 'r':
963     // GCC MBlaze Constraint Letters
964     case 'd':
965     case 'y':
966     case 'f':
967       return make_vector<unsigned>(
968         MBlaze::R3,  MBlaze::R4,  MBlaze::R5,  MBlaze::R6,
969         MBlaze::R7,  MBlaze::R9,  MBlaze::R10, MBlaze::R11,
970         MBlaze::R12, MBlaze::R19, MBlaze::R20, MBlaze::R21,
971         MBlaze::R22, MBlaze::R23, MBlaze::R24, MBlaze::R25,
972         MBlaze::R26, MBlaze::R27, MBlaze::R28, MBlaze::R29,
973         MBlaze::R30, MBlaze::R31, 0);
974   }
975   return std::vector<unsigned>();
976 }
977
978 bool MBlazeTargetLowering::
979 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
980   // The MBlaze target isn't yet aware of offsets.
981   return false;
982 }
983
984 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
985   return VT != MVT::f32;
986 }