FastISel.cpp revision e8c92dd439581bec7e3516cbdbea74e2e60fe7f0
1//===-- FastISel.cpp - Implementation of the FastISel class ---------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains the implementation of the FastISel class. 11// 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. 19// 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. 24// 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 32// in -O0 compiles. 33// 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. 39// 40//===----------------------------------------------------------------------===// 41 42#include "llvm/Function.h" 43#include "llvm/GlobalVariable.h" 44#include "llvm/Instructions.h" 45#include "llvm/IntrinsicInst.h" 46#include "llvm/CodeGen/FastISel.h" 47#include "llvm/CodeGen/MachineInstrBuilder.h" 48#include "llvm/CodeGen/MachineModuleInfo.h" 49#include "llvm/CodeGen/MachineRegisterInfo.h" 50#include "llvm/Analysis/DebugInfo.h" 51#include "llvm/Target/TargetData.h" 52#include "llvm/Target/TargetInstrInfo.h" 53#include "llvm/Target/TargetLowering.h" 54#include "llvm/Target/TargetMachine.h" 55#include "llvm/Support/ErrorHandling.h" 56#include "FunctionLoweringInfo.h" 57using namespace llvm; 58 59unsigned FastISel::getRegForValue(const Value *V) { 60 EVT RealVT = TLI.getValueType(V->getType(), /*AllowUnknown=*/true); 61 // Don't handle non-simple values in FastISel. 62 if (!RealVT.isSimple()) 63 return 0; 64 65 // Ignore illegal types. We must do this before looking up the value 66 // in ValueMap because Arguments are given virtual registers regardless 67 // of whether FastISel can handle them. 68 MVT VT = RealVT.getSimpleVT(); 69 if (!TLI.isTypeLegal(VT)) { 70 // Promote MVT::i1 to a legal type though, because it's common and easy. 71 if (VT == MVT::i1) 72 VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT(); 73 else 74 return 0; 75 } 76 77 // Look up the value to see if we already have a register for it. We 78 // cache values defined by Instructions across blocks, and other values 79 // only locally. This is because Instructions already have the SSA 80 // def-dominates-use requirement enforced. 81 if (ValueMap.count(V)) 82 return ValueMap[V]; 83 unsigned Reg = LocalValueMap[V]; 84 if (Reg != 0) 85 return Reg; 86 87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 88 if (CI->getValue().getActiveBits() <= 64) 89 Reg = FastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue()); 90 } else if (isa<AllocaInst>(V)) { 91 Reg = TargetMaterializeAlloca(cast<AllocaInst>(V)); 92 } else if (isa<ConstantPointerNull>(V)) { 93 // Translate this as an integer zero so that it can be 94 // local-CSE'd with actual integer zeros. 95 Reg = 96 getRegForValue(Constant::getNullValue(TD.getIntPtrType(V->getContext()))); 97 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 98 // Try to emit the constant directly. 99 Reg = FastEmit_f(VT, VT, ISD::ConstantFP, CF); 100 101 if (!Reg) { 102 // Try to emit the constant by using an integer constant with a cast. 103 const APFloat &Flt = CF->getValueAPF(); 104 EVT IntVT = TLI.getPointerTy(); 105 106 uint64_t x[2]; 107 uint32_t IntBitWidth = IntVT.getSizeInBits(); 108 bool isExact; 109 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true, 110 APFloat::rmTowardZero, &isExact); 111 if (isExact) { 112 APInt IntVal(IntBitWidth, 2, x); 113 114 unsigned IntegerReg = 115 getRegForValue(ConstantInt::get(V->getContext(), IntVal)); 116 if (IntegerReg != 0) 117 Reg = FastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg); 118 } 119 } 120 } else if (const Operator *Op = dyn_cast<Operator>(V)) { 121 if (!SelectOperator(Op, Op->getOpcode())) return 0; 122 Reg = LocalValueMap[Op]; 123 } else if (isa<UndefValue>(V)) { 124 Reg = createResultReg(TLI.getRegClassFor(VT)); 125 BuildMI(MBB, DL, TII.get(TargetOpcode::IMPLICIT_DEF), Reg); 126 } 127 128 // If target-independent code couldn't handle the value, give target-specific 129 // code a try. 130 if (!Reg && isa<Constant>(V)) 131 Reg = TargetMaterializeConstant(cast<Constant>(V)); 132 133 // Don't cache constant materializations in the general ValueMap. 134 // To do so would require tracking what uses they dominate. 135 if (Reg != 0) 136 LocalValueMap[V] = Reg; 137 return Reg; 138} 139 140unsigned FastISel::lookUpRegForValue(const Value *V) { 141 // Look up the value to see if we already have a register for it. We 142 // cache values defined by Instructions across blocks, and other values 143 // only locally. This is because Instructions already have the SSA 144 // def-dominatess-use requirement enforced. 145 if (ValueMap.count(V)) 146 return ValueMap[V]; 147 return LocalValueMap[V]; 148} 149 150/// UpdateValueMap - Update the value map to include the new mapping for this 151/// instruction, or insert an extra copy to get the result in a previous 152/// determined register. 153/// NOTE: This is only necessary because we might select a block that uses 154/// a value before we select the block that defines the value. It might be 155/// possible to fix this by selecting blocks in reverse postorder. 156unsigned FastISel::UpdateValueMap(const Value *I, unsigned Reg) { 157 if (!isa<Instruction>(I)) { 158 LocalValueMap[I] = Reg; 159 return Reg; 160 } 161 162 unsigned &AssignedReg = ValueMap[I]; 163 if (AssignedReg == 0) 164 AssignedReg = Reg; 165 else if (Reg != AssignedReg) { 166 const TargetRegisterClass *RegClass = MRI.getRegClass(Reg); 167 TII.copyRegToReg(*MBB, MBB->end(), AssignedReg, 168 Reg, RegClass, RegClass); 169 } 170 return AssignedReg; 171} 172 173unsigned FastISel::getRegForGEPIndex(const Value *Idx) { 174 unsigned IdxN = getRegForValue(Idx); 175 if (IdxN == 0) 176 // Unhandled operand. Halt "fast" selection and bail. 177 return 0; 178 179 // If the index is smaller or larger than intptr_t, truncate or extend it. 180 MVT PtrVT = TLI.getPointerTy(); 181 EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false); 182 if (IdxVT.bitsLT(PtrVT)) 183 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN); 184 else if (IdxVT.bitsGT(PtrVT)) 185 IdxN = FastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN); 186 return IdxN; 187} 188 189/// SelectBinaryOp - Select and emit code for a binary operator instruction, 190/// which has an opcode which directly corresponds to the given ISD opcode. 191/// 192bool FastISel::SelectBinaryOp(const User *I, unsigned ISDOpcode) { 193 EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true); 194 if (VT == MVT::Other || !VT.isSimple()) 195 // Unhandled type. Halt "fast" selection and bail. 196 return false; 197 198 // We only handle legal types. For example, on x86-32 the instruction 199 // selector contains all of the 64-bit instructions from x86-64, 200 // under the assumption that i64 won't be used if the target doesn't 201 // support it. 202 if (!TLI.isTypeLegal(VT)) { 203 // MVT::i1 is special. Allow AND, OR, or XOR because they 204 // don't require additional zeroing, which makes them easy. 205 if (VT == MVT::i1 && 206 (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR || 207 ISDOpcode == ISD::XOR)) 208 VT = TLI.getTypeToTransformTo(I->getContext(), VT); 209 else 210 return false; 211 } 212 213 unsigned Op0 = getRegForValue(I->getOperand(0)); 214 if (Op0 == 0) 215 // Unhandled operand. Halt "fast" selection and bail. 216 return false; 217 218 // Check if the second operand is a constant and handle it appropriately. 219 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 220 unsigned ResultReg = FastEmit_ri(VT.getSimpleVT(), VT.getSimpleVT(), 221 ISDOpcode, Op0, CI->getZExtValue()); 222 if (ResultReg != 0) { 223 // We successfully emitted code for the given LLVM Instruction. 224 UpdateValueMap(I, ResultReg); 225 return true; 226 } 227 } 228 229 // Check if the second operand is a constant float. 230 if (ConstantFP *CF = dyn_cast<ConstantFP>(I->getOperand(1))) { 231 unsigned ResultReg = FastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(), 232 ISDOpcode, Op0, CF); 233 if (ResultReg != 0) { 234 // We successfully emitted code for the given LLVM Instruction. 235 UpdateValueMap(I, ResultReg); 236 return true; 237 } 238 } 239 240 unsigned Op1 = getRegForValue(I->getOperand(1)); 241 if (Op1 == 0) 242 // Unhandled operand. Halt "fast" selection and bail. 243 return false; 244 245 // Now we have both operands in registers. Emit the instruction. 246 unsigned ResultReg = FastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(), 247 ISDOpcode, Op0, Op1); 248 if (ResultReg == 0) 249 // Target-specific code wasn't able to find a machine opcode for 250 // the given ISD opcode and type. Halt "fast" selection and bail. 251 return false; 252 253 // We successfully emitted code for the given LLVM Instruction. 254 UpdateValueMap(I, ResultReg); 255 return true; 256} 257 258bool FastISel::SelectGetElementPtr(const User *I) { 259 unsigned N = getRegForValue(I->getOperand(0)); 260 if (N == 0) 261 // Unhandled operand. Halt "fast" selection and bail. 262 return false; 263 264 const Type *Ty = I->getOperand(0)->getType(); 265 MVT VT = TLI.getPointerTy(); 266 for (GetElementPtrInst::const_op_iterator OI = I->op_begin()+1, 267 E = I->op_end(); OI != E; ++OI) { 268 const Value *Idx = *OI; 269 if (const StructType *StTy = dyn_cast<StructType>(Ty)) { 270 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue(); 271 if (Field) { 272 // N = N + Offset 273 uint64_t Offs = TD.getStructLayout(StTy)->getElementOffset(Field); 274 // FIXME: This can be optimized by combining the add with a 275 // subsequent one. 276 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT); 277 if (N == 0) 278 // Unhandled operand. Halt "fast" selection and bail. 279 return false; 280 } 281 Ty = StTy->getElementType(Field); 282 } else { 283 Ty = cast<SequentialType>(Ty)->getElementType(); 284 285 // If this is a constant subscript, handle it quickly. 286 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 287 if (CI->getZExtValue() == 0) continue; 288 uint64_t Offs = 289 TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 290 N = FastEmit_ri_(VT, ISD::ADD, N, Offs, VT); 291 if (N == 0) 292 // Unhandled operand. Halt "fast" selection and bail. 293 return false; 294 continue; 295 } 296 297 // N = N + Idx * ElementSize; 298 uint64_t ElementSize = TD.getTypeAllocSize(Ty); 299 unsigned IdxN = getRegForGEPIndex(Idx); 300 if (IdxN == 0) 301 // Unhandled operand. Halt "fast" selection and bail. 302 return false; 303 304 if (ElementSize != 1) { 305 IdxN = FastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT); 306 if (IdxN == 0) 307 // Unhandled operand. Halt "fast" selection and bail. 308 return false; 309 } 310 N = FastEmit_rr(VT, VT, ISD::ADD, N, IdxN); 311 if (N == 0) 312 // Unhandled operand. Halt "fast" selection and bail. 313 return false; 314 } 315 } 316 317 // We successfully emitted code for the given LLVM Instruction. 318 UpdateValueMap(I, N); 319 return true; 320} 321 322bool FastISel::SelectCall(const User *I) { 323 const Function *F = cast<CallInst>(I)->getCalledFunction(); 324 if (!F) return false; 325 326 // Handle selected intrinsic function calls. 327 unsigned IID = F->getIntrinsicID(); 328 switch (IID) { 329 default: break; 330 case Intrinsic::dbg_declare: { 331 const DbgDeclareInst *DI = cast<DbgDeclareInst>(I); 332 if (!DIDescriptor::ValidDebugInfo(DI->getVariable(), CodeGenOpt::None) || 333 !MF.getMMI().hasDebugInfo()) 334 return true; 335 336 const Value *Address = DI->getAddress(); 337 if (!Address) 338 return true; 339 if (isa<UndefValue>(Address)) 340 return true; 341 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 342 // Don't handle byval struct arguments or VLAs, for example. 343 if (!AI) break; 344 DenseMap<const AllocaInst*, int>::iterator SI = 345 StaticAllocaMap.find(AI); 346 if (SI == StaticAllocaMap.end()) break; // VLAs. 347 int FI = SI->second; 348 if (!DI->getDebugLoc().isUnknown()) 349 MF.getMMI().setVariableDbgInfo(DI->getVariable(), FI, DI->getDebugLoc()); 350 351 // Building the map above is target independent. Generating DBG_VALUE 352 // inline is target dependent; do this now. 353 (void)TargetSelectInstruction(cast<Instruction>(I)); 354 return true; 355 } 356 case Intrinsic::dbg_value: { 357 // This form of DBG_VALUE is target-independent. 358 const DbgValueInst *DI = cast<DbgValueInst>(I); 359 const TargetInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 360 const Value *V = DI->getValue(); 361 if (!V) { 362 // Currently the optimizer can produce this; insert an undef to 363 // help debugging. Probably the optimizer should not do this. 364 BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()). 365 addMetadata(DI->getVariable()); 366 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 367 BuildMI(MBB, DL, II).addImm(CI->getZExtValue()).addImm(DI->getOffset()). 368 addMetadata(DI->getVariable()); 369 } else if (const ConstantFP *CF = dyn_cast<ConstantFP>(V)) { 370 BuildMI(MBB, DL, II).addFPImm(CF).addImm(DI->getOffset()). 371 addMetadata(DI->getVariable()); 372 } else if (unsigned Reg = lookUpRegForValue(V)) { 373 BuildMI(MBB, DL, II).addReg(Reg, RegState::Debug).addImm(DI->getOffset()). 374 addMetadata(DI->getVariable()); 375 } else { 376 // We can't yet handle anything else here because it would require 377 // generating code, thus altering codegen because of debug info. 378 // Insert an undef so we can see what we dropped. 379 BuildMI(MBB, DL, II).addReg(0U).addImm(DI->getOffset()). 380 addMetadata(DI->getVariable()); 381 } 382 return true; 383 } 384 case Intrinsic::eh_exception: { 385 EVT VT = TLI.getValueType(I->getType()); 386 switch (TLI.getOperationAction(ISD::EXCEPTIONADDR, VT)) { 387 default: break; 388 case TargetLowering::Expand: { 389 assert(MBB->isLandingPad() && "Call to eh.exception not in landing pad!"); 390 unsigned Reg = TLI.getExceptionAddressRegister(); 391 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 392 unsigned ResultReg = createResultReg(RC); 393 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 394 Reg, RC, RC); 395 assert(InsertedCopy && "Can't copy address registers!"); 396 InsertedCopy = InsertedCopy; 397 UpdateValueMap(I, ResultReg); 398 return true; 399 } 400 } 401 break; 402 } 403 case Intrinsic::eh_selector: { 404 EVT VT = TLI.getValueType(I->getType()); 405 switch (TLI.getOperationAction(ISD::EHSELECTION, VT)) { 406 default: break; 407 case TargetLowering::Expand: { 408 if (MBB->isLandingPad()) 409 AddCatchInfo(*cast<CallInst>(I), &MF.getMMI(), MBB); 410 else { 411#ifndef NDEBUG 412 CatchInfoLost.insert(cast<CallInst>(I)); 413#endif 414 // FIXME: Mark exception selector register as live in. Hack for PR1508. 415 unsigned Reg = TLI.getExceptionSelectorRegister(); 416 if (Reg) MBB->addLiveIn(Reg); 417 } 418 419 unsigned Reg = TLI.getExceptionSelectorRegister(); 420 EVT SrcVT = TLI.getPointerTy(); 421 const TargetRegisterClass *RC = TLI.getRegClassFor(SrcVT); 422 unsigned ResultReg = createResultReg(RC); 423 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, Reg, 424 RC, RC); 425 assert(InsertedCopy && "Can't copy address registers!"); 426 InsertedCopy = InsertedCopy; 427 428 // Cast the register to the type of the selector. 429 if (SrcVT.bitsGT(MVT::i32)) 430 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, ISD::TRUNCATE, 431 ResultReg); 432 else if (SrcVT.bitsLT(MVT::i32)) 433 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, 434 ISD::SIGN_EXTEND, ResultReg); 435 if (ResultReg == 0) 436 // Unhandled operand. Halt "fast" selection and bail. 437 return false; 438 439 UpdateValueMap(I, ResultReg); 440 441 return true; 442 } 443 } 444 break; 445 } 446 } 447 448 // An arbitrary call. Bail. 449 return false; 450} 451 452bool FastISel::SelectCast(const User *I, unsigned Opcode) { 453 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 454 EVT DstVT = TLI.getValueType(I->getType()); 455 456 if (SrcVT == MVT::Other || !SrcVT.isSimple() || 457 DstVT == MVT::Other || !DstVT.isSimple()) 458 // Unhandled type. Halt "fast" selection and bail. 459 return false; 460 461 // Check if the destination type is legal. Or as a special case, 462 // it may be i1 if we're doing a truncate because that's 463 // easy and somewhat common. 464 if (!TLI.isTypeLegal(DstVT)) 465 if (DstVT != MVT::i1 || Opcode != ISD::TRUNCATE) 466 // Unhandled type. Halt "fast" selection and bail. 467 return false; 468 469 // Check if the source operand is legal. Or as a special case, 470 // it may be i1 if we're doing zero-extension because that's 471 // easy and somewhat common. 472 if (!TLI.isTypeLegal(SrcVT)) 473 if (SrcVT != MVT::i1 || Opcode != ISD::ZERO_EXTEND) 474 // Unhandled type. Halt "fast" selection and bail. 475 return false; 476 477 unsigned InputReg = getRegForValue(I->getOperand(0)); 478 if (!InputReg) 479 // Unhandled operand. Halt "fast" selection and bail. 480 return false; 481 482 // If the operand is i1, arrange for the high bits in the register to be zero. 483 if (SrcVT == MVT::i1) { 484 SrcVT = TLI.getTypeToTransformTo(I->getContext(), SrcVT); 485 InputReg = FastEmitZExtFromI1(SrcVT.getSimpleVT(), InputReg); 486 if (!InputReg) 487 return false; 488 } 489 // If the result is i1, truncate to the target's type for i1 first. 490 if (DstVT == MVT::i1) 491 DstVT = TLI.getTypeToTransformTo(I->getContext(), DstVT); 492 493 unsigned ResultReg = FastEmit_r(SrcVT.getSimpleVT(), 494 DstVT.getSimpleVT(), 495 Opcode, 496 InputReg); 497 if (!ResultReg) 498 return false; 499 500 UpdateValueMap(I, ResultReg); 501 return true; 502} 503 504bool FastISel::SelectBitCast(const User *I) { 505 // If the bitcast doesn't change the type, just use the operand value. 506 if (I->getType() == I->getOperand(0)->getType()) { 507 unsigned Reg = getRegForValue(I->getOperand(0)); 508 if (Reg == 0) 509 return false; 510 UpdateValueMap(I, Reg); 511 return true; 512 } 513 514 // Bitcasts of other values become reg-reg copies or BIT_CONVERT operators. 515 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 516 EVT DstVT = TLI.getValueType(I->getType()); 517 518 if (SrcVT == MVT::Other || !SrcVT.isSimple() || 519 DstVT == MVT::Other || !DstVT.isSimple() || 520 !TLI.isTypeLegal(SrcVT) || !TLI.isTypeLegal(DstVT)) 521 // Unhandled type. Halt "fast" selection and bail. 522 return false; 523 524 unsigned Op0 = getRegForValue(I->getOperand(0)); 525 if (Op0 == 0) 526 // Unhandled operand. Halt "fast" selection and bail. 527 return false; 528 529 // First, try to perform the bitcast by inserting a reg-reg copy. 530 unsigned ResultReg = 0; 531 if (SrcVT.getSimpleVT() == DstVT.getSimpleVT()) { 532 TargetRegisterClass* SrcClass = TLI.getRegClassFor(SrcVT); 533 TargetRegisterClass* DstClass = TLI.getRegClassFor(DstVT); 534 ResultReg = createResultReg(DstClass); 535 536 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 537 Op0, DstClass, SrcClass); 538 if (!InsertedCopy) 539 ResultReg = 0; 540 } 541 542 // If the reg-reg copy failed, select a BIT_CONVERT opcode. 543 if (!ResultReg) 544 ResultReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), 545 ISD::BIT_CONVERT, Op0); 546 547 if (!ResultReg) 548 return false; 549 550 UpdateValueMap(I, ResultReg); 551 return true; 552} 553 554bool 555FastISel::SelectInstruction(const Instruction *I) { 556 // Just before the terminator instruction, insert instructions to 557 // feed PHI nodes in successor blocks. 558 if (isa<TerminatorInst>(I)) 559 if (!HandlePHINodesInSuccessorBlocks(I->getParent())) 560 return false; 561 562 DL = I->getDebugLoc(); 563 564 // First, try doing target-independent selection. 565 if (SelectOperator(I, I->getOpcode())) { 566 DL = DebugLoc(); 567 return true; 568 } 569 570 // Next, try calling the target to attempt to handle the instruction. 571 if (TargetSelectInstruction(I)) { 572 DL = DebugLoc(); 573 return true; 574 } 575 576 DL = DebugLoc(); 577 return false; 578} 579 580/// FastEmitBranch - Emit an unconditional branch to the given block, 581/// unless it is the immediate (fall-through) successor, and update 582/// the CFG. 583void 584FastISel::FastEmitBranch(MachineBasicBlock *MSucc) { 585 if (MBB->isLayoutSuccessor(MSucc)) { 586 // The unconditional fall-through case, which needs no instructions. 587 } else { 588 // The unconditional branch case. 589 TII.InsertBranch(*MBB, MSucc, NULL, SmallVector<MachineOperand, 0>()); 590 } 591 MBB->addSuccessor(MSucc); 592} 593 594/// SelectFNeg - Emit an FNeg operation. 595/// 596bool 597FastISel::SelectFNeg(const User *I) { 598 unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I)); 599 if (OpReg == 0) return false; 600 601 // If the target has ISD::FNEG, use it. 602 EVT VT = TLI.getValueType(I->getType()); 603 unsigned ResultReg = FastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), 604 ISD::FNEG, OpReg); 605 if (ResultReg != 0) { 606 UpdateValueMap(I, ResultReg); 607 return true; 608 } 609 610 // Bitcast the value to integer, twiddle the sign bit with xor, 611 // and then bitcast it back to floating-point. 612 if (VT.getSizeInBits() > 64) return false; 613 EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits()); 614 if (!TLI.isTypeLegal(IntVT)) 615 return false; 616 617 unsigned IntReg = FastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(), 618 ISD::BIT_CONVERT, OpReg); 619 if (IntReg == 0) 620 return false; 621 622 unsigned IntResultReg = FastEmit_ri_(IntVT.getSimpleVT(), ISD::XOR, IntReg, 623 UINT64_C(1) << (VT.getSizeInBits()-1), 624 IntVT.getSimpleVT()); 625 if (IntResultReg == 0) 626 return false; 627 628 ResultReg = FastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), 629 ISD::BIT_CONVERT, IntResultReg); 630 if (ResultReg == 0) 631 return false; 632 633 UpdateValueMap(I, ResultReg); 634 return true; 635} 636 637bool 638FastISel::SelectOperator(const User *I, unsigned Opcode) { 639 switch (Opcode) { 640 case Instruction::Add: 641 return SelectBinaryOp(I, ISD::ADD); 642 case Instruction::FAdd: 643 return SelectBinaryOp(I, ISD::FADD); 644 case Instruction::Sub: 645 return SelectBinaryOp(I, ISD::SUB); 646 case Instruction::FSub: 647 // FNeg is currently represented in LLVM IR as a special case of FSub. 648 if (BinaryOperator::isFNeg(I)) 649 return SelectFNeg(I); 650 return SelectBinaryOp(I, ISD::FSUB); 651 case Instruction::Mul: 652 return SelectBinaryOp(I, ISD::MUL); 653 case Instruction::FMul: 654 return SelectBinaryOp(I, ISD::FMUL); 655 case Instruction::SDiv: 656 return SelectBinaryOp(I, ISD::SDIV); 657 case Instruction::UDiv: 658 return SelectBinaryOp(I, ISD::UDIV); 659 case Instruction::FDiv: 660 return SelectBinaryOp(I, ISD::FDIV); 661 case Instruction::SRem: 662 return SelectBinaryOp(I, ISD::SREM); 663 case Instruction::URem: 664 return SelectBinaryOp(I, ISD::UREM); 665 case Instruction::FRem: 666 return SelectBinaryOp(I, ISD::FREM); 667 case Instruction::Shl: 668 return SelectBinaryOp(I, ISD::SHL); 669 case Instruction::LShr: 670 return SelectBinaryOp(I, ISD::SRL); 671 case Instruction::AShr: 672 return SelectBinaryOp(I, ISD::SRA); 673 case Instruction::And: 674 return SelectBinaryOp(I, ISD::AND); 675 case Instruction::Or: 676 return SelectBinaryOp(I, ISD::OR); 677 case Instruction::Xor: 678 return SelectBinaryOp(I, ISD::XOR); 679 680 case Instruction::GetElementPtr: 681 return SelectGetElementPtr(I); 682 683 case Instruction::Br: { 684 const BranchInst *BI = cast<BranchInst>(I); 685 686 if (BI->isUnconditional()) { 687 const BasicBlock *LLVMSucc = BI->getSuccessor(0); 688 MachineBasicBlock *MSucc = MBBMap[LLVMSucc]; 689 FastEmitBranch(MSucc); 690 return true; 691 } 692 693 // Conditional branches are not handed yet. 694 // Halt "fast" selection and bail. 695 return false; 696 } 697 698 case Instruction::Unreachable: 699 // Nothing to emit. 700 return true; 701 702 case Instruction::Alloca: 703 // FunctionLowering has the static-sized case covered. 704 if (StaticAllocaMap.count(cast<AllocaInst>(I))) 705 return true; 706 707 // Dynamic-sized alloca is not handled yet. 708 return false; 709 710 case Instruction::Call: 711 return SelectCall(I); 712 713 case Instruction::BitCast: 714 return SelectBitCast(I); 715 716 case Instruction::FPToSI: 717 return SelectCast(I, ISD::FP_TO_SINT); 718 case Instruction::ZExt: 719 return SelectCast(I, ISD::ZERO_EXTEND); 720 case Instruction::SExt: 721 return SelectCast(I, ISD::SIGN_EXTEND); 722 case Instruction::Trunc: 723 return SelectCast(I, ISD::TRUNCATE); 724 case Instruction::SIToFP: 725 return SelectCast(I, ISD::SINT_TO_FP); 726 727 case Instruction::IntToPtr: // Deliberate fall-through. 728 case Instruction::PtrToInt: { 729 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 730 EVT DstVT = TLI.getValueType(I->getType()); 731 if (DstVT.bitsGT(SrcVT)) 732 return SelectCast(I, ISD::ZERO_EXTEND); 733 if (DstVT.bitsLT(SrcVT)) 734 return SelectCast(I, ISD::TRUNCATE); 735 unsigned Reg = getRegForValue(I->getOperand(0)); 736 if (Reg == 0) return false; 737 UpdateValueMap(I, Reg); 738 return true; 739 } 740 741 case Instruction::PHI: 742 llvm_unreachable("FastISel shouldn't visit PHI nodes!"); 743 744 default: 745 // Unhandled instruction. Halt "fast" selection and bail. 746 return false; 747 } 748} 749 750FastISel::FastISel(MachineFunction &mf, 751 DenseMap<const Value *, unsigned> &vm, 752 DenseMap<const BasicBlock *, MachineBasicBlock *> &bm, 753 DenseMap<const AllocaInst *, int> &am, 754 std::vector<std::pair<MachineInstr*, unsigned> > &pn 755#ifndef NDEBUG 756 , SmallSet<const Instruction *, 8> &cil 757#endif 758 ) 759 : MBB(0), 760 ValueMap(vm), 761 MBBMap(bm), 762 StaticAllocaMap(am), 763 PHINodesToUpdate(pn), 764#ifndef NDEBUG 765 CatchInfoLost(cil), 766#endif 767 MF(mf), 768 MRI(MF.getRegInfo()), 769 MFI(*MF.getFrameInfo()), 770 MCP(*MF.getConstantPool()), 771 TM(MF.getTarget()), 772 TD(*TM.getTargetData()), 773 TII(*TM.getInstrInfo()), 774 TLI(*TM.getTargetLowering()) { 775} 776 777FastISel::~FastISel() {} 778 779unsigned FastISel::FastEmit_(MVT, MVT, 780 unsigned) { 781 return 0; 782} 783 784unsigned FastISel::FastEmit_r(MVT, MVT, 785 unsigned, unsigned /*Op0*/) { 786 return 0; 787} 788 789unsigned FastISel::FastEmit_rr(MVT, MVT, 790 unsigned, unsigned /*Op0*/, 791 unsigned /*Op0*/) { 792 return 0; 793} 794 795unsigned FastISel::FastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) { 796 return 0; 797} 798 799unsigned FastISel::FastEmit_f(MVT, MVT, 800 unsigned, const ConstantFP * /*FPImm*/) { 801 return 0; 802} 803 804unsigned FastISel::FastEmit_ri(MVT, MVT, 805 unsigned, unsigned /*Op0*/, 806 uint64_t /*Imm*/) { 807 return 0; 808} 809 810unsigned FastISel::FastEmit_rf(MVT, MVT, 811 unsigned, unsigned /*Op0*/, 812 const ConstantFP * /*FPImm*/) { 813 return 0; 814} 815 816unsigned FastISel::FastEmit_rri(MVT, MVT, 817 unsigned, 818 unsigned /*Op0*/, unsigned /*Op1*/, 819 uint64_t /*Imm*/) { 820 return 0; 821} 822 823/// FastEmit_ri_ - This method is a wrapper of FastEmit_ri. It first tries 824/// to emit an instruction with an immediate operand using FastEmit_ri. 825/// If that fails, it materializes the immediate into a register and try 826/// FastEmit_rr instead. 827unsigned FastISel::FastEmit_ri_(MVT VT, unsigned Opcode, 828 unsigned Op0, uint64_t Imm, 829 MVT ImmType) { 830 // First check if immediate type is legal. If not, we can't use the ri form. 831 unsigned ResultReg = FastEmit_ri(VT, VT, Opcode, Op0, Imm); 832 if (ResultReg != 0) 833 return ResultReg; 834 unsigned MaterialReg = FastEmit_i(ImmType, ImmType, ISD::Constant, Imm); 835 if (MaterialReg == 0) 836 return 0; 837 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg); 838} 839 840/// FastEmit_rf_ - This method is a wrapper of FastEmit_ri. It first tries 841/// to emit an instruction with a floating-point immediate operand using 842/// FastEmit_rf. If that fails, it materializes the immediate into a register 843/// and try FastEmit_rr instead. 844unsigned FastISel::FastEmit_rf_(MVT VT, unsigned Opcode, 845 unsigned Op0, const ConstantFP *FPImm, 846 MVT ImmType) { 847 // First check if immediate type is legal. If not, we can't use the rf form. 848 unsigned ResultReg = FastEmit_rf(VT, VT, Opcode, Op0, FPImm); 849 if (ResultReg != 0) 850 return ResultReg; 851 852 // Materialize the constant in a register. 853 unsigned MaterialReg = FastEmit_f(ImmType, ImmType, ISD::ConstantFP, FPImm); 854 if (MaterialReg == 0) { 855 // If the target doesn't have a way to directly enter a floating-point 856 // value into a register, use an alternate approach. 857 // TODO: The current approach only supports floating-point constants 858 // that can be constructed by conversion from integer values. This should 859 // be replaced by code that creates a load from a constant-pool entry, 860 // which will require some target-specific work. 861 const APFloat &Flt = FPImm->getValueAPF(); 862 EVT IntVT = TLI.getPointerTy(); 863 864 uint64_t x[2]; 865 uint32_t IntBitWidth = IntVT.getSizeInBits(); 866 bool isExact; 867 (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true, 868 APFloat::rmTowardZero, &isExact); 869 if (!isExact) 870 return 0; 871 APInt IntVal(IntBitWidth, 2, x); 872 873 unsigned IntegerReg = FastEmit_i(IntVT.getSimpleVT(), IntVT.getSimpleVT(), 874 ISD::Constant, IntVal.getZExtValue()); 875 if (IntegerReg == 0) 876 return 0; 877 MaterialReg = FastEmit_r(IntVT.getSimpleVT(), VT, 878 ISD::SINT_TO_FP, IntegerReg); 879 if (MaterialReg == 0) 880 return 0; 881 } 882 return FastEmit_rr(VT, VT, Opcode, Op0, MaterialReg); 883} 884 885unsigned FastISel::createResultReg(const TargetRegisterClass* RC) { 886 return MRI.createVirtualRegister(RC); 887} 888 889unsigned FastISel::FastEmitInst_(unsigned MachineInstOpcode, 890 const TargetRegisterClass* RC) { 891 unsigned ResultReg = createResultReg(RC); 892 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 893 894 BuildMI(MBB, DL, II, ResultReg); 895 return ResultReg; 896} 897 898unsigned FastISel::FastEmitInst_r(unsigned MachineInstOpcode, 899 const TargetRegisterClass *RC, 900 unsigned Op0) { 901 unsigned ResultReg = createResultReg(RC); 902 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 903 904 if (II.getNumDefs() >= 1) 905 BuildMI(MBB, DL, II, ResultReg).addReg(Op0); 906 else { 907 BuildMI(MBB, DL, II).addReg(Op0); 908 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 909 II.ImplicitDefs[0], RC, RC); 910 if (!InsertedCopy) 911 ResultReg = 0; 912 } 913 914 return ResultReg; 915} 916 917unsigned FastISel::FastEmitInst_rr(unsigned MachineInstOpcode, 918 const TargetRegisterClass *RC, 919 unsigned Op0, unsigned Op1) { 920 unsigned ResultReg = createResultReg(RC); 921 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 922 923 if (II.getNumDefs() >= 1) 924 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1); 925 else { 926 BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1); 927 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 928 II.ImplicitDefs[0], RC, RC); 929 if (!InsertedCopy) 930 ResultReg = 0; 931 } 932 return ResultReg; 933} 934 935unsigned FastISel::FastEmitInst_ri(unsigned MachineInstOpcode, 936 const TargetRegisterClass *RC, 937 unsigned Op0, uint64_t Imm) { 938 unsigned ResultReg = createResultReg(RC); 939 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 940 941 if (II.getNumDefs() >= 1) 942 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Imm); 943 else { 944 BuildMI(MBB, DL, II).addReg(Op0).addImm(Imm); 945 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 946 II.ImplicitDefs[0], RC, RC); 947 if (!InsertedCopy) 948 ResultReg = 0; 949 } 950 return ResultReg; 951} 952 953unsigned FastISel::FastEmitInst_rf(unsigned MachineInstOpcode, 954 const TargetRegisterClass *RC, 955 unsigned Op0, const ConstantFP *FPImm) { 956 unsigned ResultReg = createResultReg(RC); 957 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 958 959 if (II.getNumDefs() >= 1) 960 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addFPImm(FPImm); 961 else { 962 BuildMI(MBB, DL, II).addReg(Op0).addFPImm(FPImm); 963 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 964 II.ImplicitDefs[0], RC, RC); 965 if (!InsertedCopy) 966 ResultReg = 0; 967 } 968 return ResultReg; 969} 970 971unsigned FastISel::FastEmitInst_rri(unsigned MachineInstOpcode, 972 const TargetRegisterClass *RC, 973 unsigned Op0, unsigned Op1, uint64_t Imm) { 974 unsigned ResultReg = createResultReg(RC); 975 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 976 977 if (II.getNumDefs() >= 1) 978 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addReg(Op1).addImm(Imm); 979 else { 980 BuildMI(MBB, DL, II).addReg(Op0).addReg(Op1).addImm(Imm); 981 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 982 II.ImplicitDefs[0], RC, RC); 983 if (!InsertedCopy) 984 ResultReg = 0; 985 } 986 return ResultReg; 987} 988 989unsigned FastISel::FastEmitInst_i(unsigned MachineInstOpcode, 990 const TargetRegisterClass *RC, 991 uint64_t Imm) { 992 unsigned ResultReg = createResultReg(RC); 993 const TargetInstrDesc &II = TII.get(MachineInstOpcode); 994 995 if (II.getNumDefs() >= 1) 996 BuildMI(MBB, DL, II, ResultReg).addImm(Imm); 997 else { 998 BuildMI(MBB, DL, II).addImm(Imm); 999 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 1000 II.ImplicitDefs[0], RC, RC); 1001 if (!InsertedCopy) 1002 ResultReg = 0; 1003 } 1004 return ResultReg; 1005} 1006 1007unsigned FastISel::FastEmitInst_extractsubreg(MVT RetVT, 1008 unsigned Op0, uint32_t Idx) { 1009 const TargetRegisterClass* RC = MRI.getRegClass(Op0); 1010 1011 unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT)); 1012 const TargetInstrDesc &II = TII.get(TargetOpcode::EXTRACT_SUBREG); 1013 1014 if (II.getNumDefs() >= 1) 1015 BuildMI(MBB, DL, II, ResultReg).addReg(Op0).addImm(Idx); 1016 else { 1017 BuildMI(MBB, DL, II).addReg(Op0).addImm(Idx); 1018 bool InsertedCopy = TII.copyRegToReg(*MBB, MBB->end(), ResultReg, 1019 II.ImplicitDefs[0], RC, RC); 1020 if (!InsertedCopy) 1021 ResultReg = 0; 1022 } 1023 return ResultReg; 1024} 1025 1026/// FastEmitZExtFromI1 - Emit MachineInstrs to compute the value of Op 1027/// with all but the least significant bit set to zero. 1028unsigned FastISel::FastEmitZExtFromI1(MVT VT, unsigned Op) { 1029 return FastEmit_ri(VT, VT, ISD::AND, Op, 1); 1030} 1031 1032/// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks. 1033/// Emit code to ensure constants are copied into registers when needed. 1034/// Remember the virtual registers that need to be added to the Machine PHI 1035/// nodes as input. We cannot just directly add them, because expansion 1036/// might result in multiple MBB's for one BB. As such, the start of the 1037/// BB might correspond to a different MBB than the end. 1038bool FastISel::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 1039 const TerminatorInst *TI = LLVMBB->getTerminator(); 1040 1041 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 1042 unsigned OrigNumPHINodesToUpdate = PHINodesToUpdate.size(); 1043 1044 // Check successor nodes' PHI nodes that expect a constant to be available 1045 // from this block. 1046 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 1047 const BasicBlock *SuccBB = TI->getSuccessor(succ); 1048 if (!isa<PHINode>(SuccBB->begin())) continue; 1049 MachineBasicBlock *SuccMBB = MBBMap[SuccBB]; 1050 1051 // If this terminator has multiple identical successors (common for 1052 // switches), only handle each succ once. 1053 if (!SuccsHandled.insert(SuccMBB)) continue; 1054 1055 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 1056 1057 // At this point we know that there is a 1-1 correspondence between LLVM PHI 1058 // nodes and Machine PHI nodes, but the incoming operands have not been 1059 // emitted yet. 1060 for (BasicBlock::const_iterator I = SuccBB->begin(); 1061 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 1062 // Ignore dead phi's. 1063 if (PN->use_empty()) continue; 1064 1065 // Only handle legal types. Two interesting things to note here. First, 1066 // by bailing out early, we may leave behind some dead instructions, 1067 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its 1068 // own moves. Second, this check is necessary becuase FastISel doesn't 1069 // use CreateRegForValue to create registers, so it always creates 1070 // exactly one register for each non-void instruction. 1071 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true); 1072 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) { 1073 // Promote MVT::i1. 1074 if (VT == MVT::i1) 1075 VT = TLI.getTypeToTransformTo(LLVMBB->getContext(), VT); 1076 else { 1077 PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 1078 return false; 1079 } 1080 } 1081 1082 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 1083 1084 unsigned Reg = getRegForValue(PHIOp); 1085 if (Reg == 0) { 1086 PHINodesToUpdate.resize(OrigNumPHINodesToUpdate); 1087 return false; 1088 } 1089 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg)); 1090 } 1091 } 1092 1093 return true; 1094} 1095