1 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the implementation of the FastISel class.
12 // "Fast" instruction selection is designed to emit very poor code quickly.
13 // Also, it is not designed to be able to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations are not supported. It is
15 // also not intended to be able to do much optimization, except in a few cases
16 // where doing optimizations reduces overall compile time. For example, folding
17 // constants into immediate fields is often done, because it's cheap and it
18 // reduces the number of instructions later phases have to examine.
20 // "Fast" instruction selection is able to fail gracefully and transfer
21 // control to the SelectionDAG selector for operations that it doesn't
22 // support. In many cases, this allows us to avoid duplicating a lot of
23 // the complicated lowering logic that SelectionDAG currently has.
25 // The intended use for "fast" instruction selection is "-O0" mode
26 // compilation, where the quality of the generated code is irrelevant when
27 // weighed against the speed at which the code can be generated. Also,
28 // at -O0, the LLVM optimizers are not running, and this makes the
29 // compile time of codegen a much higher portion of the overall compile
30 // time. Despite its limitations, "fast" instruction selection is able to
31 // handle enough code on its own to provide noticeable overall speedups
34 // Basic operations are supported in a target-independent way, by reading
35 // the same instruction descriptions that the SelectionDAG selector reads,
36 // and identifying simple arithmetic operations that can be directly selected
37 // from simple operators. More complicated operations currently require
38 // target-specific code.
40 //===----------------------------------------------------------------------===//
42 #define DEBUG_TYPE "isel"
43 #include "llvm/CodeGen/FastISel.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Analysis/Loads.h"
46 #include "llvm/CodeGen/Analysis.h"
47 #include "llvm/CodeGen/FunctionLoweringInfo.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/DebugInfo.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetLibraryInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
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");
74 /// startNewBlock - Set the current block to which generated machine
75 /// instructions will be appended, and clear the local CSE map.
77 void FastISel::startNewBlock() {
78 LocalValueMap.clear();
82 // Advance the emit start point past any EH_LABEL instructions.
83 MachineBasicBlock::iterator
84 I = FuncInfo.MBB->begin(), E = FuncInfo.MBB->end();
85 while (I != E && I->getOpcode() == TargetOpcode::EH_LABEL) {
89 LastLocalValue = EmitStartPt;
92 bool FastISel::LowerArguments() {
93 if (!FuncInfo.CanLowerReturn)
94 // Fallback to SDISel argument lowering code to deal with sret pointer
98 if (!FastLowerArguments())
101 // Enter non-dead arguments into ValueMap for uses in non-entry BBs.
102 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
103 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
104 if (!I->use_empty()) {
105 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
106 assert(VI != LocalValueMap.end() && "Missed an argument?");
107 FuncInfo.ValueMap[I] = VI->second;
113 void FastISel::flushLocalValueMap() {
114 LocalValueMap.clear();
115 LastLocalValue = EmitStartPt;
119 bool FastISel::hasTrivialKill(const Value *V) const {
120 // Don't consider constants or arguments to have trivial kills.
121 const Instruction *I = dyn_cast<Instruction>(V);
125 // No-op casts are trivially coalesced by fast-isel.
126 if (const CastInst *Cast = dyn_cast<CastInst>(I))
127 if (Cast->isNoopCast(TD.getIntPtrType(Cast->getContext())) &&
128 !hasTrivialKill(Cast->getOperand(0)))
131 // GEPs with all zero indices are trivially coalesced by fast-isel.
132 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
133 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
136 // Only instructions with a single use in the same basic block are considered
137 // to have trivial kills.
138 return I->hasOneUse() &&
139 !(I->getOpcode() == Instruction::BitCast ||
140 I->getOpcode() == Instruction::PtrToInt ||
141 I->getOpcode() == Instruction::IntToPtr) &&
142 cast<Instruction>(*I->use_begin())->getParent() == I->getParent();
145 unsigned FastISel::getRegForValue(const Value *V) {
146 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
147 // Don't handle non-simple values in FastISel.
148 if (!RealVT.isSimple())
151 // Ignore illegal types. We must do this before looking up the value
152 // in ValueMap because Arguments are given virtual registers regardless
153 // of whether FastISel can handle them.
154 MVT VT = RealVT.getSimpleVT();
155 if (!TLI.isTypeLegal(VT)) {
156 // Handle integer promotions, though, because they're common and easy.
157 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
158 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
163 // Look up the value to see if we already have a register for it.
164 unsigned Reg = lookUpRegForValue(V);
168 // In bottom-up mode, just create the virtual register which will be used
169 // to hold the value. It will be materialized later.
170 if (isa<Instruction>(V) &&
171 (!isa<AllocaInst>(V) ||
172 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
173 return FuncInfo.InitializeRegForValue(V);
175 SavePoint SaveInsertPt = enterLocalValueArea();
177 // Materialize the value in a register. Emit any instructions in the
179 Reg = materializeRegForValue(V, VT);
181 leaveLocalValueArea(SaveInsertPt);
186 /// materializeRegForValue - Helper for getRegForValue. This function is
187 /// called when the value isn't already available in a register and must
188 /// be materialized with new instructions.
189 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
192 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
193 if (CI->getValue().getActiveBits() <= 64)
194 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
195 } else if (isa<AllocaInst>(V)) {
196 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
197 } else if (isa<ConstantPointerNull>(V)) {
198 // Translate this as an integer zero so that it can be
199 // local-CSE'd with actual integer zeros.
201 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext())));
202 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
203 if (CF->isNullValue()) {
204 Reg = TargetMaterializeFloatZero(CF);
206 // Try to emit the constant directly.
207 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
211 // Try to emit the constant by using an integer constant with a cast.
212 const APFloat &Flt = CF->getValueAPF();
213 EVT IntVT = TLI.getPointerTy();
216 uint32_t IntBitWidth = IntVT.getSizeInBits();
218 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
219 APFloat::rmTowardZero, &isExact);
221 APInt IntVal(IntBitWidth, x);
223 unsigned IntegerReg =
224 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
226 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
227 IntegerReg, /*Kill=*/false);
230 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
231 if (!SelectOperator(Op, Op->getOpcode()))
232 if (!isa<Instruction>(Op) ||
233 !TargetSelectInstruction(cast<Instruction>(Op)))
235 Reg = lookUpRegForValue(Op);
236 } else if (isa<UndefValue>(V)) {
237 Reg = createResultReg(TLI.getRegClassFor(VT));
238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
239 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
242 // If target-independent code couldn't handle the value, give target-specific
244 if (!Reg && isa<Constant>(V))
245 Reg = TargetMaterializeConstant(cast<Constant>(V));
247 // Don't cache constant materializations in the general ValueMap.
248 // To do so would require tracking what uses they dominate.
250 LocalValueMap[V] = Reg;
251 LastLocalValue = MRI.getVRegDef(Reg);
256 unsigned FastISel::lookUpRegForValue(const Value *V) {
257 // Look up the value to see if we already have a register for it. We
258 // cache values defined by Instructions across blocks, and other values
259 // only locally. This is because Instructions already have the SSA
260 // def-dominates-use requirement enforced.
261 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
262 if (I != FuncInfo.ValueMap.end())
264 return LocalValueMap[V];
267 /// UpdateValueMap - Update the value map to include the new mapping for this
268 /// instruction, or insert an extra copy to get the result in a previous
269 /// determined register.
270 /// NOTE: This is only necessary because we might select a block that uses
271 /// a value before we select the block that defines the value. It might be
272 /// possible to fix this by selecting blocks in reverse postorder.
273 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
274 if (!isa<Instruction>(I)) {
275 LocalValueMap[I] = Reg;
279 unsigned &AssignedReg = FuncInfo.ValueMap[I];
280 if (AssignedReg == 0)
281 // Use the new register.
283 else if (Reg != AssignedReg) {
284 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
285 for (unsigned i = 0; i < NumRegs; i++)
286 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
292 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
293 unsigned IdxN = getRegForValue(Idx);
295 // Unhandled operand. Halt "fast" selection and bail.
296 return std::pair<unsigned, bool>(0, false);
298 bool IdxNIsKill = hasTrivialKill(Idx);
300 // If the index is smaller or larger than intptr_t, truncate or extend it.
301 MVT PtrVT = TLI.getPointerTy();
302 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
303 if (IdxVT.bitsLT(PtrVT)) {
304 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
308 else if (IdxVT.bitsGT(PtrVT)) {
309 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
313 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
316 void FastISel::recomputeInsertPt() {
317 if (getLastLocalValue()) {
318 FuncInfo.InsertPt = getLastLocalValue();
319 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
322 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
324 // Now skip past any EH_LABELs, which must remain at the beginning.
325 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
326 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
330 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
331 MachineBasicBlock::iterator E) {
332 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
334 MachineInstr *Dead = &*I;
336 Dead->eraseFromParent();
337 DEBUG(++NumFastIselDead);
342 FastISel::SavePoint FastISel::enterLocalValueArea() {
343 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
347 SavePoint SP = { OldInsertPt, OldDL };
351 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
352 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
353 LastLocalValue = llvm::prior(FuncInfo.InsertPt);
355 // Restore the previous insert position.
356 FuncInfo.InsertPt = OldInsertPt.InsertPt;
360 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
361 /// which has an opcode which directly corresponds to the given ISD opcode.
363 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
364 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
365 if (VT == MVT::Other || !VT.isSimple())
366 // Unhandled type. Halt "fast" selection and bail.
369 // We only handle legal types. For example, on x86-32 the instruction
370 // selector contains all of the 64-bit instructions from x86-64,
371 // under the assumption that i64 won't be used if the target doesn't
373 if (!TLI.isTypeLegal(VT)) {
374 // MVT::i1 is special. Allow AND, OR, or XOR because they
375 // don't require additional zeroing, which makes them easy.
377 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
378 ISDOpcode == ISD::XOR))
379 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
384 // Check if the first operand is a constant, and handle it as "ri". At -O0,
385 // we don't have anything that canonicalizes operand order.
386 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
387 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
388 unsigned Op1 = getRegForValue(I->getOperand(1));
389 if (Op1 == 0) return false;
391 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
393 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
394 Op1IsKill, CI->getZExtValue(),
396 if (ResultReg == 0) return false;
398 // We successfully emitted code for the given LLVM Instruction.
399 UpdateValueMap(I, ResultReg);
404 unsigned Op0 = getRegForValue(I->getOperand(0));
405 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
408 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
410 // Check if the second operand is a constant and handle it appropriately.
411 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
412 uint64_t Imm = CI->getZExtValue();
414 // Transform "sdiv exact X, 8" -> "sra X, 3".
415 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
416 cast<BinaryOperator>(I)->isExact() &&
417 isPowerOf2_64(Imm)) {
419 ISDOpcode = ISD::SRA;
422 // Transform "urem x, pow2" -> "and x, pow2-1".
423 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
424 isPowerOf2_64(Imm)) {
426 ISDOpcode = ISD::AND;
429 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
430 Op0IsKill, Imm, VT.getSimpleVT());
431 if (ResultReg == 0) return false;
433 // We successfully emitted code for the given LLVM Instruction.
434 UpdateValueMap(I, ResultReg);
438 // Check if the second operand is a constant float.
439 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
440 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
441 ISDOpcode, Op0, Op0IsKill, CF);
442 if (ResultReg != 0) {
443 // We successfully emitted code for the given LLVM Instruction.
444 UpdateValueMap(I, ResultReg);
449 unsigned Op1 = getRegForValue(I->getOperand(1));
451 // Unhandled operand. Halt "fast" selection and bail.
454 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
456 // Now we have both operands in registers. Emit the instruction.
457 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
462 // Target-specific code wasn't able to find a machine opcode for
463 // the given ISD opcode and type. Halt "fast" selection and bail.
466 // We successfully emitted code for the given LLVM Instruction.
467 UpdateValueMap(I, ResultReg);
471 bool FastISel::SelectGetElementPtr(const User *I) {
472 unsigned N = getRegForValue(I->getOperand(0));
474 // Unhandled operand. Halt "fast" selection and bail.
477 bool NIsKill = hasTrivialKill(I->getOperand(0));
479 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
480 // into a single N = N + TotalOffset.
481 uint64_t TotalOffs = 0;
482 // FIXME: What's a good SWAG number for MaxOffs?
483 uint64_t MaxOffs = 2048;
484 Type *Ty = I->getOperand(0)->getType();
485 MVT VT = TLI.getPointerTy();
486 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
487 E = I->op_end(); OI != E; ++OI) {
488 const Value *Idx = *OI;
489 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
490 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
493 TotalOffs += TD.getStructLayout(StTy)->getElementOffset(Field);
494 if (TotalOffs >= MaxOffs) {
495 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
497 // Unhandled operand. Halt "fast" selection and bail.
503 Ty = StTy->getElementType(Field);
505 Ty = cast<SequentialType>(Ty)->getElementType();
507 // If this is a constant subscript, handle it quickly.
508 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
509 if (CI->isZero()) continue;
512 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
513 if (TotalOffs >= MaxOffs) {
514 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
516 // Unhandled operand. Halt "fast" selection and bail.
524 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
526 // Unhandled operand. Halt "fast" selection and bail.
532 // N = N + Idx * ElementSize;
533 uint64_t ElementSize = TD.getTypeAllocSize(Ty);
534 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
535 unsigned IdxN = Pair.first;
536 bool IdxNIsKill = Pair.second;
538 // Unhandled operand. Halt "fast" selection and bail.
541 if (ElementSize != 1) {
542 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
544 // Unhandled operand. Halt "fast" selection and bail.
548 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
550 // Unhandled operand. Halt "fast" selection and bail.
555 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
557 // Unhandled operand. Halt "fast" selection and bail.
561 // We successfully emitted code for the given LLVM Instruction.
562 UpdateValueMap(I, N);
566 bool FastISel::SelectCall(const User *I) {
567 const CallInst *Call = cast<CallInst>(I);
569 // Handle simple inline asms.
570 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
571 // Don't attempt to handle constraints.
572 if (!IA->getConstraintString().empty())
575 unsigned ExtraInfo = 0;
576 if (IA->hasSideEffects())
577 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
578 if (IA->isAlignStack())
579 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
581 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
582 TII.get(TargetOpcode::INLINEASM))
583 .addExternalSymbol(IA->getAsmString().c_str())
588 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
589 ComputeUsesVAFloatArgument(*Call, &MMI);
591 const Function *F = Call->getCalledFunction();
592 if (!F) return false;
594 // Handle selected intrinsic function calls.
595 switch (F->getIntrinsicID()) {
597 // At -O0 we don't care about the lifetime intrinsics.
598 case Intrinsic::lifetime_start:
599 case Intrinsic::lifetime_end:
600 // The donothing intrinsic does, well, nothing.
601 case Intrinsic::donothing:
604 case Intrinsic::dbg_declare: {
605 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
606 if (!DIVariable(DI->getVariable()).Verify() ||
607 !FuncInfo.MF->getMMI().hasDebugInfo()) {
608 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
612 const Value *Address = DI->getAddress();
613 if (!Address || isa<UndefValue>(Address)) {
614 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
620 if (const Argument *Arg = dyn_cast<Argument>(Address)) {
621 // Some arguments' frame index is recorded during argument lowering.
622 Offset = FuncInfo.getArgumentFrameIndex(Arg);
624 Reg = TRI.getFrameRegister(*FuncInfo.MF);
627 Reg = lookUpRegForValue(Address);
629 // If we have a VLA that has a "use" in a metadata node that's then used
630 // here but it has no other uses, then we have a problem. E.g.,
632 // int foo (const int *x) {
637 // If we assign 'a' a vreg and fast isel later on has to use the selection
638 // DAG isel, it will want to copy the value to the vreg. However, there are
639 // no uses, which goes counter to what selection DAG isel expects.
640 if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
641 (!isa<AllocaInst>(Address) ||
642 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
643 Reg = FuncInfo.InitializeRegForValue(Address);
646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
647 TII.get(TargetOpcode::DBG_VALUE))
648 .addReg(Reg, RegState::Debug).addImm(Offset)
649 .addMetadata(DI->getVariable());
651 // We can't yet handle anything else here because it would require
652 // generating code, thus altering codegen because of debug info.
653 DEBUG(dbgs() << "Dropping debug info for " << DI);
656 case Intrinsic::dbg_value: {
657 // This form of DBG_VALUE is target-independent.
658 const DbgValueInst *DI = cast<DbgValueInst>(Call);
659 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
660 const Value *V = DI->getValue();
662 // Currently the optimizer can produce this; insert an undef to
663 // help debugging. Probably the optimizer should not do this.
664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
665 .addReg(0U).addImm(DI->getOffset())
666 .addMetadata(DI->getVariable());
667 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
668 if (CI->getBitWidth() > 64)
669 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
670 .addCImm(CI).addImm(DI->getOffset())
671 .addMetadata(DI->getVariable());
673 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
674 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
675 .addMetadata(DI->getVariable());
676 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
678 .addFPImm(CF).addImm(DI->getOffset())
679 .addMetadata(DI->getVariable());
680 } else if (unsigned Reg = lookUpRegForValue(V)) {
681 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
682 .addReg(Reg, RegState::Debug).addImm(DI->getOffset())
683 .addMetadata(DI->getVariable());
685 // We can't yet handle anything else here because it would require
686 // generating code, thus altering codegen because of debug info.
687 DEBUG(dbgs() << "Dropping debug info for " << DI);
691 case Intrinsic::objectsize: {
692 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
693 unsigned long long Res = CI->isZero() ? -1ULL : 0;
694 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
695 unsigned ResultReg = getRegForValue(ResCI);
698 UpdateValueMap(Call, ResultReg);
703 // Usually, it does not make sense to initialize a value,
704 // make an unrelated function call and use the value, because
705 // it tends to be spilled on the stack. So, we move the pointer
706 // to the last local value to the beginning of the block, so that
707 // all the values which have already been materialized,
708 // appear after the call. It also makes sense to skip intrinsics
709 // since they tend to be inlined.
710 if (!isa<IntrinsicInst>(Call))
711 flushLocalValueMap();
713 // An arbitrary call. Bail.
717 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
718 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
719 EVT DstVT = TLI.getValueType(I->getType());
721 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
722 DstVT == MVT::Other || !DstVT.isSimple())
723 // Unhandled type. Halt "fast" selection and bail.
726 // Check if the destination type is legal.
727 if (!TLI.isTypeLegal(DstVT))
730 // Check if the source operand is legal.
731 if (!TLI.isTypeLegal(SrcVT))
734 unsigned InputReg = getRegForValue(I->getOperand(0));
736 // Unhandled operand. Halt "fast" selection and bail.
739 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
741 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
744 InputReg, InputRegIsKill);
748 UpdateValueMap(I, ResultReg);
752 bool FastISel::SelectBitCast(const User *I) {
753 // If the bitcast doesn't change the type, just use the operand value.
754 if (I->getType() == I->getOperand(0)->getType()) {
755 unsigned Reg = getRegForValue(I->getOperand(0));
758 UpdateValueMap(I, Reg);
762 // Bitcasts of other values become reg-reg copies or BITCAST operators.
763 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
764 EVT DstEVT = TLI.getValueType(I->getType());
765 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
766 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
767 // Unhandled type. Halt "fast" selection and bail.
770 MVT SrcVT = SrcEVT.getSimpleVT();
771 MVT DstVT = DstEVT.getSimpleVT();
772 unsigned Op0 = getRegForValue(I->getOperand(0));
774 // Unhandled operand. Halt "fast" selection and bail.
777 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
779 // First, try to perform the bitcast by inserting a reg-reg copy.
780 unsigned ResultReg = 0;
781 if (SrcVT == DstVT) {
782 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
783 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
784 // Don't attempt a cross-class copy. It will likely fail.
785 if (SrcClass == DstClass) {
786 ResultReg = createResultReg(DstClass);
787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
788 ResultReg).addReg(Op0);
792 // If the reg-reg copy failed, select a BITCAST opcode.
794 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
799 UpdateValueMap(I, ResultReg);
804 FastISel::SelectInstruction(const Instruction *I) {
805 // Just before the terminator instruction, insert instructions to
806 // feed PHI nodes in successor blocks.
807 if (isa<TerminatorInst>(I))
808 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
811 DL = I->getDebugLoc();
813 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
815 // As a special case, don't handle calls to builtin library functions that
816 // may be translated directly to target instructions.
817 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
818 const Function *F = Call->getCalledFunction();
820 if (F && !F->hasLocalLinkage() && F->hasName() &&
821 LibInfo->getLibFunc(F->getName(), Func) &&
822 LibInfo->hasOptimizedCodeGen(Func))
826 // First, try doing target-independent selection.
827 if (SelectOperator(I, I->getOpcode())) {
828 DEBUG(++NumFastIselSuccessIndependent);
832 // Remove dead code. However, ignore call instructions since we've flushed
833 // the local value map and recomputed the insert point.
834 if (!isa<CallInst>(I)) {
836 if (SavedInsertPt != FuncInfo.InsertPt)
837 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
840 // Next, try calling the target to attempt to handle the instruction.
841 SavedInsertPt = FuncInfo.InsertPt;
842 if (TargetSelectInstruction(I)) {
843 DEBUG(++NumFastIselSuccessTarget);
847 // Check for dead code and remove as necessary.
849 if (SavedInsertPt != FuncInfo.InsertPt)
850 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
856 /// FastEmitBranch - Emit an unconditional branch to the given block,
857 /// unless it is the immediate (fall-through) successor, and update
860 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
862 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
863 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
864 // For more accurate line information if this is the only instruction
865 // in the block then emit it, otherwise we have the unconditional
866 // fall-through case, which needs no instructions.
868 // The unconditional branch case.
869 TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
870 SmallVector<MachineOperand, 0>(), DL);
872 FuncInfo.MBB->addSuccessor(MSucc);
875 /// SelectFNeg - Emit an FNeg operation.
878 FastISel::SelectFNeg(const User *I) {
879 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
880 if (OpReg == 0) return false;
882 bool OpRegIsKill = hasTrivialKill(I);
884 // If the target has ISD::FNEG, use it.
885 EVT VT = TLI.getValueType(I->getType());
886 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
887 ISD::FNEG, OpReg, OpRegIsKill);
888 if (ResultReg != 0) {
889 UpdateValueMap(I, ResultReg);
893 // Bitcast the value to integer, twiddle the sign bit with xor,
894 // and then bitcast it back to floating-point.
895 if (VT.getSizeInBits() > 64) return false;
896 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
897 if (!TLI.isTypeLegal(IntVT))
900 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
901 ISD::BITCAST, OpReg, OpRegIsKill);
905 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
906 IntReg, /*Kill=*/true,
907 UINT64_C(1) << (VT.getSizeInBits()-1),
908 IntVT.getSimpleVT());
909 if (IntResultReg == 0)
912 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
913 ISD::BITCAST, IntResultReg, /*Kill=*/true);
917 UpdateValueMap(I, ResultReg);
922 FastISel::SelectExtractValue(const User *U) {
923 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
927 // Make sure we only try to handle extracts with a legal result. But also
928 // allow i1 because it's easy.
929 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
930 if (!RealVT.isSimple())
932 MVT VT = RealVT.getSimpleVT();
933 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
936 const Value *Op0 = EVI->getOperand(0);
937 Type *AggTy = Op0->getType();
939 // Get the base result register.
941 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
942 if (I != FuncInfo.ValueMap.end())
943 ResultReg = I->second;
944 else if (isa<Instruction>(Op0))
945 ResultReg = FuncInfo.InitializeRegForValue(Op0);
947 return false; // fast-isel can't handle aggregate constants at the moment
949 // Get the actual result register, which is an offset from the base register.
950 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
952 SmallVector<EVT, 4> AggValueVTs;
953 ComputeValueVTs(TLI, AggTy, AggValueVTs);
955 for (unsigned i = 0; i < VTIndex; i++)
956 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
958 UpdateValueMap(EVI, ResultReg);
963 FastISel::SelectOperator(const User *I, unsigned Opcode) {
965 case Instruction::Add:
966 return SelectBinaryOp(I, ISD::ADD);
967 case Instruction::FAdd:
968 return SelectBinaryOp(I, ISD::FADD);
969 case Instruction::Sub:
970 return SelectBinaryOp(I, ISD::SUB);
971 case Instruction::FSub:
972 // FNeg is currently represented in LLVM IR as a special case of FSub.
973 if (BinaryOperator::isFNeg(I))
974 return SelectFNeg(I);
975 return SelectBinaryOp(I, ISD::FSUB);
976 case Instruction::Mul:
977 return SelectBinaryOp(I, ISD::MUL);
978 case Instruction::FMul:
979 return SelectBinaryOp(I, ISD::FMUL);
980 case Instruction::SDiv:
981 return SelectBinaryOp(I, ISD::SDIV);
982 case Instruction::UDiv:
983 return SelectBinaryOp(I, ISD::UDIV);
984 case Instruction::FDiv:
985 return SelectBinaryOp(I, ISD::FDIV);
986 case Instruction::SRem:
987 return SelectBinaryOp(I, ISD::SREM);
988 case Instruction::URem:
989 return SelectBinaryOp(I, ISD::UREM);
990 case Instruction::FRem:
991 return SelectBinaryOp(I, ISD::FREM);
992 case Instruction::Shl:
993 return SelectBinaryOp(I, ISD::SHL);
994 case Instruction::LShr:
995 return SelectBinaryOp(I, ISD::SRL);
996 case Instruction::AShr:
997 return SelectBinaryOp(I, ISD::SRA);
998 case Instruction::And:
999 return SelectBinaryOp(I, ISD::AND);
1000 case Instruction::Or:
1001 return SelectBinaryOp(I, ISD::OR);
1002 case Instruction::Xor:
1003 return SelectBinaryOp(I, ISD::XOR);
1005 case Instruction::GetElementPtr:
1006 return SelectGetElementPtr(I);
1008 case Instruction::Br: {
1009 const BranchInst *BI = cast<BranchInst>(I);
1011 if (BI->isUnconditional()) {
1012 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1013 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1014 FastEmitBranch(MSucc, BI->getDebugLoc());
1018 // Conditional branches are not handed yet.
1019 // Halt "fast" selection and bail.
1023 case Instruction::Unreachable:
1027 case Instruction::Alloca:
1028 // FunctionLowering has the static-sized case covered.
1029 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1032 // Dynamic-sized alloca is not handled yet.
1035 case Instruction::Call:
1036 return SelectCall(I);
1038 case Instruction::BitCast:
1039 return SelectBitCast(I);
1041 case Instruction::FPToSI:
1042 return SelectCast(I, ISD::FP_TO_SINT);
1043 case Instruction::ZExt:
1044 return SelectCast(I, ISD::ZERO_EXTEND);
1045 case Instruction::SExt:
1046 return SelectCast(I, ISD::SIGN_EXTEND);
1047 case Instruction::Trunc:
1048 return SelectCast(I, ISD::TRUNCATE);
1049 case Instruction::SIToFP:
1050 return SelectCast(I, ISD::SINT_TO_FP);
1052 case Instruction::IntToPtr: // Deliberate fall-through.
1053 case Instruction::PtrToInt: {
1054 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1055 EVT DstVT = TLI.getValueType(I->getType());
1056 if (DstVT.bitsGT(SrcVT))
1057 return SelectCast(I, ISD::ZERO_EXTEND);
1058 if (DstVT.bitsLT(SrcVT))
1059 return SelectCast(I, ISD::TRUNCATE);
1060 unsigned Reg = getRegForValue(I->getOperand(0));
1061 if (Reg == 0) return false;
1062 UpdateValueMap(I, Reg);
1066 case Instruction::ExtractValue:
1067 return SelectExtractValue(I);
1069 case Instruction::PHI:
1070 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1073 // Unhandled instruction. Halt "fast" selection and bail.
1078 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1079 const TargetLibraryInfo *libInfo)
1080 : FuncInfo(funcInfo),
1081 MRI(FuncInfo.MF->getRegInfo()),
1082 MFI(*FuncInfo.MF->getFrameInfo()),
1083 MCP(*FuncInfo.MF->getConstantPool()),
1084 TM(FuncInfo.MF->getTarget()),
1085 TD(*TM.getDataLayout()),
1086 TII(*TM.getInstrInfo()),
1087 TLI(*TM.getTargetLowering()),
1088 TRI(*TM.getRegisterInfo()),
1092 FastISel::~FastISel() {}
1094 bool FastISel::FastLowerArguments() {
1098 unsigned FastISel::FastEmit_(MVT, MVT,
1103 unsigned FastISel::FastEmit_r(MVT, MVT,
1105 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1109 unsigned FastISel::FastEmit_rr(MVT, MVT,
1111 unsigned /*Op0*/, bool /*Op0IsKill*/,
1112 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1116 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1120 unsigned FastISel::FastEmit_f(MVT, MVT,
1121 unsigned, const ConstantFP * /*FPImm*/) {
1125 unsigned FastISel::FastEmit_ri(MVT, MVT,
1127 unsigned /*Op0*/, bool /*Op0IsKill*/,
1132 unsigned FastISel::FastEmit_rf(MVT, MVT,
1134 unsigned /*Op0*/, bool /*Op0IsKill*/,
1135 const ConstantFP * /*FPImm*/) {
1139 unsigned FastISel::FastEmit_rri(MVT, MVT,
1141 unsigned /*Op0*/, bool /*Op0IsKill*/,
1142 unsigned /*Op1*/, bool /*Op1IsKill*/,
1147 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1148 /// to emit an instruction with an immediate operand using FastEmit_ri.
1149 /// If that fails, it materializes the immediate into a register and try
1150 /// FastEmit_rr instead.
1151 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1152 unsigned Op0, bool Op0IsKill,
1153 uint64_t Imm, MVT ImmType) {
1154 // If this is a multiply by a power of two, emit this as a shift left.
1155 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1158 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1159 // div x, 8 -> srl x, 3
1164 // Horrible hack (to be removed), check to make sure shift amounts are
1166 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1167 Imm >= VT.getSizeInBits())
1170 // First check if immediate type is legal. If not, we can't use the ri form.
1171 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1174 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1175 if (MaterialReg == 0) {
1176 // This is a bit ugly/slow, but failing here means falling out of
1177 // fast-isel, which would be very slow.
1178 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1179 VT.getSizeInBits());
1180 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1182 return FastEmit_rr(VT, VT, Opcode,
1184 MaterialReg, /*Kill=*/true);
1187 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1188 return MRI.createVirtualRegister(RC);
1191 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1192 const TargetRegisterClass* RC) {
1193 unsigned ResultReg = createResultReg(RC);
1194 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1196 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg);
1200 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1201 const TargetRegisterClass *RC,
1202 unsigned Op0, bool Op0IsKill) {
1203 unsigned ResultReg = createResultReg(RC);
1204 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1206 if (II.getNumDefs() >= 1)
1207 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1208 .addReg(Op0, Op0IsKill * RegState::Kill);
1210 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1211 .addReg(Op0, Op0IsKill * RegState::Kill);
1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1213 ResultReg).addReg(II.ImplicitDefs[0]);
1219 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1220 const TargetRegisterClass *RC,
1221 unsigned Op0, bool Op0IsKill,
1222 unsigned Op1, bool Op1IsKill) {
1223 unsigned ResultReg = createResultReg(RC);
1224 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1226 if (II.getNumDefs() >= 1)
1227 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1228 .addReg(Op0, Op0IsKill * RegState::Kill)
1229 .addReg(Op1, Op1IsKill * RegState::Kill);
1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1232 .addReg(Op0, Op0IsKill * RegState::Kill)
1233 .addReg(Op1, Op1IsKill * RegState::Kill);
1234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1235 ResultReg).addReg(II.ImplicitDefs[0]);
1240 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1241 const TargetRegisterClass *RC,
1242 unsigned Op0, bool Op0IsKill,
1243 unsigned Op1, bool Op1IsKill,
1244 unsigned Op2, bool Op2IsKill) {
1245 unsigned ResultReg = createResultReg(RC);
1246 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1248 if (II.getNumDefs() >= 1)
1249 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1250 .addReg(Op0, Op0IsKill * RegState::Kill)
1251 .addReg(Op1, Op1IsKill * RegState::Kill)
1252 .addReg(Op2, Op2IsKill * RegState::Kill);
1254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1255 .addReg(Op0, Op0IsKill * RegState::Kill)
1256 .addReg(Op1, Op1IsKill * RegState::Kill)
1257 .addReg(Op2, Op2IsKill * RegState::Kill);
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1259 ResultReg).addReg(II.ImplicitDefs[0]);
1264 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1265 const TargetRegisterClass *RC,
1266 unsigned Op0, bool Op0IsKill,
1268 unsigned ResultReg = createResultReg(RC);
1269 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1271 if (II.getNumDefs() >= 1)
1272 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1273 .addReg(Op0, Op0IsKill * RegState::Kill)
1276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1277 .addReg(Op0, Op0IsKill * RegState::Kill)
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1280 ResultReg).addReg(II.ImplicitDefs[0]);
1285 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1286 const TargetRegisterClass *RC,
1287 unsigned Op0, bool Op0IsKill,
1288 uint64_t Imm1, uint64_t Imm2) {
1289 unsigned ResultReg = createResultReg(RC);
1290 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1292 if (II.getNumDefs() >= 1)
1293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1294 .addReg(Op0, Op0IsKill * RegState::Kill)
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1299 .addReg(Op0, Op0IsKill * RegState::Kill)
1302 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1303 ResultReg).addReg(II.ImplicitDefs[0]);
1308 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1309 const TargetRegisterClass *RC,
1310 unsigned Op0, bool Op0IsKill,
1311 const ConstantFP *FPImm) {
1312 unsigned ResultReg = createResultReg(RC);
1313 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1315 if (II.getNumDefs() >= 1)
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1317 .addReg(Op0, Op0IsKill * RegState::Kill)
1320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1321 .addReg(Op0, Op0IsKill * RegState::Kill)
1323 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1324 ResultReg).addReg(II.ImplicitDefs[0]);
1329 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1330 const TargetRegisterClass *RC,
1331 unsigned Op0, bool Op0IsKill,
1332 unsigned Op1, bool Op1IsKill,
1334 unsigned ResultReg = createResultReg(RC);
1335 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1337 if (II.getNumDefs() >= 1)
1338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1339 .addReg(Op0, Op0IsKill * RegState::Kill)
1340 .addReg(Op1, Op1IsKill * RegState::Kill)
1343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1344 .addReg(Op0, Op0IsKill * RegState::Kill)
1345 .addReg(Op1, Op1IsKill * RegState::Kill)
1347 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1348 ResultReg).addReg(II.ImplicitDefs[0]);
1353 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1354 const TargetRegisterClass *RC,
1355 unsigned Op0, bool Op0IsKill,
1356 unsigned Op1, bool Op1IsKill,
1357 uint64_t Imm1, uint64_t Imm2) {
1358 unsigned ResultReg = createResultReg(RC);
1359 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1361 if (II.getNumDefs() >= 1)
1362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1363 .addReg(Op0, Op0IsKill * RegState::Kill)
1364 .addReg(Op1, Op1IsKill * RegState::Kill)
1365 .addImm(Imm1).addImm(Imm2);
1367 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
1368 .addReg(Op0, Op0IsKill * RegState::Kill)
1369 .addReg(Op1, Op1IsKill * RegState::Kill)
1370 .addImm(Imm1).addImm(Imm2);
1371 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1372 ResultReg).addReg(II.ImplicitDefs[0]);
1377 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1378 const TargetRegisterClass *RC,
1380 unsigned ResultReg = createResultReg(RC);
1381 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1383 if (II.getNumDefs() >= 1)
1384 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg).addImm(Imm);
1386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm);
1387 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1388 ResultReg).addReg(II.ImplicitDefs[0]);
1393 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1394 const TargetRegisterClass *RC,
1395 uint64_t Imm1, uint64_t Imm2) {
1396 unsigned ResultReg = createResultReg(RC);
1397 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1399 if (II.getNumDefs() >= 1)
1400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
1401 .addImm(Imm1).addImm(Imm2);
1403 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II).addImm(Imm1).addImm(Imm2);
1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1405 ResultReg).addReg(II.ImplicitDefs[0]);
1410 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1411 unsigned Op0, bool Op0IsKill,
1413 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1414 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1415 "Cannot yet extract from physregs");
1416 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1417 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1419 DL, TII.get(TargetOpcode::COPY), ResultReg)
1420 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1424 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1425 /// with all but the least significant bit set to zero.
1426 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1427 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1430 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1431 /// Emit code to ensure constants are copied into registers when needed.
1432 /// Remember the virtual registers that need to be added to the Machine PHI
1433 /// nodes as input. We cannot just directly add them, because expansion
1434 /// might result in multiple MBB's for one BB. As such, the start of the
1435 /// BB might correspond to a different MBB than the end.
1436 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1437 const TerminatorInst *TI = LLVMBB->getTerminator();
1439 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1440 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1442 // Check successor nodes' PHI nodes that expect a constant to be available
1444 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1445 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1446 if (!isa<PHINode>(SuccBB->begin())) continue;
1447 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1449 // If this terminator has multiple identical successors (common for
1450 // switches), only handle each succ once.
1451 if (!SuccsHandled.insert(SuccMBB)) continue;
1453 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1455 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1456 // nodes and Machine PHI nodes, but the incoming operands have not been
1458 for (BasicBlock::const_iterator I = SuccBB->begin();
1459 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1461 // Ignore dead phi's.
1462 if (PN->use_empty()) continue;
1464 // Only handle legal types. Two interesting things to note here. First,
1465 // by bailing out early, we may leave behind some dead instructions,
1466 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1467 // own moves. Second, this check is necessary because FastISel doesn't
1468 // use CreateRegs to create registers, so it always creates
1469 // exactly one register for each non-void instruction.
1470 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1471 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1472 // Handle integer promotions, though, because they're common and easy.
1473 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1474 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1476 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1481 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1483 // Set the DebugLoc for the copy. Prefer the location of the operand
1484 // if there is one; use the location of the PHI otherwise.
1485 DL = PN->getDebugLoc();
1486 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1487 DL = Inst->getDebugLoc();
1489 unsigned Reg = getRegForValue(PHIOp);
1491 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1494 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));