1 //===-- MBlazeISelLowering.cpp - MBlaze DAG Lowering Implementation -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that MBlaze uses to lower LLVM code into a
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"
38 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
39 CCValAssign::LocInfo &LocInfo,
40 ISD::ArgFlagsTy &ArgFlags,
43 const char *MBlazeTargetLowering::getTargetNodeName(unsigned Opcode) const {
45 case MBlazeISD::JmpLink : return "MBlazeISD::JmpLink";
46 case MBlazeISD::GPRel : return "MBlazeISD::GPRel";
47 case MBlazeISD::Wrap : return "MBlazeISD::Wrap";
48 case MBlazeISD::ICmp : return "MBlazeISD::ICmp";
49 case MBlazeISD::Ret : return "MBlazeISD::Ret";
50 case MBlazeISD::Select_CC : return "MBlazeISD::Select_CC";
51 default : return NULL;
55 MBlazeTargetLowering::MBlazeTargetLowering(MBlazeTargetMachine &TM)
56 : TargetLowering(TM, new MBlazeTargetObjectFile()) {
57 Subtarget = &TM.getSubtarget<MBlazeSubtarget>();
59 // MBlaze does not have i1 type, so use i32 for
60 // setcc operations results (slt, sgt, ...).
61 setBooleanContents(ZeroOrOneBooleanContent);
62 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
64 // Set up the register classes
65 addRegisterClass(MVT::i32, MBlaze::GPRRegisterClass);
66 if (Subtarget->hasFPU()) {
67 addRegisterClass(MVT::f32, MBlaze::GPRRegisterClass);
68 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
71 // Floating point operations which are not supported
72 setOperationAction(ISD::FREM, MVT::f32, Expand);
73 setOperationAction(ISD::FMA, MVT::f32, Expand);
74 setOperationAction(ISD::UINT_TO_FP, MVT::i8, Expand);
75 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Expand);
76 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
77 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
78 setOperationAction(ISD::FP_ROUND, MVT::f32, Expand);
79 setOperationAction(ISD::FP_ROUND, MVT::f64, Expand);
80 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
81 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
82 setOperationAction(ISD::FSIN, MVT::f32, Expand);
83 setOperationAction(ISD::FCOS, MVT::f32, Expand);
84 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
85 setOperationAction(ISD::FPOW, MVT::f32, Expand);
86 setOperationAction(ISD::FLOG, MVT::f32, Expand);
87 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
88 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
89 setOperationAction(ISD::FEXP, MVT::f32, Expand);
91 // Load extented operations for i1 types must be promoted
92 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
94 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
96 // Sign extended loads must be expanded
97 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
98 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
100 // MBlaze has no REM or DIVREM operations.
101 setOperationAction(ISD::UREM, MVT::i32, Expand);
102 setOperationAction(ISD::SREM, MVT::i32, Expand);
103 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
104 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
106 // If the processor doesn't support multiply then expand it
107 if (!Subtarget->hasMul()) {
108 setOperationAction(ISD::MUL, MVT::i32, Expand);
111 // If the processor doesn't support 64-bit multiply then expand
112 if (!Subtarget->hasMul() || !Subtarget->hasMul64()) {
113 setOperationAction(ISD::MULHS, MVT::i32, Expand);
114 setOperationAction(ISD::MULHS, MVT::i64, Expand);
115 setOperationAction(ISD::MULHU, MVT::i32, Expand);
116 setOperationAction(ISD::MULHU, MVT::i64, Expand);
119 // If the processor doesn't support division then expand
120 if (!Subtarget->hasDiv()) {
121 setOperationAction(ISD::UDIV, MVT::i32, Expand);
122 setOperationAction(ISD::SDIV, MVT::i32, Expand);
125 // Expand unsupported conversions
126 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
127 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
130 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
132 // MBlaze doesn't have MUL_LOHI
133 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
134 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
135 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
136 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
138 // Used by legalize types to correctly generate the setcc result.
139 // Without this, every float setcc comes with a AND/OR with the result,
140 // we don't want this, since the fpcmp result goes to a flag register,
141 // which is used implicitly by brcond and select operations.
142 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
143 AddPromotedToType(ISD::SELECT, MVT::i1, MVT::i32);
144 AddPromotedToType(ISD::SELECT_CC, MVT::i1, MVT::i32);
146 // MBlaze Custom Operations
147 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
148 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
149 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
150 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
152 // Variable Argument support
153 setOperationAction(ISD::VASTART, MVT::Other, Custom);
154 setOperationAction(ISD::VAEND, MVT::Other, Expand);
155 setOperationAction(ISD::VAARG, MVT::Other, Expand);
156 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
159 // Operations not directly supported by MBlaze.
160 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
161 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
162 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
163 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
164 setOperationAction(ISD::ROTL, MVT::i32, Expand);
165 setOperationAction(ISD::ROTR, MVT::i32, Expand);
166 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
167 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
168 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
169 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
170 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
171 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
172 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
174 // We don't have line number support yet.
175 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
177 // Use the default for now
178 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
179 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
181 // MBlaze doesn't have extending float->double load/store
182 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
183 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
185 setMinFunctionAlignment(2);
187 setStackPointerRegisterToSaveRestore(MBlaze::R1);
188 computeRegisterProperties();
191 EVT MBlazeTargetLowering::getSetCCResultType(EVT VT) const {
195 SDValue MBlazeTargetLowering::LowerOperation(SDValue Op,
196 SelectionDAG &DAG) const {
197 switch (Op.getOpcode())
199 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
200 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
201 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
202 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
203 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
204 case ISD::VASTART: return LowerVASTART(Op, DAG);
209 //===----------------------------------------------------------------------===//
210 // Lower helper functions
211 //===----------------------------------------------------------------------===//
213 MBlazeTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
214 MachineBasicBlock *MBB)
216 switch (MI->getOpcode()) {
217 default: assert(false && "Unexpected instr type to insert");
219 case MBlaze::ShiftRL:
220 case MBlaze::ShiftRA:
222 return EmitCustomShift(MI, MBB);
224 case MBlaze::Select_FCC:
225 case MBlaze::Select_CC:
226 return EmitCustomSelect(MI, MBB);
236 return EmitCustomAtomic(MI, MBB);
238 case MBlaze::MEMBARRIER:
239 // The Microblaze does not need memory barriers. Just delete the pseudo
240 // instruction and finish.
241 MI->eraseFromParent();
247 MBlazeTargetLowering::EmitCustomShift(MachineInstr *MI,
248 MachineBasicBlock *MBB) const {
249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
250 DebugLoc dl = MI->getDebugLoc();
252 // To "insert" a shift left instruction, we actually have to insert a
253 // simple loop. The incoming instruction knows the destination vreg to
254 // set, the source vreg to operate over and the shift amount.
255 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
256 MachineFunction::iterator It = MBB;
260 // andi samt, samt, 31
261 // beqid samt, finish
264 // addik samt, samt, -1
269 MachineFunction *F = MBB->getParent();
270 MachineRegisterInfo &R = F->getRegInfo();
271 MachineBasicBlock *loop = F->CreateMachineBasicBlock(LLVM_BB);
272 MachineBasicBlock *finish = F->CreateMachineBasicBlock(LLVM_BB);
274 F->insert(It, finish);
276 // Update machine-CFG edges by transferring adding all successors and
277 // remaining instructions from the current block to the new block which
278 // will contain the Phi node for the select.
279 finish->splice(finish->begin(), MBB,
280 llvm::next(MachineBasicBlock::iterator(MI)),
282 finish->transferSuccessorsAndUpdatePHIs(MBB);
284 // Add the true and fallthrough blocks as its successors.
285 MBB->addSuccessor(loop);
286 MBB->addSuccessor(finish);
288 // Next, add the finish block as a successor of the loop block
289 loop->addSuccessor(finish);
290 loop->addSuccessor(loop);
292 unsigned IAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
293 BuildMI(MBB, dl, TII->get(MBlaze::ANDI), IAMT)
294 .addReg(MI->getOperand(2).getReg())
297 unsigned IVAL = R.createVirtualRegister(MBlaze::GPRRegisterClass);
298 BuildMI(MBB, dl, TII->get(MBlaze::ADDIK), IVAL)
299 .addReg(MI->getOperand(1).getReg())
302 BuildMI(MBB, dl, TII->get(MBlaze::BEQID))
306 unsigned DST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
307 unsigned NDST = R.createVirtualRegister(MBlaze::GPRRegisterClass);
308 BuildMI(loop, dl, TII->get(MBlaze::PHI), DST)
309 .addReg(IVAL).addMBB(MBB)
310 .addReg(NDST).addMBB(loop);
312 unsigned SAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
313 unsigned NAMT = R.createVirtualRegister(MBlaze::GPRRegisterClass);
314 BuildMI(loop, dl, TII->get(MBlaze::PHI), SAMT)
315 .addReg(IAMT).addMBB(MBB)
316 .addReg(NAMT).addMBB(loop);
318 if (MI->getOpcode() == MBlaze::ShiftL)
319 BuildMI(loop, dl, TII->get(MBlaze::ADD), NDST).addReg(DST).addReg(DST);
320 else if (MI->getOpcode() == MBlaze::ShiftRA)
321 BuildMI(loop, dl, TII->get(MBlaze::SRA), NDST).addReg(DST);
322 else if (MI->getOpcode() == MBlaze::ShiftRL)
323 BuildMI(loop, dl, TII->get(MBlaze::SRL), NDST).addReg(DST);
325 llvm_unreachable("Cannot lower unknown shift instruction");
327 BuildMI(loop, dl, TII->get(MBlaze::ADDIK), NAMT)
331 BuildMI(loop, dl, TII->get(MBlaze::BNEID))
335 BuildMI(*finish, finish->begin(), dl,
336 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
337 .addReg(IVAL).addMBB(MBB)
338 .addReg(NDST).addMBB(loop);
340 // The pseudo instruction is no longer needed so remove it
341 MI->eraseFromParent();
346 MBlazeTargetLowering::EmitCustomSelect(MachineInstr *MI,
347 MachineBasicBlock *MBB) const {
348 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
349 DebugLoc dl = MI->getDebugLoc();
351 // To "insert" a SELECT_CC instruction, we actually have to insert the
352 // diamond control-flow pattern. The incoming instruction knows the
353 // destination vreg to set, the condition code register to branch on, the
354 // true/false values to select between, and a branch opcode to use.
355 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
356 MachineFunction::iterator It = MBB;
363 // bNE r1, r0, copy1MBB
364 // fallthrough --> copy0MBB
365 MachineFunction *F = MBB->getParent();
366 MachineBasicBlock *flsBB = F->CreateMachineBasicBlock(LLVM_BB);
367 MachineBasicBlock *dneBB = F->CreateMachineBasicBlock(LLVM_BB);
370 switch (MI->getOperand(4).getImm()) {
371 default: llvm_unreachable("Unknown branch condition");
372 case MBlazeCC::EQ: Opc = MBlaze::BEQID; break;
373 case MBlazeCC::NE: Opc = MBlaze::BNEID; break;
374 case MBlazeCC::GT: Opc = MBlaze::BGTID; break;
375 case MBlazeCC::LT: Opc = MBlaze::BLTID; break;
376 case MBlazeCC::GE: Opc = MBlaze::BGEID; break;
377 case MBlazeCC::LE: Opc = MBlaze::BLEID; break;
380 F->insert(It, flsBB);
381 F->insert(It, dneBB);
383 // Transfer the remainder of MBB and its successor edges to dneBB.
384 dneBB->splice(dneBB->begin(), MBB,
385 llvm::next(MachineBasicBlock::iterator(MI)),
387 dneBB->transferSuccessorsAndUpdatePHIs(MBB);
389 MBB->addSuccessor(flsBB);
390 MBB->addSuccessor(dneBB);
391 flsBB->addSuccessor(dneBB);
393 BuildMI(MBB, dl, TII->get(Opc))
394 .addReg(MI->getOperand(3).getReg())
398 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
400 //BuildMI(dneBB, dl, TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
401 // .addReg(MI->getOperand(1).getReg()).addMBB(flsBB)
402 // .addReg(MI->getOperand(2).getReg()).addMBB(BB);
404 BuildMI(*dneBB, dneBB->begin(), dl,
405 TII->get(MBlaze::PHI), MI->getOperand(0).getReg())
406 .addReg(MI->getOperand(2).getReg()).addMBB(flsBB)
407 .addReg(MI->getOperand(1).getReg()).addMBB(MBB);
409 MI->eraseFromParent(); // The pseudo instruction is gone now.
414 MBlazeTargetLowering::EmitCustomAtomic(MachineInstr *MI,
415 MachineBasicBlock *MBB) const {
416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
417 DebugLoc dl = MI->getDebugLoc();
419 // All atomic instructions on the Microblaze are implemented using the
420 // load-linked / store-conditional style atomic instruction sequences.
421 // Thus, all operations will look something like the following:
432 // To "insert" a shift left instruction, we actually have to insert a
433 // simple loop. The incoming instruction knows the destination vreg to
434 // set, the source vreg to operate over and the shift amount.
435 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
436 MachineFunction::iterator It = MBB;
440 // andi samt, samt, 31
441 // beqid samt, finish
444 // addik samt, samt, -1
449 MachineFunction *F = MBB->getParent();
450 MachineRegisterInfo &R = F->getRegInfo();
452 // Create the start and exit basic blocks for the atomic operation
453 MachineBasicBlock *start = F->CreateMachineBasicBlock(LLVM_BB);
454 MachineBasicBlock *exit = F->CreateMachineBasicBlock(LLVM_BB);
455 F->insert(It, start);
458 // Update machine-CFG edges by transferring adding all successors and
459 // remaining instructions from the current block to the new block which
460 // will contain the Phi node for the select.
461 exit->splice(exit->begin(), MBB, llvm::next(MachineBasicBlock::iterator(MI)),
463 exit->transferSuccessorsAndUpdatePHIs(MBB);
465 // Add the fallthrough block as its successors.
466 MBB->addSuccessor(start);
468 BuildMI(start, dl, TII->get(MBlaze::LWX), MI->getOperand(0).getReg())
469 .addReg(MI->getOperand(1).getReg())
472 MachineBasicBlock *final = start;
473 unsigned finalReg = 0;
475 switch (MI->getOpcode()) {
476 default: llvm_unreachable("Cannot lower unknown atomic instruction!");
479 finalReg = MI->getOperand(2).getReg();
480 start->addSuccessor(exit);
481 start->addSuccessor(start);
489 case MBlaze::LAA32: {
491 switch (MI->getOpcode()) {
492 default: llvm_unreachable("Cannot lower unknown atomic load!");
493 case MBlaze::LAA32: opcode = MBlaze::ADDIK; break;
494 case MBlaze::LAS32: opcode = MBlaze::RSUBIK; break;
495 case MBlaze::LAD32: opcode = MBlaze::AND; break;
496 case MBlaze::LAO32: opcode = MBlaze::OR; break;
497 case MBlaze::LAX32: opcode = MBlaze::XOR; break;
498 case MBlaze::LAN32: opcode = MBlaze::AND; break;
501 finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
502 start->addSuccessor(exit);
503 start->addSuccessor(start);
505 BuildMI(start, dl, TII->get(opcode), finalReg)
506 .addReg(MI->getOperand(0).getReg())
507 .addReg(MI->getOperand(2).getReg());
509 if (MI->getOpcode() == MBlaze::LAN32) {
510 unsigned tmp = finalReg;
511 finalReg = R.createVirtualRegister(MBlaze::GPRRegisterClass);
512 BuildMI(start, dl, TII->get(MBlaze::XORI), finalReg)
519 case MBlaze::CAS32: {
520 finalReg = MI->getOperand(3).getReg();
521 final = F->CreateMachineBasicBlock(LLVM_BB);
523 F->insert(It, final);
524 start->addSuccessor(exit);
525 start->addSuccessor(final);
526 final->addSuccessor(exit);
527 final->addSuccessor(start);
529 unsigned CMP = R.createVirtualRegister(MBlaze::GPRRegisterClass);
530 BuildMI(start, dl, TII->get(MBlaze::CMP), CMP)
531 .addReg(MI->getOperand(0).getReg())
532 .addReg(MI->getOperand(2).getReg());
534 BuildMI(start, dl, TII->get(MBlaze::BNEID))
538 final->moveAfter(start);
539 exit->moveAfter(final);
544 unsigned CHK = R.createVirtualRegister(MBlaze::GPRRegisterClass);
545 BuildMI(final, dl, TII->get(MBlaze::SWX))
547 .addReg(MI->getOperand(1).getReg())
550 BuildMI(final, dl, TII->get(MBlaze::ADDIC), CHK)
554 BuildMI(final, dl, TII->get(MBlaze::BNEID))
558 // The pseudo instruction is no longer needed so remove it
559 MI->eraseFromParent();
563 //===----------------------------------------------------------------------===//
564 // Misc Lower Operation implementation
565 //===----------------------------------------------------------------------===//
568 SDValue MBlazeTargetLowering::LowerSELECT_CC(SDValue Op,
569 SelectionDAG &DAG) const {
570 SDValue LHS = Op.getOperand(0);
571 SDValue RHS = Op.getOperand(1);
572 SDValue TrueVal = Op.getOperand(2);
573 SDValue FalseVal = Op.getOperand(3);
574 DebugLoc dl = Op.getDebugLoc();
578 if (LHS.getValueType() == MVT::i32) {
579 Opc = MBlazeISD::Select_CC;
580 CompareFlag = DAG.getNode(MBlazeISD::ICmp, dl, MVT::i32, LHS, RHS)
583 llvm_unreachable("Cannot lower select_cc with unknown type");
586 return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
590 SDValue MBlazeTargetLowering::
591 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
592 // FIXME there isn't actually debug info here
593 DebugLoc dl = Op.getDebugLoc();
594 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
595 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
597 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, GA);
600 SDValue MBlazeTargetLowering::
601 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
602 llvm_unreachable("TLS not implemented for MicroBlaze.");
603 return SDValue(); // Not reached
606 SDValue MBlazeTargetLowering::
607 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
610 // FIXME there isn't actually debug info here
611 DebugLoc dl = Op.getDebugLoc();
613 EVT PtrVT = Op.getValueType();
614 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
616 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 0);
617 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, JTI);
620 SDValue MBlazeTargetLowering::
621 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
623 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
624 const Constant *C = N->getConstVal();
625 DebugLoc dl = Op.getDebugLoc();
627 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
629 return DAG.getNode(MBlazeISD::Wrap, dl, MVT::i32, CP);
632 SDValue MBlazeTargetLowering::LowerVASTART(SDValue Op,
633 SelectionDAG &DAG) const {
634 MachineFunction &MF = DAG.getMachineFunction();
635 MBlazeFunctionInfo *FuncInfo = MF.getInfo<MBlazeFunctionInfo>();
637 DebugLoc dl = Op.getDebugLoc();
638 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
641 // vastart just stores the address of the VarArgsFrameIndex slot into the
642 // memory location argument.
643 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
644 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
645 MachinePointerInfo(SV),
649 //===----------------------------------------------------------------------===//
650 // Calling Convention Implementation
651 //===----------------------------------------------------------------------===//
653 #include "MBlazeGenCallingConv.inc"
655 static bool CC_MBlaze_AssignReg(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
656 CCValAssign::LocInfo &LocInfo,
657 ISD::ArgFlagsTy &ArgFlags,
659 static const unsigned ArgRegs[] = {
660 MBlaze::R5, MBlaze::R6, MBlaze::R7,
661 MBlaze::R8, MBlaze::R9, MBlaze::R10
664 const unsigned NumArgRegs = array_lengthof(ArgRegs);
665 unsigned Reg = State.AllocateReg(ArgRegs, NumArgRegs);
666 if (!Reg) return false;
668 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
669 State.AllocateStack(SizeInBytes, SizeInBytes);
670 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
675 //===----------------------------------------------------------------------===//
676 // Call Calling Convention Implementation
677 //===----------------------------------------------------------------------===//
679 /// LowerCall - functions arguments are copied from virtual regs to
680 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
681 /// TODO: isVarArg, isTailCall.
682 SDValue MBlazeTargetLowering::
683 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
684 bool isVarArg, bool &isTailCall,
685 const SmallVectorImpl<ISD::OutputArg> &Outs,
686 const SmallVectorImpl<SDValue> &OutVals,
687 const SmallVectorImpl<ISD::InputArg> &Ins,
688 DebugLoc dl, SelectionDAG &DAG,
689 SmallVectorImpl<SDValue> &InVals) const {
690 // MBlaze does not yet support tail call optimization
693 // The MBlaze requires stack slots for arguments passed to var arg
694 // functions even if they are passed in registers.
695 bool needsRegArgSlots = isVarArg;
697 MachineFunction &MF = DAG.getMachineFunction();
698 MachineFrameInfo *MFI = MF.getFrameInfo();
699 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
701 // Analyze operands of the call, assigning locations to each operand.
702 SmallVector<CCValAssign, 16> ArgLocs;
703 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
704 getTargetMachine(), ArgLocs, *DAG.getContext());
705 CCInfo.AnalyzeCallOperands(Outs, CC_MBlaze);
707 // Get a count of how many bytes are to be pushed on the stack.
708 unsigned NumBytes = CCInfo.getNextStackOffset();
710 // Variable argument function calls require a minimum of 24-bytes of stack
711 if (isVarArg && NumBytes < 24) NumBytes = 24;
713 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
715 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
716 SmallVector<SDValue, 8> MemOpChains;
718 // Walk the register/memloc assignments, inserting copies/loads.
719 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
720 CCValAssign &VA = ArgLocs[i];
721 MVT RegVT = VA.getLocVT();
722 SDValue Arg = OutVals[i];
724 // Promote the value if needed.
725 switch (VA.getLocInfo()) {
726 default: llvm_unreachable("Unknown loc info!");
727 case CCValAssign::Full: break;
728 case CCValAssign::SExt:
729 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
731 case CCValAssign::ZExt:
732 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
734 case CCValAssign::AExt:
735 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
739 // Arguments that can be passed on register must be kept at
742 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
744 // Register can't get to this point...
745 assert(VA.isMemLoc());
747 // Since we are alread passing values on the stack we don't
748 // need to worry about creating additional slots for the
749 // values passed via registers.
750 needsRegArgSlots = false;
752 // Create the frame index object for this incoming parameter
753 unsigned ArgSize = VA.getValVT().getSizeInBits()/8;
754 unsigned StackLoc = VA.getLocMemOffset() + 4;
755 int FI = MFI->CreateFixedObject(ArgSize, StackLoc, true);
757 SDValue PtrOff = DAG.getFrameIndex(FI,getPointerTy());
759 // emit ISD::STORE whichs stores the
760 // parameter value to a stack Location
761 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
762 MachinePointerInfo(),
767 // If we need to reserve stack space for the arguments passed via registers
768 // then create a fixed stack object at the beginning of the stack.
769 if (needsRegArgSlots && TFI.hasReservedCallFrame(MF))
770 MFI->CreateFixedObject(28,0,true);
772 // Transform all store nodes into one single node because all store
773 // nodes are independent of each other.
774 if (!MemOpChains.empty())
775 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
776 &MemOpChains[0], MemOpChains.size());
778 // Build a sequence of copy-to-reg nodes chained together with token
779 // chain and flag operands which copy the outgoing args into registers.
780 // The InFlag in necessary since all emitted instructions must be
783 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
784 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
785 RegsToPass[i].second, InFlag);
786 InFlag = Chain.getValue(1);
789 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
790 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
791 // node so that legalize doesn't hack it.
792 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
793 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
794 getPointerTy(), 0, 0);
795 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
796 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
799 // MBlazeJmpLink = #chain, #target_address, #opt_in_flags...
800 // = Chain, Callee, Reg#1, Reg#2, ...
802 // Returns a chain & a flag for retval copy to use.
803 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
804 SmallVector<SDValue, 8> Ops;
805 Ops.push_back(Chain);
806 Ops.push_back(Callee);
808 // Add argument registers to the end of the list so that they are
809 // known live into the call.
810 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
811 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
812 RegsToPass[i].second.getValueType()));
815 if (InFlag.getNode())
816 Ops.push_back(InFlag);
818 Chain = DAG.getNode(MBlazeISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
819 InFlag = Chain.getValue(1);
821 // Create the CALLSEQ_END node.
822 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
823 DAG.getIntPtrConstant(0, true), InFlag);
825 InFlag = Chain.getValue(1);
827 // Handle result values, copying them out of physregs into vregs that we
829 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
830 Ins, dl, DAG, InVals);
833 /// LowerCallResult - Lower the result values of a call into the
834 /// appropriate copies out of appropriate physical registers.
835 SDValue MBlazeTargetLowering::
836 LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv,
837 bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins,
838 DebugLoc dl, SelectionDAG &DAG,
839 SmallVectorImpl<SDValue> &InVals) const {
840 // Assign locations to each value returned by this call.
841 SmallVector<CCValAssign, 16> RVLocs;
842 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
843 getTargetMachine(), RVLocs, *DAG.getContext());
845 CCInfo.AnalyzeCallResult(Ins, RetCC_MBlaze);
847 // Copy all of the result registers out of their specified physreg.
848 for (unsigned i = 0; i != RVLocs.size(); ++i) {
849 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
850 RVLocs[i].getValVT(), InFlag).getValue(1);
851 InFlag = Chain.getValue(2);
852 InVals.push_back(Chain.getValue(0));
858 //===----------------------------------------------------------------------===//
859 // Formal Arguments Calling Convention Implementation
860 //===----------------------------------------------------------------------===//
862 /// LowerFormalArguments - transform physical registers into
863 /// virtual registers and generate load operations for
864 /// arguments places on the stack.
865 SDValue MBlazeTargetLowering::
866 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
867 const SmallVectorImpl<ISD::InputArg> &Ins,
868 DebugLoc dl, SelectionDAG &DAG,
869 SmallVectorImpl<SDValue> &InVals) const {
870 MachineFunction &MF = DAG.getMachineFunction();
871 MachineFrameInfo *MFI = MF.getFrameInfo();
872 MBlazeFunctionInfo *MBlazeFI = MF.getInfo<MBlazeFunctionInfo>();
874 unsigned StackReg = MF.getTarget().getRegisterInfo()->getFrameRegister(MF);
875 MBlazeFI->setVarArgsFrameIndex(0);
877 // Used with vargs to acumulate store chains.
878 std::vector<SDValue> OutChains;
880 // Keep track of the last register used for arguments
881 unsigned ArgRegEnd = 0;
883 // Assign locations to all of the incoming arguments.
884 SmallVector<CCValAssign, 16> ArgLocs;
885 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
886 getTargetMachine(), ArgLocs, *DAG.getContext());
888 CCInfo.AnalyzeFormalArguments(Ins, CC_MBlaze);
891 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
892 CCValAssign &VA = ArgLocs[i];
894 // Arguments stored on registers
896 MVT RegVT = VA.getLocVT();
897 ArgRegEnd = VA.getLocReg();
898 TargetRegisterClass *RC = 0;
900 if (RegVT == MVT::i32)
901 RC = MBlaze::GPRRegisterClass;
902 else if (RegVT == MVT::f32)
903 RC = MBlaze::GPRRegisterClass;
905 llvm_unreachable("RegVT not supported by LowerFormalArguments");
907 // Transform the arguments stored on
908 // physical registers into virtual ones
909 unsigned Reg = MF.addLiveIn(ArgRegEnd, RC);
910 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
912 // If this is an 8 or 16-bit value, it has been passed promoted
913 // to 32 bits. Insert an assert[sz]ext to capture this, then
914 // truncate to the right size. If if is a floating point value
915 // then convert to the correct type.
916 if (VA.getLocInfo() != CCValAssign::Full) {
918 if (VA.getLocInfo() == CCValAssign::SExt)
919 Opcode = ISD::AssertSext;
920 else if (VA.getLocInfo() == CCValAssign::ZExt)
921 Opcode = ISD::AssertZext;
923 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
924 DAG.getValueType(VA.getValVT()));
925 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
928 InVals.push_back(ArgValue);
929 } else { // VA.isRegLoc()
931 assert(VA.isMemLoc());
933 // The last argument is not a register
936 // The stack pointer offset is relative to the caller stack frame.
937 // Since the real stack size is unknown here, a negative SPOffset
938 // is used so there's a way to adjust these offsets when the stack
939 // size get known (on EliminateFrameIndex). A dummy SPOffset is
940 // used instead of a direct negative address (which is recorded to
941 // be used on emitPrologue) to avoid mis-calc of the first stack
942 // offset on PEI::calculateFrameObjectOffsets.
943 // Arguments are always 32-bit.
944 unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
945 unsigned StackLoc = VA.getLocMemOffset() + 4;
946 int FI = MFI->CreateFixedObject(ArgSize, 0, true);
947 MBlazeFI->recordLoadArgsFI(FI, -StackLoc);
948 MBlazeFI->recordLiveIn(FI);
950 // Create load nodes to retrieve arguments from the stack
951 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
952 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
953 MachinePointerInfo::getFixedStack(FI),
958 // To meet ABI, when VARARGS are passed on registers, the registers
959 // must have their values written to the caller stack frame. If the last
960 // argument was placed in the stack, there's no need to save any register.
961 if ((isVarArg) && ArgRegEnd) {
962 if (StackPtr.getNode() == 0)
963 StackPtr = DAG.getRegister(StackReg, getPointerTy());
965 // The last register argument that must be saved is MBlaze::R10
966 TargetRegisterClass *RC = MBlaze::GPRRegisterClass;
968 unsigned Begin = getMBlazeRegisterNumbering(MBlaze::R5);
969 unsigned Start = getMBlazeRegisterNumbering(ArgRegEnd+1);
970 unsigned End = getMBlazeRegisterNumbering(MBlaze::R10);
971 unsigned StackLoc = Start - Begin + 1;
973 for (; Start <= End; ++Start, ++StackLoc) {
974 unsigned Reg = getMBlazeRegisterFromNumbering(Start);
975 unsigned LiveReg = MF.addLiveIn(Reg, RC);
976 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, LiveReg, MVT::i32);
978 int FI = MFI->CreateFixedObject(4, 0, true);
979 MBlazeFI->recordStoreVarArgsFI(FI, -(StackLoc*4));
980 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
981 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
982 MachinePointerInfo(),
985 // Record the frame index of the first variable argument
986 // which is a value necessary to VASTART.
987 if (!MBlazeFI->getVarArgsFrameIndex())
988 MBlazeFI->setVarArgsFrameIndex(FI);
992 // All stores are grouped in one node to allow the matching between
993 // the size of Ins and InVals. This only happens when on varg functions
994 if (!OutChains.empty()) {
995 OutChains.push_back(Chain);
996 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
997 &OutChains[0], OutChains.size());
1003 //===----------------------------------------------------------------------===//
1004 // Return Value Calling Convention Implementation
1005 //===----------------------------------------------------------------------===//
1007 SDValue MBlazeTargetLowering::
1008 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1009 const SmallVectorImpl<ISD::OutputArg> &Outs,
1010 const SmallVectorImpl<SDValue> &OutVals,
1011 DebugLoc dl, SelectionDAG &DAG) const {
1012 // CCValAssign - represent the assignment of
1013 // the return value to a location
1014 SmallVector<CCValAssign, 16> RVLocs;
1016 // CCState - Info about the registers and stack slot.
1017 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1018 getTargetMachine(), RVLocs, *DAG.getContext());
1020 // Analize return values.
1021 CCInfo.AnalyzeReturn(Outs, RetCC_MBlaze);
1023 // If this is the first return lowered for this function, add
1024 // the regs to the liveout set for the function.
1025 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1026 for (unsigned i = 0; i != RVLocs.size(); ++i)
1027 if (RVLocs[i].isRegLoc())
1028 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1033 // Copy the result values into the output registers.
1034 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1035 CCValAssign &VA = RVLocs[i];
1036 assert(VA.isRegLoc() && "Can only return in registers!");
1038 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1041 // guarantee that all emitted copies are
1042 // stuck together, avoiding something bad
1043 Flag = Chain.getValue(1);
1046 // If this function is using the interrupt_handler calling convention
1047 // then use "rtid r14, 0" otherwise use "rtsd r15, 8"
1048 unsigned Ret = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlazeISD::IRet
1050 unsigned Reg = (CallConv == llvm::CallingConv::MBLAZE_INTR) ? MBlaze::R14
1052 SDValue DReg = DAG.getRegister(Reg, MVT::i32);
1055 return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg, Flag);
1057 return DAG.getNode(Ret, dl, MVT::Other, Chain, DReg);
1060 //===----------------------------------------------------------------------===//
1061 // MBlaze Inline Assembly Support
1062 //===----------------------------------------------------------------------===//
1064 /// getConstraintType - Given a constraint letter, return the type of
1065 /// constraint it is for this target.
1066 MBlazeTargetLowering::ConstraintType MBlazeTargetLowering::
1067 getConstraintType(const std::string &Constraint) const
1069 // MBlaze specific constrainy
1071 // 'd' : An address register. Equivalent to r.
1072 // 'y' : Equivalent to r; retained for
1073 // backwards compatibility.
1074 // 'f' : Floating Point registers.
1075 if (Constraint.size() == 1) {
1076 switch (Constraint[0]) {
1081 return C_RegisterClass;
1085 return TargetLowering::getConstraintType(Constraint);
1088 /// Examine constraint type and operand type and determine a weight value.
1089 /// This object must already have been set up with the operand type
1090 /// and the current alternative constraint selected.
1091 TargetLowering::ConstraintWeight
1092 MBlazeTargetLowering::getSingleConstraintMatchWeight(
1093 AsmOperandInfo &info, const char *constraint) const {
1094 ConstraintWeight weight = CW_Invalid;
1095 Value *CallOperandVal = info.CallOperandVal;
1096 // If we don't have a value, we can't do a match,
1097 // but allow it at the lowest weight.
1098 if (CallOperandVal == NULL)
1100 Type *type = CallOperandVal->getType();
1101 // Look at the constraint type.
1102 switch (*constraint) {
1104 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1108 if (type->isIntegerTy())
1109 weight = CW_Register;
1112 if (type->isFloatTy())
1113 weight = CW_Register;
1119 /// Given a register class constraint, like 'r', if this corresponds directly
1120 /// to an LLVM register class, return a register of 0 and the register class
1122 std::pair<unsigned, const TargetRegisterClass*> MBlazeTargetLowering::
1123 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const {
1124 if (Constraint.size() == 1) {
1125 switch (Constraint[0]) {
1127 return std::make_pair(0U, MBlaze::GPRRegisterClass);
1128 // TODO: These can't possibly be right, but match what was in
1129 // getRegClassForInlineAsmConstraint.
1134 return std::make_pair(0U, MBlaze::GPRRegisterClass);
1137 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1140 bool MBlazeTargetLowering::
1141 isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1142 // The MBlaze target isn't yet aware of offsets.
1146 bool MBlazeTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
1147 return VT != MVT::f32;