1 //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===// 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 defines the X86-specific support for the FastISel class. Much 11 // of the target-specific code is generated by tablegen in the file 12 // X86GenFastISel.inc, which is #included here. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "X86.h" 17 #include "X86ISelLowering.h" 18 #include "X86InstrBuilder.h" 19 #include "X86RegisterInfo.h" 20 #include "X86Subtarget.h" 21 #include "X86TargetMachine.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/FastISel.h" 24 #include "llvm/CodeGen/FunctionLoweringInfo.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/Support/CallSite.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/GetElementPtrTypeIterator.h" 38 #include "llvm/Target/TargetOptions.h" 39 using namespace llvm; 40 41 namespace { 42 43 class X86FastISel : public FastISel { 44 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can 45 /// make the right decision when generating code for different targets. 46 const X86Subtarget *Subtarget; 47 48 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 49 /// floating point ops. 50 /// When SSE is available, use it for f32 operations. 51 /// When SSE2 is available, use it for f64 operations. 52 bool X86ScalarSSEf64; 53 bool X86ScalarSSEf32; 54 55 public: 56 explicit X86FastISel(FunctionLoweringInfo &funcInfo, 57 const TargetLibraryInfo *libInfo) 58 : FastISel(funcInfo, libInfo) { 59 Subtarget = &TM.getSubtarget<X86Subtarget>(); 60 X86ScalarSSEf64 = Subtarget->hasSSE2(); 61 X86ScalarSSEf32 = Subtarget->hasSSE1(); 62 } 63 64 virtual bool TargetSelectInstruction(const Instruction *I); 65 66 /// \brief The specified machine instr operand is a vreg, and that 67 /// vreg is being provided by the specified load instruction. If possible, 68 /// try to fold the load as an operand to the instruction, returning true if 69 /// possible. 70 virtual bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 71 const LoadInst *LI); 72 73 virtual bool FastLowerArguments(); 74 75 #include "X86GenFastISel.inc" 76 77 private: 78 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT); 79 80 bool X86FastEmitLoad(EVT VT, const X86AddressMode &AM, unsigned &RR); 81 82 bool X86FastEmitStore(EVT VT, const Value *Val, const X86AddressMode &AM, 83 bool Aligned = false); 84 bool X86FastEmitStore(EVT VT, unsigned ValReg, const X86AddressMode &AM, 85 bool Aligned = false); 86 87 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT, 88 unsigned &ResultReg); 89 90 bool X86SelectAddress(const Value *V, X86AddressMode &AM); 91 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM); 92 93 bool X86SelectLoad(const Instruction *I); 94 95 bool X86SelectStore(const Instruction *I); 96 97 bool X86SelectRet(const Instruction *I); 98 99 bool X86SelectCmp(const Instruction *I); 100 101 bool X86SelectZExt(const Instruction *I); 102 103 bool X86SelectBranch(const Instruction *I); 104 105 bool X86SelectShift(const Instruction *I); 106 107 bool X86SelectDivRem(const Instruction *I); 108 109 bool X86SelectSelect(const Instruction *I); 110 111 bool X86SelectTrunc(const Instruction *I); 112 113 bool X86SelectFPExt(const Instruction *I); 114 bool X86SelectFPTrunc(const Instruction *I); 115 116 bool X86VisitIntrinsicCall(const IntrinsicInst &I); 117 bool X86SelectCall(const Instruction *I); 118 119 bool DoSelectCall(const Instruction *I, const char *MemIntName); 120 121 const X86InstrInfo *getInstrInfo() const { 122 return getTargetMachine()->getInstrInfo(); 123 } 124 const X86TargetMachine *getTargetMachine() const { 125 return static_cast<const X86TargetMachine *>(&TM); 126 } 127 128 bool handleConstantAddresses(const Value *V, X86AddressMode &AM); 129 130 unsigned TargetMaterializeConstant(const Constant *C); 131 132 unsigned TargetMaterializeAlloca(const AllocaInst *C); 133 134 unsigned TargetMaterializeFloatZero(const ConstantFP *CF); 135 136 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is 137 /// computed in an SSE register, not on the X87 floating point stack. 138 bool isScalarFPTypeInSSEReg(EVT VT) const { 139 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2 140 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1 141 } 142 143 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false); 144 145 bool IsMemcpySmall(uint64_t Len); 146 147 bool TryEmitSmallMemcpy(X86AddressMode DestAM, 148 X86AddressMode SrcAM, uint64_t Len); 149 }; 150 151 } // end anonymous namespace. 152 153 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) { 154 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true); 155 if (evt == MVT::Other || !evt.isSimple()) 156 // Unhandled type. Halt "fast" selection and bail. 157 return false; 158 159 VT = evt.getSimpleVT(); 160 // For now, require SSE/SSE2 for performing floating-point operations, 161 // since x87 requires additional work. 162 if (VT == MVT::f64 && !X86ScalarSSEf64) 163 return false; 164 if (VT == MVT::f32 && !X86ScalarSSEf32) 165 return false; 166 // Similarly, no f80 support yet. 167 if (VT == MVT::f80) 168 return false; 169 // We only handle legal types. For example, on x86-32 the instruction 170 // selector contains all of the 64-bit instructions from x86-64, 171 // under the assumption that i64 won't be used if the target doesn't 172 // support it. 173 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT); 174 } 175 176 #include "X86GenCallingConv.inc" 177 178 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT. 179 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV. 180 /// Return true and the result register by reference if it is possible. 181 bool X86FastISel::X86FastEmitLoad(EVT VT, const X86AddressMode &AM, 182 unsigned &ResultReg) { 183 // Get opcode and regclass of the output for the given load instruction. 184 unsigned Opc = 0; 185 const TargetRegisterClass *RC = NULL; 186 switch (VT.getSimpleVT().SimpleTy) { 187 default: return false; 188 case MVT::i1: 189 case MVT::i8: 190 Opc = X86::MOV8rm; 191 RC = &X86::GR8RegClass; 192 break; 193 case MVT::i16: 194 Opc = X86::MOV16rm; 195 RC = &X86::GR16RegClass; 196 break; 197 case MVT::i32: 198 Opc = X86::MOV32rm; 199 RC = &X86::GR32RegClass; 200 break; 201 case MVT::i64: 202 // Must be in x86-64 mode. 203 Opc = X86::MOV64rm; 204 RC = &X86::GR64RegClass; 205 break; 206 case MVT::f32: 207 if (X86ScalarSSEf32) { 208 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 209 RC = &X86::FR32RegClass; 210 } else { 211 Opc = X86::LD_Fp32m; 212 RC = &X86::RFP32RegClass; 213 } 214 break; 215 case MVT::f64: 216 if (X86ScalarSSEf64) { 217 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 218 RC = &X86::FR64RegClass; 219 } else { 220 Opc = X86::LD_Fp64m; 221 RC = &X86::RFP64RegClass; 222 } 223 break; 224 case MVT::f80: 225 // No f80 support yet. 226 return false; 227 } 228 229 ResultReg = createResultReg(RC); 230 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 231 DL, TII.get(Opc), ResultReg), AM); 232 return true; 233 } 234 235 /// X86FastEmitStore - Emit a machine instruction to store a value Val of 236 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr 237 /// and a displacement offset, or a GlobalAddress, 238 /// i.e. V. Return true if it is possible. 239 bool 240 X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, 241 const X86AddressMode &AM, bool Aligned) { 242 // Get opcode and regclass of the output for the given store instruction. 243 unsigned Opc = 0; 244 switch (VT.getSimpleVT().SimpleTy) { 245 case MVT::f80: // No f80 support yet. 246 default: return false; 247 case MVT::i1: { 248 // Mask out all but lowest bit. 249 unsigned AndResult = createResultReg(&X86::GR8RegClass); 250 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 251 TII.get(X86::AND8ri), AndResult).addReg(ValReg).addImm(1); 252 ValReg = AndResult; 253 } 254 // FALLTHROUGH, handling i1 as i8. 255 case MVT::i8: Opc = X86::MOV8mr; break; 256 case MVT::i16: Opc = X86::MOV16mr; break; 257 case MVT::i32: Opc = X86::MOV32mr; break; 258 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode. 259 case MVT::f32: 260 Opc = X86ScalarSSEf32 ? 261 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m; 262 break; 263 case MVT::f64: 264 Opc = X86ScalarSSEf64 ? 265 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m; 266 break; 267 case MVT::v4f32: 268 if (Aligned) 269 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 270 else 271 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr; 272 break; 273 case MVT::v2f64: 274 if (Aligned) 275 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr; 276 else 277 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr; 278 break; 279 case MVT::v4i32: 280 case MVT::v2i64: 281 case MVT::v8i16: 282 case MVT::v16i8: 283 if (Aligned) 284 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr; 285 else 286 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr; 287 break; 288 } 289 290 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 291 DL, TII.get(Opc)), AM).addReg(ValReg); 292 return true; 293 } 294 295 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val, 296 const X86AddressMode &AM, bool Aligned) { 297 // Handle 'null' like i32/i64 0. 298 if (isa<ConstantPointerNull>(Val)) 299 Val = Constant::getNullValue(TD.getIntPtrType(Val->getContext())); 300 301 // If this is a store of a simple constant, fold the constant into the store. 302 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 303 unsigned Opc = 0; 304 bool Signed = true; 305 switch (VT.getSimpleVT().SimpleTy) { 306 default: break; 307 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8. 308 case MVT::i8: Opc = X86::MOV8mi; break; 309 case MVT::i16: Opc = X86::MOV16mi; break; 310 case MVT::i32: Opc = X86::MOV32mi; break; 311 case MVT::i64: 312 // Must be a 32-bit sign extended value. 313 if (isInt<32>(CI->getSExtValue())) 314 Opc = X86::MOV64mi32; 315 break; 316 } 317 318 if (Opc) { 319 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, 320 DL, TII.get(Opc)), AM) 321 .addImm(Signed ? (uint64_t) CI->getSExtValue() : 322 CI->getZExtValue()); 323 return true; 324 } 325 } 326 327 unsigned ValReg = getRegForValue(Val); 328 if (ValReg == 0) 329 return false; 330 331 return X86FastEmitStore(VT, ValReg, AM, Aligned); 332 } 333 334 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of 335 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g. 336 /// ISD::SIGN_EXTEND). 337 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, 338 unsigned Src, EVT SrcVT, 339 unsigned &ResultReg) { 340 unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, 341 Src, /*TODO: Kill=*/false); 342 if (RR == 0) 343 return false; 344 345 ResultReg = RR; 346 return true; 347 } 348 349 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) { 350 // Handle constant address. 351 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 352 // Can't handle alternate code models yet. 353 if (TM.getCodeModel() != CodeModel::Small) 354 return false; 355 356 // Can't handle TLS yet. 357 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 358 if (GVar->isThreadLocal()) 359 return false; 360 361 // Can't handle TLS yet, part 2 (this is slightly crazy, but this is how 362 // it works...). 363 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 364 if (const GlobalVariable *GVar = 365 dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false))) 366 if (GVar->isThreadLocal()) 367 return false; 368 369 // RIP-relative addresses can't have additional register operands, so if 370 // we've already folded stuff into the addressing mode, just force the 371 // global value into its own register, which we can use as the basereg. 372 if (!Subtarget->isPICStyleRIPRel() || 373 (AM.Base.Reg == 0 && AM.IndexReg == 0)) { 374 // Okay, we've committed to selecting this global. Set up the address. 375 AM.GV = GV; 376 377 // Allow the subtarget to classify the global. 378 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM); 379 380 // If this reference is relative to the pic base, set it now. 381 if (isGlobalRelativeToPICBase(GVFlags)) { 382 // FIXME: How do we know Base.Reg is free?? 383 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 384 } 385 386 // Unless the ABI requires an extra load, return a direct reference to 387 // the global. 388 if (!isGlobalStubReference(GVFlags)) { 389 if (Subtarget->isPICStyleRIPRel()) { 390 // Use rip-relative addressing if we can. Above we verified that the 391 // base and index registers are unused. 392 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 393 AM.Base.Reg = X86::RIP; 394 } 395 AM.GVOpFlags = GVFlags; 396 return true; 397 } 398 399 // Ok, we need to do a load from a stub. If we've already loaded from 400 // this stub, reuse the loaded pointer, otherwise emit the load now. 401 DenseMap<const Value*, unsigned>::iterator I = LocalValueMap.find(V); 402 unsigned LoadReg; 403 if (I != LocalValueMap.end() && I->second != 0) { 404 LoadReg = I->second; 405 } else { 406 // Issue load from stub. 407 unsigned Opc = 0; 408 const TargetRegisterClass *RC = NULL; 409 X86AddressMode StubAM; 410 StubAM.Base.Reg = AM.Base.Reg; 411 StubAM.GV = GV; 412 StubAM.GVOpFlags = GVFlags; 413 414 // Prepare for inserting code in the local-value area. 415 SavePoint SaveInsertPt = enterLocalValueArea(); 416 417 if (TLI.getPointerTy() == MVT::i64) { 418 Opc = X86::MOV64rm; 419 RC = &X86::GR64RegClass; 420 421 if (Subtarget->isPICStyleRIPRel()) 422 StubAM.Base.Reg = X86::RIP; 423 } else { 424 Opc = X86::MOV32rm; 425 RC = &X86::GR32RegClass; 426 } 427 428 LoadReg = createResultReg(RC); 429 MachineInstrBuilder LoadMI = 430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), LoadReg); 431 addFullAddress(LoadMI, StubAM); 432 433 // Ok, back to normal mode. 434 leaveLocalValueArea(SaveInsertPt); 435 436 // Prevent loading GV stub multiple times in same MBB. 437 LocalValueMap[V] = LoadReg; 438 } 439 440 // Now construct the final address. Note that the Disp, Scale, 441 // and Index values may already be set here. 442 AM.Base.Reg = LoadReg; 443 AM.GV = 0; 444 return true; 445 } 446 } 447 448 // If all else fails, try to materialize the value in a register. 449 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 450 if (AM.Base.Reg == 0) { 451 AM.Base.Reg = getRegForValue(V); 452 return AM.Base.Reg != 0; 453 } 454 if (AM.IndexReg == 0) { 455 assert(AM.Scale == 1 && "Scale with no index!"); 456 AM.IndexReg = getRegForValue(V); 457 return AM.IndexReg != 0; 458 } 459 } 460 461 return false; 462 } 463 464 /// X86SelectAddress - Attempt to fill in an address from the given value. 465 /// 466 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) { 467 SmallVector<const Value *, 32> GEPs; 468 redo_gep: 469 const User *U = NULL; 470 unsigned Opcode = Instruction::UserOp1; 471 if (const Instruction *I = dyn_cast<Instruction>(V)) { 472 // Don't walk into other basic blocks; it's possible we haven't 473 // visited them yet, so the instructions may not yet be assigned 474 // virtual registers. 475 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) || 476 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) { 477 Opcode = I->getOpcode(); 478 U = I; 479 } 480 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 481 Opcode = C->getOpcode(); 482 U = C; 483 } 484 485 if (PointerType *Ty = dyn_cast<PointerType>(V->getType())) 486 if (Ty->getAddressSpace() > 255) 487 // Fast instruction selection doesn't support the special 488 // address spaces. 489 return false; 490 491 switch (Opcode) { 492 default: break; 493 case Instruction::BitCast: 494 // Look past bitcasts. 495 return X86SelectAddress(U->getOperand(0), AM); 496 497 case Instruction::IntToPtr: 498 // Look past no-op inttoptrs. 499 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 500 return X86SelectAddress(U->getOperand(0), AM); 501 break; 502 503 case Instruction::PtrToInt: 504 // Look past no-op ptrtoints. 505 if (TLI.getValueType(U->getType()) == TLI.getPointerTy()) 506 return X86SelectAddress(U->getOperand(0), AM); 507 break; 508 509 case Instruction::Alloca: { 510 // Do static allocas. 511 const AllocaInst *A = cast<AllocaInst>(V); 512 DenseMap<const AllocaInst*, int>::iterator SI = 513 FuncInfo.StaticAllocaMap.find(A); 514 if (SI != FuncInfo.StaticAllocaMap.end()) { 515 AM.BaseType = X86AddressMode::FrameIndexBase; 516 AM.Base.FrameIndex = SI->second; 517 return true; 518 } 519 break; 520 } 521 522 case Instruction::Add: { 523 // Adds of constants are common and easy enough. 524 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 525 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue(); 526 // They have to fit in the 32-bit signed displacement field though. 527 if (isInt<32>(Disp)) { 528 AM.Disp = (uint32_t)Disp; 529 return X86SelectAddress(U->getOperand(0), AM); 530 } 531 } 532 break; 533 } 534 535 case Instruction::GetElementPtr: { 536 X86AddressMode SavedAM = AM; 537 538 // Pattern-match simple GEPs. 539 uint64_t Disp = (int32_t)AM.Disp; 540 unsigned IndexReg = AM.IndexReg; 541 unsigned Scale = AM.Scale; 542 gep_type_iterator GTI = gep_type_begin(U); 543 // Iterate through the indices, folding what we can. Constants can be 544 // folded, and one dynamic index can be handled, if the scale is supported. 545 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); 546 i != e; ++i, ++GTI) { 547 const Value *Op = *i; 548 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 549 const StructLayout *SL = TD.getStructLayout(STy); 550 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue()); 551 continue; 552 } 553 554 // A array/variable index is always of the form i*S where S is the 555 // constant scale size. See if we can push the scale into immediates. 556 uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType()); 557 for (;;) { 558 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 559 // Constant-offset addressing. 560 Disp += CI->getSExtValue() * S; 561 break; 562 } 563 if (isa<AddOperator>(Op) && 564 (!isa<Instruction>(Op) || 565 FuncInfo.MBBMap[cast<Instruction>(Op)->getParent()] 566 == FuncInfo.MBB) && 567 isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) { 568 // An add (in the same block) with a constant operand. Fold the 569 // constant. 570 ConstantInt *CI = 571 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1)); 572 Disp += CI->getSExtValue() * S; 573 // Iterate on the other operand. 574 Op = cast<AddOperator>(Op)->getOperand(0); 575 continue; 576 } 577 if (IndexReg == 0 && 578 (!AM.GV || !Subtarget->isPICStyleRIPRel()) && 579 (S == 1 || S == 2 || S == 4 || S == 8)) { 580 // Scaled-index addressing. 581 Scale = S; 582 IndexReg = getRegForGEPIndex(Op).first; 583 if (IndexReg == 0) 584 return false; 585 break; 586 } 587 // Unsupported. 588 goto unsupported_gep; 589 } 590 } 591 592 // Check for displacement overflow. 593 if (!isInt<32>(Disp)) 594 break; 595 596 AM.IndexReg = IndexReg; 597 AM.Scale = Scale; 598 AM.Disp = (uint32_t)Disp; 599 GEPs.push_back(V); 600 601 if (const GetElementPtrInst *GEP = 602 dyn_cast<GetElementPtrInst>(U->getOperand(0))) { 603 // Ok, the GEP indices were covered by constant-offset and scaled-index 604 // addressing. Update the address state and move on to examining the base. 605 V = GEP; 606 goto redo_gep; 607 } else if (X86SelectAddress(U->getOperand(0), AM)) { 608 return true; 609 } 610 611 // If we couldn't merge the gep value into this addr mode, revert back to 612 // our address and just match the value instead of completely failing. 613 AM = SavedAM; 614 615 for (SmallVectorImpl<const Value *>::reverse_iterator 616 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I) 617 if (handleConstantAddresses(*I, AM)) 618 return true; 619 620 return false; 621 unsupported_gep: 622 // Ok, the GEP indices weren't all covered. 623 break; 624 } 625 } 626 627 return handleConstantAddresses(V, AM); 628 } 629 630 /// X86SelectCallAddress - Attempt to fill in an address from the given value. 631 /// 632 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) { 633 const User *U = NULL; 634 unsigned Opcode = Instruction::UserOp1; 635 const Instruction *I = dyn_cast<Instruction>(V); 636 bool InMBB = true; 637 if (I) { 638 Opcode = I->getOpcode(); 639 U = I; 640 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock(); 641 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 642 Opcode = C->getOpcode(); 643 U = C; 644 } 645 646 switch (Opcode) { 647 default: break; 648 case Instruction::BitCast: 649 // Look past bitcasts if its operand is in the same BB. 650 if (InMBB) 651 return X86SelectCallAddress(U->getOperand(0), AM); 652 break; 653 654 case Instruction::IntToPtr: 655 // Look past no-op inttoptrs if its operand is in the same BB. 656 if (InMBB && 657 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy()) 658 return X86SelectCallAddress(U->getOperand(0), AM); 659 break; 660 661 case Instruction::PtrToInt: 662 // Look past no-op ptrtoints if its operand is in the same BB. 663 if (InMBB && 664 TLI.getValueType(U->getType()) == TLI.getPointerTy()) 665 return X86SelectCallAddress(U->getOperand(0), AM); 666 break; 667 } 668 669 // Handle constant address. 670 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 671 // Can't handle alternate code models yet. 672 if (TM.getCodeModel() != CodeModel::Small) 673 return false; 674 675 // RIP-relative addresses can't have additional register operands. 676 if (Subtarget->isPICStyleRIPRel() && 677 (AM.Base.Reg != 0 || AM.IndexReg != 0)) 678 return false; 679 680 // Can't handle DLLImport. 681 if (GV->hasDLLImportLinkage()) 682 return false; 683 684 // Can't handle TLS. 685 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 686 if (GVar->isThreadLocal()) 687 return false; 688 689 // Okay, we've committed to selecting this global. Set up the basic address. 690 AM.GV = GV; 691 692 // No ABI requires an extra load for anything other than DLLImport, which 693 // we rejected above. Return a direct reference to the global. 694 if (Subtarget->isPICStyleRIPRel()) { 695 // Use rip-relative addressing if we can. Above we verified that the 696 // base and index registers are unused. 697 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 698 AM.Base.Reg = X86::RIP; 699 } else if (Subtarget->isPICStyleStubPIC()) { 700 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET; 701 } else if (Subtarget->isPICStyleGOT()) { 702 AM.GVOpFlags = X86II::MO_GOTOFF; 703 } 704 705 return true; 706 } 707 708 // If all else fails, try to materialize the value in a register. 709 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 710 if (AM.Base.Reg == 0) { 711 AM.Base.Reg = getRegForValue(V); 712 return AM.Base.Reg != 0; 713 } 714 if (AM.IndexReg == 0) { 715 assert(AM.Scale == 1 && "Scale with no index!"); 716 AM.IndexReg = getRegForValue(V); 717 return AM.IndexReg != 0; 718 } 719 } 720 721 return false; 722 } 723 724 725 /// X86SelectStore - Select and emit code to implement store instructions. 726 bool X86FastISel::X86SelectStore(const Instruction *I) { 727 // Atomic stores need special handling. 728 const StoreInst *S = cast<StoreInst>(I); 729 730 if (S->isAtomic()) 731 return false; 732 733 unsigned SABIAlignment = 734 TD.getABITypeAlignment(S->getValueOperand()->getType()); 735 bool Aligned = S->getAlignment() == 0 || S->getAlignment() >= SABIAlignment; 736 737 MVT VT; 738 if (!isTypeLegal(I->getOperand(0)->getType(), VT, /*AllowI1=*/true)) 739 return false; 740 741 X86AddressMode AM; 742 if (!X86SelectAddress(I->getOperand(1), AM)) 743 return false; 744 745 return X86FastEmitStore(VT, I->getOperand(0), AM, Aligned); 746 } 747 748 /// X86SelectRet - Select and emit code to implement ret instructions. 749 bool X86FastISel::X86SelectRet(const Instruction *I) { 750 const ReturnInst *Ret = cast<ReturnInst>(I); 751 const Function &F = *I->getParent()->getParent(); 752 const X86MachineFunctionInfo *X86MFInfo = 753 FuncInfo.MF->getInfo<X86MachineFunctionInfo>(); 754 755 if (!FuncInfo.CanLowerReturn) 756 return false; 757 758 CallingConv::ID CC = F.getCallingConv(); 759 if (CC != CallingConv::C && 760 CC != CallingConv::Fast && 761 CC != CallingConv::X86_FastCall && 762 CC != CallingConv::X86_64_SysV) 763 return false; 764 765 if (Subtarget->isCallingConvWin64(CC)) 766 return false; 767 768 // Don't handle popping bytes on return for now. 769 if (X86MFInfo->getBytesToPopOnReturn() != 0) 770 return false; 771 772 // fastcc with -tailcallopt is intended to provide a guaranteed 773 // tail call optimization. Fastisel doesn't know how to do that. 774 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 775 return false; 776 777 // Let SDISel handle vararg functions. 778 if (F.isVarArg()) 779 return false; 780 781 // Build a list of return value registers. 782 SmallVector<unsigned, 4> RetRegs; 783 784 if (Ret->getNumOperands() > 0) { 785 SmallVector<ISD::OutputArg, 4> Outs; 786 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI); 787 788 // Analyze operands of the call, assigning locations to each operand. 789 SmallVector<CCValAssign, 16> ValLocs; 790 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, TM, ValLocs, 791 I->getContext()); 792 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 793 794 const Value *RV = Ret->getOperand(0); 795 unsigned Reg = getRegForValue(RV); 796 if (Reg == 0) 797 return false; 798 799 // Only handle a single return value for now. 800 if (ValLocs.size() != 1) 801 return false; 802 803 CCValAssign &VA = ValLocs[0]; 804 805 // Don't bother handling odd stuff for now. 806 if (VA.getLocInfo() != CCValAssign::Full) 807 return false; 808 // Only handle register returns for now. 809 if (!VA.isRegLoc()) 810 return false; 811 812 // The calling-convention tables for x87 returns don't tell 813 // the whole story. 814 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 815 return false; 816 817 unsigned SrcReg = Reg + VA.getValNo(); 818 EVT SrcVT = TLI.getValueType(RV->getType()); 819 EVT DstVT = VA.getValVT(); 820 // Special handling for extended integers. 821 if (SrcVT != DstVT) { 822 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16) 823 return false; 824 825 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt()) 826 return false; 827 828 assert(DstVT == MVT::i32 && "X86 should always ext to i32"); 829 830 if (SrcVT == MVT::i1) { 831 if (Outs[0].Flags.isSExt()) 832 return false; 833 SrcReg = FastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false); 834 SrcVT = MVT::i8; 835 } 836 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : 837 ISD::SIGN_EXTEND; 838 SrcReg = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, 839 SrcReg, /*TODO: Kill=*/false); 840 } 841 842 // Make the copy. 843 unsigned DstReg = VA.getLocReg(); 844 const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg); 845 // Avoid a cross-class copy. This is very unlikely. 846 if (!SrcRC->contains(DstReg)) 847 return false; 848 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 849 DstReg).addReg(SrcReg); 850 851 // Add register to return instruction. 852 RetRegs.push_back(VA.getLocReg()); 853 } 854 855 // The x86-64 ABI for returning structs by value requires that we copy 856 // the sret argument into %rax for the return. We saved the argument into 857 // a virtual register in the entry block, so now we copy the value out 858 // and into %rax. We also do the same with %eax for Win32. 859 if (F.hasStructRetAttr() && 860 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 861 unsigned Reg = X86MFInfo->getSRetReturnReg(); 862 assert(Reg && 863 "SRetReturnReg should have been set in LowerFormalArguments()!"); 864 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 866 RetReg).addReg(Reg); 867 RetRegs.push_back(RetReg); 868 } 869 870 // Now emit the RET. 871 MachineInstrBuilder MIB = 872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::RET)); 873 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i) 874 MIB.addReg(RetRegs[i], RegState::Implicit); 875 return true; 876 } 877 878 /// X86SelectLoad - Select and emit code to implement load instructions. 879 /// 880 bool X86FastISel::X86SelectLoad(const Instruction *I) { 881 // Atomic loads need special handling. 882 if (cast<LoadInst>(I)->isAtomic()) 883 return false; 884 885 MVT VT; 886 if (!isTypeLegal(I->getType(), VT, /*AllowI1=*/true)) 887 return false; 888 889 X86AddressMode AM; 890 if (!X86SelectAddress(I->getOperand(0), AM)) 891 return false; 892 893 unsigned ResultReg = 0; 894 if (X86FastEmitLoad(VT, AM, ResultReg)) { 895 UpdateValueMap(I, ResultReg); 896 return true; 897 } 898 return false; 899 } 900 901 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) { 902 bool HasAVX = Subtarget->hasAVX(); 903 bool X86ScalarSSEf32 = Subtarget->hasSSE1(); 904 bool X86ScalarSSEf64 = Subtarget->hasSSE2(); 905 906 switch (VT.getSimpleVT().SimpleTy) { 907 default: return 0; 908 case MVT::i8: return X86::CMP8rr; 909 case MVT::i16: return X86::CMP16rr; 910 case MVT::i32: return X86::CMP32rr; 911 case MVT::i64: return X86::CMP64rr; 912 case MVT::f32: 913 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0; 914 case MVT::f64: 915 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0; 916 } 917 } 918 919 /// X86ChooseCmpImmediateOpcode - If we have a comparison with RHS as the RHS 920 /// of the comparison, return an opcode that works for the compare (e.g. 921 /// CMP32ri) otherwise return 0. 922 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) { 923 switch (VT.getSimpleVT().SimpleTy) { 924 // Otherwise, we can't fold the immediate into this comparison. 925 default: return 0; 926 case MVT::i8: return X86::CMP8ri; 927 case MVT::i16: return X86::CMP16ri; 928 case MVT::i32: return X86::CMP32ri; 929 case MVT::i64: 930 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext 931 // field. 932 if ((int)RHSC->getSExtValue() == RHSC->getSExtValue()) 933 return X86::CMP64ri32; 934 return 0; 935 } 936 } 937 938 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, 939 EVT VT) { 940 unsigned Op0Reg = getRegForValue(Op0); 941 if (Op0Reg == 0) return false; 942 943 // Handle 'null' like i32/i64 0. 944 if (isa<ConstantPointerNull>(Op1)) 945 Op1 = Constant::getNullValue(TD.getIntPtrType(Op0->getContext())); 946 947 // We have two options: compare with register or immediate. If the RHS of 948 // the compare is an immediate that we can fold into this compare, use 949 // CMPri, otherwise use CMPrr. 950 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 951 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) { 952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareImmOpc)) 953 .addReg(Op0Reg) 954 .addImm(Op1C->getSExtValue()); 955 return true; 956 } 957 } 958 959 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget); 960 if (CompareOpc == 0) return false; 961 962 unsigned Op1Reg = getRegForValue(Op1); 963 if (Op1Reg == 0) return false; 964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CompareOpc)) 965 .addReg(Op0Reg) 966 .addReg(Op1Reg); 967 968 return true; 969 } 970 971 bool X86FastISel::X86SelectCmp(const Instruction *I) { 972 const CmpInst *CI = cast<CmpInst>(I); 973 974 MVT VT; 975 if (!isTypeLegal(I->getOperand(0)->getType(), VT)) 976 return false; 977 978 unsigned ResultReg = createResultReg(&X86::GR8RegClass); 979 unsigned SetCCOpc; 980 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0. 981 switch (CI->getPredicate()) { 982 case CmpInst::FCMP_OEQ: { 983 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT)) 984 return false; 985 986 unsigned EReg = createResultReg(&X86::GR8RegClass); 987 unsigned NPReg = createResultReg(&X86::GR8RegClass); 988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETEr), EReg); 989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 990 TII.get(X86::SETNPr), NPReg); 991 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 992 TII.get(X86::AND8rr), ResultReg).addReg(NPReg).addReg(EReg); 993 UpdateValueMap(I, ResultReg); 994 return true; 995 } 996 case CmpInst::FCMP_UNE: { 997 if (!X86FastEmitCompare(CI->getOperand(0), CI->getOperand(1), VT)) 998 return false; 999 1000 unsigned NEReg = createResultReg(&X86::GR8RegClass); 1001 unsigned PReg = createResultReg(&X86::GR8RegClass); 1002 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETNEr), NEReg); 1003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SETPr), PReg); 1004 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::OR8rr),ResultReg) 1005 .addReg(PReg).addReg(NEReg); 1006 UpdateValueMap(I, ResultReg); 1007 return true; 1008 } 1009 case CmpInst::FCMP_OGT: SwapArgs = false; SetCCOpc = X86::SETAr; break; 1010 case CmpInst::FCMP_OGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break; 1011 case CmpInst::FCMP_OLT: SwapArgs = true; SetCCOpc = X86::SETAr; break; 1012 case CmpInst::FCMP_OLE: SwapArgs = true; SetCCOpc = X86::SETAEr; break; 1013 case CmpInst::FCMP_ONE: SwapArgs = false; SetCCOpc = X86::SETNEr; break; 1014 case CmpInst::FCMP_ORD: SwapArgs = false; SetCCOpc = X86::SETNPr; break; 1015 case CmpInst::FCMP_UNO: SwapArgs = false; SetCCOpc = X86::SETPr; break; 1016 case CmpInst::FCMP_UEQ: SwapArgs = false; SetCCOpc = X86::SETEr; break; 1017 case CmpInst::FCMP_UGT: SwapArgs = true; SetCCOpc = X86::SETBr; break; 1018 case CmpInst::FCMP_UGE: SwapArgs = true; SetCCOpc = X86::SETBEr; break; 1019 case CmpInst::FCMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break; 1020 case CmpInst::FCMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break; 1021 1022 case CmpInst::ICMP_EQ: SwapArgs = false; SetCCOpc = X86::SETEr; break; 1023 case CmpInst::ICMP_NE: SwapArgs = false; SetCCOpc = X86::SETNEr; break; 1024 case CmpInst::ICMP_UGT: SwapArgs = false; SetCCOpc = X86::SETAr; break; 1025 case CmpInst::ICMP_UGE: SwapArgs = false; SetCCOpc = X86::SETAEr; break; 1026 case CmpInst::ICMP_ULT: SwapArgs = false; SetCCOpc = X86::SETBr; break; 1027 case CmpInst::ICMP_ULE: SwapArgs = false; SetCCOpc = X86::SETBEr; break; 1028 case CmpInst::ICMP_SGT: SwapArgs = false; SetCCOpc = X86::SETGr; break; 1029 case CmpInst::ICMP_SGE: SwapArgs = false; SetCCOpc = X86::SETGEr; break; 1030 case CmpInst::ICMP_SLT: SwapArgs = false; SetCCOpc = X86::SETLr; break; 1031 case CmpInst::ICMP_SLE: SwapArgs = false; SetCCOpc = X86::SETLEr; break; 1032 default: 1033 return false; 1034 } 1035 1036 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 1037 if (SwapArgs) 1038 std::swap(Op0, Op1); 1039 1040 // Emit a compare of Op0/Op1. 1041 if (!X86FastEmitCompare(Op0, Op1, VT)) 1042 return false; 1043 1044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(SetCCOpc), ResultReg); 1045 UpdateValueMap(I, ResultReg); 1046 return true; 1047 } 1048 1049 bool X86FastISel::X86SelectZExt(const Instruction *I) { 1050 EVT DstVT = TLI.getValueType(I->getType()); 1051 if (!TLI.isTypeLegal(DstVT)) 1052 return false; 1053 1054 unsigned ResultReg = getRegForValue(I->getOperand(0)); 1055 if (ResultReg == 0) 1056 return false; 1057 1058 // Handle zero-extension from i1 to i8, which is common. 1059 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType()); 1060 if (SrcVT.SimpleTy == MVT::i1) { 1061 // Set the high bits to zero. 1062 ResultReg = FastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false); 1063 SrcVT = MVT::i8; 1064 1065 if (ResultReg == 0) 1066 return false; 1067 } 1068 1069 if (DstVT == MVT::i64) { 1070 // Handle extension to 64-bits via sub-register shenanigans. 1071 unsigned MovInst; 1072 1073 switch (SrcVT.SimpleTy) { 1074 case MVT::i8: MovInst = X86::MOVZX32rr8; break; 1075 case MVT::i16: MovInst = X86::MOVZX32rr16; break; 1076 case MVT::i32: MovInst = X86::MOV32rr; break; 1077 default: llvm_unreachable("Unexpected zext to i64 source type"); 1078 } 1079 1080 unsigned Result32 = createResultReg(&X86::GR32RegClass); 1081 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovInst), Result32) 1082 .addReg(ResultReg); 1083 1084 ResultReg = createResultReg(&X86::GR64RegClass); 1085 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::SUBREG_TO_REG), 1086 ResultReg) 1087 .addImm(0).addReg(Result32).addImm(X86::sub_32bit); 1088 } else if (DstVT != MVT::i8) { 1089 ResultReg = FastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND, 1090 ResultReg, /*Kill=*/true); 1091 if (ResultReg == 0) 1092 return false; 1093 } 1094 1095 UpdateValueMap(I, ResultReg); 1096 return true; 1097 } 1098 1099 1100 bool X86FastISel::X86SelectBranch(const Instruction *I) { 1101 // Unconditional branches are selected by tablegen-generated code. 1102 // Handle a conditional branch. 1103 const BranchInst *BI = cast<BranchInst>(I); 1104 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)]; 1105 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)]; 1106 1107 // Fold the common case of a conditional branch with a comparison 1108 // in the same block (values defined on other blocks may not have 1109 // initialized registers). 1110 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) { 1111 if (CI->hasOneUse() && CI->getParent() == I->getParent()) { 1112 EVT VT = TLI.getValueType(CI->getOperand(0)->getType()); 1113 1114 // Try to take advantage of fallthrough opportunities. 1115 CmpInst::Predicate Predicate = CI->getPredicate(); 1116 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1117 std::swap(TrueMBB, FalseMBB); 1118 Predicate = CmpInst::getInversePredicate(Predicate); 1119 } 1120 1121 bool SwapArgs; // false -> compare Op0, Op1. true -> compare Op1, Op0. 1122 unsigned BranchOpc; // Opcode to jump on, e.g. "X86::JA" 1123 1124 switch (Predicate) { 1125 case CmpInst::FCMP_OEQ: 1126 std::swap(TrueMBB, FalseMBB); 1127 Predicate = CmpInst::FCMP_UNE; 1128 // FALL THROUGH 1129 case CmpInst::FCMP_UNE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1130 case CmpInst::FCMP_OGT: SwapArgs = false; BranchOpc = X86::JA_4; break; 1131 case CmpInst::FCMP_OGE: SwapArgs = false; BranchOpc = X86::JAE_4; break; 1132 case CmpInst::FCMP_OLT: SwapArgs = true; BranchOpc = X86::JA_4; break; 1133 case CmpInst::FCMP_OLE: SwapArgs = true; BranchOpc = X86::JAE_4; break; 1134 case CmpInst::FCMP_ONE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1135 case CmpInst::FCMP_ORD: SwapArgs = false; BranchOpc = X86::JNP_4; break; 1136 case CmpInst::FCMP_UNO: SwapArgs = false; BranchOpc = X86::JP_4; break; 1137 case CmpInst::FCMP_UEQ: SwapArgs = false; BranchOpc = X86::JE_4; break; 1138 case CmpInst::FCMP_UGT: SwapArgs = true; BranchOpc = X86::JB_4; break; 1139 case CmpInst::FCMP_UGE: SwapArgs = true; BranchOpc = X86::JBE_4; break; 1140 case CmpInst::FCMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break; 1141 case CmpInst::FCMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break; 1142 1143 case CmpInst::ICMP_EQ: SwapArgs = false; BranchOpc = X86::JE_4; break; 1144 case CmpInst::ICMP_NE: SwapArgs = false; BranchOpc = X86::JNE_4; break; 1145 case CmpInst::ICMP_UGT: SwapArgs = false; BranchOpc = X86::JA_4; break; 1146 case CmpInst::ICMP_UGE: SwapArgs = false; BranchOpc = X86::JAE_4; break; 1147 case CmpInst::ICMP_ULT: SwapArgs = false; BranchOpc = X86::JB_4; break; 1148 case CmpInst::ICMP_ULE: SwapArgs = false; BranchOpc = X86::JBE_4; break; 1149 case CmpInst::ICMP_SGT: SwapArgs = false; BranchOpc = X86::JG_4; break; 1150 case CmpInst::ICMP_SGE: SwapArgs = false; BranchOpc = X86::JGE_4; break; 1151 case CmpInst::ICMP_SLT: SwapArgs = false; BranchOpc = X86::JL_4; break; 1152 case CmpInst::ICMP_SLE: SwapArgs = false; BranchOpc = X86::JLE_4; break; 1153 default: 1154 return false; 1155 } 1156 1157 const Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1); 1158 if (SwapArgs) 1159 std::swap(Op0, Op1); 1160 1161 // Emit a compare of the LHS and RHS, setting the flags. 1162 if (!X86FastEmitCompare(Op0, Op1, VT)) 1163 return false; 1164 1165 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BranchOpc)) 1166 .addMBB(TrueMBB); 1167 1168 if (Predicate == CmpInst::FCMP_UNE) { 1169 // X86 requires a second branch to handle UNE (and OEQ, 1170 // which is mapped to UNE above). 1171 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JP_4)) 1172 .addMBB(TrueMBB); 1173 } 1174 1175 FastEmitBranch(FalseMBB, DL); 1176 FuncInfo.MBB->addSuccessor(TrueMBB); 1177 return true; 1178 } 1179 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) { 1180 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which 1181 // typically happen for _Bool and C++ bools. 1182 MVT SourceVT; 1183 if (TI->hasOneUse() && TI->getParent() == I->getParent() && 1184 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) { 1185 unsigned TestOpc = 0; 1186 switch (SourceVT.SimpleTy) { 1187 default: break; 1188 case MVT::i8: TestOpc = X86::TEST8ri; break; 1189 case MVT::i16: TestOpc = X86::TEST16ri; break; 1190 case MVT::i32: TestOpc = X86::TEST32ri; break; 1191 case MVT::i64: TestOpc = X86::TEST64ri32; break; 1192 } 1193 if (TestOpc) { 1194 unsigned OpReg = getRegForValue(TI->getOperand(0)); 1195 if (OpReg == 0) return false; 1196 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TestOpc)) 1197 .addReg(OpReg).addImm(1); 1198 1199 unsigned JmpOpc = X86::JNE_4; 1200 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1201 std::swap(TrueMBB, FalseMBB); 1202 JmpOpc = X86::JE_4; 1203 } 1204 1205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(JmpOpc)) 1206 .addMBB(TrueMBB); 1207 FastEmitBranch(FalseMBB, DL); 1208 FuncInfo.MBB->addSuccessor(TrueMBB); 1209 return true; 1210 } 1211 } 1212 } 1213 1214 // Otherwise do a clumsy setcc and re-test it. 1215 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used 1216 // in an explicit cast, so make sure to handle that correctly. 1217 unsigned OpReg = getRegForValue(BI->getCondition()); 1218 if (OpReg == 0) return false; 1219 1220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8ri)) 1221 .addReg(OpReg).addImm(1); 1222 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::JNE_4)) 1223 .addMBB(TrueMBB); 1224 FastEmitBranch(FalseMBB, DL); 1225 FuncInfo.MBB->addSuccessor(TrueMBB); 1226 return true; 1227 } 1228 1229 bool X86FastISel::X86SelectShift(const Instruction *I) { 1230 unsigned CReg = 0, OpReg = 0; 1231 const TargetRegisterClass *RC = NULL; 1232 if (I->getType()->isIntegerTy(8)) { 1233 CReg = X86::CL; 1234 RC = &X86::GR8RegClass; 1235 switch (I->getOpcode()) { 1236 case Instruction::LShr: OpReg = X86::SHR8rCL; break; 1237 case Instruction::AShr: OpReg = X86::SAR8rCL; break; 1238 case Instruction::Shl: OpReg = X86::SHL8rCL; break; 1239 default: return false; 1240 } 1241 } else if (I->getType()->isIntegerTy(16)) { 1242 CReg = X86::CX; 1243 RC = &X86::GR16RegClass; 1244 switch (I->getOpcode()) { 1245 case Instruction::LShr: OpReg = X86::SHR16rCL; break; 1246 case Instruction::AShr: OpReg = X86::SAR16rCL; break; 1247 case Instruction::Shl: OpReg = X86::SHL16rCL; break; 1248 default: return false; 1249 } 1250 } else if (I->getType()->isIntegerTy(32)) { 1251 CReg = X86::ECX; 1252 RC = &X86::GR32RegClass; 1253 switch (I->getOpcode()) { 1254 case Instruction::LShr: OpReg = X86::SHR32rCL; break; 1255 case Instruction::AShr: OpReg = X86::SAR32rCL; break; 1256 case Instruction::Shl: OpReg = X86::SHL32rCL; break; 1257 default: return false; 1258 } 1259 } else if (I->getType()->isIntegerTy(64)) { 1260 CReg = X86::RCX; 1261 RC = &X86::GR64RegClass; 1262 switch (I->getOpcode()) { 1263 case Instruction::LShr: OpReg = X86::SHR64rCL; break; 1264 case Instruction::AShr: OpReg = X86::SAR64rCL; break; 1265 case Instruction::Shl: OpReg = X86::SHL64rCL; break; 1266 default: return false; 1267 } 1268 } else { 1269 return false; 1270 } 1271 1272 MVT VT; 1273 if (!isTypeLegal(I->getType(), VT)) 1274 return false; 1275 1276 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1277 if (Op0Reg == 0) return false; 1278 1279 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1280 if (Op1Reg == 0) return false; 1281 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1282 CReg).addReg(Op1Reg); 1283 1284 // The shift instruction uses X86::CL. If we defined a super-register 1285 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here. 1286 if (CReg != X86::CL) 1287 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1288 TII.get(TargetOpcode::KILL), X86::CL) 1289 .addReg(CReg, RegState::Kill); 1290 1291 unsigned ResultReg = createResultReg(RC); 1292 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpReg), ResultReg) 1293 .addReg(Op0Reg); 1294 UpdateValueMap(I, ResultReg); 1295 return true; 1296 } 1297 1298 bool X86FastISel::X86SelectDivRem(const Instruction *I) { 1299 const static unsigned NumTypes = 4; // i8, i16, i32, i64 1300 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem 1301 const static bool S = true; // IsSigned 1302 const static bool U = false; // !IsSigned 1303 const static unsigned Copy = TargetOpcode::COPY; 1304 // For the X86 DIV/IDIV instruction, in most cases the dividend 1305 // (numerator) must be in a specific register pair highreg:lowreg, 1306 // producing the quotient in lowreg and the remainder in highreg. 1307 // For most data types, to set up the instruction, the dividend is 1308 // copied into lowreg, and lowreg is sign-extended or zero-extended 1309 // into highreg. The exception is i8, where the dividend is defined 1310 // as a single register rather than a register pair, and we 1311 // therefore directly sign-extend or zero-extend the dividend into 1312 // lowreg, instead of copying, and ignore the highreg. 1313 const static struct DivRemEntry { 1314 // The following portion depends only on the data type. 1315 const TargetRegisterClass *RC; 1316 unsigned LowInReg; // low part of the register pair 1317 unsigned HighInReg; // high part of the register pair 1318 // The following portion depends on both the data type and the operation. 1319 struct DivRemResult { 1320 unsigned OpDivRem; // The specific DIV/IDIV opcode to use. 1321 unsigned OpSignExtend; // Opcode for sign-extending lowreg into 1322 // highreg, or copying a zero into highreg. 1323 unsigned OpCopy; // Opcode for copying dividend into lowreg, or 1324 // zero/sign-extending into lowreg for i8. 1325 unsigned DivRemResultReg; // Register containing the desired result. 1326 bool IsOpSigned; // Whether to use signed or unsigned form. 1327 } ResultTable[NumOps]; 1328 } OpTable[NumTypes] = { 1329 { &X86::GR8RegClass, X86::AX, 0, { 1330 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv 1331 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem 1332 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv 1333 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem 1334 } 1335 }, // i8 1336 { &X86::GR16RegClass, X86::AX, X86::DX, { 1337 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv 1338 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem 1339 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv 1340 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem 1341 } 1342 }, // i16 1343 { &X86::GR32RegClass, X86::EAX, X86::EDX, { 1344 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv 1345 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem 1346 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv 1347 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem 1348 } 1349 }, // i32 1350 { &X86::GR64RegClass, X86::RAX, X86::RDX, { 1351 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv 1352 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem 1353 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv 1354 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem 1355 } 1356 }, // i64 1357 }; 1358 1359 MVT VT; 1360 if (!isTypeLegal(I->getType(), VT)) 1361 return false; 1362 1363 unsigned TypeIndex, OpIndex; 1364 switch (VT.SimpleTy) { 1365 default: return false; 1366 case MVT::i8: TypeIndex = 0; break; 1367 case MVT::i16: TypeIndex = 1; break; 1368 case MVT::i32: TypeIndex = 2; break; 1369 case MVT::i64: TypeIndex = 3; 1370 if (!Subtarget->is64Bit()) 1371 return false; 1372 break; 1373 } 1374 1375 switch (I->getOpcode()) { 1376 default: llvm_unreachable("Unexpected div/rem opcode"); 1377 case Instruction::SDiv: OpIndex = 0; break; 1378 case Instruction::SRem: OpIndex = 1; break; 1379 case Instruction::UDiv: OpIndex = 2; break; 1380 case Instruction::URem: OpIndex = 3; break; 1381 } 1382 1383 const DivRemEntry &TypeEntry = OpTable[TypeIndex]; 1384 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex]; 1385 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1386 if (Op0Reg == 0) 1387 return false; 1388 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1389 if (Op1Reg == 0) 1390 return false; 1391 1392 // Move op0 into low-order input register. 1393 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1394 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg); 1395 // Zero-extend or sign-extend into high-order input register. 1396 if (OpEntry.OpSignExtend) { 1397 if (OpEntry.IsOpSigned) 1398 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1399 TII.get(OpEntry.OpSignExtend)); 1400 else { 1401 unsigned Zero32 = createResultReg(&X86::GR32RegClass); 1402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1403 TII.get(X86::MOV32r0), Zero32); 1404 1405 // Copy the zero into the appropriate sub/super/identical physical 1406 // register. Unfortunately the operations needed are not uniform enough to 1407 // fit neatly into the table above. 1408 if (VT.SimpleTy == MVT::i16) { 1409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1410 TII.get(Copy), TypeEntry.HighInReg) 1411 .addReg(Zero32, 0, X86::sub_16bit); 1412 } else if (VT.SimpleTy == MVT::i32) { 1413 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1414 TII.get(Copy), TypeEntry.HighInReg) 1415 .addReg(Zero32); 1416 } else if (VT.SimpleTy == MVT::i64) { 1417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1418 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg) 1419 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit); 1420 } 1421 } 1422 } 1423 // Generate the DIV/IDIV instruction. 1424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1425 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg); 1426 // For i8 remainder, we can't reference AH directly, as we'll end 1427 // up with bogus copies like %R9B = COPY %AH. Reference AX 1428 // instead to prevent AH references in a REX instruction. 1429 // 1430 // The current assumption of the fast register allocator is that isel 1431 // won't generate explicit references to the GPR8_NOREX registers. If 1432 // the allocator and/or the backend get enhanced to be more robust in 1433 // that regard, this can be, and should be, removed. 1434 unsigned ResultReg = 0; 1435 if ((I->getOpcode() == Instruction::SRem || 1436 I->getOpcode() == Instruction::URem) && 1437 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) { 1438 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass); 1439 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass); 1440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1441 TII.get(Copy), SourceSuperReg).addReg(X86::AX); 1442 1443 // Shift AX right by 8 bits instead of using AH. 1444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::SHR16ri), 1445 ResultSuperReg).addReg(SourceSuperReg).addImm(8); 1446 1447 // Now reference the 8-bit subreg of the result. 1448 ResultReg = FastEmitInst_extractsubreg(MVT::i8, ResultSuperReg, 1449 /*Kill=*/true, X86::sub_8bit); 1450 } 1451 // Copy the result out of the physreg if we haven't already. 1452 if (!ResultReg) { 1453 ResultReg = createResultReg(TypeEntry.RC); 1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Copy), ResultReg) 1455 .addReg(OpEntry.DivRemResultReg); 1456 } 1457 UpdateValueMap(I, ResultReg); 1458 1459 return true; 1460 } 1461 1462 bool X86FastISel::X86SelectSelect(const Instruction *I) { 1463 MVT VT; 1464 if (!isTypeLegal(I->getType(), VT)) 1465 return false; 1466 1467 // We only use cmov here, if we don't have a cmov instruction bail. 1468 if (!Subtarget->hasCMov()) return false; 1469 1470 unsigned Opc = 0; 1471 const TargetRegisterClass *RC = NULL; 1472 if (VT == MVT::i16) { 1473 Opc = X86::CMOVE16rr; 1474 RC = &X86::GR16RegClass; 1475 } else if (VT == MVT::i32) { 1476 Opc = X86::CMOVE32rr; 1477 RC = &X86::GR32RegClass; 1478 } else if (VT == MVT::i64) { 1479 Opc = X86::CMOVE64rr; 1480 RC = &X86::GR64RegClass; 1481 } else { 1482 return false; 1483 } 1484 1485 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1486 if (Op0Reg == 0) return false; 1487 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1488 if (Op1Reg == 0) return false; 1489 unsigned Op2Reg = getRegForValue(I->getOperand(2)); 1490 if (Op2Reg == 0) return false; 1491 1492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TEST8rr)) 1493 .addReg(Op0Reg).addReg(Op0Reg); 1494 unsigned ResultReg = createResultReg(RC); 1495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg) 1496 .addReg(Op1Reg).addReg(Op2Reg); 1497 UpdateValueMap(I, ResultReg); 1498 return true; 1499 } 1500 1501 bool X86FastISel::X86SelectFPExt(const Instruction *I) { 1502 // fpext from float to double. 1503 if (X86ScalarSSEf64 && 1504 I->getType()->isDoubleTy()) { 1505 const Value *V = I->getOperand(0); 1506 if (V->getType()->isFloatTy()) { 1507 unsigned OpReg = getRegForValue(V); 1508 if (OpReg == 0) return false; 1509 unsigned ResultReg = createResultReg(&X86::FR64RegClass); 1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1511 TII.get(X86::CVTSS2SDrr), ResultReg) 1512 .addReg(OpReg); 1513 UpdateValueMap(I, ResultReg); 1514 return true; 1515 } 1516 } 1517 1518 return false; 1519 } 1520 1521 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) { 1522 if (X86ScalarSSEf64) { 1523 if (I->getType()->isFloatTy()) { 1524 const Value *V = I->getOperand(0); 1525 if (V->getType()->isDoubleTy()) { 1526 unsigned OpReg = getRegForValue(V); 1527 if (OpReg == 0) return false; 1528 unsigned ResultReg = createResultReg(&X86::FR32RegClass); 1529 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 1530 TII.get(X86::CVTSD2SSrr), ResultReg) 1531 .addReg(OpReg); 1532 UpdateValueMap(I, ResultReg); 1533 return true; 1534 } 1535 } 1536 } 1537 1538 return false; 1539 } 1540 1541 bool X86FastISel::X86SelectTrunc(const Instruction *I) { 1542 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 1543 EVT DstVT = TLI.getValueType(I->getType()); 1544 1545 // This code only handles truncation to byte. 1546 if (DstVT != MVT::i8 && DstVT != MVT::i1) 1547 return false; 1548 if (!TLI.isTypeLegal(SrcVT)) 1549 return false; 1550 1551 unsigned InputReg = getRegForValue(I->getOperand(0)); 1552 if (!InputReg) 1553 // Unhandled operand. Halt "fast" selection and bail. 1554 return false; 1555 1556 if (SrcVT == MVT::i8) { 1557 // Truncate from i8 to i1; no code needed. 1558 UpdateValueMap(I, InputReg); 1559 return true; 1560 } 1561 1562 if (!Subtarget->is64Bit()) { 1563 // If we're on x86-32; we can't extract an i8 from a general register. 1564 // First issue a copy to GR16_ABCD or GR32_ABCD. 1565 const TargetRegisterClass *CopyRC = (SrcVT == MVT::i16) ? 1566 (const TargetRegisterClass*)&X86::GR16_ABCDRegClass : 1567 (const TargetRegisterClass*)&X86::GR32_ABCDRegClass; 1568 unsigned CopyReg = createResultReg(CopyRC); 1569 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1570 CopyReg).addReg(InputReg); 1571 InputReg = CopyReg; 1572 } 1573 1574 // Issue an extract_subreg. 1575 unsigned ResultReg = FastEmitInst_extractsubreg(MVT::i8, 1576 InputReg, /*Kill=*/true, 1577 X86::sub_8bit); 1578 if (!ResultReg) 1579 return false; 1580 1581 UpdateValueMap(I, ResultReg); 1582 return true; 1583 } 1584 1585 bool X86FastISel::IsMemcpySmall(uint64_t Len) { 1586 return Len <= (Subtarget->is64Bit() ? 32 : 16); 1587 } 1588 1589 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM, 1590 X86AddressMode SrcAM, uint64_t Len) { 1591 1592 // Make sure we don't bloat code by inlining very large memcpy's. 1593 if (!IsMemcpySmall(Len)) 1594 return false; 1595 1596 bool i64Legal = Subtarget->is64Bit(); 1597 1598 // We don't care about alignment here since we just emit integer accesses. 1599 while (Len) { 1600 MVT VT; 1601 if (Len >= 8 && i64Legal) 1602 VT = MVT::i64; 1603 else if (Len >= 4) 1604 VT = MVT::i32; 1605 else if (Len >= 2) 1606 VT = MVT::i16; 1607 else { 1608 VT = MVT::i8; 1609 } 1610 1611 unsigned Reg; 1612 bool RV = X86FastEmitLoad(VT, SrcAM, Reg); 1613 RV &= X86FastEmitStore(VT, Reg, DestAM); 1614 assert(RV && "Failed to emit load or store??"); 1615 1616 unsigned Size = VT.getSizeInBits()/8; 1617 Len -= Size; 1618 DestAM.Disp += Size; 1619 SrcAM.Disp += Size; 1620 } 1621 1622 return true; 1623 } 1624 1625 bool X86FastISel::X86VisitIntrinsicCall(const IntrinsicInst &I) { 1626 // FIXME: Handle more intrinsics. 1627 switch (I.getIntrinsicID()) { 1628 default: return false; 1629 case Intrinsic::memcpy: { 1630 const MemCpyInst &MCI = cast<MemCpyInst>(I); 1631 // Don't handle volatile or variable length memcpys. 1632 if (MCI.isVolatile()) 1633 return false; 1634 1635 if (isa<ConstantInt>(MCI.getLength())) { 1636 // Small memcpy's are common enough that we want to do them 1637 // without a call if possible. 1638 uint64_t Len = cast<ConstantInt>(MCI.getLength())->getZExtValue(); 1639 if (IsMemcpySmall(Len)) { 1640 X86AddressMode DestAM, SrcAM; 1641 if (!X86SelectAddress(MCI.getRawDest(), DestAM) || 1642 !X86SelectAddress(MCI.getRawSource(), SrcAM)) 1643 return false; 1644 TryEmitSmallMemcpy(DestAM, SrcAM, Len); 1645 return true; 1646 } 1647 } 1648 1649 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 1650 if (!MCI.getLength()->getType()->isIntegerTy(SizeWidth)) 1651 return false; 1652 1653 if (MCI.getSourceAddressSpace() > 255 || MCI.getDestAddressSpace() > 255) 1654 return false; 1655 1656 return DoSelectCall(&I, "memcpy"); 1657 } 1658 case Intrinsic::memset: { 1659 const MemSetInst &MSI = cast<MemSetInst>(I); 1660 1661 if (MSI.isVolatile()) 1662 return false; 1663 1664 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 1665 if (!MSI.getLength()->getType()->isIntegerTy(SizeWidth)) 1666 return false; 1667 1668 if (MSI.getDestAddressSpace() > 255) 1669 return false; 1670 1671 return DoSelectCall(&I, "memset"); 1672 } 1673 case Intrinsic::stackprotector: { 1674 // Emit code to store the stack guard onto the stack. 1675 EVT PtrTy = TLI.getPointerTy(); 1676 1677 const Value *Op1 = I.getArgOperand(0); // The guard's value. 1678 const AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 1679 1680 // Grab the frame index. 1681 X86AddressMode AM; 1682 if (!X86SelectAddress(Slot, AM)) return false; 1683 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false; 1684 return true; 1685 } 1686 case Intrinsic::dbg_declare: { 1687 const DbgDeclareInst *DI = cast<DbgDeclareInst>(&I); 1688 X86AddressMode AM; 1689 assert(DI->getAddress() && "Null address should be checked earlier!"); 1690 if (!X86SelectAddress(DI->getAddress(), AM)) 1691 return false; 1692 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 1693 // FIXME may need to add RegState::Debug to any registers produced, 1694 // although ESP/EBP should be the only ones at the moment. 1695 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II), AM). 1696 addImm(0).addMetadata(DI->getVariable()); 1697 return true; 1698 } 1699 case Intrinsic::trap: { 1700 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::TRAP)); 1701 return true; 1702 } 1703 case Intrinsic::sadd_with_overflow: 1704 case Intrinsic::uadd_with_overflow: { 1705 // FIXME: Should fold immediates. 1706 1707 // Replace "add with overflow" intrinsics with an "add" instruction followed 1708 // by a seto/setc instruction. 1709 const Function *Callee = I.getCalledFunction(); 1710 Type *RetTy = 1711 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(unsigned(0)); 1712 1713 MVT VT; 1714 if (!isTypeLegal(RetTy, VT)) 1715 return false; 1716 1717 const Value *Op1 = I.getArgOperand(0); 1718 const Value *Op2 = I.getArgOperand(1); 1719 unsigned Reg1 = getRegForValue(Op1); 1720 unsigned Reg2 = getRegForValue(Op2); 1721 1722 if (Reg1 == 0 || Reg2 == 0) 1723 // FIXME: Handle values *not* in registers. 1724 return false; 1725 1726 unsigned OpC = 0; 1727 if (VT == MVT::i32) 1728 OpC = X86::ADD32rr; 1729 else if (VT == MVT::i64) 1730 OpC = X86::ADD64rr; 1731 else 1732 return false; 1733 1734 // The call to CreateRegs builds two sequential registers, to store the 1735 // both the returned values. 1736 unsigned ResultReg = FuncInfo.CreateRegs(I.getType()); 1737 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(OpC), ResultReg) 1738 .addReg(Reg1).addReg(Reg2); 1739 1740 unsigned Opc = X86::SETBr; 1741 if (I.getIntrinsicID() == Intrinsic::sadd_with_overflow) 1742 Opc = X86::SETOr; 1743 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg+1); 1744 1745 UpdateValueMap(&I, ResultReg, 2); 1746 return true; 1747 } 1748 } 1749 } 1750 1751 bool X86FastISel::FastLowerArguments() { 1752 if (!FuncInfo.CanLowerReturn) 1753 return false; 1754 1755 const Function *F = FuncInfo.Fn; 1756 if (F->isVarArg()) 1757 return false; 1758 1759 CallingConv::ID CC = F->getCallingConv(); 1760 if (CC != CallingConv::C) 1761 return false; 1762 1763 if (Subtarget->isCallingConvWin64(CC)) 1764 return false; 1765 1766 if (!Subtarget->is64Bit()) 1767 return false; 1768 1769 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments. 1770 unsigned Idx = 1; 1771 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1772 I != E; ++I, ++Idx) { 1773 if (Idx > 6) 1774 return false; 1775 1776 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) || 1777 F->getAttributes().hasAttribute(Idx, Attribute::InReg) || 1778 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) || 1779 F->getAttributes().hasAttribute(Idx, Attribute::Nest)) 1780 return false; 1781 1782 Type *ArgTy = I->getType(); 1783 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy()) 1784 return false; 1785 1786 EVT ArgVT = TLI.getValueType(ArgTy); 1787 if (!ArgVT.isSimple()) return false; 1788 switch (ArgVT.getSimpleVT().SimpleTy) { 1789 case MVT::i32: 1790 case MVT::i64: 1791 break; 1792 default: 1793 return false; 1794 } 1795 } 1796 1797 static const uint16_t GPR32ArgRegs[] = { 1798 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D 1799 }; 1800 static const uint16_t GPR64ArgRegs[] = { 1801 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9 1802 }; 1803 1804 Idx = 0; 1805 const TargetRegisterClass *RC32 = TLI.getRegClassFor(MVT::i32); 1806 const TargetRegisterClass *RC64 = TLI.getRegClassFor(MVT::i64); 1807 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 1808 I != E; ++I, ++Idx) { 1809 bool is32Bit = TLI.getValueType(I->getType()) == MVT::i32; 1810 const TargetRegisterClass *RC = is32Bit ? RC32 : RC64; 1811 unsigned SrcReg = is32Bit ? GPR32ArgRegs[Idx] : GPR64ArgRegs[Idx]; 1812 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC); 1813 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy. 1814 // Without this, EmitLiveInCopies may eliminate the livein if its only 1815 // use is a bitcast (which isn't turned into an instruction). 1816 unsigned ResultReg = createResultReg(RC); 1817 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 1818 ResultReg).addReg(DstReg, getKillRegState(true)); 1819 UpdateValueMap(I, ResultReg); 1820 } 1821 return true; 1822 } 1823 1824 bool X86FastISel::X86SelectCall(const Instruction *I) { 1825 const CallInst *CI = cast<CallInst>(I); 1826 const Value *Callee = CI->getCalledValue(); 1827 1828 // Can't handle inline asm yet. 1829 if (isa<InlineAsm>(Callee)) 1830 return false; 1831 1832 // Handle intrinsic calls. 1833 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) 1834 return X86VisitIntrinsicCall(*II); 1835 1836 // Allow SelectionDAG isel to handle tail calls. 1837 if (cast<CallInst>(I)->isTailCall()) 1838 return false; 1839 1840 return DoSelectCall(I, 0); 1841 } 1842 1843 static unsigned computeBytesPoppedByCallee(const X86Subtarget &Subtarget, 1844 const ImmutableCallSite &CS) { 1845 if (Subtarget.is64Bit()) 1846 return 0; 1847 if (Subtarget.isTargetWindows()) 1848 return 0; 1849 CallingConv::ID CC = CS.getCallingConv(); 1850 if (CC == CallingConv::Fast || CC == CallingConv::GHC) 1851 return 0; 1852 if (!CS.paramHasAttr(1, Attribute::StructRet)) 1853 return 0; 1854 if (CS.paramHasAttr(1, Attribute::InReg)) 1855 return 0; 1856 return 4; 1857 } 1858 1859 // Select either a call, or an llvm.memcpy/memmove/memset intrinsic 1860 bool X86FastISel::DoSelectCall(const Instruction *I, const char *MemIntName) { 1861 const CallInst *CI = cast<CallInst>(I); 1862 const Value *Callee = CI->getCalledValue(); 1863 1864 // Handle only C and fastcc calling conventions for now. 1865 ImmutableCallSite CS(CI); 1866 CallingConv::ID CC = CS.getCallingConv(); 1867 bool isWin64 = Subtarget->isCallingConvWin64(CC); 1868 if (CC != CallingConv::C && CC != CallingConv::Fast && 1869 CC != CallingConv::X86_FastCall && CC != CallingConv::X86_64_Win64 && 1870 CC != CallingConv::X86_64_SysV) 1871 return false; 1872 1873 // fastcc with -tailcallopt is intended to provide a guaranteed 1874 // tail call optimization. Fastisel doesn't know how to do that. 1875 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 1876 return false; 1877 1878 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 1879 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 1880 bool isVarArg = FTy->isVarArg(); 1881 1882 // Don't know how to handle Win64 varargs yet. Nothing special needed for 1883 // x86-32. Special handling for x86-64 is implemented. 1884 if (isVarArg && isWin64) 1885 return false; 1886 1887 // Fast-isel doesn't know about callee-pop yet. 1888 if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg, 1889 TM.Options.GuaranteedTailCallOpt)) 1890 return false; 1891 1892 // Check whether the function can return without sret-demotion. 1893 SmallVector<ISD::OutputArg, 4> Outs; 1894 GetReturnInfo(I->getType(), CS.getAttributes(), Outs, TLI); 1895 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(), 1896 *FuncInfo.MF, FTy->isVarArg(), 1897 Outs, FTy->getContext()); 1898 if (!CanLowerReturn) 1899 return false; 1900 1901 // Materialize callee address in a register. FIXME: GV address can be 1902 // handled with a CALLpcrel32 instead. 1903 X86AddressMode CalleeAM; 1904 if (!X86SelectCallAddress(Callee, CalleeAM)) 1905 return false; 1906 unsigned CalleeOp = 0; 1907 const GlobalValue *GV = 0; 1908 if (CalleeAM.GV != 0) { 1909 GV = CalleeAM.GV; 1910 } else if (CalleeAM.Base.Reg != 0) { 1911 CalleeOp = CalleeAM.Base.Reg; 1912 } else 1913 return false; 1914 1915 // Deal with call operands first. 1916 SmallVector<const Value *, 8> ArgVals; 1917 SmallVector<unsigned, 8> Args; 1918 SmallVector<MVT, 8> ArgVTs; 1919 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags; 1920 unsigned arg_size = CS.arg_size(); 1921 Args.reserve(arg_size); 1922 ArgVals.reserve(arg_size); 1923 ArgVTs.reserve(arg_size); 1924 ArgFlags.reserve(arg_size); 1925 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 1926 i != e; ++i) { 1927 // If we're lowering a mem intrinsic instead of a regular call, skip the 1928 // last two arguments, which should not passed to the underlying functions. 1929 if (MemIntName && e-i <= 2) 1930 break; 1931 Value *ArgVal = *i; 1932 ISD::ArgFlagsTy Flags; 1933 unsigned AttrInd = i - CS.arg_begin() + 1; 1934 if (CS.paramHasAttr(AttrInd, Attribute::SExt)) 1935 Flags.setSExt(); 1936 if (CS.paramHasAttr(AttrInd, Attribute::ZExt)) 1937 Flags.setZExt(); 1938 1939 if (CS.paramHasAttr(AttrInd, Attribute::ByVal)) { 1940 PointerType *Ty = cast<PointerType>(ArgVal->getType()); 1941 Type *ElementTy = Ty->getElementType(); 1942 unsigned FrameSize = TD.getTypeAllocSize(ElementTy); 1943 unsigned FrameAlign = CS.getParamAlignment(AttrInd); 1944 if (!FrameAlign) 1945 FrameAlign = TLI.getByValTypeAlignment(ElementTy); 1946 Flags.setByVal(); 1947 Flags.setByValSize(FrameSize); 1948 Flags.setByValAlign(FrameAlign); 1949 if (!IsMemcpySmall(FrameSize)) 1950 return false; 1951 } 1952 1953 if (CS.paramHasAttr(AttrInd, Attribute::InReg)) 1954 Flags.setInReg(); 1955 if (CS.paramHasAttr(AttrInd, Attribute::Nest)) 1956 Flags.setNest(); 1957 1958 // If this is an i1/i8/i16 argument, promote to i32 to avoid an extra 1959 // instruction. This is safe because it is common to all fastisel supported 1960 // calling conventions on x86. 1961 if (ConstantInt *CI = dyn_cast<ConstantInt>(ArgVal)) { 1962 if (CI->getBitWidth() == 1 || CI->getBitWidth() == 8 || 1963 CI->getBitWidth() == 16) { 1964 if (Flags.isSExt()) 1965 ArgVal = ConstantExpr::getSExt(CI,Type::getInt32Ty(CI->getContext())); 1966 else 1967 ArgVal = ConstantExpr::getZExt(CI,Type::getInt32Ty(CI->getContext())); 1968 } 1969 } 1970 1971 unsigned ArgReg; 1972 1973 // Passing bools around ends up doing a trunc to i1 and passing it. 1974 // Codegen this as an argument + "and 1". 1975 if (ArgVal->getType()->isIntegerTy(1) && isa<TruncInst>(ArgVal) && 1976 cast<TruncInst>(ArgVal)->getParent() == I->getParent() && 1977 ArgVal->hasOneUse()) { 1978 ArgVal = cast<TruncInst>(ArgVal)->getOperand(0); 1979 ArgReg = getRegForValue(ArgVal); 1980 if (ArgReg == 0) return false; 1981 1982 MVT ArgVT; 1983 if (!isTypeLegal(ArgVal->getType(), ArgVT)) return false; 1984 1985 ArgReg = FastEmit_ri(ArgVT, ArgVT, ISD::AND, ArgReg, 1986 ArgVal->hasOneUse(), 1); 1987 } else { 1988 ArgReg = getRegForValue(ArgVal); 1989 } 1990 1991 if (ArgReg == 0) return false; 1992 1993 Type *ArgTy = ArgVal->getType(); 1994 MVT ArgVT; 1995 if (!isTypeLegal(ArgTy, ArgVT)) 1996 return false; 1997 if (ArgVT == MVT::x86mmx) 1998 return false; 1999 unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy); 2000 Flags.setOrigAlign(OriginalAlignment); 2001 2002 Args.push_back(ArgReg); 2003 ArgVals.push_back(ArgVal); 2004 ArgVTs.push_back(ArgVT); 2005 ArgFlags.push_back(Flags); 2006 } 2007 2008 // Analyze operands of the call, assigning locations to each operand. 2009 SmallVector<CCValAssign, 16> ArgLocs; 2010 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, TM, ArgLocs, 2011 I->getParent()->getContext()); 2012 2013 // Allocate shadow area for Win64 2014 if (isWin64) 2015 CCInfo.AllocateStack(32, 8); 2016 2017 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CC_X86); 2018 2019 // Get a count of how many bytes are to be pushed on the stack. 2020 unsigned NumBytes = CCInfo.getNextStackOffset(); 2021 2022 // Issue CALLSEQ_START 2023 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 2024 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown)) 2025 .addImm(NumBytes); 2026 2027 // Process argument: walk the register/memloc assignments, inserting 2028 // copies / loads. 2029 SmallVector<unsigned, 4> RegArgs; 2030 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2031 CCValAssign &VA = ArgLocs[i]; 2032 unsigned Arg = Args[VA.getValNo()]; 2033 EVT ArgVT = ArgVTs[VA.getValNo()]; 2034 2035 // Promote the value if needed. 2036 switch (VA.getLocInfo()) { 2037 case CCValAssign::Full: break; 2038 case CCValAssign::SExt: { 2039 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2040 "Unexpected extend"); 2041 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), 2042 Arg, ArgVT, Arg); 2043 assert(Emitted && "Failed to emit a sext!"); (void)Emitted; 2044 ArgVT = VA.getLocVT(); 2045 break; 2046 } 2047 case CCValAssign::ZExt: { 2048 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2049 "Unexpected extend"); 2050 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), 2051 Arg, ArgVT, Arg); 2052 assert(Emitted && "Failed to emit a zext!"); (void)Emitted; 2053 ArgVT = VA.getLocVT(); 2054 break; 2055 } 2056 case CCValAssign::AExt: { 2057 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 2058 "Unexpected extend"); 2059 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), 2060 Arg, ArgVT, Arg); 2061 if (!Emitted) 2062 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), 2063 Arg, ArgVT, Arg); 2064 if (!Emitted) 2065 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), 2066 Arg, ArgVT, Arg); 2067 2068 assert(Emitted && "Failed to emit a aext!"); (void)Emitted; 2069 ArgVT = VA.getLocVT(); 2070 break; 2071 } 2072 case CCValAssign::BCvt: { 2073 unsigned BC = FastEmit_r(ArgVT.getSimpleVT(), VA.getLocVT(), 2074 ISD::BITCAST, Arg, /*TODO: Kill=*/false); 2075 assert(BC != 0 && "Failed to emit a bitcast!"); 2076 Arg = BC; 2077 ArgVT = VA.getLocVT(); 2078 break; 2079 } 2080 case CCValAssign::VExt: 2081 // VExt has not been implemented, so this should be impossible to reach 2082 // for now. However, fallback to Selection DAG isel once implemented. 2083 return false; 2084 case CCValAssign::Indirect: 2085 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully 2086 // support this. 2087 return false; 2088 } 2089 2090 if (VA.isRegLoc()) { 2091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2092 VA.getLocReg()).addReg(Arg); 2093 RegArgs.push_back(VA.getLocReg()); 2094 } else { 2095 unsigned LocMemOffset = VA.getLocMemOffset(); 2096 X86AddressMode AM; 2097 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo*>( 2098 getTargetMachine()->getRegisterInfo()); 2099 AM.Base.Reg = RegInfo->getStackRegister(); 2100 AM.Disp = LocMemOffset; 2101 const Value *ArgVal = ArgVals[VA.getValNo()]; 2102 ISD::ArgFlagsTy Flags = ArgFlags[VA.getValNo()]; 2103 2104 if (Flags.isByVal()) { 2105 X86AddressMode SrcAM; 2106 SrcAM.Base.Reg = Arg; 2107 bool Res = TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()); 2108 assert(Res && "memcpy length already checked!"); (void)Res; 2109 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) { 2110 // If this is a really simple value, emit this with the Value* version 2111 // of X86FastEmitStore. If it isn't simple, we don't want to do this, 2112 // as it can cause us to reevaluate the argument. 2113 if (!X86FastEmitStore(ArgVT, ArgVal, AM)) 2114 return false; 2115 } else { 2116 if (!X86FastEmitStore(ArgVT, Arg, AM)) 2117 return false; 2118 } 2119 } 2120 } 2121 2122 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2123 // GOT pointer. 2124 if (Subtarget->isPICStyleGOT()) { 2125 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2126 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2127 X86::EBX).addReg(Base); 2128 } 2129 2130 if (Subtarget->is64Bit() && isVarArg && !isWin64) { 2131 // Count the number of XMM registers allocated. 2132 static const uint16_t XMMArgRegs[] = { 2133 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2134 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2135 }; 2136 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2137 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::MOV8ri), 2138 X86::AL).addImm(NumXMMRegs); 2139 } 2140 2141 // Issue the call. 2142 MachineInstrBuilder MIB; 2143 if (CalleeOp) { 2144 // Register-indirect call. 2145 unsigned CallOpc; 2146 if (Subtarget->is64Bit()) 2147 CallOpc = X86::CALL64r; 2148 else 2149 CallOpc = X86::CALL32r; 2150 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc)) 2151 .addReg(CalleeOp); 2152 2153 } else { 2154 // Direct call. 2155 assert(GV && "Not a direct call"); 2156 unsigned CallOpc; 2157 if (Subtarget->is64Bit()) 2158 CallOpc = X86::CALL64pcrel32; 2159 else 2160 CallOpc = X86::CALLpcrel32; 2161 2162 // See if we need any target-specific flags on the GV operand. 2163 unsigned char OpFlags = 0; 2164 2165 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2166 // external symbols most go through the PLT in PIC mode. If the symbol 2167 // has hidden or protected visibility, or if it is static or local, then 2168 // we don't need to use the PLT - we can directly call it. 2169 if (Subtarget->isTargetELF() && 2170 TM.getRelocationModel() == Reloc::PIC_ && 2171 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2172 OpFlags = X86II::MO_PLT; 2173 } else if (Subtarget->isPICStyleStubAny() && 2174 (GV->isDeclaration() || GV->isWeakForLinker()) && 2175 (!Subtarget->getTargetTriple().isMacOSX() || 2176 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2177 // PC-relative references to external symbols should go through $stub, 2178 // unless we're building with the leopard linker or later, which 2179 // automatically synthesizes these stubs. 2180 OpFlags = X86II::MO_DARWIN_STUB; 2181 } 2182 2183 2184 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc)); 2185 if (MemIntName) 2186 MIB.addExternalSymbol(MemIntName, OpFlags); 2187 else 2188 MIB.addGlobalAddress(GV, 0, OpFlags); 2189 } 2190 2191 // Add a register mask with the call-preserved registers. 2192 // Proper defs for return values will be added by setPhysRegsDeadExcept(). 2193 MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv())); 2194 2195 // Add an implicit use GOT pointer in EBX. 2196 if (Subtarget->isPICStyleGOT()) 2197 MIB.addReg(X86::EBX, RegState::Implicit); 2198 2199 if (Subtarget->is64Bit() && isVarArg && !isWin64) 2200 MIB.addReg(X86::AL, RegState::Implicit); 2201 2202 // Add implicit physical register uses to the call. 2203 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i) 2204 MIB.addReg(RegArgs[i], RegState::Implicit); 2205 2206 // Issue CALLSEQ_END 2207 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 2208 const unsigned NumBytesCallee = computeBytesPoppedByCallee(*Subtarget, CS); 2209 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp)) 2210 .addImm(NumBytes).addImm(NumBytesCallee); 2211 2212 // Build info for return calling conv lowering code. 2213 // FIXME: This is practically a copy-paste from TargetLowering::LowerCallTo. 2214 SmallVector<ISD::InputArg, 32> Ins; 2215 SmallVector<EVT, 4> RetTys; 2216 ComputeValueVTs(TLI, I->getType(), RetTys); 2217 for (unsigned i = 0, e = RetTys.size(); i != e; ++i) { 2218 EVT VT = RetTys[i]; 2219 MVT RegisterVT = TLI.getRegisterType(I->getParent()->getContext(), VT); 2220 unsigned NumRegs = TLI.getNumRegisters(I->getParent()->getContext(), VT); 2221 for (unsigned j = 0; j != NumRegs; ++j) { 2222 ISD::InputArg MyFlags; 2223 MyFlags.VT = RegisterVT; 2224 MyFlags.Used = !CS.getInstruction()->use_empty(); 2225 if (CS.paramHasAttr(0, Attribute::SExt)) 2226 MyFlags.Flags.setSExt(); 2227 if (CS.paramHasAttr(0, Attribute::ZExt)) 2228 MyFlags.Flags.setZExt(); 2229 if (CS.paramHasAttr(0, Attribute::InReg)) 2230 MyFlags.Flags.setInReg(); 2231 Ins.push_back(MyFlags); 2232 } 2233 } 2234 2235 // Now handle call return values. 2236 SmallVector<unsigned, 4> UsedRegs; 2237 SmallVector<CCValAssign, 16> RVLocs; 2238 CCState CCRetInfo(CC, false, *FuncInfo.MF, TM, RVLocs, 2239 I->getParent()->getContext()); 2240 unsigned ResultReg = FuncInfo.CreateRegs(I->getType()); 2241 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86); 2242 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2243 EVT CopyVT = RVLocs[i].getValVT(); 2244 unsigned CopyReg = ResultReg + i; 2245 2246 // If this is a call to a function that returns an fp value on the x87 fp 2247 // stack, but where we prefer to use the value in xmm registers, copy it 2248 // out as F80 and use a truncate to move it from fp stack reg to xmm reg. 2249 if ((RVLocs[i].getLocReg() == X86::ST0 || 2250 RVLocs[i].getLocReg() == X86::ST1)) { 2251 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) { 2252 CopyVT = MVT::f80; 2253 CopyReg = createResultReg(&X86::RFP80RegClass); 2254 } 2255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(X86::FpPOP_RETVAL), 2256 CopyReg); 2257 } else { 2258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY), 2259 CopyReg).addReg(RVLocs[i].getLocReg()); 2260 UsedRegs.push_back(RVLocs[i].getLocReg()); 2261 } 2262 2263 if (CopyVT != RVLocs[i].getValVT()) { 2264 // Round the F80 the right size, which also moves to the appropriate xmm 2265 // register. This is accomplished by storing the F80 value in memory and 2266 // then loading it back. Ewww... 2267 EVT ResVT = RVLocs[i].getValVT(); 2268 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64; 2269 unsigned MemSize = ResVT.getSizeInBits()/8; 2270 int FI = MFI.CreateStackObject(MemSize, MemSize, false); 2271 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2272 TII.get(Opc)), FI) 2273 .addReg(CopyReg); 2274 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm; 2275 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2276 TII.get(Opc), ResultReg + i), FI); 2277 } 2278 } 2279 2280 if (RVLocs.size()) 2281 UpdateValueMap(I, ResultReg, RVLocs.size()); 2282 2283 // Set all unused physreg defs as dead. 2284 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI); 2285 2286 return true; 2287 } 2288 2289 2290 bool 2291 X86FastISel::TargetSelectInstruction(const Instruction *I) { 2292 switch (I->getOpcode()) { 2293 default: break; 2294 case Instruction::Load: 2295 return X86SelectLoad(I); 2296 case Instruction::Store: 2297 return X86SelectStore(I); 2298 case Instruction::Ret: 2299 return X86SelectRet(I); 2300 case Instruction::ICmp: 2301 case Instruction::FCmp: 2302 return X86SelectCmp(I); 2303 case Instruction::ZExt: 2304 return X86SelectZExt(I); 2305 case Instruction::Br: 2306 return X86SelectBranch(I); 2307 case Instruction::Call: 2308 return X86SelectCall(I); 2309 case Instruction::LShr: 2310 case Instruction::AShr: 2311 case Instruction::Shl: 2312 return X86SelectShift(I); 2313 case Instruction::SDiv: 2314 case Instruction::UDiv: 2315 case Instruction::SRem: 2316 case Instruction::URem: 2317 return X86SelectDivRem(I); 2318 case Instruction::Select: 2319 return X86SelectSelect(I); 2320 case Instruction::Trunc: 2321 return X86SelectTrunc(I); 2322 case Instruction::FPExt: 2323 return X86SelectFPExt(I); 2324 case Instruction::FPTrunc: 2325 return X86SelectFPTrunc(I); 2326 case Instruction::IntToPtr: // Deliberate fall-through. 2327 case Instruction::PtrToInt: { 2328 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType()); 2329 EVT DstVT = TLI.getValueType(I->getType()); 2330 if (DstVT.bitsGT(SrcVT)) 2331 return X86SelectZExt(I); 2332 if (DstVT.bitsLT(SrcVT)) 2333 return X86SelectTrunc(I); 2334 unsigned Reg = getRegForValue(I->getOperand(0)); 2335 if (Reg == 0) return false; 2336 UpdateValueMap(I, Reg); 2337 return true; 2338 } 2339 } 2340 2341 return false; 2342 } 2343 2344 unsigned X86FastISel::TargetMaterializeConstant(const Constant *C) { 2345 MVT VT; 2346 if (!isTypeLegal(C->getType(), VT)) 2347 return 0; 2348 2349 // Can't handle alternate code models yet. 2350 if (TM.getCodeModel() != CodeModel::Small) 2351 return 0; 2352 2353 // Get opcode and regclass of the output for the given load instruction. 2354 unsigned Opc = 0; 2355 const TargetRegisterClass *RC = NULL; 2356 switch (VT.SimpleTy) { 2357 default: return 0; 2358 case MVT::i8: 2359 Opc = X86::MOV8rm; 2360 RC = &X86::GR8RegClass; 2361 break; 2362 case MVT::i16: 2363 Opc = X86::MOV16rm; 2364 RC = &X86::GR16RegClass; 2365 break; 2366 case MVT::i32: 2367 Opc = X86::MOV32rm; 2368 RC = &X86::GR32RegClass; 2369 break; 2370 case MVT::i64: 2371 // Must be in x86-64 mode. 2372 Opc = X86::MOV64rm; 2373 RC = &X86::GR64RegClass; 2374 break; 2375 case MVT::f32: 2376 if (X86ScalarSSEf32) { 2377 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 2378 RC = &X86::FR32RegClass; 2379 } else { 2380 Opc = X86::LD_Fp32m; 2381 RC = &X86::RFP32RegClass; 2382 } 2383 break; 2384 case MVT::f64: 2385 if (X86ScalarSSEf64) { 2386 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 2387 RC = &X86::FR64RegClass; 2388 } else { 2389 Opc = X86::LD_Fp64m; 2390 RC = &X86::RFP64RegClass; 2391 } 2392 break; 2393 case MVT::f80: 2394 // No f80 support yet. 2395 return 0; 2396 } 2397 2398 // Materialize addresses with LEA instructions. 2399 if (isa<GlobalValue>(C)) { 2400 X86AddressMode AM; 2401 if (X86SelectAddress(C, AM)) { 2402 // If the expression is just a basereg, then we're done, otherwise we need 2403 // to emit an LEA. 2404 if (AM.BaseType == X86AddressMode::RegBase && 2405 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == 0) 2406 return AM.Base.Reg; 2407 2408 Opc = TLI.getPointerTy() == MVT::i32 ? X86::LEA32r : X86::LEA64r; 2409 unsigned ResultReg = createResultReg(RC); 2410 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2411 TII.get(Opc), ResultReg), AM); 2412 return ResultReg; 2413 } 2414 return 0; 2415 } 2416 2417 // MachineConstantPool wants an explicit alignment. 2418 unsigned Align = TD.getPrefTypeAlignment(C->getType()); 2419 if (Align == 0) { 2420 // Alignment of vector types. FIXME! 2421 Align = TD.getTypeAllocSize(C->getType()); 2422 } 2423 2424 // x86-32 PIC requires a PIC base register for constant pools. 2425 unsigned PICBase = 0; 2426 unsigned char OpFlag = 0; 2427 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic 2428 OpFlag = X86II::MO_PIC_BASE_OFFSET; 2429 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2430 } else if (Subtarget->isPICStyleGOT()) { 2431 OpFlag = X86II::MO_GOTOFF; 2432 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 2433 } else if (Subtarget->isPICStyleRIPRel() && 2434 TM.getCodeModel() == CodeModel::Small) { 2435 PICBase = X86::RIP; 2436 } 2437 2438 // Create the load from the constant pool. 2439 unsigned MCPOffset = MCP.getConstantPoolIndex(C, Align); 2440 unsigned ResultReg = createResultReg(RC); 2441 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2442 TII.get(Opc), ResultReg), 2443 MCPOffset, PICBase, OpFlag); 2444 2445 return ResultReg; 2446 } 2447 2448 unsigned X86FastISel::TargetMaterializeAlloca(const AllocaInst *C) { 2449 // Fail on dynamic allocas. At this point, getRegForValue has already 2450 // checked its CSE maps, so if we're here trying to handle a dynamic 2451 // alloca, we're not going to succeed. X86SelectAddress has a 2452 // check for dynamic allocas, because it's called directly from 2453 // various places, but TargetMaterializeAlloca also needs a check 2454 // in order to avoid recursion between getRegForValue, 2455 // X86SelectAddrss, and TargetMaterializeAlloca. 2456 if (!FuncInfo.StaticAllocaMap.count(C)) 2457 return 0; 2458 2459 X86AddressMode AM; 2460 if (!X86SelectAddress(C, AM)) 2461 return 0; 2462 unsigned Opc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 2463 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy()); 2464 unsigned ResultReg = createResultReg(RC); 2465 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, 2466 TII.get(Opc), ResultReg), AM); 2467 return ResultReg; 2468 } 2469 2470 unsigned X86FastISel::TargetMaterializeFloatZero(const ConstantFP *CF) { 2471 MVT VT; 2472 if (!isTypeLegal(CF->getType(), VT)) 2473 return 0; 2474 2475 // Get opcode and regclass for the given zero. 2476 unsigned Opc = 0; 2477 const TargetRegisterClass *RC = NULL; 2478 switch (VT.SimpleTy) { 2479 default: return 0; 2480 case MVT::f32: 2481 if (X86ScalarSSEf32) { 2482 Opc = X86::FsFLD0SS; 2483 RC = &X86::FR32RegClass; 2484 } else { 2485 Opc = X86::LD_Fp032; 2486 RC = &X86::RFP32RegClass; 2487 } 2488 break; 2489 case MVT::f64: 2490 if (X86ScalarSSEf64) { 2491 Opc = X86::FsFLD0SD; 2492 RC = &X86::FR64RegClass; 2493 } else { 2494 Opc = X86::LD_Fp064; 2495 RC = &X86::RFP64RegClass; 2496 } 2497 break; 2498 case MVT::f80: 2499 // No f80 support yet. 2500 return 0; 2501 } 2502 2503 unsigned ResultReg = createResultReg(RC); 2504 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), ResultReg); 2505 return ResultReg; 2506 } 2507 2508 2509 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 2510 const LoadInst *LI) { 2511 X86AddressMode AM; 2512 if (!X86SelectAddress(LI->getOperand(0), AM)) 2513 return false; 2514 2515 const X86InstrInfo &XII = (const X86InstrInfo&)TII; 2516 2517 unsigned Size = TD.getTypeAllocSize(LI->getType()); 2518 unsigned Alignment = LI->getAlignment(); 2519 2520 SmallVector<MachineOperand, 8> AddrOps; 2521 AM.getFullAddress(AddrOps); 2522 2523 MachineInstr *Result = 2524 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps, Size, Alignment); 2525 if (Result == 0) return false; 2526 2527 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result); 2528 MI->eraseFromParent(); 2529 return true; 2530 } 2531 2532 2533 namespace llvm { 2534 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo, 2535 const TargetLibraryInfo *libInfo) { 2536 return new X86FastISel(funcInfo, libInfo); 2537 } 2538 } 2539