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