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 "X86CallingConv.h" 18 #include "X86InstrBuilder.h" 19 #include "X86InstrInfo.h" 20 #include "X86MachineFunctionInfo.h" 21 #include "X86RegisterInfo.h" 22 #include "X86Subtarget.h" 23 #include "X86TargetMachine.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FastISel.h" 27 #include "llvm/CodeGen/FunctionLoweringInfo.h" 28 #include "llvm/CodeGen/MachineConstantPool.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/IR/CallSite.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/DebugInfo.h" 34 #include "llvm/IR/DerivedTypes.h" 35 #include "llvm/IR/GetElementPtrTypeIterator.h" 36 #include "llvm/IR/GlobalAlias.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/Instructions.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/Operator.h" 41 #include "llvm/MC/MCAsmInfo.h" 42 #include "llvm/MC/MCSymbol.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Target/TargetOptions.h" 45 using namespace llvm; 46 47 namespace { 48 49 class X86FastISel final : public FastISel { 50 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can 51 /// make the right decision when generating code for different targets. 52 const X86Subtarget *Subtarget; 53 54 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87 55 /// floating point ops. 56 /// When SSE is available, use it for f32 operations. 57 /// When SSE2 is available, use it for f64 operations. 58 bool X86ScalarSSEf64; 59 bool X86ScalarSSEf32; 60 61 public: 62 explicit X86FastISel(FunctionLoweringInfo &funcInfo, 63 const TargetLibraryInfo *libInfo) 64 : FastISel(funcInfo, libInfo) { 65 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>(); 66 X86ScalarSSEf64 = Subtarget->hasSSE2(); 67 X86ScalarSSEf32 = Subtarget->hasSSE1(); 68 } 69 70 bool fastSelectInstruction(const Instruction *I) override; 71 72 /// \brief The specified machine instr operand is a vreg, and that 73 /// vreg is being provided by the specified load instruction. If possible, 74 /// try to fold the load as an operand to the instruction, returning true if 75 /// possible. 76 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 77 const LoadInst *LI) override; 78 79 bool fastLowerArguments() override; 80 bool fastLowerCall(CallLoweringInfo &CLI) override; 81 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override; 82 83 #include "X86GenFastISel.inc" 84 85 private: 86 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL); 87 88 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO, 89 unsigned &ResultReg, unsigned Alignment = 1); 90 91 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM, 92 MachineMemOperand *MMO = nullptr, bool Aligned = false); 93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill, 94 X86AddressMode &AM, 95 MachineMemOperand *MMO = nullptr, bool Aligned = false); 96 97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT, 98 unsigned &ResultReg); 99 100 bool X86SelectAddress(const Value *V, X86AddressMode &AM); 101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM); 102 103 bool X86SelectLoad(const Instruction *I); 104 105 bool X86SelectStore(const Instruction *I); 106 107 bool X86SelectRet(const Instruction *I); 108 109 bool X86SelectCmp(const Instruction *I); 110 111 bool X86SelectZExt(const Instruction *I); 112 113 bool X86SelectBranch(const Instruction *I); 114 115 bool X86SelectShift(const Instruction *I); 116 117 bool X86SelectDivRem(const Instruction *I); 118 119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I); 120 121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I); 122 123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I); 124 125 bool X86SelectSelect(const Instruction *I); 126 127 bool X86SelectTrunc(const Instruction *I); 128 129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc, 130 const TargetRegisterClass *RC); 131 132 bool X86SelectFPExt(const Instruction *I); 133 bool X86SelectFPTrunc(const Instruction *I); 134 bool X86SelectSIToFP(const Instruction *I); 135 136 const X86InstrInfo *getInstrInfo() const { 137 return Subtarget->getInstrInfo(); 138 } 139 const X86TargetMachine *getTargetMachine() const { 140 return static_cast<const X86TargetMachine *>(&TM); 141 } 142 143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM); 144 145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT); 146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT); 147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT); 148 unsigned fastMaterializeConstant(const Constant *C) override; 149 150 unsigned fastMaterializeAlloca(const AllocaInst *C) override; 151 152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override; 153 154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is 155 /// computed in an SSE register, not on the X87 floating point stack. 156 bool isScalarFPTypeInSSEReg(EVT VT) const { 157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2 158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1 159 } 160 161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false); 162 163 bool IsMemcpySmall(uint64_t Len); 164 165 bool TryEmitSmallMemcpy(X86AddressMode DestAM, 166 X86AddressMode SrcAM, uint64_t Len); 167 168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 169 const Value *Cond); 170 171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB, 172 X86AddressMode &AM); 173 }; 174 175 } // end anonymous namespace. 176 177 static std::pair<X86::CondCode, bool> 178 getX86ConditionCode(CmpInst::Predicate Predicate) { 179 X86::CondCode CC = X86::COND_INVALID; 180 bool NeedSwap = false; 181 switch (Predicate) { 182 default: break; 183 // Floating-point Predicates 184 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break; 185 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through 186 case CmpInst::FCMP_OGT: CC = X86::COND_A; break; 187 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through 188 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break; 189 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through 190 case CmpInst::FCMP_ULT: CC = X86::COND_B; break; 191 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through 192 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break; 193 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break; 194 case CmpInst::FCMP_UNO: CC = X86::COND_P; break; 195 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break; 196 case CmpInst::FCMP_OEQ: // fall-through 197 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break; 198 199 // Integer Predicates 200 case CmpInst::ICMP_EQ: CC = X86::COND_E; break; 201 case CmpInst::ICMP_NE: CC = X86::COND_NE; break; 202 case CmpInst::ICMP_UGT: CC = X86::COND_A; break; 203 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break; 204 case CmpInst::ICMP_ULT: CC = X86::COND_B; break; 205 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break; 206 case CmpInst::ICMP_SGT: CC = X86::COND_G; break; 207 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break; 208 case CmpInst::ICMP_SLT: CC = X86::COND_L; break; 209 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break; 210 } 211 212 return std::make_pair(CC, NeedSwap); 213 } 214 215 static std::pair<unsigned, bool> 216 getX86SSEConditionCode(CmpInst::Predicate Predicate) { 217 unsigned CC; 218 bool NeedSwap = false; 219 220 // SSE Condition code mapping: 221 // 0 - EQ 222 // 1 - LT 223 // 2 - LE 224 // 3 - UNORD 225 // 4 - NEQ 226 // 5 - NLT 227 // 6 - NLE 228 // 7 - ORD 229 switch (Predicate) { 230 default: llvm_unreachable("Unexpected predicate"); 231 case CmpInst::FCMP_OEQ: CC = 0; break; 232 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through 233 case CmpInst::FCMP_OLT: CC = 1; break; 234 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through 235 case CmpInst::FCMP_OLE: CC = 2; break; 236 case CmpInst::FCMP_UNO: CC = 3; break; 237 case CmpInst::FCMP_UNE: CC = 4; break; 238 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through 239 case CmpInst::FCMP_UGE: CC = 5; break; 240 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through 241 case CmpInst::FCMP_UGT: CC = 6; break; 242 case CmpInst::FCMP_ORD: CC = 7; break; 243 case CmpInst::FCMP_UEQ: 244 case CmpInst::FCMP_ONE: CC = 8; break; 245 } 246 247 return std::make_pair(CC, NeedSwap); 248 } 249 250 /// \brief Adds a complex addressing mode to the given machine instr builder. 251 /// Note, this will constrain the index register. If its not possible to 252 /// constrain the given index register, then a new one will be created. The 253 /// IndexReg field of the addressing mode will be updated to match in this case. 254 const MachineInstrBuilder & 255 X86FastISel::addFullAddress(const MachineInstrBuilder &MIB, 256 X86AddressMode &AM) { 257 // First constrain the index register. It needs to be a GR64_NOSP. 258 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg, 259 MIB->getNumOperands() + 260 X86::AddrIndexReg); 261 return ::addFullAddress(MIB, AM); 262 } 263 264 /// \brief Check if it is possible to fold the condition from the XALU intrinsic 265 /// into the user. The condition code will only be updated on success. 266 bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I, 267 const Value *Cond) { 268 if (!isa<ExtractValueInst>(Cond)) 269 return false; 270 271 const auto *EV = cast<ExtractValueInst>(Cond); 272 if (!isa<IntrinsicInst>(EV->getAggregateOperand())) 273 return false; 274 275 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand()); 276 MVT RetVT; 277 const Function *Callee = II->getCalledFunction(); 278 Type *RetTy = 279 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U); 280 if (!isTypeLegal(RetTy, RetVT)) 281 return false; 282 283 if (RetVT != MVT::i32 && RetVT != MVT::i64) 284 return false; 285 286 X86::CondCode TmpCC; 287 switch (II->getIntrinsicID()) { 288 default: return false; 289 case Intrinsic::sadd_with_overflow: 290 case Intrinsic::ssub_with_overflow: 291 case Intrinsic::smul_with_overflow: 292 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break; 293 case Intrinsic::uadd_with_overflow: 294 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break; 295 } 296 297 // Check if both instructions are in the same basic block. 298 if (II->getParent() != I->getParent()) 299 return false; 300 301 // Make sure nothing is in the way 302 BasicBlock::const_iterator Start(I); 303 BasicBlock::const_iterator End(II); 304 for (auto Itr = std::prev(Start); Itr != End; --Itr) { 305 // We only expect extractvalue instructions between the intrinsic and the 306 // instruction to be selected. 307 if (!isa<ExtractValueInst>(Itr)) 308 return false; 309 310 // Check that the extractvalue operand comes from the intrinsic. 311 const auto *EVI = cast<ExtractValueInst>(Itr); 312 if (EVI->getAggregateOperand() != II) 313 return false; 314 } 315 316 CC = TmpCC; 317 return true; 318 } 319 320 bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) { 321 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true); 322 if (evt == MVT::Other || !evt.isSimple()) 323 // Unhandled type. Halt "fast" selection and bail. 324 return false; 325 326 VT = evt.getSimpleVT(); 327 // For now, require SSE/SSE2 for performing floating-point operations, 328 // since x87 requires additional work. 329 if (VT == MVT::f64 && !X86ScalarSSEf64) 330 return false; 331 if (VT == MVT::f32 && !X86ScalarSSEf32) 332 return false; 333 // Similarly, no f80 support yet. 334 if (VT == MVT::f80) 335 return false; 336 // We only handle legal types. For example, on x86-32 the instruction 337 // selector contains all of the 64-bit instructions from x86-64, 338 // under the assumption that i64 won't be used if the target doesn't 339 // support it. 340 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT); 341 } 342 343 #include "X86GenCallingConv.inc" 344 345 /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT. 346 /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV. 347 /// Return true and the result register by reference if it is possible. 348 bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM, 349 MachineMemOperand *MMO, unsigned &ResultReg, 350 unsigned Alignment) { 351 bool HasAVX = Subtarget->hasAVX(); 352 // Get opcode and regclass of the output for the given load instruction. 353 unsigned Opc = 0; 354 const TargetRegisterClass *RC = nullptr; 355 switch (VT.getSimpleVT().SimpleTy) { 356 default: return false; 357 case MVT::i1: 358 case MVT::i8: 359 Opc = X86::MOV8rm; 360 RC = &X86::GR8RegClass; 361 break; 362 case MVT::i16: 363 Opc = X86::MOV16rm; 364 RC = &X86::GR16RegClass; 365 break; 366 case MVT::i32: 367 Opc = X86::MOV32rm; 368 RC = &X86::GR32RegClass; 369 break; 370 case MVT::i64: 371 // Must be in x86-64 mode. 372 Opc = X86::MOV64rm; 373 RC = &X86::GR64RegClass; 374 break; 375 case MVT::f32: 376 if (X86ScalarSSEf32) { 377 Opc = HasAVX ? X86::VMOVSSrm : X86::MOVSSrm; 378 RC = &X86::FR32RegClass; 379 } else { 380 Opc = X86::LD_Fp32m; 381 RC = &X86::RFP32RegClass; 382 } 383 break; 384 case MVT::f64: 385 if (X86ScalarSSEf64) { 386 Opc = HasAVX ? X86::VMOVSDrm : X86::MOVSDrm; 387 RC = &X86::FR64RegClass; 388 } else { 389 Opc = X86::LD_Fp64m; 390 RC = &X86::RFP64RegClass; 391 } 392 break; 393 case MVT::f80: 394 // No f80 support yet. 395 return false; 396 case MVT::v4f32: 397 if (Alignment >= 16) 398 Opc = HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm; 399 else 400 Opc = HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm; 401 RC = &X86::VR128RegClass; 402 break; 403 case MVT::v2f64: 404 if (Alignment >= 16) 405 Opc = HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm; 406 else 407 Opc = HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm; 408 RC = &X86::VR128RegClass; 409 break; 410 case MVT::v4i32: 411 case MVT::v2i64: 412 case MVT::v8i16: 413 case MVT::v16i8: 414 if (Alignment >= 16) 415 Opc = HasAVX ? X86::VMOVDQArm : X86::MOVDQArm; 416 else 417 Opc = HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm; 418 RC = &X86::VR128RegClass; 419 break; 420 case MVT::v8f32: 421 assert(HasAVX); 422 Opc = (Alignment >= 32) ? X86::VMOVAPSYrm : X86::VMOVUPSYrm; 423 RC = &X86::VR256RegClass; 424 break; 425 case MVT::v4f64: 426 assert(HasAVX); 427 Opc = (Alignment >= 32) ? X86::VMOVAPDYrm : X86::VMOVUPDYrm; 428 RC = &X86::VR256RegClass; 429 break; 430 case MVT::v8i32: 431 case MVT::v4i64: 432 case MVT::v16i16: 433 case MVT::v32i8: 434 assert(HasAVX); 435 Opc = (Alignment >= 32) ? X86::VMOVDQAYrm : X86::VMOVDQUYrm; 436 RC = &X86::VR256RegClass; 437 break; 438 case MVT::v16f32: 439 assert(Subtarget->hasAVX512()); 440 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm; 441 RC = &X86::VR512RegClass; 442 break; 443 case MVT::v8f64: 444 assert(Subtarget->hasAVX512()); 445 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm; 446 RC = &X86::VR512RegClass; 447 break; 448 case MVT::v8i64: 449 case MVT::v16i32: 450 case MVT::v32i16: 451 case MVT::v64i8: 452 assert(Subtarget->hasAVX512()); 453 // Note: There are a lot more choices based on type with AVX-512, but 454 // there's really no advantage when the load isn't masked. 455 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zmr : X86::VMOVDQU64Zmr; 456 RC = &X86::VR512RegClass; 457 break; 458 } 459 460 ResultReg = createResultReg(RC); 461 MachineInstrBuilder MIB = 462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 463 addFullAddress(MIB, AM); 464 if (MMO) 465 MIB->addMemOperand(*FuncInfo.MF, MMO); 466 return true; 467 } 468 469 /// X86FastEmitStore - Emit a machine instruction to store a value Val of 470 /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr 471 /// and a displacement offset, or a GlobalAddress, 472 /// i.e. V. Return true if it is possible. 473 bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill, 474 X86AddressMode &AM, 475 MachineMemOperand *MMO, bool Aligned) { 476 bool HasSSE2 = Subtarget->hasSSE2(); 477 bool HasSSE4A = Subtarget->hasSSE4A(); 478 bool HasAVX = Subtarget->hasAVX(); 479 bool IsNonTemporal = MMO && MMO->isNonTemporal(); 480 481 // Get opcode and regclass of the output for the given store instruction. 482 unsigned Opc = 0; 483 switch (VT.getSimpleVT().SimpleTy) { 484 case MVT::f80: // No f80 support yet. 485 default: return false; 486 case MVT::i1: { 487 // Mask out all but lowest bit. 488 unsigned AndResult = createResultReg(&X86::GR8RegClass); 489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 490 TII.get(X86::AND8ri), AndResult) 491 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1); 492 ValReg = AndResult; 493 } 494 // FALLTHROUGH, handling i1 as i8. 495 case MVT::i8: Opc = X86::MOV8mr; break; 496 case MVT::i16: Opc = X86::MOV16mr; break; 497 case MVT::i32: 498 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr; 499 break; 500 case MVT::i64: 501 // Must be in x86-64 mode. 502 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr; 503 break; 504 case MVT::f32: 505 if (X86ScalarSSEf32) { 506 if (IsNonTemporal && HasSSE4A) 507 Opc = X86::MOVNTSS; 508 else 509 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr; 510 } else 511 Opc = X86::ST_Fp32m; 512 break; 513 case MVT::f64: 514 if (X86ScalarSSEf32) { 515 if (IsNonTemporal && HasSSE4A) 516 Opc = X86::MOVNTSD; 517 else 518 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr; 519 } else 520 Opc = X86::ST_Fp64m; 521 break; 522 case MVT::v4f32: 523 if (Aligned) { 524 if (IsNonTemporal) 525 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr; 526 else 527 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr; 528 } else 529 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr; 530 break; 531 case MVT::v2f64: 532 if (Aligned) { 533 if (IsNonTemporal) 534 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr; 535 else 536 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr; 537 } else 538 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr; 539 break; 540 case MVT::v4i32: 541 case MVT::v2i64: 542 case MVT::v8i16: 543 case MVT::v16i8: 544 if (Aligned) { 545 if (IsNonTemporal) 546 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr; 547 else 548 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr; 549 } else 550 Opc = HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr; 551 break; 552 case MVT::v8f32: 553 assert(HasAVX); 554 if (Aligned) 555 Opc = IsNonTemporal ? X86::VMOVNTPSYmr : X86::VMOVAPSYmr; 556 else 557 Opc = X86::VMOVUPSYmr; 558 break; 559 case MVT::v4f64: 560 assert(HasAVX); 561 if (Aligned) { 562 Opc = IsNonTemporal ? X86::VMOVNTPDYmr : X86::VMOVAPDYmr; 563 } else 564 Opc = X86::VMOVUPDYmr; 565 break; 566 case MVT::v8i32: 567 case MVT::v4i64: 568 case MVT::v16i16: 569 case MVT::v32i8: 570 assert(HasAVX); 571 if (Aligned) 572 Opc = IsNonTemporal ? X86::VMOVNTDQYmr : X86::VMOVDQAYmr; 573 else 574 Opc = X86::VMOVDQUYmr; 575 break; 576 case MVT::v16f32: 577 assert(Subtarget->hasAVX512()); 578 if (Aligned) 579 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr; 580 else 581 Opc = X86::VMOVUPSZmr; 582 break; 583 case MVT::v8f64: 584 assert(Subtarget->hasAVX512()); 585 if (Aligned) { 586 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr; 587 } else 588 Opc = X86::VMOVUPDZmr; 589 break; 590 case MVT::v8i64: 591 case MVT::v16i32: 592 case MVT::v32i16: 593 case MVT::v64i8: 594 assert(Subtarget->hasAVX512()); 595 // Note: There are a lot more choices based on type with AVX-512, but 596 // there's really no advantage when the store isn't masked. 597 if (Aligned) 598 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr; 599 else 600 Opc = X86::VMOVDQU64Zmr; 601 break; 602 } 603 604 const MCInstrDesc &Desc = TII.get(Opc); 605 // Some of the instructions in the previous switch use FR128 instead 606 // of FR32 for ValReg. Make sure the register we feed the instruction 607 // matches its register class constraints. 608 // Note: This is fine to do a copy from FR32 to FR128, this is the 609 // same registers behind the scene and actually why it did not trigger 610 // any bugs before. 611 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1); 612 MachineInstrBuilder MIB = 613 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc); 614 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill)); 615 if (MMO) 616 MIB->addMemOperand(*FuncInfo.MF, MMO); 617 618 return true; 619 } 620 621 bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val, 622 X86AddressMode &AM, 623 MachineMemOperand *MMO, bool Aligned) { 624 // Handle 'null' like i32/i64 0. 625 if (isa<ConstantPointerNull>(Val)) 626 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext())); 627 628 // If this is a store of a simple constant, fold the constant into the store. 629 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { 630 unsigned Opc = 0; 631 bool Signed = true; 632 switch (VT.getSimpleVT().SimpleTy) { 633 default: break; 634 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8. 635 case MVT::i8: Opc = X86::MOV8mi; break; 636 case MVT::i16: Opc = X86::MOV16mi; break; 637 case MVT::i32: Opc = X86::MOV32mi; break; 638 case MVT::i64: 639 // Must be a 32-bit sign extended value. 640 if (isInt<32>(CI->getSExtValue())) 641 Opc = X86::MOV64mi32; 642 break; 643 } 644 645 if (Opc) { 646 MachineInstrBuilder MIB = 647 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc)); 648 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue() 649 : CI->getZExtValue()); 650 if (MMO) 651 MIB->addMemOperand(*FuncInfo.MF, MMO); 652 return true; 653 } 654 } 655 656 unsigned ValReg = getRegForValue(Val); 657 if (ValReg == 0) 658 return false; 659 660 bool ValKill = hasTrivialKill(Val); 661 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned); 662 } 663 664 /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of 665 /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g. 666 /// ISD::SIGN_EXTEND). 667 bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, 668 unsigned Src, EVT SrcVT, 669 unsigned &ResultReg) { 670 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, 671 Src, /*TODO: Kill=*/false); 672 if (RR == 0) 673 return false; 674 675 ResultReg = RR; 676 return true; 677 } 678 679 bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) { 680 // Handle constant address. 681 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 682 // Can't handle alternate code models yet. 683 if (TM.getCodeModel() != CodeModel::Small) 684 return false; 685 686 // Can't handle TLS yet. 687 if (GV->isThreadLocal()) 688 return false; 689 690 // RIP-relative addresses can't have additional register operands, so if 691 // we've already folded stuff into the addressing mode, just force the 692 // global value into its own register, which we can use as the basereg. 693 if (!Subtarget->isPICStyleRIPRel() || 694 (AM.Base.Reg == 0 && AM.IndexReg == 0)) { 695 // Okay, we've committed to selecting this global. Set up the address. 696 AM.GV = GV; 697 698 // Allow the subtarget to classify the global. 699 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV); 700 701 // If this reference is relative to the pic base, set it now. 702 if (isGlobalRelativeToPICBase(GVFlags)) { 703 // FIXME: How do we know Base.Reg is free?? 704 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 705 } 706 707 // Unless the ABI requires an extra load, return a direct reference to 708 // the global. 709 if (!isGlobalStubReference(GVFlags)) { 710 if (Subtarget->isPICStyleRIPRel()) { 711 // Use rip-relative addressing if we can. Above we verified that the 712 // base and index registers are unused. 713 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 714 AM.Base.Reg = X86::RIP; 715 } 716 AM.GVOpFlags = GVFlags; 717 return true; 718 } 719 720 // Ok, we need to do a load from a stub. If we've already loaded from 721 // this stub, reuse the loaded pointer, otherwise emit the load now. 722 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V); 723 unsigned LoadReg; 724 if (I != LocalValueMap.end() && I->second != 0) { 725 LoadReg = I->second; 726 } else { 727 // Issue load from stub. 728 unsigned Opc = 0; 729 const TargetRegisterClass *RC = nullptr; 730 X86AddressMode StubAM; 731 StubAM.Base.Reg = AM.Base.Reg; 732 StubAM.GV = GV; 733 StubAM.GVOpFlags = GVFlags; 734 735 // Prepare for inserting code in the local-value area. 736 SavePoint SaveInsertPt = enterLocalValueArea(); 737 738 if (TLI.getPointerTy(DL) == MVT::i64) { 739 Opc = X86::MOV64rm; 740 RC = &X86::GR64RegClass; 741 742 if (Subtarget->isPICStyleRIPRel()) 743 StubAM.Base.Reg = X86::RIP; 744 } else { 745 Opc = X86::MOV32rm; 746 RC = &X86::GR32RegClass; 747 } 748 749 LoadReg = createResultReg(RC); 750 MachineInstrBuilder LoadMI = 751 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg); 752 addFullAddress(LoadMI, StubAM); 753 754 // Ok, back to normal mode. 755 leaveLocalValueArea(SaveInsertPt); 756 757 // Prevent loading GV stub multiple times in same MBB. 758 LocalValueMap[V] = LoadReg; 759 } 760 761 // Now construct the final address. Note that the Disp, Scale, 762 // and Index values may already be set here. 763 AM.Base.Reg = LoadReg; 764 AM.GV = nullptr; 765 return true; 766 } 767 } 768 769 // If all else fails, try to materialize the value in a register. 770 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 771 if (AM.Base.Reg == 0) { 772 AM.Base.Reg = getRegForValue(V); 773 return AM.Base.Reg != 0; 774 } 775 if (AM.IndexReg == 0) { 776 assert(AM.Scale == 1 && "Scale with no index!"); 777 AM.IndexReg = getRegForValue(V); 778 return AM.IndexReg != 0; 779 } 780 } 781 782 return false; 783 } 784 785 /// X86SelectAddress - Attempt to fill in an address from the given value. 786 /// 787 bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) { 788 SmallVector<const Value *, 32> GEPs; 789 redo_gep: 790 const User *U = nullptr; 791 unsigned Opcode = Instruction::UserOp1; 792 if (const Instruction *I = dyn_cast<Instruction>(V)) { 793 // Don't walk into other basic blocks; it's possible we haven't 794 // visited them yet, so the instructions may not yet be assigned 795 // virtual registers. 796 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) || 797 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) { 798 Opcode = I->getOpcode(); 799 U = I; 800 } 801 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 802 Opcode = C->getOpcode(); 803 U = C; 804 } 805 806 if (PointerType *Ty = dyn_cast<PointerType>(V->getType())) 807 if (Ty->getAddressSpace() > 255) 808 // Fast instruction selection doesn't support the special 809 // address spaces. 810 return false; 811 812 switch (Opcode) { 813 default: break; 814 case Instruction::BitCast: 815 // Look past bitcasts. 816 return X86SelectAddress(U->getOperand(0), AM); 817 818 case Instruction::IntToPtr: 819 // Look past no-op inttoptrs. 820 if (TLI.getValueType(DL, U->getOperand(0)->getType()) == 821 TLI.getPointerTy(DL)) 822 return X86SelectAddress(U->getOperand(0), AM); 823 break; 824 825 case Instruction::PtrToInt: 826 // Look past no-op ptrtoints. 827 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL)) 828 return X86SelectAddress(U->getOperand(0), AM); 829 break; 830 831 case Instruction::Alloca: { 832 // Do static allocas. 833 const AllocaInst *A = cast<AllocaInst>(V); 834 DenseMap<const AllocaInst *, int>::iterator SI = 835 FuncInfo.StaticAllocaMap.find(A); 836 if (SI != FuncInfo.StaticAllocaMap.end()) { 837 AM.BaseType = X86AddressMode::FrameIndexBase; 838 AM.Base.FrameIndex = SI->second; 839 return true; 840 } 841 break; 842 } 843 844 case Instruction::Add: { 845 // Adds of constants are common and easy enough. 846 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) { 847 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue(); 848 // They have to fit in the 32-bit signed displacement field though. 849 if (isInt<32>(Disp)) { 850 AM.Disp = (uint32_t)Disp; 851 return X86SelectAddress(U->getOperand(0), AM); 852 } 853 } 854 break; 855 } 856 857 case Instruction::GetElementPtr: { 858 X86AddressMode SavedAM = AM; 859 860 // Pattern-match simple GEPs. 861 uint64_t Disp = (int32_t)AM.Disp; 862 unsigned IndexReg = AM.IndexReg; 863 unsigned Scale = AM.Scale; 864 gep_type_iterator GTI = gep_type_begin(U); 865 // Iterate through the indices, folding what we can. Constants can be 866 // folded, and one dynamic index can be handled, if the scale is supported. 867 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); 868 i != e; ++i, ++GTI) { 869 const Value *Op = *i; 870 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 871 const StructLayout *SL = DL.getStructLayout(STy); 872 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue()); 873 continue; 874 } 875 876 // A array/variable index is always of the form i*S where S is the 877 // constant scale size. See if we can push the scale into immediates. 878 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType()); 879 for (;;) { 880 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { 881 // Constant-offset addressing. 882 Disp += CI->getSExtValue() * S; 883 break; 884 } 885 if (canFoldAddIntoGEP(U, Op)) { 886 // A compatible add with a constant operand. Fold the constant. 887 ConstantInt *CI = 888 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1)); 889 Disp += CI->getSExtValue() * S; 890 // Iterate on the other operand. 891 Op = cast<AddOperator>(Op)->getOperand(0); 892 continue; 893 } 894 if (IndexReg == 0 && 895 (!AM.GV || !Subtarget->isPICStyleRIPRel()) && 896 (S == 1 || S == 2 || S == 4 || S == 8)) { 897 // Scaled-index addressing. 898 Scale = S; 899 IndexReg = getRegForGEPIndex(Op).first; 900 if (IndexReg == 0) 901 return false; 902 break; 903 } 904 // Unsupported. 905 goto unsupported_gep; 906 } 907 } 908 909 // Check for displacement overflow. 910 if (!isInt<32>(Disp)) 911 break; 912 913 AM.IndexReg = IndexReg; 914 AM.Scale = Scale; 915 AM.Disp = (uint32_t)Disp; 916 GEPs.push_back(V); 917 918 if (const GetElementPtrInst *GEP = 919 dyn_cast<GetElementPtrInst>(U->getOperand(0))) { 920 // Ok, the GEP indices were covered by constant-offset and scaled-index 921 // addressing. Update the address state and move on to examining the base. 922 V = GEP; 923 goto redo_gep; 924 } else if (X86SelectAddress(U->getOperand(0), AM)) { 925 return true; 926 } 927 928 // If we couldn't merge the gep value into this addr mode, revert back to 929 // our address and just match the value instead of completely failing. 930 AM = SavedAM; 931 932 for (SmallVectorImpl<const Value *>::reverse_iterator 933 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I) 934 if (handleConstantAddresses(*I, AM)) 935 return true; 936 937 return false; 938 unsupported_gep: 939 // Ok, the GEP indices weren't all covered. 940 break; 941 } 942 } 943 944 return handleConstantAddresses(V, AM); 945 } 946 947 /// X86SelectCallAddress - Attempt to fill in an address from the given value. 948 /// 949 bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) { 950 const User *U = nullptr; 951 unsigned Opcode = Instruction::UserOp1; 952 const Instruction *I = dyn_cast<Instruction>(V); 953 // Record if the value is defined in the same basic block. 954 // 955 // This information is crucial to know whether or not folding an 956 // operand is valid. 957 // Indeed, FastISel generates or reuses a virtual register for all 958 // operands of all instructions it selects. Obviously, the definition and 959 // its uses must use the same virtual register otherwise the produced 960 // code is incorrect. 961 // Before instruction selection, FunctionLoweringInfo::set sets the virtual 962 // registers for values that are alive across basic blocks. This ensures 963 // that the values are consistently set between across basic block, even 964 // if different instruction selection mechanisms are used (e.g., a mix of 965 // SDISel and FastISel). 966 // For values local to a basic block, the instruction selection process 967 // generates these virtual registers with whatever method is appropriate 968 // for its needs. In particular, FastISel and SDISel do not share the way 969 // local virtual registers are set. 970 // Therefore, this is impossible (or at least unsafe) to share values 971 // between basic blocks unless they use the same instruction selection 972 // method, which is not guarantee for X86. 973 // Moreover, things like hasOneUse could not be used accurately, if we 974 // allow to reference values across basic blocks whereas they are not 975 // alive across basic blocks initially. 976 bool InMBB = true; 977 if (I) { 978 Opcode = I->getOpcode(); 979 U = I; 980 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock(); 981 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) { 982 Opcode = C->getOpcode(); 983 U = C; 984 } 985 986 switch (Opcode) { 987 default: break; 988 case Instruction::BitCast: 989 // Look past bitcasts if its operand is in the same BB. 990 if (InMBB) 991 return X86SelectCallAddress(U->getOperand(0), AM); 992 break; 993 994 case Instruction::IntToPtr: 995 // Look past no-op inttoptrs if its operand is in the same BB. 996 if (InMBB && 997 TLI.getValueType(DL, U->getOperand(0)->getType()) == 998 TLI.getPointerTy(DL)) 999 return X86SelectCallAddress(U->getOperand(0), AM); 1000 break; 1001 1002 case Instruction::PtrToInt: 1003 // Look past no-op ptrtoints if its operand is in the same BB. 1004 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL)) 1005 return X86SelectCallAddress(U->getOperand(0), AM); 1006 break; 1007 } 1008 1009 // Handle constant address. 1010 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 1011 // Can't handle alternate code models yet. 1012 if (TM.getCodeModel() != CodeModel::Small) 1013 return false; 1014 1015 // RIP-relative addresses can't have additional register operands. 1016 if (Subtarget->isPICStyleRIPRel() && 1017 (AM.Base.Reg != 0 || AM.IndexReg != 0)) 1018 return false; 1019 1020 // Can't handle DLL Import. 1021 if (GV->hasDLLImportStorageClass()) 1022 return false; 1023 1024 // Can't handle TLS. 1025 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 1026 if (GVar->isThreadLocal()) 1027 return false; 1028 1029 // Okay, we've committed to selecting this global. Set up the basic address. 1030 AM.GV = GV; 1031 1032 // No ABI requires an extra load for anything other than DLLImport, which 1033 // we rejected above. Return a direct reference to the global. 1034 if (Subtarget->isPICStyleRIPRel()) { 1035 // Use rip-relative addressing if we can. Above we verified that the 1036 // base and index registers are unused. 1037 assert(AM.Base.Reg == 0 && AM.IndexReg == 0); 1038 AM.Base.Reg = X86::RIP; 1039 } else { 1040 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr); 1041 } 1042 1043 return true; 1044 } 1045 1046 // If all else fails, try to materialize the value in a register. 1047 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) { 1048 if (AM.Base.Reg == 0) { 1049 AM.Base.Reg = getRegForValue(V); 1050 return AM.Base.Reg != 0; 1051 } 1052 if (AM.IndexReg == 0) { 1053 assert(AM.Scale == 1 && "Scale with no index!"); 1054 AM.IndexReg = getRegForValue(V); 1055 return AM.IndexReg != 0; 1056 } 1057 } 1058 1059 return false; 1060 } 1061 1062 1063 /// X86SelectStore - Select and emit code to implement store instructions. 1064 bool X86FastISel::X86SelectStore(const Instruction *I) { 1065 // Atomic stores need special handling. 1066 const StoreInst *S = cast<StoreInst>(I); 1067 1068 if (S->isAtomic()) 1069 return false; 1070 1071 const Value *PtrV = I->getOperand(1); 1072 if (TLI.supportSwiftError()) { 1073 // Swifterror values can come from either a function parameter with 1074 // swifterror attribute or an alloca with swifterror attribute. 1075 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 1076 if (Arg->hasSwiftErrorAttr()) 1077 return false; 1078 } 1079 1080 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 1081 if (Alloca->isSwiftError()) 1082 return false; 1083 } 1084 } 1085 1086 const Value *Val = S->getValueOperand(); 1087 const Value *Ptr = S->getPointerOperand(); 1088 1089 MVT VT; 1090 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true)) 1091 return false; 1092 1093 unsigned Alignment = S->getAlignment(); 1094 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType()); 1095 if (Alignment == 0) // Ensure that codegen never sees alignment 0 1096 Alignment = ABIAlignment; 1097 bool Aligned = Alignment >= ABIAlignment; 1098 1099 X86AddressMode AM; 1100 if (!X86SelectAddress(Ptr, AM)) 1101 return false; 1102 1103 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned); 1104 } 1105 1106 /// X86SelectRet - Select and emit code to implement ret instructions. 1107 bool X86FastISel::X86SelectRet(const Instruction *I) { 1108 const ReturnInst *Ret = cast<ReturnInst>(I); 1109 const Function &F = *I->getParent()->getParent(); 1110 const X86MachineFunctionInfo *X86MFInfo = 1111 FuncInfo.MF->getInfo<X86MachineFunctionInfo>(); 1112 1113 if (!FuncInfo.CanLowerReturn) 1114 return false; 1115 1116 if (TLI.supportSwiftError() && 1117 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 1118 return false; 1119 1120 if (TLI.supportSplitCSR(FuncInfo.MF)) 1121 return false; 1122 1123 CallingConv::ID CC = F.getCallingConv(); 1124 if (CC != CallingConv::C && 1125 CC != CallingConv::Fast && 1126 CC != CallingConv::X86_FastCall && 1127 CC != CallingConv::X86_64_SysV) 1128 return false; 1129 1130 if (Subtarget->isCallingConvWin64(CC)) 1131 return false; 1132 1133 // Don't handle popping bytes on return for now. 1134 if (X86MFInfo->getBytesToPopOnReturn() != 0) 1135 return false; 1136 1137 // fastcc with -tailcallopt is intended to provide a guaranteed 1138 // tail call optimization. Fastisel doesn't know how to do that. 1139 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 1140 return false; 1141 1142 // Let SDISel handle vararg functions. 1143 if (F.isVarArg()) 1144 return false; 1145 1146 // Build a list of return value registers. 1147 SmallVector<unsigned, 4> RetRegs; 1148 1149 if (Ret->getNumOperands() > 0) { 1150 SmallVector<ISD::OutputArg, 4> Outs; 1151 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL); 1152 1153 // Analyze operands of the call, assigning locations to each operand. 1154 SmallVector<CCValAssign, 16> ValLocs; 1155 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext()); 1156 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1157 1158 const Value *RV = Ret->getOperand(0); 1159 unsigned Reg = getRegForValue(RV); 1160 if (Reg == 0) 1161 return false; 1162 1163 // Only handle a single return value for now. 1164 if (ValLocs.size() != 1) 1165 return false; 1166 1167 CCValAssign &VA = ValLocs[0]; 1168 1169 // Don't bother handling odd stuff for now. 1170 if (VA.getLocInfo() != CCValAssign::Full) 1171 return false; 1172 // Only handle register returns for now. 1173 if (!VA.isRegLoc()) 1174 return false; 1175 1176 // The calling-convention tables for x87 returns don't tell 1177 // the whole story. 1178 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) 1179 return false; 1180 1181 unsigned SrcReg = Reg + VA.getValNo(); 1182 EVT SrcVT = TLI.getValueType(DL, RV->getType()); 1183 EVT DstVT = VA.getValVT(); 1184 // Special handling for extended integers. 1185 if (SrcVT != DstVT) { 1186 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16) 1187 return false; 1188 1189 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt()) 1190 return false; 1191 1192 assert(DstVT == MVT::i32 && "X86 should always ext to i32"); 1193 1194 if (SrcVT == MVT::i1) { 1195 if (Outs[0].Flags.isSExt()) 1196 return false; 1197 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false); 1198 SrcVT = MVT::i8; 1199 } 1200 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : 1201 ISD::SIGN_EXTEND; 1202 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, 1203 SrcReg, /*TODO: Kill=*/false); 1204 } 1205 1206 // Make the copy. 1207 unsigned DstReg = VA.getLocReg(); 1208 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg); 1209 // Avoid a cross-class copy. This is very unlikely. 1210 if (!SrcRC->contains(DstReg)) 1211 return false; 1212 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1213 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg); 1214 1215 // Add register to return instruction. 1216 RetRegs.push_back(VA.getLocReg()); 1217 } 1218 1219 // Swift calling convention does not require we copy the sret argument 1220 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift. 1221 1222 // All x86 ABIs require that for returning structs by value we copy 1223 // the sret argument into %rax/%eax (depending on ABI) for the return. 1224 // We saved the argument into a virtual register in the entry block, 1225 // so now we copy the value out and into %rax/%eax. 1226 if (F.hasStructRetAttr() && CC != CallingConv::Swift) { 1227 unsigned Reg = X86MFInfo->getSRetReturnReg(); 1228 assert(Reg && 1229 "SRetReturnReg should have been set in LowerFormalArguments()!"); 1230 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1232 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg); 1233 RetRegs.push_back(RetReg); 1234 } 1235 1236 // Now emit the RET. 1237 MachineInstrBuilder MIB = 1238 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1239 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL)); 1240 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i) 1241 MIB.addReg(RetRegs[i], RegState::Implicit); 1242 return true; 1243 } 1244 1245 /// X86SelectLoad - Select and emit code to implement load instructions. 1246 /// 1247 bool X86FastISel::X86SelectLoad(const Instruction *I) { 1248 const LoadInst *LI = cast<LoadInst>(I); 1249 1250 // Atomic loads need special handling. 1251 if (LI->isAtomic()) 1252 return false; 1253 1254 const Value *SV = I->getOperand(0); 1255 if (TLI.supportSwiftError()) { 1256 // Swifterror values can come from either a function parameter with 1257 // swifterror attribute or an alloca with swifterror attribute. 1258 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 1259 if (Arg->hasSwiftErrorAttr()) 1260 return false; 1261 } 1262 1263 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 1264 if (Alloca->isSwiftError()) 1265 return false; 1266 } 1267 } 1268 1269 MVT VT; 1270 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true)) 1271 return false; 1272 1273 const Value *Ptr = LI->getPointerOperand(); 1274 1275 X86AddressMode AM; 1276 if (!X86SelectAddress(Ptr, AM)) 1277 return false; 1278 1279 unsigned Alignment = LI->getAlignment(); 1280 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType()); 1281 if (Alignment == 0) // Ensure that codegen never sees alignment 0 1282 Alignment = ABIAlignment; 1283 1284 unsigned ResultReg = 0; 1285 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg, 1286 Alignment)) 1287 return false; 1288 1289 updateValueMap(I, ResultReg); 1290 return true; 1291 } 1292 1293 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) { 1294 bool HasAVX = Subtarget->hasAVX(); 1295 bool X86ScalarSSEf32 = Subtarget->hasSSE1(); 1296 bool X86ScalarSSEf64 = Subtarget->hasSSE2(); 1297 1298 switch (VT.getSimpleVT().SimpleTy) { 1299 default: return 0; 1300 case MVT::i8: return X86::CMP8rr; 1301 case MVT::i16: return X86::CMP16rr; 1302 case MVT::i32: return X86::CMP32rr; 1303 case MVT::i64: return X86::CMP64rr; 1304 case MVT::f32: 1305 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0; 1306 case MVT::f64: 1307 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0; 1308 } 1309 } 1310 1311 /// If we have a comparison with RHS as the RHS of the comparison, return an 1312 /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0. 1313 static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) { 1314 int64_t Val = RHSC->getSExtValue(); 1315 switch (VT.getSimpleVT().SimpleTy) { 1316 // Otherwise, we can't fold the immediate into this comparison. 1317 default: 1318 return 0; 1319 case MVT::i8: 1320 return X86::CMP8ri; 1321 case MVT::i16: 1322 if (isInt<8>(Val)) 1323 return X86::CMP16ri8; 1324 return X86::CMP16ri; 1325 case MVT::i32: 1326 if (isInt<8>(Val)) 1327 return X86::CMP32ri8; 1328 return X86::CMP32ri; 1329 case MVT::i64: 1330 if (isInt<8>(Val)) 1331 return X86::CMP64ri8; 1332 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext 1333 // field. 1334 if (isInt<32>(Val)) 1335 return X86::CMP64ri32; 1336 return 0; 1337 } 1338 } 1339 1340 bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, 1341 EVT VT, DebugLoc CurDbgLoc) { 1342 unsigned Op0Reg = getRegForValue(Op0); 1343 if (Op0Reg == 0) return false; 1344 1345 // Handle 'null' like i32/i64 0. 1346 if (isa<ConstantPointerNull>(Op1)) 1347 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext())); 1348 1349 // We have two options: compare with register or immediate. If the RHS of 1350 // the compare is an immediate that we can fold into this compare, use 1351 // CMPri, otherwise use CMPrr. 1352 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) { 1353 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) { 1354 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc)) 1355 .addReg(Op0Reg) 1356 .addImm(Op1C->getSExtValue()); 1357 return true; 1358 } 1359 } 1360 1361 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget); 1362 if (CompareOpc == 0) return false; 1363 1364 unsigned Op1Reg = getRegForValue(Op1); 1365 if (Op1Reg == 0) return false; 1366 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc)) 1367 .addReg(Op0Reg) 1368 .addReg(Op1Reg); 1369 1370 return true; 1371 } 1372 1373 bool X86FastISel::X86SelectCmp(const Instruction *I) { 1374 const CmpInst *CI = cast<CmpInst>(I); 1375 1376 MVT VT; 1377 if (!isTypeLegal(I->getOperand(0)->getType(), VT)) 1378 return false; 1379 1380 // Try to optimize or fold the cmp. 1381 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1382 unsigned ResultReg = 0; 1383 switch (Predicate) { 1384 default: break; 1385 case CmpInst::FCMP_FALSE: { 1386 ResultReg = createResultReg(&X86::GR32RegClass); 1387 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0), 1388 ResultReg); 1389 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true, 1390 X86::sub_8bit); 1391 if (!ResultReg) 1392 return false; 1393 break; 1394 } 1395 case CmpInst::FCMP_TRUE: { 1396 ResultReg = createResultReg(&X86::GR8RegClass); 1397 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 1398 ResultReg).addImm(1); 1399 break; 1400 } 1401 } 1402 1403 if (ResultReg) { 1404 updateValueMap(I, ResultReg); 1405 return true; 1406 } 1407 1408 const Value *LHS = CI->getOperand(0); 1409 const Value *RHS = CI->getOperand(1); 1410 1411 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 1412 // We don't have to materialize a zero constant for this case and can just use 1413 // %x again on the RHS. 1414 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1415 const auto *RHSC = dyn_cast<ConstantFP>(RHS); 1416 if (RHSC && RHSC->isNullValue()) 1417 RHS = LHS; 1418 } 1419 1420 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 1421 static unsigned SETFOpcTable[2][3] = { 1422 { X86::SETEr, X86::SETNPr, X86::AND8rr }, 1423 { X86::SETNEr, X86::SETPr, X86::OR8rr } 1424 }; 1425 unsigned *SETFOpc = nullptr; 1426 switch (Predicate) { 1427 default: break; 1428 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break; 1429 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break; 1430 } 1431 1432 ResultReg = createResultReg(&X86::GR8RegClass); 1433 if (SETFOpc) { 1434 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc())) 1435 return false; 1436 1437 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass); 1438 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass); 1439 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]), 1440 FlagReg1); 1441 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]), 1442 FlagReg2); 1443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]), 1444 ResultReg).addReg(FlagReg1).addReg(FlagReg2); 1445 updateValueMap(I, ResultReg); 1446 return true; 1447 } 1448 1449 X86::CondCode CC; 1450 bool SwapArgs; 1451 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); 1452 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1453 unsigned Opc = X86::getSETFromCond(CC); 1454 1455 if (SwapArgs) 1456 std::swap(LHS, RHS); 1457 1458 // Emit a compare of LHS/RHS. 1459 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc())) 1460 return false; 1461 1462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 1463 updateValueMap(I, ResultReg); 1464 return true; 1465 } 1466 1467 bool X86FastISel::X86SelectZExt(const Instruction *I) { 1468 EVT DstVT = TLI.getValueType(DL, I->getType()); 1469 if (!TLI.isTypeLegal(DstVT)) 1470 return false; 1471 1472 unsigned ResultReg = getRegForValue(I->getOperand(0)); 1473 if (ResultReg == 0) 1474 return false; 1475 1476 // Handle zero-extension from i1 to i8, which is common. 1477 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType()); 1478 if (SrcVT.SimpleTy == MVT::i1) { 1479 // Set the high bits to zero. 1480 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false); 1481 SrcVT = MVT::i8; 1482 1483 if (ResultReg == 0) 1484 return false; 1485 } 1486 1487 if (DstVT == MVT::i64) { 1488 // Handle extension to 64-bits via sub-register shenanigans. 1489 unsigned MovInst; 1490 1491 switch (SrcVT.SimpleTy) { 1492 case MVT::i8: MovInst = X86::MOVZX32rr8; break; 1493 case MVT::i16: MovInst = X86::MOVZX32rr16; break; 1494 case MVT::i32: MovInst = X86::MOV32rr; break; 1495 default: llvm_unreachable("Unexpected zext to i64 source type"); 1496 } 1497 1498 unsigned Result32 = createResultReg(&X86::GR32RegClass); 1499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32) 1500 .addReg(ResultReg); 1501 1502 ResultReg = createResultReg(&X86::GR64RegClass); 1503 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG), 1504 ResultReg) 1505 .addImm(0).addReg(Result32).addImm(X86::sub_32bit); 1506 } else if (DstVT != MVT::i8) { 1507 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND, 1508 ResultReg, /*Kill=*/true); 1509 if (ResultReg == 0) 1510 return false; 1511 } 1512 1513 updateValueMap(I, ResultReg); 1514 return true; 1515 } 1516 1517 bool X86FastISel::X86SelectBranch(const Instruction *I) { 1518 // Unconditional branches are selected by tablegen-generated code. 1519 // Handle a conditional branch. 1520 const BranchInst *BI = cast<BranchInst>(I); 1521 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)]; 1522 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)]; 1523 1524 // Fold the common case of a conditional branch with a comparison 1525 // in the same block (values defined on other blocks may not have 1526 // initialized registers). 1527 X86::CondCode CC; 1528 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) { 1529 if (CI->hasOneUse() && CI->getParent() == I->getParent()) { 1530 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType()); 1531 1532 // Try to optimize or fold the cmp. 1533 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1534 switch (Predicate) { 1535 default: break; 1536 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true; 1537 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true; 1538 } 1539 1540 const Value *CmpLHS = CI->getOperand(0); 1541 const Value *CmpRHS = CI->getOperand(1); 1542 1543 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 1544 // 0.0. 1545 // We don't have to materialize a zero constant for this case and can just 1546 // use %x again on the RHS. 1547 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 1548 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 1549 if (CmpRHSC && CmpRHSC->isNullValue()) 1550 CmpRHS = CmpLHS; 1551 } 1552 1553 // Try to take advantage of fallthrough opportunities. 1554 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1555 std::swap(TrueMBB, FalseMBB); 1556 Predicate = CmpInst::getInversePredicate(Predicate); 1557 } 1558 1559 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition 1560 // code check. Instead two branch instructions are required to check all 1561 // the flags. First we change the predicate to a supported condition code, 1562 // which will be the first branch. Later one we will emit the second 1563 // branch. 1564 bool NeedExtraBranch = false; 1565 switch (Predicate) { 1566 default: break; 1567 case CmpInst::FCMP_OEQ: 1568 std::swap(TrueMBB, FalseMBB); // fall-through 1569 case CmpInst::FCMP_UNE: 1570 NeedExtraBranch = true; 1571 Predicate = CmpInst::FCMP_ONE; 1572 break; 1573 } 1574 1575 bool SwapArgs; 1576 unsigned BranchOpc; 1577 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate); 1578 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1579 1580 BranchOpc = X86::GetCondBranchFromCond(CC); 1581 if (SwapArgs) 1582 std::swap(CmpLHS, CmpRHS); 1583 1584 // Emit a compare of the LHS and RHS, setting the flags. 1585 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc())) 1586 return false; 1587 1588 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc)) 1589 .addMBB(TrueMBB); 1590 1591 // X86 requires a second branch to handle UNE (and OEQ, which is mapped 1592 // to UNE above). 1593 if (NeedExtraBranch) { 1594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1)) 1595 .addMBB(TrueMBB); 1596 } 1597 1598 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1599 return true; 1600 } 1601 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) { 1602 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which 1603 // typically happen for _Bool and C++ bools. 1604 MVT SourceVT; 1605 if (TI->hasOneUse() && TI->getParent() == I->getParent() && 1606 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) { 1607 unsigned TestOpc = 0; 1608 switch (SourceVT.SimpleTy) { 1609 default: break; 1610 case MVT::i8: TestOpc = X86::TEST8ri; break; 1611 case MVT::i16: TestOpc = X86::TEST16ri; break; 1612 case MVT::i32: TestOpc = X86::TEST32ri; break; 1613 case MVT::i64: TestOpc = X86::TEST64ri32; break; 1614 } 1615 if (TestOpc) { 1616 unsigned OpReg = getRegForValue(TI->getOperand(0)); 1617 if (OpReg == 0) return false; 1618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc)) 1619 .addReg(OpReg).addImm(1); 1620 1621 unsigned JmpOpc = X86::JNE_1; 1622 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) { 1623 std::swap(TrueMBB, FalseMBB); 1624 JmpOpc = X86::JE_1; 1625 } 1626 1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc)) 1628 .addMBB(TrueMBB); 1629 1630 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1631 return true; 1632 } 1633 } 1634 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) { 1635 // Fake request the condition, otherwise the intrinsic might be completely 1636 // optimized away. 1637 unsigned TmpReg = getRegForValue(BI->getCondition()); 1638 if (TmpReg == 0) 1639 return false; 1640 1641 unsigned BranchOpc = X86::GetCondBranchFromCond(CC); 1642 1643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc)) 1644 .addMBB(TrueMBB); 1645 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1646 return true; 1647 } 1648 1649 // Otherwise do a clumsy setcc and re-test it. 1650 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used 1651 // in an explicit cast, so make sure to handle that correctly. 1652 unsigned OpReg = getRegForValue(BI->getCondition()); 1653 if (OpReg == 0) return false; 1654 1655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1656 .addReg(OpReg).addImm(1); 1657 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1)) 1658 .addMBB(TrueMBB); 1659 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB); 1660 return true; 1661 } 1662 1663 bool X86FastISel::X86SelectShift(const Instruction *I) { 1664 unsigned CReg = 0, OpReg = 0; 1665 const TargetRegisterClass *RC = nullptr; 1666 if (I->getType()->isIntegerTy(8)) { 1667 CReg = X86::CL; 1668 RC = &X86::GR8RegClass; 1669 switch (I->getOpcode()) { 1670 case Instruction::LShr: OpReg = X86::SHR8rCL; break; 1671 case Instruction::AShr: OpReg = X86::SAR8rCL; break; 1672 case Instruction::Shl: OpReg = X86::SHL8rCL; break; 1673 default: return false; 1674 } 1675 } else if (I->getType()->isIntegerTy(16)) { 1676 CReg = X86::CX; 1677 RC = &X86::GR16RegClass; 1678 switch (I->getOpcode()) { 1679 case Instruction::LShr: OpReg = X86::SHR16rCL; break; 1680 case Instruction::AShr: OpReg = X86::SAR16rCL; break; 1681 case Instruction::Shl: OpReg = X86::SHL16rCL; break; 1682 default: return false; 1683 } 1684 } else if (I->getType()->isIntegerTy(32)) { 1685 CReg = X86::ECX; 1686 RC = &X86::GR32RegClass; 1687 switch (I->getOpcode()) { 1688 case Instruction::LShr: OpReg = X86::SHR32rCL; break; 1689 case Instruction::AShr: OpReg = X86::SAR32rCL; break; 1690 case Instruction::Shl: OpReg = X86::SHL32rCL; break; 1691 default: return false; 1692 } 1693 } else if (I->getType()->isIntegerTy(64)) { 1694 CReg = X86::RCX; 1695 RC = &X86::GR64RegClass; 1696 switch (I->getOpcode()) { 1697 case Instruction::LShr: OpReg = X86::SHR64rCL; break; 1698 case Instruction::AShr: OpReg = X86::SAR64rCL; break; 1699 case Instruction::Shl: OpReg = X86::SHL64rCL; break; 1700 default: return false; 1701 } 1702 } else { 1703 return false; 1704 } 1705 1706 MVT VT; 1707 if (!isTypeLegal(I->getType(), VT)) 1708 return false; 1709 1710 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1711 if (Op0Reg == 0) return false; 1712 1713 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1714 if (Op1Reg == 0) return false; 1715 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY), 1716 CReg).addReg(Op1Reg); 1717 1718 // The shift instruction uses X86::CL. If we defined a super-register 1719 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here. 1720 if (CReg != X86::CL) 1721 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1722 TII.get(TargetOpcode::KILL), X86::CL) 1723 .addReg(CReg, RegState::Kill); 1724 1725 unsigned ResultReg = createResultReg(RC); 1726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg) 1727 .addReg(Op0Reg); 1728 updateValueMap(I, ResultReg); 1729 return true; 1730 } 1731 1732 bool X86FastISel::X86SelectDivRem(const Instruction *I) { 1733 const static unsigned NumTypes = 4; // i8, i16, i32, i64 1734 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem 1735 const static bool S = true; // IsSigned 1736 const static bool U = false; // !IsSigned 1737 const static unsigned Copy = TargetOpcode::COPY; 1738 // For the X86 DIV/IDIV instruction, in most cases the dividend 1739 // (numerator) must be in a specific register pair highreg:lowreg, 1740 // producing the quotient in lowreg and the remainder in highreg. 1741 // For most data types, to set up the instruction, the dividend is 1742 // copied into lowreg, and lowreg is sign-extended or zero-extended 1743 // into highreg. The exception is i8, where the dividend is defined 1744 // as a single register rather than a register pair, and we 1745 // therefore directly sign-extend or zero-extend the dividend into 1746 // lowreg, instead of copying, and ignore the highreg. 1747 const static struct DivRemEntry { 1748 // The following portion depends only on the data type. 1749 const TargetRegisterClass *RC; 1750 unsigned LowInReg; // low part of the register pair 1751 unsigned HighInReg; // high part of the register pair 1752 // The following portion depends on both the data type and the operation. 1753 struct DivRemResult { 1754 unsigned OpDivRem; // The specific DIV/IDIV opcode to use. 1755 unsigned OpSignExtend; // Opcode for sign-extending lowreg into 1756 // highreg, or copying a zero into highreg. 1757 unsigned OpCopy; // Opcode for copying dividend into lowreg, or 1758 // zero/sign-extending into lowreg for i8. 1759 unsigned DivRemResultReg; // Register containing the desired result. 1760 bool IsOpSigned; // Whether to use signed or unsigned form. 1761 } ResultTable[NumOps]; 1762 } OpTable[NumTypes] = { 1763 { &X86::GR8RegClass, X86::AX, 0, { 1764 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv 1765 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem 1766 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv 1767 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem 1768 } 1769 }, // i8 1770 { &X86::GR16RegClass, X86::AX, X86::DX, { 1771 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv 1772 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem 1773 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv 1774 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem 1775 } 1776 }, // i16 1777 { &X86::GR32RegClass, X86::EAX, X86::EDX, { 1778 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv 1779 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem 1780 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv 1781 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem 1782 } 1783 }, // i32 1784 { &X86::GR64RegClass, X86::RAX, X86::RDX, { 1785 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv 1786 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem 1787 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv 1788 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem 1789 } 1790 }, // i64 1791 }; 1792 1793 MVT VT; 1794 if (!isTypeLegal(I->getType(), VT)) 1795 return false; 1796 1797 unsigned TypeIndex, OpIndex; 1798 switch (VT.SimpleTy) { 1799 default: return false; 1800 case MVT::i8: TypeIndex = 0; break; 1801 case MVT::i16: TypeIndex = 1; break; 1802 case MVT::i32: TypeIndex = 2; break; 1803 case MVT::i64: TypeIndex = 3; 1804 if (!Subtarget->is64Bit()) 1805 return false; 1806 break; 1807 } 1808 1809 switch (I->getOpcode()) { 1810 default: llvm_unreachable("Unexpected div/rem opcode"); 1811 case Instruction::SDiv: OpIndex = 0; break; 1812 case Instruction::SRem: OpIndex = 1; break; 1813 case Instruction::UDiv: OpIndex = 2; break; 1814 case Instruction::URem: OpIndex = 3; break; 1815 } 1816 1817 const DivRemEntry &TypeEntry = OpTable[TypeIndex]; 1818 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex]; 1819 unsigned Op0Reg = getRegForValue(I->getOperand(0)); 1820 if (Op0Reg == 0) 1821 return false; 1822 unsigned Op1Reg = getRegForValue(I->getOperand(1)); 1823 if (Op1Reg == 0) 1824 return false; 1825 1826 // Move op0 into low-order input register. 1827 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1828 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg); 1829 // Zero-extend or sign-extend into high-order input register. 1830 if (OpEntry.OpSignExtend) { 1831 if (OpEntry.IsOpSigned) 1832 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1833 TII.get(OpEntry.OpSignExtend)); 1834 else { 1835 unsigned Zero32 = createResultReg(&X86::GR32RegClass); 1836 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1837 TII.get(X86::MOV32r0), Zero32); 1838 1839 // Copy the zero into the appropriate sub/super/identical physical 1840 // register. Unfortunately the operations needed are not uniform enough 1841 // to fit neatly into the table above. 1842 if (VT.SimpleTy == MVT::i16) { 1843 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1844 TII.get(Copy), TypeEntry.HighInReg) 1845 .addReg(Zero32, 0, X86::sub_16bit); 1846 } else if (VT.SimpleTy == MVT::i32) { 1847 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1848 TII.get(Copy), TypeEntry.HighInReg) 1849 .addReg(Zero32); 1850 } else if (VT.SimpleTy == MVT::i64) { 1851 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1852 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg) 1853 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit); 1854 } 1855 } 1856 } 1857 // Generate the DIV/IDIV instruction. 1858 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1859 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg); 1860 // For i8 remainder, we can't reference AH directly, as we'll end 1861 // up with bogus copies like %R9B = COPY %AH. Reference AX 1862 // instead to prevent AH references in a REX instruction. 1863 // 1864 // The current assumption of the fast register allocator is that isel 1865 // won't generate explicit references to the GPR8_NOREX registers. If 1866 // the allocator and/or the backend get enhanced to be more robust in 1867 // that regard, this can be, and should be, removed. 1868 unsigned ResultReg = 0; 1869 if ((I->getOpcode() == Instruction::SRem || 1870 I->getOpcode() == Instruction::URem) && 1871 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) { 1872 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass); 1873 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass); 1874 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 1875 TII.get(Copy), SourceSuperReg).addReg(X86::AX); 1876 1877 // Shift AX right by 8 bits instead of using AH. 1878 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri), 1879 ResultSuperReg).addReg(SourceSuperReg).addImm(8); 1880 1881 // Now reference the 8-bit subreg of the result. 1882 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg, 1883 /*Kill=*/true, X86::sub_8bit); 1884 } 1885 // Copy the result out of the physreg if we haven't already. 1886 if (!ResultReg) { 1887 ResultReg = createResultReg(TypeEntry.RC); 1888 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg) 1889 .addReg(OpEntry.DivRemResultReg); 1890 } 1891 updateValueMap(I, ResultReg); 1892 1893 return true; 1894 } 1895 1896 /// \brief Emit a conditional move instruction (if the are supported) to lower 1897 /// the select. 1898 bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) { 1899 // Check if the subtarget supports these instructions. 1900 if (!Subtarget->hasCMov()) 1901 return false; 1902 1903 // FIXME: Add support for i8. 1904 if (RetVT < MVT::i16 || RetVT > MVT::i64) 1905 return false; 1906 1907 const Value *Cond = I->getOperand(0); 1908 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 1909 bool NeedTest = true; 1910 X86::CondCode CC = X86::COND_NE; 1911 1912 // Optimize conditions coming from a compare if both instructions are in the 1913 // same basic block (values defined in other basic blocks may not have 1914 // initialized registers). 1915 const auto *CI = dyn_cast<CmpInst>(Cond); 1916 if (CI && (CI->getParent() == I->getParent())) { 1917 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 1918 1919 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction. 1920 static unsigned SETFOpcTable[2][3] = { 1921 { X86::SETNPr, X86::SETEr , X86::TEST8rr }, 1922 { X86::SETPr, X86::SETNEr, X86::OR8rr } 1923 }; 1924 unsigned *SETFOpc = nullptr; 1925 switch (Predicate) { 1926 default: break; 1927 case CmpInst::FCMP_OEQ: 1928 SETFOpc = &SETFOpcTable[0][0]; 1929 Predicate = CmpInst::ICMP_NE; 1930 break; 1931 case CmpInst::FCMP_UNE: 1932 SETFOpc = &SETFOpcTable[1][0]; 1933 Predicate = CmpInst::ICMP_NE; 1934 break; 1935 } 1936 1937 bool NeedSwap; 1938 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate); 1939 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code."); 1940 1941 const Value *CmpLHS = CI->getOperand(0); 1942 const Value *CmpRHS = CI->getOperand(1); 1943 if (NeedSwap) 1944 std::swap(CmpLHS, CmpRHS); 1945 1946 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType()); 1947 // Emit a compare of the LHS and RHS, setting the flags. 1948 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc())) 1949 return false; 1950 1951 if (SETFOpc) { 1952 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass); 1953 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass); 1954 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]), 1955 FlagReg1); 1956 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]), 1957 FlagReg2); 1958 auto const &II = TII.get(SETFOpc[2]); 1959 if (II.getNumDefs()) { 1960 unsigned TmpReg = createResultReg(&X86::GR8RegClass); 1961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg) 1962 .addReg(FlagReg2).addReg(FlagReg1); 1963 } else { 1964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II) 1965 .addReg(FlagReg2).addReg(FlagReg1); 1966 } 1967 } 1968 NeedTest = false; 1969 } else if (foldX86XALUIntrinsic(CC, I, Cond)) { 1970 // Fake request the condition, otherwise the intrinsic might be completely 1971 // optimized away. 1972 unsigned TmpReg = getRegForValue(Cond); 1973 if (TmpReg == 0) 1974 return false; 1975 1976 NeedTest = false; 1977 } 1978 1979 if (NeedTest) { 1980 // Selects operate on i1, however, CondReg is 8 bits width and may contain 1981 // garbage. Indeed, only the less significant bit is supposed to be 1982 // accurate. If we read more than the lsb, we may see non-zero values 1983 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for 1984 // the select. This is achieved by performing TEST against 1. 1985 unsigned CondReg = getRegForValue(Cond); 1986 if (CondReg == 0) 1987 return false; 1988 bool CondIsKill = hasTrivialKill(Cond); 1989 1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 1991 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1); 1992 } 1993 1994 const Value *LHS = I->getOperand(1); 1995 const Value *RHS = I->getOperand(2); 1996 1997 unsigned RHSReg = getRegForValue(RHS); 1998 bool RHSIsKill = hasTrivialKill(RHS); 1999 2000 unsigned LHSReg = getRegForValue(LHS); 2001 bool LHSIsKill = hasTrivialKill(LHS); 2002 2003 if (!LHSReg || !RHSReg) 2004 return false; 2005 2006 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize()); 2007 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill, 2008 LHSReg, LHSIsKill); 2009 updateValueMap(I, ResultReg); 2010 return true; 2011 } 2012 2013 /// \brief Emit SSE or AVX instructions to lower the select. 2014 /// 2015 /// Try to use SSE1/SSE2 instructions to simulate a select without branches. 2016 /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary 2017 /// SSE instructions are available. If AVX is available, try to use a VBLENDV. 2018 bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) { 2019 // Optimize conditions coming from a compare if both instructions are in the 2020 // same basic block (values defined in other basic blocks may not have 2021 // initialized registers). 2022 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0)); 2023 if (!CI || (CI->getParent() != I->getParent())) 2024 return false; 2025 2026 if (I->getType() != CI->getOperand(0)->getType() || 2027 !((Subtarget->hasSSE1() && RetVT == MVT::f32) || 2028 (Subtarget->hasSSE2() && RetVT == MVT::f64))) 2029 return false; 2030 2031 const Value *CmpLHS = CI->getOperand(0); 2032 const Value *CmpRHS = CI->getOperand(1); 2033 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2034 2035 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0. 2036 // We don't have to materialize a zero constant for this case and can just use 2037 // %x again on the RHS. 2038 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) { 2039 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS); 2040 if (CmpRHSC && CmpRHSC->isNullValue()) 2041 CmpRHS = CmpLHS; 2042 } 2043 2044 unsigned CC; 2045 bool NeedSwap; 2046 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate); 2047 if (CC > 7) 2048 return false; 2049 2050 if (NeedSwap) 2051 std::swap(CmpLHS, CmpRHS); 2052 2053 // Choose the SSE instruction sequence based on data type (float or double). 2054 static unsigned OpcTable[2][4] = { 2055 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr }, 2056 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr } 2057 }; 2058 2059 unsigned *Opc = nullptr; 2060 switch (RetVT.SimpleTy) { 2061 default: return false; 2062 case MVT::f32: Opc = &OpcTable[0][0]; break; 2063 case MVT::f64: Opc = &OpcTable[1][0]; break; 2064 } 2065 2066 const Value *LHS = I->getOperand(1); 2067 const Value *RHS = I->getOperand(2); 2068 2069 unsigned LHSReg = getRegForValue(LHS); 2070 bool LHSIsKill = hasTrivialKill(LHS); 2071 2072 unsigned RHSReg = getRegForValue(RHS); 2073 bool RHSIsKill = hasTrivialKill(RHS); 2074 2075 unsigned CmpLHSReg = getRegForValue(CmpLHS); 2076 bool CmpLHSIsKill = hasTrivialKill(CmpLHS); 2077 2078 unsigned CmpRHSReg = getRegForValue(CmpRHS); 2079 bool CmpRHSIsKill = hasTrivialKill(CmpRHS); 2080 2081 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS) 2082 return false; 2083 2084 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2085 unsigned ResultReg; 2086 2087 if (Subtarget->hasAVX()) { 2088 const TargetRegisterClass *FR32 = &X86::FR32RegClass; 2089 const TargetRegisterClass *VR128 = &X86::VR128RegClass; 2090 2091 // If we have AVX, create 1 blendv instead of 3 logic instructions. 2092 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly 2093 // uses XMM0 as the selection register. That may need just as many 2094 // instructions as the AND/ANDN/OR sequence due to register moves, so 2095 // don't bother. 2096 unsigned CmpOpcode = 2097 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr; 2098 unsigned BlendOpcode = 2099 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr; 2100 2101 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill, 2102 CmpRHSReg, CmpRHSIsKill, CC); 2103 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill, 2104 LHSReg, LHSIsKill, CmpReg, true); 2105 ResultReg = createResultReg(RC); 2106 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2107 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg); 2108 } else { 2109 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill, 2110 CmpRHSReg, CmpRHSIsKill, CC); 2111 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false, 2112 LHSReg, LHSIsKill); 2113 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true, 2114 RHSReg, RHSIsKill); 2115 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true, 2116 AndReg, /*IsKill=*/true); 2117 } 2118 updateValueMap(I, ResultReg); 2119 return true; 2120 } 2121 2122 bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) { 2123 // These are pseudo CMOV instructions and will be later expanded into control- 2124 // flow. 2125 unsigned Opc; 2126 switch (RetVT.SimpleTy) { 2127 default: return false; 2128 case MVT::i8: Opc = X86::CMOV_GR8; break; 2129 case MVT::i16: Opc = X86::CMOV_GR16; break; 2130 case MVT::i32: Opc = X86::CMOV_GR32; break; 2131 case MVT::f32: Opc = X86::CMOV_FR32; break; 2132 case MVT::f64: Opc = X86::CMOV_FR64; break; 2133 } 2134 2135 const Value *Cond = I->getOperand(0); 2136 X86::CondCode CC = X86::COND_NE; 2137 2138 // Optimize conditions coming from a compare if both instructions are in the 2139 // same basic block (values defined in other basic blocks may not have 2140 // initialized registers). 2141 const auto *CI = dyn_cast<CmpInst>(Cond); 2142 if (CI && (CI->getParent() == I->getParent())) { 2143 bool NeedSwap; 2144 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate()); 2145 if (CC > X86::LAST_VALID_COND) 2146 return false; 2147 2148 const Value *CmpLHS = CI->getOperand(0); 2149 const Value *CmpRHS = CI->getOperand(1); 2150 2151 if (NeedSwap) 2152 std::swap(CmpLHS, CmpRHS); 2153 2154 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType()); 2155 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc())) 2156 return false; 2157 } else { 2158 unsigned CondReg = getRegForValue(Cond); 2159 if (CondReg == 0) 2160 return false; 2161 bool CondIsKill = hasTrivialKill(Cond); 2162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri)) 2163 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1); 2164 } 2165 2166 const Value *LHS = I->getOperand(1); 2167 const Value *RHS = I->getOperand(2); 2168 2169 unsigned LHSReg = getRegForValue(LHS); 2170 bool LHSIsKill = hasTrivialKill(LHS); 2171 2172 unsigned RHSReg = getRegForValue(RHS); 2173 bool RHSIsKill = hasTrivialKill(RHS); 2174 2175 if (!LHSReg || !RHSReg) 2176 return false; 2177 2178 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2179 2180 unsigned ResultReg = 2181 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC); 2182 updateValueMap(I, ResultReg); 2183 return true; 2184 } 2185 2186 bool X86FastISel::X86SelectSelect(const Instruction *I) { 2187 MVT RetVT; 2188 if (!isTypeLegal(I->getType(), RetVT)) 2189 return false; 2190 2191 // Check if we can fold the select. 2192 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) { 2193 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI); 2194 const Value *Opnd = nullptr; 2195 switch (Predicate) { 2196 default: break; 2197 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break; 2198 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break; 2199 } 2200 // No need for a select anymore - this is an unconditional move. 2201 if (Opnd) { 2202 unsigned OpReg = getRegForValue(Opnd); 2203 if (OpReg == 0) 2204 return false; 2205 bool OpIsKill = hasTrivialKill(Opnd); 2206 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT); 2207 unsigned ResultReg = createResultReg(RC); 2208 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2209 TII.get(TargetOpcode::COPY), ResultReg) 2210 .addReg(OpReg, getKillRegState(OpIsKill)); 2211 updateValueMap(I, ResultReg); 2212 return true; 2213 } 2214 } 2215 2216 // First try to use real conditional move instructions. 2217 if (X86FastEmitCMoveSelect(RetVT, I)) 2218 return true; 2219 2220 // Try to use a sequence of SSE instructions to simulate a conditional move. 2221 if (X86FastEmitSSESelect(RetVT, I)) 2222 return true; 2223 2224 // Fall-back to pseudo conditional move instructions, which will be later 2225 // converted to control-flow. 2226 if (X86FastEmitPseudoSelect(RetVT, I)) 2227 return true; 2228 2229 return false; 2230 } 2231 2232 bool X86FastISel::X86SelectSIToFP(const Instruction *I) { 2233 // The target-independent selection algorithm in FastISel already knows how 2234 // to select a SINT_TO_FP if the target is SSE but not AVX. 2235 // Early exit if the subtarget doesn't have AVX. 2236 if (!Subtarget->hasAVX()) 2237 return false; 2238 2239 if (!I->getOperand(0)->getType()->isIntegerTy(32)) 2240 return false; 2241 2242 // Select integer to float/double conversion. 2243 unsigned OpReg = getRegForValue(I->getOperand(0)); 2244 if (OpReg == 0) 2245 return false; 2246 2247 const TargetRegisterClass *RC = nullptr; 2248 unsigned Opcode; 2249 2250 if (I->getType()->isDoubleTy()) { 2251 // sitofp int -> double 2252 Opcode = X86::VCVTSI2SDrr; 2253 RC = &X86::FR64RegClass; 2254 } else if (I->getType()->isFloatTy()) { 2255 // sitofp int -> float 2256 Opcode = X86::VCVTSI2SSrr; 2257 RC = &X86::FR32RegClass; 2258 } else 2259 return false; 2260 2261 unsigned ImplicitDefReg = createResultReg(RC); 2262 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2263 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2264 unsigned ResultReg = 2265 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false); 2266 updateValueMap(I, ResultReg); 2267 return true; 2268 } 2269 2270 // Helper method used by X86SelectFPExt and X86SelectFPTrunc. 2271 bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I, 2272 unsigned TargetOpc, 2273 const TargetRegisterClass *RC) { 2274 assert((I->getOpcode() == Instruction::FPExt || 2275 I->getOpcode() == Instruction::FPTrunc) && 2276 "Instruction must be an FPExt or FPTrunc!"); 2277 2278 unsigned OpReg = getRegForValue(I->getOperand(0)); 2279 if (OpReg == 0) 2280 return false; 2281 2282 unsigned ResultReg = createResultReg(RC); 2283 MachineInstrBuilder MIB; 2284 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc), 2285 ResultReg); 2286 if (Subtarget->hasAVX()) 2287 MIB.addReg(OpReg); 2288 MIB.addReg(OpReg); 2289 updateValueMap(I, ResultReg); 2290 return true; 2291 } 2292 2293 bool X86FastISel::X86SelectFPExt(const Instruction *I) { 2294 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() && 2295 I->getOperand(0)->getType()->isFloatTy()) { 2296 // fpext from float to double. 2297 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr; 2298 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass); 2299 } 2300 2301 return false; 2302 } 2303 2304 bool X86FastISel::X86SelectFPTrunc(const Instruction *I) { 2305 if (X86ScalarSSEf64 && I->getType()->isFloatTy() && 2306 I->getOperand(0)->getType()->isDoubleTy()) { 2307 // fptrunc from double to float. 2308 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr; 2309 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass); 2310 } 2311 2312 return false; 2313 } 2314 2315 bool X86FastISel::X86SelectTrunc(const Instruction *I) { 2316 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 2317 EVT DstVT = TLI.getValueType(DL, I->getType()); 2318 2319 // This code only handles truncation to byte. 2320 if (DstVT != MVT::i8 && DstVT != MVT::i1) 2321 return false; 2322 if (!TLI.isTypeLegal(SrcVT)) 2323 return false; 2324 2325 unsigned InputReg = getRegForValue(I->getOperand(0)); 2326 if (!InputReg) 2327 // Unhandled operand. Halt "fast" selection and bail. 2328 return false; 2329 2330 if (SrcVT == MVT::i8) { 2331 // Truncate from i8 to i1; no code needed. 2332 updateValueMap(I, InputReg); 2333 return true; 2334 } 2335 2336 bool KillInputReg = false; 2337 if (!Subtarget->is64Bit()) { 2338 // If we're on x86-32; we can't extract an i8 from a general register. 2339 // First issue a copy to GR16_ABCD or GR32_ABCD. 2340 const TargetRegisterClass *CopyRC = 2341 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass; 2342 unsigned CopyReg = createResultReg(CopyRC); 2343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2344 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg); 2345 InputReg = CopyReg; 2346 KillInputReg = true; 2347 } 2348 2349 // Issue an extract_subreg. 2350 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8, 2351 InputReg, KillInputReg, 2352 X86::sub_8bit); 2353 if (!ResultReg) 2354 return false; 2355 2356 updateValueMap(I, ResultReg); 2357 return true; 2358 } 2359 2360 bool X86FastISel::IsMemcpySmall(uint64_t Len) { 2361 return Len <= (Subtarget->is64Bit() ? 32 : 16); 2362 } 2363 2364 bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM, 2365 X86AddressMode SrcAM, uint64_t Len) { 2366 2367 // Make sure we don't bloat code by inlining very large memcpy's. 2368 if (!IsMemcpySmall(Len)) 2369 return false; 2370 2371 bool i64Legal = Subtarget->is64Bit(); 2372 2373 // We don't care about alignment here since we just emit integer accesses. 2374 while (Len) { 2375 MVT VT; 2376 if (Len >= 8 && i64Legal) 2377 VT = MVT::i64; 2378 else if (Len >= 4) 2379 VT = MVT::i32; 2380 else if (Len >= 2) 2381 VT = MVT::i16; 2382 else 2383 VT = MVT::i8; 2384 2385 unsigned Reg; 2386 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg); 2387 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM); 2388 assert(RV && "Failed to emit load or store??"); 2389 2390 unsigned Size = VT.getSizeInBits()/8; 2391 Len -= Size; 2392 DestAM.Disp += Size; 2393 SrcAM.Disp += Size; 2394 } 2395 2396 return true; 2397 } 2398 2399 bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) { 2400 // FIXME: Handle more intrinsics. 2401 switch (II->getIntrinsicID()) { 2402 default: return false; 2403 case Intrinsic::convert_from_fp16: 2404 case Intrinsic::convert_to_fp16: { 2405 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) 2406 return false; 2407 2408 const Value *Op = II->getArgOperand(0); 2409 unsigned InputReg = getRegForValue(Op); 2410 if (InputReg == 0) 2411 return false; 2412 2413 // F16C only allows converting from float to half and from half to float. 2414 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16; 2415 if (IsFloatToHalf) { 2416 if (!Op->getType()->isFloatTy()) 2417 return false; 2418 } else { 2419 if (!II->getType()->isFloatTy()) 2420 return false; 2421 } 2422 2423 unsigned ResultReg = 0; 2424 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16); 2425 if (IsFloatToHalf) { 2426 // 'InputReg' is implicitly promoted from register class FR32 to 2427 // register class VR128 by method 'constrainOperandRegClass' which is 2428 // directly called by 'fastEmitInst_ri'. 2429 // Instruction VCVTPS2PHrr takes an extra immediate operand which is 2430 // used to provide rounding control: use MXCSR.RC, encoded as 0b100. 2431 // It's consistent with the other FP instructions, which are usually 2432 // controlled by MXCSR. 2433 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4); 2434 2435 // Move the lower 32-bits of ResultReg to another register of class GR32. 2436 ResultReg = createResultReg(&X86::GR32RegClass); 2437 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2438 TII.get(X86::VMOVPDI2DIrr), ResultReg) 2439 .addReg(InputReg, RegState::Kill); 2440 2441 // The result value is in the lower 16-bits of ResultReg. 2442 unsigned RegIdx = X86::sub_16bit; 2443 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx); 2444 } else { 2445 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!"); 2446 // Explicitly sign-extend the input to 32-bit. 2447 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg, 2448 /*Kill=*/false); 2449 2450 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr. 2451 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR, 2452 InputReg, /*Kill=*/true); 2453 2454 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true); 2455 2456 // The result value is in the lower 32-bits of ResultReg. 2457 // Emit an explicit copy from register class VR128 to register class FR32. 2458 ResultReg = createResultReg(&X86::FR32RegClass); 2459 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2460 TII.get(TargetOpcode::COPY), ResultReg) 2461 .addReg(InputReg, RegState::Kill); 2462 } 2463 2464 updateValueMap(II, ResultReg); 2465 return true; 2466 } 2467 case Intrinsic::frameaddress: { 2468 MachineFunction *MF = FuncInfo.MF; 2469 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI()) 2470 return false; 2471 2472 Type *RetTy = II->getCalledFunction()->getReturnType(); 2473 2474 MVT VT; 2475 if (!isTypeLegal(RetTy, VT)) 2476 return false; 2477 2478 unsigned Opc; 2479 const TargetRegisterClass *RC = nullptr; 2480 2481 switch (VT.SimpleTy) { 2482 default: llvm_unreachable("Invalid result type for frameaddress."); 2483 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break; 2484 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break; 2485 } 2486 2487 // This needs to be set before we call getPtrSizedFrameRegister, otherwise 2488 // we get the wrong frame register. 2489 MachineFrameInfo *MFI = MF->getFrameInfo(); 2490 MFI->setFrameAddressIsTaken(true); 2491 2492 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 2493 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF); 2494 assert(((FrameReg == X86::RBP && VT == MVT::i64) || 2495 (FrameReg == X86::EBP && VT == MVT::i32)) && 2496 "Invalid Frame Register!"); 2497 2498 // Always make a copy of the frame register to to a vreg first, so that we 2499 // never directly reference the frame register (the TwoAddressInstruction- 2500 // Pass doesn't like that). 2501 unsigned SrcReg = createResultReg(RC); 2502 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2503 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg); 2504 2505 // Now recursively load from the frame address. 2506 // movq (%rbp), %rax 2507 // movq (%rax), %rax 2508 // movq (%rax), %rax 2509 // ... 2510 unsigned DestReg; 2511 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue(); 2512 while (Depth--) { 2513 DestReg = createResultReg(RC); 2514 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2515 TII.get(Opc), DestReg), SrcReg); 2516 SrcReg = DestReg; 2517 } 2518 2519 updateValueMap(II, SrcReg); 2520 return true; 2521 } 2522 case Intrinsic::memcpy: { 2523 const MemCpyInst *MCI = cast<MemCpyInst>(II); 2524 // Don't handle volatile or variable length memcpys. 2525 if (MCI->isVolatile()) 2526 return false; 2527 2528 if (isa<ConstantInt>(MCI->getLength())) { 2529 // Small memcpy's are common enough that we want to do them 2530 // without a call if possible. 2531 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue(); 2532 if (IsMemcpySmall(Len)) { 2533 X86AddressMode DestAM, SrcAM; 2534 if (!X86SelectAddress(MCI->getRawDest(), DestAM) || 2535 !X86SelectAddress(MCI->getRawSource(), SrcAM)) 2536 return false; 2537 TryEmitSmallMemcpy(DestAM, SrcAM, Len); 2538 return true; 2539 } 2540 } 2541 2542 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2543 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth)) 2544 return false; 2545 2546 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255) 2547 return false; 2548 2549 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2); 2550 } 2551 case Intrinsic::memset: { 2552 const MemSetInst *MSI = cast<MemSetInst>(II); 2553 2554 if (MSI->isVolatile()) 2555 return false; 2556 2557 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32; 2558 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth)) 2559 return false; 2560 2561 if (MSI->getDestAddressSpace() > 255) 2562 return false; 2563 2564 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2); 2565 } 2566 case Intrinsic::stackprotector: { 2567 // Emit code to store the stack guard onto the stack. 2568 EVT PtrTy = TLI.getPointerTy(DL); 2569 2570 const Value *Op1 = II->getArgOperand(0); // The guard's value. 2571 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1)); 2572 2573 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]); 2574 2575 // Grab the frame index. 2576 X86AddressMode AM; 2577 if (!X86SelectAddress(Slot, AM)) return false; 2578 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false; 2579 return true; 2580 } 2581 case Intrinsic::dbg_declare: { 2582 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II); 2583 X86AddressMode AM; 2584 assert(DI->getAddress() && "Null address should be checked earlier!"); 2585 if (!X86SelectAddress(DI->getAddress(), AM)) 2586 return false; 2587 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE); 2588 // FIXME may need to add RegState::Debug to any registers produced, 2589 // although ESP/EBP should be the only ones at the moment. 2590 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && 2591 "Expected inlined-at fields to agree"); 2592 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM) 2593 .addImm(0) 2594 .addMetadata(DI->getVariable()) 2595 .addMetadata(DI->getExpression()); 2596 return true; 2597 } 2598 case Intrinsic::trap: { 2599 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP)); 2600 return true; 2601 } 2602 case Intrinsic::sqrt: { 2603 if (!Subtarget->hasSSE1()) 2604 return false; 2605 2606 Type *RetTy = II->getCalledFunction()->getReturnType(); 2607 2608 MVT VT; 2609 if (!isTypeLegal(RetTy, VT)) 2610 return false; 2611 2612 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT 2613 // is not generated by FastISel yet. 2614 // FIXME: Update this code once tablegen can handle it. 2615 static const uint16_t SqrtOpc[2][2] = { 2616 {X86::SQRTSSr, X86::VSQRTSSr}, 2617 {X86::SQRTSDr, X86::VSQRTSDr} 2618 }; 2619 bool HasAVX = Subtarget->hasAVX(); 2620 unsigned Opc; 2621 const TargetRegisterClass *RC; 2622 switch (VT.SimpleTy) { 2623 default: return false; 2624 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break; 2625 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break; 2626 } 2627 2628 const Value *SrcVal = II->getArgOperand(0); 2629 unsigned SrcReg = getRegForValue(SrcVal); 2630 2631 if (SrcReg == 0) 2632 return false; 2633 2634 unsigned ImplicitDefReg = 0; 2635 if (HasAVX) { 2636 ImplicitDefReg = createResultReg(RC); 2637 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2638 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg); 2639 } 2640 2641 unsigned ResultReg = createResultReg(RC); 2642 MachineInstrBuilder MIB; 2643 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), 2644 ResultReg); 2645 2646 if (ImplicitDefReg) 2647 MIB.addReg(ImplicitDefReg); 2648 2649 MIB.addReg(SrcReg); 2650 2651 updateValueMap(II, ResultReg); 2652 return true; 2653 } 2654 case Intrinsic::sadd_with_overflow: 2655 case Intrinsic::uadd_with_overflow: 2656 case Intrinsic::ssub_with_overflow: 2657 case Intrinsic::usub_with_overflow: 2658 case Intrinsic::smul_with_overflow: 2659 case Intrinsic::umul_with_overflow: { 2660 // This implements the basic lowering of the xalu with overflow intrinsics 2661 // into add/sub/mul followed by either seto or setb. 2662 const Function *Callee = II->getCalledFunction(); 2663 auto *Ty = cast<StructType>(Callee->getReturnType()); 2664 Type *RetTy = Ty->getTypeAtIndex(0U); 2665 Type *CondTy = Ty->getTypeAtIndex(1); 2666 2667 MVT VT; 2668 if (!isTypeLegal(RetTy, VT)) 2669 return false; 2670 2671 if (VT < MVT::i8 || VT > MVT::i64) 2672 return false; 2673 2674 const Value *LHS = II->getArgOperand(0); 2675 const Value *RHS = II->getArgOperand(1); 2676 2677 // Canonicalize immediate to the RHS. 2678 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && 2679 isCommutativeIntrinsic(II)) 2680 std::swap(LHS, RHS); 2681 2682 bool UseIncDec = false; 2683 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne()) 2684 UseIncDec = true; 2685 2686 unsigned BaseOpc, CondOpc; 2687 switch (II->getIntrinsicID()) { 2688 default: llvm_unreachable("Unexpected intrinsic!"); 2689 case Intrinsic::sadd_with_overflow: 2690 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD); 2691 CondOpc = X86::SETOr; 2692 break; 2693 case Intrinsic::uadd_with_overflow: 2694 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break; 2695 case Intrinsic::ssub_with_overflow: 2696 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB); 2697 CondOpc = X86::SETOr; 2698 break; 2699 case Intrinsic::usub_with_overflow: 2700 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break; 2701 case Intrinsic::smul_with_overflow: 2702 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break; 2703 case Intrinsic::umul_with_overflow: 2704 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break; 2705 } 2706 2707 unsigned LHSReg = getRegForValue(LHS); 2708 if (LHSReg == 0) 2709 return false; 2710 bool LHSIsKill = hasTrivialKill(LHS); 2711 2712 unsigned ResultReg = 0; 2713 // Check if we have an immediate version. 2714 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) { 2715 static const uint16_t Opc[2][4] = { 2716 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r }, 2717 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r } 2718 }; 2719 2720 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) { 2721 ResultReg = createResultReg(TLI.getRegClassFor(VT)); 2722 bool IsDec = BaseOpc == X86ISD::DEC; 2723 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2724 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg) 2725 .addReg(LHSReg, getKillRegState(LHSIsKill)); 2726 } else 2727 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill, 2728 CI->getZExtValue()); 2729 } 2730 2731 unsigned RHSReg; 2732 bool RHSIsKill; 2733 if (!ResultReg) { 2734 RHSReg = getRegForValue(RHS); 2735 if (RHSReg == 0) 2736 return false; 2737 RHSIsKill = hasTrivialKill(RHS); 2738 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg, 2739 RHSIsKill); 2740 } 2741 2742 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit 2743 // it manually. 2744 if (BaseOpc == X86ISD::UMUL && !ResultReg) { 2745 static const uint16_t MULOpc[] = 2746 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r }; 2747 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX }; 2748 // First copy the first operand into RAX, which is an implicit input to 2749 // the X86::MUL*r instruction. 2750 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2751 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8]) 2752 .addReg(LHSReg, getKillRegState(LHSIsKill)); 2753 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8], 2754 TLI.getRegClassFor(VT), RHSReg, RHSIsKill); 2755 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) { 2756 static const uint16_t MULOpc[] = 2757 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr }; 2758 if (VT == MVT::i8) { 2759 // Copy the first operand into AL, which is an implicit input to the 2760 // X86::IMUL8r instruction. 2761 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2762 TII.get(TargetOpcode::COPY), X86::AL) 2763 .addReg(LHSReg, getKillRegState(LHSIsKill)); 2764 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg, 2765 RHSIsKill); 2766 } else 2767 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8], 2768 TLI.getRegClassFor(VT), LHSReg, LHSIsKill, 2769 RHSReg, RHSIsKill); 2770 } 2771 2772 if (!ResultReg) 2773 return false; 2774 2775 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy); 2776 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers."); 2777 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc), 2778 ResultReg2); 2779 2780 updateValueMap(II, ResultReg, 2); 2781 return true; 2782 } 2783 case Intrinsic::x86_sse_cvttss2si: 2784 case Intrinsic::x86_sse_cvttss2si64: 2785 case Intrinsic::x86_sse2_cvttsd2si: 2786 case Intrinsic::x86_sse2_cvttsd2si64: { 2787 bool IsInputDouble; 2788 switch (II->getIntrinsicID()) { 2789 default: llvm_unreachable("Unexpected intrinsic."); 2790 case Intrinsic::x86_sse_cvttss2si: 2791 case Intrinsic::x86_sse_cvttss2si64: 2792 if (!Subtarget->hasSSE1()) 2793 return false; 2794 IsInputDouble = false; 2795 break; 2796 case Intrinsic::x86_sse2_cvttsd2si: 2797 case Intrinsic::x86_sse2_cvttsd2si64: 2798 if (!Subtarget->hasSSE2()) 2799 return false; 2800 IsInputDouble = true; 2801 break; 2802 } 2803 2804 Type *RetTy = II->getCalledFunction()->getReturnType(); 2805 MVT VT; 2806 if (!isTypeLegal(RetTy, VT)) 2807 return false; 2808 2809 static const uint16_t CvtOpc[2][2][2] = { 2810 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr }, 2811 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } }, 2812 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr }, 2813 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } } 2814 }; 2815 bool HasAVX = Subtarget->hasAVX(); 2816 unsigned Opc; 2817 switch (VT.SimpleTy) { 2818 default: llvm_unreachable("Unexpected result type."); 2819 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break; 2820 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break; 2821 } 2822 2823 // Check if we can fold insertelement instructions into the convert. 2824 const Value *Op = II->getArgOperand(0); 2825 while (auto *IE = dyn_cast<InsertElementInst>(Op)) { 2826 const Value *Index = IE->getOperand(2); 2827 if (!isa<ConstantInt>(Index)) 2828 break; 2829 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 2830 2831 if (Idx == 0) { 2832 Op = IE->getOperand(1); 2833 break; 2834 } 2835 Op = IE->getOperand(0); 2836 } 2837 2838 unsigned Reg = getRegForValue(Op); 2839 if (Reg == 0) 2840 return false; 2841 2842 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT)); 2843 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg) 2844 .addReg(Reg); 2845 2846 updateValueMap(II, ResultReg); 2847 return true; 2848 } 2849 } 2850 } 2851 2852 bool X86FastISel::fastLowerArguments() { 2853 if (!FuncInfo.CanLowerReturn) 2854 return false; 2855 2856 const Function *F = FuncInfo.Fn; 2857 if (F->isVarArg()) 2858 return false; 2859 2860 CallingConv::ID CC = F->getCallingConv(); 2861 if (CC != CallingConv::C) 2862 return false; 2863 2864 if (Subtarget->isCallingConvWin64(CC)) 2865 return false; 2866 2867 if (!Subtarget->is64Bit()) 2868 return false; 2869 2870 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments. 2871 unsigned GPRCnt = 0; 2872 unsigned FPRCnt = 0; 2873 unsigned Idx = 0; 2874 for (auto const &Arg : F->args()) { 2875 // The first argument is at index 1. 2876 ++Idx; 2877 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) || 2878 F->getAttributes().hasAttribute(Idx, Attribute::InReg) || 2879 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) || 2880 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) || 2881 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) || 2882 F->getAttributes().hasAttribute(Idx, Attribute::Nest)) 2883 return false; 2884 2885 Type *ArgTy = Arg.getType(); 2886 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy()) 2887 return false; 2888 2889 EVT ArgVT = TLI.getValueType(DL, ArgTy); 2890 if (!ArgVT.isSimple()) return false; 2891 switch (ArgVT.getSimpleVT().SimpleTy) { 2892 default: return false; 2893 case MVT::i32: 2894 case MVT::i64: 2895 ++GPRCnt; 2896 break; 2897 case MVT::f32: 2898 case MVT::f64: 2899 if (!Subtarget->hasSSE1()) 2900 return false; 2901 ++FPRCnt; 2902 break; 2903 } 2904 2905 if (GPRCnt > 6) 2906 return false; 2907 2908 if (FPRCnt > 8) 2909 return false; 2910 } 2911 2912 static const MCPhysReg GPR32ArgRegs[] = { 2913 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D 2914 }; 2915 static const MCPhysReg GPR64ArgRegs[] = { 2916 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9 2917 }; 2918 static const MCPhysReg XMMArgRegs[] = { 2919 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2920 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2921 }; 2922 2923 unsigned GPRIdx = 0; 2924 unsigned FPRIdx = 0; 2925 for (auto const &Arg : F->args()) { 2926 MVT VT = TLI.getSimpleValueType(DL, Arg.getType()); 2927 const TargetRegisterClass *RC = TLI.getRegClassFor(VT); 2928 unsigned SrcReg; 2929 switch (VT.SimpleTy) { 2930 default: llvm_unreachable("Unexpected value type."); 2931 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break; 2932 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break; 2933 case MVT::f32: // fall-through 2934 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break; 2935 } 2936 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC); 2937 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy. 2938 // Without this, EmitLiveInCopies may eliminate the livein if its only 2939 // use is a bitcast (which isn't turned into an instruction). 2940 unsigned ResultReg = createResultReg(RC); 2941 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 2942 TII.get(TargetOpcode::COPY), ResultReg) 2943 .addReg(DstReg, getKillRegState(true)); 2944 updateValueMap(&Arg, ResultReg); 2945 } 2946 return true; 2947 } 2948 2949 static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget, 2950 CallingConv::ID CC, 2951 ImmutableCallSite *CS) { 2952 if (Subtarget->is64Bit()) 2953 return 0; 2954 if (Subtarget->getTargetTriple().isOSMSVCRT()) 2955 return 0; 2956 if (CC == CallingConv::Fast || CC == CallingConv::GHC || 2957 CC == CallingConv::HiPE) 2958 return 0; 2959 2960 if (CS) 2961 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) || 2962 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU()) 2963 return 0; 2964 2965 return 4; 2966 } 2967 2968 bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) { 2969 auto &OutVals = CLI.OutVals; 2970 auto &OutFlags = CLI.OutFlags; 2971 auto &OutRegs = CLI.OutRegs; 2972 auto &Ins = CLI.Ins; 2973 auto &InRegs = CLI.InRegs; 2974 CallingConv::ID CC = CLI.CallConv; 2975 bool &IsTailCall = CLI.IsTailCall; 2976 bool IsVarArg = CLI.IsVarArg; 2977 const Value *Callee = CLI.Callee; 2978 MCSymbol *Symbol = CLI.Symbol; 2979 2980 bool Is64Bit = Subtarget->is64Bit(); 2981 bool IsWin64 = Subtarget->isCallingConvWin64(CC); 2982 2983 // Handle only C, fastcc, and webkit_js calling conventions for now. 2984 switch (CC) { 2985 default: return false; 2986 case CallingConv::C: 2987 case CallingConv::Fast: 2988 case CallingConv::WebKit_JS: 2989 case CallingConv::Swift: 2990 case CallingConv::X86_FastCall: 2991 case CallingConv::X86_64_Win64: 2992 case CallingConv::X86_64_SysV: 2993 break; 2994 } 2995 2996 // Allow SelectionDAG isel to handle tail calls. 2997 if (IsTailCall) 2998 return false; 2999 3000 // fastcc with -tailcallopt is intended to provide a guaranteed 3001 // tail call optimization. Fastisel doesn't know how to do that. 3002 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) 3003 return false; 3004 3005 // Don't know how to handle Win64 varargs yet. Nothing special needed for 3006 // x86-32. Special handling for x86-64 is implemented. 3007 if (IsVarArg && IsWin64) 3008 return false; 3009 3010 // Don't know about inalloca yet. 3011 if (CLI.CS && CLI.CS->hasInAllocaArgument()) 3012 return false; 3013 3014 for (auto Flag : CLI.OutFlags) 3015 if (Flag.isSwiftError()) 3016 return false; 3017 3018 // Fast-isel doesn't know about callee-pop yet. 3019 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg, 3020 TM.Options.GuaranteedTailCallOpt)) 3021 return false; 3022 3023 SmallVector<MVT, 16> OutVTs; 3024 SmallVector<unsigned, 16> ArgRegs; 3025 3026 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra 3027 // instruction. This is safe because it is common to all FastISel supported 3028 // calling conventions on x86. 3029 for (int i = 0, e = OutVals.size(); i != e; ++i) { 3030 Value *&Val = OutVals[i]; 3031 ISD::ArgFlagsTy Flags = OutFlags[i]; 3032 if (auto *CI = dyn_cast<ConstantInt>(Val)) { 3033 if (CI->getBitWidth() < 32) { 3034 if (Flags.isSExt()) 3035 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext())); 3036 else 3037 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext())); 3038 } 3039 } 3040 3041 // Passing bools around ends up doing a trunc to i1 and passing it. 3042 // Codegen this as an argument + "and 1". 3043 MVT VT; 3044 auto *TI = dyn_cast<TruncInst>(Val); 3045 unsigned ResultReg; 3046 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS && 3047 (TI->getParent() == CLI.CS->getInstruction()->getParent()) && 3048 TI->hasOneUse()) { 3049 Value *PrevVal = TI->getOperand(0); 3050 ResultReg = getRegForValue(PrevVal); 3051 3052 if (!ResultReg) 3053 return false; 3054 3055 if (!isTypeLegal(PrevVal->getType(), VT)) 3056 return false; 3057 3058 ResultReg = 3059 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1); 3060 } else { 3061 if (!isTypeLegal(Val->getType(), VT)) 3062 return false; 3063 ResultReg = getRegForValue(Val); 3064 } 3065 3066 if (!ResultReg) 3067 return false; 3068 3069 ArgRegs.push_back(ResultReg); 3070 OutVTs.push_back(VT); 3071 } 3072 3073 // Analyze operands of the call, assigning locations to each operand. 3074 SmallVector<CCValAssign, 16> ArgLocs; 3075 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext()); 3076 3077 // Allocate shadow area for Win64 3078 if (IsWin64) 3079 CCInfo.AllocateStack(32, 8); 3080 3081 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86); 3082 3083 // Get a count of how many bytes are to be pushed on the stack. 3084 unsigned NumBytes = CCInfo.getAlignedCallFrameSize(); 3085 3086 // Issue CALLSEQ_START 3087 unsigned AdjStackDown = TII.getCallFrameSetupOpcode(); 3088 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown)) 3089 .addImm(NumBytes).addImm(0); 3090 3091 // Walk the register/memloc assignments, inserting copies/loads. 3092 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 3093 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3094 CCValAssign const &VA = ArgLocs[i]; 3095 const Value *ArgVal = OutVals[VA.getValNo()]; 3096 MVT ArgVT = OutVTs[VA.getValNo()]; 3097 3098 if (ArgVT == MVT::x86mmx) 3099 return false; 3100 3101 unsigned ArgReg = ArgRegs[VA.getValNo()]; 3102 3103 // Promote the value if needed. 3104 switch (VA.getLocInfo()) { 3105 case CCValAssign::Full: break; 3106 case CCValAssign::SExt: { 3107 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3108 "Unexpected extend"); 3109 3110 if (ArgVT.SimpleTy == MVT::i1) 3111 return false; 3112 3113 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 3114 ArgVT, ArgReg); 3115 assert(Emitted && "Failed to emit a sext!"); (void)Emitted; 3116 ArgVT = VA.getLocVT(); 3117 break; 3118 } 3119 case CCValAssign::ZExt: { 3120 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3121 "Unexpected extend"); 3122 3123 // Handle zero-extension from i1 to i8, which is common. 3124 if (ArgVT.SimpleTy == MVT::i1) { 3125 // Set the high bits to zero. 3126 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false); 3127 ArgVT = MVT::i8; 3128 3129 if (ArgReg == 0) 3130 return false; 3131 } 3132 3133 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 3134 ArgVT, ArgReg); 3135 assert(Emitted && "Failed to emit a zext!"); (void)Emitted; 3136 ArgVT = VA.getLocVT(); 3137 break; 3138 } 3139 case CCValAssign::AExt: { 3140 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && 3141 "Unexpected extend"); 3142 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg, 3143 ArgVT, ArgReg); 3144 if (!Emitted) 3145 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg, 3146 ArgVT, ArgReg); 3147 if (!Emitted) 3148 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg, 3149 ArgVT, ArgReg); 3150 3151 assert(Emitted && "Failed to emit a aext!"); (void)Emitted; 3152 ArgVT = VA.getLocVT(); 3153 break; 3154 } 3155 case CCValAssign::BCvt: { 3156 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg, 3157 /*TODO: Kill=*/false); 3158 assert(ArgReg && "Failed to emit a bitcast!"); 3159 ArgVT = VA.getLocVT(); 3160 break; 3161 } 3162 case CCValAssign::VExt: 3163 // VExt has not been implemented, so this should be impossible to reach 3164 // for now. However, fallback to Selection DAG isel once implemented. 3165 return false; 3166 case CCValAssign::AExtUpper: 3167 case CCValAssign::SExtUpper: 3168 case CCValAssign::ZExtUpper: 3169 case CCValAssign::FPExt: 3170 llvm_unreachable("Unexpected loc info!"); 3171 case CCValAssign::Indirect: 3172 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully 3173 // support this. 3174 return false; 3175 } 3176 3177 if (VA.isRegLoc()) { 3178 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3179 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg); 3180 OutRegs.push_back(VA.getLocReg()); 3181 } else { 3182 assert(VA.isMemLoc()); 3183 3184 // Don't emit stores for undef values. 3185 if (isa<UndefValue>(ArgVal)) 3186 continue; 3187 3188 unsigned LocMemOffset = VA.getLocMemOffset(); 3189 X86AddressMode AM; 3190 AM.Base.Reg = RegInfo->getStackRegister(); 3191 AM.Disp = LocMemOffset; 3192 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()]; 3193 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType()); 3194 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand( 3195 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset), 3196 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment); 3197 if (Flags.isByVal()) { 3198 X86AddressMode SrcAM; 3199 SrcAM.Base.Reg = ArgReg; 3200 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize())) 3201 return false; 3202 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) { 3203 // If this is a really simple value, emit this with the Value* version 3204 // of X86FastEmitStore. If it isn't simple, we don't want to do this, 3205 // as it can cause us to reevaluate the argument. 3206 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO)) 3207 return false; 3208 } else { 3209 bool ValIsKill = hasTrivialKill(ArgVal); 3210 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO)) 3211 return false; 3212 } 3213 } 3214 } 3215 3216 // ELF / PIC requires GOT in the EBX register before function calls via PLT 3217 // GOT pointer. 3218 if (Subtarget->isPICStyleGOT()) { 3219 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3220 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3221 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base); 3222 } 3223 3224 if (Is64Bit && IsVarArg && !IsWin64) { 3225 // From AMD64 ABI document: 3226 // For calls that may call functions that use varargs or stdargs 3227 // (prototype-less calls or calls to functions containing ellipsis (...) in 3228 // the declaration) %al is used as hidden argument to specify the number 3229 // of SSE registers used. The contents of %al do not need to match exactly 3230 // the number of registers, but must be an ubound on the number of SSE 3231 // registers used and is in the range 0 - 8 inclusive. 3232 3233 // Count the number of XMM registers allocated. 3234 static const MCPhysReg XMMArgRegs[] = { 3235 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 3236 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 3237 }; 3238 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs); 3239 assert((Subtarget->hasSSE1() || !NumXMMRegs) 3240 && "SSE registers cannot be used when SSE is disabled"); 3241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri), 3242 X86::AL).addImm(NumXMMRegs); 3243 } 3244 3245 // Materialize callee address in a register. FIXME: GV address can be 3246 // handled with a CALLpcrel32 instead. 3247 X86AddressMode CalleeAM; 3248 if (!X86SelectCallAddress(Callee, CalleeAM)) 3249 return false; 3250 3251 unsigned CalleeOp = 0; 3252 const GlobalValue *GV = nullptr; 3253 if (CalleeAM.GV != nullptr) { 3254 GV = CalleeAM.GV; 3255 } else if (CalleeAM.Base.Reg != 0) { 3256 CalleeOp = CalleeAM.Base.Reg; 3257 } else 3258 return false; 3259 3260 // Issue the call. 3261 MachineInstrBuilder MIB; 3262 if (CalleeOp) { 3263 // Register-indirect call. 3264 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r; 3265 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)) 3266 .addReg(CalleeOp); 3267 } else { 3268 // Direct call. 3269 assert(GV && "Not a direct call"); 3270 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32; 3271 3272 // See if we need any target-specific flags on the GV operand. 3273 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV); 3274 // Ignore NonLazyBind attribute in FastISel 3275 if (OpFlags == X86II::MO_GOTPCREL) 3276 OpFlags = 0; 3277 3278 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc)); 3279 if (Symbol) 3280 MIB.addSym(Symbol, OpFlags); 3281 else 3282 MIB.addGlobalAddress(GV, 0, OpFlags); 3283 } 3284 3285 // Add a register mask operand representing the call-preserved registers. 3286 // Proper defs for return values will be added by setPhysRegsDeadExcept(). 3287 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC)); 3288 3289 // Add an implicit use GOT pointer in EBX. 3290 if (Subtarget->isPICStyleGOT()) 3291 MIB.addReg(X86::EBX, RegState::Implicit); 3292 3293 if (Is64Bit && IsVarArg && !IsWin64) 3294 MIB.addReg(X86::AL, RegState::Implicit); 3295 3296 // Add implicit physical register uses to the call. 3297 for (auto Reg : OutRegs) 3298 MIB.addReg(Reg, RegState::Implicit); 3299 3300 // Issue CALLSEQ_END 3301 unsigned NumBytesForCalleeToPop = 3302 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS); 3303 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode(); 3304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp)) 3305 .addImm(NumBytes).addImm(NumBytesForCalleeToPop); 3306 3307 // Now handle call return values. 3308 SmallVector<CCValAssign, 16> RVLocs; 3309 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs, 3310 CLI.RetTy->getContext()); 3311 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86); 3312 3313 // Copy all of the result registers out of their specified physreg. 3314 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy); 3315 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3316 CCValAssign &VA = RVLocs[i]; 3317 EVT CopyVT = VA.getValVT(); 3318 unsigned CopyReg = ResultReg + i; 3319 3320 // If this is x86-64, and we disabled SSE, we can't return FP values 3321 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 3322 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 3323 report_fatal_error("SSE register return with SSE disabled"); 3324 } 3325 3326 // If we prefer to use the value in xmm registers, copy it out as f80 and 3327 // use a truncate to move it from fp stack reg to xmm reg. 3328 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) && 3329 isScalarFPTypeInSSEReg(VA.getValVT())) { 3330 CopyVT = MVT::f80; 3331 CopyReg = createResultReg(&X86::RFP80RegClass); 3332 } 3333 3334 // Copy out the result. 3335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3336 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg()); 3337 InRegs.push_back(VA.getLocReg()); 3338 3339 // Round the f80 to the right size, which also moves it to the appropriate 3340 // xmm register. This is accomplished by storing the f80 value in memory 3341 // and then loading it back. 3342 if (CopyVT != VA.getValVT()) { 3343 EVT ResVT = VA.getValVT(); 3344 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64; 3345 unsigned MemSize = ResVT.getSizeInBits()/8; 3346 int FI = MFI.CreateStackObject(MemSize, MemSize, false); 3347 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3348 TII.get(Opc)), FI) 3349 .addReg(CopyReg); 3350 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm; 3351 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3352 TII.get(Opc), ResultReg + i), FI); 3353 } 3354 } 3355 3356 CLI.ResultReg = ResultReg; 3357 CLI.NumResultRegs = RVLocs.size(); 3358 CLI.Call = MIB; 3359 3360 return true; 3361 } 3362 3363 bool 3364 X86FastISel::fastSelectInstruction(const Instruction *I) { 3365 switch (I->getOpcode()) { 3366 default: break; 3367 case Instruction::Load: 3368 return X86SelectLoad(I); 3369 case Instruction::Store: 3370 return X86SelectStore(I); 3371 case Instruction::Ret: 3372 return X86SelectRet(I); 3373 case Instruction::ICmp: 3374 case Instruction::FCmp: 3375 return X86SelectCmp(I); 3376 case Instruction::ZExt: 3377 return X86SelectZExt(I); 3378 case Instruction::Br: 3379 return X86SelectBranch(I); 3380 case Instruction::LShr: 3381 case Instruction::AShr: 3382 case Instruction::Shl: 3383 return X86SelectShift(I); 3384 case Instruction::SDiv: 3385 case Instruction::UDiv: 3386 case Instruction::SRem: 3387 case Instruction::URem: 3388 return X86SelectDivRem(I); 3389 case Instruction::Select: 3390 return X86SelectSelect(I); 3391 case Instruction::Trunc: 3392 return X86SelectTrunc(I); 3393 case Instruction::FPExt: 3394 return X86SelectFPExt(I); 3395 case Instruction::FPTrunc: 3396 return X86SelectFPTrunc(I); 3397 case Instruction::SIToFP: 3398 return X86SelectSIToFP(I); 3399 case Instruction::IntToPtr: // Deliberate fall-through. 3400 case Instruction::PtrToInt: { 3401 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 3402 EVT DstVT = TLI.getValueType(DL, I->getType()); 3403 if (DstVT.bitsGT(SrcVT)) 3404 return X86SelectZExt(I); 3405 if (DstVT.bitsLT(SrcVT)) 3406 return X86SelectTrunc(I); 3407 unsigned Reg = getRegForValue(I->getOperand(0)); 3408 if (Reg == 0) return false; 3409 updateValueMap(I, Reg); 3410 return true; 3411 } 3412 case Instruction::BitCast: { 3413 // Select SSE2/AVX bitcasts between 128/256 bit vector types. 3414 if (!Subtarget->hasSSE2()) 3415 return false; 3416 3417 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType()); 3418 EVT DstVT = TLI.getValueType(DL, I->getType()); 3419 3420 if (!SrcVT.isSimple() || !DstVT.isSimple()) 3421 return false; 3422 3423 if (!SrcVT.is128BitVector() && 3424 !(Subtarget->hasAVX() && SrcVT.is256BitVector())) 3425 return false; 3426 3427 unsigned Reg = getRegForValue(I->getOperand(0)); 3428 if (Reg == 0) 3429 return false; 3430 3431 // No instruction is needed for conversion. Reuse the register used by 3432 // the fist operand. 3433 updateValueMap(I, Reg); 3434 return true; 3435 } 3436 } 3437 3438 return false; 3439 } 3440 3441 unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) { 3442 if (VT > MVT::i64) 3443 return 0; 3444 3445 uint64_t Imm = CI->getZExtValue(); 3446 if (Imm == 0) { 3447 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass); 3448 switch (VT.SimpleTy) { 3449 default: llvm_unreachable("Unexpected value type"); 3450 case MVT::i1: 3451 case MVT::i8: 3452 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true, 3453 X86::sub_8bit); 3454 case MVT::i16: 3455 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true, 3456 X86::sub_16bit); 3457 case MVT::i32: 3458 return SrcReg; 3459 case MVT::i64: { 3460 unsigned ResultReg = createResultReg(&X86::GR64RegClass); 3461 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3462 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg) 3463 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit); 3464 return ResultReg; 3465 } 3466 } 3467 } 3468 3469 unsigned Opc = 0; 3470 switch (VT.SimpleTy) { 3471 default: llvm_unreachable("Unexpected value type"); 3472 case MVT::i1: VT = MVT::i8; // fall-through 3473 case MVT::i8: Opc = X86::MOV8ri; break; 3474 case MVT::i16: Opc = X86::MOV16ri; break; 3475 case MVT::i32: Opc = X86::MOV32ri; break; 3476 case MVT::i64: { 3477 if (isUInt<32>(Imm)) 3478 Opc = X86::MOV32ri; 3479 else if (isInt<32>(Imm)) 3480 Opc = X86::MOV64ri32; 3481 else 3482 Opc = X86::MOV64ri; 3483 break; 3484 } 3485 } 3486 if (VT == MVT::i64 && Opc == X86::MOV32ri) { 3487 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm); 3488 unsigned ResultReg = createResultReg(&X86::GR64RegClass); 3489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3490 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg) 3491 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit); 3492 return ResultReg; 3493 } 3494 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm); 3495 } 3496 3497 unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) { 3498 if (CFP->isNullValue()) 3499 return fastMaterializeFloatZero(CFP); 3500 3501 // Can't handle alternate code models yet. 3502 CodeModel::Model CM = TM.getCodeModel(); 3503 if (CM != CodeModel::Small && CM != CodeModel::Large) 3504 return 0; 3505 3506 // Get opcode and regclass of the output for the given load instruction. 3507 unsigned Opc = 0; 3508 const TargetRegisterClass *RC = nullptr; 3509 switch (VT.SimpleTy) { 3510 default: return 0; 3511 case MVT::f32: 3512 if (X86ScalarSSEf32) { 3513 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm; 3514 RC = &X86::FR32RegClass; 3515 } else { 3516 Opc = X86::LD_Fp32m; 3517 RC = &X86::RFP32RegClass; 3518 } 3519 break; 3520 case MVT::f64: 3521 if (X86ScalarSSEf64) { 3522 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm; 3523 RC = &X86::FR64RegClass; 3524 } else { 3525 Opc = X86::LD_Fp64m; 3526 RC = &X86::RFP64RegClass; 3527 } 3528 break; 3529 case MVT::f80: 3530 // No f80 support yet. 3531 return 0; 3532 } 3533 3534 // MachineConstantPool wants an explicit alignment. 3535 unsigned Align = DL.getPrefTypeAlignment(CFP->getType()); 3536 if (Align == 0) { 3537 // Alignment of vector types. FIXME! 3538 Align = DL.getTypeAllocSize(CFP->getType()); 3539 } 3540 3541 // x86-32 PIC requires a PIC base register for constant pools. 3542 unsigned PICBase = 0; 3543 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr); 3544 if (OpFlag == X86II::MO_PIC_BASE_OFFSET) 3545 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3546 else if (OpFlag == X86II::MO_GOTOFF) 3547 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF); 3548 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small) 3549 PICBase = X86::RIP; 3550 3551 // Create the load from the constant pool. 3552 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align); 3553 unsigned ResultReg = createResultReg(RC); 3554 3555 if (CM == CodeModel::Large) { 3556 unsigned AddrReg = createResultReg(&X86::GR64RegClass); 3557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri), 3558 AddrReg) 3559 .addConstantPoolIndex(CPI, 0, OpFlag); 3560 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3561 TII.get(Opc), ResultReg); 3562 addDirectMem(MIB, AddrReg); 3563 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand( 3564 MachinePointerInfo::getConstantPool(*FuncInfo.MF), 3565 MachineMemOperand::MOLoad, DL.getPointerSize(), Align); 3566 MIB->addMemOperand(*FuncInfo.MF, MMO); 3567 return ResultReg; 3568 } 3569 3570 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3571 TII.get(Opc), ResultReg), 3572 CPI, PICBase, OpFlag); 3573 return ResultReg; 3574 } 3575 3576 unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) { 3577 // Can't handle alternate code models yet. 3578 if (TM.getCodeModel() != CodeModel::Small) 3579 return 0; 3580 3581 // Materialize addresses with LEA/MOV instructions. 3582 X86AddressMode AM; 3583 if (X86SelectAddress(GV, AM)) { 3584 // If the expression is just a basereg, then we're done, otherwise we need 3585 // to emit an LEA. 3586 if (AM.BaseType == X86AddressMode::RegBase && 3587 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr) 3588 return AM.Base.Reg; 3589 3590 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT)); 3591 if (TM.getRelocationModel() == Reloc::Static && 3592 TLI.getPointerTy(DL) == MVT::i64) { 3593 // The displacement code could be more than 32 bits away so we need to use 3594 // an instruction with a 64 bit immediate 3595 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri), 3596 ResultReg) 3597 .addGlobalAddress(GV); 3598 } else { 3599 unsigned Opc = 3600 TLI.getPointerTy(DL) == MVT::i32 3601 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r) 3602 : X86::LEA64r; 3603 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3604 TII.get(Opc), ResultReg), AM); 3605 } 3606 return ResultReg; 3607 } 3608 return 0; 3609 } 3610 3611 unsigned X86FastISel::fastMaterializeConstant(const Constant *C) { 3612 EVT CEVT = TLI.getValueType(DL, C->getType(), true); 3613 3614 // Only handle simple types. 3615 if (!CEVT.isSimple()) 3616 return 0; 3617 MVT VT = CEVT.getSimpleVT(); 3618 3619 if (const auto *CI = dyn_cast<ConstantInt>(C)) 3620 return X86MaterializeInt(CI, VT); 3621 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 3622 return X86MaterializeFP(CFP, VT); 3623 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 3624 return X86MaterializeGV(GV, VT); 3625 3626 return 0; 3627 } 3628 3629 unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) { 3630 // Fail on dynamic allocas. At this point, getRegForValue has already 3631 // checked its CSE maps, so if we're here trying to handle a dynamic 3632 // alloca, we're not going to succeed. X86SelectAddress has a 3633 // check for dynamic allocas, because it's called directly from 3634 // various places, but targetMaterializeAlloca also needs a check 3635 // in order to avoid recursion between getRegForValue, 3636 // X86SelectAddrss, and targetMaterializeAlloca. 3637 if (!FuncInfo.StaticAllocaMap.count(C)) 3638 return 0; 3639 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?"); 3640 3641 X86AddressMode AM; 3642 if (!X86SelectAddress(C, AM)) 3643 return 0; 3644 unsigned Opc = 3645 TLI.getPointerTy(DL) == MVT::i32 3646 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r) 3647 : X86::LEA64r; 3648 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL)); 3649 unsigned ResultReg = createResultReg(RC); 3650 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, 3651 TII.get(Opc), ResultReg), AM); 3652 return ResultReg; 3653 } 3654 3655 unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) { 3656 MVT VT; 3657 if (!isTypeLegal(CF->getType(), VT)) 3658 return 0; 3659 3660 // Get opcode and regclass for the given zero. 3661 unsigned Opc = 0; 3662 const TargetRegisterClass *RC = nullptr; 3663 switch (VT.SimpleTy) { 3664 default: return 0; 3665 case MVT::f32: 3666 if (X86ScalarSSEf32) { 3667 Opc = X86::FsFLD0SS; 3668 RC = &X86::FR32RegClass; 3669 } else { 3670 Opc = X86::LD_Fp032; 3671 RC = &X86::RFP32RegClass; 3672 } 3673 break; 3674 case MVT::f64: 3675 if (X86ScalarSSEf64) { 3676 Opc = X86::FsFLD0SD; 3677 RC = &X86::FR64RegClass; 3678 } else { 3679 Opc = X86::LD_Fp064; 3680 RC = &X86::RFP64RegClass; 3681 } 3682 break; 3683 case MVT::f80: 3684 // No f80 support yet. 3685 return 0; 3686 } 3687 3688 unsigned ResultReg = createResultReg(RC); 3689 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg); 3690 return ResultReg; 3691 } 3692 3693 3694 bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo, 3695 const LoadInst *LI) { 3696 const Value *Ptr = LI->getPointerOperand(); 3697 X86AddressMode AM; 3698 if (!X86SelectAddress(Ptr, AM)) 3699 return false; 3700 3701 const X86InstrInfo &XII = (const X86InstrInfo &)TII; 3702 3703 unsigned Size = DL.getTypeAllocSize(LI->getType()); 3704 unsigned Alignment = LI->getAlignment(); 3705 3706 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3707 Alignment = DL.getABITypeAlignment(LI->getType()); 3708 3709 SmallVector<MachineOperand, 8> AddrOps; 3710 AM.getFullAddress(AddrOps); 3711 3712 MachineInstr *Result = XII.foldMemoryOperandImpl( 3713 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment, 3714 /*AllowCommute=*/true); 3715 if (!Result) 3716 return false; 3717 3718 // The index register could be in the wrong register class. Unfortunately, 3719 // foldMemoryOperandImpl could have commuted the instruction so its not enough 3720 // to just look at OpNo + the offset to the index reg. We actually need to 3721 // scan the instruction to find the index reg and see if its the correct reg 3722 // class. 3723 unsigned OperandNo = 0; 3724 for (MachineInstr::mop_iterator I = Result->operands_begin(), 3725 E = Result->operands_end(); I != E; ++I, ++OperandNo) { 3726 MachineOperand &MO = *I; 3727 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg) 3728 continue; 3729 // Found the index reg, now try to rewrite it. 3730 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(), 3731 MO.getReg(), OperandNo); 3732 if (IndexReg == MO.getReg()) 3733 continue; 3734 MO.setReg(IndexReg); 3735 } 3736 3737 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI)); 3738 MI->eraseFromParent(); 3739 return true; 3740 } 3741 3742 3743 namespace llvm { 3744 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo, 3745 const TargetLibraryInfo *libInfo) { 3746 return new X86FastISel(funcInfo, libInfo); 3747 } 3748 } 3749