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