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