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