Fixed some bugs.
[llvm/zpu.git] / lib / Target / MBlaze / MBlazeISelLowering.cpp
blob9f0afcf427cb50e7e053a7eb7e5b27b63a0bcf4b
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.
13 //===----------------------------------------------------------------------===//
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;
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;
50 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
51 : TargetLowering(TM, new MBlazeTargetObjectFile()) {
52 Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
54 // MBlaze does not have i1 type, so use i32 for
55 // setcc operations results (slt, sgt, ...).
56 setBooleanContents(ZeroOrOneBooleanContent);
58 // Set up the register classes
59 addRegisterClass(MVT::i32, MBlaze::GPRRegisterClass);
60 if (Subtarget->hasFPU()) {
61 addRegisterClass(MVT::f32, MBlaze::GPRRegisterClass);
62 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
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);
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);
89 // Sign extended loads must be expanded
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
93 // MBlaze has no REM or DIVREM operations.
94 setOperationAction(ISD::UREM, MVT::i32, Expand);
95 setOperationAction(ISD::SREM, MVT::i32, Expand);
96 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
97 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
99 // If the processor doesn't support multiply then expand it
100 if (!Subtarget->hasMul()) {
101 setOperationAction(ISD::MUL, MVT::i32, Expand);
104 // If the processor doesn't support 64-bit multiply then expand
105 if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
106 setOperationAction(ISD::MULHS, MVT::i32, Expand);
107 setOperationAction(ISD::MULHS, MVT::i64, Expand);
108 setOperationAction(ISD::MULHU, MVT::i32, Expand);
109 setOperationAction(ISD::MULHU, MVT::i64, Expand);
112 // If the processor doesn't support division then expand
113 if (!Subtarget->hasDiv()) {
114 setOperationAction(ISD::UDIV, MVT::i32, Expand);
115 setOperationAction(ISD::SDIV, MVT::i32, Expand);
118 // Expand unsupported conversions
119 setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
120 setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
122 // Expand SELECT_CC
123 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
125 // MBlaze doesn't have MUL_LOHI
126 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
127 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
128 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
129 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
131 // Used by legalize types to correctly generate the setcc result.
132 // Without this, every float setcc comes with a AND/OR with the result,
133 // we don't want this, since the fpcmp result goes to a flag register,
134 // which is used implicitly by brcond and select operations.
135 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
136 AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
137 AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
139 // MBlaze Custom Operations
140 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
141 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
142 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
143 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
145 // Variable Argument support
146 setOperationAction(ISD::VASTART, MVT::Other, Custom);
147 setOperationAction(ISD::VAEND, MVT::Other, Expand);
148 setOperationAction(ISD::VAARG, MVT::Other, Expand);
149 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
152 // Operations not directly supported by MBlaze.
153 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
154 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
155 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
156 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
157 setOperationAction(ISD::ROTL, MVT::i32, Expand);
158 setOperationAction(ISD::ROTR, MVT::i32, Expand);
159 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
160 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
161 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
162 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
163 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
164 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
165 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
167 // We don't have line number support yet.
168 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
170 // Use the default for now
171 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
172 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
173 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
175 // MBlaze doesn't have extending float->double load/store
176 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
177 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
179 setStackPointerRegisterToSaveRestore(MBlaze::R1);
180 computeRegisterProperties();
183 MVT::SimpleValueType MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
184 return MVT::i32;
187 /// getFunctionAlignment - Return the Log2 alignment of this function.
188 unsigned MBlazeTargetLowering::getFunctionAlignment(const Function *) const {
189 return 2;
192 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
193 SelectionDAG &DAG) const {
194 switch (Op.getOpcode())
196 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
197 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
198 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
199 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
200 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
201 case ISD::VASTART: return LowerVASTART(Op, DAG);
203 return SDValue();
206 //===----------------------------------------------------------------------===//
207 // Lower helper functions
208 //===----------------------------------------------------------------------===//
209 MachineBasicBlock*
210 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
211 MachineBasicBlock *BB) const {
212 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
213 DebugLoc dl = MI->getDebugLoc();
215 switch (MI->getOpcode()) {
216 default: assert(false && "Unexpected instr type to insert");
217 case MBlaze::ShiftRL:
218 case MBlaze::ShiftRA:
219 case MBlaze::ShiftL: {
220 // To "insert" a shift left instruction, we actually have to insert a
221 // simple loop. The incoming instruction knows the destination vreg to
222 // set, the source vreg to operate over and the shift amount.
223 const BasicBlock *LLVM_BB = BB->getBasicBlock();
224 MachineFunction::iterator It = BB;
225 ++It;
227 // start:
228 // andi samt, samt, 31
229 // beqid samt, finish
230 // add dst, src, r0
231 // loop:
232 // addik samt, samt, -1
233 // sra dst, dst
234 // bneid samt, loop
235 // nop
236 // finish:
237 MachineFunction *F = BB->getParent();
238 MachineRegisterInfo &R = F->getRegInfo();
239 MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
240 MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
241 F->insert(It, loop);
242 F->insert(It, finish);
244 // Update machine-CFG edges by transfering adding all successors and
245 // remaining instructions from the current block to the new block which
246 // will contain the Phi node for the select.
247 finish->splice(finish->begin(), BB,
248 llvm::next(MachineBasicBlock::iterator(MI)),
249 BB->end());
250 finish->transferSuccessorsAndUpdatePHIs(BB);
252 // Add the true and fallthrough blocks as its successors.
253 BB->addSuccessor(loop);
254 BB->addSuccessor(finish);
256 // Next, add the finish block as a successor of the loop block
257 loop->addSuccessor(finish);
258 loop->addSuccessor(loop);
260 unsigned IAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
261 BuildMI(BB, dl, TII->get(MBlaze::ANDI), IAMT)
262 .addReg(MI->getOperand(2).getReg())
263 .addImm(31);
265 unsigned IVAL = R.createVirtualRegister(MBlaze::GPRRegisterClass);
266 BuildMI(BB, dl, TII->get(MBlaze::ADDI), IVAL)
267 .addReg(MI->getOperand(1).getReg())
268 .addImm(0);
270 BuildMI(BB, dl, TII->get(MBlaze::BEQID))
271 .addReg(IAMT)
272 .addMBB(finish);
274 unsigned DST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
275 unsigned NDST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
276 BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
277 .addReg(IVAL).addMBB(BB)
278 .addReg(NDST).addMBB(loop);
280 unsigned SAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
281 unsigned NAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
282 BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
283 .addReg(IAMT).addMBB(BB)
284 .addReg(NAMT).addMBB(loop);
286 if (MI->getOpcode() == MBlaze::ShiftL)
287 BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
288 else if (MI->getOpcode() == MBlaze::ShiftRA)
289 BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
290 else if (MI->getOpcode() == MBlaze::ShiftRL)
291 BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
292 else
293 llvm_unreachable( "Cannot lower unknown shift instruction" );
295 BuildMI(loop, dl, TII->get(MBlaze::ADDI), NAMT)
296 .addReg(SAMT)
297 .addImm(-1);
299 BuildMI(loop, dl, TII->get(MBlaze::BNEID))
300 .addReg(NAMT)
301 .addMBB(loop);
303 BuildMI(*finish, finish->begin(), dl,
304 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
305 .addReg(IVAL).addMBB(BB)
306 .addReg(NDST).addMBB(loop);
308 // The pseudo instruction is no longer needed so remove it
309 MI->eraseFromParent();
310 return finish;
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;
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);
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;
344 F->insert(It, flsBB);
345 F->insert(It, dneBB);
347 // Transfer the remainder of BB and its successor edges to dneBB.
348 dneBB->splice(dneBB->begin(), BB,
349 llvm::next(MachineBasicBlock::iterator(MI)),
350 BB->end());
351 dneBB->transferSuccessorsAndUpdatePHIs(BB);
353 BB->addSuccessor(flsBB);
354 BB->addSuccessor(dneBB);
355 flsBB->addSuccessor(dneBB);
357 BuildMI(BB, dl, TII->get(Opc))
358 .addReg(MI->getOperand(3).getReg())
359 .addMBB(dneBB);
361 // sinkMBB:
362 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
363 // ...
364 //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
365 // .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
366 // .addReg(MI->getOperand(2).getReg()).addMBB(BB);
368 BuildMI(*dneBB, dneBB->begin(), dl,
369 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
370 .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
371 .addReg(MI->getOperand(1).getReg()).addMBB(BB);
373 MI->eraseFromParent(); // The pseudo instruction is gone now.
374 return dneBB;
379 //===----------------------------------------------------------------------===//
380 // Misc Lower Operation implementation
381 //===----------------------------------------------------------------------===//
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;
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" );
402 return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
403 CompareFlag);
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, dl, MVT::i32);
413 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
416 SDValue MBlazeTargetLowering::
417 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
418 llvm_unreachable("TLS not implemented for MicroBlaze.");
419 return SDValue(); // Not reached
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();
429 EVT PtrVT = Op.getValueType();
430 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
432 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0 );
433 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
436 SDValue MBlazeTargetLowering::
437 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
438 SDValue ResNode;
439 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
440 const Constant *C = N->getConstVal();
441 DebugLoc dl = Op.getDebugLoc();
443 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
444 N->getOffset(), 0 );
445 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
448 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
449 SelectionDAG &DAG) const {
450 MachineFunction &MF = DAG.getMachineFunction();
451 MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
453 DebugLoc dl = Op.getDebugLoc();
454 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
455 getPointerTy());
457 // vastart just stores the address of the VarArgsFrameIndex slot into the
458 // memory location argument.
459 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
460 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
461 MachinePointerInfo(SV),
462 false, false, 0);
465 //===----------------------------------------------------------------------===//
466 // Calling Convention Implementation
467 //===----------------------------------------------------------------------===//
469 #include "MBlazeGenCallingConv.inc"
471 static bool CC_MBlaze2(unsigned ValNo, EVT ValVT,
472 MVT LocVT, CCValAssign::LocInfo LocInfo,
473 ISD::ArgFlagsTy ArgFlags, CCState &State) {
474 static const unsigned RegsSize=6;
475 static const unsigned IntRegs[] = {
476 MBlaze::R5, MBlaze::R6, MBlaze::R7,
477 MBlaze::R8, MBlaze::R9, MBlaze::R10
480 unsigned Reg=0;
482 // Promote i8 and i16
483 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
484 LocVT = MVT::i32;
485 if (ArgFlags.isSExt())
486 LocInfo = CCValAssign::SExt;
487 else if (ArgFlags.isZExt())
488 LocInfo = CCValAssign::ZExt;
489 else
490 LocInfo = CCValAssign::AExt;
493 if (ValVT == MVT::i32) {
494 Reg = State.AllocateReg(IntRegs, RegsSize);
495 LocVT = MVT::i32;
496 } else if (ValVT == MVT::f32) {
497 Reg = State.AllocateReg(IntRegs, RegsSize);
498 LocVT = MVT::f32;
501 if (!Reg) {
502 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
503 unsigned Offset = State.AllocateStack(SizeInBytes, SizeInBytes);
504 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
505 } else {
506 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
507 State.AllocateStack(SizeInBytes, SizeInBytes);
508 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
511 return false; // CC must always match
514 //===----------------------------------------------------------------------===//
515 // Call Calling Convention Implementation
516 //===----------------------------------------------------------------------===//
518 /// LowerCall - functions arguments are copied from virtual regs to
519 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
520 /// TODO: isVarArg, isTailCall.
521 SDValue MBlazeTargetLowering::
522 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
523 bool isVarArg, bool &isTailCall,
524 const SmallVectorImpl<ISD::OutputArg> &Outs,
525 const SmallVectorImpl<SDValue> &OutVals,
526 const SmallVectorImpl<ISD::InputArg> &Ins,
527 DebugLoc dl, SelectionDAG &DAG,
528 SmallVectorImpl<SDValue> &InVals) const {
529 // MBlaze does not yet support tail call optimization
530 isTailCall = false;
532 MachineFunction &MF = DAG.getMachineFunction();
533 MachineFrameInfo *MFI = MF.getFrameInfo();
535 // Analyze operands of the call, assigning locations to each operand.
536 SmallVector<CCValAssign, 16> ArgLocs;
537 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
538 *DAG.getContext());
539 CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze2);
541 // Get a count of how many bytes are to be pushed on the stack.
542 unsigned NumBytes = CCInfo.getNextStackOffset();
543 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
545 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
546 SmallVector<SDValue, 8> MemOpChains;
548 // First/LastArgStackLoc contains the first/last
549 // "at stack" argument location.
550 int LastArgStackLoc = 0;
551 unsigned FirstStackArgLoc = 0;
553 // Walk the register/memloc assignments, inserting copies/loads.
554 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
555 CCValAssign &VA = ArgLocs[i];
556 EVT RegVT = VA.getLocVT();
557 SDValue Arg = OutVals[i];
559 // Promote the value if needed.
560 switch (VA.getLocInfo()) {
561 default: llvm_unreachable("Unknown loc info!");
562 case CCValAssign::Full: break;
563 case CCValAssign::SExt:
564 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
565 break;
566 case CCValAssign::ZExt:
567 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
568 break;
569 case CCValAssign::AExt:
570 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
571 break;
574 // Arguments that can be passed on register must be kept at
575 // RegsToPass vector
576 if (VA.isRegLoc()) {
577 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
578 } else {
579 // Register can't get to this point...
580 assert(VA.isMemLoc());
582 // Create the frame index object for this incoming parameter
583 LastArgStackLoc = (FirstStackArgLoc + VA.getLocMemOffset());
584 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
585 LastArgStackLoc, true);
587 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
589 // emit ISD::STORE whichs stores the
590 // parameter value to a stack Location
591 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
592 MachinePointerInfo(),
593 false, false, 0));
597 // Transform all store nodes into one single node because all store
598 // nodes are independent of each other.
599 if (!MemOpChains.empty())
600 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
601 &MemOpChains[0], MemOpChains.size());
603 // Build a sequence of copy-to-reg nodes chained together with token
604 // chain and flag operands which copy the outgoing args into registers.
605 // The InFlag in necessary since all emited instructions must be
606 // stuck together.
607 SDValue InFlag;
608 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
609 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
610 RegsToPass[i].second, InFlag);
611 InFlag = Chain.getValue(1);
614 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
615 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
616 // node so that legalize doesn't hack it.
617 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
618 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
619 getPointerTy(), 0, 0 );
620 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
621 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
622 getPointerTy(), 0 );
624 // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
625 // = Chain, Callee, Reg#1, Reg#2, ...
627 // Returns a chain & a flag for retval copy to use.
628 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
629 SmallVector<SDValue, 8> Ops;
630 Ops.push_back(Chain);
631 Ops.push_back(Callee);
633 // Add argument registers to the end of the list so that they are
634 // known live into the call.
635 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
636 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
637 RegsToPass[i].second.getValueType()));
640 if (InFlag.getNode())
641 Ops.push_back(InFlag);
643 Chain = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
644 InFlag = Chain.getValue(1);
646 // Create the CALLSEQ_END node.
647 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
648 DAG.getIntPtrConstant(0, true), InFlag);
649 if (!Ins.empty())
650 InFlag = Chain.getValue(1);
652 // Handle result values, copying them out of physregs into vregs that we
653 // return.
654 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
655 Ins, dl, DAG, InVals);
658 /// LowerCallResult - Lower the result values of a call into the
659 /// appropriate copies out of appropriate physical registers.
660 SDValue MBlazeTargetLowering::
661 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
662 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
663 DebugLoc dl, SelectionDAG &DAG,
664 SmallVectorImpl<SDValue> &InVals) const {
665 // Assign locations to each value returned by this call.
666 SmallVector<CCValAssign, 16> RVLocs;
667 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
668 RVLocs, *DAG.getContext());
670 CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
672 // Copy all of the result registers out of their specified physreg.
673 for (unsigned i = 0; i != RVLocs.size(); ++i) {
674 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
675 RVLocs[i].getValVT(), InFlag).getValue(1);
676 InFlag = Chain.getValue(2);
677 InVals.push_back(Chain.getValue(0));
680 return Chain;
683 //===----------------------------------------------------------------------===//
684 // Formal Arguments Calling Convention Implementation
685 //===----------------------------------------------------------------------===//
687 /// LowerFormalArguments - transform physical registers into
688 /// virtual registers and generate load operations for
689 /// arguments places on the stack.
690 SDValue MBlazeTargetLowering::
691 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
692 const SmallVectorImpl<ISD::InputArg> &Ins,
693 DebugLoc dl, SelectionDAG &DAG,
694 SmallVectorImpl<SDValue> &InVals) const {
695 MachineFunction &MF = DAG.getMachineFunction();
696 MachineFrameInfo *MFI = MF.getFrameInfo();
697 MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
699 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
700 MBlazeFI->setVarArgsFrameIndex(0);
702 // Used with vargs to acumulate store chains.
703 std::vector<SDValue> OutChains;
705 // Keep track of the last register used for arguments
706 unsigned ArgRegEnd = 0;
708 // Assign locations to all of the incoming arguments.
709 SmallVector<CCValAssign, 16> ArgLocs;
710 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
711 ArgLocs, *DAG.getContext());
713 CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze2);
714 SDValue StackPtr;
716 unsigned FirstStackArgLoc = 0;
718 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
719 CCValAssign &VA = ArgLocs[i];
721 // Arguments stored on registers
722 if (VA.isRegLoc()) {
723 EVT RegVT = VA.getLocVT();
724 ArgRegEnd = VA.getLocReg();
725 TargetRegisterClass *RC = 0;
727 if (RegVT == MVT::i32)
728 RC = MBlaze::GPRRegisterClass;
729 else if (RegVT == MVT::f32)
730 RC = MBlaze::GPRRegisterClass;
731 else
732 llvm_unreachable("RegVT not supported by LowerFormalArguments");
734 // Transform the arguments stored on
735 // physical registers into virtual ones
736 unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
737 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
739 // If this is an 8 or 16-bit value, it has been passed promoted
740 // to 32 bits. Insert an assert[sz]ext to capture this, then
741 // truncate to the right size. If if is a floating point value
742 // then convert to the correct type.
743 if (VA.getLocInfo() != CCValAssign::Full) {
744 unsigned Opcode = 0;
745 if (VA.getLocInfo() == CCValAssign::SExt)
746 Opcode = ISD::AssertSext;
747 else if (VA.getLocInfo() == CCValAssign::ZExt)
748 Opcode = ISD::AssertZext;
749 if (Opcode)
750 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
751 DAG.getValueType(VA.getValVT()));
752 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
755 InVals.push_back(ArgValue);
757 } else { // VA.isRegLoc()
759 // sanity check
760 assert(VA.isMemLoc());
762 // The last argument is not a register
763 ArgRegEnd = 0;
765 // The stack pointer offset is relative to the caller stack frame.
766 // Since the real stack size is unknown here, a negative SPOffset
767 // is used so there's a way to adjust these offsets when the stack
768 // size get known (on EliminateFrameIndex). A dummy SPOffset is
769 // used instead of a direct negative address (which is recorded to
770 // be used on emitPrologue) to avoid mis-calc of the first stack
771 // offset on PEI::calculateFrameObjectOffsets.
772 // Arguments are always 32-bit.
773 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
774 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
775 MBlazeFI->recordLoadArgsFI(FI, -(ArgSize+
776 (FirstStackArgLoc + VA.getLocMemOffset())));
778 // Create load nodes to retrieve arguments from the stack
779 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
780 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
781 MachinePointerInfo::getFixedStack(FI),
782 false, false, 0));
786 // To meet ABI, when VARARGS are passed on registers, the registers
787 // must have their values written to the caller stack frame. If the last
788 // argument was placed in the stack, there's no need to save any register.
789 if ((isVarArg) && ArgRegEnd) {
790 if (StackPtr.getNode() == 0)
791 StackPtr = DAG.getRegister(StackReg, getPointerTy());
793 // The last register argument that must be saved is MBlaze::R10
794 TargetRegisterClass *RC = MBlaze::GPRRegisterClass;
796 unsigned Begin = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R5);
797 unsigned Start = MBlazeRegisterInfo::getRegisterNumbering(ArgRegEnd+1);
798 unsigned End = MBlazeRegisterInfo::getRegisterNumbering(MBlaze::R10);
799 unsigned StackLoc = ArgLocs.size()-1 + (Start - Begin);
801 for (; Start <= End; ++Start, ++StackLoc) {
802 unsigned Reg = MBlazeRegisterInfo::getRegisterFromNumbering(Start);
803 unsigned LiveReg = MF.addLiveIn(Reg, RC);
804 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
806 int FI = MFI->CreateFixedObject(4, 0, true);
807 MBlazeFI->recordStoreVarArgsFI(FI, -(4+(StackLoc*4)));
808 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
809 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
810 MachinePointerInfo(),
811 false, false, 0));
813 // Record the frame index of the first variable argument
814 // which is a value necessary to VASTART.
815 if (!MBlazeFI->getVarArgsFrameIndex())
816 MBlazeFI->setVarArgsFrameIndex(FI);
820 // All stores are grouped in one node to allow the matching between
821 // the size of Ins and InVals. This only happens when on varg functions
822 if (!OutChains.empty()) {
823 OutChains.push_back(Chain);
824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
825 &OutChains[0], OutChains.size());
828 return Chain;
831 //===----------------------------------------------------------------------===//
832 // Return Value Calling Convention Implementation
833 //===----------------------------------------------------------------------===//
835 SDValue MBlazeTargetLowering::
836 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
837 const SmallVectorImpl<ISD::OutputArg> &Outs,
838 const SmallVectorImpl<SDValue> &OutVals,
839 DebugLoc dl, SelectionDAG &DAG) const {
840 // CCValAssign - represent the assignment of
841 // the return value to a location
842 SmallVector<CCValAssign, 16> RVLocs;
844 // CCState - Info about the registers and stack slot.
845 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
846 RVLocs, *DAG.getContext());
848 // Analize return values.
849 CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
851 // If this is the first return lowered for this function, add
852 // the regs to the liveout set for the function.
853 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
854 for (unsigned i = 0; i != RVLocs.size(); ++i)
855 if (RVLocs[i].isRegLoc())
856 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
859 SDValue Flag;
861 // Copy the result values into the output registers.
862 for (unsigned i = 0; i != RVLocs.size(); ++i) {
863 CCValAssign &VA = RVLocs[i];
864 assert(VA.isRegLoc() && "Can only return in registers!");
866 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
867 OutVals[i], Flag);
869 // guarantee that all emitted copies are
870 // stuck together, avoiding something bad
871 Flag = Chain.getValue(1);
874 // Return on MBlaze is always a "rtsd R15, 8"
875 if (Flag.getNode())
876 return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
877 Chain, DAG.getRegister(MBlaze::R15, MVT::i32), Flag);
878 else // Return Void
879 return DAG.getNode(MBlazeISD::Ret, dl, MVT::Other,
880 Chain, DAG.getRegister(MBlaze::R15, MVT::i32));
883 //===----------------------------------------------------------------------===//
884 // MBlaze Inline Assembly Support
885 //===----------------------------------------------------------------------===//
887 /// getConstraintType - Given a constraint letter, return the type of
888 /// constraint it is for this target.
889 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
890 getConstraintType(const std::string &Constraint) const
892 // MBlaze specific constrainy
894 // 'd' : An address register. Equivalent to r.
895 // 'y' : Equivalent to r; retained for
896 // backwards compatibility.
897 // 'f' : Floating Point registers.
898 if (Constraint.size() == 1) {
899 switch (Constraint[0]) {
900 default : break;
901 case 'd':
902 case 'y':
903 case 'f':
904 return C_RegisterClass;
905 break;
908 return TargetLowering::getConstraintType(Constraint);
911 /// Examine constraint type and operand type and determine a weight value.
912 /// This object must already have been set up with the operand type
913 /// and the current alternative constraint selected.
914 TargetLowering::ConstraintWeight
915 MBlazeTargetLowering::getSingleConstraintMatchWeight(
916 AsmOperandInfo &info, const char *constraint) const {
917 ConstraintWeight weight = CW_Invalid;
918 Value *CallOperandVal = info.CallOperandVal;
919 // If we don't have a value, we can't do a match,
920 // but allow it at the lowest weight.
921 if (CallOperandVal == NULL)
922 return CW_Default;
923 const Type *type = CallOperandVal->getType();
924 // Look at the constraint type.
925 switch (*constraint) {
926 default:
927 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
928 break;
929 case 'd':
930 case 'y':
931 if (type->isIntegerTy())
932 weight = CW_Register;
933 break;
934 case 'f':
935 if (type->isFloatTy())
936 weight = CW_Register;
937 break;
939 return weight;
942 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"),
943 /// return a list of registers that can be used to satisfy the constraint.
944 /// This should only be used for C_RegisterClass constraints.
945 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
946 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
947 if (Constraint.size() == 1) {
948 switch (Constraint[0]) {
949 case 'r':
950 return std::make_pair(0U, MBlaze::GPRRegisterClass);
951 case 'f':
952 if (VT == MVT::f32)
953 return std::make_pair(0U, MBlaze::GPRRegisterClass);
956 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
959 /// Given a register class constraint, like 'r', if this corresponds directly
960 /// to an LLVM register class, return a register of 0 and the register class
961 /// pointer.
962 std::vector<unsigned> MBlazeTargetLowering::
963 getRegClassForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
964 if (Constraint.size() != 1)
965 return std::vector<unsigned>();
967 switch (Constraint[0]) {
968 default : break;
969 case 'r':
970 // GCC MBlaze Constraint Letters
971 case 'd':
972 case 'y':
973 case 'f':
974 return make_vector<unsigned>(
975 MBlaze::R3, MBlaze::R4, MBlaze::R5, MBlaze::R6,
976 MBlaze::R7, MBlaze::R9, MBlaze::R10, MBlaze::R11,
977 MBlaze::R12, MBlaze::R19, MBlaze::R20, MBlaze::R21,
978 MBlaze::R22, MBlaze::R23, MBlaze::R24, MBlaze::R25,
979 MBlaze::R26, MBlaze::R27, MBlaze::R28, MBlaze::R29,
980 MBlaze::R30, MBlaze::R31, 0);
982 return std::vector<unsigned>();
985 bool MBlazeTargetLowering::
986 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
987 // The MBlaze target isn't yet aware of offsets.
988 return false;
991 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
992 return VT != MVT::f32;