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/Optional.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Analysis/Loads.h"
47 #include "llvm/CodeGen/Analysis.h"
48 #include "llvm/CodeGen/FunctionLoweringInfo.h"
49 #include "llvm/CodeGen/MachineInstrBuilder.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/DebugInfo.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalVariable.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Target/TargetInstrInfo.h"
62 #include "llvm/Target/TargetLibraryInfo.h"
63 #include "llvm/Target/TargetLowering.h"
64 #include "llvm/Target/TargetMachine.h"
67 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
68 "target-independent selector");
69 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
70 "target-specific selector");
71 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
73 /// startNewBlock - Set the current block to which generated machine
74 /// instructions will be appended, and clear the local CSE map.
76 void FastISel::startNewBlock() {
77 LocalValueMap.clear();
79 // Instructions are appended to FuncInfo.MBB. If the basic block already
80 // contains labels or copies, use the last instruction as the last local
83 if (!FuncInfo.MBB->empty())
84 EmitStartPt = &FuncInfo.MBB->back();
85 LastLocalValue = EmitStartPt;
88 bool FastISel::LowerArguments() {
89 if (!FuncInfo.CanLowerReturn)
90 // Fallback to SDISel argument lowering code to deal with sret pointer
94 if (!FastLowerArguments())
97 // Enter arguments into ValueMap for uses in non-entry BBs.
98 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
99 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
100 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
101 assert(VI != LocalValueMap.end() && "Missed an argument?");
102 FuncInfo.ValueMap[I] = VI->second;
107 void FastISel::flushLocalValueMap() {
108 LocalValueMap.clear();
109 LastLocalValue = EmitStartPt;
113 bool FastISel::hasTrivialKill(const Value *V) const {
114 // Don't consider constants or arguments to have trivial kills.
115 const Instruction *I = dyn_cast<Instruction>(V);
119 // No-op casts are trivially coalesced by fast-isel.
120 if (const CastInst *Cast = dyn_cast<CastInst>(I))
121 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
122 !hasTrivialKill(Cast->getOperand(0)))
125 // GEPs with all zero indices are trivially coalesced by fast-isel.
126 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
127 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
130 // Only instructions with a single use in the same basic block are considered
131 // to have trivial kills.
132 return I->hasOneUse() &&
133 !(I->getOpcode() == Instruction::BitCast ||
134 I->getOpcode() == Instruction::PtrToInt ||
135 I->getOpcode() == Instruction::IntToPtr) &&
136 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
139 unsigned FastISel::getRegForValue(const Value *V) {
140 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
141 // Don't handle non-simple values in FastISel.
142 if (!RealVT.isSimple())
145 // Ignore illegal types. We must do this before looking up the value
146 // in ValueMap because Arguments are given virtual registers regardless
147 // of whether FastISel can handle them.
148 MVT VT = RealVT.getSimpleVT();
149 if (!TLI.isTypeLegal(VT)) {
150 // Handle integer promotions, though, because they're common and easy.
151 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
152 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
157 // Look up the value to see if we already have a register for it.
158 unsigned Reg = lookUpRegForValue(V);
162 // In bottom-up mode, just create the virtual register which will be used
163 // to hold the value. It will be materialized later.
164 if (isa<Instruction>(V) &&
165 (!isa<AllocaInst>(V) ||
166 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
167 return FuncInfo.InitializeRegForValue(V);
169 SavePoint SaveInsertPt = enterLocalValueArea();
171 // Materialize the value in a register. Emit any instructions in the
173 Reg = materializeRegForValue(V, VT);
175 leaveLocalValueArea(SaveInsertPt);
180 /// materializeRegForValue - Helper for getRegForValue. This function is
181 /// called when the value isn't already available in a register and must
182 /// be materialized with new instructions.
183 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
186 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
187 if (CI->getValue().getActiveBits() <= 64)
188 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
189 } else if (isa<AllocaInst>(V)) {
190 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
191 } else if (isa<ConstantPointerNull>(V)) {
192 // Translate this as an integer zero so that it can be
193 // local-CSE'd with actual integer zeros.
195 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
196 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
197 if (CF->isNullValue()) {
198 Reg = TargetMaterializeFloatZero(CF);
200 // Try to emit the constant directly.
201 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
205 // Try to emit the constant by using an integer constant with a cast.
206 const APFloat &Flt = CF->getValueAPF();
207 EVT IntVT = TLI.getPointerTy();
210 uint32_t IntBitWidth = IntVT.getSizeInBits();
212 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
213 APFloat::rmTowardZero, &isExact);
215 APInt IntVal(IntBitWidth, x);
217 unsigned IntegerReg =
218 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
220 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
221 IntegerReg, /*Kill=*/false);
224 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
225 if (!SelectOperator(Op, Op->getOpcode()))
226 if (!isa<Instruction>(Op) ||
227 !TargetSelectInstruction(cast<Instruction>(Op)))
229 Reg = lookUpRegForValue(Op);
230 } else if (isa<UndefValue>(V)) {
231 Reg = createResultReg(TLI.getRegClassFor(VT));
232 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
233 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
236 // If target-independent code couldn't handle the value, give target-specific
238 if (!Reg && isa<Constant>(V))
239 Reg = TargetMaterializeConstant(cast<Constant>(V));
241 // Don't cache constant materializations in the general ValueMap.
242 // To do so would require tracking what uses they dominate.
244 LocalValueMap[V] = Reg;
245 LastLocalValue = MRI.getVRegDef(Reg);
250 unsigned FastISel::lookUpRegForValue(const Value *V) {
251 // Look up the value to see if we already have a register for it. We
252 // cache values defined by Instructions across blocks, and other values
253 // only locally. This is because Instructions already have the SSA
254 // def-dominates-use requirement enforced.
255 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
256 if (I != FuncInfo.ValueMap.end())
258 return LocalValueMap[V];
261 /// UpdateValueMap - Update the value map to include the new mapping for this
262 /// instruction, or insert an extra copy to get the result in a previous
263 /// determined register.
264 /// NOTE: This is only necessary because we might select a block that uses
265 /// a value before we select the block that defines the value. It might be
266 /// possible to fix this by selecting blocks in reverse postorder.
267 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
268 if (!isa<Instruction>(I)) {
269 LocalValueMap[I] = Reg;
273 unsigned &AssignedReg = FuncInfo.ValueMap[I];
274 if (AssignedReg == 0)
275 // Use the new register.
277 else if (Reg != AssignedReg) {
278 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
279 for (unsigned i = 0; i < NumRegs; i++)
280 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
286 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
287 unsigned IdxN = getRegForValue(Idx);
289 // Unhandled operand. Halt "fast" selection and bail.
290 return std::pair<unsigned, bool>(0, false);
292 bool IdxNIsKill = hasTrivialKill(Idx);
294 // If the index is smaller or larger than intptr_t, truncate or extend it.
295 MVT PtrVT = TLI.getPointerTy();
296 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
297 if (IdxVT.bitsLT(PtrVT)) {
298 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
302 else if (IdxVT.bitsGT(PtrVT)) {
303 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
307 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
310 void FastISel::recomputeInsertPt() {
311 if (getLastLocalValue()) {
312 FuncInfo.InsertPt = getLastLocalValue();
313 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
316 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
318 // Now skip past any EH_LABELs, which must remain at the beginning.
319 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
320 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
324 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
325 MachineBasicBlock::iterator E) {
326 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
328 MachineInstr *Dead = &*I;
330 Dead->eraseFromParent();
336 FastISel::SavePoint FastISel::enterLocalValueArea() {
337 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
341 SavePoint SP = { OldInsertPt, OldDL };
345 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
346 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
347 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
349 // Restore the previous insert position.
350 FuncInfo.InsertPt = OldInsertPt.InsertPt;
354 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
355 /// which has an opcode which directly corresponds to the given ISD opcode.
357 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
358 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
359 if (VT == MVT::Other || !VT.isSimple())
360 // Unhandled type. Halt "fast" selection and bail.
363 // We only handle legal types. For example, on x86-32 the instruction
364 // selector contains all of the 64-bit instructions from x86-64,
365 // under the assumption that i64 won't be used if the target doesn't
367 if (!TLI.isTypeLegal(VT)) {
368 // MVT::i1 is special. Allow AND, OR, or XOR because they
369 // don't require additional zeroing, which makes them easy.
371 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
372 ISDOpcode == ISD::XOR))
373 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
378 // Check if the first operand is a constant, and handle it as "ri". At -O0,
379 // we don't have anything that canonicalizes operand order.
380 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
381 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
382 unsigned Op1 = getRegForValue(I->getOperand(1));
383 if (Op1 == 0) return false;
385 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
387 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
388 Op1IsKill, CI->getZExtValue(),
390 if (ResultReg == 0) return false;
392 // We successfully emitted code for the given LLVM Instruction.
393 UpdateValueMap(I, ResultReg);
398 unsigned Op0 = getRegForValue(I->getOperand(0));
399 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
402 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
404 // Check if the second operand is a constant and handle it appropriately.
405 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
406 uint64_t Imm = CI->getZExtValue();
408 // Transform "sdiv exact X, 8" -> "sra X, 3".
409 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
410 cast<BinaryOperator>(I)->isExact() &&
411 isPowerOf2_64(Imm)) {
413 ISDOpcode = ISD::SRA;
416 // Transform "urem x, pow2" -> "and x, pow2-1".
417 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
418 isPowerOf2_64(Imm)) {
420 ISDOpcode = ISD::AND;
423 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
424 Op0IsKill, Imm, VT.getSimpleVT());
425 if (ResultReg == 0) return false;
427 // We successfully emitted code for the given LLVM Instruction.
428 UpdateValueMap(I, ResultReg);
432 // Check if the second operand is a constant float.
433 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
434 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
435 ISDOpcode, Op0, Op0IsKill, CF);
436 if (ResultReg != 0) {
437 // We successfully emitted code for the given LLVM Instruction.
438 UpdateValueMap(I, ResultReg);
443 unsigned Op1 = getRegForValue(I->getOperand(1));
445 // Unhandled operand. Halt "fast" selection and bail.
448 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
450 // Now we have both operands in registers. Emit the instruction.
451 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
456 // Target-specific code wasn't able to find a machine opcode for
457 // the given ISD opcode and type. Halt "fast" selection and bail.
460 // We successfully emitted code for the given LLVM Instruction.
461 UpdateValueMap(I, ResultReg);
465 bool FastISel::SelectGetElementPtr(const User *I) {
466 unsigned N = getRegForValue(I->getOperand(0));
468 // Unhandled operand. Halt "fast" selection and bail.
471 bool NIsKill = hasTrivialKill(I->getOperand(0));
473 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
474 // into a single N = N + TotalOffset.
475 uint64_t TotalOffs = 0;
476 // FIXME: What's a good SWAG number for MaxOffs?
477 uint64_t MaxOffs = 2048;
478 Type *Ty = I->getOperand(0)->getType();
479 MVT VT = TLI.getPointerTy();
480 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
481 E = I->op_end(); OI != E; ++OI) {
482 const Value *Idx = *OI;
483 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
484 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
487 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
488 if (TotalOffs >= MaxOffs) {
489 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
491 // Unhandled operand. Halt "fast" selection and bail.
497 Ty = StTy->getElementType(Field);
499 Ty = cast<SequentialType>(Ty)->getElementType();
501 // If this is a constant subscript, handle it quickly.
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
503 if (CI->isZero()) continue;
506 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
507 if (TotalOffs >= MaxOffs) {
508 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
510 // Unhandled operand. Halt "fast" selection and bail.
518 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
520 // Unhandled operand. Halt "fast" selection and bail.
526 // N = N + Idx * ElementSize;
527 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
528 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
529 unsigned IdxN = Pair.first;
530 bool IdxNIsKill = Pair.second;
532 // Unhandled operand. Halt "fast" selection and bail.
535 if (ElementSize != 1) {
536 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
538 // Unhandled operand. Halt "fast" selection and bail.
542 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
544 // Unhandled operand. Halt "fast" selection and bail.
549 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
551 // Unhandled operand. Halt "fast" selection and bail.
555 // We successfully emitted code for the given LLVM Instruction.
556 UpdateValueMap(I, N);
560 bool FastISel::SelectCall(const User *I) {
561 const CallInst *Call = cast<CallInst>(I);
563 // Handle simple inline asms.
564 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
565 // Don't attempt to handle constraints.
566 if (!IA->getConstraintString().empty())
569 unsigned ExtraInfo = 0;
570 if (IA->hasSideEffects())
571 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
572 if (IA->isAlignStack())
573 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
575 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
576 TII.get(TargetOpcode::INLINEASM))
577 .addExternalSymbol(IA->getAsmString().c_str())
582 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
583 ComputeUsesVAFloatArgument(*Call, &MMI);
585 const Function *F = Call->getCalledFunction();
586 if (!F) return false;
588 // Handle selected intrinsic function calls.
589 switch (F->getIntrinsicID()) {
591 // At -O0 we don't care about the lifetime intrinsics.
592 case Intrinsic::lifetime_start:
593 case Intrinsic::lifetime_end:
594 // The donothing intrinsic does, well, nothing.
595 case Intrinsic::donothing:
598 case Intrinsic::dbg_declare: {
599 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
600 DIVariable DIVar(DI->getVariable());
601 assert((!DIVar || DIVar.isVariable()) &&
602 "Variable in DbgDeclareInst should be either null or a DIVariable.");
604 !FuncInfo.MF->getMMI().hasDebugInfo()) {
605 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
609 const Value *Address = DI->getAddress();
610 if (!Address || isa<UndefValue>(Address)) {
611 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
616 Optional<MachineOperand> Op;
617 if (const Argument *Arg = dyn_cast<Argument>(Address))
618 // Some arguments' frame index is recorded during argument lowering.
619 Offset = FuncInfo.getArgumentFrameIndex(Arg);
621 Op = MachineOperand::CreateFI(Offset);
623 if (unsigned Reg = lookUpRegForValue(Address))
624 Op = MachineOperand::CreateReg(Reg, false);
626 // If we have a VLA that has a "use" in a metadata node that's then used
627 // here but it has no other uses, then we have a problem. E.g.,
629 // int foo (const int *x) {
634 // If we assign 'a' a vreg and fast isel later on has to use the selection
635 // DAG isel, it will want to copy the value to the vreg. However, there are
636 // no uses, which goes counter to what selection DAG isel expects.
637 if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
638 (!isa<AllocaInst>(Address) ||
639 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
640 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
645 Op->setIsDebug(true);
646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
647 TII.get(TargetOpcode::DBG_VALUE),
648 /* IsIndirect */ DI->getAddress()->getType()->isPointerTy(),
649 Op->getReg(), Offset, DI->getVariable());
651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
652 TII.get(TargetOpcode::DBG_VALUE)).addOperand(*Op).addImm(0)
653 .addMetadata(DI->getVariable());
655 // We can't yet handle anything else here because it would require
656 // generating code, thus altering codegen because of debug info.
657 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
660 case Intrinsic::dbg_value: {
661 // This form of DBG_VALUE is target-independent.
662 const DbgValueInst *DI = cast<DbgValueInst>(Call);
663 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
664 const Value *V = DI->getValue();
666 // Currently the optimizer can produce this; insert an undef to
667 // help debugging. Probably the optimizer should not do this.
668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
669 .addReg(0U).addImm(DI->getOffset())
670 .addMetadata(DI->getVariable());
671 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
672 if (CI->getBitWidth() > 64)
673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
674 .addCImm(CI).addImm(DI->getOffset())
675 .addMetadata(DI->getVariable());
677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
678 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
679 .addMetadata(DI->getVariable());
680 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
682 .addFPImm(CF).addImm(DI->getOffset())
683 .addMetadata(DI->getVariable());
684 } else if (unsigned Reg = lookUpRegForValue(V)) {
685 bool IsIndirect = DI->getOffset() != 0;
686 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, IsIndirect,
687 Reg, DI->getOffset(), DI->getVariable());
689 // We can't yet handle anything else here because it would require
690 // generating code, thus altering codegen because of debug info.
691 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
695 case Intrinsic::objectsize: {
696 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
697 unsigned long long Res = CI->isZero() ? -1ULL : 0;
698 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
699 unsigned ResultReg = getRegForValue(ResCI);
702 UpdateValueMap(Call, ResultReg);
705 case Intrinsic::expect: {
706 unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
709 UpdateValueMap(Call, ResultReg);
714 // Usually, it does not make sense to initialize a value,
715 // make an unrelated function call and use the value, because
716 // it tends to be spilled on the stack. So, we move the pointer
717 // to the last local value to the beginning of the block, so that
718 // all the values which have already been materialized,
719 // appear after the call. It also makes sense to skip intrinsics
720 // since they tend to be inlined.
721 if (!isa<IntrinsicInst>(Call))
722 flushLocalValueMap();
724 // An arbitrary call. Bail.
728 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
729 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
730 EVT DstVT = TLI.getValueType(I->getType());
732 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
733 DstVT == MVT::Other || !DstVT.isSimple())
734 // Unhandled type. Halt "fast" selection and bail.
737 // Check if the destination type is legal.
738 if (!TLI.isTypeLegal(DstVT))
741 // Check if the source operand is legal.
742 if (!TLI.isTypeLegal(SrcVT))
745 unsigned InputReg = getRegForValue(I->getOperand(0));
747 // Unhandled operand. Halt "fast" selection and bail.
750 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
752 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
755 InputReg, InputRegIsKill);
759 UpdateValueMap(I, ResultReg);
763 bool FastISel::SelectBitCast(const User *I) {
764 // If the bitcast doesn't change the type, just use the operand value.
765 if (I->getType() == I->getOperand(0)->getType()) {
766 unsigned Reg = getRegForValue(I->getOperand(0));
769 UpdateValueMap(I, Reg);
773 // Bitcasts of other values become reg-reg copies or BITCAST operators.
774 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
775 EVT DstEVT = TLI.getValueType(I->getType());
776 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
777 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
778 // Unhandled type. Halt "fast" selection and bail.
781 MVT SrcVT = SrcEVT.getSimpleVT();
782 MVT DstVT = DstEVT.getSimpleVT();
783 unsigned Op0 = getRegForValue(I->getOperand(0));
785 // Unhandled operand. Halt "fast" selection and bail.
788 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
790 // First, try to perform the bitcast by inserting a reg-reg copy.
791 unsigned ResultReg = 0;
792 if (SrcVT == DstVT) {
793 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
794 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
795 // Don't attempt a cross-class copy. It will likely fail.
796 if (SrcClass == DstClass) {
797 ResultReg = createResultReg(DstClass);
798 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
799 ResultReg).addReg(Op0);
803 // If the reg-reg copy failed, select a BITCAST opcode.
805 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
810 UpdateValueMap(I, ResultReg);
815 FastISel::SelectInstruction(const Instruction *I) {
816 // Just before the terminator instruction, insert instructions to
817 // feed PHI nodes in successor blocks.
818 if (isa<TerminatorInst>(I))
819 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
822 DL = I->getDebugLoc();
824 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
826 // As a special case, don't handle calls to builtin library functions that
827 // may be translated directly to target instructions.
828 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
829 const Function *F = Call->getCalledFunction();
831 if (F && !F->hasLocalLinkage() && F->hasName() &&
832 LibInfo->getLibFunc(F->getName(), Func) &&
833 LibInfo->hasOptimizedCodeGen(Func))
837 // First, try doing target-independent selection.
838 if (SelectOperator(I, I->getOpcode())) {
839 ++NumFastIselSuccessIndependent;
843 // Remove dead code. However, ignore call instructions since we've flushed
844 // the local value map and recomputed the insert point.
845 if (!isa<CallInst>(I)) {
847 if (SavedInsertPt != FuncInfo.InsertPt)
848 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
851 // Next, try calling the target to attempt to handle the instruction.
852 SavedInsertPt = FuncInfo.InsertPt;
853 if (TargetSelectInstruction(I)) {
854 ++NumFastIselSuccessTarget;
858 // Check for dead code and remove as necessary.
860 if (SavedInsertPt != FuncInfo.InsertPt)
861 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
867 /// FastEmitBranch - Emit an unconditional branch to the given block,
868 /// unless it is the immediate (fall-through) successor, and update
871 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
873 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
874 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
875 // For more accurate line information if this is the only instruction
876 // in the block then emit it, otherwise we have the unconditional
877 // fall-through case, which needs no instructions.
879 // The unconditional branch case.
880 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
881 SmallVector<MachineOperand, 0>(), DL);
883 FuncInfo.MBB->addSuccessor(MSucc);
886 /// SelectFNeg - Emit an FNeg operation.
889 FastISel::SelectFNeg(const User *I) {
890 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
891 if (OpReg == 0) return false;
893 bool OpRegIsKill = hasTrivialKill(I);
895 // If the target has ISD::FNEG, use it.
896 EVT VT = TLI.getValueType(I->getType());
897 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
898 ISD::FNEG, OpReg, OpRegIsKill);
899 if (ResultReg != 0) {
900 UpdateValueMap(I, ResultReg);
904 // Bitcast the value to integer, twiddle the sign bit with xor,
905 // and then bitcast it back to floating-point.
906 if (VT.getSizeInBits() > 64) return false;
907 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
908 if (!TLI.isTypeLegal(IntVT))
911 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
912 ISD::BITCAST, OpReg, OpRegIsKill);
916 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
917 IntReg, /*Kill=*/true,
918 UINT64_C(1) << (VT.getSizeInBits()-1),
919 IntVT.getSimpleVT());
920 if (IntResultReg == 0)
923 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
924 ISD::BITCAST, IntResultReg, /*Kill=*/true);
928 UpdateValueMap(I, ResultReg);
933 FastISel::SelectExtractValue(const User *U) {
934 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
938 // Make sure we only try to handle extracts with a legal result. But also
939 // allow i1 because it's easy.
940 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
941 if (!RealVT.isSimple())
943 MVT VT = RealVT.getSimpleVT();
944 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
947 const Value *Op0 = EVI->getOperand(0);
948 Type *AggTy = Op0->getType();
950 // Get the base result register.
952 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
953 if (I != FuncInfo.ValueMap.end())
954 ResultReg = I->second;
955 else if (isa<Instruction>(Op0))
956 ResultReg = FuncInfo.InitializeRegForValue(Op0);
958 return false; // fast-isel can't handle aggregate constants at the moment
960 // Get the actual result register, which is an offset from the base register.
961 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
963 SmallVector<EVT, 4> AggValueVTs;
964 ComputeValueVTs(TLI, AggTy, AggValueVTs);
966 for (unsigned i = 0; i < VTIndex; i++)
967 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
969 UpdateValueMap(EVI, ResultReg);
974 FastISel::SelectOperator(const User *I, unsigned Opcode) {
976 case Instruction::Add:
977 return SelectBinaryOp(I, ISD::ADD);
978 case Instruction::FAdd:
979 return SelectBinaryOp(I, ISD::FADD);
980 case Instruction::Sub:
981 return SelectBinaryOp(I, ISD::SUB);
982 case Instruction::FSub:
983 // FNeg is currently represented in LLVM IR as a special case of FSub.
984 if (BinaryOperator::isFNeg(I))
985 return SelectFNeg(I);
986 return SelectBinaryOp(I, ISD::FSUB);
987 case Instruction::Mul:
988 return SelectBinaryOp(I, ISD::MUL);
989 case Instruction::FMul:
990 return SelectBinaryOp(I, ISD::FMUL);
991 case Instruction::SDiv:
992 return SelectBinaryOp(I, ISD::SDIV);
993 case Instruction::UDiv:
994 return SelectBinaryOp(I, ISD::UDIV);
995 case Instruction::FDiv:
996 return SelectBinaryOp(I, ISD::FDIV);
997 case Instruction::SRem:
998 return SelectBinaryOp(I, ISD::SREM);
999 case Instruction::URem:
1000 return SelectBinaryOp(I, ISD::UREM);
1001 case Instruction::FRem:
1002 return SelectBinaryOp(I, ISD::FREM);
1003 case Instruction::Shl:
1004 return SelectBinaryOp(I, ISD::SHL);
1005 case Instruction::LShr:
1006 return SelectBinaryOp(I, ISD::SRL);
1007 case Instruction::AShr:
1008 return SelectBinaryOp(I, ISD::SRA);
1009 case Instruction::And:
1010 return SelectBinaryOp(I, ISD::AND);
1011 case Instruction::Or:
1012 return SelectBinaryOp(I, ISD::OR);
1013 case Instruction::Xor:
1014 return SelectBinaryOp(I, ISD::XOR);
1016 case Instruction::GetElementPtr:
1017 return SelectGetElementPtr(I);
1019 case Instruction::Br: {
1020 const BranchInst *BI = cast<BranchInst>(I);
1022 if (BI->isUnconditional()) {
1023 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1024 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1025 FastEmitBranch(MSucc, BI->getDebugLoc());
1029 // Conditional branches are not handed yet.
1030 // Halt "fast" selection and bail.
1034 case Instruction::Unreachable:
1038 case Instruction::Alloca:
1039 // FunctionLowering has the static-sized case covered.
1040 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1043 // Dynamic-sized alloca is not handled yet.
1046 case Instruction::Call:
1047 return SelectCall(I);
1049 case Instruction::BitCast:
1050 return SelectBitCast(I);
1052 case Instruction::FPToSI:
1053 return SelectCast(I, ISD::FP_TO_SINT);
1054 case Instruction::ZExt:
1055 return SelectCast(I, ISD::ZERO_EXTEND);
1056 case Instruction::SExt:
1057 return SelectCast(I, ISD::SIGN_EXTEND);
1058 case Instruction::Trunc:
1059 return SelectCast(I, ISD::TRUNCATE);
1060 case Instruction::SIToFP:
1061 return SelectCast(I, ISD::SINT_TO_FP);
1063 case Instruction::IntToPtr: // Deliberate fall-through.
1064 case Instruction::PtrToInt: {
1065 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1066 EVT DstVT = TLI.getValueType(I->getType());
1067 if (DstVT.bitsGT(SrcVT))
1068 return SelectCast(I, ISD::ZERO_EXTEND);
1069 if (DstVT.bitsLT(SrcVT))
1070 return SelectCast(I, ISD::TRUNCATE);
1071 unsigned Reg = getRegForValue(I->getOperand(0));
1072 if (Reg == 0) return false;
1073 UpdateValueMap(I, Reg);
1077 case Instruction::ExtractValue:
1078 return SelectExtractValue(I);
1080 case Instruction::PHI:
1081 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1084 // Unhandled instruction. Halt "fast" selection and bail.
1089 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1090 const TargetLibraryInfo *libInfo)
1091 : FuncInfo(funcInfo),
1092 MRI(FuncInfo.MF->getRegInfo()),
1093 MFI(*FuncInfo.MF->getFrameInfo()),
1094 MCP(*FuncInfo.MF->getConstantPool()),
1095 TM(FuncInfo.MF->getTarget()),
1096 TD(*TM.getDataLayout()),
1097 TII(*TM.getInstrInfo()),
1098 TLI(*TM.getTargetLowering()),
1099 TRI(*TM.getRegisterInfo()),
1103 FastISel::~FastISel() {}
1105 bool FastISel::FastLowerArguments() {
1109 unsigned FastISel::FastEmit_(MVT, MVT,
1114 unsigned FastISel::FastEmit_r(MVT, MVT,
1116 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1120 unsigned FastISel::FastEmit_rr(MVT, MVT,
1122 unsigned /*Op0*/, bool /*Op0IsKill*/,
1123 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1127 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1131 unsigned FastISel::FastEmit_f(MVT, MVT,
1132 unsigned, const ConstantFP * /*FPImm*/) {
1136 unsigned FastISel::FastEmit_ri(MVT, MVT,
1138 unsigned /*Op0*/, bool /*Op0IsKill*/,
1143 unsigned FastISel::FastEmit_rf(MVT, MVT,
1145 unsigned /*Op0*/, bool /*Op0IsKill*/,
1146 const ConstantFP * /*FPImm*/) {
1150 unsigned FastISel::FastEmit_rri(MVT, MVT,
1152 unsigned /*Op0*/, bool /*Op0IsKill*/,
1153 unsigned /*Op1*/, bool /*Op1IsKill*/,
1158 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1159 /// to emit an instruction with an immediate operand using FastEmit_ri.
1160 /// If that fails, it materializes the immediate into a register and try
1161 /// FastEmit_rr instead.
1162 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1163 unsigned Op0, bool Op0IsKill,
1164 uint64_t Imm, MVT ImmType) {
1165 // If this is a multiply by a power of two, emit this as a shift left.
1166 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1169 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1170 // div x, 8 -> srl x, 3
1175 // Horrible hack (to be removed), check to make sure shift amounts are
1177 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1178 Imm >= VT.getSizeInBits())
1181 // First check if immediate type is legal. If not, we can't use the ri form.
1182 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1185 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1186 if (MaterialReg == 0) {
1187 // This is a bit ugly/slow, but failing here means falling out of
1188 // fast-isel, which would be very slow.
1189 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1190 VT.getSizeInBits());
1191 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1192 assert (MaterialReg != 0 && "Unable to materialize imm.");
1193 if (MaterialReg == 0) return 0;
1195 return FastEmit_rr(VT, VT, Opcode,
1197 MaterialReg, /*Kill=*/true);
1200 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1201 return MRI.createVirtualRegister(RC);
1204 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1205 const TargetRegisterClass* RC) {
1206 unsigned ResultReg = createResultReg(RC);
1207 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1209 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1213 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1214 const TargetRegisterClass *RC,
1215 unsigned Op0, bool Op0IsKill) {
1216 unsigned ResultReg = createResultReg(RC);
1217 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1219 if (II.getNumDefs() >= 1)
1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1221 .addReg(Op0, Op0IsKill * RegState::Kill);
1223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1224 .addReg(Op0, Op0IsKill * RegState::Kill);
1225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1226 ResultReg).addReg(II.ImplicitDefs[0]);
1232 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1233 const TargetRegisterClass *RC,
1234 unsigned Op0, bool Op0IsKill,
1235 unsigned Op1, bool Op1IsKill) {
1236 unsigned ResultReg = createResultReg(RC);
1237 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1239 if (II.getNumDefs() >= 1)
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1241 .addReg(Op0, Op0IsKill * RegState::Kill)
1242 .addReg(Op1, Op1IsKill * RegState::Kill);
1244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1245 .addReg(Op0, Op0IsKill * RegState::Kill)
1246 .addReg(Op1, Op1IsKill * RegState::Kill);
1247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1248 ResultReg).addReg(II.ImplicitDefs[0]);
1253 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1254 const TargetRegisterClass *RC,
1255 unsigned Op0, bool Op0IsKill,
1256 unsigned Op1, bool Op1IsKill,
1257 unsigned Op2, bool Op2IsKill) {
1258 unsigned ResultReg = createResultReg(RC);
1259 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1261 if (II.getNumDefs() >= 1)
1262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1263 .addReg(Op0, Op0IsKill * RegState::Kill)
1264 .addReg(Op1, Op1IsKill * RegState::Kill)
1265 .addReg(Op2, Op2IsKill * RegState::Kill);
1267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1268 .addReg(Op0, Op0IsKill * RegState::Kill)
1269 .addReg(Op1, Op1IsKill * RegState::Kill)
1270 .addReg(Op2, Op2IsKill * RegState::Kill);
1271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1272 ResultReg).addReg(II.ImplicitDefs[0]);
1277 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1278 const TargetRegisterClass *RC,
1279 unsigned Op0, bool Op0IsKill,
1281 unsigned ResultReg = createResultReg(RC);
1282 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1284 if (II.getNumDefs() >= 1)
1285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1286 .addReg(Op0, Op0IsKill * RegState::Kill)
1289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1290 .addReg(Op0, Op0IsKill * RegState::Kill)
1292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1293 ResultReg).addReg(II.ImplicitDefs[0]);
1298 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1299 const TargetRegisterClass *RC,
1300 unsigned Op0, bool Op0IsKill,
1301 uint64_t Imm1, uint64_t Imm2) {
1302 unsigned ResultReg = createResultReg(RC);
1303 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1305 if (II.getNumDefs() >= 1)
1306 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1307 .addReg(Op0, Op0IsKill * RegState::Kill)
1311 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1312 .addReg(Op0, Op0IsKill * RegState::Kill)
1315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1316 ResultReg).addReg(II.ImplicitDefs[0]);
1321 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1322 const TargetRegisterClass *RC,
1323 unsigned Op0, bool Op0IsKill,
1324 const ConstantFP *FPImm) {
1325 unsigned ResultReg = createResultReg(RC);
1326 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1328 if (II.getNumDefs() >= 1)
1329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1330 .addReg(Op0, Op0IsKill * RegState::Kill)
1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1334 .addReg(Op0, Op0IsKill * RegState::Kill)
1336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1337 ResultReg).addReg(II.ImplicitDefs[0]);
1342 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1343 const TargetRegisterClass *RC,
1344 unsigned Op0, bool Op0IsKill,
1345 unsigned Op1, bool Op1IsKill,
1347 unsigned ResultReg = createResultReg(RC);
1348 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1350 if (II.getNumDefs() >= 1)
1351 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1352 .addReg(Op0, Op0IsKill * RegState::Kill)
1353 .addReg(Op1, Op1IsKill * RegState::Kill)
1356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1357 .addReg(Op0, Op0IsKill * RegState::Kill)
1358 .addReg(Op1, Op1IsKill * RegState::Kill)
1360 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1361 ResultReg).addReg(II.ImplicitDefs[0]);
1366 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1367 const TargetRegisterClass *RC,
1368 unsigned Op0, bool Op0IsKill,
1369 unsigned Op1, bool Op1IsKill,
1370 uint64_t Imm1, uint64_t Imm2) {
1371 unsigned ResultReg = createResultReg(RC);
1372 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1374 if (II.getNumDefs() >= 1)
1375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1376 .addReg(Op0, Op0IsKill * RegState::Kill)
1377 .addReg(Op1, Op1IsKill * RegState::Kill)
1378 .addImm(Imm1).addImm(Imm2);
1380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1381 .addReg(Op0, Op0IsKill * RegState::Kill)
1382 .addReg(Op1, Op1IsKill * RegState::Kill)
1383 .addImm(Imm1).addImm(Imm2);
1384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1385 ResultReg).addReg(II.ImplicitDefs[0]);
1390 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1391 const TargetRegisterClass *RC,
1393 unsigned ResultReg = createResultReg(RC);
1394 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1396 if (II.getNumDefs() >= 1)
1397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1401 ResultReg).addReg(II.ImplicitDefs[0]);
1406 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1407 const TargetRegisterClass *RC,
1408 uint64_t Imm1, uint64_t Imm2) {
1409 unsigned ResultReg = createResultReg(RC);
1410 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1412 if (II.getNumDefs() >= 1)
1413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1414 .addImm(Imm1).addImm(Imm2);
1416 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1418 ResultReg).addReg(II.ImplicitDefs[0]);
1423 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1424 unsigned Op0, bool Op0IsKill,
1426 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1427 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1428 "Cannot yet extract from physregs");
1429 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1430 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1432 DL, TII.get(TargetOpcode::COPY), ResultReg)
1433 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1437 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1438 /// with all but the least significant bit set to zero.
1439 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1440 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1443 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1444 /// Emit code to ensure constants are copied into registers when needed.
1445 /// Remember the virtual registers that need to be added to the Machine PHI
1446 /// nodes as input. We cannot just directly add them, because expansion
1447 /// might result in multiple MBB's for one BB. As such, the start of the
1448 /// BB might correspond to a different MBB than the end.
1449 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1450 const TerminatorInst *TI = LLVMBB->getTerminator();
1452 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1453 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1455 // Check successor nodes' PHI nodes that expect a constant to be available
1457 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1458 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1459 if (!isa<PHINode>(SuccBB->begin())) continue;
1460 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1462 // If this terminator has multiple identical successors (common for
1463 // switches), only handle each succ once.
1464 if (!SuccsHandled.insert(SuccMBB)) continue;
1466 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1468 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1469 // nodes and Machine PHI nodes, but the incoming operands have not been
1471 for (BasicBlock::const_iterator I = SuccBB->begin();
1472 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1474 // Ignore dead phi's.
1475 if (PN->use_empty()) continue;
1477 // Only handle legal types. Two interesting things to note here. First,
1478 // by bailing out early, we may leave behind some dead instructions,
1479 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1480 // own moves. Second, this check is necessary because FastISel doesn't
1481 // use CreateRegs to create registers, so it always creates
1482 // exactly one register for each non-void instruction.
1483 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1484 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1485 // Handle integer promotions, though, because they're common and easy.
1486 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1487 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1489 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1494 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1496 // Set the DebugLoc for the copy. Prefer the location of the operand
1497 // if there is one; use the location of the PHI otherwise.
1498 DL = PN->getDebugLoc();
1499 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1500 DL = Inst->getDebugLoc();
1502 unsigned Reg = getRegForValue(PHIOp);
1504 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1507 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1515 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
1516 assert(LI->hasOneUse() &&
1517 "tryToFoldLoad expected a LoadInst with a single use");
1518 // We know that the load has a single use, but don't know what it is. If it
1519 // isn't one of the folded instructions, then we can't succeed here. Handle
1520 // this by scanning the single-use users of the load until we get to FoldInst.
1521 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
1523 const Instruction *TheUser = LI->use_back();
1524 while (TheUser != FoldInst && // Scan up until we find FoldInst.
1525 // Stay in the right block.
1526 TheUser->getParent() == FoldInst->getParent() &&
1527 --MaxUsers) { // Don't scan too far.
1528 // If there are multiple or no uses of this instruction, then bail out.
1529 if (!TheUser->hasOneUse())
1532 TheUser = TheUser->use_back();
1535 // If we didn't find the fold instruction, then we failed to collapse the
1537 if (TheUser != FoldInst)
1540 // Don't try to fold volatile loads. Target has to deal with alignment
1542 if (LI->isVolatile())
1545 // Figure out which vreg this is going into. If there is no assigned vreg yet
1546 // then there actually was no reference to it. Perhaps the load is referenced
1547 // by a dead instruction.
1548 unsigned LoadReg = getRegForValue(LI);
1552 // We can't fold if this vreg has no uses or more than one use. Multiple uses
1553 // may mean that the instruction got lowered to multiple MIs, or the use of
1554 // the loaded value ended up being multiple operands of the result.
1555 if (!MRI.hasOneUse(LoadReg))
1558 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
1559 MachineInstr *User = &*RI;
1561 // Set the insertion point properly. Folding the load can cause generation of
1562 // other random instructions (like sign extends) for addressing modes; make
1563 // sure they get inserted in a logical place before the new instruction.
1564 FuncInfo.InsertPt = User;
1565 FuncInfo.MBB = User->getParent();
1567 // Ask the target to try folding the load.
1568 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);