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 #include "llvm/CodeGen/FastISel.h"
43 #include "llvm/ADT/Optional.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/IR/DataLayout.h"
52 #include "llvm/IR/DebugInfo.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalVariable.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetLibraryInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetMachine.h"
66 #define DEBUG_TYPE "isel"
68 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
69 "target-independent selector");
70 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
71 "target-specific selector");
72 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();
80 // Instructions are appended to FuncInfo.MBB. If the basic block already
81 // contains labels or copies, use the last instruction as the last local
83 EmitStartPt = nullptr;
84 if (!FuncInfo.MBB->empty())
85 EmitStartPt = &FuncInfo.MBB->back();
86 LastLocalValue = EmitStartPt;
89 bool FastISel::LowerArguments() {
90 if (!FuncInfo.CanLowerReturn)
91 // Fallback to SDISel argument lowering code to deal with sret pointer
95 if (!FastLowerArguments())
98 // Enter arguments into ValueMap for uses in non-entry BBs.
99 for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
100 E = FuncInfo.Fn->arg_end(); I != E; ++I) {
101 DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(I);
102 assert(VI != LocalValueMap.end() && "Missed an argument?");
103 FuncInfo.ValueMap[I] = VI->second;
108 void FastISel::flushLocalValueMap() {
109 LocalValueMap.clear();
110 LastLocalValue = EmitStartPt;
114 bool FastISel::hasTrivialKill(const Value *V) const {
115 // Don't consider constants or arguments to have trivial kills.
116 const Instruction *I = dyn_cast<Instruction>(V);
120 // No-op casts are trivially coalesced by fast-isel.
121 if (const CastInst *Cast = dyn_cast<CastInst>(I))
122 if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) &&
123 !hasTrivialKill(Cast->getOperand(0)))
126 // GEPs with all zero indices are trivially coalesced by fast-isel.
127 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
128 if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
131 // Only instructions with a single use in the same basic block are considered
132 // to have trivial kills.
133 return I->hasOneUse() &&
134 !(I->getOpcode() == Instruction::BitCast ||
135 I->getOpcode() == Instruction::PtrToInt ||
136 I->getOpcode() == Instruction::IntToPtr) &&
137 cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
140 unsigned FastISel::getRegForValue(const Value *V) {
141 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true);
142 // Don't handle non-simple values in FastISel.
143 if (!RealVT.isSimple())
146 // Ignore illegal types. We must do this before looking up the value
147 // in ValueMap because Arguments are given virtual registers regardless
148 // of whether FastISel can handle them.
149 MVT VT = RealVT.getSimpleVT();
150 if (!TLI.isTypeLegal(VT)) {
151 // Handle integer promotions, though, because they're common and easy.
152 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
153 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
158 // Look up the value to see if we already have a register for it.
159 unsigned Reg = lookUpRegForValue(V);
163 // In bottom-up mode, just create the virtual register which will be used
164 // to hold the value. It will be materialized later.
165 if (isa<Instruction>(V) &&
166 (!isa<AllocaInst>(V) ||
167 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
168 return FuncInfo.InitializeRegForValue(V);
170 SavePoint SaveInsertPt = enterLocalValueArea();
172 // Materialize the value in a register. Emit any instructions in the
174 Reg = materializeRegForValue(V, VT);
176 leaveLocalValueArea(SaveInsertPt);
181 /// materializeRegForValue - Helper for getRegForValue. This function is
182 /// called when the value isn't already available in a register and must
183 /// be materialized with new instructions.
184 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
187 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
188 if (CI->getValue().getActiveBits() <= 64)
189 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
190 } else if (isa<AllocaInst>(V)) {
191 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V));
192 } else if (isa<ConstantPointerNull>(V)) {
193 // Translate this as an integer zero so that it can be
194 // local-CSE'd with actual integer zeros.
196 getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getContext())));
197 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
198 if (CF->isNullValue()) {
199 Reg = TargetMaterializeFloatZero(CF);
201 // Try to emit the constant directly.
202 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF);
206 // Try to emit the constant by using an integer constant with a cast.
207 const APFloat &Flt = CF->getValueAPF();
208 EVT IntVT = TLI.getPointerTy();
211 uint32_t IntBitWidth = IntVT.getSizeInBits();
213 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
214 APFloat::rmTowardZero, &isExact);
216 APInt IntVal(IntBitWidth, x);
218 unsigned IntegerReg =
219 getRegForValue(ConstantInt::get(V->getContext(), IntVal));
221 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
222 IntegerReg, /*Kill=*/false);
225 } else if (const Operator *Op = dyn_cast<Operator>(V)) {
226 if (!SelectOperator(Op, Op->getOpcode()))
227 if (!isa<Instruction>(Op) ||
228 !TargetSelectInstruction(cast<Instruction>(Op)))
230 Reg = lookUpRegForValue(Op);
231 } else if (isa<UndefValue>(V)) {
232 Reg = createResultReg(TLI.getRegClassFor(VT));
233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
234 TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
237 // If target-independent code couldn't handle the value, give target-specific
239 if (!Reg && isa<Constant>(V))
240 Reg = TargetMaterializeConstant(cast<Constant>(V));
242 // Don't cache constant materializations in the general ValueMap.
243 // To do so would require tracking what uses they dominate.
245 LocalValueMap[V] = Reg;
246 LastLocalValue = MRI.getVRegDef(Reg);
251 unsigned FastISel::lookUpRegForValue(const Value *V) {
252 // Look up the value to see if we already have a register for it. We
253 // cache values defined by Instructions across blocks, and other values
254 // only locally. This is because Instructions already have the SSA
255 // def-dominates-use requirement enforced.
256 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
257 if (I != FuncInfo.ValueMap.end())
259 return LocalValueMap[V];
262 /// UpdateValueMap - Update the value map to include the new mapping for this
263 /// instruction, or insert an extra copy to get the result in a previous
264 /// determined register.
265 /// NOTE: This is only necessary because we might select a block that uses
266 /// a value before we select the block that defines the value. It might be
267 /// possible to fix this by selecting blocks in reverse postorder.
268 void FastISel::UpdateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
269 if (!isa<Instruction>(I)) {
270 LocalValueMap[I] = Reg;
274 unsigned &AssignedReg = FuncInfo.ValueMap[I];
275 if (AssignedReg == 0)
276 // Use the new register.
278 else if (Reg != AssignedReg) {
279 // Arrange for uses of AssignedReg to be replaced by uses of Reg.
280 for (unsigned i = 0; i < NumRegs; i++)
281 FuncInfo.RegFixups[AssignedReg+i] = Reg+i;
287 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
288 unsigned IdxN = getRegForValue(Idx);
290 // Unhandled operand. Halt "fast" selection and bail.
291 return std::pair<unsigned, bool>(0, false);
293 bool IdxNIsKill = hasTrivialKill(Idx);
295 // If the index is smaller or larger than intptr_t, truncate or extend it.
296 MVT PtrVT = TLI.getPointerTy();
297 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
298 if (IdxVT.bitsLT(PtrVT)) {
299 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND,
303 else if (IdxVT.bitsGT(PtrVT)) {
304 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE,
308 return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
311 void FastISel::recomputeInsertPt() {
312 if (getLastLocalValue()) {
313 FuncInfo.InsertPt = getLastLocalValue();
314 FuncInfo.MBB = FuncInfo.InsertPt->getParent();
317 FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
319 // Now skip past any EH_LABELs, which must remain at the beginning.
320 while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
321 FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
325 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
326 MachineBasicBlock::iterator E) {
327 assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
329 MachineInstr *Dead = &*I;
331 Dead->eraseFromParent();
337 FastISel::SavePoint FastISel::enterLocalValueArea() {
338 MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
339 DebugLoc OldDL = DbgLoc;
342 SavePoint SP = { OldInsertPt, OldDL };
346 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
347 if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
348 LastLocalValue = std::prev(FuncInfo.InsertPt);
350 // Restore the previous insert position.
351 FuncInfo.InsertPt = OldInsertPt.InsertPt;
352 DbgLoc = OldInsertPt.DL;
355 /// SelectBinaryOp - Select and emit code for a binary operator instruction,
356 /// which has an opcode which directly corresponds to the given ISD opcode.
358 bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) {
359 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
360 if (VT == MVT::Other || !VT.isSimple())
361 // Unhandled type. Halt "fast" selection and bail.
364 // We only handle legal types. For example, on x86-32 the instruction
365 // selector contains all of the 64-bit instructions from x86-64,
366 // under the assumption that i64 won't be used if the target doesn't
368 if (!TLI.isTypeLegal(VT)) {
369 // MVT::i1 is special. Allow AND, OR, or XOR because they
370 // don't require additional zeroing, which makes them easy.
372 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
373 ISDOpcode == ISD::XOR))
374 VT = TLI.getTypeToTransformTo(I->getContext(), VT);
379 // Check if the first operand is a constant, and handle it as "ri". At -O0,
380 // we don't have anything that canonicalizes operand order.
381 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
382 if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
383 unsigned Op1 = getRegForValue(I->getOperand(1));
384 if (Op1 == 0) return false;
386 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
388 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1,
389 Op1IsKill, CI->getZExtValue(),
391 if (ResultReg == 0) return false;
393 // We successfully emitted code for the given LLVM Instruction.
394 UpdateValueMap(I, ResultReg);
399 unsigned Op0 = getRegForValue(I->getOperand(0));
400 if (Op0 == 0) // Unhandled operand. Halt "fast" selection and bail.
403 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
405 // Check if the second operand is a constant and handle it appropriately.
406 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
407 uint64_t Imm = CI->getZExtValue();
409 // Transform "sdiv exact X, 8" -> "sra X, 3".
410 if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
411 cast<BinaryOperator>(I)->isExact() &&
412 isPowerOf2_64(Imm)) {
414 ISDOpcode = ISD::SRA;
417 // Transform "urem x, pow2" -> "and x, pow2-1".
418 if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
419 isPowerOf2_64(Imm)) {
421 ISDOpcode = ISD::AND;
424 unsigned ResultReg = FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
425 Op0IsKill, Imm, VT.getSimpleVT());
426 if (ResultReg == 0) return false;
428 // We successfully emitted code for the given LLVM Instruction.
429 UpdateValueMap(I, ResultReg);
433 // Check if the second operand is a constant float.
434 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
435 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
436 ISDOpcode, Op0, Op0IsKill, CF);
437 if (ResultReg != 0) {
438 // We successfully emitted code for the given LLVM Instruction.
439 UpdateValueMap(I, ResultReg);
444 unsigned Op1 = getRegForValue(I->getOperand(1));
446 // Unhandled operand. Halt "fast" selection and bail.
449 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
451 // Now we have both operands in registers. Emit the instruction.
452 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
457 // Target-specific code wasn't able to find a machine opcode for
458 // the given ISD opcode and type. Halt "fast" selection and bail.
461 // We successfully emitted code for the given LLVM Instruction.
462 UpdateValueMap(I, ResultReg);
466 bool FastISel::SelectGetElementPtr(const User *I) {
467 unsigned N = getRegForValue(I->getOperand(0));
469 // Unhandled operand. Halt "fast" selection and bail.
472 bool NIsKill = hasTrivialKill(I->getOperand(0));
474 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
475 // into a single N = N + TotalOffset.
476 uint64_t TotalOffs = 0;
477 // FIXME: What's a good SWAG number for MaxOffs?
478 uint64_t MaxOffs = 2048;
479 Type *Ty = I->getOperand(0)->getType();
480 MVT VT = TLI.getPointerTy();
481 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1,
482 E = I->op_end(); OI != E; ++OI) {
483 const Value *Idx = *OI;
484 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
485 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
488 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
489 if (TotalOffs >= MaxOffs) {
490 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
492 // Unhandled operand. Halt "fast" selection and bail.
498 Ty = StTy->getElementType(Field);
500 Ty = cast<SequentialType>(Ty)->getElementType();
502 // If this is a constant subscript, handle it quickly.
503 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
504 if (CI->isZero()) continue;
507 DL.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
508 if (TotalOffs >= MaxOffs) {
509 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
511 // Unhandled operand. Halt "fast" selection and bail.
519 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
521 // Unhandled operand. Halt "fast" selection and bail.
527 // N = N + Idx * ElementSize;
528 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
529 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
530 unsigned IdxN = Pair.first;
531 bool IdxNIsKill = Pair.second;
533 // Unhandled operand. Halt "fast" selection and bail.
536 if (ElementSize != 1) {
537 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
539 // Unhandled operand. Halt "fast" selection and bail.
543 N = FastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
545 // Unhandled operand. Halt "fast" selection and bail.
550 N = FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
552 // Unhandled operand. Halt "fast" selection and bail.
556 // We successfully emitted code for the given LLVM Instruction.
557 UpdateValueMap(I, N);
561 bool FastISel::SelectCall(const User *I) {
562 const CallInst *Call = cast<CallInst>(I);
564 // Handle simple inline asms.
565 if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
566 // Don't attempt to handle constraints.
567 if (!IA->getConstraintString().empty())
570 unsigned ExtraInfo = 0;
571 if (IA->hasSideEffects())
572 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
573 if (IA->isAlignStack())
574 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
577 TII.get(TargetOpcode::INLINEASM))
578 .addExternalSymbol(IA->getAsmString().c_str())
583 MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
584 ComputeUsesVAFloatArgument(*Call, &MMI);
586 const Function *F = Call->getCalledFunction();
587 if (!F) return false;
589 // Handle selected intrinsic function calls.
590 switch (F->getIntrinsicID()) {
592 // At -O0 we don't care about the lifetime intrinsics.
593 case Intrinsic::lifetime_start:
594 case Intrinsic::lifetime_end:
595 // The donothing intrinsic does, well, nothing.
596 case Intrinsic::donothing:
599 case Intrinsic::dbg_declare: {
600 const DbgDeclareInst *DI = cast<DbgDeclareInst>(Call);
601 DIVariable DIVar(DI->getVariable());
602 assert((!DIVar || DIVar.isVariable()) &&
603 "Variable in DbgDeclareInst should be either null or a DIVariable.");
605 !FuncInfo.MF->getMMI().hasDebugInfo()) {
606 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
610 const Value *Address = DI->getAddress();
611 if (!Address || isa<UndefValue>(Address)) {
612 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
617 Optional<MachineOperand> Op;
618 if (const Argument *Arg = dyn_cast<Argument>(Address))
619 // Some arguments' frame index is recorded during argument lowering.
620 Offset = FuncInfo.getArgumentFrameIndex(Arg);
622 Op = MachineOperand::CreateFI(Offset);
624 if (unsigned Reg = lookUpRegForValue(Address))
625 Op = MachineOperand::CreateReg(Reg, false);
627 // If we have a VLA that has a "use" in a metadata node that's then used
628 // here but it has no other uses, then we have a problem. E.g.,
630 // int foo (const int *x) {
635 // If we assign 'a' a vreg and fast isel later on has to use the selection
636 // DAG isel, it will want to copy the value to the vreg. However, there are
637 // no uses, which goes counter to what selection DAG isel expects.
638 if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
639 (!isa<AllocaInst>(Address) ||
640 !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
641 Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
646 Op->setIsDebug(true);
647 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
648 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
652 TII.get(TargetOpcode::DBG_VALUE))
655 .addMetadata(DI->getVariable());
657 // We can't yet handle anything else here because it would require
658 // generating code, thus altering codegen because of debug info.
659 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
663 case Intrinsic::dbg_value: {
664 // This form of DBG_VALUE is target-independent.
665 const DbgValueInst *DI = cast<DbgValueInst>(Call);
666 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
667 const Value *V = DI->getValue();
669 // Currently the optimizer can produce this; insert an undef to
670 // help debugging. Probably the optimizer should not do this.
671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
672 .addReg(0U).addImm(DI->getOffset())
673 .addMetadata(DI->getVariable());
674 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
675 if (CI->getBitWidth() > 64)
676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
677 .addCImm(CI).addImm(DI->getOffset())
678 .addMetadata(DI->getVariable());
680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
681 .addImm(CI->getZExtValue()).addImm(DI->getOffset())
682 .addMetadata(DI->getVariable());
683 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) {
684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
685 .addFPImm(CF).addImm(DI->getOffset())
686 .addMetadata(DI->getVariable());
687 } else if (unsigned Reg = lookUpRegForValue(V)) {
688 // FIXME: This does not handle register-indirect values at offset 0.
689 bool IsIndirect = DI->getOffset() != 0;
690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect,
691 Reg, DI->getOffset(), DI->getVariable());
693 // We can't yet handle anything else here because it would require
694 // generating code, thus altering codegen because of debug info.
695 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
699 case Intrinsic::objectsize: {
700 ConstantInt *CI = cast<ConstantInt>(Call->getArgOperand(1));
701 unsigned long long Res = CI->isZero() ? -1ULL : 0;
702 Constant *ResCI = ConstantInt::get(Call->getType(), Res);
703 unsigned ResultReg = getRegForValue(ResCI);
706 UpdateValueMap(Call, ResultReg);
709 case Intrinsic::expect: {
710 unsigned ResultReg = getRegForValue(Call->getArgOperand(0));
713 UpdateValueMap(Call, ResultReg);
718 // Usually, it does not make sense to initialize a value,
719 // make an unrelated function call and use the value, because
720 // it tends to be spilled on the stack. So, we move the pointer
721 // to the last local value to the beginning of the block, so that
722 // all the values which have already been materialized,
723 // appear after the call. It also makes sense to skip intrinsics
724 // since they tend to be inlined.
725 if (!isa<IntrinsicInst>(Call))
726 flushLocalValueMap();
728 // An arbitrary call. Bail.
732 bool FastISel::SelectCast(const User *I, unsigned Opcode) {
733 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
734 EVT DstVT = TLI.getValueType(I->getType());
736 if (SrcVT == MVT::Other || !SrcVT.isSimple() ||
737 DstVT == MVT::Other || !DstVT.isSimple())
738 // Unhandled type. Halt "fast" selection and bail.
741 // Check if the destination type is legal.
742 if (!TLI.isTypeLegal(DstVT))
745 // Check if the source operand is legal.
746 if (!TLI.isTypeLegal(SrcVT))
749 unsigned InputReg = getRegForValue(I->getOperand(0));
751 // Unhandled operand. Halt "fast" selection and bail.
754 bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
756 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(),
759 InputReg, InputRegIsKill);
763 UpdateValueMap(I, ResultReg);
767 bool FastISel::SelectBitCast(const User *I) {
768 // If the bitcast doesn't change the type, just use the operand value.
769 if (I->getType() == I->getOperand(0)->getType()) {
770 unsigned Reg = getRegForValue(I->getOperand(0));
773 UpdateValueMap(I, Reg);
777 // Bitcasts of other values become reg-reg copies or BITCAST operators.
778 EVT SrcEVT = TLI.getValueType(I->getOperand(0)->getType());
779 EVT DstEVT = TLI.getValueType(I->getType());
780 if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
781 !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
782 // Unhandled type. Halt "fast" selection and bail.
785 MVT SrcVT = SrcEVT.getSimpleVT();
786 MVT DstVT = DstEVT.getSimpleVT();
787 unsigned Op0 = getRegForValue(I->getOperand(0));
789 // Unhandled operand. Halt "fast" selection and bail.
792 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
794 // First, try to perform the bitcast by inserting a reg-reg copy.
795 unsigned ResultReg = 0;
796 if (SrcVT == DstVT) {
797 const TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT);
798 const TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT);
799 // Don't attempt a cross-class copy. It will likely fail.
800 if (SrcClass == DstClass) {
801 ResultReg = createResultReg(DstClass);
802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
803 TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
807 // If the reg-reg copy failed, select a BITCAST opcode.
809 ResultReg = FastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
814 UpdateValueMap(I, ResultReg);
819 FastISel::SelectInstruction(const Instruction *I) {
820 // Just before the terminator instruction, insert instructions to
821 // feed PHI nodes in successor blocks.
822 if (isa<TerminatorInst>(I))
823 if (!HandlePHINodesInSuccessorBlocks(I->getParent()))
826 DbgLoc = I->getDebugLoc();
828 MachineBasicBlock::iterator SavedInsertPt = FuncInfo.InsertPt;
830 if (const CallInst *Call = dyn_cast<CallInst>(I)) {
831 const Function *F = Call->getCalledFunction();
834 // As a special case, don't handle calls to builtin library functions that
835 // may be translated directly to target instructions.
836 if (F && !F->hasLocalLinkage() && F->hasName() &&
837 LibInfo->getLibFunc(F->getName(), Func) &&
838 LibInfo->hasOptimizedCodeGen(Func))
841 // Don't handle Intrinsic::trap if a trap funciton is specified.
842 if (F && F->getIntrinsicID() == Intrinsic::trap &&
843 !TM.Options.getTrapFunctionName().empty())
847 // First, try doing target-independent selection.
848 if (SelectOperator(I, I->getOpcode())) {
849 ++NumFastIselSuccessIndependent;
853 // Remove dead code. However, ignore call instructions since we've flushed
854 // the local value map and recomputed the insert point.
855 if (!isa<CallInst>(I)) {
857 if (SavedInsertPt != FuncInfo.InsertPt)
858 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
861 // Next, try calling the target to attempt to handle the instruction.
862 SavedInsertPt = FuncInfo.InsertPt;
863 if (TargetSelectInstruction(I)) {
864 ++NumFastIselSuccessTarget;
868 // Check for dead code and remove as necessary.
870 if (SavedInsertPt != FuncInfo.InsertPt)
871 removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
877 /// FastEmitBranch - Emit an unconditional branch to the given block,
878 /// unless it is the immediate (fall-through) successor, and update
881 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
883 if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
884 FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
885 // For more accurate line information if this is the only instruction
886 // in the block then emit it, otherwise we have the unconditional
887 // fall-through case, which needs no instructions.
889 // The unconditional branch case.
890 TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
891 SmallVector<MachineOperand, 0>(), DbgLoc);
893 FuncInfo.MBB->addSuccessor(MSucc);
896 /// SelectFNeg - Emit an FNeg operation.
899 FastISel::SelectFNeg(const User *I) {
900 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
901 if (OpReg == 0) return false;
903 bool OpRegIsKill = hasTrivialKill(I);
905 // If the target has ISD::FNEG, use it.
906 EVT VT = TLI.getValueType(I->getType());
907 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(),
908 ISD::FNEG, OpReg, OpRegIsKill);
909 if (ResultReg != 0) {
910 UpdateValueMap(I, ResultReg);
914 // Bitcast the value to integer, twiddle the sign bit with xor,
915 // and then bitcast it back to floating-point.
916 if (VT.getSizeInBits() > 64) return false;
917 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
918 if (!TLI.isTypeLegal(IntVT))
921 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
922 ISD::BITCAST, OpReg, OpRegIsKill);
926 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR,
927 IntReg, /*Kill=*/true,
928 UINT64_C(1) << (VT.getSizeInBits()-1),
929 IntVT.getSimpleVT());
930 if (IntResultReg == 0)
933 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(),
934 ISD::BITCAST, IntResultReg, /*Kill=*/true);
938 UpdateValueMap(I, ResultReg);
943 FastISel::SelectExtractValue(const User *U) {
944 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
948 // Make sure we only try to handle extracts with a legal result. But also
949 // allow i1 because it's easy.
950 EVT RealVT = TLI.getValueType(EVI->getType(), /*AllowUnknown=*/true);
951 if (!RealVT.isSimple())
953 MVT VT = RealVT.getSimpleVT();
954 if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
957 const Value *Op0 = EVI->getOperand(0);
958 Type *AggTy = Op0->getType();
960 // Get the base result register.
962 DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
963 if (I != FuncInfo.ValueMap.end())
964 ResultReg = I->second;
965 else if (isa<Instruction>(Op0))
966 ResultReg = FuncInfo.InitializeRegForValue(Op0);
968 return false; // fast-isel can't handle aggregate constants at the moment
970 // Get the actual result register, which is an offset from the base register.
971 unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
973 SmallVector<EVT, 4> AggValueVTs;
974 ComputeValueVTs(TLI, AggTy, AggValueVTs);
976 for (unsigned i = 0; i < VTIndex; i++)
977 ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
979 UpdateValueMap(EVI, ResultReg);
984 FastISel::SelectOperator(const User *I, unsigned Opcode) {
986 case Instruction::Add:
987 return SelectBinaryOp(I, ISD::ADD);
988 case Instruction::FAdd:
989 return SelectBinaryOp(I, ISD::FADD);
990 case Instruction::Sub:
991 return SelectBinaryOp(I, ISD::SUB);
992 case Instruction::FSub:
993 // FNeg is currently represented in LLVM IR as a special case of FSub.
994 if (BinaryOperator::isFNeg(I))
995 return SelectFNeg(I);
996 return SelectBinaryOp(I, ISD::FSUB);
997 case Instruction::Mul:
998 return SelectBinaryOp(I, ISD::MUL);
999 case Instruction::FMul:
1000 return SelectBinaryOp(I, ISD::FMUL);
1001 case Instruction::SDiv:
1002 return SelectBinaryOp(I, ISD::SDIV);
1003 case Instruction::UDiv:
1004 return SelectBinaryOp(I, ISD::UDIV);
1005 case Instruction::FDiv:
1006 return SelectBinaryOp(I, ISD::FDIV);
1007 case Instruction::SRem:
1008 return SelectBinaryOp(I, ISD::SREM);
1009 case Instruction::URem:
1010 return SelectBinaryOp(I, ISD::UREM);
1011 case Instruction::FRem:
1012 return SelectBinaryOp(I, ISD::FREM);
1013 case Instruction::Shl:
1014 return SelectBinaryOp(I, ISD::SHL);
1015 case Instruction::LShr:
1016 return SelectBinaryOp(I, ISD::SRL);
1017 case Instruction::AShr:
1018 return SelectBinaryOp(I, ISD::SRA);
1019 case Instruction::And:
1020 return SelectBinaryOp(I, ISD::AND);
1021 case Instruction::Or:
1022 return SelectBinaryOp(I, ISD::OR);
1023 case Instruction::Xor:
1024 return SelectBinaryOp(I, ISD::XOR);
1026 case Instruction::GetElementPtr:
1027 return SelectGetElementPtr(I);
1029 case Instruction::Br: {
1030 const BranchInst *BI = cast<BranchInst>(I);
1032 if (BI->isUnconditional()) {
1033 const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1034 MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1035 FastEmitBranch(MSucc, BI->getDebugLoc());
1039 // Conditional branches are not handed yet.
1040 // Halt "fast" selection and bail.
1044 case Instruction::Unreachable:
1045 if (TM.Options.TrapUnreachable)
1046 return FastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
1050 case Instruction::Alloca:
1051 // FunctionLowering has the static-sized case covered.
1052 if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1055 // Dynamic-sized alloca is not handled yet.
1058 case Instruction::Call:
1059 return SelectCall(I);
1061 case Instruction::BitCast:
1062 return SelectBitCast(I);
1064 case Instruction::FPToSI:
1065 return SelectCast(I, ISD::FP_TO_SINT);
1066 case Instruction::ZExt:
1067 return SelectCast(I, ISD::ZERO_EXTEND);
1068 case Instruction::SExt:
1069 return SelectCast(I, ISD::SIGN_EXTEND);
1070 case Instruction::Trunc:
1071 return SelectCast(I, ISD::TRUNCATE);
1072 case Instruction::SIToFP:
1073 return SelectCast(I, ISD::SINT_TO_FP);
1075 case Instruction::IntToPtr: // Deliberate fall-through.
1076 case Instruction::PtrToInt: {
1077 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
1078 EVT DstVT = TLI.getValueType(I->getType());
1079 if (DstVT.bitsGT(SrcVT))
1080 return SelectCast(I, ISD::ZERO_EXTEND);
1081 if (DstVT.bitsLT(SrcVT))
1082 return SelectCast(I, ISD::TRUNCATE);
1083 unsigned Reg = getRegForValue(I->getOperand(0));
1084 if (Reg == 0) return false;
1085 UpdateValueMap(I, Reg);
1089 case Instruction::ExtractValue:
1090 return SelectExtractValue(I);
1092 case Instruction::PHI:
1093 llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1096 // Unhandled instruction. Halt "fast" selection and bail.
1101 FastISel::FastISel(FunctionLoweringInfo &funcInfo,
1102 const TargetLibraryInfo *libInfo)
1103 : FuncInfo(funcInfo),
1104 MRI(FuncInfo.MF->getRegInfo()),
1105 MFI(*FuncInfo.MF->getFrameInfo()),
1106 MCP(*FuncInfo.MF->getConstantPool()),
1107 TM(FuncInfo.MF->getTarget()),
1108 DL(*TM.getDataLayout()),
1109 TII(*TM.getInstrInfo()),
1110 TLI(*TM.getTargetLowering()),
1111 TRI(*TM.getRegisterInfo()),
1115 FastISel::~FastISel() {}
1117 bool FastISel::FastLowerArguments() {
1121 unsigned FastISel::FastEmit_(MVT, MVT,
1126 unsigned FastISel::FastEmit_r(MVT, MVT,
1128 unsigned /*Op0*/, bool /*Op0IsKill*/) {
1132 unsigned FastISel::FastEmit_rr(MVT, MVT,
1134 unsigned /*Op0*/, bool /*Op0IsKill*/,
1135 unsigned /*Op1*/, bool /*Op1IsKill*/) {
1139 unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1143 unsigned FastISel::FastEmit_f(MVT, MVT,
1144 unsigned, const ConstantFP * /*FPImm*/) {
1148 unsigned FastISel::FastEmit_ri(MVT, MVT,
1150 unsigned /*Op0*/, bool /*Op0IsKill*/,
1155 unsigned FastISel::FastEmit_rf(MVT, MVT,
1157 unsigned /*Op0*/, bool /*Op0IsKill*/,
1158 const ConstantFP * /*FPImm*/) {
1162 unsigned FastISel::FastEmit_rri(MVT, MVT,
1164 unsigned /*Op0*/, bool /*Op0IsKill*/,
1165 unsigned /*Op1*/, bool /*Op1IsKill*/,
1170 /// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries
1171 /// to emit an instruction with an immediate operand using FastEmit_ri.
1172 /// If that fails, it materializes the immediate into a register and try
1173 /// FastEmit_rr instead.
1174 unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode,
1175 unsigned Op0, bool Op0IsKill,
1176 uint64_t Imm, MVT ImmType) {
1177 // If this is a multiply by a power of two, emit this as a shift left.
1178 if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1181 } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1182 // div x, 8 -> srl x, 3
1187 // Horrible hack (to be removed), check to make sure shift amounts are
1189 if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1190 Imm >= VT.getSizeInBits())
1193 // First check if immediate type is legal. If not, we can't use the ri form.
1194 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1197 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1198 if (MaterialReg == 0) {
1199 // This is a bit ugly/slow, but failing here means falling out of
1200 // fast-isel, which would be very slow.
1201 IntegerType *ITy = IntegerType::get(FuncInfo.Fn->getContext(),
1202 VT.getSizeInBits());
1203 MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1204 assert (MaterialReg != 0 && "Unable to materialize imm.");
1205 if (MaterialReg == 0) return 0;
1207 return FastEmit_rr(VT, VT, Opcode,
1209 MaterialReg, /*Kill=*/true);
1212 unsigned FastISel::createResultReg(const TargetRegisterClass* RC) {
1213 return MRI.createVirtualRegister(RC);
1216 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II,
1217 unsigned Op, unsigned OpNum) {
1218 if (TargetRegisterInfo::isVirtualRegister(Op)) {
1219 const TargetRegisterClass *RegClass =
1220 TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
1221 if (!MRI.constrainRegClass(Op, RegClass)) {
1222 // If it's not legal to COPY between the register classes, something
1223 // has gone very wrong before we got here.
1224 unsigned NewOp = createResultReg(RegClass);
1225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1226 TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
1233 unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode,
1234 const TargetRegisterClass* RC) {
1235 unsigned ResultReg = createResultReg(RC);
1236 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
1242 unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode,
1243 const TargetRegisterClass *RC,
1244 unsigned Op0, bool Op0IsKill) {
1245 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1247 unsigned ResultReg = createResultReg(RC);
1248 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1250 if (II.getNumDefs() >= 1)
1251 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1252 .addReg(Op0, Op0IsKill * RegState::Kill);
1254 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1255 .addReg(Op0, Op0IsKill * RegState::Kill);
1256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1257 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1263 unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
1264 const TargetRegisterClass *RC,
1265 unsigned Op0, bool Op0IsKill,
1266 unsigned Op1, bool Op1IsKill) {
1267 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1269 unsigned ResultReg = createResultReg(RC);
1270 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1271 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1273 if (II.getNumDefs() >= 1)
1274 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1275 .addReg(Op0, Op0IsKill * RegState::Kill)
1276 .addReg(Op1, Op1IsKill * RegState::Kill);
1278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1279 .addReg(Op0, Op0IsKill * RegState::Kill)
1280 .addReg(Op1, Op1IsKill * RegState::Kill);
1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1282 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1287 unsigned FastISel::FastEmitInst_rrr(unsigned MachineInstOpcode,
1288 const TargetRegisterClass *RC,
1289 unsigned Op0, bool Op0IsKill,
1290 unsigned Op1, bool Op1IsKill,
1291 unsigned Op2, bool Op2IsKill) {
1292 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1294 unsigned ResultReg = createResultReg(RC);
1295 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1296 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1297 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
1299 if (II.getNumDefs() >= 1)
1300 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1301 .addReg(Op0, Op0IsKill * RegState::Kill)
1302 .addReg(Op1, Op1IsKill * RegState::Kill)
1303 .addReg(Op2, Op2IsKill * RegState::Kill);
1305 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1306 .addReg(Op0, Op0IsKill * RegState::Kill)
1307 .addReg(Op1, Op1IsKill * RegState::Kill)
1308 .addReg(Op2, Op2IsKill * RegState::Kill);
1309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1310 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1315 unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
1316 const TargetRegisterClass *RC,
1317 unsigned Op0, bool Op0IsKill,
1319 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1321 unsigned ResultReg = createResultReg(RC);
1322 RC = TII.getRegClass(II, II.getNumDefs(), &TRI, *FuncInfo.MF);
1323 MRI.constrainRegClass(Op0, RC);
1325 if (II.getNumDefs() >= 1)
1326 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1327 .addReg(Op0, Op0IsKill * RegState::Kill)
1330 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1331 .addReg(Op0, Op0IsKill * RegState::Kill)
1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1334 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1339 unsigned FastISel::FastEmitInst_rii(unsigned MachineInstOpcode,
1340 const TargetRegisterClass *RC,
1341 unsigned Op0, bool Op0IsKill,
1342 uint64_t Imm1, uint64_t Imm2) {
1343 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1345 unsigned ResultReg = createResultReg(RC);
1346 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1348 if (II.getNumDefs() >= 1)
1349 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1350 .addReg(Op0, Op0IsKill * RegState::Kill)
1354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1355 .addReg(Op0, Op0IsKill * RegState::Kill)
1358 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1359 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1364 unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
1365 const TargetRegisterClass *RC,
1366 unsigned Op0, bool Op0IsKill,
1367 const ConstantFP *FPImm) {
1368 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1370 unsigned ResultReg = createResultReg(RC);
1371 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1373 if (II.getNumDefs() >= 1)
1374 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1375 .addReg(Op0, Op0IsKill * RegState::Kill)
1378 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1379 .addReg(Op0, Op0IsKill * RegState::Kill)
1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1382 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1387 unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
1388 const TargetRegisterClass *RC,
1389 unsigned Op0, bool Op0IsKill,
1390 unsigned Op1, bool Op1IsKill,
1392 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1394 unsigned ResultReg = createResultReg(RC);
1395 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1396 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1398 if (II.getNumDefs() >= 1)
1399 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1400 .addReg(Op0, Op0IsKill * RegState::Kill)
1401 .addReg(Op1, Op1IsKill * RegState::Kill)
1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1405 .addReg(Op0, Op0IsKill * RegState::Kill)
1406 .addReg(Op1, Op1IsKill * RegState::Kill)
1408 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1409 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1414 unsigned FastISel::FastEmitInst_rrii(unsigned MachineInstOpcode,
1415 const TargetRegisterClass *RC,
1416 unsigned Op0, bool Op0IsKill,
1417 unsigned Op1, bool Op1IsKill,
1418 uint64_t Imm1, uint64_t Imm2) {
1419 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1421 unsigned ResultReg = createResultReg(RC);
1422 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1423 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1425 if (II.getNumDefs() >= 1)
1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1427 .addReg(Op0, Op0IsKill * RegState::Kill)
1428 .addReg(Op1, Op1IsKill * RegState::Kill)
1429 .addImm(Imm1).addImm(Imm2);
1431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1432 .addReg(Op0, Op0IsKill * RegState::Kill)
1433 .addReg(Op1, Op1IsKill * RegState::Kill)
1434 .addImm(Imm1).addImm(Imm2);
1435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1436 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1441 unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode,
1442 const TargetRegisterClass *RC,
1444 unsigned ResultReg = createResultReg(RC);
1445 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1447 if (II.getNumDefs() >= 1)
1448 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg).addImm(Imm);
1450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
1451 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1452 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1457 unsigned FastISel::FastEmitInst_ii(unsigned MachineInstOpcode,
1458 const TargetRegisterClass *RC,
1459 uint64_t Imm1, uint64_t Imm2) {
1460 unsigned ResultReg = createResultReg(RC);
1461 const MCInstrDesc &II = TII.get(MachineInstOpcode);
1463 if (II.getNumDefs() >= 1)
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1465 .addImm(Imm1).addImm(Imm2);
1467 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm1).addImm(Imm2);
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1469 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1474 unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT,
1475 unsigned Op0, bool Op0IsKill,
1477 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1478 assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1479 "Cannot yet extract from physregs");
1480 const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1481 MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1482 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
1483 DbgLoc, TII.get(TargetOpcode::COPY), ResultReg)
1484 .addReg(Op0, getKillRegState(Op0IsKill), Idx);
1488 /// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op
1489 /// with all but the least significant bit set to zero.
1490 unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1491 return FastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1494 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1495 /// Emit code to ensure constants are copied into registers when needed.
1496 /// Remember the virtual registers that need to be added to the Machine PHI
1497 /// nodes as input. We cannot just directly add them, because expansion
1498 /// might result in multiple MBB's for one BB. As such, the start of the
1499 /// BB might correspond to a different MBB than the end.
1500 bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
1501 const TerminatorInst *TI = LLVMBB->getTerminator();
1503 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
1504 unsigned OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
1506 // Check successor nodes' PHI nodes that expect a constant to be available
1508 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1509 const BasicBlock *SuccBB = TI->getSuccessor(succ);
1510 if (!isa<PHINode>(SuccBB->begin())) continue;
1511 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
1513 // If this terminator has multiple identical successors (common for
1514 // switches), only handle each succ once.
1515 if (!SuccsHandled.insert(SuccMBB)) continue;
1517 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
1519 // At this point we know that there is a 1-1 correspondence between LLVM PHI
1520 // nodes and Machine PHI nodes, but the incoming operands have not been
1522 for (BasicBlock::const_iterator I = SuccBB->begin();
1523 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1525 // Ignore dead phi's.
1526 if (PN->use_empty()) continue;
1528 // Only handle legal types. Two interesting things to note here. First,
1529 // by bailing out early, we may leave behind some dead instructions,
1530 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
1531 // own moves. Second, this check is necessary because FastISel doesn't
1532 // use CreateRegs to create registers, so it always creates
1533 // exactly one register for each non-void instruction.
1534 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
1535 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
1536 // Handle integer promotions, though, because they're common and easy.
1537 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
1538 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
1540 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1545 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1547 // Set the DebugLoc for the copy. Prefer the location of the operand
1548 // if there is one; use the location of the PHI otherwise.
1549 DbgLoc = PN->getDebugLoc();
1550 if (const Instruction *Inst = dyn_cast<Instruction>(PHIOp))
1551 DbgLoc = Inst->getDebugLoc();
1553 unsigned Reg = getRegForValue(PHIOp);
1555 FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
1558 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
1559 DbgLoc = DebugLoc();
1566 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
1567 assert(LI->hasOneUse() &&
1568 "tryToFoldLoad expected a LoadInst with a single use");
1569 // We know that the load has a single use, but don't know what it is. If it
1570 // isn't one of the folded instructions, then we can't succeed here. Handle
1571 // this by scanning the single-use users of the load until we get to FoldInst.
1572 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
1574 const Instruction *TheUser = LI->user_back();
1575 while (TheUser != FoldInst && // Scan up until we find FoldInst.
1576 // Stay in the right block.
1577 TheUser->getParent() == FoldInst->getParent() &&
1578 --MaxUsers) { // Don't scan too far.
1579 // If there are multiple or no uses of this instruction, then bail out.
1580 if (!TheUser->hasOneUse())
1583 TheUser = TheUser->user_back();
1586 // If we didn't find the fold instruction, then we failed to collapse the
1588 if (TheUser != FoldInst)
1591 // Don't try to fold volatile loads. Target has to deal with alignment
1593 if (LI->isVolatile())
1596 // Figure out which vreg this is going into. If there is no assigned vreg yet
1597 // then there actually was no reference to it. Perhaps the load is referenced
1598 // by a dead instruction.
1599 unsigned LoadReg = getRegForValue(LI);
1603 // We can't fold if this vreg has no uses or more than one use. Multiple uses
1604 // may mean that the instruction got lowered to multiple MIs, or the use of
1605 // the loaded value ended up being multiple operands of the result.
1606 if (!MRI.hasOneUse(LoadReg))
1609 MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
1610 MachineInstr *User = RI->getParent();
1612 // Set the insertion point properly. Folding the load can cause generation of
1613 // other random instructions (like sign extends) for addressing modes; make
1614 // sure they get inserted in a logical place before the new instruction.
1615 FuncInfo.InsertPt = User;
1616 FuncInfo.MBB = User->getParent();
1618 // Ask the target to try folding the load.
1619 return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
1622 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
1624 if (!isa<AddOperator>(Add))
1626 // Type size needs to match.
1627 if (DL.getTypeSizeInBits(GEP->getType()) !=
1628 DL.getTypeSizeInBits(Add->getType()))
1630 // Must be in the same basic block.
1631 if (isa<Instruction>(Add) &&
1632 FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
1634 // Must have a constant operand.
1635 return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));