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