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 // "Fast" instruction selection is designed to emit very poor code quickly.
13 // Also, it is not designed to be able to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is
15 // also not intended to be able to do much optimization, except in a few cases
16 // where doing optimizations reduces overall compile time. For example, folding
17 // constants into immediate fields is often done, because it's cheap and it
18 // reduces the number of instructions later phases have to examine.
20 // "Fast" instruction selection is able to fail gracefully and transfer
21 // control to the SelectionDAG selector for operations that it doesn't
22 // support. In many cases, this allows us to avoid duplicating a lot of
23 // the complicated lowering logic that SelectionDAG currently has.
25 // The intended use for "fast" instruction selection is "-O0" mode
26 // compilation, where the quality of the generated code is irrelevant when
27 // weighed against the speed at which the code can be generated. Also,
28 // at -O0, the LLVM optimizers are not running, and this makes the
29 // compile time of codegen a much higher portion of the overall compile
30 // time. Despite its limitations, "fast" instruction selection is able to
31 // handle enough code on its own to provide noticeable overall speedups
34 // Basic operations are supported in a target-independent way, by reading
35 // the same instruction descriptions that the SelectionDAG selector reads,
36 // and identifying simple arithmetic operations that can be directly selected
37 // from simple operators. More complicated operations currently require
38 // target-specific code.
40 //===----------------------------------------------------------------------===//
42 #define DEBUG_TYPE "isel"
43 #include "llvm/CodeGen/FastISel.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/CodeGen/Analysis.h"
47 #include "llvm/CodeGen/FunctionLoweringInfo.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/DebugInfo.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetLibraryInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
66 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
67 "target-independent selector");
68 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
69 "target-specific selector");
70 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
72 /// startNewBlock - Set the current block to which generated machine
73 /// instructions will be appended, and clear the local CSE map.
75 void FastISel::startNewBlock() {
76 LocalValueMap.clear();
80 // Advance the emit start point past any EH_LABEL instructions.
81 MachineBasicBlock::iterator
82 I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
83 while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
87 LastLocalValue = EmitStartPt;
90 bool FastISel::LowerArguments() {
91 if (!FuncInfo.CanLowerReturn)
92 // Fallback to SDISel argument lowering code to deal with sret pointer
96 if (!FastLowerArguments())
99 // Enter non-dead arguments into ValueMap for uses in non-entry BBs.
100 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
101 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
102 if (!I->use_empty()) {
103 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
104 assert(VI != LocalValueMap.end() && "Missed an argument?");
105 FuncInfo.ValueMap[I] = VI->second;
111 void FastISel::flushLocalValueMap() {
112 LocalValueMap.clear();
113 LastLocalValue = EmitStartPt;
117 bool FastISel::hasTrivialKill(const Value *V) const {
118 // Don't consider constants or arguments to have trivial kills.
119 const Instruction *I = dyn_cast<Instruction>(V);
123 // No-op casts are trivially coalesced by fast-isel.
124 if (const CastInst *Cast = dyn_cast<CastInst>(I))
125 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
126 !hasTrivialKill(Cast->getOperand(0)))
129 // GEPs with all zero indices are trivially coalesced by fast-isel.
130 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
131 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
134 // Only instructions with a single use in the same basic block are considered
135 // to have trivial kills.
136 return I->hasOneUse() &&
137 !(I->getOpcode() == Instruction::BitCast ||
138 I->getOpcode() == Instruction::PtrToInt ||
139 I->getOpcode() == Instruction::IntToPtr) &&
140 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
143 unsigned FastISel::getRegForValue(const Value *V) {
144 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
145 // Don't handle non-simple values in FastISel.
146 if (!RealVT.isSimple())
149 // Ignore illegal types. We must do this before looking up the value
150 // in ValueMap because Arguments are given virtual registers regardless
151 // of whether FastISel can handle them.
152 MVT VT = RealVT.getSimpleVT();
153 if (!TLI.isTypeLegal(VT)) {
154 // Handle integer promotions, though, because they're common and easy.
155 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
156 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
161 // Look up the value to see if we already have a register for it.
162 unsigned Reg = lookUpRegForValue(V);
166 // In bottom-up mode, just create the virtual register which will be used
167 // to hold the value. It will be materialized later.
168 if (isa<Instruction>(V) &&
169 (!isa<AllocaInst>(V) ||
170 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
171 return FuncInfo.InitializeRegForValue(V);
173 SavePoint SaveInsertPt = enterLocalValueArea();
175 // Materialize the value in a register. Emit any instructions in the
177 Reg = materializeRegForValue(V, VT);
179 leaveLocalValueArea(SaveInsertPt);
184 /// materializeRegForValue - Helper for getRegForValue. This function is
185 /// called when the value isn't already available in a register and must
186 /// be materialized with new instructions.
187 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
190 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
191 if (CI->getValue().getActiveBits() <= 64)
192 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
193 } else if (isa<AllocaInst>(V)) {
194 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
195 } else if (isa<ConstantPointerNull>(V)) {
196 // Translate this as an integer zero so that it can be
197 // local-CSE'd with actual integer zeros.
199 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
200 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
201 if (CF->isNullValue()) {
202 Reg = TargetMaterializeFloatZero(CF);
204 // Try to emit the constant directly.
205 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
209 // Try to emit the constant by using an integer constant with a cast.
210 const APFloat &Flt = CF->getValueAPF();
211 EVT IntVT = TLI.getPointerTy();
214 uint32_t IntBitWidth = IntVT.getSizeInBits();
216 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
217 APFloat::rmTowardZero, &isExact);
219 APInt IntVal(IntBitWidth, x);
221 unsigned IntegerReg =
222 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
224 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
225 IntegerReg, /*Kill=*/false);
228 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
229 if (!SelectOperator(Op, Op->getOpcode()))
230 if (!isa<Instruction>(Op) ||
231 !TargetSelectInstruction(cast<Instruction>(Op)))
233 Reg = lookUpRegForValue(Op);
234 } else if (isa<UndefValue>(V)) {
235 Reg = createResultReg(TLI.getRegClassFor(VT));
236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
237 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
240 // If target-independent code couldn't handle the value, give target-specific
242 if (!Reg && isa<Constant>(V))
243 Reg = TargetMaterializeConstant(cast<Constant>(V));
245 // Don't cache constant materializations in the general ValueMap.
246 // To do so would require tracking what uses they dominate.
248 LocalValueMap[V] = Reg;
249 LastLocalValue = MRI.getVRegDef(Reg);
254 unsigned FastISel::lookUpRegForValue(const Value *V) {
255 // Look up the value to see if we already have a register for it. We
256 // cache values defined by Instructions across blocks, and other values
257 // only locally. This is because Instructions already have the SSA
258 // def-dominates-use requirement enforced.
259 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
260 if (I != FuncInfo.ValueMap.end())
262 return LocalValueMap[V];
265 /// UpdateValueMap - Update the value map to include the new mapping for this
266 /// instruction, or insert an extra copy to get the result in a previous
267 /// determined register.
268 /// NOTE: This is only necessary because we might select a block that uses
269 /// a value before we select the block that defines the value. It might be
270 /// possible to fix this by selecting blocks in reverse postorder.
271 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
272 if (!isa<Instruction>(I)) {
273 LocalValueMap[I] = Reg;
277 unsigned &AssignedReg = FuncInfo.ValueMap[I];
278 if (AssignedReg == 0)
279 // Use the new register.
281 else if (Reg != AssignedReg) {
282 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
283 for (unsigned i = 0; i < NumRegs; i++)
284 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
290 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
291 unsigned IdxN = getRegForValue(Idx);
293 // Unhandled operand. Halt "fast" selection and bail.
294 return std::pair<unsigned, bool>(0, false);
296 bool IdxNIsKill = hasTrivialKill(Idx);
298 // If the index is smaller or larger than intptr_t, truncate or extend it.
299 MVT PtrVT = TLI.getPointerTy();
300 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
301 if (IdxVT.bitsLT(PtrVT)) {
302 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
306 else if (IdxVT.bitsGT(PtrVT)) {
307 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
311 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
314 void FastISel::recomputeInsertPt() {
315 if (getLastLocalValue()) {
316 FuncInfo.InsertPt = getLastLocalValue();
317 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
320 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
322 // Now skip past any EH_LABELs, which must remain at the beginning.
323 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
324 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
328 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
329 MachineBasicBlock::iterator E) {
330 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
332 MachineInstr *Dead = &*I;
334 Dead->eraseFromParent();
340 FastISel::SavePoint FastISel::enterLocalValueArea() {
341 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
345 SavePoint SP = { OldInsertPt, OldDL };
349 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
350 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
351 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
353 // Restore the previous insert position.
354 FuncInfo.InsertPt = OldInsertPt.InsertPt;
358 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
359 /// which has an opcode which directly corresponds to the given ISD opcode.
361 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
362 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
363 if (VT == MVT::Other || !VT.isSimple())
364 // Unhandled type. Halt "fast" selection and bail.
367 // We only handle legal types. For example, on x86-32 the instruction
368 // selector contains all of the 64-bit instructions from x86-64,
369 // under the assumption that i64 won't be used if the target doesn't
371 if (!TLI.isTypeLegal(VT)) {
372 // MVT::i1 is special. Allow AND, OR, or XOR because they
373 // don't require additional zeroing, which makes them easy.
375 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
376 ISDOpcode == ISD::XOR))
377 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
382 // Check if the first operand is a constant, and handle it as "ri". At -O0,
383 // we don't have anything that canonicalizes operand order.
384 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
385 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
386 unsigned Op1 = getRegForValue(I->getOperand(1));
387 if (Op1 == 0) return false;
389 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
391 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
392 Op1IsKill, CI->getZExtValue(),
394 if (ResultReg == 0) return false;
396 // We successfully emitted code for the given LLVM Instruction.
397 UpdateValueMap(I, ResultReg);
402 unsigned Op0 = getRegForValue(I->getOperand(0));
403 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
406 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
408 // Check if the second operand is a constant and handle it appropriately.
409 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
410 uint64_t Imm = CI->getZExtValue();
412 // Transform "sdiv exact X, 8" -> "sra X, 3".
413 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
414 cast<BinaryOperator>(I)->isExact() &&
415 isPowerOf2_64(Imm)) {
417 ISDOpcode = ISD::SRA;
420 // Transform "urem x, pow2" -> "and x, pow2-1".
421 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
422 isPowerOf2_64(Imm)) {
424 ISDOpcode = ISD::AND;
427 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
428 Op0IsKill, Imm, VT.getSimpleVT());
429 if (ResultReg == 0) return false;
431 // We successfully emitted code for the given LLVM Instruction.
432 UpdateValueMap(I, ResultReg);
436 // Check if the second operand is a constant float.
437 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
438 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
439 ISDOpcode, Op0, Op0IsKill, CF);
440 if (ResultReg != 0) {
441 // We successfully emitted code for the given LLVM Instruction.
442 UpdateValueMap(I, ResultReg);
447 unsigned Op1 = getRegForValue(I->getOperand(1));
449 // Unhandled operand. Halt "fast" selection and bail.
452 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
454 // Now we have both operands in registers. Emit the instruction.
455 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
460 // Target-specific code wasn't able to find a machine opcode for
461 // the given ISD opcode and type. Halt "fast" selection and bail.
464 // We successfully emitted code for the given LLVM Instruction.
465 UpdateValueMap(I, ResultReg);
469 bool FastISel::SelectGetElementPtr(const User *I) {
470 unsigned N = getRegForValue(I->getOperand(0));
472 // Unhandled operand. Halt "fast" selection and bail.
475 bool NIsKill = hasTrivialKill(I->getOperand(0));
477 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
478 // into a single N = N + TotalOffset.
479 uint64_t TotalOffs = 0;
480 // FIXME: What's a good SWAG number for MaxOffs?
481 uint64_t MaxOffs = 2048;
482 Type *Ty = I->getOperand(0)->getType();
483 MVT VT = TLI.getPointerTy();
484 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
485 E = I->op_end(); OI != E; ++OI) {
486 const Value *Idx = *OI;
487 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
488 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
491 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
492 if (TotalOffs >= MaxOffs) {
493 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
495 // Unhandled operand. Halt "fast" selection and bail.
501 Ty = StTy->getElementType(Field);
503 Ty = cast<SequentialType>(Ty)->getElementType();
505 // If this is a constant subscript, handle it quickly.
506 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
507 if (CI->isZero()) continue;
510 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
511 if (TotalOffs >= MaxOffs) {
512 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
514 // Unhandled operand. Halt "fast" selection and bail.
522 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
524 // Unhandled operand. Halt "fast" selection and bail.
530 // N = N + Idx * ElementSize;
531 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
532 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
533 unsigned IdxN = Pair.first;
534 bool IdxNIsKill = Pair.second;
536 // Unhandled operand. Halt "fast" selection and bail.
539 if (ElementSize != 1) {
540 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
542 // Unhandled operand. Halt "fast" selection and bail.
546 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
548 // Unhandled operand. Halt "fast" selection and bail.
553 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
555 // Unhandled operand. Halt "fast" selection and bail.
559 // We successfully emitted code for the given LLVM Instruction.
560 UpdateValueMap(I, N);
564 bool FastISel::SelectCall(const User *I) {
565 const CallInst *Call = cast<CallInst>(I);
567 // Handle simple inline asms.
568 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
569 // Don't attempt to handle constraints.
570 if (!IA->getConstraintString().empty())
573 unsigned ExtraInfo = 0;
574 if (IA->hasSideEffects())
575 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
576 if (IA->isAlignStack())
577 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
579 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
580 TII.get(TargetOpcode::INLINEASM))
581 .addExternalSymbol(IA->getAsmString().c_str())
586 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
587 ComputeUsesVAFloatArgument(*Call, &MMI);
589 const Function *F = Call->getCalledFunction();
590 if (!F) return false;
592 // Handle selected intrinsic function calls.
593 switch (F->getIntrinsicID()) {
595 // At -O0 we don't care about the lifetime intrinsics.
596 case Intrinsic::lifetime_start:
597 case Intrinsic::lifetime_end:
598 // The donothing intrinsic does, well, nothing.
599 case Intrinsic::donothing:
602 case Intrinsic::dbg_declare: {
603 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
604 if (!DIVariable(DI->getVariable()).Verify() ||
605 !FuncInfo.MF->getMMI().hasDebugInfo()) {
606 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
610 const Value *Address = DI->getAddress();
611 if (!Address || isa<UndefValue>(Address)) {
612 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
618 if (const Argument *Arg = dyn_cast<Argument>(Address)) {
619 // Some arguments' frame index is recorded during argument lowering.
620 Offset = FuncInfo.getArgumentFrameIndex(Arg);
622 Reg = TRI.getFrameRegister(*FuncInfo.MF);
625 Reg = lookUpRegForValue(Address);
627 // If we have a VLA that has a "use" in a metadata node that's then used
628 // here but it has no other uses, then we have a problem. E.g.,
630 // int foo (const int *x) {
635 // If we assign 'a' a vreg and fast isel later on has to use the selection
636 // DAG isel, it will want to copy the value to the vreg. However, there are
637 // no uses, which goes counter to what selection DAG isel expects.
638 if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
639 (!isa<AllocaInst>(Address) ||
640 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
641 Reg = FuncInfo.InitializeRegForValue(Address);
644 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
645 TII.get(TargetOpcode::DBG_VALUE))
646 .addReg(Reg, RegState::Debug).addImm(Offset)
647 .addMetadata(DI->getVariable());
649 // We can't yet handle anything else here because it would require
650 // generating code, thus altering codegen because of debug info.
651 DEBUG(dbgs() << "Dropping debug info for " << DI);
654 case Intrinsic::dbg_value: {
655 // This form of DBG_VALUE is target-independent.
656 const DbgValueInst *DI = cast<DbgValueInst>(Call);
657 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
658 const Value *V = DI->getValue();
660 // Currently the optimizer can produce this; insert an undef to
661 // help debugging. Probably the optimizer should not do this.
662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
663 .addReg(0U).addImm(DI->getOffset())
664 .addMetadata(DI->getVariable());
665 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
666 if (CI->getBitWidth() > 64)
667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
668 .addCImm(CI).addImm(DI->getOffset())
669 .addMetadata(DI->getVariable());
671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
672 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
673 .addMetadata(DI->getVariable());
674 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
676 .addFPImm(CF).addImm(DI->getOffset())
677 .addMetadata(DI->getVariable());
678 } else if (unsigned Reg = lookUpRegForValue(V)) {
679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
680 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
681 .addMetadata(DI->getVariable());
683 // We can't yet handle anything else here because it would require
684 // generating code, thus altering codegen because of debug info.
685 DEBUG(dbgs() << "Dropping debug info for " << DI);
689 case Intrinsic::objectsize: {
690 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
691 unsigned long long Res = CI->isZero() ? -1ULL : 0;
692 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
693 unsigned ResultReg = getRegForValue(ResCI);
696 UpdateValueMap(Call, ResultReg);
701 // Usually, it does not make sense to initialize a value,
702 // make an unrelated function call and use the value, because
703 // it tends to be spilled on the stack. So, we move the pointer
704 // to the last local value to the beginning of the block, so that
705 // all the values which have already been materialized,
706 // appear after the call. It also makes sense to skip intrinsics
707 // since they tend to be inlined.
708 if (!isa<IntrinsicInst>(Call))
709 flushLocalValueMap();
711 // An arbitrary call. Bail.
715 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
716 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
717 EVT DstVT = TLI.getValueType(I->getType());
719 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
720 DstVT == MVT::Other || !DstVT.isSimple())
721 // Unhandled type. Halt "fast" selection and bail.
724 // Check if the destination type is legal.
725 if (!TLI.isTypeLegal(DstVT))
728 // Check if the source operand is legal.
729 if (!TLI.isTypeLegal(SrcVT))
732 unsigned InputReg = getRegForValue(I->getOperand(0));
734 // Unhandled operand. Halt "fast" selection and bail.
737 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
739 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
742 InputReg, InputRegIsKill);
746 UpdateValueMap(I, ResultReg);
750 bool FastISel::SelectBitCast(const User *I) {
751 // If the bitcast doesn't change the type, just use the operand value.
752 if (I->getType() == I->getOperand(0)->getType()) {
753 unsigned Reg = getRegForValue(I->getOperand(0));
756 UpdateValueMap(I, Reg);
760 // Bitcasts of other values become reg-reg copies or BITCAST operators.
761 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
762 EVT DstEVT = TLI.getValueType(I->getType());
763 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
764 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
765 // Unhandled type. Halt "fast" selection and bail.
768 MVT SrcVT = SrcEVT.getSimpleVT();
769 MVT DstVT = DstEVT.getSimpleVT();
770 unsigned Op0 = getRegForValue(I->getOperand(0));
772 // Unhandled operand. Halt "fast" selection and bail.
775 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
777 // First, try to perform the bitcast by inserting a reg-reg copy.
778 unsigned ResultReg = 0;
779 if (SrcVT == DstVT) {
780 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
781 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
782 // Don't attempt a cross-class copy. It will likely fail.
783 if (SrcClass == DstClass) {
784 ResultReg = createResultReg(DstClass);
785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
786 ResultReg).addReg(Op0);
790 // If the reg-reg copy failed, select a BITCAST opcode.
792 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
797 UpdateValueMap(I, ResultReg);
802 FastISel::SelectInstruction(const Instruction *I) {
803 // Just before the terminator instruction, insert instructions to
804 // feed PHI nodes in successor blocks.
805 if (isa<TerminatorInst>(I))
806 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
809 DL = I->getDebugLoc();
811 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
813 // As a special case, don't handle calls to builtin library functions that
814 // may be translated directly to target instructions.
815 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
816 const Function *F = Call->getCalledFunction();
818 if (F && !F->hasLocalLinkage() && F->hasName() &&
819 LibInfo->getLibFunc(F->getName(), Func) &&
820 LibInfo->hasOptimizedCodeGen(Func))
824 // First, try doing target-independent selection.
825 if (!SkipTargetIndependentFastISel() && SelectOperator(I, I->getOpcode())) {
826 ++NumFastIselSuccessIndependent;
830 // Remove dead code. However, ignore call instructions since we've flushed
831 // the local value map and recomputed the insert point.
832 if (!isa<CallInst>(I)) {
834 if (SavedInsertPt != FuncInfo.InsertPt)
835 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
838 // Next, try calling the target to attempt to handle the instruction.
839 SavedInsertPt = FuncInfo.InsertPt;
840 if (TargetSelectInstruction(I)) {
841 ++NumFastIselSuccessTarget;
845 // Check for dead code and remove as necessary.
847 if (SavedInsertPt != FuncInfo.InsertPt)
848 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
854 /// FastEmitBranch - Emit an unconditional branch to the given block,
855 /// unless it is the immediate (fall-through) successor, and update
858 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
860 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
861 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
862 // For more accurate line information if this is the only instruction
863 // in the block then emit it, otherwise we have the unconditional
864 // fall-through case, which needs no instructions.
866 // The unconditional branch case.
867 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
868 SmallVector<MachineOperand, 0>(), DL);
870 FuncInfo.MBB->addSuccessor(MSucc);
873 /// SelectFNeg - Emit an FNeg operation.
876 FastISel::SelectFNeg(const User *I) {
877 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
878 if (OpReg == 0) return false;
880 bool OpRegIsKill = hasTrivialKill(I);
882 // If the target has ISD::FNEG, use it.
883 EVT VT = TLI.getValueType(I->getType());
884 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
885 ISD::FNEG, OpReg, OpRegIsKill);
886 if (ResultReg != 0) {
887 UpdateValueMap(I, ResultReg);
891 // Bitcast the value to integer, twiddle the sign bit with xor,
892 // and then bitcast it back to floating-point.
893 if (VT.getSizeInBits() > 64) return false;
894 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
895 if (!TLI.isTypeLegal(IntVT))
898 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
899 ISD::BITCAST, OpReg, OpRegIsKill);
903 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
904 IntReg, /*Kill=*/true,
905 UINT64_C(1) << (VT.getSizeInBits()-1),
906 IntVT.getSimpleVT());
907 if (IntResultReg == 0)
910 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
911 ISD::BITCAST, IntResultReg, /*Kill=*/true);
915 UpdateValueMap(I, ResultReg);
920 FastISel::SelectExtractValue(const User *U) {
921 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
925 // Make sure we only try to handle extracts with a legal result. But also
926 // allow i1 because it's easy.
927 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
928 if (!RealVT.isSimple())
930 MVT VT = RealVT.getSimpleVT();
931 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
934 const Value *Op0 = EVI->getOperand(0);
935 Type *AggTy = Op0->getType();
937 // Get the base result register.
939 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
940 if (I != FuncInfo.ValueMap.end())
941 ResultReg = I->second;
942 else if (isa<Instruction>(Op0))
943 ResultReg = FuncInfo.InitializeRegForValue(Op0);
945 return false; // fast-isel can't handle aggregate constants at the moment
947 // Get the actual result register, which is an offset from the base register.
948 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
950 SmallVector<EVT, 4> AggValueVTs;
951 ComputeValueVTs(TLI, AggTy, AggValueVTs);
953 for (unsigned i = 0; i < VTIndex; i++)
954 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
956 UpdateValueMap(EVI, ResultReg);
961 FastISel::SelectOperator(const User *I, unsigned Opcode) {
963 case Instruction::Add:
964 return SelectBinaryOp(I, ISD::ADD);
965 case Instruction::FAdd:
966 return SelectBinaryOp(I, ISD::FADD);
967 case Instruction::Sub:
968 return SelectBinaryOp(I, ISD::SUB);
969 case Instruction::FSub:
970 // FNeg is currently represented in LLVM IR as a special case of FSub.
971 if (BinaryOperator::isFNeg(I))
972 return SelectFNeg(I);
973 return SelectBinaryOp(I, ISD::FSUB);
974 case Instruction::Mul:
975 return SelectBinaryOp(I, ISD::MUL);
976 case Instruction::FMul:
977 return SelectBinaryOp(I, ISD::FMUL);
978 case Instruction::SDiv:
979 return SelectBinaryOp(I, ISD::SDIV);
980 case Instruction::UDiv:
981 return SelectBinaryOp(I, ISD::UDIV);
982 case Instruction::FDiv:
983 return SelectBinaryOp(I, ISD::FDIV);
984 case Instruction::SRem:
985 return SelectBinaryOp(I, ISD::SREM);
986 case Instruction::URem:
987 return SelectBinaryOp(I, ISD::UREM);
988 case Instruction::FRem:
989 return SelectBinaryOp(I, ISD::FREM);
990 case Instruction::Shl:
991 return SelectBinaryOp(I, ISD::SHL);
992 case Instruction::LShr:
993 return SelectBinaryOp(I, ISD::SRL);
994 case Instruction::AShr:
995 return SelectBinaryOp(I, ISD::SRA);
996 case Instruction::And:
997 return SelectBinaryOp(I, ISD::AND);
998 case Instruction::Or:
999 return SelectBinaryOp(I, ISD::OR);
1000 case Instruction::Xor:
1001 return SelectBinaryOp(I, ISD::XOR);
1003 case Instruction::GetElementPtr:
1004 return SelectGetElementPtr(I);
1006 case Instruction::Br: {
1007 const BranchInst *BI = cast<BranchInst>(I);
1009 if (BI->isUnconditional()) {
1010 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1011 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1012 FastEmitBranch(MSucc, BI->getDebugLoc());
1016 // Conditional branches are not handed yet.
1017 // Halt "fast" selection and bail.
1021 case Instruction::Unreachable:
1025 case Instruction::Alloca:
1026 // FunctionLowering has the static-sized case covered.
1027 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1030 // Dynamic-sized alloca is not handled yet.
1033 case Instruction::Call:
1034 return SelectCall(I);
1036 case Instruction::BitCast:
1037 return SelectBitCast(I);
1039 case Instruction::FPToSI:
1040 return SelectCast(I, ISD::FP_TO_SINT);
1041 case Instruction::ZExt:
1042 return SelectCast(I, ISD::ZERO_EXTEND);
1043 case Instruction::SExt:
1044 return SelectCast(I, ISD::SIGN_EXTEND);
1045 case Instruction::Trunc:
1046 return SelectCast(I, ISD::TRUNCATE);
1047 case Instruction::SIToFP:
1048 return SelectCast(I, ISD::SINT_TO_FP);
1050 case Instruction::IntToPtr: // Deliberate fall-through.
1051 case Instruction::PtrToInt: {
1052 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1053 EVT DstVT = TLI.getValueType(I->getType());
1054 if (DstVT.bitsGT(SrcVT))
1055 return SelectCast(I, ISD::ZERO_EXTEND);
1056 if (DstVT.bitsLT(SrcVT))
1057 return SelectCast(I, ISD::TRUNCATE);
1058 unsigned Reg = getRegForValue(I->getOperand(0));
1059 if (Reg == 0) return false;
1060 UpdateValueMap(I, Reg);
1064 case Instruction::ExtractValue:
1065 return SelectExtractValue(I);
1067 case Instruction::PHI:
1068 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1071 // Unhandled instruction. Halt "fast" selection and bail.
1076 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1077 const TargetLibraryInfo *libInfo)
1078 : FuncInfo(funcInfo),
1079 MRI(FuncInfo.MF->getRegInfo()),
1080 MFI(*FuncInfo.MF->getFrameInfo()),
1081 MCP(*FuncInfo.MF->getConstantPool()),
1082 TM(FuncInfo.MF->getTarget()),
1083 TD(*TM.getDataLayout()),
1084 TII(*TM.getInstrInfo()),
1085 TLI(*TM.getTargetLowering()),
1086 TRI(*TM.getRegisterInfo()),
1090 FastISel::~FastISel() {}
1092 bool FastISel::FastLowerArguments() {
1096 unsigned FastISel::FastEmit_(MVT, MVT,
1101 unsigned FastISel::FastEmit_r(MVT, MVT,
1103 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1107 unsigned FastISel::FastEmit_rr(MVT, MVT,
1109 unsigned /*Op0*/, bool /*Op0IsKill*/,
1110 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1114 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1118 unsigned FastISel::FastEmit_f(MVT, MVT,
1119 unsigned, const ConstantFP * /*FPImm*/) {
1123 unsigned FastISel::FastEmit_ri(MVT, MVT,
1125 unsigned /*Op0*/, bool /*Op0IsKill*/,
1130 unsigned FastISel::FastEmit_rf(MVT, MVT,
1132 unsigned /*Op0*/, bool /*Op0IsKill*/,
1133 const ConstantFP * /*FPImm*/) {
1137 unsigned FastISel::FastEmit_rri(MVT, MVT,
1139 unsigned /*Op0*/, bool /*Op0IsKill*/,
1140 unsigned /*Op1*/, bool /*Op1IsKill*/,
1145 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1146 /// to emit an instruction with an immediate operand using FastEmit_ri.
1147 /// If that fails, it materializes the immediate into a register and try
1148 /// FastEmit_rr instead.
1149 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1150 unsigned Op0, bool Op0IsKill,
1151 uint64_t Imm, MVT ImmType) {
1152 // If this is a multiply by a power of two, emit this as a shift left.
1153 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1156 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1157 // div x, 8 -> srl x, 3
1162 // Horrible hack (to be removed), check to make sure shift amounts are
1164 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1165 Imm >= VT.getSizeInBits())
1168 // First check if immediate type is legal. If not, we can't use the ri form.
1169 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1172 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1173 if (MaterialReg == 0) {
1174 // This is a bit ugly/slow, but failing here means falling out of
1175 // fast-isel, which would be very slow.
1176 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1177 VT.getSizeInBits());
1178 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1180 return FastEmit_rr(VT, VT, Opcode,
1182 MaterialReg, /*Kill=*/true);
1185 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1186 return MRI.createVirtualRegister(RC);
1189 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1190 const TargetRegisterClass* RC) {
1191 unsigned ResultReg = createResultReg(RC);
1192 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1194 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1198 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1199 const TargetRegisterClass *RC,
1200 unsigned Op0, bool Op0IsKill) {
1201 unsigned ResultReg = createResultReg(RC);
1202 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1204 if (II.getNumDefs() >= 1)
1205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1206 .addReg(Op0, Op0IsKill * RegState::Kill);
1208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1209 .addReg(Op0, Op0IsKill * RegState::Kill);
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1211 ResultReg).addReg(II.ImplicitDefs[0]);
1217 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1218 const TargetRegisterClass *RC,
1219 unsigned Op0, bool Op0IsKill,
1220 unsigned Op1, bool Op1IsKill) {
1221 unsigned ResultReg = createResultReg(RC);
1222 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1224 if (II.getNumDefs() >= 1)
1225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1226 .addReg(Op0, Op0IsKill * RegState::Kill)
1227 .addReg(Op1, Op1IsKill * RegState::Kill);
1229 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1230 .addReg(Op0, Op0IsKill * RegState::Kill)
1231 .addReg(Op1, Op1IsKill * RegState::Kill);
1232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1233 ResultReg).addReg(II.ImplicitDefs[0]);
1238 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1239 const TargetRegisterClass *RC,
1240 unsigned Op0, bool Op0IsKill,
1241 unsigned Op1, bool Op1IsKill,
1242 unsigned Op2, bool Op2IsKill) {
1243 unsigned ResultReg = createResultReg(RC);
1244 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1246 if (II.getNumDefs() >= 1)
1247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1248 .addReg(Op0, Op0IsKill * RegState::Kill)
1249 .addReg(Op1, Op1IsKill * RegState::Kill)
1250 .addReg(Op2, Op2IsKill * RegState::Kill);
1252 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1253 .addReg(Op0, Op0IsKill * RegState::Kill)
1254 .addReg(Op1, Op1IsKill * RegState::Kill)
1255 .addReg(Op2, Op2IsKill * RegState::Kill);
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1257 ResultReg).addReg(II.ImplicitDefs[0]);
1262 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1263 const TargetRegisterClass *RC,
1264 unsigned Op0, bool Op0IsKill,
1266 unsigned ResultReg = createResultReg(RC);
1267 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1269 if (II.getNumDefs() >= 1)
1270 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1271 .addReg(Op0, Op0IsKill * RegState::Kill)
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1275 .addReg(Op0, Op0IsKill * RegState::Kill)
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1278 ResultReg).addReg(II.ImplicitDefs[0]);
1283 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1284 const TargetRegisterClass *RC,
1285 unsigned Op0, bool Op0IsKill,
1286 uint64_t Imm1, uint64_t Imm2) {
1287 unsigned ResultReg = createResultReg(RC);
1288 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1290 if (II.getNumDefs() >= 1)
1291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1292 .addReg(Op0, Op0IsKill * RegState::Kill)
1296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1297 .addReg(Op0, Op0IsKill * RegState::Kill)
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1301 ResultReg).addReg(II.ImplicitDefs[0]);
1306 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1307 const TargetRegisterClass *RC,
1308 unsigned Op0, bool Op0IsKill,
1309 const ConstantFP *FPImm) {
1310 unsigned ResultReg = createResultReg(RC);
1311 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1313 if (II.getNumDefs() >= 1)
1314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1315 .addReg(Op0, Op0IsKill * RegState::Kill)
1318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1319 .addReg(Op0, Op0IsKill * RegState::Kill)
1321 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1322 ResultReg).addReg(II.ImplicitDefs[0]);
1327 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1328 const TargetRegisterClass *RC,
1329 unsigned Op0, bool Op0IsKill,
1330 unsigned Op1, bool Op1IsKill,
1332 unsigned ResultReg = createResultReg(RC);
1333 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1335 if (II.getNumDefs() >= 1)
1336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1337 .addReg(Op0, Op0IsKill * RegState::Kill)
1338 .addReg(Op1, Op1IsKill * RegState::Kill)
1341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1342 .addReg(Op0, Op0IsKill * RegState::Kill)
1343 .addReg(Op1, Op1IsKill * RegState::Kill)
1345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1346 ResultReg).addReg(II.ImplicitDefs[0]);
1351 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1352 const TargetRegisterClass *RC,
1353 unsigned Op0, bool Op0IsKill,
1354 unsigned Op1, bool Op1IsKill,
1355 uint64_t Imm1, uint64_t Imm2) {
1356 unsigned ResultReg = createResultReg(RC);
1357 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1359 if (II.getNumDefs() >= 1)
1360 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1361 .addReg(Op0, Op0IsKill * RegState::Kill)
1362 .addReg(Op1, Op1IsKill * RegState::Kill)
1363 .addImm(Imm1).addImm(Imm2);
1365 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1366 .addReg(Op0, Op0IsKill * RegState::Kill)
1367 .addReg(Op1, Op1IsKill * RegState::Kill)
1368 .addImm(Imm1).addImm(Imm2);
1369 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1370 ResultReg).addReg(II.ImplicitDefs[0]);
1375 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1376 const TargetRegisterClass *RC,
1378 unsigned ResultReg = createResultReg(RC);
1379 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1381 if (II.getNumDefs() >= 1)
1382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1385 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1386 ResultReg).addReg(II.ImplicitDefs[0]);
1391 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1392 const TargetRegisterClass *RC,
1393 uint64_t Imm1, uint64_t Imm2) {
1394 unsigned ResultReg = createResultReg(RC);
1395 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1397 if (II.getNumDefs() >= 1)
1398 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1399 .addImm(Imm1).addImm(Imm2);
1401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1403 ResultReg).addReg(II.ImplicitDefs[0]);
1408 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1409 unsigned Op0, bool Op0IsKill,
1411 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1412 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1413 "Cannot yet extract from physregs");
1414 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1415 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1417 DL, TII.get(TargetOpcode::COPY), ResultReg)
1418 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1422 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1423 /// with all but the least significant bit set to zero.
1424 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1425 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1428 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1429 /// Emit code to ensure constants are copied into registers when needed.
1430 /// Remember the virtual registers that need to be added to the Machine PHI
1431 /// nodes as input. We cannot just directly add them, because expansion
1432 /// might result in multiple MBB's for one BB. As such, the start of the
1433 /// BB might correspond to a different MBB than the end.
1434 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1435 const TerminatorInst *TI = LLVMBB->getTerminator();
1437 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1438 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1440 // Check successor nodes' PHI nodes that expect a constant to be available
1442 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1443 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1444 if (!isa<PHINode>(SuccBB->begin())) continue;
1445 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1447 // If this terminator has multiple identical successors (common for
1448 // switches), only handle each succ once.
1449 if (!SuccsHandled.insert(SuccMBB)) continue;
1451 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1453 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1454 // nodes and Machine PHI nodes, but the incoming operands have not been
1456 for (BasicBlock::const_iterator I = SuccBB->begin();
1457 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1459 // Ignore dead phi's.
1460 if (PN->use_empty()) continue;
1462 // Only handle legal types. Two interesting things to note here. First,
1463 // by bailing out early, we may leave behind some dead instructions,
1464 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1465 // own moves. Second, this check is necessary because FastISel doesn't
1466 // use CreateRegs to create registers, so it always creates
1467 // exactly one register for each non-void instruction.
1468 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1469 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1470 // Handle integer promotions, though, because they're common and easy.
1471 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1472 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1474 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1479 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1481 // Set the DebugLoc for the copy. Prefer the location of the operand
1482 // if there is one; use the location of the PHI otherwise.
1483 DL = PN->getDebugLoc();
1484 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1485 DL = Inst->getDebugLoc();
1487 unsigned Reg = getRegForValue(PHIOp);
1489 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1492 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));