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/Function.h"
44 #include "llvm/GlobalVariable.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/IntrinsicInst.h"
47 #include "llvm/Operator.h"
48 #include "llvm/CodeGen/Analysis.h"
49 #include "llvm/CodeGen/FastISel.h"
50 #include "llvm/CodeGen/FunctionLoweringInfo.h"
51 #include "llvm/CodeGen/MachineInstrBuilder.h"
52 #include "llvm/CodeGen/MachineModuleInfo.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/Analysis/DebugInfo.h"
55 #include "llvm/Analysis/Loads.h"
56 #include "llvm/Target/TargetData.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetLowering.h"
59 #include "llvm/Target/TargetMachine.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/ADT/Statistic.h"
65 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
66 "target-independent selector");
67 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
68 "target-specific selector");
69 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
71 /// startNewBlock - Set the current block to which generated machine
72 /// instructions will be appended, and clear the local CSE map.
74 void FastISel::startNewBlock() {
75 LocalValueMap.clear();
79 // Advance the emit start point past any EH_LABEL instructions.
80 MachineBasicBlock::iterator
81 I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
82 while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
86 LastLocalValue = EmitStartPt;
89 void FastISel::flushLocalValueMap() {
90 LocalValueMap.clear();
91 LastLocalValue = EmitStartPt;
95 bool FastISel::hasTrivialKill(const Value *V) const {
96 // Don't consider constants or arguments to have trivial kills.
97 const Instruction *I = dyn_cast<Instruction>(V);
101 // No-op casts are trivially coalesced by fast-isel.
102 if (const CastInst *Cast = dyn_cast<CastInst>(I))
103 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
104 !hasTrivialKill(Cast->getOperand(0)))
107 // GEPs with all zero indices are trivially coalesced by fast-isel.
108 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
109 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
112 // Only instructions with a single use in the same basic block are considered
113 // to have trivial kills.
114 return I->hasOneUse() &&
115 !(I->getOpcode() == Instruction::BitCast ||
116 I->getOpcode() == Instruction::PtrToInt ||
117 I->getOpcode() == Instruction::IntToPtr) &&
118 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
121 unsigned FastISel::getRegForValue(const Value *V) {
122 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
123 // Don't handle non-simple values in FastISel.
124 if (!RealVT.isSimple())
127 // Ignore illegal types. We must do this before looking up the value
128 // in ValueMap because Arguments are given virtual registers regardless
129 // of whether FastISel can handle them.
130 MVT VT = RealVT.getSimpleVT();
131 if (!TLI.isTypeLegal(VT)) {
132 // Handle integer promotions, though, because they're common and easy.
133 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
134 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
139 // Look up the value to see if we already have a register for it. We
140 // cache values defined by Instructions across blocks, and other values
141 // only locally. This is because Instructions already have the SSA
142 // def-dominates-use requirement enforced.
143 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
144 if (I != FuncInfo.ValueMap.end())
147 unsigned Reg = LocalValueMap[V];
151 // In bottom-up mode, just create the virtual register which will be used
152 // to hold the value. It will be materialized later.
153 if (isa<Instruction>(V) &&
154 (!isa<AllocaInst>(V) ||
155 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
156 return FuncInfo.InitializeRegForValue(V);
158 SavePoint SaveInsertPt = enterLocalValueArea();
160 // Materialize the value in a register. Emit any instructions in the
162 Reg = materializeRegForValue(V, VT);
164 leaveLocalValueArea(SaveInsertPt);
169 /// materializeRegForValue - Helper for getRegForValue. This function is
170 /// called when the value isn't already available in a register and must
171 /// be materialized with new instructions.
172 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
175 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
176 if (CI->getValue().getActiveBits() <= 64)
177 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
178 } else if (isa<AllocaInst>(V)) {
179 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
180 } else if (isa<ConstantPointerNull>(V)) {
181 // Translate this as an integer zero so that it can be
182 // local-CSE'd with actual integer zeros.
184 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
185 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
186 if (CF->isNullValue()) {
187 Reg = TargetMaterializeFloatZero(CF);
189 // Try to emit the constant directly.
190 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
194 // Try to emit the constant by using an integer constant with a cast.
195 const APFloat &Flt = CF->getValueAPF();
196 EVT IntVT = TLI.getPointerTy();
199 uint32_t IntBitWidth = IntVT.getSizeInBits();
201 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
202 APFloat::rmTowardZero, &isExact);
204 APInt IntVal(IntBitWidth, x);
206 unsigned IntegerReg =
207 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
209 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
210 IntegerReg, /*Kill=*/false);
213 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
214 if (!SelectOperator(Op, Op->getOpcode()))
215 if (!isa<Instruction>(Op) ||
216 !TargetSelectInstruction(cast<Instruction>(Op)))
218 Reg = lookUpRegForValue(Op);
219 } else if (isa<UndefValue>(V)) {
220 Reg = createResultReg(TLI.getRegClassFor(VT));
221 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
222 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
225 // If target-independent code couldn't handle the value, give target-specific
227 if (!Reg && isa<Constant>(V))
228 Reg = TargetMaterializeConstant(cast<Constant>(V));
230 // Don't cache constant materializations in the general ValueMap.
231 // To do so would require tracking what uses they dominate.
233 LocalValueMap[V] = Reg;
234 LastLocalValue = MRI.getVRegDef(Reg);
239 unsigned FastISel::lookUpRegForValue(const Value *V) {
240 // Look up the value to see if we already have a register for it. We
241 // cache values defined by Instructions across blocks, and other values
242 // only locally. This is because Instructions already have the SSA
243 // def-dominates-use requirement enforced.
244 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
245 if (I != FuncInfo.ValueMap.end())
247 return LocalValueMap[V];
250 /// UpdateValueMap - Update the value map to include the new mapping for this
251 /// instruction, or insert an extra copy to get the result in a previous
252 /// determined register.
253 /// NOTE: This is only necessary because we might select a block that uses
254 /// a value before we select the block that defines the value. It might be
255 /// possible to fix this by selecting blocks in reverse postorder.
256 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
257 if (!isa<Instruction>(I)) {
258 LocalValueMap[I] = Reg;
262 unsigned &AssignedReg = FuncInfo.ValueMap[I];
263 if (AssignedReg == 0)
264 // Use the new register.
266 else if (Reg != AssignedReg) {
267 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
268 for (unsigned i = 0; i < NumRegs; i++)
269 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
275 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
276 unsigned IdxN = getRegForValue(Idx);
278 // Unhandled operand. Halt "fast" selection and bail.
279 return std::pair<unsigned, bool>(0, false);
281 bool IdxNIsKill = hasTrivialKill(Idx);
283 // If the index is smaller or larger than intptr_t, truncate or extend it.
284 MVT PtrVT = TLI.getPointerTy();
285 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
286 if (IdxVT.bitsLT(PtrVT)) {
287 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
291 else if (IdxVT.bitsGT(PtrVT)) {
292 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
296 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
299 void FastISel::recomputeInsertPt() {
300 if (getLastLocalValue()) {
301 FuncInfo.InsertPt = getLastLocalValue();
302 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
305 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
307 // Now skip past any EH_LABELs, which must remain at the beginning.
308 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
309 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
313 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
314 MachineBasicBlock::iterator E) {
315 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
317 MachineInstr *Dead = &*I;
319 Dead->eraseFromParent();
325 FastISel::SavePoint FastISel::enterLocalValueArea() {
326 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
330 SavePoint SP = { OldInsertPt, OldDL };
334 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
335 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
336 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
338 // Restore the previous insert position.
339 FuncInfo.InsertPt = OldInsertPt.InsertPt;
343 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
344 /// which has an opcode which directly corresponds to the given ISD opcode.
346 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
347 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
348 if (VT == MVT::Other || !VT.isSimple())
349 // Unhandled type. Halt "fast" selection and bail.
352 // We only handle legal types. For example, on x86-32 the instruction
353 // selector contains all of the 64-bit instructions from x86-64,
354 // under the assumption that i64 won't be used if the target doesn't
356 if (!TLI.isTypeLegal(VT)) {
357 // MVT::i1 is special. Allow AND, OR, or XOR because they
358 // don't require additional zeroing, which makes them easy.
360 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
361 ISDOpcode == ISD::XOR))
362 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
367 // Check if the first operand is a constant, and handle it as "ri". At -O0,
368 // we don't have anything that canonicalizes operand order.
369 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
370 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
371 unsigned Op1 = getRegForValue(I->getOperand(1));
372 if (Op1 == 0) return false;
374 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
376 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
377 Op1IsKill, CI->getZExtValue(),
379 if (ResultReg == 0) return false;
381 // We successfully emitted code for the given LLVM Instruction.
382 UpdateValueMap(I, ResultReg);
387 unsigned Op0 = getRegForValue(I->getOperand(0));
388 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
391 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
393 // Check if the second operand is a constant and handle it appropriately.
394 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
395 uint64_t Imm = CI->getZExtValue();
397 // Transform "sdiv exact X, 8" -> "sra X, 3".
398 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
399 cast<BinaryOperator>(I)->isExact() &&
400 isPowerOf2_64(Imm)) {
402 ISDOpcode = ISD::SRA;
405 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
406 Op0IsKill, Imm, VT.getSimpleVT());
407 if (ResultReg == 0) return false;
409 // We successfully emitted code for the given LLVM Instruction.
410 UpdateValueMap(I, ResultReg);
414 // Check if the second operand is a constant float.
415 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
416 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
417 ISDOpcode, Op0, Op0IsKill, CF);
418 if (ResultReg != 0) {
419 // We successfully emitted code for the given LLVM Instruction.
420 UpdateValueMap(I, ResultReg);
425 unsigned Op1 = getRegForValue(I->getOperand(1));
427 // Unhandled operand. Halt "fast" selection and bail.
430 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
432 // Now we have both operands in registers. Emit the instruction.
433 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
438 // Target-specific code wasn't able to find a machine opcode for
439 // the given ISD opcode and type. Halt "fast" selection and bail.
442 // We successfully emitted code for the given LLVM Instruction.
443 UpdateValueMap(I, ResultReg);
447 bool FastISel::SelectGetElementPtr(const User *I) {
448 unsigned N = getRegForValue(I->getOperand(0));
450 // Unhandled operand. Halt "fast" selection and bail.
453 bool NIsKill = hasTrivialKill(I->getOperand(0));
455 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
456 // into a single N = N + TotalOffset.
457 uint64_t TotalOffs = 0;
458 // FIXME: What's a good SWAG number for MaxOffs?
459 uint64_t MaxOffs = 2048;
460 Type *Ty = I->getOperand(0)->getType();
461 MVT VT = TLI.getPointerTy();
462 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
463 E = I->op_end(); OI != E; ++OI) {
464 const Value *Idx = *OI;
465 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
466 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
469 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
470 if (TotalOffs >= MaxOffs) {
471 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
473 // Unhandled operand. Halt "fast" selection and bail.
479 Ty = StTy->getElementType(Field);
481 Ty = cast<SequentialType>(Ty)->getElementType();
483 // If this is a constant subscript, handle it quickly.
484 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
485 if (CI->isZero()) continue;
488 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
489 if (TotalOffs >= MaxOffs) {
490 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
492 // Unhandled operand. Halt "fast" selection and bail.
500 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
502 // Unhandled operand. Halt "fast" selection and bail.
508 // N = N + Idx * ElementSize;
509 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
510 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
511 unsigned IdxN = Pair.first;
512 bool IdxNIsKill = Pair.second;
514 // Unhandled operand. Halt "fast" selection and bail.
517 if (ElementSize != 1) {
518 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
520 // Unhandled operand. Halt "fast" selection and bail.
524 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
526 // Unhandled operand. Halt "fast" selection and bail.
531 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
533 // Unhandled operand. Halt "fast" selection and bail.
537 // We successfully emitted code for the given LLVM Instruction.
538 UpdateValueMap(I, N);
542 bool FastISel::SelectCall(const User *I) {
543 const CallInst *Call = cast<CallInst>(I);
545 // Handle simple inline asms.
546 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
547 // Don't attempt to handle constraints.
548 if (!IA->getConstraintString().empty())
551 unsigned ExtraInfo = 0;
552 if (IA->hasSideEffects())
553 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
554 if (IA->isAlignStack())
555 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
558 TII.get(TargetOpcode::INLINEASM))
559 .addExternalSymbol(IA->getAsmString().c_str())
564 const Function *F = Call->getCalledFunction();
565 if (!F) return false;
567 // Handle selected intrinsic function calls.
568 switch (F->getIntrinsicID()) {
570 case Intrinsic::dbg_declare: {
571 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
572 if (!DIVariable(DI->getVariable()).Verify() ||
573 !FuncInfo.MF->getMMI().hasDebugInfo())
576 const Value *Address = DI->getAddress();
577 if (!Address || isa<UndefValue>(Address) || isa<AllocaInst>(Address))
582 if (const Argument *Arg = dyn_cast<Argument>(Address)) {
583 // Some arguments' frame index is recorded during argument lowering.
584 Offset = FuncInfo.getArgumentFrameIndex(Arg);
586 Reg = TRI.getFrameRegister(*FuncInfo.MF);
589 Reg = getRegForValue(Address);
592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
593 TII.get(TargetOpcode::DBG_VALUE))
594 .addReg(Reg, RegState::Debug).addImm(Offset)
595 .addMetadata(DI->getVariable());
598 case Intrinsic::dbg_value: {
599 // This form of DBG_VALUE is target-independent.
600 const DbgValueInst *DI = cast<DbgValueInst>(Call);
601 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
602 const Value *V = DI->getValue();
604 // Currently the optimizer can produce this; insert an undef to
605 // help debugging. Probably the optimizer should not do this.
606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
607 .addReg(0U).addImm(DI->getOffset())
608 .addMetadata(DI->getVariable());
609 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
610 if (CI->getBitWidth() > 64)
611 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
612 .addCImm(CI).addImm(DI->getOffset())
613 .addMetadata(DI->getVariable());
615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
616 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
617 .addMetadata(DI->getVariable());
618 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
619 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
620 .addFPImm(CF).addImm(DI->getOffset())
621 .addMetadata(DI->getVariable());
622 } else if (unsigned Reg = lookUpRegForValue(V)) {
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
624 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
625 .addMetadata(DI->getVariable());
627 // We can't yet handle anything else here because it would require
628 // generating code, thus altering codegen because of debug info.
629 DEBUG(dbgs() << "Dropping debug info for " << DI);
633 case Intrinsic::objectsize: {
634 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
635 unsigned long long Res = CI->isZero() ? -1ULL : 0;
636 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
637 unsigned ResultReg = getRegForValue(ResCI);
640 UpdateValueMap(Call, ResultReg);
645 // Usually, it does not make sense to initialize a value,
646 // make an unrelated function call and use the value, because
647 // it tends to be spilled on the stack. So, we move the pointer
648 // to the last local value to the beginning of the block, so that
649 // all the values which have already been materialized,
650 // appear after the call. It also makes sense to skip intrinsics
651 // since they tend to be inlined.
652 if (!isa<IntrinsicInst>(F))
653 flushLocalValueMap();
655 // An arbitrary call. Bail.
659 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
660 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
661 EVT DstVT = TLI.getValueType(I->getType());
663 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
664 DstVT == MVT::Other || !DstVT.isSimple())
665 // Unhandled type. Halt "fast" selection and bail.
668 // Check if the destination type is legal.
669 if (!TLI.isTypeLegal(DstVT))
672 // Check if the source operand is legal.
673 if (!TLI.isTypeLegal(SrcVT))
676 unsigned InputReg = getRegForValue(I->getOperand(0));
678 // Unhandled operand. Halt "fast" selection and bail.
681 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
683 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
686 InputReg, InputRegIsKill);
690 UpdateValueMap(I, ResultReg);
694 bool FastISel::SelectBitCast(const User *I) {
695 // If the bitcast doesn't change the type, just use the operand value.
696 if (I->getType() == I->getOperand(0)->getType()) {
697 unsigned Reg = getRegForValue(I->getOperand(0));
700 UpdateValueMap(I, Reg);
704 // Bitcasts of other values become reg-reg copies or BITCAST operators.
705 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
706 EVT DstVT = TLI.getValueType(I->getType());
708 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
709 DstVT == MVT::Other || !DstVT.isSimple() ||
710 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT))
711 // Unhandled type. Halt "fast" selection and bail.
714 unsigned Op0 = getRegForValue(I->getOperand(0));
716 // Unhandled operand. Halt "fast" selection and bail.
719 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
721 // First, try to perform the bitcast by inserting a reg-reg copy.
722 unsigned ResultReg = 0;
723 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) {
724 TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
725 TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
726 // Don't attempt a cross-class copy. It will likely fail.
727 if (SrcClass == DstClass) {
728 ResultReg = createResultReg(DstClass);
729 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
730 ResultReg).addReg(Op0);
734 // If the reg-reg copy failed, select a BITCAST opcode.
736 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
737 ISD::BITCAST, Op0, Op0IsKill);
742 UpdateValueMap(I, ResultReg);
747 FastISel::SelectInstruction(const Instruction *I) {
748 // Just before the terminator instruction, insert instructions to
749 // feed PHI nodes in successor blocks.
750 if (isa<TerminatorInst>(I))
751 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
754 DL = I->getDebugLoc();
756 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
758 // First, try doing target-independent selection.
759 if (SelectOperator(I, I->getOpcode())) {
760 ++NumFastIselSuccessIndependent;
764 // Remove dead code. However, ignore call instructions since we've flushed
765 // the local value map and recomputed the insert point.
766 if (!isa<CallInst>(I)) {
768 if (SavedInsertPt != FuncInfo.InsertPt)
769 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
772 // Next, try calling the target to attempt to handle the instruction.
773 SavedInsertPt = FuncInfo.InsertPt;
774 if (TargetSelectInstruction(I)) {
775 ++NumFastIselSuccessTarget;
779 // Check for dead code and remove as necessary.
781 if (SavedInsertPt != FuncInfo.InsertPt)
782 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
788 /// FastEmitBranch - Emit an unconditional branch to the given block,
789 /// unless it is the immediate (fall-through) successor, and update
792 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
793 if (FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
794 // The unconditional fall-through case, which needs no instructions.
796 // The unconditional branch case.
797 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
798 SmallVector<MachineOperand, 0>(), DL);
800 FuncInfo.MBB->addSuccessor(MSucc);
803 /// SelectFNeg - Emit an FNeg operation.
806 FastISel::SelectFNeg(const User *I) {
807 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
808 if (OpReg == 0) return false;
810 bool OpRegIsKill = hasTrivialKill(I);
812 // If the target has ISD::FNEG, use it.
813 EVT VT = TLI.getValueType(I->getType());
814 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
815 ISD::FNEG, OpReg, OpRegIsKill);
816 if (ResultReg != 0) {
817 UpdateValueMap(I, ResultReg);
821 // Bitcast the value to integer, twiddle the sign bit with xor,
822 // and then bitcast it back to floating-point.
823 if (VT.getSizeInBits() > 64) return false;
824 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
825 if (!TLI.isTypeLegal(IntVT))
828 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
829 ISD::BITCAST, OpReg, OpRegIsKill);
833 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
834 IntReg, /*Kill=*/true,
835 UINT64_C(1) << (VT.getSizeInBits()-1),
836 IntVT.getSimpleVT());
837 if (IntResultReg == 0)
840 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
841 ISD::BITCAST, IntResultReg, /*Kill=*/true);
845 UpdateValueMap(I, ResultReg);
850 FastISel::SelectExtractValue(const User *U) {
851 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
855 // Make sure we only try to handle extracts with a legal result. But also
856 // allow i1 because it's easy.
857 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
858 if (!RealVT.isSimple())
860 MVT VT = RealVT.getSimpleVT();
861 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
864 const Value *Op0 = EVI->getOperand(0);
865 Type *AggTy = Op0->getType();
867 // Get the base result register.
869 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
870 if (I != FuncInfo.ValueMap.end())
871 ResultReg = I->second;
872 else if (isa<Instruction>(Op0))
873 ResultReg = FuncInfo.InitializeRegForValue(Op0);
875 return false; // fast-isel can't handle aggregate constants at the moment
877 // Get the actual result register, which is an offset from the base register.
878 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
880 SmallVector<EVT, 4> AggValueVTs;
881 ComputeValueVTs(TLI, AggTy, AggValueVTs);
883 for (unsigned i = 0; i < VTIndex; i++)
884 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
886 UpdateValueMap(EVI, ResultReg);
891 FastISel::SelectOperator(const User *I, unsigned Opcode) {
893 case Instruction::Add:
894 return SelectBinaryOp(I, ISD::ADD);
895 case Instruction::FAdd:
896 return SelectBinaryOp(I, ISD::FADD);
897 case Instruction::Sub:
898 return SelectBinaryOp(I, ISD::SUB);
899 case Instruction::FSub:
900 // FNeg is currently represented in LLVM IR as a special case of FSub.
901 if (BinaryOperator::isFNeg(I))
902 return SelectFNeg(I);
903 return SelectBinaryOp(I, ISD::FSUB);
904 case Instruction::Mul:
905 return SelectBinaryOp(I, ISD::MUL);
906 case Instruction::FMul:
907 return SelectBinaryOp(I, ISD::FMUL);
908 case Instruction::SDiv:
909 return SelectBinaryOp(I, ISD::SDIV);
910 case Instruction::UDiv:
911 return SelectBinaryOp(I, ISD::UDIV);
912 case Instruction::FDiv:
913 return SelectBinaryOp(I, ISD::FDIV);
914 case Instruction::SRem:
915 return SelectBinaryOp(I, ISD::SREM);
916 case Instruction::URem:
917 return SelectBinaryOp(I, ISD::UREM);
918 case Instruction::FRem:
919 return SelectBinaryOp(I, ISD::FREM);
920 case Instruction::Shl:
921 return SelectBinaryOp(I, ISD::SHL);
922 case Instruction::LShr:
923 return SelectBinaryOp(I, ISD::SRL);
924 case Instruction::AShr:
925 return SelectBinaryOp(I, ISD::SRA);
926 case Instruction::And:
927 return SelectBinaryOp(I, ISD::AND);
928 case Instruction::Or:
929 return SelectBinaryOp(I, ISD::OR);
930 case Instruction::Xor:
931 return SelectBinaryOp(I, ISD::XOR);
933 case Instruction::GetElementPtr:
934 return SelectGetElementPtr(I);
936 case Instruction::Br: {
937 const BranchInst *BI = cast<BranchInst>(I);
939 if (BI->isUnconditional()) {
940 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
941 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
942 FastEmitBranch(MSucc, BI->getDebugLoc());
946 // Conditional branches are not handed yet.
947 // Halt "fast" selection and bail.
951 case Instruction::Unreachable:
955 case Instruction::Alloca:
956 // FunctionLowering has the static-sized case covered.
957 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
960 // Dynamic-sized alloca is not handled yet.
963 case Instruction::Call:
964 return SelectCall(I);
966 case Instruction::BitCast:
967 return SelectBitCast(I);
969 case Instruction::FPToSI:
970 return SelectCast(I, ISD::FP_TO_SINT);
971 case Instruction::ZExt:
972 return SelectCast(I, ISD::ZERO_EXTEND);
973 case Instruction::SExt:
974 return SelectCast(I, ISD::SIGN_EXTEND);
975 case Instruction::Trunc:
976 return SelectCast(I, ISD::TRUNCATE);
977 case Instruction::SIToFP:
978 return SelectCast(I, ISD::SINT_TO_FP);
980 case Instruction::IntToPtr: // Deliberate fall-through.
981 case Instruction::PtrToInt: {
982 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
983 EVT DstVT = TLI.getValueType(I->getType());
984 if (DstVT.bitsGT(SrcVT))
985 return SelectCast(I, ISD::ZERO_EXTEND);
986 if (DstVT.bitsLT(SrcVT))
987 return SelectCast(I, ISD::TRUNCATE);
988 unsigned Reg = getRegForValue(I->getOperand(0));
989 if (Reg == 0) return false;
990 UpdateValueMap(I, Reg);
994 case Instruction::ExtractValue:
995 return SelectExtractValue(I);
997 case Instruction::PHI:
998 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1001 // Unhandled instruction. Halt "fast" selection and bail.
1006 FastISel::FastISel(FunctionLoweringInfo &funcInfo)
1007 : FuncInfo(funcInfo),
1008 MRI(FuncInfo.MF->getRegInfo()),
1009 MFI(*FuncInfo.MF->getFrameInfo()),
1010 MCP(*FuncInfo.MF->getConstantPool()),
1011 TM(FuncInfo.MF->getTarget()),
1012 TD(*TM.getTargetData()),
1013 TII(*TM.getInstrInfo()),
1014 TLI(*TM.getTargetLowering()),
1015 TRI(*TM.getRegisterInfo()) {
1018 FastISel::~FastISel() {}
1020 unsigned FastISel::FastEmit_(MVT, MVT,
1025 unsigned FastISel::FastEmit_r(MVT, MVT,
1027 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1031 unsigned FastISel::FastEmit_rr(MVT, MVT,
1033 unsigned /*Op0*/, bool /*Op0IsKill*/,
1034 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1038 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1042 unsigned FastISel::FastEmit_f(MVT, MVT,
1043 unsigned, const ConstantFP * /*FPImm*/) {
1047 unsigned FastISel::FastEmit_ri(MVT, MVT,
1049 unsigned /*Op0*/, bool /*Op0IsKill*/,
1054 unsigned FastISel::FastEmit_rf(MVT, MVT,
1056 unsigned /*Op0*/, bool /*Op0IsKill*/,
1057 const ConstantFP * /*FPImm*/) {
1061 unsigned FastISel::FastEmit_rri(MVT, MVT,
1063 unsigned /*Op0*/, bool /*Op0IsKill*/,
1064 unsigned /*Op1*/, bool /*Op1IsKill*/,
1069 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1070 /// to emit an instruction with an immediate operand using FastEmit_ri.
1071 /// If that fails, it materializes the immediate into a register and try
1072 /// FastEmit_rr instead.
1073 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1074 unsigned Op0, bool Op0IsKill,
1075 uint64_t Imm, MVT ImmType) {
1076 // If this is a multiply by a power of two, emit this as a shift left.
1077 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1080 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1081 // div x, 8 -> srl x, 3
1086 // Horrible hack (to be removed), check to make sure shift amounts are
1088 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1089 Imm >= VT.getSizeInBits())
1092 // First check if immediate type is legal. If not, we can't use the ri form.
1093 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1096 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1097 if (MaterialReg == 0) {
1098 // This is a bit ugly/slow, but failing here means falling out of
1099 // fast-isel, which would be very slow.
1100 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1101 VT.getSizeInBits());
1102 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1104 return FastEmit_rr(VT, VT, Opcode,
1106 MaterialReg, /*Kill=*/true);
1109 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1110 return MRI.createVirtualRegister(RC);
1113 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1114 const TargetRegisterClass* RC) {
1115 unsigned ResultReg = createResultReg(RC);
1116 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1118 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1122 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1123 const TargetRegisterClass *RC,
1124 unsigned Op0, bool Op0IsKill) {
1125 unsigned ResultReg = createResultReg(RC);
1126 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1128 if (II.getNumDefs() >= 1)
1129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1130 .addReg(Op0, Op0IsKill * RegState::Kill);
1132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1133 .addReg(Op0, Op0IsKill * RegState::Kill);
1134 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1135 ResultReg).addReg(II.ImplicitDefs[0]);
1141 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1142 const TargetRegisterClass *RC,
1143 unsigned Op0, bool Op0IsKill,
1144 unsigned Op1, bool Op1IsKill) {
1145 unsigned ResultReg = createResultReg(RC);
1146 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1148 if (II.getNumDefs() >= 1)
1149 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1150 .addReg(Op0, Op0IsKill * RegState::Kill)
1151 .addReg(Op1, Op1IsKill * RegState::Kill);
1153 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1154 .addReg(Op0, Op0IsKill * RegState::Kill)
1155 .addReg(Op1, Op1IsKill * RegState::Kill);
1156 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1157 ResultReg).addReg(II.ImplicitDefs[0]);
1162 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1163 const TargetRegisterClass *RC,
1164 unsigned Op0, bool Op0IsKill,
1165 unsigned Op1, bool Op1IsKill,
1166 unsigned Op2, bool Op2IsKill) {
1167 unsigned ResultReg = createResultReg(RC);
1168 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1170 if (II.getNumDefs() >= 1)
1171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1172 .addReg(Op0, Op0IsKill * RegState::Kill)
1173 .addReg(Op1, Op1IsKill * RegState::Kill)
1174 .addReg(Op2, Op2IsKill * RegState::Kill);
1176 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1177 .addReg(Op0, Op0IsKill * RegState::Kill)
1178 .addReg(Op1, Op1IsKill * RegState::Kill)
1179 .addReg(Op2, Op2IsKill * RegState::Kill);
1180 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1181 ResultReg).addReg(II.ImplicitDefs[0]);
1186 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1187 const TargetRegisterClass *RC,
1188 unsigned Op0, bool Op0IsKill,
1190 unsigned ResultReg = createResultReg(RC);
1191 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1193 if (II.getNumDefs() >= 1)
1194 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1195 .addReg(Op0, Op0IsKill * RegState::Kill)
1198 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1199 .addReg(Op0, Op0IsKill * RegState::Kill)
1201 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1202 ResultReg).addReg(II.ImplicitDefs[0]);
1207 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1208 const TargetRegisterClass *RC,
1209 unsigned Op0, bool Op0IsKill,
1210 uint64_t Imm1, uint64_t Imm2) {
1211 unsigned ResultReg = createResultReg(RC);
1212 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1214 if (II.getNumDefs() >= 1)
1215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1216 .addReg(Op0, Op0IsKill * RegState::Kill)
1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1221 .addReg(Op0, Op0IsKill * RegState::Kill)
1224 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1225 ResultReg).addReg(II.ImplicitDefs[0]);
1230 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1231 const TargetRegisterClass *RC,
1232 unsigned Op0, bool Op0IsKill,
1233 const ConstantFP *FPImm) {
1234 unsigned ResultReg = createResultReg(RC);
1235 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1237 if (II.getNumDefs() >= 1)
1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1239 .addReg(Op0, Op0IsKill * RegState::Kill)
1242 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1243 .addReg(Op0, Op0IsKill * RegState::Kill)
1245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1246 ResultReg).addReg(II.ImplicitDefs[0]);
1251 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1252 const TargetRegisterClass *RC,
1253 unsigned Op0, bool Op0IsKill,
1254 unsigned Op1, bool Op1IsKill,
1256 unsigned ResultReg = createResultReg(RC);
1257 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1259 if (II.getNumDefs() >= 1)
1260 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1261 .addReg(Op0, Op0IsKill * RegState::Kill)
1262 .addReg(Op1, Op1IsKill * RegState::Kill)
1265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1266 .addReg(Op0, Op0IsKill * RegState::Kill)
1267 .addReg(Op1, Op1IsKill * RegState::Kill)
1269 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1270 ResultReg).addReg(II.ImplicitDefs[0]);
1275 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1276 const TargetRegisterClass *RC,
1278 unsigned ResultReg = createResultReg(RC);
1279 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1281 if (II.getNumDefs() >= 1)
1282 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1284 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1286 ResultReg).addReg(II.ImplicitDefs[0]);
1291 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1292 const TargetRegisterClass *RC,
1293 uint64_t Imm1, uint64_t Imm2) {
1294 unsigned ResultReg = createResultReg(RC);
1295 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1297 if (II.getNumDefs() >= 1)
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1299 .addImm(Imm1).addImm(Imm2);
1301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1303 ResultReg).addReg(II.ImplicitDefs[0]);
1308 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1309 unsigned Op0, bool Op0IsKill,
1311 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1312 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1313 "Cannot yet extract from physregs");
1314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1315 DL, TII.get(TargetOpcode::COPY), ResultReg)
1316 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1320 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1321 /// with all but the least significant bit set to zero.
1322 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1323 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1326 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1327 /// Emit code to ensure constants are copied into registers when needed.
1328 /// Remember the virtual registers that need to be added to the Machine PHI
1329 /// nodes as input. We cannot just directly add them, because expansion
1330 /// might result in multiple MBB's for one BB. As such, the start of the
1331 /// BB might correspond to a different MBB than the end.
1332 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1333 const TerminatorInst *TI = LLVMBB->getTerminator();
1335 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1336 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1338 // Check successor nodes' PHI nodes that expect a constant to be available
1340 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1341 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1342 if (!isa<PHINode>(SuccBB->begin())) continue;
1343 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1345 // If this terminator has multiple identical successors (common for
1346 // switches), only handle each succ once.
1347 if (!SuccsHandled.insert(SuccMBB)) continue;
1349 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1351 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1352 // nodes and Machine PHI nodes, but the incoming operands have not been
1354 for (BasicBlock::const_iterator I = SuccBB->begin();
1355 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1357 // Ignore dead phi's.
1358 if (PN->use_empty()) continue;
1360 // Only handle legal types. Two interesting things to note here. First,
1361 // by bailing out early, we may leave behind some dead instructions,
1362 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1363 // own moves. Second, this check is necessary because FastISel doesn't
1364 // use CreateRegs to create registers, so it always creates
1365 // exactly one register for each non-void instruction.
1366 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1367 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1368 // Handle integer promotions, though, because they're common and easy.
1369 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1370 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1372 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1377 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1379 // Set the DebugLoc for the copy. Prefer the location of the operand
1380 // if there is one; use the location of the PHI otherwise.
1381 DL = PN->getDebugLoc();
1382 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1383 DL = Inst->getDebugLoc();
1385 unsigned Reg = getRegForValue(PHIOp);
1387 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1390 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));