1 ///===-- FastISel.cpp - Implementation of the FastISel class --------------===//
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 contains the implementation of the FastISel class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Instructions.h"
15 #include "llvm/CodeGen/FastISel.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
24 unsigned FastISel::getRegForValue(Value *V) {
25 // Look up the value to see if we already have a register for it. We
26 // cache values defined by Instructions across blocks, and other values
27 // only locally. This is because Instructions already have the SSA
28 // def-dominatess-use requirement enforced.
29 if (ValueMap.count(V))
31 unsigned Reg = LocalValueMap[V];
35 MVT::SimpleValueType VT = TLI.getValueType(V->getType()).getSimpleVT();
36 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
37 if (CI->getValue().getActiveBits() > 64)
39 // Don't cache constant materializations. To do so would require
40 // tracking what uses they dominate.
41 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
42 } else if (isa<ConstantPointerNull>(V)) {
43 Reg = FastEmit_i(VT, VT, ISD::Constant, 0);
44 } else if (ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
45 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
48 const APFloat &Flt = CF->getValueAPF();
49 MVT IntVT = TLI.getPointerTy();
52 uint32_t IntBitWidth = IntVT.getSizeInBits();
53 if (Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
54 APFloat::rmTowardZero) != APFloat::opOK)
56 APInt IntVal(IntBitWidth, 2, x);
58 unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
59 ISD::Constant, IntVal.getZExtValue());
62 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg);
66 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
67 if (!SelectOperator(CE, CE->getOpcode())) return 0;
68 Reg = LocalValueMap[CE];
69 } else if (isa<UndefValue>(V)) {
70 Reg = createResultReg(TLI.getRegClassFor(VT));
71 BuildMI(MBB, TII.get(TargetInstrInfo::IMPLICIT_DEF), Reg);
76 LocalValueMap[V] = Reg;
80 /// UpdateValueMap - Update the value map to include the new mapping for this
81 /// instruction, or insert an extra copy to get the result in a previous
82 /// determined register.
83 /// NOTE: This is only necessary because we might select a block that uses
84 /// a value before we select the block that defines the value. It might be
85 /// possible to fix this by selecting blocks in reverse postorder.
86 void FastISel::UpdateValueMap(Value* I, unsigned Reg) {
87 if (!isa<Instruction>(I)) {
88 LocalValueMap[I] = Reg;
91 if (!ValueMap.count(I))
94 TII.copyRegToReg(*MBB, MBB->end(), ValueMap[I],
95 Reg, MRI.getRegClass(Reg), MRI.getRegClass(Reg));
98 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
99 /// which has an opcode which directly corresponds to the given ISD opcode.
101 bool FastISel::SelectBinaryOp(User *I, ISD::NodeType ISDOpcode) {
102 MVT VT = MVT::getMVT(I->getType(), /*HandleUnknown=*/true);
103 if (VT == MVT::Other || !VT.isSimple())
104 // Unhandled type. Halt "fast" selection and bail.
106 // We only handle legal types. For example, on x86-32 the instruction
107 // selector contains all of the 64-bit instructions from x86-64,
108 // under the assumption that i64 won't be used if the target doesn't
110 if (!TLI.isTypeLegal(VT))
113 unsigned Op0 = getRegForValue(I->getOperand(0));
115 // Unhandled operand. Halt "fast" selection and bail.
118 // Check if the second operand is a constant and handle it appropriately.
119 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
120 unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(),
121 ISDOpcode, Op0, CI->getZExtValue());
122 if (ResultReg != 0) {
123 // We successfully emitted code for the given LLVM Instruction.
124 UpdateValueMap(I, ResultReg);
129 // Check if the second operand is a constant float.
130 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
131 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
133 if (ResultReg != 0) {
134 // We successfully emitted code for the given LLVM Instruction.
135 UpdateValueMap(I, ResultReg);
140 unsigned Op1 = getRegForValue(I->getOperand(1));
142 // Unhandled operand. Halt "fast" selection and bail.
145 // Now we have both operands in registers. Emit the instruction.
146 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
147 ISDOpcode, Op0, Op1);
149 // Target-specific code wasn't able to find a machine opcode for
150 // the given ISD opcode and type. Halt "fast" selection and bail.
153 // We successfully emitted code for the given LLVM Instruction.
154 UpdateValueMap(I, ResultReg);
158 bool FastISel::SelectGetElementPtr(User *I) {
159 unsigned N = getRegForValue(I->getOperand(0));
161 // Unhandled operand. Halt "fast" selection and bail.
164 const Type *Ty = I->getOperand(0)->getType();
165 MVT::SimpleValueType VT = TLI.getPointerTy().getSimpleVT();
166 for (GetElementPtrInst::op_iterator OI = I->op_begin()+1, E = I->op_end();
169 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
170 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
173 uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field);
174 // FIXME: This can be optimized by combining the add with a
176 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
178 // Unhandled operand. Halt "fast" selection and bail.
181 Ty = StTy->getElementType(Field);
183 Ty = cast<SequentialType>(Ty)->getElementType();
185 // If this is a constant subscript, handle it quickly.
186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
187 if (CI->getZExtValue() == 0) continue;
189 TD.getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
190 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT);
192 // Unhandled operand. Halt "fast" selection and bail.
197 // N = N + Idx * ElementSize;
198 uint64_t ElementSize = TD.getABITypeSize(Ty);
199 unsigned IdxN = getRegForValue(Idx);
201 // Unhandled operand. Halt "fast" selection and bail.
204 // If the index is smaller or larger than intptr_t, truncate or extend
206 MVT IdxVT = MVT::getMVT(Idx->getType(), /*HandleUnknown=*/false);
207 if (IdxVT.bitsLT(VT))
208 IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::SIGN_EXTEND, IdxN);
209 else if (IdxVT.bitsGT(VT))
210 IdxN = FastEmit_r(IdxVT.getSimpleVT(), VT, ISD::TRUNCATE, IdxN);
212 // Unhandled operand. Halt "fast" selection and bail.
215 if (ElementSize != 1) {
216 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
218 // Unhandled operand. Halt "fast" selection and bail.
221 N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
223 // Unhandled operand. Halt "fast" selection and bail.
228 // We successfully emitted code for the given LLVM Instruction.
229 UpdateValueMap(I, N);
233 bool FastISel::SelectCast(User *I, ISD::NodeType Opcode) {
234 MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
235 MVT DstVT = TLI.getValueType(I->getType());
237 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
238 DstVT == MVT::Other || !DstVT.isSimple() ||
239 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
240 // Unhandled type. Halt "fast" selection and bail.
243 unsigned InputReg = getRegForValue(I->getOperand(0));
245 // Unhandled operand. Halt "fast" selection and bail.
248 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
255 UpdateValueMap(I, ResultReg);
259 bool FastISel::SelectBitCast(User *I) {
260 // If the bitcast doesn't change the type, just use the operand value.
261 if (I->getType() == I->getOperand(0)->getType()) {
262 unsigned Reg = getRegForValue(I->getOperand(0));
265 UpdateValueMap(I, Reg);
269 // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators.
270 MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
271 MVT DstVT = TLI.getValueType(I->getType());
273 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
274 DstVT == MVT::Other || !DstVT.isSimple() ||
275 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
276 // Unhandled type. Halt "fast" selection and bail.
279 unsigned Op0 = getRegForValue(I->getOperand(0));
281 // Unhandled operand. Halt "fast" selection and bail.
284 // First, try to perform the bitcast by inserting a reg-reg copy.
285 unsigned ResultReg = 0;
286 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
287 TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
288 TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
289 ResultReg = createResultReg(DstClass);
291 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg,
292 Op0, DstClass, SrcClass);
297 // If the reg-reg copy failed, select a BIT_CONVERT opcode.
299 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
300 ISD::BIT_CONVERT, Op0);
305 UpdateValueMap(I, ResultReg);
310 FastISel::SelectInstruction(Instruction *I) {
311 return SelectOperator(I, I->getOpcode());
315 FastISel::SelectOperator(User *I, unsigned Opcode) {
317 case Instruction::Add: {
318 ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FADD : ISD::ADD;
319 return SelectBinaryOp(I, Opc);
321 case Instruction::Sub: {
322 ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FSUB : ISD::SUB;
323 return SelectBinaryOp(I, Opc);
325 case Instruction::Mul: {
326 ISD::NodeType Opc = I->getType()->isFPOrFPVector() ? ISD::FMUL : ISD::MUL;
327 return SelectBinaryOp(I, Opc);
329 case Instruction::SDiv:
330 return SelectBinaryOp(I, ISD::SDIV);
331 case Instruction::UDiv:
332 return SelectBinaryOp(I, ISD::UDIV);
333 case Instruction::FDiv:
334 return SelectBinaryOp(I, ISD::FDIV);
335 case Instruction::SRem:
336 return SelectBinaryOp(I, ISD::SREM);
337 case Instruction::URem:
338 return SelectBinaryOp(I, ISD::UREM);
339 case Instruction::FRem:
340 return SelectBinaryOp(I, ISD::FREM);
341 case Instruction::Shl:
342 return SelectBinaryOp(I, ISD::SHL);
343 case Instruction::LShr:
344 return SelectBinaryOp(I, ISD::SRL);
345 case Instruction::AShr:
346 return SelectBinaryOp(I, ISD::SRA);
347 case Instruction::And:
348 return SelectBinaryOp(I, ISD::AND);
349 case Instruction::Or:
350 return SelectBinaryOp(I, ISD::OR);
351 case Instruction::Xor:
352 return SelectBinaryOp(I, ISD::XOR);
354 case Instruction::GetElementPtr:
355 return SelectGetElementPtr(I);
357 case Instruction::Br: {
358 BranchInst *BI = cast<BranchInst>(I);
360 if (BI->isUnconditional()) {
361 MachineFunction::iterator NextMBB =
362 next(MachineFunction::iterator(MBB));
363 BasicBlock *LLVMSucc = BI->getSuccessor(0);
364 MachineBasicBlock *MSucc = MBBMap[LLVMSucc];
366 if (NextMBB != MF.end() && MSucc == NextMBB) {
367 // The unconditional fall-through case, which needs no instructions.
369 // The unconditional branch case.
370 TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>());
372 MBB->addSuccessor(MSucc);
376 // Conditional branches are not handed yet.
377 // Halt "fast" selection and bail.
381 case Instruction::Unreachable:
385 case Instruction::PHI:
386 // PHI nodes are already emitted.
389 case Instruction::BitCast:
390 return SelectBitCast(I);
392 case Instruction::FPToSI:
393 return SelectCast(I, ISD::FP_TO_SINT);
394 case Instruction::ZExt:
395 return SelectCast(I, ISD::ZERO_EXTEND);
396 case Instruction::SExt:
397 return SelectCast(I, ISD::SIGN_EXTEND);
398 case Instruction::Trunc:
399 return SelectCast(I, ISD::TRUNCATE);
400 case Instruction::SIToFP:
401 return SelectCast(I, ISD::SINT_TO_FP);
403 case Instruction::IntToPtr: // Deliberate fall-through.
404 case Instruction::PtrToInt: {
405 MVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
406 MVT DstVT = TLI.getValueType(I->getType());
407 if (DstVT.bitsGT(SrcVT))
408 return SelectCast(I, ISD::ZERO_EXTEND);
409 if (DstVT.bitsLT(SrcVT))
410 return SelectCast(I, ISD::TRUNCATE);
411 unsigned Reg = getRegForValue(I->getOperand(0));
412 if (Reg == 0) return false;
413 UpdateValueMap(I, Reg);
418 // Unhandled instruction. Halt "fast" selection and bail.
423 FastISel::FastISel(MachineFunction &mf,
424 DenseMap<const Value *, unsigned> &vm,
425 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm)
430 MRI(MF.getRegInfo()),
432 TD(*TM.getTargetData()),
433 TII(*TM.getInstrInfo()),
434 TLI(*TM.getTargetLowering()) {
437 FastISel::~FastISel() {}
439 unsigned FastISel::FastEmit_(MVT::SimpleValueType, MVT::SimpleValueType,
444 unsigned FastISel::FastEmit_r(MVT::SimpleValueType, MVT::SimpleValueType,
445 ISD::NodeType, unsigned /*Op0*/) {
449 unsigned FastISel::FastEmit_rr(MVT::SimpleValueType, MVT::SimpleValueType,
450 ISD::NodeType, unsigned /*Op0*/,
455 unsigned FastISel::FastEmit_i(MVT::SimpleValueType, MVT::SimpleValueType,
456 ISD::NodeType, uint64_t /*Imm*/) {
460 unsigned FastISel::FastEmit_f(MVT::SimpleValueType, MVT::SimpleValueType,
461 ISD::NodeType, ConstantFP * /*FPImm*/) {
465 unsigned FastISel::FastEmit_ri(MVT::SimpleValueType, MVT::SimpleValueType,
466 ISD::NodeType, unsigned /*Op0*/,
471 unsigned FastISel::FastEmit_rf(MVT::SimpleValueType, MVT::SimpleValueType,
472 ISD::NodeType, unsigned /*Op0*/,
473 ConstantFP * /*FPImm*/) {
477 unsigned FastISel::FastEmit_rri(MVT::SimpleValueType, MVT::SimpleValueType,
479 unsigned /*Op0*/, unsigned /*Op1*/,
484 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
485 /// to emit an instruction with an immediate operand using FastEmit_ri.
486 /// If that fails, it materializes the immediate into a register and try
487 /// FastEmit_rr instead.
488 unsigned FastISel::FastEmit_ri_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
489 unsigned Op0, uint64_t Imm,
490 MVT::SimpleValueType ImmType) {
491 // First check if immediate type is legal. If not, we can't use the ri form.
492 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm);
495 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
496 if (MaterialReg == 0)
498 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
501 /// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries
502 /// to emit an instruction with a floating-point immediate operand using
503 /// FastEmit_rf. If that fails, it materializes the immediate into a register
504 /// and try FastEmit_rr instead.
505 unsigned FastISel::FastEmit_rf_(MVT::SimpleValueType VT, ISD::NodeType Opcode,
506 unsigned Op0, ConstantFP *FPImm,
507 MVT::SimpleValueType ImmType) {
508 // First check if immediate type is legal. If not, we can't use the rf form.
509 unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm);
513 // Materialize the constant in a register.
514 unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm);
515 if (MaterialReg == 0) {
516 // If the target doesn't have a way to directly enter a floating-point
517 // value into a register, use an alternate approach.
518 // TODO: The current approach only supports floating-point constants
519 // that can be constructed by conversion from integer values. This should
520 // be replaced by code that creates a load from a constant-pool entry,
521 // which will require some target-specific work.
522 const APFloat &Flt = FPImm->getValueAPF();
523 MVT IntVT = TLI.getPointerTy();
526 uint32_t IntBitWidth = IntVT.getSizeInBits();
527 if (Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
528 APFloat::rmTowardZero) != APFloat::opOK)
530 APInt IntVal(IntBitWidth, 2, x);
532 unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(),
533 ISD::Constant, IntVal.getZExtValue());
536 MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT,
537 ISD::SINT_TO_FP, IntegerReg);
538 if (MaterialReg == 0)
541 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
544 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
545 return MRI.createVirtualRegister(RC);
548 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
549 const TargetRegisterClass* RC) {
550 unsigned ResultReg = createResultReg(RC);
551 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
553 BuildMI(MBB, II, ResultReg);
557 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
558 const TargetRegisterClass *RC,
560 unsigned ResultReg = createResultReg(RC);
561 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
563 BuildMI(MBB, II, ResultReg).addReg(Op0);
567 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
568 const TargetRegisterClass *RC,
569 unsigned Op0, unsigned Op1) {
570 unsigned ResultReg = createResultReg(RC);
571 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
573 BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1);
577 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
578 const TargetRegisterClass *RC,
579 unsigned Op0, uint64_t Imm) {
580 unsigned ResultReg = createResultReg(RC);
581 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
583 BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Imm);
587 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
588 const TargetRegisterClass *RC,
589 unsigned Op0, ConstantFP *FPImm) {
590 unsigned ResultReg = createResultReg(RC);
591 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
593 BuildMI(MBB, II, ResultReg).addReg(Op0).addFPImm(FPImm);
597 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
598 const TargetRegisterClass *RC,
599 unsigned Op0, unsigned Op1, uint64_t Imm) {
600 unsigned ResultReg = createResultReg(RC);
601 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
603 BuildMI(MBB, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm);
607 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
608 const TargetRegisterClass *RC,
610 unsigned ResultReg = createResultReg(RC);
611 const TargetInstrDesc &II = TII.get(MachineInstOpcode);
613 BuildMI(MBB, II, ResultReg).addImm(Imm);
617 unsigned FastISel::FastEmitInst_extractsubreg(unsigned Op0, uint32_t Idx) {
618 const TargetRegisterClass* RC = MRI.getRegClass(Op0);
619 const TargetRegisterClass* SRC = *(RC->subregclasses_begin()+Idx-1);
621 unsigned ResultReg = createResultReg(SRC);
622 const TargetInstrDesc &II = TII.get(TargetInstrInfo::EXTRACT_SUBREG);
624 BuildMI(MBB, II, ResultReg).addReg(Op0).addImm(Idx);