1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the interfaces that X86 uses to lower LLVM code into a 11 // selection DAG. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #define DEBUG_TYPE "x86-isel" 16 #include "X86ISelLowering.h" 17 #include "Utils/X86ShuffleDecode.h" 18 #include "X86.h" 19 #include "X86InstrBuilder.h" 20 #include "X86TargetMachine.h" 21 #include "X86TargetObjectFile.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/ADT/VariadicFunction.h" 26 #include "llvm/CodeGen/IntrinsicLowering.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineInstrBuilder.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineModuleInfo.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/IR/CallingConv.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/GlobalAlias.h" 38 #include "llvm/IR/GlobalVariable.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/IR/LLVMContext.h" 42 #include "llvm/MC/MCAsmInfo.h" 43 #include "llvm/MC/MCContext.h" 44 #include "llvm/MC/MCExpr.h" 45 #include "llvm/MC/MCSymbol.h" 46 #include "llvm/Support/CallSite.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/MathExtras.h" 50 #include "llvm/Target/TargetOptions.h" 51 #include <bitset> 52 #include <cctype> 53 using namespace llvm; 54 55 STATISTIC(NumTailCalls, "Number of tail calls"); 56 57 // Forward declarations. 58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 59 SDValue V2); 60 61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal, 62 SelectionDAG &DAG, SDLoc dl, 63 unsigned vectorWidth) { 64 assert((vectorWidth == 128 || vectorWidth == 256) && 65 "Unsupported vector width"); 66 EVT VT = Vec.getValueType(); 67 EVT ElVT = VT.getVectorElementType(); 68 unsigned Factor = VT.getSizeInBits()/vectorWidth; 69 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 70 VT.getVectorNumElements()/Factor); 71 72 // Extract from UNDEF is UNDEF. 73 if (Vec.getOpcode() == ISD::UNDEF) 74 return DAG.getUNDEF(ResultVT); 75 76 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR 77 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits(); 78 79 // This is the index of the first element of the vectorWidth-bit chunk 80 // we want. 81 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth) 82 * ElemsPerChunk); 83 84 // If the input is a buildvector just emit a smaller one. 85 if (Vec.getOpcode() == ISD::BUILD_VECTOR) 86 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT, 87 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk); 88 89 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 90 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 91 VecIdx); 92 93 return Result; 94 95 } 96 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This 97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128 98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4 99 /// instructions or a simple subregister reference. Idx is an index in the 100 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes 101 /// lowering EXTRACT_VECTOR_ELT operations easier. 102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal, 103 SelectionDAG &DAG, SDLoc dl) { 104 assert((Vec.getValueType().is256BitVector() || 105 Vec.getValueType().is512BitVector()) && "Unexpected vector size!"); 106 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128); 107 } 108 109 /// Generate a DAG to grab 256-bits from a 512-bit vector. 110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal, 111 SelectionDAG &DAG, SDLoc dl) { 112 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!"); 113 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256); 114 } 115 116 static SDValue InsertSubVector(SDValue Result, SDValue Vec, 117 unsigned IdxVal, SelectionDAG &DAG, 118 SDLoc dl, unsigned vectorWidth) { 119 assert((vectorWidth == 128 || vectorWidth == 256) && 120 "Unsupported vector width"); 121 // Inserting UNDEF is Result 122 if (Vec.getOpcode() == ISD::UNDEF) 123 return Result; 124 EVT VT = Vec.getValueType(); 125 EVT ElVT = VT.getVectorElementType(); 126 EVT ResultVT = Result.getValueType(); 127 128 // Insert the relevant vectorWidth bits. 129 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits(); 130 131 // This is the index of the first element of the vectorWidth-bit chunk 132 // we want. 133 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth) 134 * ElemsPerChunk); 135 136 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 137 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 138 VecIdx); 139 } 140 /// Generate a DAG to put 128-bits into a vector > 128 bits. This 141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or 142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a 143 /// simple superregister reference. Idx is an index in the 128 bits 144 /// we want. It need not be aligned to a 128-bit bounday. That makes 145 /// lowering INSERT_VECTOR_ELT operations easier. 146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, 147 unsigned IdxVal, SelectionDAG &DAG, 148 SDLoc dl) { 149 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!"); 150 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128); 151 } 152 153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, 154 unsigned IdxVal, SelectionDAG &DAG, 155 SDLoc dl) { 156 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!"); 157 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256); 158 } 159 160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128 161 /// instructions. This is used because creating CONCAT_VECTOR nodes of 162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower 163 /// large BUILD_VECTORS. 164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT, 165 unsigned NumElems, SelectionDAG &DAG, 166 SDLoc dl) { 167 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl); 168 return Insert128BitVector(V, V2, NumElems/2, DAG, dl); 169 } 170 171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT, 172 unsigned NumElems, SelectionDAG &DAG, 173 SDLoc dl) { 174 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl); 175 return Insert256BitVector(V, V2, NumElems/2, DAG, dl); 176 } 177 178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 179 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 180 bool is64Bit = Subtarget->is64Bit(); 181 182 if (Subtarget->isTargetEnvMacho()) { 183 if (is64Bit) 184 return new X86_64MachoTargetObjectFile(); 185 return new TargetLoweringObjectFileMachO(); 186 } 187 188 if (Subtarget->isTargetLinux()) 189 return new X86LinuxTargetObjectFile(); 190 if (Subtarget->isTargetELF()) 191 return new TargetLoweringObjectFileELF(); 192 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 193 return new TargetLoweringObjectFileCOFF(); 194 llvm_unreachable("unknown subtarget type"); 195 } 196 197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 198 : TargetLowering(TM, createTLOF(TM)) { 199 Subtarget = &TM.getSubtarget<X86Subtarget>(); 200 X86ScalarSSEf64 = Subtarget->hasSSE2(); 201 X86ScalarSSEf32 = Subtarget->hasSSE1(); 202 TD = getDataLayout(); 203 204 resetOperationActions(); 205 } 206 207 void X86TargetLowering::resetOperationActions() { 208 const TargetMachine &TM = getTargetMachine(); 209 static bool FirstTimeThrough = true; 210 211 // If none of the target options have changed, then we don't need to reset the 212 // operation actions. 213 if (!FirstTimeThrough && TO == TM.Options) return; 214 215 if (!FirstTimeThrough) { 216 // Reinitialize the actions. 217 initActions(); 218 FirstTimeThrough = false; 219 } 220 221 TO = TM.Options; 222 223 // Set up the TargetLowering object. 224 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 225 226 // X86 is weird, it always uses i8 for shift amounts and setcc results. 227 setBooleanContents(ZeroOrOneBooleanContent); 228 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 229 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 230 231 // For 64-bit since we have so many registers use the ILP scheduler, for 232 // 32-bit code use the register pressure specific scheduling. 233 // For Atom, always use ILP scheduling. 234 if (Subtarget->isAtom()) 235 setSchedulingPreference(Sched::ILP); 236 else if (Subtarget->is64Bit()) 237 setSchedulingPreference(Sched::ILP); 238 else 239 setSchedulingPreference(Sched::RegPressure); 240 const X86RegisterInfo *RegInfo = 241 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo()); 242 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister()); 243 244 // Bypass expensive divides on Atom when compiling with O2 245 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) { 246 addBypassSlowDiv(32, 8); 247 if (Subtarget->is64Bit()) 248 addBypassSlowDiv(64, 16); 249 } 250 251 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 252 // Setup Windows compiler runtime calls. 253 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 254 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 255 setLibcallName(RTLIB::SREM_I64, "_allrem"); 256 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 257 setLibcallName(RTLIB::MUL_I64, "_allmul"); 258 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 259 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 260 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 261 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 262 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 263 264 // The _ftol2 runtime function has an unusual calling conv, which 265 // is modeled by a special pseudo-instruction. 266 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0); 267 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0); 268 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0); 269 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0); 270 } 271 272 if (Subtarget->isTargetDarwin()) { 273 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 274 setUseUnderscoreSetJmp(false); 275 setUseUnderscoreLongJmp(false); 276 } else if (Subtarget->isTargetMingw()) { 277 // MS runtime is weird: it exports _setjmp, but longjmp! 278 setUseUnderscoreSetJmp(true); 279 setUseUnderscoreLongJmp(false); 280 } else { 281 setUseUnderscoreSetJmp(true); 282 setUseUnderscoreLongJmp(true); 283 } 284 285 // Set up the register classes. 286 addRegisterClass(MVT::i8, &X86::GR8RegClass); 287 addRegisterClass(MVT::i16, &X86::GR16RegClass); 288 addRegisterClass(MVT::i32, &X86::GR32RegClass); 289 if (Subtarget->is64Bit()) 290 addRegisterClass(MVT::i64, &X86::GR64RegClass); 291 292 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 293 294 // We don't accept any truncstore of integer registers. 295 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 296 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 297 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 298 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 299 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 300 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 301 302 // SETOEQ and SETUNE require checking two conditions. 303 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 304 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 305 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 306 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 307 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 308 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 309 310 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 311 // operation. 312 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 313 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 314 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 315 316 if (Subtarget->is64Bit()) { 317 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 318 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 319 } else if (!TM.Options.UseSoftFloat) { 320 // We have an algorithm for SSE2->double, and we turn this into a 321 // 64-bit FILD followed by conditional FADD for other targets. 322 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 323 // We have an algorithm for SSE2, and we turn this into a 64-bit 324 // FILD for other targets. 325 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 326 } 327 328 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 329 // this operation. 330 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 331 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 332 333 if (!TM.Options.UseSoftFloat) { 334 // SSE has no i16 to fp conversion, only i32 335 if (X86ScalarSSEf32) { 336 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 337 // f32 and f64 cases are Legal, f80 case is not 338 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 339 } else { 340 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 341 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 342 } 343 } else { 344 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 345 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 346 } 347 348 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 349 // are Legal, f80 is custom lowered. 350 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 351 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 352 353 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 354 // this operation. 355 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 356 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 357 358 if (X86ScalarSSEf32) { 359 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 360 // f32 and f64 cases are Legal, f80 case is not 361 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 362 } else { 363 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 364 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 365 } 366 367 // Handle FP_TO_UINT by promoting the destination to a larger signed 368 // conversion. 369 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 370 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 371 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 372 373 if (Subtarget->is64Bit()) { 374 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 375 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 376 } else if (!TM.Options.UseSoftFloat) { 377 // Since AVX is a superset of SSE3, only check for SSE here. 378 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 379 // Expand FP_TO_UINT into a select. 380 // FIXME: We would like to use a Custom expander here eventually to do 381 // the optimal thing for SSE vs. the default expansion in the legalizer. 382 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 383 else 384 // With SSE3 we can use fisttpll to convert to a signed i64; without 385 // SSE, we're stuck with a fistpll. 386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 387 } 388 389 if (isTargetFTOL()) { 390 // Use the _ftol2 runtime function, which has a pseudo-instruction 391 // to handle its weird calling convention. 392 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom); 393 } 394 395 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 396 if (!X86ScalarSSEf64) { 397 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 398 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 399 if (Subtarget->is64Bit()) { 400 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 401 // Without SSE, i64->f64 goes through memory. 402 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 403 } 404 } 405 406 // Scalar integer divide and remainder are lowered to use operations that 407 // produce two results, to match the available instructions. This exposes 408 // the two-result form to trivial CSE, which is able to combine x/y and x%y 409 // into a single instruction. 410 // 411 // Scalar integer multiply-high is also lowered to use two-result 412 // operations, to match the available instructions. However, plain multiply 413 // (low) operations are left as Legal, as there are single-result 414 // instructions for this in x86. Using the two-result multiply instructions 415 // when both high and low results are needed must be arranged by dagcombine. 416 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 417 MVT VT = IntVTs[i]; 418 setOperationAction(ISD::MULHS, VT, Expand); 419 setOperationAction(ISD::MULHU, VT, Expand); 420 setOperationAction(ISD::SDIV, VT, Expand); 421 setOperationAction(ISD::UDIV, VT, Expand); 422 setOperationAction(ISD::SREM, VT, Expand); 423 setOperationAction(ISD::UREM, VT, Expand); 424 425 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 426 setOperationAction(ISD::ADDC, VT, Custom); 427 setOperationAction(ISD::ADDE, VT, Custom); 428 setOperationAction(ISD::SUBC, VT, Custom); 429 setOperationAction(ISD::SUBE, VT, Custom); 430 } 431 432 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 433 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 434 setOperationAction(ISD::BR_CC , MVT::f32, Expand); 435 setOperationAction(ISD::BR_CC , MVT::f64, Expand); 436 setOperationAction(ISD::BR_CC , MVT::f80, Expand); 437 setOperationAction(ISD::BR_CC , MVT::i8, Expand); 438 setOperationAction(ISD::BR_CC , MVT::i16, Expand); 439 setOperationAction(ISD::BR_CC , MVT::i32, Expand); 440 setOperationAction(ISD::BR_CC , MVT::i64, Expand); 441 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 442 if (Subtarget->is64Bit()) 443 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 444 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 445 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 446 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 447 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 448 setOperationAction(ISD::FREM , MVT::f32 , Expand); 449 setOperationAction(ISD::FREM , MVT::f64 , Expand); 450 setOperationAction(ISD::FREM , MVT::f80 , Expand); 451 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 452 453 // Promote the i8 variants and force them on up to i32 which has a shorter 454 // encoding. 455 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 456 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32); 457 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote); 458 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32); 459 if (Subtarget->hasBMI()) { 460 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand); 461 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand); 462 if (Subtarget->is64Bit()) 463 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 464 } else { 465 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 466 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 467 if (Subtarget->is64Bit()) 468 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 469 } 470 471 if (Subtarget->hasLZCNT()) { 472 // When promoting the i8 variants, force them to i32 for a shorter 473 // encoding. 474 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 475 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote); 477 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32); 478 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand); 479 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand); 480 if (Subtarget->is64Bit()) 481 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 482 } else { 483 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 484 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 485 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 486 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom); 487 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom); 488 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom); 489 if (Subtarget->is64Bit()) { 490 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 491 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom); 492 } 493 } 494 495 if (Subtarget->hasPOPCNT()) { 496 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 497 } else { 498 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 499 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 500 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 501 if (Subtarget->is64Bit()) 502 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 503 } 504 505 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 506 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 507 508 // These should be promoted to a larger select which is supported. 509 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 510 // X86 wants to expand cmov itself. 511 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 512 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 513 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 514 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 515 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 516 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 517 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 518 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 519 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 520 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 521 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 522 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 523 if (Subtarget->is64Bit()) { 524 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 525 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 526 } 527 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 528 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 529 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 530 // support continuation, user-level threading, and etc.. As a result, no 531 // other SjLj exception interfaces are implemented and please don't build 532 // your own exception handling based on them. 533 // LLVM/Clang supports zero-cost DWARF exception handling. 534 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 535 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 536 537 // Darwin ABI issue. 538 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 539 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 540 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 541 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 542 if (Subtarget->is64Bit()) 543 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 544 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 545 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 546 if (Subtarget->is64Bit()) { 547 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 548 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 549 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 550 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 551 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 552 } 553 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 554 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 555 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 556 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 557 if (Subtarget->is64Bit()) { 558 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 559 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 560 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 561 } 562 563 if (Subtarget->hasSSE1()) 564 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 565 566 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 567 568 // Expand certain atomics 569 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 570 MVT VT = IntVTs[i]; 571 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 572 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 573 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 574 } 575 576 if (!Subtarget->is64Bit()) { 577 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 578 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 579 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 580 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 581 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 582 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 583 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 584 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 585 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom); 586 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom); 587 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom); 588 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom); 589 } 590 591 if (Subtarget->hasCmpxchg16b()) { 592 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 593 } 594 595 // FIXME - use subtarget debug flags 596 if (!Subtarget->isTargetDarwin() && 597 !Subtarget->isTargetELF() && 598 !Subtarget->isTargetCygMing()) { 599 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 600 } 601 602 if (Subtarget->is64Bit()) { 603 setExceptionPointerRegister(X86::RAX); 604 setExceptionSelectorRegister(X86::RDX); 605 } else { 606 setExceptionPointerRegister(X86::EAX); 607 setExceptionSelectorRegister(X86::EDX); 608 } 609 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 610 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 611 612 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 613 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 614 615 setOperationAction(ISD::TRAP, MVT::Other, Legal); 616 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 617 618 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 619 setOperationAction(ISD::VASTART , MVT::Other, Custom); 620 setOperationAction(ISD::VAEND , MVT::Other, Expand); 621 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) { 622 // TargetInfo::X86_64ABIBuiltinVaList 623 setOperationAction(ISD::VAARG , MVT::Other, Custom); 624 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 625 } else { 626 // TargetInfo::CharPtrBuiltinVaList 627 setOperationAction(ISD::VAARG , MVT::Other, Expand); 628 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 629 } 630 631 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 632 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 633 634 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 635 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 636 MVT::i64 : MVT::i32, Custom); 637 else if (TM.Options.EnableSegmentedStacks) 638 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 639 MVT::i64 : MVT::i32, Custom); 640 else 641 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 642 MVT::i64 : MVT::i32, Expand); 643 644 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) { 645 // f32 and f64 use SSE. 646 // Set up the FP register classes. 647 addRegisterClass(MVT::f32, &X86::FR32RegClass); 648 addRegisterClass(MVT::f64, &X86::FR64RegClass); 649 650 // Use ANDPD to simulate FABS. 651 setOperationAction(ISD::FABS , MVT::f64, Custom); 652 setOperationAction(ISD::FABS , MVT::f32, Custom); 653 654 // Use XORP to simulate FNEG. 655 setOperationAction(ISD::FNEG , MVT::f64, Custom); 656 setOperationAction(ISD::FNEG , MVT::f32, Custom); 657 658 // Use ANDPD and ORPD to simulate FCOPYSIGN. 659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 661 662 // Lower this to FGETSIGNx86 plus an AND. 663 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 664 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 665 666 // We don't support sin/cos/fmod 667 setOperationAction(ISD::FSIN , MVT::f64, Expand); 668 setOperationAction(ISD::FCOS , MVT::f64, Expand); 669 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 670 setOperationAction(ISD::FSIN , MVT::f32, Expand); 671 setOperationAction(ISD::FCOS , MVT::f32, Expand); 672 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 673 674 // Expand FP immediates into loads from the stack, except for the special 675 // cases we handle. 676 addLegalFPImmediate(APFloat(+0.0)); // xorpd 677 addLegalFPImmediate(APFloat(+0.0f)); // xorps 678 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) { 679 // Use SSE for f32, x87 for f64. 680 // Set up the FP register classes. 681 addRegisterClass(MVT::f32, &X86::FR32RegClass); 682 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 683 684 // Use ANDPS to simulate FABS. 685 setOperationAction(ISD::FABS , MVT::f32, Custom); 686 687 // Use XORP to simulate FNEG. 688 setOperationAction(ISD::FNEG , MVT::f32, Custom); 689 690 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 691 692 // Use ANDPS and ORPS to simulate FCOPYSIGN. 693 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 694 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 695 696 // We don't support sin/cos/fmod 697 setOperationAction(ISD::FSIN , MVT::f32, Expand); 698 setOperationAction(ISD::FCOS , MVT::f32, Expand); 699 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 700 701 // Special cases we handle for FP constants. 702 addLegalFPImmediate(APFloat(+0.0f)); // xorps 703 addLegalFPImmediate(APFloat(+0.0)); // FLD0 704 addLegalFPImmediate(APFloat(+1.0)); // FLD1 705 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 706 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 707 708 if (!TM.Options.UnsafeFPMath) { 709 setOperationAction(ISD::FSIN , MVT::f64, Expand); 710 setOperationAction(ISD::FCOS , MVT::f64, Expand); 711 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 712 } 713 } else if (!TM.Options.UseSoftFloat) { 714 // f32 and f64 in x87. 715 // Set up the FP register classes. 716 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 717 addRegisterClass(MVT::f32, &X86::RFP32RegClass); 718 719 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 720 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 721 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 722 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 723 724 if (!TM.Options.UnsafeFPMath) { 725 setOperationAction(ISD::FSIN , MVT::f64, Expand); 726 setOperationAction(ISD::FSIN , MVT::f32, Expand); 727 setOperationAction(ISD::FCOS , MVT::f64, Expand); 728 setOperationAction(ISD::FCOS , MVT::f32, Expand); 729 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 730 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 731 } 732 addLegalFPImmediate(APFloat(+0.0)); // FLD0 733 addLegalFPImmediate(APFloat(+1.0)); // FLD1 734 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 735 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 736 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 737 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 738 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 739 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 740 } 741 742 // We don't support FMA. 743 setOperationAction(ISD::FMA, MVT::f64, Expand); 744 setOperationAction(ISD::FMA, MVT::f32, Expand); 745 746 // Long double always uses X87. 747 if (!TM.Options.UseSoftFloat) { 748 addRegisterClass(MVT::f80, &X86::RFP80RegClass); 749 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 750 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 751 { 752 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 753 addLegalFPImmediate(TmpFlt); // FLD0 754 TmpFlt.changeSign(); 755 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 756 757 bool ignored; 758 APFloat TmpFlt2(+1.0); 759 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 760 &ignored); 761 addLegalFPImmediate(TmpFlt2); // FLD1 762 TmpFlt2.changeSign(); 763 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 764 } 765 766 if (!TM.Options.UnsafeFPMath) { 767 setOperationAction(ISD::FSIN , MVT::f80, Expand); 768 setOperationAction(ISD::FCOS , MVT::f80, Expand); 769 setOperationAction(ISD::FSINCOS, MVT::f80, Expand); 770 } 771 772 setOperationAction(ISD::FFLOOR, MVT::f80, Expand); 773 setOperationAction(ISD::FCEIL, MVT::f80, Expand); 774 setOperationAction(ISD::FTRUNC, MVT::f80, Expand); 775 setOperationAction(ISD::FRINT, MVT::f80, Expand); 776 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand); 777 setOperationAction(ISD::FMA, MVT::f80, Expand); 778 } 779 780 // Always use a library call for pow. 781 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 782 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 783 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 784 785 setOperationAction(ISD::FLOG, MVT::f80, Expand); 786 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 787 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 788 setOperationAction(ISD::FEXP, MVT::f80, Expand); 789 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 790 791 // First set operation action for all vector types to either promote 792 // (for widening) or expand (for scalarization). Then we will selectively 793 // turn on ones that can be effectively codegen'd. 794 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 795 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 796 MVT VT = (MVT::SimpleValueType)i; 797 setOperationAction(ISD::ADD , VT, Expand); 798 setOperationAction(ISD::SUB , VT, Expand); 799 setOperationAction(ISD::FADD, VT, Expand); 800 setOperationAction(ISD::FNEG, VT, Expand); 801 setOperationAction(ISD::FSUB, VT, Expand); 802 setOperationAction(ISD::MUL , VT, Expand); 803 setOperationAction(ISD::FMUL, VT, Expand); 804 setOperationAction(ISD::SDIV, VT, Expand); 805 setOperationAction(ISD::UDIV, VT, Expand); 806 setOperationAction(ISD::FDIV, VT, Expand); 807 setOperationAction(ISD::SREM, VT, Expand); 808 setOperationAction(ISD::UREM, VT, Expand); 809 setOperationAction(ISD::LOAD, VT, Expand); 810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand); 811 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand); 812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 813 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand); 814 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand); 815 setOperationAction(ISD::FABS, VT, Expand); 816 setOperationAction(ISD::FSIN, VT, Expand); 817 setOperationAction(ISD::FSINCOS, VT, Expand); 818 setOperationAction(ISD::FCOS, VT, Expand); 819 setOperationAction(ISD::FSINCOS, VT, Expand); 820 setOperationAction(ISD::FREM, VT, Expand); 821 setOperationAction(ISD::FMA, VT, Expand); 822 setOperationAction(ISD::FPOWI, VT, Expand); 823 setOperationAction(ISD::FSQRT, VT, Expand); 824 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 825 setOperationAction(ISD::FFLOOR, VT, Expand); 826 setOperationAction(ISD::FCEIL, VT, Expand); 827 setOperationAction(ISD::FTRUNC, VT, Expand); 828 setOperationAction(ISD::FRINT, VT, Expand); 829 setOperationAction(ISD::FNEARBYINT, VT, Expand); 830 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 831 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 832 setOperationAction(ISD::SDIVREM, VT, Expand); 833 setOperationAction(ISD::UDIVREM, VT, Expand); 834 setOperationAction(ISD::FPOW, VT, Expand); 835 setOperationAction(ISD::CTPOP, VT, Expand); 836 setOperationAction(ISD::CTTZ, VT, Expand); 837 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 838 setOperationAction(ISD::CTLZ, VT, Expand); 839 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 840 setOperationAction(ISD::SHL, VT, Expand); 841 setOperationAction(ISD::SRA, VT, Expand); 842 setOperationAction(ISD::SRL, VT, Expand); 843 setOperationAction(ISD::ROTL, VT, Expand); 844 setOperationAction(ISD::ROTR, VT, Expand); 845 setOperationAction(ISD::BSWAP, VT, Expand); 846 setOperationAction(ISD::SETCC, VT, Expand); 847 setOperationAction(ISD::FLOG, VT, Expand); 848 setOperationAction(ISD::FLOG2, VT, Expand); 849 setOperationAction(ISD::FLOG10, VT, Expand); 850 setOperationAction(ISD::FEXP, VT, Expand); 851 setOperationAction(ISD::FEXP2, VT, Expand); 852 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 853 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 854 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 855 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 856 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand); 857 setOperationAction(ISD::TRUNCATE, VT, Expand); 858 setOperationAction(ISD::SIGN_EXTEND, VT, Expand); 859 setOperationAction(ISD::ZERO_EXTEND, VT, Expand); 860 setOperationAction(ISD::ANY_EXTEND, VT, Expand); 861 setOperationAction(ISD::VSELECT, VT, Expand); 862 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE; 863 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 864 setTruncStoreAction(VT, 865 (MVT::SimpleValueType)InnerVT, Expand); 866 setLoadExtAction(ISD::SEXTLOAD, VT, Expand); 867 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand); 868 setLoadExtAction(ISD::EXTLOAD, VT, Expand); 869 } 870 871 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 872 // with -msoft-float, disable use of MMX as well. 873 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) { 874 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass); 875 // No operations on x86mmx supported, everything uses intrinsics. 876 } 877 878 // MMX-sized vectors (other than x86mmx) are expected to be expanded 879 // into smaller operations. 880 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 881 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 882 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 883 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 884 setOperationAction(ISD::AND, MVT::v8i8, Expand); 885 setOperationAction(ISD::AND, MVT::v4i16, Expand); 886 setOperationAction(ISD::AND, MVT::v2i32, Expand); 887 setOperationAction(ISD::AND, MVT::v1i64, Expand); 888 setOperationAction(ISD::OR, MVT::v8i8, Expand); 889 setOperationAction(ISD::OR, MVT::v4i16, Expand); 890 setOperationAction(ISD::OR, MVT::v2i32, Expand); 891 setOperationAction(ISD::OR, MVT::v1i64, Expand); 892 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 893 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 894 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 895 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 899 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 901 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 902 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 903 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 904 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 905 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 906 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 907 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 908 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 909 910 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) { 911 addRegisterClass(MVT::v4f32, &X86::VR128RegClass); 912 913 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 914 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 915 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 916 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 917 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 918 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 919 setOperationAction(ISD::FABS, MVT::v4f32, Custom); 920 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 921 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 922 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 924 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 925 } 926 927 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) { 928 addRegisterClass(MVT::v2f64, &X86::VR128RegClass); 929 930 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 931 // registers cannot be used even for integer operations. 932 addRegisterClass(MVT::v16i8, &X86::VR128RegClass); 933 addRegisterClass(MVT::v8i16, &X86::VR128RegClass); 934 addRegisterClass(MVT::v4i32, &X86::VR128RegClass); 935 addRegisterClass(MVT::v2i64, &X86::VR128RegClass); 936 937 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 938 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 939 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 940 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 941 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 942 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 943 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 944 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 945 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 946 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 947 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 948 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 949 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 950 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 951 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 952 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 953 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 954 setOperationAction(ISD::FABS, MVT::v2f64, Custom); 955 956 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 957 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 958 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 959 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 960 961 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 962 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 964 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 965 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 966 967 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 968 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 969 MVT VT = (MVT::SimpleValueType)i; 970 // Do not attempt to custom lower non-power-of-2 vectors 971 if (!isPowerOf2_32(VT.getVectorNumElements())) 972 continue; 973 // Do not attempt to custom lower non-128-bit vectors 974 if (!VT.is128BitVector()) 975 continue; 976 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 977 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 978 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 979 } 980 981 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 982 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 983 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 984 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 986 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 987 988 if (Subtarget->is64Bit()) { 989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 991 } 992 993 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 994 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 995 MVT VT = (MVT::SimpleValueType)i; 996 997 // Do not attempt to promote non-128-bit vectors 998 if (!VT.is128BitVector()) 999 continue; 1000 1001 setOperationAction(ISD::AND, VT, Promote); 1002 AddPromotedToType (ISD::AND, VT, MVT::v2i64); 1003 setOperationAction(ISD::OR, VT, Promote); 1004 AddPromotedToType (ISD::OR, VT, MVT::v2i64); 1005 setOperationAction(ISD::XOR, VT, Promote); 1006 AddPromotedToType (ISD::XOR, VT, MVT::v2i64); 1007 setOperationAction(ISD::LOAD, VT, Promote); 1008 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64); 1009 setOperationAction(ISD::SELECT, VT, Promote); 1010 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64); 1011 } 1012 1013 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 1014 1015 // Custom lower v2i64 and v2f64 selects. 1016 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1017 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 1018 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 1019 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 1020 1021 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 1022 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 1023 1024 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1025 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1026 // As there is no 64-bit GPR available, we need build a special custom 1027 // sequence to convert from v2i32 to v2f32. 1028 if (!Subtarget->is64Bit()) 1029 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom); 1030 1031 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1032 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom); 1033 1034 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal); 1035 } 1036 1037 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) { 1038 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1039 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1040 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1041 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1042 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1043 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1044 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1045 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1046 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1047 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1048 1049 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1050 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1051 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1052 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1053 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1054 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 1055 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 1056 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 1057 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 1058 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 1059 1060 // FIXME: Do we need to handle scalar-to-vector here? 1061 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 1062 1063 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 1064 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 1065 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 1066 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 1067 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1068 1069 // i8 and i16 vectors are custom , because the source register and source 1070 // source memory operand types are not the same width. f32 vectors are 1071 // custom since the immediate controlling the insert encodes additional 1072 // information. 1073 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1075 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1076 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1077 1078 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 1079 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 1080 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 1081 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 1082 1083 // FIXME: these should be Legal but thats only for the case where 1084 // the index is constant. For now custom expand to deal with that. 1085 if (Subtarget->is64Bit()) { 1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 1088 } 1089 } 1090 1091 if (Subtarget->hasSSE2()) { 1092 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 1093 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 1094 1095 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 1096 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 1097 1098 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 1099 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 1100 1101 // In the customized shift lowering, the legal cases in AVX2 will be 1102 // recognized. 1103 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 1104 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 1105 1106 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 1107 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 1108 1109 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 1110 1111 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1112 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1113 } 1114 1115 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) { 1116 addRegisterClass(MVT::v32i8, &X86::VR256RegClass); 1117 addRegisterClass(MVT::v16i16, &X86::VR256RegClass); 1118 addRegisterClass(MVT::v8i32, &X86::VR256RegClass); 1119 addRegisterClass(MVT::v8f32, &X86::VR256RegClass); 1120 addRegisterClass(MVT::v4i64, &X86::VR256RegClass); 1121 addRegisterClass(MVT::v4f64, &X86::VR256RegClass); 1122 1123 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 1124 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 1125 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 1126 1127 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 1128 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1129 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1130 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1131 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1132 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal); 1133 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal); 1134 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal); 1135 setOperationAction(ISD::FRINT, MVT::v8f32, Legal); 1136 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal); 1137 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1138 setOperationAction(ISD::FABS, MVT::v8f32, Custom); 1139 1140 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1141 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1142 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1143 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1144 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1145 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1146 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1147 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1148 setOperationAction(ISD::FRINT, MVT::v4f64, Legal); 1149 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal); 1150 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1151 setOperationAction(ISD::FABS, MVT::v4f64, Custom); 1152 1153 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom); 1154 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom); 1155 1156 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 1157 1158 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1159 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 1160 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1161 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1162 1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1164 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom); 1165 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 1166 1167 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal); 1168 1169 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1170 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1171 1172 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1173 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1174 1175 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1176 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1177 1178 setOperationAction(ISD::SDIV, MVT::v16i16, Custom); 1179 1180 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1181 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1182 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1183 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1184 1185 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1186 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1187 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1188 1189 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1190 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1191 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1192 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1193 1194 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom); 1195 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom); 1196 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom); 1197 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1198 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom); 1199 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom); 1200 1201 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) { 1202 setOperationAction(ISD::FMA, MVT::v8f32, Legal); 1203 setOperationAction(ISD::FMA, MVT::v4f64, Legal); 1204 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 1205 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1206 setOperationAction(ISD::FMA, MVT::f32, Legal); 1207 setOperationAction(ISD::FMA, MVT::f64, Legal); 1208 } 1209 1210 if (Subtarget->hasInt256()) { 1211 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1212 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1213 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1214 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1215 1216 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1217 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1218 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1219 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1220 1221 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1222 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1223 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1224 // Don't lower v32i8 because there is no 128-bit byte mul 1225 1226 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1227 1228 setOperationAction(ISD::SDIV, MVT::v8i32, Custom); 1229 } else { 1230 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1231 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1232 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1233 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1234 1235 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1236 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1237 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1238 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1239 1240 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1241 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1242 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1243 // Don't lower v32i8 because there is no 128-bit byte mul 1244 } 1245 1246 // In the customized shift lowering, the legal cases in AVX2 will be 1247 // recognized. 1248 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1249 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1250 1251 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1252 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1253 1254 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1255 1256 // Custom lower several nodes for 256-bit types. 1257 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 1258 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 1259 MVT VT = (MVT::SimpleValueType)i; 1260 1261 // Extract subvector is special because the value type 1262 // (result) is 128-bit but the source is 256-bit wide. 1263 if (VT.is128BitVector()) 1264 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1265 1266 // Do not attempt to custom lower other non-256-bit vectors 1267 if (!VT.is256BitVector()) 1268 continue; 1269 1270 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1271 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1277 } 1278 1279 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1280 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) { 1281 MVT VT = (MVT::SimpleValueType)i; 1282 1283 // Do not attempt to promote non-256-bit vectors 1284 if (!VT.is256BitVector()) 1285 continue; 1286 1287 setOperationAction(ISD::AND, VT, Promote); 1288 AddPromotedToType (ISD::AND, VT, MVT::v4i64); 1289 setOperationAction(ISD::OR, VT, Promote); 1290 AddPromotedToType (ISD::OR, VT, MVT::v4i64); 1291 setOperationAction(ISD::XOR, VT, Promote); 1292 AddPromotedToType (ISD::XOR, VT, MVT::v4i64); 1293 setOperationAction(ISD::LOAD, VT, Promote); 1294 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64); 1295 setOperationAction(ISD::SELECT, VT, Promote); 1296 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64); 1297 } 1298 } 1299 1300 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) { 1301 addRegisterClass(MVT::v16i32, &X86::VR512RegClass); 1302 addRegisterClass(MVT::v16f32, &X86::VR512RegClass); 1303 addRegisterClass(MVT::v8i64, &X86::VR512RegClass); 1304 addRegisterClass(MVT::v8f64, &X86::VR512RegClass); 1305 1306 addRegisterClass(MVT::v8i1, &X86::VK8RegClass); 1307 addRegisterClass(MVT::v16i1, &X86::VK16RegClass); 1308 1309 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal); 1310 setOperationAction(ISD::LOAD, MVT::v16f32, Legal); 1311 setOperationAction(ISD::LOAD, MVT::v8f64, Legal); 1312 setOperationAction(ISD::LOAD, MVT::v8i64, Legal); 1313 setOperationAction(ISD::LOAD, MVT::v16i32, Legal); 1314 setOperationAction(ISD::LOAD, MVT::v16i1, Legal); 1315 1316 setOperationAction(ISD::FADD, MVT::v16f32, Legal); 1317 setOperationAction(ISD::FSUB, MVT::v16f32, Legal); 1318 setOperationAction(ISD::FMUL, MVT::v16f32, Legal); 1319 setOperationAction(ISD::FDIV, MVT::v16f32, Legal); 1320 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal); 1321 setOperationAction(ISD::FNEG, MVT::v16f32, Custom); 1322 1323 setOperationAction(ISD::FADD, MVT::v8f64, Legal); 1324 setOperationAction(ISD::FSUB, MVT::v8f64, Legal); 1325 setOperationAction(ISD::FMUL, MVT::v8f64, Legal); 1326 setOperationAction(ISD::FDIV, MVT::v8f64, Legal); 1327 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal); 1328 setOperationAction(ISD::FNEG, MVT::v8f64, Custom); 1329 setOperationAction(ISD::FMA, MVT::v8f64, Legal); 1330 setOperationAction(ISD::FMA, MVT::v16f32, Legal); 1331 setOperationAction(ISD::SDIV, MVT::v16i32, Custom); 1332 1333 1334 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal); 1335 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal); 1336 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal); 1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal); 1338 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal); 1339 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal); 1340 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal); 1341 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal); 1342 1343 setOperationAction(ISD::TRUNCATE, MVT::i1, Legal); 1344 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom); 1345 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom); 1346 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom); 1347 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom); 1348 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom); 1349 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom); 1350 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom); 1351 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom); 1352 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom); 1353 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom); 1354 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom); 1355 1356 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom); 1357 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom); 1358 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom); 1359 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom); 1360 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom); 1361 1362 setOperationAction(ISD::SETCC, MVT::v16i1, Custom); 1363 setOperationAction(ISD::SETCC, MVT::v8i1, Custom); 1364 1365 setOperationAction(ISD::MUL, MVT::v8i64, Custom); 1366 1367 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom); 1368 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom); 1369 setOperationAction(ISD::SELECT, MVT::v8f64, Custom); 1370 setOperationAction(ISD::SELECT, MVT::v8i64, Custom); 1371 setOperationAction(ISD::SELECT, MVT::v16f32, Custom); 1372 1373 setOperationAction(ISD::ADD, MVT::v8i64, Legal); 1374 setOperationAction(ISD::ADD, MVT::v16i32, Legal); 1375 1376 setOperationAction(ISD::SUB, MVT::v8i64, Legal); 1377 setOperationAction(ISD::SUB, MVT::v16i32, Legal); 1378 1379 setOperationAction(ISD::MUL, MVT::v16i32, Legal); 1380 1381 setOperationAction(ISD::SRL, MVT::v8i64, Custom); 1382 setOperationAction(ISD::SRL, MVT::v16i32, Custom); 1383 1384 setOperationAction(ISD::SHL, MVT::v8i64, Custom); 1385 setOperationAction(ISD::SHL, MVT::v16i32, Custom); 1386 1387 setOperationAction(ISD::SRA, MVT::v8i64, Custom); 1388 setOperationAction(ISD::SRA, MVT::v16i32, Custom); 1389 1390 setOperationAction(ISD::AND, MVT::v8i64, Legal); 1391 setOperationAction(ISD::OR, MVT::v8i64, Legal); 1392 setOperationAction(ISD::XOR, MVT::v8i64, Legal); 1393 1394 // Custom lower several nodes. 1395 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 1396 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 1397 MVT VT = (MVT::SimpleValueType)i; 1398 1399 unsigned EltSize = VT.getVectorElementType().getSizeInBits(); 1400 // Extract subvector is special because the value type 1401 // (result) is 256/128-bit but the source is 512-bit wide. 1402 if (VT.is128BitVector() || VT.is256BitVector()) 1403 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1404 1405 if (VT.getVectorElementType() == MVT::i1) 1406 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal); 1407 1408 // Do not attempt to custom lower other non-512-bit vectors 1409 if (!VT.is512BitVector()) 1410 continue; 1411 1412 if (VT != MVT::v8i64) { 1413 setOperationAction(ISD::XOR, VT, Promote); 1414 AddPromotedToType (ISD::XOR, VT, MVT::v8i64); 1415 setOperationAction(ISD::OR, VT, Promote); 1416 AddPromotedToType (ISD::OR, VT, MVT::v8i64); 1417 setOperationAction(ISD::AND, VT, Promote); 1418 AddPromotedToType (ISD::AND, VT, MVT::v8i64); 1419 } 1420 if ( EltSize >= 32) { 1421 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1422 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1423 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1424 setOperationAction(ISD::VSELECT, VT, Legal); 1425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1426 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 1427 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1428 } 1429 } 1430 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) { 1431 MVT VT = (MVT::SimpleValueType)i; 1432 1433 // Do not attempt to promote non-256-bit vectors 1434 if (!VT.is512BitVector()) 1435 continue; 1436 1437 setOperationAction(ISD::LOAD, VT, Promote); 1438 AddPromotedToType (ISD::LOAD, VT, MVT::v8i64); 1439 setOperationAction(ISD::SELECT, VT, Promote); 1440 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64); 1441 } 1442 }// has AVX-512 1443 1444 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1445 // of this type with custom code. 1446 for (int VT = MVT::FIRST_VECTOR_VALUETYPE; 1447 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) { 1448 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, 1449 Custom); 1450 } 1451 1452 // We want to custom lower some of our intrinsics. 1453 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1454 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 1455 1456 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1457 // handle type legalization for these operations here. 1458 // 1459 // FIXME: We really should do custom legalization for addition and 1460 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1461 // than generic legalization for 64-bit multiplication-with-overflow, though. 1462 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1463 // Add/Sub/Mul with overflow operations are custom lowered. 1464 MVT VT = IntVTs[i]; 1465 setOperationAction(ISD::SADDO, VT, Custom); 1466 setOperationAction(ISD::UADDO, VT, Custom); 1467 setOperationAction(ISD::SSUBO, VT, Custom); 1468 setOperationAction(ISD::USUBO, VT, Custom); 1469 setOperationAction(ISD::SMULO, VT, Custom); 1470 setOperationAction(ISD::UMULO, VT, Custom); 1471 } 1472 1473 // There are no 8-bit 3-address imul/mul instructions 1474 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1475 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1476 1477 if (!Subtarget->is64Bit()) { 1478 // These libcalls are not available in 32-bit. 1479 setLibcallName(RTLIB::SHL_I128, 0); 1480 setLibcallName(RTLIB::SRL_I128, 0); 1481 setLibcallName(RTLIB::SRA_I128, 0); 1482 } 1483 1484 // Combine sin / cos into one node or libcall if possible. 1485 if (Subtarget->hasSinCos()) { 1486 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1487 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1488 if (Subtarget->isTargetDarwin()) { 1489 // For MacOSX, we don't want to the normal expansion of a libcall to 1490 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 1491 // traffic. 1492 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1493 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1494 } 1495 } 1496 1497 // We have target-specific dag combine patterns for the following nodes: 1498 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1499 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1500 setTargetDAGCombine(ISD::VSELECT); 1501 setTargetDAGCombine(ISD::SELECT); 1502 setTargetDAGCombine(ISD::SHL); 1503 setTargetDAGCombine(ISD::SRA); 1504 setTargetDAGCombine(ISD::SRL); 1505 setTargetDAGCombine(ISD::OR); 1506 setTargetDAGCombine(ISD::AND); 1507 setTargetDAGCombine(ISD::ADD); 1508 setTargetDAGCombine(ISD::FADD); 1509 setTargetDAGCombine(ISD::FSUB); 1510 setTargetDAGCombine(ISD::FMA); 1511 setTargetDAGCombine(ISD::SUB); 1512 setTargetDAGCombine(ISD::LOAD); 1513 setTargetDAGCombine(ISD::STORE); 1514 setTargetDAGCombine(ISD::ZERO_EXTEND); 1515 setTargetDAGCombine(ISD::ANY_EXTEND); 1516 setTargetDAGCombine(ISD::SIGN_EXTEND); 1517 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1518 setTargetDAGCombine(ISD::TRUNCATE); 1519 setTargetDAGCombine(ISD::SINT_TO_FP); 1520 setTargetDAGCombine(ISD::SETCC); 1521 if (Subtarget->is64Bit()) 1522 setTargetDAGCombine(ISD::MUL); 1523 setTargetDAGCombine(ISD::XOR); 1524 1525 computeRegisterProperties(); 1526 1527 // On Darwin, -Os means optimize for size without hurting performance, 1528 // do not reduce the limit. 1529 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1530 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1531 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1532 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1533 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1534 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1535 setPrefLoopAlignment(4); // 2^4 bytes. 1536 1537 // Predictable cmov don't hurt on atom because it's in-order. 1538 PredictableSelectIsExpensive = !Subtarget->isAtom(); 1539 1540 setPrefFunctionAlignment(4); // 2^4 bytes. 1541 } 1542 1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 1544 if (!VT.isVector()) return MVT::i8; 1545 return VT.changeVectorElementTypeToInteger(); 1546 } 1547 1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1549 /// the desired ByVal argument alignment. 1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1551 if (MaxAlign == 16) 1552 return; 1553 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1554 if (VTy->getBitWidth() == 128) 1555 MaxAlign = 16; 1556 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1557 unsigned EltAlign = 0; 1558 getMaxByValAlign(ATy->getElementType(), EltAlign); 1559 if (EltAlign > MaxAlign) 1560 MaxAlign = EltAlign; 1561 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1562 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1563 unsigned EltAlign = 0; 1564 getMaxByValAlign(STy->getElementType(i), EltAlign); 1565 if (EltAlign > MaxAlign) 1566 MaxAlign = EltAlign; 1567 if (MaxAlign == 16) 1568 break; 1569 } 1570 } 1571 } 1572 1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1574 /// function arguments in the caller parameter area. For X86, aggregates 1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest 1576 /// are at 4-byte boundaries. 1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1578 if (Subtarget->is64Bit()) { 1579 // Max of 8 and alignment of type. 1580 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1581 if (TyAlign > 8) 1582 return TyAlign; 1583 return 8; 1584 } 1585 1586 unsigned Align = 4; 1587 if (Subtarget->hasSSE1()) 1588 getMaxByValAlign(Ty, Align); 1589 return Align; 1590 } 1591 1592 /// getOptimalMemOpType - Returns the target specific optimal type for load 1593 /// and store operations as a result of memset, memcpy, and memmove 1594 /// lowering. If DstAlign is zero that means it's safe to destination 1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1596 /// means there isn't a need to check it against alignment requirement, 1597 /// probably because the source does not need to be loaded. If 'IsMemset' is 1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 1600 /// source is constant so it does not need to be loaded. 1601 /// It returns EVT::Other if the type should be determined using generic 1602 /// target-independent logic. 1603 EVT 1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1605 unsigned DstAlign, unsigned SrcAlign, 1606 bool IsMemset, bool ZeroMemset, 1607 bool MemcpyStrSrc, 1608 MachineFunction &MF) const { 1609 const Function *F = MF.getFunction(); 1610 if ((!IsMemset || ZeroMemset) && 1611 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1612 Attribute::NoImplicitFloat)) { 1613 if (Size >= 16 && 1614 (Subtarget->isUnalignedMemAccessFast() || 1615 ((DstAlign == 0 || DstAlign >= 16) && 1616 (SrcAlign == 0 || SrcAlign >= 16)))) { 1617 if (Size >= 32) { 1618 if (Subtarget->hasInt256()) 1619 return MVT::v8i32; 1620 if (Subtarget->hasFp256()) 1621 return MVT::v8f32; 1622 } 1623 if (Subtarget->hasSSE2()) 1624 return MVT::v4i32; 1625 if (Subtarget->hasSSE1()) 1626 return MVT::v4f32; 1627 } else if (!MemcpyStrSrc && Size >= 8 && 1628 !Subtarget->is64Bit() && 1629 Subtarget->hasSSE2()) { 1630 // Do not use f64 to lower memcpy if source is string constant. It's 1631 // better to use i32 to avoid the loads. 1632 return MVT::f64; 1633 } 1634 } 1635 if (Subtarget->is64Bit() && Size >= 8) 1636 return MVT::i64; 1637 return MVT::i32; 1638 } 1639 1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const { 1641 if (VT == MVT::f32) 1642 return X86ScalarSSEf32; 1643 else if (VT == MVT::f64) 1644 return X86ScalarSSEf64; 1645 return true; 1646 } 1647 1648 bool 1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const { 1650 if (Fast) 1651 *Fast = Subtarget->isUnalignedMemAccessFast(); 1652 return true; 1653 } 1654 1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 1656 /// current function. The returned value is a member of the 1657 /// MachineJumpTableInfo::JTEntryKind enum. 1658 unsigned X86TargetLowering::getJumpTableEncoding() const { 1659 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1660 // symbol. 1661 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1662 Subtarget->isPICStyleGOT()) 1663 return MachineJumpTableInfo::EK_Custom32; 1664 1665 // Otherwise, use the normal jump table encoding heuristics. 1666 return TargetLowering::getJumpTableEncoding(); 1667 } 1668 1669 const MCExpr * 1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1671 const MachineBasicBlock *MBB, 1672 unsigned uid,MCContext &Ctx) const{ 1673 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1674 Subtarget->isPICStyleGOT()); 1675 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1676 // entries. 1677 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1678 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1679 } 1680 1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1682 /// jumptable. 1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1684 SelectionDAG &DAG) const { 1685 if (!Subtarget->is64Bit()) 1686 // This doesn't have SDLoc associated with it, but is not really the 1687 // same as a Register. 1688 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy()); 1689 return Table; 1690 } 1691 1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1694 /// MCExpr. 1695 const MCExpr *X86TargetLowering:: 1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1697 MCContext &Ctx) const { 1698 // X86-64 uses RIP relative addressing based on the jump table label. 1699 if (Subtarget->isPICStyleRIPRel()) 1700 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1701 1702 // Otherwise, the reference is relative to the PIC base. 1703 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1704 } 1705 1706 // FIXME: Why this routine is here? Move to RegInfo! 1707 std::pair<const TargetRegisterClass*, uint8_t> 1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{ 1709 const TargetRegisterClass *RRC = 0; 1710 uint8_t Cost = 1; 1711 switch (VT.SimpleTy) { 1712 default: 1713 return TargetLowering::findRepresentativeClass(VT); 1714 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1715 RRC = Subtarget->is64Bit() ? 1716 (const TargetRegisterClass*)&X86::GR64RegClass : 1717 (const TargetRegisterClass*)&X86::GR32RegClass; 1718 break; 1719 case MVT::x86mmx: 1720 RRC = &X86::VR64RegClass; 1721 break; 1722 case MVT::f32: case MVT::f64: 1723 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1724 case MVT::v4f32: case MVT::v2f64: 1725 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1726 case MVT::v4f64: 1727 RRC = &X86::VR128RegClass; 1728 break; 1729 } 1730 return std::make_pair(RRC, Cost); 1731 } 1732 1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1734 unsigned &Offset) const { 1735 if (!Subtarget->isTargetLinux()) 1736 return false; 1737 1738 if (Subtarget->is64Bit()) { 1739 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1740 Offset = 0x28; 1741 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1742 AddressSpace = 256; 1743 else 1744 AddressSpace = 257; 1745 } else { 1746 // %gs:0x14 on i386 1747 Offset = 0x14; 1748 AddressSpace = 256; 1749 } 1750 return true; 1751 } 1752 1753 //===----------------------------------------------------------------------===// 1754 // Return Value Calling Convention Implementation 1755 //===----------------------------------------------------------------------===// 1756 1757 #include "X86GenCallingConv.inc" 1758 1759 bool 1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1761 MachineFunction &MF, bool isVarArg, 1762 const SmallVectorImpl<ISD::OutputArg> &Outs, 1763 LLVMContext &Context) const { 1764 SmallVector<CCValAssign, 16> RVLocs; 1765 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1766 RVLocs, Context); 1767 return CCInfo.CheckReturn(Outs, RetCC_X86); 1768 } 1769 1770 SDValue 1771 X86TargetLowering::LowerReturn(SDValue Chain, 1772 CallingConv::ID CallConv, bool isVarArg, 1773 const SmallVectorImpl<ISD::OutputArg> &Outs, 1774 const SmallVectorImpl<SDValue> &OutVals, 1775 SDLoc dl, SelectionDAG &DAG) const { 1776 MachineFunction &MF = DAG.getMachineFunction(); 1777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1778 1779 SmallVector<CCValAssign, 16> RVLocs; 1780 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1781 RVLocs, *DAG.getContext()); 1782 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1783 1784 SDValue Flag; 1785 SmallVector<SDValue, 6> RetOps; 1786 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1787 // Operand #1 = Bytes To Pop 1788 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1789 MVT::i16)); 1790 1791 // Copy the result values into the output registers. 1792 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1793 CCValAssign &VA = RVLocs[i]; 1794 assert(VA.isRegLoc() && "Can only return in registers!"); 1795 SDValue ValToCopy = OutVals[i]; 1796 EVT ValVT = ValToCopy.getValueType(); 1797 1798 // Promote values to the appropriate types 1799 if (VA.getLocInfo() == CCValAssign::SExt) 1800 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy); 1801 else if (VA.getLocInfo() == CCValAssign::ZExt) 1802 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy); 1803 else if (VA.getLocInfo() == CCValAssign::AExt) 1804 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy); 1805 else if (VA.getLocInfo() == CCValAssign::BCvt) 1806 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy); 1807 1808 // If this is x86-64, and we disabled SSE, we can't return FP values, 1809 // or SSE or MMX vectors. 1810 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1811 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1812 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) { 1813 report_fatal_error("SSE register return with SSE disabled"); 1814 } 1815 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1816 // llvm-gcc has never done it right and no one has noticed, so this 1817 // should be OK for now. 1818 if (ValVT == MVT::f64 && 1819 (Subtarget->is64Bit() && !Subtarget->hasSSE2())) 1820 report_fatal_error("SSE2 register return with SSE2 disabled"); 1821 1822 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1823 // the RET instruction and handled by the FP Stackifier. 1824 if (VA.getLocReg() == X86::ST0 || 1825 VA.getLocReg() == X86::ST1) { 1826 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1827 // change the value to the FP stack register class. 1828 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1829 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1830 RetOps.push_back(ValToCopy); 1831 // Don't emit a copytoreg. 1832 continue; 1833 } 1834 1835 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1836 // which is returned in RAX / RDX. 1837 if (Subtarget->is64Bit()) { 1838 if (ValVT == MVT::x86mmx) { 1839 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1840 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1841 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1842 ValToCopy); 1843 // If we don't have SSE2 available, convert to v4f32 so the generated 1844 // register is legal. 1845 if (!Subtarget->hasSSE2()) 1846 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1847 } 1848 } 1849 } 1850 1851 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1852 Flag = Chain.getValue(1); 1853 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1854 } 1855 1856 // The x86-64 ABIs require that for returning structs by value we copy 1857 // the sret argument into %rax/%eax (depending on ABI) for the return. 1858 // Win32 requires us to put the sret argument to %eax as well. 1859 // We saved the argument into a virtual register in the entry block, 1860 // so now we copy the value out and into %rax/%eax. 1861 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() && 1862 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 1863 MachineFunction &MF = DAG.getMachineFunction(); 1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1865 unsigned Reg = FuncInfo->getSRetReturnReg(); 1866 assert(Reg && 1867 "SRetReturnReg should have been set in LowerFormalArguments()."); 1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1869 1870 unsigned RetValReg 1871 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ? 1872 X86::RAX : X86::EAX; 1873 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag); 1874 Flag = Chain.getValue(1); 1875 1876 // RAX/EAX now acts like a return value. 1877 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy())); 1878 } 1879 1880 RetOps[0] = Chain; // Update chain. 1881 1882 // Add the flag if we have it. 1883 if (Flag.getNode()) 1884 RetOps.push_back(Flag); 1885 1886 return DAG.getNode(X86ISD::RET_FLAG, dl, 1887 MVT::Other, &RetOps[0], RetOps.size()); 1888 } 1889 1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 1891 if (N->getNumValues() != 1) 1892 return false; 1893 if (!N->hasNUsesOfValue(1, 0)) 1894 return false; 1895 1896 SDValue TCChain = Chain; 1897 SDNode *Copy = *N->use_begin(); 1898 if (Copy->getOpcode() == ISD::CopyToReg) { 1899 // If the copy has a glue operand, we conservatively assume it isn't safe to 1900 // perform a tail call. 1901 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 1902 return false; 1903 TCChain = Copy->getOperand(0); 1904 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 1905 return false; 1906 1907 bool HasRet = false; 1908 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1909 UI != UE; ++UI) { 1910 if (UI->getOpcode() != X86ISD::RET_FLAG) 1911 return false; 1912 HasRet = true; 1913 } 1914 1915 if (!HasRet) 1916 return false; 1917 1918 Chain = TCChain; 1919 return true; 1920 } 1921 1922 MVT 1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT, 1924 ISD::NodeType ExtendKind) const { 1925 MVT ReturnMVT; 1926 // TODO: Is this also valid on 32-bit? 1927 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1928 ReturnMVT = MVT::i8; 1929 else 1930 ReturnMVT = MVT::i32; 1931 1932 MVT MinVT = getRegisterType(ReturnMVT); 1933 return VT.bitsLT(MinVT) ? MinVT : VT; 1934 } 1935 1936 /// LowerCallResult - Lower the result values of a call into the 1937 /// appropriate copies out of appropriate physical registers. 1938 /// 1939 SDValue 1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1941 CallingConv::ID CallConv, bool isVarArg, 1942 const SmallVectorImpl<ISD::InputArg> &Ins, 1943 SDLoc dl, SelectionDAG &DAG, 1944 SmallVectorImpl<SDValue> &InVals) const { 1945 1946 // Assign locations to each value returned by this call. 1947 SmallVector<CCValAssign, 16> RVLocs; 1948 bool Is64Bit = Subtarget->is64Bit(); 1949 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1950 getTargetMachine(), RVLocs, *DAG.getContext()); 1951 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1952 1953 // Copy all of the result registers out of their specified physreg. 1954 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 1955 CCValAssign &VA = RVLocs[i]; 1956 EVT CopyVT = VA.getValVT(); 1957 1958 // If this is x86-64, and we disabled SSE, we can't return FP values 1959 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1960 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 1961 report_fatal_error("SSE register return with SSE disabled"); 1962 } 1963 1964 SDValue Val; 1965 1966 // If this is a call to a function that returns an fp value on the floating 1967 // point stack, we must guarantee the value is popped from the stack, so 1968 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1969 // if the return value is not used. We use the FpPOP_RETVAL instruction 1970 // instead. 1971 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1972 // If we prefer to use the value in xmm registers, copy it out as f80 and 1973 // use a truncate to move it from fp stack reg to xmm reg. 1974 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1975 SDValue Ops[] = { Chain, InFlag }; 1976 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1977 MVT::Other, MVT::Glue, Ops), 1); 1978 Val = Chain.getValue(0); 1979 1980 // Round the f80 to the right size, which also moves it to the appropriate 1981 // xmm register. 1982 if (CopyVT != VA.getValVT()) 1983 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1984 // This truncation won't change the value. 1985 DAG.getIntPtrConstant(1)); 1986 } else { 1987 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1988 CopyVT, InFlag).getValue(1); 1989 Val = Chain.getValue(0); 1990 } 1991 InFlag = Chain.getValue(2); 1992 InVals.push_back(Val); 1993 } 1994 1995 return Chain; 1996 } 1997 1998 //===----------------------------------------------------------------------===// 1999 // C & StdCall & Fast Calling Convention implementation 2000 //===----------------------------------------------------------------------===// 2001 // StdCall calling convention seems to be standard for many Windows' API 2002 // routines and around. It differs from C calling convention just a little: 2003 // callee should clean up the stack, not caller. Symbols should be also 2004 // decorated in some fancy way :) It doesn't support any vector arguments. 2005 // For info on fast calling convention see Fast Calling Convention (tail call) 2006 // implementation LowerX86_32FastCCCallTo. 2007 2008 /// CallIsStructReturn - Determines whether a call uses struct return 2009 /// semantics. 2010 enum StructReturnType { 2011 NotStructReturn, 2012 RegStructReturn, 2013 StackStructReturn 2014 }; 2015 static StructReturnType 2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 2017 if (Outs.empty()) 2018 return NotStructReturn; 2019 2020 const ISD::ArgFlagsTy &Flags = Outs[0].Flags; 2021 if (!Flags.isSRet()) 2022 return NotStructReturn; 2023 if (Flags.isInReg()) 2024 return RegStructReturn; 2025 return StackStructReturn; 2026 } 2027 2028 /// ArgsAreStructReturn - Determines whether a function uses struct 2029 /// return semantics. 2030 static StructReturnType 2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 2032 if (Ins.empty()) 2033 return NotStructReturn; 2034 2035 const ISD::ArgFlagsTy &Flags = Ins[0].Flags; 2036 if (!Flags.isSRet()) 2037 return NotStructReturn; 2038 if (Flags.isInReg()) 2039 return RegStructReturn; 2040 return StackStructReturn; 2041 } 2042 2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 2044 /// by "Src" to address "Dst" with size and alignment information specified by 2045 /// the specific parameter attribute. The copy will be passed as a byval 2046 /// function parameter. 2047 static SDValue 2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 2049 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 2050 SDLoc dl) { 2051 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 2052 2053 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 2054 /*isVolatile*/false, /*AlwaysInline=*/true, 2055 MachinePointerInfo(), MachinePointerInfo()); 2056 } 2057 2058 /// IsTailCallConvention - Return true if the calling convention is one that 2059 /// supports tail call optimization. 2060 static bool IsTailCallConvention(CallingConv::ID CC) { 2061 return (CC == CallingConv::Fast || CC == CallingConv::GHC || 2062 CC == CallingConv::HiPE); 2063 } 2064 2065 /// \brief Return true if the calling convention is a C calling convention. 2066 static bool IsCCallConvention(CallingConv::ID CC) { 2067 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 || 2068 CC == CallingConv::X86_64_SysV); 2069 } 2070 2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 2072 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 2073 return false; 2074 2075 CallSite CS(CI); 2076 CallingConv::ID CalleeCC = CS.getCallingConv(); 2077 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC)) 2078 return false; 2079 2080 return true; 2081 } 2082 2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into 2084 /// a tailcall target by changing its ABI. 2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC, 2086 bool GuaranteedTailCallOpt) { 2087 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 2088 } 2089 2090 SDValue 2091 X86TargetLowering::LowerMemArgument(SDValue Chain, 2092 CallingConv::ID CallConv, 2093 const SmallVectorImpl<ISD::InputArg> &Ins, 2094 SDLoc dl, SelectionDAG &DAG, 2095 const CCValAssign &VA, 2096 MachineFrameInfo *MFI, 2097 unsigned i) const { 2098 // Create the nodes corresponding to a load from this parameter slot. 2099 ISD::ArgFlagsTy Flags = Ins[i].Flags; 2100 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv, 2101 getTargetMachine().Options.GuaranteedTailCallOpt); 2102 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 2103 EVT ValVT; 2104 2105 // If value is passed by pointer we have address passed instead of the value 2106 // itself. 2107 if (VA.getLocInfo() == CCValAssign::Indirect) 2108 ValVT = VA.getLocVT(); 2109 else 2110 ValVT = VA.getValVT(); 2111 2112 // FIXME: For now, all byval parameter objects are marked mutable. This can be 2113 // changed with more analysis. 2114 // In case of tail call optimization mark all arguments mutable. Since they 2115 // could be overwritten by lowering of arguments in case of a tail call. 2116 if (Flags.isByVal()) { 2117 unsigned Bytes = Flags.getByValSize(); 2118 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 2119 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 2120 return DAG.getFrameIndex(FI, getPointerTy()); 2121 } else { 2122 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 2123 VA.getLocMemOffset(), isImmutable); 2124 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 2125 return DAG.getLoad(ValVT, dl, Chain, FIN, 2126 MachinePointerInfo::getFixedStack(FI), 2127 false, false, false, 0); 2128 } 2129 } 2130 2131 SDValue 2132 X86TargetLowering::LowerFormalArguments(SDValue Chain, 2133 CallingConv::ID CallConv, 2134 bool isVarArg, 2135 const SmallVectorImpl<ISD::InputArg> &Ins, 2136 SDLoc dl, 2137 SelectionDAG &DAG, 2138 SmallVectorImpl<SDValue> &InVals) 2139 const { 2140 MachineFunction &MF = DAG.getMachineFunction(); 2141 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2142 2143 const Function* Fn = MF.getFunction(); 2144 if (Fn->hasExternalLinkage() && 2145 Subtarget->isTargetCygMing() && 2146 Fn->getName() == "main") 2147 FuncInfo->setForceFramePointer(true); 2148 2149 MachineFrameInfo *MFI = MF.getFrameInfo(); 2150 bool Is64Bit = Subtarget->is64Bit(); 2151 bool IsWindows = Subtarget->isTargetWindows(); 2152 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv); 2153 2154 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2155 "Var args not supported with calling convention fastcc, ghc or hipe"); 2156 2157 // Assign locations to all of the incoming arguments. 2158 SmallVector<CCValAssign, 16> ArgLocs; 2159 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2160 ArgLocs, *DAG.getContext()); 2161 2162 // Allocate shadow area for Win64 2163 if (IsWin64) 2164 CCInfo.AllocateStack(32, 8); 2165 2166 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 2167 2168 unsigned LastVal = ~0U; 2169 SDValue ArgValue; 2170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2171 CCValAssign &VA = ArgLocs[i]; 2172 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 2173 // places. 2174 assert(VA.getValNo() != LastVal && 2175 "Don't support value assigned to multiple locs yet"); 2176 (void)LastVal; 2177 LastVal = VA.getValNo(); 2178 2179 if (VA.isRegLoc()) { 2180 EVT RegVT = VA.getLocVT(); 2181 const TargetRegisterClass *RC; 2182 if (RegVT == MVT::i32) 2183 RC = &X86::GR32RegClass; 2184 else if (Is64Bit && RegVT == MVT::i64) 2185 RC = &X86::GR64RegClass; 2186 else if (RegVT == MVT::f32) 2187 RC = &X86::FR32RegClass; 2188 else if (RegVT == MVT::f64) 2189 RC = &X86::FR64RegClass; 2190 else if (RegVT.is512BitVector()) 2191 RC = &X86::VR512RegClass; 2192 else if (RegVT.is256BitVector()) 2193 RC = &X86::VR256RegClass; 2194 else if (RegVT.is128BitVector()) 2195 RC = &X86::VR128RegClass; 2196 else if (RegVT == MVT::x86mmx) 2197 RC = &X86::VR64RegClass; 2198 else if (RegVT == MVT::v8i1) 2199 RC = &X86::VK8RegClass; 2200 else if (RegVT == MVT::v16i1) 2201 RC = &X86::VK16RegClass; 2202 else 2203 llvm_unreachable("Unknown argument type!"); 2204 2205 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2206 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 2207 2208 // If this is an 8 or 16-bit value, it is really passed promoted to 32 2209 // bits. Insert an assert[sz]ext to capture this, then truncate to the 2210 // right size. 2211 if (VA.getLocInfo() == CCValAssign::SExt) 2212 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 2213 DAG.getValueType(VA.getValVT())); 2214 else if (VA.getLocInfo() == CCValAssign::ZExt) 2215 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 2216 DAG.getValueType(VA.getValVT())); 2217 else if (VA.getLocInfo() == CCValAssign::BCvt) 2218 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 2219 2220 if (VA.isExtInLoc()) { 2221 // Handle MMX values passed in XMM regs. 2222 if (RegVT.isVector()) 2223 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue); 2224 else 2225 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 2226 } 2227 } else { 2228 assert(VA.isMemLoc()); 2229 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 2230 } 2231 2232 // If value is passed via pointer - do a load. 2233 if (VA.getLocInfo() == CCValAssign::Indirect) 2234 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 2235 MachinePointerInfo(), false, false, false, 0); 2236 2237 InVals.push_back(ArgValue); 2238 } 2239 2240 // The x86-64 ABIs require that for returning structs by value we copy 2241 // the sret argument into %rax/%eax (depending on ABI) for the return. 2242 // Win32 requires us to put the sret argument to %eax as well. 2243 // Save the argument into a virtual register so that we can access it 2244 // from the return points. 2245 if (MF.getFunction()->hasStructRetAttr() && 2246 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 2247 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2248 unsigned Reg = FuncInfo->getSRetReturnReg(); 2249 if (!Reg) { 2250 MVT PtrTy = getPointerTy(); 2251 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 2252 FuncInfo->setSRetReturnReg(Reg); 2253 } 2254 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 2255 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 2256 } 2257 2258 unsigned StackSize = CCInfo.getNextStackOffset(); 2259 // Align stack specially for tail calls. 2260 if (FuncIsMadeTailCallSafe(CallConv, 2261 MF.getTarget().Options.GuaranteedTailCallOpt)) 2262 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 2263 2264 // If the function takes variable number of arguments, make a frame index for 2265 // the start of the first vararg value... for expansion of llvm.va_start. 2266 if (isVarArg) { 2267 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 2268 CallConv != CallingConv::X86_ThisCall)) { 2269 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 2270 } 2271 if (Is64Bit) { 2272 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 2273 2274 // FIXME: We should really autogenerate these arrays 2275 static const uint16_t GPR64ArgRegsWin64[] = { 2276 X86::RCX, X86::RDX, X86::R8, X86::R9 2277 }; 2278 static const uint16_t GPR64ArgRegs64Bit[] = { 2279 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 2280 }; 2281 static const uint16_t XMMArgRegs64Bit[] = { 2282 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2283 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2284 }; 2285 const uint16_t *GPR64ArgRegs; 2286 unsigned NumXMMRegs = 0; 2287 2288 if (IsWin64) { 2289 // The XMM registers which might contain var arg parameters are shadowed 2290 // in their paired GPR. So we only need to save the GPR to their home 2291 // slots. 2292 TotalNumIntRegs = 4; 2293 GPR64ArgRegs = GPR64ArgRegsWin64; 2294 } else { 2295 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 2296 GPR64ArgRegs = GPR64ArgRegs64Bit; 2297 2298 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, 2299 TotalNumXMMRegs); 2300 } 2301 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 2302 TotalNumIntRegs); 2303 2304 bool NoImplicitFloatOps = Fn->getAttributes(). 2305 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 2306 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) && 2307 "SSE register cannot be used when SSE is disabled!"); 2308 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat && 2309 NoImplicitFloatOps) && 2310 "SSE register cannot be used when SSE is disabled!"); 2311 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps || 2312 !Subtarget->hasSSE1()) 2313 // Kernel mode asks for SSE to be disabled, so don't push them 2314 // on the stack. 2315 TotalNumXMMRegs = 0; 2316 2317 if (IsWin64) { 2318 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 2319 // Get to the caller-allocated home save location. Add 8 to account 2320 // for the return address. 2321 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 2322 FuncInfo->setRegSaveFrameIndex( 2323 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 2324 // Fixup to set vararg frame on shadow area (4 x i64). 2325 if (NumIntRegs < 4) 2326 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 2327 } else { 2328 // For X86-64, if there are vararg parameters that are passed via 2329 // registers, then we must store them to their spots on the stack so 2330 // they may be loaded by deferencing the result of va_next. 2331 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 2332 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 2333 FuncInfo->setRegSaveFrameIndex( 2334 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 2335 false)); 2336 } 2337 2338 // Store the integer parameter registers. 2339 SmallVector<SDValue, 8> MemOps; 2340 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 2341 getPointerTy()); 2342 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 2343 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 2344 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 2345 DAG.getIntPtrConstant(Offset)); 2346 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 2347 &X86::GR64RegClass); 2348 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2349 SDValue Store = 2350 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2351 MachinePointerInfo::getFixedStack( 2352 FuncInfo->getRegSaveFrameIndex(), Offset), 2353 false, false, 0); 2354 MemOps.push_back(Store); 2355 Offset += 8; 2356 } 2357 2358 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 2359 // Now store the XMM (fp + vector) parameter registers. 2360 SmallVector<SDValue, 11> SaveXMMOps; 2361 SaveXMMOps.push_back(Chain); 2362 2363 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass); 2364 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 2365 SaveXMMOps.push_back(ALVal); 2366 2367 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2368 FuncInfo->getRegSaveFrameIndex())); 2369 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2370 FuncInfo->getVarArgsFPOffset())); 2371 2372 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 2373 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 2374 &X86::VR128RegClass); 2375 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 2376 SaveXMMOps.push_back(Val); 2377 } 2378 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 2379 MVT::Other, 2380 &SaveXMMOps[0], SaveXMMOps.size())); 2381 } 2382 2383 if (!MemOps.empty()) 2384 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2385 &MemOps[0], MemOps.size()); 2386 } 2387 } 2388 2389 // Some CCs need callee pop. 2390 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2391 MF.getTarget().Options.GuaranteedTailCallOpt)) { 2392 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2393 } else { 2394 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2395 // If this is an sret function, the return should pop the hidden pointer. 2396 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2397 argsAreStructReturn(Ins) == StackStructReturn) 2398 FuncInfo->setBytesToPopOnReturn(4); 2399 } 2400 2401 if (!Is64Bit) { 2402 // RegSaveFrameIndex is X86-64 only. 2403 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2404 if (CallConv == CallingConv::X86_FastCall || 2405 CallConv == CallingConv::X86_ThisCall) 2406 // fastcc functions can't have varargs. 2407 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2408 } 2409 2410 FuncInfo->setArgumentStackSize(StackSize); 2411 2412 return Chain; 2413 } 2414 2415 SDValue 2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2417 SDValue StackPtr, SDValue Arg, 2418 SDLoc dl, SelectionDAG &DAG, 2419 const CCValAssign &VA, 2420 ISD::ArgFlagsTy Flags) const { 2421 unsigned LocMemOffset = VA.getLocMemOffset(); 2422 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2423 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2424 if (Flags.isByVal()) 2425 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2426 2427 return DAG.getStore(Chain, dl, Arg, PtrOff, 2428 MachinePointerInfo::getStack(LocMemOffset), 2429 false, false, 0); 2430 } 2431 2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2433 /// optimization is performed and it is required. 2434 SDValue 2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2436 SDValue &OutRetAddr, SDValue Chain, 2437 bool IsTailCall, bool Is64Bit, 2438 int FPDiff, SDLoc dl) const { 2439 // Adjust the Return address stack slot. 2440 EVT VT = getPointerTy(); 2441 OutRetAddr = getReturnAddressFrameIndex(DAG); 2442 2443 // Load the "old" Return address. 2444 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2445 false, false, false, 0); 2446 return SDValue(OutRetAddr.getNode(), 1); 2447 } 2448 2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2450 /// optimization is performed and it is required (FPDiff!=0). 2451 static SDValue 2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2453 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT, 2454 unsigned SlotSize, int FPDiff, SDLoc dl) { 2455 // Store the return address to the appropriate stack slot. 2456 if (!FPDiff) return Chain; 2457 // Calculate the new stack slot for the return address. 2458 int NewReturnAddrFI = 2459 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize, 2460 false); 2461 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT); 2462 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2463 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2464 false, false, 0); 2465 return Chain; 2466 } 2467 2468 SDValue 2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2470 SmallVectorImpl<SDValue> &InVals) const { 2471 SelectionDAG &DAG = CLI.DAG; 2472 SDLoc &dl = CLI.DL; 2473 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 2474 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 2475 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 2476 SDValue Chain = CLI.Chain; 2477 SDValue Callee = CLI.Callee; 2478 CallingConv::ID CallConv = CLI.CallConv; 2479 bool &isTailCall = CLI.IsTailCall; 2480 bool isVarArg = CLI.IsVarArg; 2481 2482 MachineFunction &MF = DAG.getMachineFunction(); 2483 bool Is64Bit = Subtarget->is64Bit(); 2484 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv); 2485 bool IsWindows = Subtarget->isTargetWindows(); 2486 StructReturnType SR = callIsStructReturn(Outs); 2487 bool IsSibcall = false; 2488 2489 if (MF.getTarget().Options.DisableTailCalls) 2490 isTailCall = false; 2491 2492 if (isTailCall) { 2493 // Check if it's really possible to do a tail call. 2494 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2495 isVarArg, SR != NotStructReturn, 2496 MF.getFunction()->hasStructRetAttr(), CLI.RetTy, 2497 Outs, OutVals, Ins, DAG); 2498 2499 // Sibcalls are automatically detected tailcalls which do not require 2500 // ABI changes. 2501 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall) 2502 IsSibcall = true; 2503 2504 if (isTailCall) 2505 ++NumTailCalls; 2506 } 2507 2508 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2509 "Var args not supported with calling convention fastcc, ghc or hipe"); 2510 2511 // Analyze operands of the call, assigning locations to each operand. 2512 SmallVector<CCValAssign, 16> ArgLocs; 2513 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2514 ArgLocs, *DAG.getContext()); 2515 2516 // Allocate shadow area for Win64 2517 if (IsWin64) 2518 CCInfo.AllocateStack(32, 8); 2519 2520 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2521 2522 // Get a count of how many bytes are to be pushed on the stack. 2523 unsigned NumBytes = CCInfo.getNextStackOffset(); 2524 if (IsSibcall) 2525 // This is a sibcall. The memory operands are available in caller's 2526 // own caller's stack. 2527 NumBytes = 0; 2528 else if (getTargetMachine().Options.GuaranteedTailCallOpt && 2529 IsTailCallConvention(CallConv)) 2530 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2531 2532 int FPDiff = 0; 2533 if (isTailCall && !IsSibcall) { 2534 // Lower arguments at fp - stackoffset + fpdiff. 2535 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>(); 2536 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn(); 2537 2538 FPDiff = NumBytesCallerPushed - NumBytes; 2539 2540 // Set the delta of movement of the returnaddr stackslot. 2541 // But only set if delta is greater than previous delta. 2542 if (FPDiff < X86Info->getTCReturnAddrDelta()) 2543 X86Info->setTCReturnAddrDelta(FPDiff); 2544 } 2545 2546 if (!IsSibcall) 2547 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 2548 dl); 2549 2550 SDValue RetAddrFrIdx; 2551 // Load return address for tail calls. 2552 if (isTailCall && FPDiff) 2553 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2554 Is64Bit, FPDiff, dl); 2555 2556 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2557 SmallVector<SDValue, 8> MemOpChains; 2558 SDValue StackPtr; 2559 2560 // Walk the register/memloc assignments, inserting copies/loads. In the case 2561 // of tail call optimization arguments are handle later. 2562 const X86RegisterInfo *RegInfo = 2563 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 2564 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2565 CCValAssign &VA = ArgLocs[i]; 2566 EVT RegVT = VA.getLocVT(); 2567 SDValue Arg = OutVals[i]; 2568 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2569 bool isByVal = Flags.isByVal(); 2570 2571 // Promote the value if needed. 2572 switch (VA.getLocInfo()) { 2573 default: llvm_unreachable("Unknown loc info!"); 2574 case CCValAssign::Full: break; 2575 case CCValAssign::SExt: 2576 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2577 break; 2578 case CCValAssign::ZExt: 2579 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2580 break; 2581 case CCValAssign::AExt: 2582 if (RegVT.is128BitVector()) { 2583 // Special case: passing MMX values in XMM registers. 2584 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2585 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2586 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2587 } else 2588 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2589 break; 2590 case CCValAssign::BCvt: 2591 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2592 break; 2593 case CCValAssign::Indirect: { 2594 // Store the argument. 2595 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2596 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2597 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2598 MachinePointerInfo::getFixedStack(FI), 2599 false, false, 0); 2600 Arg = SpillSlot; 2601 break; 2602 } 2603 } 2604 2605 if (VA.isRegLoc()) { 2606 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2607 if (isVarArg && IsWin64) { 2608 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2609 // shadow reg if callee is a varargs function. 2610 unsigned ShadowReg = 0; 2611 switch (VA.getLocReg()) { 2612 case X86::XMM0: ShadowReg = X86::RCX; break; 2613 case X86::XMM1: ShadowReg = X86::RDX; break; 2614 case X86::XMM2: ShadowReg = X86::R8; break; 2615 case X86::XMM3: ShadowReg = X86::R9; break; 2616 } 2617 if (ShadowReg) 2618 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2619 } 2620 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2621 assert(VA.isMemLoc()); 2622 if (StackPtr.getNode() == 0) 2623 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 2624 getPointerTy()); 2625 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2626 dl, DAG, VA, Flags)); 2627 } 2628 } 2629 2630 if (!MemOpChains.empty()) 2631 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2632 &MemOpChains[0], MemOpChains.size()); 2633 2634 if (Subtarget->isPICStyleGOT()) { 2635 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2636 // GOT pointer. 2637 if (!isTailCall) { 2638 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX), 2639 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy()))); 2640 } else { 2641 // If we are tail calling and generating PIC/GOT style code load the 2642 // address of the callee into ECX. The value in ecx is used as target of 2643 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2644 // for tail calls on PIC/GOT architectures. Normally we would just put the 2645 // address of GOT into ebx and then call target@PLT. But for tail calls 2646 // ebx would be restored (since ebx is callee saved) before jumping to the 2647 // target@PLT. 2648 2649 // Note: The actual moving to ECX is done further down. 2650 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2651 if (G && !G->getGlobal()->hasHiddenVisibility() && 2652 !G->getGlobal()->hasProtectedVisibility()) 2653 Callee = LowerGlobalAddress(Callee, DAG); 2654 else if (isa<ExternalSymbolSDNode>(Callee)) 2655 Callee = LowerExternalSymbol(Callee, DAG); 2656 } 2657 } 2658 2659 if (Is64Bit && isVarArg && !IsWin64) { 2660 // From AMD64 ABI document: 2661 // For calls that may call functions that use varargs or stdargs 2662 // (prototype-less calls or calls to functions containing ellipsis (...) in 2663 // the declaration) %al is used as hidden argument to specify the number 2664 // of SSE registers used. The contents of %al do not need to match exactly 2665 // the number of registers, but must be an ubound on the number of SSE 2666 // registers used and is in the range 0 - 8 inclusive. 2667 2668 // Count the number of XMM registers allocated. 2669 static const uint16_t XMMArgRegs[] = { 2670 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2671 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2672 }; 2673 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2674 assert((Subtarget->hasSSE1() || !NumXMMRegs) 2675 && "SSE registers cannot be used when SSE is disabled"); 2676 2677 RegsToPass.push_back(std::make_pair(unsigned(X86::AL), 2678 DAG.getConstant(NumXMMRegs, MVT::i8))); 2679 } 2680 2681 // For tail calls lower the arguments to the 'real' stack slot. 2682 if (isTailCall) { 2683 // Force all the incoming stack arguments to be loaded from the stack 2684 // before any new outgoing arguments are stored to the stack, because the 2685 // outgoing stack slots may alias the incoming argument stack slots, and 2686 // the alias isn't otherwise explicit. This is slightly more conservative 2687 // than necessary, because it means that each store effectively depends 2688 // on every argument instead of just those arguments it would clobber. 2689 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2690 2691 SmallVector<SDValue, 8> MemOpChains2; 2692 SDValue FIN; 2693 int FI = 0; 2694 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2696 CCValAssign &VA = ArgLocs[i]; 2697 if (VA.isRegLoc()) 2698 continue; 2699 assert(VA.isMemLoc()); 2700 SDValue Arg = OutVals[i]; 2701 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2702 // Create frame index. 2703 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2704 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2705 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2706 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2707 2708 if (Flags.isByVal()) { 2709 // Copy relative to framepointer. 2710 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2711 if (StackPtr.getNode() == 0) 2712 StackPtr = DAG.getCopyFromReg(Chain, dl, 2713 RegInfo->getStackRegister(), 2714 getPointerTy()); 2715 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2716 2717 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2718 ArgChain, 2719 Flags, DAG, dl)); 2720 } else { 2721 // Store relative to framepointer. 2722 MemOpChains2.push_back( 2723 DAG.getStore(ArgChain, dl, Arg, FIN, 2724 MachinePointerInfo::getFixedStack(FI), 2725 false, false, 0)); 2726 } 2727 } 2728 } 2729 2730 if (!MemOpChains2.empty()) 2731 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2732 &MemOpChains2[0], MemOpChains2.size()); 2733 2734 // Store the return address to the appropriate stack slot. 2735 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, 2736 getPointerTy(), RegInfo->getSlotSize(), 2737 FPDiff, dl); 2738 } 2739 2740 // Build a sequence of copy-to-reg nodes chained together with token chain 2741 // and flag operands which copy the outgoing args into registers. 2742 SDValue InFlag; 2743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2744 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2745 RegsToPass[i].second, InFlag); 2746 InFlag = Chain.getValue(1); 2747 } 2748 2749 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2750 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2751 // In the 64-bit large code model, we have to make all calls 2752 // through a register, since the call instruction's 32-bit 2753 // pc-relative offset may not be large enough to hold the whole 2754 // address. 2755 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2756 // If the callee is a GlobalAddress node (quite common, every direct call 2757 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2758 // it. 2759 2760 // We should use extra load for direct calls to dllimported functions in 2761 // non-JIT mode. 2762 const GlobalValue *GV = G->getGlobal(); 2763 if (!GV->hasDLLImportLinkage()) { 2764 unsigned char OpFlags = 0; 2765 bool ExtraLoad = false; 2766 unsigned WrapperKind = ISD::DELETED_NODE; 2767 2768 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2769 // external symbols most go through the PLT in PIC mode. If the symbol 2770 // has hidden or protected visibility, or if it is static or local, then 2771 // we don't need to use the PLT - we can directly call it. 2772 if (Subtarget->isTargetELF() && 2773 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2774 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2775 OpFlags = X86II::MO_PLT; 2776 } else if (Subtarget->isPICStyleStubAny() && 2777 (GV->isDeclaration() || GV->isWeakForLinker()) && 2778 (!Subtarget->getTargetTriple().isMacOSX() || 2779 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2780 // PC-relative references to external symbols should go through $stub, 2781 // unless we're building with the leopard linker or later, which 2782 // automatically synthesizes these stubs. 2783 OpFlags = X86II::MO_DARWIN_STUB; 2784 } else if (Subtarget->isPICStyleRIPRel() && 2785 isa<Function>(GV) && 2786 cast<Function>(GV)->getAttributes(). 2787 hasAttribute(AttributeSet::FunctionIndex, 2788 Attribute::NonLazyBind)) { 2789 // If the function is marked as non-lazy, generate an indirect call 2790 // which loads from the GOT directly. This avoids runtime overhead 2791 // at the cost of eager binding (and one extra byte of encoding). 2792 OpFlags = X86II::MO_GOTPCREL; 2793 WrapperKind = X86ISD::WrapperRIP; 2794 ExtraLoad = true; 2795 } 2796 2797 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2798 G->getOffset(), OpFlags); 2799 2800 // Add a wrapper if needed. 2801 if (WrapperKind != ISD::DELETED_NODE) 2802 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2803 // Add extra indirection if needed. 2804 if (ExtraLoad) 2805 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2806 MachinePointerInfo::getGOT(), 2807 false, false, false, 0); 2808 } 2809 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2810 unsigned char OpFlags = 0; 2811 2812 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2813 // external symbols should go through the PLT. 2814 if (Subtarget->isTargetELF() && 2815 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2816 OpFlags = X86II::MO_PLT; 2817 } else if (Subtarget->isPICStyleStubAny() && 2818 (!Subtarget->getTargetTriple().isMacOSX() || 2819 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2820 // PC-relative references to external symbols should go through $stub, 2821 // unless we're building with the leopard linker or later, which 2822 // automatically synthesizes these stubs. 2823 OpFlags = X86II::MO_DARWIN_STUB; 2824 } 2825 2826 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2827 OpFlags); 2828 } 2829 2830 // Returns a chain & a flag for retval copy to use. 2831 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2832 SmallVector<SDValue, 8> Ops; 2833 2834 if (!IsSibcall && isTailCall) { 2835 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2836 DAG.getIntPtrConstant(0, true), InFlag, dl); 2837 InFlag = Chain.getValue(1); 2838 } 2839 2840 Ops.push_back(Chain); 2841 Ops.push_back(Callee); 2842 2843 if (isTailCall) 2844 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2845 2846 // Add argument registers to the end of the list so that they are known live 2847 // into the call. 2848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2849 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2850 RegsToPass[i].second.getValueType())); 2851 2852 // Add a register mask operand representing the call-preserved registers. 2853 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 2854 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 2855 assert(Mask && "Missing call preserved mask for calling convention"); 2856 Ops.push_back(DAG.getRegisterMask(Mask)); 2857 2858 if (InFlag.getNode()) 2859 Ops.push_back(InFlag); 2860 2861 if (isTailCall) { 2862 // We used to do: 2863 //// If this is the first return lowered for this function, add the regs 2864 //// to the liveout set for the function. 2865 // This isn't right, although it's probably harmless on x86; liveouts 2866 // should be computed from returns not tail calls. Consider a void 2867 // function making a tail call to a function returning int. 2868 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size()); 2869 } 2870 2871 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2872 InFlag = Chain.getValue(1); 2873 2874 // Create the CALLSEQ_END node. 2875 unsigned NumBytesForCalleeToPush; 2876 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2877 getTargetMachine().Options.GuaranteedTailCallOpt)) 2878 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2879 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2880 SR == StackStructReturn) 2881 // If this is a call to a struct-return function, the callee 2882 // pops the hidden struct pointer, so we have to push it back. 2883 // This is common for Darwin/X86, Linux & Mingw32 targets. 2884 // For MSVC Win32 targets, the caller pops the hidden struct pointer. 2885 NumBytesForCalleeToPush = 4; 2886 else 2887 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2888 2889 // Returns a flag for retval copy to use. 2890 if (!IsSibcall) { 2891 Chain = DAG.getCALLSEQ_END(Chain, 2892 DAG.getIntPtrConstant(NumBytes, true), 2893 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2894 true), 2895 InFlag, dl); 2896 InFlag = Chain.getValue(1); 2897 } 2898 2899 // Handle result values, copying them out of physregs into vregs that we 2900 // return. 2901 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2902 Ins, dl, DAG, InVals); 2903 } 2904 2905 //===----------------------------------------------------------------------===// 2906 // Fast Calling Convention (tail call) implementation 2907 //===----------------------------------------------------------------------===// 2908 2909 // Like std call, callee cleans arguments, convention except that ECX is 2910 // reserved for storing the tail called function address. Only 2 registers are 2911 // free for argument passing (inreg). Tail call optimization is performed 2912 // provided: 2913 // * tailcallopt is enabled 2914 // * caller/callee are fastcc 2915 // On X86_64 architecture with GOT-style position independent code only local 2916 // (within module) calls are supported at the moment. 2917 // To keep the stack aligned according to platform abi the function 2918 // GetAlignedArgumentStackSize ensures that argument delta is always multiples 2919 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2920 // If a tail called function callee has more arguments than the caller the 2921 // caller needs to make sure that there is room to move the RETADDR to. This is 2922 // achieved by reserving an area the size of the argument delta right after the 2923 // original REtADDR, but before the saved framepointer or the spilled registers 2924 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2925 // stack layout: 2926 // arg1 2927 // arg2 2928 // RETADDR 2929 // [ new RETADDR 2930 // move area ] 2931 // (possible EBP) 2932 // ESI 2933 // EDI 2934 // local1 .. 2935 2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2937 /// for a 16 byte align requirement. 2938 unsigned 2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2940 SelectionDAG& DAG) const { 2941 MachineFunction &MF = DAG.getMachineFunction(); 2942 const TargetMachine &TM = MF.getTarget(); 2943 const X86RegisterInfo *RegInfo = 2944 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo()); 2945 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2946 unsigned StackAlignment = TFI.getStackAlignment(); 2947 uint64_t AlignMask = StackAlignment - 1; 2948 int64_t Offset = StackSize; 2949 unsigned SlotSize = RegInfo->getSlotSize(); 2950 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2951 // Number smaller than 12 so just add the difference. 2952 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2953 } else { 2954 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2955 Offset = ((~AlignMask) & Offset) + StackAlignment + 2956 (StackAlignment-SlotSize); 2957 } 2958 return Offset; 2959 } 2960 2961 /// MatchingStackOffset - Return true if the given stack call argument is 2962 /// already available in the same position (relatively) of the caller's 2963 /// incoming argument stack. 2964 static 2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2966 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2967 const X86InstrInfo *TII) { 2968 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2969 int FI = INT_MAX; 2970 if (Arg.getOpcode() == ISD::CopyFromReg) { 2971 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2972 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2973 return false; 2974 MachineInstr *Def = MRI->getVRegDef(VR); 2975 if (!Def) 2976 return false; 2977 if (!Flags.isByVal()) { 2978 if (!TII->isLoadFromStackSlot(Def, FI)) 2979 return false; 2980 } else { 2981 unsigned Opcode = Def->getOpcode(); 2982 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2983 Def->getOperand(1).isFI()) { 2984 FI = Def->getOperand(1).getIndex(); 2985 Bytes = Flags.getByValSize(); 2986 } else 2987 return false; 2988 } 2989 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2990 if (Flags.isByVal()) 2991 // ByVal argument is passed in as a pointer but it's now being 2992 // dereferenced. e.g. 2993 // define @foo(%struct.X* %A) { 2994 // tail call @bar(%struct.X* byval %A) 2995 // } 2996 return false; 2997 SDValue Ptr = Ld->getBasePtr(); 2998 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2999 if (!FINode) 3000 return false; 3001 FI = FINode->getIndex(); 3002 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 3003 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 3004 FI = FINode->getIndex(); 3005 Bytes = Flags.getByValSize(); 3006 } else 3007 return false; 3008 3009 assert(FI != INT_MAX); 3010 if (!MFI->isFixedObjectIndex(FI)) 3011 return false; 3012 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 3013 } 3014 3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 3016 /// for tail call optimization. Targets which want to do tail call 3017 /// optimization should implement this function. 3018 bool 3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 3020 CallingConv::ID CalleeCC, 3021 bool isVarArg, 3022 bool isCalleeStructRet, 3023 bool isCallerStructRet, 3024 Type *RetTy, 3025 const SmallVectorImpl<ISD::OutputArg> &Outs, 3026 const SmallVectorImpl<SDValue> &OutVals, 3027 const SmallVectorImpl<ISD::InputArg> &Ins, 3028 SelectionDAG &DAG) const { 3029 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC)) 3030 return false; 3031 3032 // If -tailcallopt is specified, make fastcc functions tail-callable. 3033 const MachineFunction &MF = DAG.getMachineFunction(); 3034 const Function *CallerF = MF.getFunction(); 3035 3036 // If the function return type is x86_fp80 and the callee return type is not, 3037 // then the FP_EXTEND of the call result is not a nop. It's not safe to 3038 // perform a tailcall optimization here. 3039 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty()) 3040 return false; 3041 3042 CallingConv::ID CallerCC = CallerF->getCallingConv(); 3043 bool CCMatch = CallerCC == CalleeCC; 3044 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC); 3045 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC); 3046 3047 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 3048 if (IsTailCallConvention(CalleeCC) && CCMatch) 3049 return true; 3050 return false; 3051 } 3052 3053 // Look for obvious safe cases to perform tail call optimization that do not 3054 // require ABI changes. This is what gcc calls sibcall. 3055 3056 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 3057 // emit a special epilogue. 3058 const X86RegisterInfo *RegInfo = 3059 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 3060 if (RegInfo->needsStackRealignment(MF)) 3061 return false; 3062 3063 // Also avoid sibcall optimization if either caller or callee uses struct 3064 // return semantics. 3065 if (isCalleeStructRet || isCallerStructRet) 3066 return false; 3067 3068 // An stdcall caller is expected to clean up its arguments; the callee 3069 // isn't going to do that. 3070 if (!CCMatch && CallerCC == CallingConv::X86_StdCall) 3071 return false; 3072 3073 // Do not sibcall optimize vararg calls unless all arguments are passed via 3074 // registers. 3075 if (isVarArg && !Outs.empty()) { 3076 3077 // Optimizing for varargs on Win64 is unlikely to be safe without 3078 // additional testing. 3079 if (IsCalleeWin64 || IsCallerWin64) 3080 return false; 3081 3082 SmallVector<CCValAssign, 16> ArgLocs; 3083 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 3084 getTargetMachine(), ArgLocs, *DAG.getContext()); 3085 3086 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 3087 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 3088 if (!ArgLocs[i].isRegLoc()) 3089 return false; 3090 } 3091 3092 // If the call result is in ST0 / ST1, it needs to be popped off the x87 3093 // stack. Therefore, if it's not used by the call it is not safe to optimize 3094 // this into a sibcall. 3095 bool Unused = false; 3096 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3097 if (!Ins[i].Used) { 3098 Unused = true; 3099 break; 3100 } 3101 } 3102 if (Unused) { 3103 SmallVector<CCValAssign, 16> RVLocs; 3104 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 3105 getTargetMachine(), RVLocs, *DAG.getContext()); 3106 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 3107 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 3108 CCValAssign &VA = RVLocs[i]; 3109 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 3110 return false; 3111 } 3112 } 3113 3114 // If the calling conventions do not match, then we'd better make sure the 3115 // results are returned in the same way as what the caller expects. 3116 if (!CCMatch) { 3117 SmallVector<CCValAssign, 16> RVLocs1; 3118 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 3119 getTargetMachine(), RVLocs1, *DAG.getContext()); 3120 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 3121 3122 SmallVector<CCValAssign, 16> RVLocs2; 3123 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 3124 getTargetMachine(), RVLocs2, *DAG.getContext()); 3125 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 3126 3127 if (RVLocs1.size() != RVLocs2.size()) 3128 return false; 3129 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 3130 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 3131 return false; 3132 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 3133 return false; 3134 if (RVLocs1[i].isRegLoc()) { 3135 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 3136 return false; 3137 } else { 3138 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 3139 return false; 3140 } 3141 } 3142 } 3143 3144 // If the callee takes no arguments then go on to check the results of the 3145 // call. 3146 if (!Outs.empty()) { 3147 // Check if stack adjustment is needed. For now, do not do this if any 3148 // argument is passed on the stack. 3149 SmallVector<CCValAssign, 16> ArgLocs; 3150 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 3151 getTargetMachine(), ArgLocs, *DAG.getContext()); 3152 3153 // Allocate shadow area for Win64 3154 if (IsCalleeWin64) 3155 CCInfo.AllocateStack(32, 8); 3156 3157 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 3158 if (CCInfo.getNextStackOffset()) { 3159 MachineFunction &MF = DAG.getMachineFunction(); 3160 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 3161 return false; 3162 3163 // Check if the arguments are already laid out in the right way as 3164 // the caller's fixed stack objects. 3165 MachineFrameInfo *MFI = MF.getFrameInfo(); 3166 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 3167 const X86InstrInfo *TII = 3168 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo(); 3169 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3170 CCValAssign &VA = ArgLocs[i]; 3171 SDValue Arg = OutVals[i]; 3172 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3173 if (VA.getLocInfo() == CCValAssign::Indirect) 3174 return false; 3175 if (!VA.isRegLoc()) { 3176 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 3177 MFI, MRI, TII)) 3178 return false; 3179 } 3180 } 3181 } 3182 3183 // If the tailcall address may be in a register, then make sure it's 3184 // possible to register allocate for it. In 32-bit, the call address can 3185 // only target EAX, EDX, or ECX since the tail call must be scheduled after 3186 // callee-saved registers are restored. These happen to be the same 3187 // registers used to pass 'inreg' arguments so watch out for those. 3188 if (!Subtarget->is64Bit() && 3189 ((!isa<GlobalAddressSDNode>(Callee) && 3190 !isa<ExternalSymbolSDNode>(Callee)) || 3191 getTargetMachine().getRelocationModel() == Reloc::PIC_)) { 3192 unsigned NumInRegs = 0; 3193 // In PIC we need an extra register to formulate the address computation 3194 // for the callee. 3195 unsigned MaxInRegs = 3196 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3; 3197 3198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3199 CCValAssign &VA = ArgLocs[i]; 3200 if (!VA.isRegLoc()) 3201 continue; 3202 unsigned Reg = VA.getLocReg(); 3203 switch (Reg) { 3204 default: break; 3205 case X86::EAX: case X86::EDX: case X86::ECX: 3206 if (++NumInRegs == MaxInRegs) 3207 return false; 3208 break; 3209 } 3210 } 3211 } 3212 } 3213 3214 return true; 3215 } 3216 3217 FastISel * 3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 3219 const TargetLibraryInfo *libInfo) const { 3220 return X86::createFastISel(funcInfo, libInfo); 3221 } 3222 3223 //===----------------------------------------------------------------------===// 3224 // Other Lowering Hooks 3225 //===----------------------------------------------------------------------===// 3226 3227 static bool MayFoldLoad(SDValue Op) { 3228 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 3229 } 3230 3231 static bool MayFoldIntoStore(SDValue Op) { 3232 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 3233 } 3234 3235 static bool isTargetShuffle(unsigned Opcode) { 3236 switch(Opcode) { 3237 default: return false; 3238 case X86ISD::PSHUFD: 3239 case X86ISD::PSHUFHW: 3240 case X86ISD::PSHUFLW: 3241 case X86ISD::SHUFP: 3242 case X86ISD::PALIGNR: 3243 case X86ISD::MOVLHPS: 3244 case X86ISD::MOVLHPD: 3245 case X86ISD::MOVHLPS: 3246 case X86ISD::MOVLPS: 3247 case X86ISD::MOVLPD: 3248 case X86ISD::MOVSHDUP: 3249 case X86ISD::MOVSLDUP: 3250 case X86ISD::MOVDDUP: 3251 case X86ISD::MOVSS: 3252 case X86ISD::MOVSD: 3253 case X86ISD::UNPCKL: 3254 case X86ISD::UNPCKH: 3255 case X86ISD::VPERMILP: 3256 case X86ISD::VPERM2X128: 3257 case X86ISD::VPERMI: 3258 return true; 3259 } 3260 } 3261 3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3263 SDValue V1, SelectionDAG &DAG) { 3264 switch(Opc) { 3265 default: llvm_unreachable("Unknown x86 shuffle node"); 3266 case X86ISD::MOVSHDUP: 3267 case X86ISD::MOVSLDUP: 3268 case X86ISD::MOVDDUP: 3269 return DAG.getNode(Opc, dl, VT, V1); 3270 } 3271 } 3272 3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3274 SDValue V1, unsigned TargetMask, 3275 SelectionDAG &DAG) { 3276 switch(Opc) { 3277 default: llvm_unreachable("Unknown x86 shuffle node"); 3278 case X86ISD::PSHUFD: 3279 case X86ISD::PSHUFHW: 3280 case X86ISD::PSHUFLW: 3281 case X86ISD::VPERMILP: 3282 case X86ISD::VPERMI: 3283 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 3284 } 3285 } 3286 3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3288 SDValue V1, SDValue V2, unsigned TargetMask, 3289 SelectionDAG &DAG) { 3290 switch(Opc) { 3291 default: llvm_unreachable("Unknown x86 shuffle node"); 3292 case X86ISD::PALIGNR: 3293 case X86ISD::SHUFP: 3294 case X86ISD::VPERM2X128: 3295 return DAG.getNode(Opc, dl, VT, V1, V2, 3296 DAG.getConstant(TargetMask, MVT::i8)); 3297 } 3298 } 3299 3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3301 SDValue V1, SDValue V2, SelectionDAG &DAG) { 3302 switch(Opc) { 3303 default: llvm_unreachable("Unknown x86 shuffle node"); 3304 case X86ISD::MOVLHPS: 3305 case X86ISD::MOVLHPD: 3306 case X86ISD::MOVHLPS: 3307 case X86ISD::MOVLPS: 3308 case X86ISD::MOVLPD: 3309 case X86ISD::MOVSS: 3310 case X86ISD::MOVSD: 3311 case X86ISD::UNPCKL: 3312 case X86ISD::UNPCKH: 3313 return DAG.getNode(Opc, dl, VT, V1, V2); 3314 } 3315 } 3316 3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 3318 MachineFunction &MF = DAG.getMachineFunction(); 3319 const X86RegisterInfo *RegInfo = 3320 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 3321 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 3322 int ReturnAddrIndex = FuncInfo->getRAIndex(); 3323 3324 if (ReturnAddrIndex == 0) { 3325 // Set up a frame object for the return address. 3326 unsigned SlotSize = RegInfo->getSlotSize(); 3327 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, 3328 -(int64_t)SlotSize, 3329 false); 3330 FuncInfo->setRAIndex(ReturnAddrIndex); 3331 } 3332 3333 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 3334 } 3335 3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 3337 bool hasSymbolicDisplacement) { 3338 // Offset should fit into 32 bit immediate field. 3339 if (!isInt<32>(Offset)) 3340 return false; 3341 3342 // If we don't have a symbolic displacement - we don't have any extra 3343 // restrictions. 3344 if (!hasSymbolicDisplacement) 3345 return true; 3346 3347 // FIXME: Some tweaks might be needed for medium code model. 3348 if (M != CodeModel::Small && M != CodeModel::Kernel) 3349 return false; 3350 3351 // For small code model we assume that latest object is 16MB before end of 31 3352 // bits boundary. We may also accept pretty large negative constants knowing 3353 // that all objects are in the positive half of address space. 3354 if (M == CodeModel::Small && Offset < 16*1024*1024) 3355 return true; 3356 3357 // For kernel code model we know that all object resist in the negative half 3358 // of 32bits address space. We may not accept negative offsets, since they may 3359 // be just off and we may accept pretty large positive ones. 3360 if (M == CodeModel::Kernel && Offset > 0) 3361 return true; 3362 3363 return false; 3364 } 3365 3366 /// isCalleePop - Determines whether the callee is required to pop its 3367 /// own arguments. Callee pop is necessary to support tail calls. 3368 bool X86::isCalleePop(CallingConv::ID CallingConv, 3369 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 3370 if (IsVarArg) 3371 return false; 3372 3373 switch (CallingConv) { 3374 default: 3375 return false; 3376 case CallingConv::X86_StdCall: 3377 return !is64Bit; 3378 case CallingConv::X86_FastCall: 3379 return !is64Bit; 3380 case CallingConv::X86_ThisCall: 3381 return !is64Bit; 3382 case CallingConv::Fast: 3383 return TailCallOpt; 3384 case CallingConv::GHC: 3385 return TailCallOpt; 3386 case CallingConv::HiPE: 3387 return TailCallOpt; 3388 } 3389 } 3390 3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 3392 /// specific condition code, returning the condition code and the LHS/RHS of the 3393 /// comparison to make. 3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 3395 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 3396 if (!isFP) { 3397 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3398 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 3399 // X > -1 -> X == 0, jump !sign. 3400 RHS = DAG.getConstant(0, RHS.getValueType()); 3401 return X86::COND_NS; 3402 } 3403 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3404 // X < 0 -> X == 0, jump on sign. 3405 return X86::COND_S; 3406 } 3407 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3408 // X < 1 -> X <= 0 3409 RHS = DAG.getConstant(0, RHS.getValueType()); 3410 return X86::COND_LE; 3411 } 3412 } 3413 3414 switch (SetCCOpcode) { 3415 default: llvm_unreachable("Invalid integer condition!"); 3416 case ISD::SETEQ: return X86::COND_E; 3417 case ISD::SETGT: return X86::COND_G; 3418 case ISD::SETGE: return X86::COND_GE; 3419 case ISD::SETLT: return X86::COND_L; 3420 case ISD::SETLE: return X86::COND_LE; 3421 case ISD::SETNE: return X86::COND_NE; 3422 case ISD::SETULT: return X86::COND_B; 3423 case ISD::SETUGT: return X86::COND_A; 3424 case ISD::SETULE: return X86::COND_BE; 3425 case ISD::SETUGE: return X86::COND_AE; 3426 } 3427 } 3428 3429 // First determine if it is required or is profitable to flip the operands. 3430 3431 // If LHS is a foldable load, but RHS is not, flip the condition. 3432 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3433 !ISD::isNON_EXTLoad(RHS.getNode())) { 3434 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3435 std::swap(LHS, RHS); 3436 } 3437 3438 switch (SetCCOpcode) { 3439 default: break; 3440 case ISD::SETOLT: 3441 case ISD::SETOLE: 3442 case ISD::SETUGT: 3443 case ISD::SETUGE: 3444 std::swap(LHS, RHS); 3445 break; 3446 } 3447 3448 // On a floating point condition, the flags are set as follows: 3449 // ZF PF CF op 3450 // 0 | 0 | 0 | X > Y 3451 // 0 | 0 | 1 | X < Y 3452 // 1 | 0 | 0 | X == Y 3453 // 1 | 1 | 1 | unordered 3454 switch (SetCCOpcode) { 3455 default: llvm_unreachable("Condcode should be pre-legalized away"); 3456 case ISD::SETUEQ: 3457 case ISD::SETEQ: return X86::COND_E; 3458 case ISD::SETOLT: // flipped 3459 case ISD::SETOGT: 3460 case ISD::SETGT: return X86::COND_A; 3461 case ISD::SETOLE: // flipped 3462 case ISD::SETOGE: 3463 case ISD::SETGE: return X86::COND_AE; 3464 case ISD::SETUGT: // flipped 3465 case ISD::SETULT: 3466 case ISD::SETLT: return X86::COND_B; 3467 case ISD::SETUGE: // flipped 3468 case ISD::SETULE: 3469 case ISD::SETLE: return X86::COND_BE; 3470 case ISD::SETONE: 3471 case ISD::SETNE: return X86::COND_NE; 3472 case ISD::SETUO: return X86::COND_P; 3473 case ISD::SETO: return X86::COND_NP; 3474 case ISD::SETOEQ: 3475 case ISD::SETUNE: return X86::COND_INVALID; 3476 } 3477 } 3478 3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition 3480 /// code. Current x86 isa includes the following FP cmov instructions: 3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3482 static bool hasFPCMov(unsigned X86CC) { 3483 switch (X86CC) { 3484 default: 3485 return false; 3486 case X86::COND_B: 3487 case X86::COND_BE: 3488 case X86::COND_E: 3489 case X86::COND_P: 3490 case X86::COND_A: 3491 case X86::COND_AE: 3492 case X86::COND_NE: 3493 case X86::COND_NP: 3494 return true; 3495 } 3496 } 3497 3498 /// isFPImmLegal - Returns true if the target can instruction select the 3499 /// specified FP immediate natively. If false, the legalizer will 3500 /// materialize the FP immediate as a load from a constant pool. 3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3502 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3503 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3504 return true; 3505 } 3506 return false; 3507 } 3508 3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within 3510 /// the specified range (L, H]. 3511 static bool isUndefOrInRange(int Val, int Low, int Hi) { 3512 return (Val < 0) || (Val >= Low && Val < Hi); 3513 } 3514 3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3516 /// specified value. 3517 static bool isUndefOrEqual(int Val, int CmpVal) { 3518 return (Val < 0 || Val == CmpVal); 3519 } 3520 3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning 3522 /// from position Pos and ending in Pos+Size, falls within the specified 3523 /// sequential range (L, L+Pos]. or is undef. 3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, 3525 unsigned Pos, unsigned Size, int Low) { 3526 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3527 if (!isUndefOrEqual(Mask[i], Low)) 3528 return false; 3529 return true; 3530 } 3531 3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3533 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3534 /// the second operand. 3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) { 3536 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3537 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3538 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3539 return (Mask[0] < 2 && Mask[1] < 2); 3540 return false; 3541 } 3542 3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3544 /// is suitable for input to PSHUFHW. 3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3546 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3547 return false; 3548 3549 // Lower quadword copied in order or undef. 3550 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0)) 3551 return false; 3552 3553 // Upper quadword shuffled. 3554 for (unsigned i = 4; i != 8; ++i) 3555 if (!isUndefOrInRange(Mask[i], 4, 8)) 3556 return false; 3557 3558 if (VT == MVT::v16i16) { 3559 // Lower quadword copied in order or undef. 3560 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8)) 3561 return false; 3562 3563 // Upper quadword shuffled. 3564 for (unsigned i = 12; i != 16; ++i) 3565 if (!isUndefOrInRange(Mask[i], 12, 16)) 3566 return false; 3567 } 3568 3569 return true; 3570 } 3571 3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3573 /// is suitable for input to PSHUFLW. 3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3575 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3576 return false; 3577 3578 // Upper quadword copied in order. 3579 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4)) 3580 return false; 3581 3582 // Lower quadword shuffled. 3583 for (unsigned i = 0; i != 4; ++i) 3584 if (!isUndefOrInRange(Mask[i], 0, 4)) 3585 return false; 3586 3587 if (VT == MVT::v16i16) { 3588 // Upper quadword copied in order. 3589 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12)) 3590 return false; 3591 3592 // Lower quadword shuffled. 3593 for (unsigned i = 8; i != 12; ++i) 3594 if (!isUndefOrInRange(Mask[i], 8, 12)) 3595 return false; 3596 } 3597 3598 return true; 3599 } 3600 3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3602 /// is suitable for input to PALIGNR. 3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT, 3604 const X86Subtarget *Subtarget) { 3605 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) || 3606 (VT.is256BitVector() && !Subtarget->hasInt256())) 3607 return false; 3608 3609 unsigned NumElts = VT.getVectorNumElements(); 3610 unsigned NumLanes = VT.getSizeInBits()/128; 3611 unsigned NumLaneElts = NumElts/NumLanes; 3612 3613 // Do not handle 64-bit element shuffles with palignr. 3614 if (NumLaneElts == 2) 3615 return false; 3616 3617 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) { 3618 unsigned i; 3619 for (i = 0; i != NumLaneElts; ++i) { 3620 if (Mask[i+l] >= 0) 3621 break; 3622 } 3623 3624 // Lane is all undef, go to next lane 3625 if (i == NumLaneElts) 3626 continue; 3627 3628 int Start = Mask[i+l]; 3629 3630 // Make sure its in this lane in one of the sources 3631 if (!isUndefOrInRange(Start, l, l+NumLaneElts) && 3632 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts)) 3633 return false; 3634 3635 // If not lane 0, then we must match lane 0 3636 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l)) 3637 return false; 3638 3639 // Correct second source to be contiguous with first source 3640 if (Start >= (int)NumElts) 3641 Start -= NumElts - NumLaneElts; 3642 3643 // Make sure we're shifting in the right direction. 3644 if (Start <= (int)(i+l)) 3645 return false; 3646 3647 Start -= i; 3648 3649 // Check the rest of the elements to see if they are consecutive. 3650 for (++i; i != NumLaneElts; ++i) { 3651 int Idx = Mask[i+l]; 3652 3653 // Make sure its in this lane 3654 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) && 3655 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts)) 3656 return false; 3657 3658 // If not lane 0, then we must match lane 0 3659 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l)) 3660 return false; 3661 3662 if (Idx >= (int)NumElts) 3663 Idx -= NumElts - NumLaneElts; 3664 3665 if (!isUndefOrEqual(Idx, Start+i)) 3666 return false; 3667 3668 } 3669 } 3670 3671 return true; 3672 } 3673 3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3675 /// the two vector operands have swapped position. 3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, 3677 unsigned NumElems) { 3678 for (unsigned i = 0; i != NumElems; ++i) { 3679 int idx = Mask[i]; 3680 if (idx < 0) 3681 continue; 3682 else if (idx < (int)NumElems) 3683 Mask[i] = idx + NumElems; 3684 else 3685 Mask[i] = idx - NumElems; 3686 } 3687 } 3688 3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit 3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be 3692 /// reverse of what x86 shuffles want. 3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256, 3694 bool Commuted = false) { 3695 if (!HasFp256 && VT.is256BitVector()) 3696 return false; 3697 3698 unsigned NumElems = VT.getVectorNumElements(); 3699 unsigned NumLanes = VT.getSizeInBits()/128; 3700 unsigned NumLaneElems = NumElems/NumLanes; 3701 3702 if (NumLaneElems != 2 && NumLaneElems != 4) 3703 return false; 3704 3705 // VSHUFPSY divides the resulting vector into 4 chunks. 3706 // The sources are also splitted into 4 chunks, and each destination 3707 // chunk must come from a different source chunk. 3708 // 3709 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3710 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3711 // 3712 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3713 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3714 // 3715 // VSHUFPDY divides the resulting vector into 4 chunks. 3716 // The sources are also splitted into 4 chunks, and each destination 3717 // chunk must come from a different source chunk. 3718 // 3719 // SRC1 => X3 X2 X1 X0 3720 // SRC2 => Y3 Y2 Y1 Y0 3721 // 3722 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3723 // 3724 unsigned HalfLaneElems = NumLaneElems/2; 3725 for (unsigned l = 0; l != NumElems; l += NumLaneElems) { 3726 for (unsigned i = 0; i != NumLaneElems; ++i) { 3727 int Idx = Mask[i+l]; 3728 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0); 3729 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems)) 3730 return false; 3731 // For VSHUFPSY, the mask of the second half must be the same as the 3732 // first but with the appropriate offsets. This works in the same way as 3733 // VPERMILPS works with masks. 3734 if (NumElems != 8 || l == 0 || Mask[i] < 0) 3735 continue; 3736 if (!isUndefOrEqual(Idx, Mask[i]+l)) 3737 return false; 3738 } 3739 } 3740 3741 return true; 3742 } 3743 3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) { 3747 if (!VT.is128BitVector()) 3748 return false; 3749 3750 unsigned NumElems = VT.getVectorNumElements(); 3751 3752 if (NumElems != 4) 3753 return false; 3754 3755 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3756 return isUndefOrEqual(Mask[0], 6) && 3757 isUndefOrEqual(Mask[1], 7) && 3758 isUndefOrEqual(Mask[2], 2) && 3759 isUndefOrEqual(Mask[3], 3); 3760 } 3761 3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3764 /// <2, 3, 2, 3> 3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) { 3766 if (!VT.is128BitVector()) 3767 return false; 3768 3769 unsigned NumElems = VT.getVectorNumElements(); 3770 3771 if (NumElems != 4) 3772 return false; 3773 3774 return isUndefOrEqual(Mask[0], 2) && 3775 isUndefOrEqual(Mask[1], 3) && 3776 isUndefOrEqual(Mask[2], 2) && 3777 isUndefOrEqual(Mask[3], 3); 3778 } 3779 3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3782 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) { 3783 if (!VT.is128BitVector()) 3784 return false; 3785 3786 unsigned NumElems = VT.getVectorNumElements(); 3787 3788 if (NumElems != 2 && NumElems != 4) 3789 return false; 3790 3791 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3792 if (!isUndefOrEqual(Mask[i], i + NumElems)) 3793 return false; 3794 3795 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 3796 if (!isUndefOrEqual(Mask[i], i)) 3797 return false; 3798 3799 return true; 3800 } 3801 3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) { 3805 if (!VT.is128BitVector()) 3806 return false; 3807 3808 unsigned NumElems = VT.getVectorNumElements(); 3809 3810 if (NumElems != 2 && NumElems != 4) 3811 return false; 3812 3813 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3814 if (!isUndefOrEqual(Mask[i], i)) 3815 return false; 3816 3817 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3818 if (!isUndefOrEqual(Mask[i + e], i + NumElems)) 3819 return false; 3820 3821 return true; 3822 } 3823 3824 // 3825 // Some special combinations that can be optimized. 3826 // 3827 static 3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp, 3829 SelectionDAG &DAG) { 3830 MVT VT = SVOp->getValueType(0).getSimpleVT(); 3831 SDLoc dl(SVOp); 3832 3833 if (VT != MVT::v8i32 && VT != MVT::v8f32) 3834 return SDValue(); 3835 3836 ArrayRef<int> Mask = SVOp->getMask(); 3837 3838 // These are the special masks that may be optimized. 3839 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14}; 3840 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15}; 3841 bool MatchEvenMask = true; 3842 bool MatchOddMask = true; 3843 for (int i=0; i<8; ++i) { 3844 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i])) 3845 MatchEvenMask = false; 3846 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i])) 3847 MatchOddMask = false; 3848 } 3849 3850 if (!MatchEvenMask && !MatchOddMask) 3851 return SDValue(); 3852 3853 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT); 3854 3855 SDValue Op0 = SVOp->getOperand(0); 3856 SDValue Op1 = SVOp->getOperand(1); 3857 3858 if (MatchEvenMask) { 3859 // Shift the second operand right to 32 bits. 3860 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 }; 3861 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask); 3862 } else { 3863 // Shift the first operand left to 32 bits. 3864 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 }; 3865 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask); 3866 } 3867 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15}; 3868 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask); 3869 } 3870 3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL. 3873 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT, 3874 bool HasInt256, bool V2IsSplat = false) { 3875 unsigned NumElts = VT.getVectorNumElements(); 3876 3877 assert((VT.is128BitVector() || VT.is256BitVector()) && 3878 "Unsupported vector type for unpckh"); 3879 3880 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3881 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3882 return false; 3883 3884 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3885 // independently on 128-bit lanes. 3886 unsigned NumLanes = VT.getSizeInBits()/128; 3887 unsigned NumLaneElts = NumElts/NumLanes; 3888 3889 for (unsigned l = 0; l != NumElts; l += NumLaneElts) { 3890 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) { 3891 int BitI = Mask[l+i]; 3892 int BitI1 = Mask[l+i+1]; 3893 if (!isUndefOrEqual(BitI, j)) 3894 return false; 3895 if (V2IsSplat) { 3896 if (!isUndefOrEqual(BitI1, NumElts)) 3897 return false; 3898 } else { 3899 if (!isUndefOrEqual(BitI1, j + NumElts)) 3900 return false; 3901 } 3902 } 3903 } 3904 3905 return true; 3906 } 3907 3908 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3909 /// specifies a shuffle of elements that is suitable for input to UNPCKH. 3910 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT, 3911 bool HasInt256, bool V2IsSplat = false) { 3912 unsigned NumElts = VT.getVectorNumElements(); 3913 3914 assert((VT.is128BitVector() || VT.is256BitVector()) && 3915 "Unsupported vector type for unpckh"); 3916 3917 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3918 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3919 return false; 3920 3921 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3922 // independently on 128-bit lanes. 3923 unsigned NumLanes = VT.getSizeInBits()/128; 3924 unsigned NumLaneElts = NumElts/NumLanes; 3925 3926 for (unsigned l = 0; l != NumElts; l += NumLaneElts) { 3927 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) { 3928 int BitI = Mask[l+i]; 3929 int BitI1 = Mask[l+i+1]; 3930 if (!isUndefOrEqual(BitI, j)) 3931 return false; 3932 if (V2IsSplat) { 3933 if (isUndefOrEqual(BitI1, NumElts)) 3934 return false; 3935 } else { 3936 if (!isUndefOrEqual(BitI1, j+NumElts)) 3937 return false; 3938 } 3939 } 3940 } 3941 return true; 3942 } 3943 3944 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3945 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3946 /// <0, 0, 1, 1> 3947 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3948 unsigned NumElts = VT.getVectorNumElements(); 3949 bool Is256BitVec = VT.is256BitVector(); 3950 3951 assert((VT.is128BitVector() || VT.is256BitVector()) && 3952 "Unsupported vector type for unpckh"); 3953 3954 if (Is256BitVec && NumElts != 4 && NumElts != 8 && 3955 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3956 return false; 3957 3958 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3959 // FIXME: Need a better way to get rid of this, there's no latency difference 3960 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3961 // the former later. We should also remove the "_undef" special mask. 3962 if (NumElts == 4 && Is256BitVec) 3963 return false; 3964 3965 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3966 // independently on 128-bit lanes. 3967 unsigned NumLanes = VT.getSizeInBits()/128; 3968 unsigned NumLaneElts = NumElts/NumLanes; 3969 3970 for (unsigned l = 0; l != NumElts; l += NumLaneElts) { 3971 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) { 3972 int BitI = Mask[l+i]; 3973 int BitI1 = Mask[l+i+1]; 3974 3975 if (!isUndefOrEqual(BitI, j)) 3976 return false; 3977 if (!isUndefOrEqual(BitI1, j)) 3978 return false; 3979 } 3980 } 3981 3982 return true; 3983 } 3984 3985 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3986 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3987 /// <2, 2, 3, 3> 3988 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3989 unsigned NumElts = VT.getVectorNumElements(); 3990 3991 assert((VT.is128BitVector() || VT.is256BitVector()) && 3992 "Unsupported vector type for unpckh"); 3993 3994 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3995 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3996 return false; 3997 3998 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3999 // independently on 128-bit lanes. 4000 unsigned NumLanes = VT.getSizeInBits()/128; 4001 unsigned NumLaneElts = NumElts/NumLanes; 4002 4003 for (unsigned l = 0; l != NumElts; l += NumLaneElts) { 4004 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) { 4005 int BitI = Mask[l+i]; 4006 int BitI1 = Mask[l+i+1]; 4007 if (!isUndefOrEqual(BitI, j)) 4008 return false; 4009 if (!isUndefOrEqual(BitI1, j)) 4010 return false; 4011 } 4012 } 4013 return true; 4014 } 4015 4016 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 4017 /// specifies a shuffle of elements that is suitable for input to MOVSS, 4018 /// MOVSD, and MOVD, i.e. setting the lowest element. 4019 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) { 4020 if (VT.getVectorElementType().getSizeInBits() < 32) 4021 return false; 4022 if (!VT.is128BitVector()) 4023 return false; 4024 4025 unsigned NumElts = VT.getVectorNumElements(); 4026 4027 if (!isUndefOrEqual(Mask[0], NumElts)) 4028 return false; 4029 4030 for (unsigned i = 1; i != NumElts; ++i) 4031 if (!isUndefOrEqual(Mask[i], i)) 4032 return false; 4033 4034 return true; 4035 } 4036 4037 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered 4038 /// as permutations between 128-bit chunks or halves. As an example: this 4039 /// shuffle bellow: 4040 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 4041 /// The first half comes from the second half of V1 and the second half from the 4042 /// the second half of V2. 4043 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 4044 if (!HasFp256 || !VT.is256BitVector()) 4045 return false; 4046 4047 // The shuffle result is divided into half A and half B. In total the two 4048 // sources have 4 halves, namely: C, D, E, F. The final values of A and 4049 // B must come from C, D, E or F. 4050 unsigned HalfSize = VT.getVectorNumElements()/2; 4051 bool MatchA = false, MatchB = false; 4052 4053 // Check if A comes from one of C, D, E, F. 4054 for (unsigned Half = 0; Half != 4; ++Half) { 4055 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 4056 MatchA = true; 4057 break; 4058 } 4059 } 4060 4061 // Check if B comes from one of C, D, E, F. 4062 for (unsigned Half = 0; Half != 4; ++Half) { 4063 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 4064 MatchB = true; 4065 break; 4066 } 4067 } 4068 4069 return MatchA && MatchB; 4070 } 4071 4072 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle 4073 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions. 4074 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) { 4075 MVT VT = SVOp->getValueType(0).getSimpleVT(); 4076 4077 unsigned HalfSize = VT.getVectorNumElements()/2; 4078 4079 unsigned FstHalf = 0, SndHalf = 0; 4080 for (unsigned i = 0; i < HalfSize; ++i) { 4081 if (SVOp->getMaskElt(i) > 0) { 4082 FstHalf = SVOp->getMaskElt(i)/HalfSize; 4083 break; 4084 } 4085 } 4086 for (unsigned i = HalfSize; i < HalfSize*2; ++i) { 4087 if (SVOp->getMaskElt(i) > 0) { 4088 SndHalf = SVOp->getMaskElt(i)/HalfSize; 4089 break; 4090 } 4091 } 4092 4093 return (FstHalf | (SndHalf << 4)); 4094 } 4095 4096 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand 4097 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 4098 /// Note that VPERMIL mask matching is different depending whether theunderlying 4099 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point 4100 /// to the same elements of the low, but to the higher half of the source. 4101 /// In VPERMILPD the two lanes could be shuffled independently of each other 4102 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY. 4103 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 4104 if (!HasFp256) 4105 return false; 4106 4107 unsigned NumElts = VT.getVectorNumElements(); 4108 // Only match 256-bit with 32/64-bit types 4109 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8)) 4110 return false; 4111 4112 unsigned NumLanes = VT.getSizeInBits()/128; 4113 unsigned LaneSize = NumElts/NumLanes; 4114 for (unsigned l = 0; l != NumElts; l += LaneSize) { 4115 for (unsigned i = 0; i != LaneSize; ++i) { 4116 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize)) 4117 return false; 4118 if (NumElts != 8 || l == 0) 4119 continue; 4120 // VPERMILPS handling 4121 if (Mask[i] < 0) 4122 continue; 4123 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l)) 4124 return false; 4125 } 4126 } 4127 4128 return true; 4129 } 4130 4131 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse 4132 /// of what x86 movss want. X86 movs requires the lowest element to be lowest 4133 /// element of vector 2 and the other elements to come from vector 1 in order. 4134 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT, 4135 bool V2IsSplat = false, bool V2IsUndef = false) { 4136 if (!VT.is128BitVector()) 4137 return false; 4138 4139 unsigned NumOps = VT.getVectorNumElements(); 4140 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 4141 return false; 4142 4143 if (!isUndefOrEqual(Mask[0], 0)) 4144 return false; 4145 4146 for (unsigned i = 1; i != NumOps; ++i) 4147 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 4148 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 4149 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 4150 return false; 4151 4152 return true; 4153 } 4154 4155 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 4156 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 4157 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 4158 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT, 4159 const X86Subtarget *Subtarget) { 4160 if (!Subtarget->hasSSE3()) 4161 return false; 4162 4163 unsigned NumElems = VT.getVectorNumElements(); 4164 4165 if ((VT.is128BitVector() && NumElems != 4) || 4166 (VT.is256BitVector() && NumElems != 8)) 4167 return false; 4168 4169 // "i+1" is the value the indexed mask element must have 4170 for (unsigned i = 0; i != NumElems; i += 2) 4171 if (!isUndefOrEqual(Mask[i], i+1) || 4172 !isUndefOrEqual(Mask[i+1], i+1)) 4173 return false; 4174 4175 return true; 4176 } 4177 4178 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 4179 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 4180 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 4181 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT, 4182 const X86Subtarget *Subtarget) { 4183 if (!Subtarget->hasSSE3()) 4184 return false; 4185 4186 unsigned NumElems = VT.getVectorNumElements(); 4187 4188 if ((VT.is128BitVector() && NumElems != 4) || 4189 (VT.is256BitVector() && NumElems != 8)) 4190 return false; 4191 4192 // "i" is the value the indexed mask element must have 4193 for (unsigned i = 0; i != NumElems; i += 2) 4194 if (!isUndefOrEqual(Mask[i], i) || 4195 !isUndefOrEqual(Mask[i+1], i)) 4196 return false; 4197 4198 return true; 4199 } 4200 4201 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 4202 /// specifies a shuffle of elements that is suitable for input to 256-bit 4203 /// version of MOVDDUP. 4204 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 4205 if (!HasFp256 || !VT.is256BitVector()) 4206 return false; 4207 4208 unsigned NumElts = VT.getVectorNumElements(); 4209 if (NumElts != 4) 4210 return false; 4211 4212 for (unsigned i = 0; i != NumElts/2; ++i) 4213 if (!isUndefOrEqual(Mask[i], 0)) 4214 return false; 4215 for (unsigned i = NumElts/2; i != NumElts; ++i) 4216 if (!isUndefOrEqual(Mask[i], NumElts/2)) 4217 return false; 4218 return true; 4219 } 4220 4221 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 4222 /// specifies a shuffle of elements that is suitable for input to 128-bit 4223 /// version of MOVDDUP. 4224 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) { 4225 if (!VT.is128BitVector()) 4226 return false; 4227 4228 unsigned e = VT.getVectorNumElements() / 2; 4229 for (unsigned i = 0; i != e; ++i) 4230 if (!isUndefOrEqual(Mask[i], i)) 4231 return false; 4232 for (unsigned i = 0; i != e; ++i) 4233 if (!isUndefOrEqual(Mask[e+i], i)) 4234 return false; 4235 return true; 4236 } 4237 4238 /// isVEXTRACTIndex - Return true if the specified 4239 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is 4240 /// suitable for instruction that extract 128 or 256 bit vectors 4241 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) { 4242 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width"); 4243 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4244 return false; 4245 4246 // The index should be aligned on a vecWidth-bit boundary. 4247 uint64_t Index = 4248 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4249 4250 MVT VT = N->getValueType(0).getSimpleVT(); 4251 unsigned ElSize = VT.getVectorElementType().getSizeInBits(); 4252 bool Result = (Index * ElSize) % vecWidth == 0; 4253 4254 return Result; 4255 } 4256 4257 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR 4258 /// operand specifies a subvector insert that is suitable for input to 4259 /// insertion of 128 or 256-bit subvectors 4260 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) { 4261 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width"); 4262 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4263 return false; 4264 // The index should be aligned on a vecWidth-bit boundary. 4265 uint64_t Index = 4266 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4267 4268 MVT VT = N->getValueType(0).getSimpleVT(); 4269 unsigned ElSize = VT.getVectorElementType().getSizeInBits(); 4270 bool Result = (Index * ElSize) % vecWidth == 0; 4271 4272 return Result; 4273 } 4274 4275 bool X86::isVINSERT128Index(SDNode *N) { 4276 return isVINSERTIndex(N, 128); 4277 } 4278 4279 bool X86::isVINSERT256Index(SDNode *N) { 4280 return isVINSERTIndex(N, 256); 4281 } 4282 4283 bool X86::isVEXTRACT128Index(SDNode *N) { 4284 return isVEXTRACTIndex(N, 128); 4285 } 4286 4287 bool X86::isVEXTRACT256Index(SDNode *N) { 4288 return isVEXTRACTIndex(N, 256); 4289 } 4290 4291 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4292 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4293 /// Handles 128-bit and 256-bit. 4294 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) { 4295 MVT VT = N->getValueType(0).getSimpleVT(); 4296 4297 assert((VT.is128BitVector() || VT.is256BitVector()) && 4298 "Unsupported vector type for PSHUF/SHUFP"); 4299 4300 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate 4301 // independently on 128-bit lanes. 4302 unsigned NumElts = VT.getVectorNumElements(); 4303 unsigned NumLanes = VT.getSizeInBits()/128; 4304 unsigned NumLaneElts = NumElts/NumLanes; 4305 4306 assert((NumLaneElts == 2 || NumLaneElts == 4) && 4307 "Only supports 2 or 4 elements per lane"); 4308 4309 unsigned Shift = (NumLaneElts == 4) ? 1 : 0; 4310 unsigned Mask = 0; 4311 for (unsigned i = 0; i != NumElts; ++i) { 4312 int Elt = N->getMaskElt(i); 4313 if (Elt < 0) continue; 4314 Elt &= NumLaneElts - 1; 4315 unsigned ShAmt = (i << Shift) % 8; 4316 Mask |= Elt << ShAmt; 4317 } 4318 4319 return Mask; 4320 } 4321 4322 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4323 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4324 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) { 4325 MVT VT = N->getValueType(0).getSimpleVT(); 4326 4327 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4328 "Unsupported vector type for PSHUFHW"); 4329 4330 unsigned NumElts = VT.getVectorNumElements(); 4331 4332 unsigned Mask = 0; 4333 for (unsigned l = 0; l != NumElts; l += 8) { 4334 // 8 nodes per lane, but we only care about the last 4. 4335 for (unsigned i = 0; i < 4; ++i) { 4336 int Elt = N->getMaskElt(l+i+4); 4337 if (Elt < 0) continue; 4338 Elt &= 0x3; // only 2-bits. 4339 Mask |= Elt << (i * 2); 4340 } 4341 } 4342 4343 return Mask; 4344 } 4345 4346 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4347 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4348 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) { 4349 MVT VT = N->getValueType(0).getSimpleVT(); 4350 4351 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4352 "Unsupported vector type for PSHUFHW"); 4353 4354 unsigned NumElts = VT.getVectorNumElements(); 4355 4356 unsigned Mask = 0; 4357 for (unsigned l = 0; l != NumElts; l += 8) { 4358 // 8 nodes per lane, but we only care about the first 4. 4359 for (unsigned i = 0; i < 4; ++i) { 4360 int Elt = N->getMaskElt(l+i); 4361 if (Elt < 0) continue; 4362 Elt &= 0x3; // only 2-bits 4363 Mask |= Elt << (i * 2); 4364 } 4365 } 4366 4367 return Mask; 4368 } 4369 4370 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4371 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4372 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) { 4373 MVT VT = SVOp->getValueType(0).getSimpleVT(); 4374 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3; 4375 4376 unsigned NumElts = VT.getVectorNumElements(); 4377 unsigned NumLanes = VT.getSizeInBits()/128; 4378 unsigned NumLaneElts = NumElts/NumLanes; 4379 4380 int Val = 0; 4381 unsigned i; 4382 for (i = 0; i != NumElts; ++i) { 4383 Val = SVOp->getMaskElt(i); 4384 if (Val >= 0) 4385 break; 4386 } 4387 if (Val >= (int)NumElts) 4388 Val -= NumElts - NumLaneElts; 4389 4390 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4391 return (Val - i) * EltSize; 4392 } 4393 4394 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) { 4395 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width"); 4396 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4397 llvm_unreachable("Illegal extract subvector for VEXTRACT"); 4398 4399 uint64_t Index = 4400 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4401 4402 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT(); 4403 MVT ElVT = VecVT.getVectorElementType(); 4404 4405 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits(); 4406 return Index / NumElemsPerChunk; 4407 } 4408 4409 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) { 4410 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width"); 4411 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4412 llvm_unreachable("Illegal insert subvector for VINSERT"); 4413 4414 uint64_t Index = 4415 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4416 4417 MVT VecVT = N->getValueType(0).getSimpleVT(); 4418 MVT ElVT = VecVT.getVectorElementType(); 4419 4420 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits(); 4421 return Index / NumElemsPerChunk; 4422 } 4423 4424 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate 4425 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4426 /// and VINSERTI128 instructions. 4427 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) { 4428 return getExtractVEXTRACTImmediate(N, 128); 4429 } 4430 4431 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate 4432 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4 4433 /// and VINSERTI64x4 instructions. 4434 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) { 4435 return getExtractVEXTRACTImmediate(N, 256); 4436 } 4437 4438 /// getInsertVINSERT128Immediate - Return the appropriate immediate 4439 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4440 /// and VINSERTI128 instructions. 4441 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) { 4442 return getInsertVINSERTImmediate(N, 128); 4443 } 4444 4445 /// getInsertVINSERT256Immediate - Return the appropriate immediate 4446 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4 4447 /// and VINSERTI64x4 instructions. 4448 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) { 4449 return getInsertVINSERTImmediate(N, 256); 4450 } 4451 4452 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle 4453 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions. 4454 /// Handles 256-bit. 4455 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) { 4456 MVT VT = N->getValueType(0).getSimpleVT(); 4457 4458 unsigned NumElts = VT.getVectorNumElements(); 4459 4460 assert((VT.is256BitVector() && NumElts == 4) && 4461 "Unsupported vector type for VPERMQ/VPERMPD"); 4462 4463 unsigned Mask = 0; 4464 for (unsigned i = 0; i != NumElts; ++i) { 4465 int Elt = N->getMaskElt(i); 4466 if (Elt < 0) 4467 continue; 4468 Mask |= Elt << (i*2); 4469 } 4470 4471 return Mask; 4472 } 4473 /// isZeroNode - Returns true if Elt is a constant zero or a floating point 4474 /// constant +0.0. 4475 bool X86::isZeroNode(SDValue Elt) { 4476 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt)) 4477 return CN->isNullValue(); 4478 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt)) 4479 return CFP->getValueAPF().isPosZero(); 4480 return false; 4481 } 4482 4483 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4484 /// their permute mask. 4485 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4486 SelectionDAG &DAG) { 4487 MVT VT = SVOp->getValueType(0).getSimpleVT(); 4488 unsigned NumElems = VT.getVectorNumElements(); 4489 SmallVector<int, 8> MaskVec; 4490 4491 for (unsigned i = 0; i != NumElems; ++i) { 4492 int Idx = SVOp->getMaskElt(i); 4493 if (Idx >= 0) { 4494 if (Idx < (int)NumElems) 4495 Idx += NumElems; 4496 else 4497 Idx -= NumElems; 4498 } 4499 MaskVec.push_back(Idx); 4500 } 4501 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1), 4502 SVOp->getOperand(0), &MaskVec[0]); 4503 } 4504 4505 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4506 /// match movhlps. The lower half elements should come from upper half of 4507 /// V1 (and in order), and the upper half elements should come from the upper 4508 /// half of V2 (and in order). 4509 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) { 4510 if (!VT.is128BitVector()) 4511 return false; 4512 if (VT.getVectorNumElements() != 4) 4513 return false; 4514 for (unsigned i = 0, e = 2; i != e; ++i) 4515 if (!isUndefOrEqual(Mask[i], i+2)) 4516 return false; 4517 for (unsigned i = 2; i != 4; ++i) 4518 if (!isUndefOrEqual(Mask[i], i+4)) 4519 return false; 4520 return true; 4521 } 4522 4523 /// isScalarLoadToVector - Returns true if the node is a scalar load that 4524 /// is promoted to a vector. It also returns the LoadSDNode by reference if 4525 /// required. 4526 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4527 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4528 return false; 4529 N = N->getOperand(0).getNode(); 4530 if (!ISD::isNON_EXTLoad(N)) 4531 return false; 4532 if (LD) 4533 *LD = cast<LoadSDNode>(N); 4534 return true; 4535 } 4536 4537 // Test whether the given value is a vector value which will be legalized 4538 // into a load. 4539 static bool WillBeConstantPoolLoad(SDNode *N) { 4540 if (N->getOpcode() != ISD::BUILD_VECTOR) 4541 return false; 4542 4543 // Check for any non-constant elements. 4544 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4545 switch (N->getOperand(i).getNode()->getOpcode()) { 4546 case ISD::UNDEF: 4547 case ISD::ConstantFP: 4548 case ISD::Constant: 4549 break; 4550 default: 4551 return false; 4552 } 4553 4554 // Vectors of all-zeros and all-ones are materialized with special 4555 // instructions rather than being loaded. 4556 return !ISD::isBuildVectorAllZeros(N) && 4557 !ISD::isBuildVectorAllOnes(N); 4558 } 4559 4560 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4561 /// match movlp{s|d}. The lower half elements should come from lower half of 4562 /// V1 (and in order), and the upper half elements should come from the upper 4563 /// half of V2 (and in order). And since V1 will become the source of the 4564 /// MOVLP, it must be either a vector load or a scalar load to vector. 4565 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4566 ArrayRef<int> Mask, EVT VT) { 4567 if (!VT.is128BitVector()) 4568 return false; 4569 4570 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4571 return false; 4572 // Is V2 is a vector load, don't do this transformation. We will try to use 4573 // load folding shufps op. 4574 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4575 return false; 4576 4577 unsigned NumElems = VT.getVectorNumElements(); 4578 4579 if (NumElems != 2 && NumElems != 4) 4580 return false; 4581 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4582 if (!isUndefOrEqual(Mask[i], i)) 4583 return false; 4584 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 4585 if (!isUndefOrEqual(Mask[i], i+NumElems)) 4586 return false; 4587 return true; 4588 } 4589 4590 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4591 /// all the same. 4592 static bool isSplatVector(SDNode *N) { 4593 if (N->getOpcode() != ISD::BUILD_VECTOR) 4594 return false; 4595 4596 SDValue SplatValue = N->getOperand(0); 4597 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4598 if (N->getOperand(i) != SplatValue) 4599 return false; 4600 return true; 4601 } 4602 4603 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4604 /// to an zero vector. 4605 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4606 static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4607 SDValue V1 = N->getOperand(0); 4608 SDValue V2 = N->getOperand(1); 4609 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4610 for (unsigned i = 0; i != NumElems; ++i) { 4611 int Idx = N->getMaskElt(i); 4612 if (Idx >= (int)NumElems) { 4613 unsigned Opc = V2.getOpcode(); 4614 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4615 continue; 4616 if (Opc != ISD::BUILD_VECTOR || 4617 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4618 return false; 4619 } else if (Idx >= 0) { 4620 unsigned Opc = V1.getOpcode(); 4621 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4622 continue; 4623 if (Opc != ISD::BUILD_VECTOR || 4624 !X86::isZeroNode(V1.getOperand(Idx))) 4625 return false; 4626 } 4627 } 4628 return true; 4629 } 4630 4631 /// getZeroVector - Returns a vector of specified type with all zero elements. 4632 /// 4633 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget, 4634 SelectionDAG &DAG, SDLoc dl) { 4635 assert(VT.isVector() && "Expected a vector type"); 4636 4637 // Always build SSE zero vectors as <4 x i32> bitcasted 4638 // to their dest type. This ensures they get CSE'd. 4639 SDValue Vec; 4640 if (VT.is128BitVector()) { // SSE 4641 if (Subtarget->hasSSE2()) { // SSE2 4642 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4643 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4644 } else { // SSE1 4645 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4646 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4647 } 4648 } else if (VT.is256BitVector()) { // AVX 4649 if (Subtarget->hasInt256()) { // AVX2 4650 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4651 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4652 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 4653 array_lengthof(Ops)); 4654 } else { 4655 // 256-bit logic and arithmetic instructions in AVX are all 4656 // floating-point, no support for integer ops. Emit fp zeroed vectors. 4657 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4658 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4659 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 4660 array_lengthof(Ops)); 4661 } 4662 } else 4663 llvm_unreachable("Unexpected vector type"); 4664 4665 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4666 } 4667 4668 /// getOnesVector - Returns a vector of specified type with all bits set. 4669 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with 4670 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately. 4671 /// Then bitcast to their original type, ensuring they get CSE'd. 4672 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG, 4673 SDLoc dl) { 4674 assert(VT.isVector() && "Expected a vector type"); 4675 4676 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4677 SDValue Vec; 4678 if (VT.is256BitVector()) { 4679 if (HasInt256) { // AVX2 4680 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4681 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 4682 array_lengthof(Ops)); 4683 } else { // AVX 4684 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4685 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl); 4686 } 4687 } else if (VT.is128BitVector()) { 4688 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4689 } else 4690 llvm_unreachable("Unexpected vector type"); 4691 4692 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4693 } 4694 4695 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4696 /// that point to V2 points to its first element. 4697 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) { 4698 for (unsigned i = 0; i != NumElems; ++i) { 4699 if (Mask[i] > (int)NumElems) { 4700 Mask[i] = NumElems; 4701 } 4702 } 4703 } 4704 4705 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4706 /// operation of specified width. 4707 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4708 SDValue V2) { 4709 unsigned NumElems = VT.getVectorNumElements(); 4710 SmallVector<int, 8> Mask; 4711 Mask.push_back(NumElems); 4712 for (unsigned i = 1; i != NumElems; ++i) 4713 Mask.push_back(i); 4714 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4715 } 4716 4717 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4718 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4719 SDValue V2) { 4720 unsigned NumElems = VT.getVectorNumElements(); 4721 SmallVector<int, 8> Mask; 4722 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4723 Mask.push_back(i); 4724 Mask.push_back(i + NumElems); 4725 } 4726 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4727 } 4728 4729 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4730 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4731 SDValue V2) { 4732 unsigned NumElems = VT.getVectorNumElements(); 4733 SmallVector<int, 8> Mask; 4734 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) { 4735 Mask.push_back(i + Half); 4736 Mask.push_back(i + NumElems + Half); 4737 } 4738 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4739 } 4740 4741 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4742 // a generic shuffle instruction because the target has no such instructions. 4743 // Generate shuffles which repeat i16 and i8 several times until they can be 4744 // represented by v4f32 and then be manipulated by target suported shuffles. 4745 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4746 EVT VT = V.getValueType(); 4747 int NumElems = VT.getVectorNumElements(); 4748 SDLoc dl(V); 4749 4750 while (NumElems > 4) { 4751 if (EltNo < NumElems/2) { 4752 V = getUnpackl(DAG, dl, VT, V, V); 4753 } else { 4754 V = getUnpackh(DAG, dl, VT, V, V); 4755 EltNo -= NumElems/2; 4756 } 4757 NumElems >>= 1; 4758 } 4759 return V; 4760 } 4761 4762 /// getLegalSplat - Generate a legal splat with supported x86 shuffles 4763 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4764 EVT VT = V.getValueType(); 4765 SDLoc dl(V); 4766 4767 if (VT.is128BitVector()) { 4768 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4769 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4770 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4771 &SplatMask[0]); 4772 } else if (VT.is256BitVector()) { 4773 // To use VPERMILPS to splat scalars, the second half of indicies must 4774 // refer to the higher part, which is a duplication of the lower one, 4775 // because VPERMILPS can only handle in-lane permutations. 4776 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4777 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4778 4779 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4780 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4781 &SplatMask[0]); 4782 } else 4783 llvm_unreachable("Vector size not supported"); 4784 4785 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4786 } 4787 4788 /// PromoteSplat - Splat is promoted to target supported vector shuffles. 4789 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4790 EVT SrcVT = SV->getValueType(0); 4791 SDValue V1 = SV->getOperand(0); 4792 SDLoc dl(SV); 4793 4794 int EltNo = SV->getSplatIndex(); 4795 int NumElems = SrcVT.getVectorNumElements(); 4796 bool Is256BitVec = SrcVT.is256BitVector(); 4797 4798 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) && 4799 "Unknown how to promote splat for type"); 4800 4801 // Extract the 128-bit part containing the splat element and update 4802 // the splat element index when it refers to the higher register. 4803 if (Is256BitVec) { 4804 V1 = Extract128BitVector(V1, EltNo, DAG, dl); 4805 if (EltNo >= NumElems/2) 4806 EltNo -= NumElems/2; 4807 } 4808 4809 // All i16 and i8 vector types can't be used directly by a generic shuffle 4810 // instruction because the target has no such instruction. Generate shuffles 4811 // which repeat i16 and i8 several times until they fit in i32, and then can 4812 // be manipulated by target suported shuffles. 4813 EVT EltVT = SrcVT.getVectorElementType(); 4814 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4815 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4816 4817 // Recreate the 256-bit vector and place the same 128-bit vector 4818 // into the low and high part. This is necessary because we want 4819 // to use VPERM* to shuffle the vectors 4820 if (Is256BitVec) { 4821 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1); 4822 } 4823 4824 return getLegalSplat(DAG, V1, EltNo); 4825 } 4826 4827 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4828 /// vector of zero or undef vector. This produces a shuffle where the low 4829 /// element of V2 is swizzled into the zero/undef vector, landing at element 4830 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4831 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4832 bool IsZero, 4833 const X86Subtarget *Subtarget, 4834 SelectionDAG &DAG) { 4835 EVT VT = V2.getValueType(); 4836 SDValue V1 = IsZero 4837 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT); 4838 unsigned NumElems = VT.getVectorNumElements(); 4839 SmallVector<int, 16> MaskVec; 4840 for (unsigned i = 0; i != NumElems; ++i) 4841 // If this is the insertion idx, put the low elt of V2 here. 4842 MaskVec.push_back(i == Idx ? NumElems : i); 4843 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]); 4844 } 4845 4846 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the 4847 /// target specific opcode. Returns true if the Mask could be calculated. 4848 /// Sets IsUnary to true if only uses one source. 4849 static bool getTargetShuffleMask(SDNode *N, MVT VT, 4850 SmallVectorImpl<int> &Mask, bool &IsUnary) { 4851 unsigned NumElems = VT.getVectorNumElements(); 4852 SDValue ImmN; 4853 4854 IsUnary = false; 4855 switch(N->getOpcode()) { 4856 case X86ISD::SHUFP: 4857 ImmN = N->getOperand(N->getNumOperands()-1); 4858 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4859 break; 4860 case X86ISD::UNPCKH: 4861 DecodeUNPCKHMask(VT, Mask); 4862 break; 4863 case X86ISD::UNPCKL: 4864 DecodeUNPCKLMask(VT, Mask); 4865 break; 4866 case X86ISD::MOVHLPS: 4867 DecodeMOVHLPSMask(NumElems, Mask); 4868 break; 4869 case X86ISD::MOVLHPS: 4870 DecodeMOVLHPSMask(NumElems, Mask); 4871 break; 4872 case X86ISD::PALIGNR: 4873 ImmN = N->getOperand(N->getNumOperands()-1); 4874 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4875 break; 4876 case X86ISD::PSHUFD: 4877 case X86ISD::VPERMILP: 4878 ImmN = N->getOperand(N->getNumOperands()-1); 4879 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4880 IsUnary = true; 4881 break; 4882 case X86ISD::PSHUFHW: 4883 ImmN = N->getOperand(N->getNumOperands()-1); 4884 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4885 IsUnary = true; 4886 break; 4887 case X86ISD::PSHUFLW: 4888 ImmN = N->getOperand(N->getNumOperands()-1); 4889 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4890 IsUnary = true; 4891 break; 4892 case X86ISD::VPERMI: 4893 ImmN = N->getOperand(N->getNumOperands()-1); 4894 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4895 IsUnary = true; 4896 break; 4897 case X86ISD::MOVSS: 4898 case X86ISD::MOVSD: { 4899 // The index 0 always comes from the first element of the second source, 4900 // this is why MOVSS and MOVSD are used in the first place. The other 4901 // elements come from the other positions of the first source vector 4902 Mask.push_back(NumElems); 4903 for (unsigned i = 1; i != NumElems; ++i) { 4904 Mask.push_back(i); 4905 } 4906 break; 4907 } 4908 case X86ISD::VPERM2X128: 4909 ImmN = N->getOperand(N->getNumOperands()-1); 4910 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4911 if (Mask.empty()) return false; 4912 break; 4913 case X86ISD::MOVDDUP: 4914 case X86ISD::MOVLHPD: 4915 case X86ISD::MOVLPD: 4916 case X86ISD::MOVLPS: 4917 case X86ISD::MOVSHDUP: 4918 case X86ISD::MOVSLDUP: 4919 // Not yet implemented 4920 return false; 4921 default: llvm_unreachable("unknown target shuffle node"); 4922 } 4923 4924 return true; 4925 } 4926 4927 /// getShuffleScalarElt - Returns the scalar element that will make up the ith 4928 /// element of the result of the vector shuffle. 4929 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG, 4930 unsigned Depth) { 4931 if (Depth == 6) 4932 return SDValue(); // Limit search depth. 4933 4934 SDValue V = SDValue(N, 0); 4935 EVT VT = V.getValueType(); 4936 unsigned Opcode = V.getOpcode(); 4937 4938 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4939 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4940 int Elt = SV->getMaskElt(Index); 4941 4942 if (Elt < 0) 4943 return DAG.getUNDEF(VT.getVectorElementType()); 4944 4945 unsigned NumElems = VT.getVectorNumElements(); 4946 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0) 4947 : SV->getOperand(1); 4948 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1); 4949 } 4950 4951 // Recurse into target specific vector shuffles to find scalars. 4952 if (isTargetShuffle(Opcode)) { 4953 MVT ShufVT = V.getValueType().getSimpleVT(); 4954 unsigned NumElems = ShufVT.getVectorNumElements(); 4955 SmallVector<int, 16> ShuffleMask; 4956 bool IsUnary; 4957 4958 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary)) 4959 return SDValue(); 4960 4961 int Elt = ShuffleMask[Index]; 4962 if (Elt < 0) 4963 return DAG.getUNDEF(ShufVT.getVectorElementType()); 4964 4965 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0) 4966 : N->getOperand(1); 4967 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, 4968 Depth+1); 4969 } 4970 4971 // Actual nodes that may contain scalar elements 4972 if (Opcode == ISD::BITCAST) { 4973 V = V.getOperand(0); 4974 EVT SrcVT = V.getValueType(); 4975 unsigned NumElems = VT.getVectorNumElements(); 4976 4977 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4978 return SDValue(); 4979 } 4980 4981 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4982 return (Index == 0) ? V.getOperand(0) 4983 : DAG.getUNDEF(VT.getVectorElementType()); 4984 4985 if (V.getOpcode() == ISD::BUILD_VECTOR) 4986 return V.getOperand(Index); 4987 4988 return SDValue(); 4989 } 4990 4991 /// getNumOfConsecutiveZeros - Return the number of elements of a vector 4992 /// shuffle operation which come from a consecutively from a zero. The 4993 /// search can start in two different directions, from left or right. 4994 /// We count undefs as zeros until PreferredNum is reached. 4995 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, 4996 unsigned NumElems, bool ZerosFromLeft, 4997 SelectionDAG &DAG, 4998 unsigned PreferredNum = -1U) { 4999 unsigned NumZeros = 0; 5000 for (unsigned i = 0; i != NumElems; ++i) { 5001 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1; 5002 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0); 5003 if (!Elt.getNode()) 5004 break; 5005 5006 if (X86::isZeroNode(Elt)) 5007 ++NumZeros; 5008 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum. 5009 NumZeros = std::min(NumZeros + 1, PreferredNum); 5010 else 5011 break; 5012 } 5013 5014 return NumZeros; 5015 } 5016 5017 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE) 5018 /// correspond consecutively to elements from one of the vector operands, 5019 /// starting from its index OpIdx. Also tell OpNum which source vector operand. 5020 static 5021 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, 5022 unsigned MaskI, unsigned MaskE, unsigned OpIdx, 5023 unsigned NumElems, unsigned &OpNum) { 5024 bool SeenV1 = false; 5025 bool SeenV2 = false; 5026 5027 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) { 5028 int Idx = SVOp->getMaskElt(i); 5029 // Ignore undef indicies 5030 if (Idx < 0) 5031 continue; 5032 5033 if (Idx < (int)NumElems) 5034 SeenV1 = true; 5035 else 5036 SeenV2 = true; 5037 5038 // Only accept consecutive elements from the same vector 5039 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 5040 return false; 5041 } 5042 5043 OpNum = SeenV1 ? 0 : 1; 5044 return true; 5045 } 5046 5047 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a 5048 /// logical left shift of a vector. 5049 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 5050 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 5051 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 5052 unsigned NumZeros = getNumOfConsecutiveZeros( 5053 SVOp, NumElems, false /* check zeros from right */, DAG, 5054 SVOp->getMaskElt(0)); 5055 unsigned OpSrc; 5056 5057 if (!NumZeros) 5058 return false; 5059 5060 // Considering the elements in the mask that are not consecutive zeros, 5061 // check if they consecutively come from only one of the source vectors. 5062 // 5063 // V1 = {X, A, B, C} 0 5064 // \ \ \ / 5065 // vector_shuffle V1, V2 <1, 2, 3, X> 5066 // 5067 if (!isShuffleMaskConsecutive(SVOp, 5068 0, // Mask Start Index 5069 NumElems-NumZeros, // Mask End Index(exclusive) 5070 NumZeros, // Where to start looking in the src vector 5071 NumElems, // Number of elements in vector 5072 OpSrc)) // Which source operand ? 5073 return false; 5074 5075 isLeft = false; 5076 ShAmt = NumZeros; 5077 ShVal = SVOp->getOperand(OpSrc); 5078 return true; 5079 } 5080 5081 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 5082 /// logical left shift of a vector. 5083 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 5084 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 5085 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 5086 unsigned NumZeros = getNumOfConsecutiveZeros( 5087 SVOp, NumElems, true /* check zeros from left */, DAG, 5088 NumElems - SVOp->getMaskElt(NumElems - 1) - 1); 5089 unsigned OpSrc; 5090 5091 if (!NumZeros) 5092 return false; 5093 5094 // Considering the elements in the mask that are not consecutive zeros, 5095 // check if they consecutively come from only one of the source vectors. 5096 // 5097 // 0 { A, B, X, X } = V2 5098 // / \ / / 5099 // vector_shuffle V1, V2 <X, X, 4, 5> 5100 // 5101 if (!isShuffleMaskConsecutive(SVOp, 5102 NumZeros, // Mask Start Index 5103 NumElems, // Mask End Index(exclusive) 5104 0, // Where to start looking in the src vector 5105 NumElems, // Number of elements in vector 5106 OpSrc)) // Which source operand ? 5107 return false; 5108 5109 isLeft = true; 5110 ShAmt = NumZeros; 5111 ShVal = SVOp->getOperand(OpSrc); 5112 return true; 5113 } 5114 5115 /// isVectorShift - Returns true if the shuffle can be implemented as a 5116 /// logical left or right shift of a vector. 5117 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 5118 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 5119 // Although the logic below support any bitwidth size, there are no 5120 // shift instructions which handle more than 128-bit vectors. 5121 if (!SVOp->getValueType(0).is128BitVector()) 5122 return false; 5123 5124 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 5125 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 5126 return true; 5127 5128 return false; 5129 } 5130 5131 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 5132 /// 5133 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 5134 unsigned NumNonZero, unsigned NumZero, 5135 SelectionDAG &DAG, 5136 const X86Subtarget* Subtarget, 5137 const TargetLowering &TLI) { 5138 if (NumNonZero > 8) 5139 return SDValue(); 5140 5141 SDLoc dl(Op); 5142 SDValue V(0, 0); 5143 bool First = true; 5144 for (unsigned i = 0; i < 16; ++i) { 5145 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 5146 if (ThisIsNonZero && First) { 5147 if (NumZero) 5148 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 5149 else 5150 V = DAG.getUNDEF(MVT::v8i16); 5151 First = false; 5152 } 5153 5154 if ((i & 1) != 0) { 5155 SDValue ThisElt(0, 0), LastElt(0, 0); 5156 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 5157 if (LastIsNonZero) { 5158 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 5159 MVT::i16, Op.getOperand(i-1)); 5160 } 5161 if (ThisIsNonZero) { 5162 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 5163 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 5164 ThisElt, DAG.getConstant(8, MVT::i8)); 5165 if (LastIsNonZero) 5166 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 5167 } else 5168 ThisElt = LastElt; 5169 5170 if (ThisElt.getNode()) 5171 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 5172 DAG.getIntPtrConstant(i/2)); 5173 } 5174 } 5175 5176 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 5177 } 5178 5179 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 5180 /// 5181 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 5182 unsigned NumNonZero, unsigned NumZero, 5183 SelectionDAG &DAG, 5184 const X86Subtarget* Subtarget, 5185 const TargetLowering &TLI) { 5186 if (NumNonZero > 4) 5187 return SDValue(); 5188 5189 SDLoc dl(Op); 5190 SDValue V(0, 0); 5191 bool First = true; 5192 for (unsigned i = 0; i < 8; ++i) { 5193 bool isNonZero = (NonZeros & (1 << i)) != 0; 5194 if (isNonZero) { 5195 if (First) { 5196 if (NumZero) 5197 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 5198 else 5199 V = DAG.getUNDEF(MVT::v8i16); 5200 First = false; 5201 } 5202 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 5203 MVT::v8i16, V, Op.getOperand(i), 5204 DAG.getIntPtrConstant(i)); 5205 } 5206 } 5207 5208 return V; 5209 } 5210 5211 /// getVShift - Return a vector logical shift node. 5212 /// 5213 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 5214 unsigned NumBits, SelectionDAG &DAG, 5215 const TargetLowering &TLI, SDLoc dl) { 5216 assert(VT.is128BitVector() && "Unknown type for VShift"); 5217 EVT ShVT = MVT::v2i64; 5218 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ; 5219 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 5220 return DAG.getNode(ISD::BITCAST, dl, VT, 5221 DAG.getNode(Opc, dl, ShVT, SrcOp, 5222 DAG.getConstant(NumBits, 5223 TLI.getScalarShiftAmountTy(SrcOp.getValueType())))); 5224 } 5225 5226 SDValue 5227 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl, 5228 SelectionDAG &DAG) const { 5229 5230 // Check if the scalar load can be widened into a vector load. And if 5231 // the address is "base + cst" see if the cst can be "absorbed" into 5232 // the shuffle mask. 5233 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 5234 SDValue Ptr = LD->getBasePtr(); 5235 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 5236 return SDValue(); 5237 EVT PVT = LD->getValueType(0); 5238 if (PVT != MVT::i32 && PVT != MVT::f32) 5239 return SDValue(); 5240 5241 int FI = -1; 5242 int64_t Offset = 0; 5243 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 5244 FI = FINode->getIndex(); 5245 Offset = 0; 5246 } else if (DAG.isBaseWithConstantOffset(Ptr) && 5247 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 5248 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 5249 Offset = Ptr.getConstantOperandVal(1); 5250 Ptr = Ptr.getOperand(0); 5251 } else { 5252 return SDValue(); 5253 } 5254 5255 // FIXME: 256-bit vector instructions don't require a strict alignment, 5256 // improve this code to support it better. 5257 unsigned RequiredAlign = VT.getSizeInBits()/8; 5258 SDValue Chain = LD->getChain(); 5259 // Make sure the stack object alignment is at least 16 or 32. 5260 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 5261 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 5262 if (MFI->isFixedObjectIndex(FI)) { 5263 // Can't change the alignment. FIXME: It's possible to compute 5264 // the exact stack offset and reference FI + adjust offset instead. 5265 // If someone *really* cares about this. That's the way to implement it. 5266 return SDValue(); 5267 } else { 5268 MFI->setObjectAlignment(FI, RequiredAlign); 5269 } 5270 } 5271 5272 // (Offset % 16 or 32) must be multiple of 4. Then address is then 5273 // Ptr + (Offset & ~15). 5274 if (Offset < 0) 5275 return SDValue(); 5276 if ((Offset % RequiredAlign) & 3) 5277 return SDValue(); 5278 int64_t StartOffset = Offset & ~(RequiredAlign-1); 5279 if (StartOffset) 5280 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(), 5281 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 5282 5283 int EltNo = (Offset - StartOffset) >> 2; 5284 unsigned NumElems = VT.getVectorNumElements(); 5285 5286 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 5287 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 5288 LD->getPointerInfo().getWithOffset(StartOffset), 5289 false, false, false, 0); 5290 5291 SmallVector<int, 8> Mask(NumElems, EltNo); 5292 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]); 5293 } 5294 5295 return SDValue(); 5296 } 5297 5298 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 5299 /// vector of type 'VT', see if the elements can be replaced by a single large 5300 /// load which has the same value as a build_vector whose operands are 'elts'. 5301 /// 5302 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 5303 /// 5304 /// FIXME: we'd also like to handle the case where the last elements are zero 5305 /// rather than undef via VZEXT_LOAD, but we do not detect that case today. 5306 /// There's even a handy isZeroNode for that purpose. 5307 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 5308 SDLoc &DL, SelectionDAG &DAG) { 5309 EVT EltVT = VT.getVectorElementType(); 5310 unsigned NumElems = Elts.size(); 5311 5312 LoadSDNode *LDBase = NULL; 5313 unsigned LastLoadedElt = -1U; 5314 5315 // For each element in the initializer, see if we've found a load or an undef. 5316 // If we don't find an initial load element, or later load elements are 5317 // non-consecutive, bail out. 5318 for (unsigned i = 0; i < NumElems; ++i) { 5319 SDValue Elt = Elts[i]; 5320 5321 if (!Elt.getNode() || 5322 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 5323 return SDValue(); 5324 if (!LDBase) { 5325 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 5326 return SDValue(); 5327 LDBase = cast<LoadSDNode>(Elt.getNode()); 5328 LastLoadedElt = i; 5329 continue; 5330 } 5331 if (Elt.getOpcode() == ISD::UNDEF) 5332 continue; 5333 5334 LoadSDNode *LD = cast<LoadSDNode>(Elt); 5335 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 5336 return SDValue(); 5337 LastLoadedElt = i; 5338 } 5339 5340 // If we have found an entire vector of loads and undefs, then return a large 5341 // load of the entire vector width starting at the base pointer. If we found 5342 // consecutive loads for the low half, generate a vzext_load node. 5343 if (LastLoadedElt == NumElems - 1) { 5344 SDValue NewLd = SDValue(); 5345 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 5346 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5347 LDBase->getPointerInfo(), 5348 LDBase->isVolatile(), LDBase->isNonTemporal(), 5349 LDBase->isInvariant(), 0); 5350 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5351 LDBase->getPointerInfo(), 5352 LDBase->isVolatile(), LDBase->isNonTemporal(), 5353 LDBase->isInvariant(), LDBase->getAlignment()); 5354 5355 if (LDBase->hasAnyUseOfValue(1)) { 5356 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 5357 SDValue(LDBase, 1), 5358 SDValue(NewLd.getNode(), 1)); 5359 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain); 5360 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1), 5361 SDValue(NewLd.getNode(), 1)); 5362 } 5363 5364 return NewLd; 5365 } 5366 if (NumElems == 4 && LastLoadedElt == 1 && 5367 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5368 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5369 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5370 SDValue ResNode = 5371 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 5372 array_lengthof(Ops), MVT::i64, 5373 LDBase->getPointerInfo(), 5374 LDBase->getAlignment(), 5375 false/*isVolatile*/, true/*ReadMem*/, 5376 false/*WriteMem*/); 5377 5378 // Make sure the newly-created LOAD is in the same position as LDBase in 5379 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and 5380 // update uses of LDBase's output chain to use the TokenFactor. 5381 if (LDBase->hasAnyUseOfValue(1)) { 5382 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 5383 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1)); 5384 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain); 5385 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1), 5386 SDValue(ResNode.getNode(), 1)); 5387 } 5388 5389 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5390 } 5391 return SDValue(); 5392 } 5393 5394 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction 5395 /// to generate a splat value for the following cases: 5396 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant. 5397 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5398 /// a scalar load, or a constant. 5399 /// The VBROADCAST node is returned when a pattern is found, 5400 /// or SDValue() otherwise. 5401 SDValue 5402 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const { 5403 if (!Subtarget->hasFp256()) 5404 return SDValue(); 5405 5406 MVT VT = Op.getValueType().getSimpleVT(); 5407 SDLoc dl(Op); 5408 5409 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && 5410 "Unsupported vector type for broadcast."); 5411 5412 SDValue Ld; 5413 bool ConstSplatVal; 5414 5415 switch (Op.getOpcode()) { 5416 default: 5417 // Unknown pattern found. 5418 return SDValue(); 5419 5420 case ISD::BUILD_VECTOR: { 5421 // The BUILD_VECTOR node must be a splat. 5422 if (!isSplatVector(Op.getNode())) 5423 return SDValue(); 5424 5425 Ld = Op.getOperand(0); 5426 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5427 Ld.getOpcode() == ISD::ConstantFP); 5428 5429 // The suspected load node has several users. Make sure that all 5430 // of its users are from the BUILD_VECTOR node. 5431 // Constants may have multiple users. 5432 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5433 return SDValue(); 5434 break; 5435 } 5436 5437 case ISD::VECTOR_SHUFFLE: { 5438 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5439 5440 // Shuffles must have a splat mask where the first element is 5441 // broadcasted. 5442 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5443 return SDValue(); 5444 5445 SDValue Sc = Op.getOperand(0); 5446 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR && 5447 Sc.getOpcode() != ISD::BUILD_VECTOR) { 5448 5449 if (!Subtarget->hasInt256()) 5450 return SDValue(); 5451 5452 // Use the register form of the broadcast instruction available on AVX2. 5453 if (VT.is256BitVector()) 5454 Sc = Extract128BitVector(Sc, 0, DAG, dl); 5455 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc); 5456 } 5457 5458 Ld = Sc.getOperand(0); 5459 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5460 Ld.getOpcode() == ISD::ConstantFP); 5461 5462 // The scalar_to_vector node and the suspected 5463 // load node must have exactly one user. 5464 // Constants may have multiple users. 5465 5466 // AVX-512 has register version of the broadcast 5467 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() && 5468 Ld.getValueType().getSizeInBits() >= 32; 5469 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) && 5470 !hasRegVer)) 5471 return SDValue(); 5472 break; 5473 } 5474 } 5475 5476 bool IsGE256 = (VT.getSizeInBits() >= 256); 5477 5478 // Handle the broadcasting a single constant scalar from the constant pool 5479 // into a vector. On Sandybridge it is still better to load a constant vector 5480 // from the constant pool and not to broadcast it from a scalar. 5481 if (ConstSplatVal && Subtarget->hasInt256()) { 5482 EVT CVT = Ld.getValueType(); 5483 assert(!CVT.isVector() && "Must not broadcast a vector type"); 5484 unsigned ScalarSize = CVT.getSizeInBits(); 5485 5486 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) { 5487 const Constant *C = 0; 5488 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld)) 5489 C = CI->getConstantIntValue(); 5490 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld)) 5491 C = CF->getConstantFPValue(); 5492 5493 assert(C && "Invalid constant type"); 5494 5495 SDValue CP = DAG.getConstantPool(C, getPointerTy()); 5496 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment(); 5497 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP, 5498 MachinePointerInfo::getConstantPool(), 5499 false, false, false, Alignment); 5500 5501 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5502 } 5503 } 5504 5505 bool IsLoad = ISD::isNormalLoad(Ld.getNode()); 5506 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5507 5508 // Handle AVX2 in-register broadcasts. 5509 if (!IsLoad && Subtarget->hasInt256() && 5510 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))) 5511 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5512 5513 // The scalar source must be a normal load. 5514 if (!IsLoad) 5515 return SDValue(); 5516 5517 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) 5518 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5519 5520 // The integer check is needed for the 64-bit into 128-bit so it doesn't match 5521 // double since there is no vbroadcastsd xmm 5522 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) { 5523 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64) 5524 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5525 } 5526 5527 // Unsupported broadcast. 5528 return SDValue(); 5529 } 5530 5531 SDValue 5532 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const { 5533 EVT VT = Op.getValueType(); 5534 5535 // Skip if insert_vec_elt is not supported. 5536 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT)) 5537 return SDValue(); 5538 5539 SDLoc DL(Op); 5540 unsigned NumElems = Op.getNumOperands(); 5541 5542 SDValue VecIn1; 5543 SDValue VecIn2; 5544 SmallVector<unsigned, 4> InsertIndices; 5545 SmallVector<int, 8> Mask(NumElems, -1); 5546 5547 for (unsigned i = 0; i != NumElems; ++i) { 5548 unsigned Opc = Op.getOperand(i).getOpcode(); 5549 5550 if (Opc == ISD::UNDEF) 5551 continue; 5552 5553 if (Opc != ISD::EXTRACT_VECTOR_ELT) { 5554 // Quit if more than 1 elements need inserting. 5555 if (InsertIndices.size() > 1) 5556 return SDValue(); 5557 5558 InsertIndices.push_back(i); 5559 continue; 5560 } 5561 5562 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0); 5563 SDValue ExtIdx = Op.getOperand(i).getOperand(1); 5564 5565 // Quit if extracted from vector of different type. 5566 if (ExtractedFromVec.getValueType() != VT) 5567 return SDValue(); 5568 5569 // Quit if non-constant index. 5570 if (!isa<ConstantSDNode>(ExtIdx)) 5571 return SDValue(); 5572 5573 if (VecIn1.getNode() == 0) 5574 VecIn1 = ExtractedFromVec; 5575 else if (VecIn1 != ExtractedFromVec) { 5576 if (VecIn2.getNode() == 0) 5577 VecIn2 = ExtractedFromVec; 5578 else if (VecIn2 != ExtractedFromVec) 5579 // Quit if more than 2 vectors to shuffle 5580 return SDValue(); 5581 } 5582 5583 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue(); 5584 5585 if (ExtractedFromVec == VecIn1) 5586 Mask[i] = Idx; 5587 else if (ExtractedFromVec == VecIn2) 5588 Mask[i] = Idx + NumElems; 5589 } 5590 5591 if (VecIn1.getNode() == 0) 5592 return SDValue(); 5593 5594 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 5595 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]); 5596 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) { 5597 unsigned Idx = InsertIndices[i]; 5598 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx), 5599 DAG.getIntPtrConstant(Idx)); 5600 } 5601 5602 return NV; 5603 } 5604 5605 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types. 5606 SDValue 5607 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const { 5608 5609 EVT VT = Op.getValueType(); 5610 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) && 5611 "Unexpected type in LowerBUILD_VECTORvXi1!"); 5612 5613 SDLoc dl(Op); 5614 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5615 SDValue Cst = DAG.getTargetConstant(0, MVT::i1); 5616 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst, 5617 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 5618 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 5619 Ops, VT.getVectorNumElements()); 5620 } 5621 5622 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5623 SDValue Cst = DAG.getTargetConstant(1, MVT::i1); 5624 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst, 5625 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 5626 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, 5627 Ops, VT.getVectorNumElements()); 5628 } 5629 5630 bool AllContants = true; 5631 uint64_t Immediate = 0; 5632 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) { 5633 SDValue In = Op.getOperand(idx); 5634 if (In.getOpcode() == ISD::UNDEF) 5635 continue; 5636 if (!isa<ConstantSDNode>(In)) { 5637 AllContants = false; 5638 break; 5639 } 5640 if (cast<ConstantSDNode>(In)->getZExtValue()) 5641 Immediate |= (1ULL << idx); 5642 } 5643 5644 if (AllContants) { 5645 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, 5646 DAG.getConstant(Immediate, MVT::i16)); 5647 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask, 5648 DAG.getIntPtrConstant(0)); 5649 } 5650 5651 if (!isSplatVector(Op.getNode())) 5652 llvm_unreachable("Unsupported predicate operation"); 5653 5654 SDValue In = Op.getOperand(0); 5655 SDValue EFLAGS, X86CC; 5656 if (In.getOpcode() == ISD::SETCC) { 5657 SDValue Op0 = In.getOperand(0); 5658 SDValue Op1 = In.getOperand(1); 5659 ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get(); 5660 bool isFP = Op1.getValueType().isFloatingPoint(); 5661 unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 5662 5663 assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation"); 5664 5665 X86CC = DAG.getConstant(X86CCVal, MVT::i8); 5666 EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG); 5667 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG); 5668 } else if (In.getOpcode() == X86ISD::SETCC) { 5669 X86CC = In.getOperand(0); 5670 EFLAGS = In.getOperand(1); 5671 } else { 5672 // The algorithm: 5673 // Bit1 = In & 0x1 5674 // if (Bit1 != 0) 5675 // ZF = 0 5676 // else 5677 // ZF = 1 5678 // if (ZF == 0) 5679 // res = allOnes ### CMOVNE -1, %res 5680 // else 5681 // res = allZero 5682 MVT InVT = In.getValueType().getSimpleVT(); 5683 SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT)); 5684 EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG); 5685 X86CC = DAG.getConstant(X86::COND_NE, MVT::i8); 5686 } 5687 5688 if (VT == MVT::v16i1) { 5689 SDValue Cst1 = DAG.getConstant(-1, MVT::i16); 5690 SDValue Cst0 = DAG.getConstant(0, MVT::i16); 5691 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16, 5692 Cst0, Cst1, X86CC, EFLAGS); 5693 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp); 5694 } 5695 5696 if (VT == MVT::v8i1) { 5697 SDValue Cst1 = DAG.getConstant(-1, MVT::i32); 5698 SDValue Cst0 = DAG.getConstant(0, MVT::i32); 5699 SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32, 5700 Cst0, Cst1, X86CC, EFLAGS); 5701 CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp); 5702 return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp); 5703 } 5704 llvm_unreachable("Unsupported predicate operation"); 5705 } 5706 5707 SDValue 5708 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5709 SDLoc dl(Op); 5710 5711 MVT VT = Op.getValueType().getSimpleVT(); 5712 MVT ExtVT = VT.getVectorElementType(); 5713 unsigned NumElems = Op.getNumOperands(); 5714 5715 // Generate vectors for predicate vectors. 5716 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512()) 5717 return LowerBUILD_VECTORvXi1(Op, DAG); 5718 5719 // Vectors containing all zeros can be matched by pxor and xorps later 5720 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5721 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5722 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5723 if (VT == MVT::v4i32 || VT == MVT::v8i32) 5724 return Op; 5725 5726 return getZeroVector(VT, Subtarget, DAG, dl); 5727 } 5728 5729 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5730 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use 5731 // vpcmpeqd on 256-bit vectors. 5732 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) { 5733 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256())) 5734 return Op; 5735 5736 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl); 5737 } 5738 5739 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 5740 if (Broadcast.getNode()) 5741 return Broadcast; 5742 5743 unsigned EVTBits = ExtVT.getSizeInBits(); 5744 5745 unsigned NumZero = 0; 5746 unsigned NumNonZero = 0; 5747 unsigned NonZeros = 0; 5748 bool IsAllConstants = true; 5749 SmallSet<SDValue, 8> Values; 5750 for (unsigned i = 0; i < NumElems; ++i) { 5751 SDValue Elt = Op.getOperand(i); 5752 if (Elt.getOpcode() == ISD::UNDEF) 5753 continue; 5754 Values.insert(Elt); 5755 if (Elt.getOpcode() != ISD::Constant && 5756 Elt.getOpcode() != ISD::ConstantFP) 5757 IsAllConstants = false; 5758 if (X86::isZeroNode(Elt)) 5759 NumZero++; 5760 else { 5761 NonZeros |= (1 << i); 5762 NumNonZero++; 5763 } 5764 } 5765 5766 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5767 if (NumNonZero == 0) 5768 return DAG.getUNDEF(VT); 5769 5770 // Special case for single non-zero, non-undef, element. 5771 if (NumNonZero == 1) { 5772 unsigned Idx = countTrailingZeros(NonZeros); 5773 SDValue Item = Op.getOperand(Idx); 5774 5775 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5776 // the value are obviously zero, truncate the value to i32 and do the 5777 // insertion that way. Only do this if the value is non-constant or if the 5778 // value is a constant being inserted into element 0. It is cheaper to do 5779 // a constant pool load than it is to do a movd + shuffle. 5780 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5781 (!IsAllConstants || Idx == 0)) { 5782 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5783 // Handle SSE only. 5784 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5785 EVT VecVT = MVT::v4i32; 5786 unsigned VecElts = 4; 5787 5788 // Truncate the value (which may itself be a constant) to i32, and 5789 // convert it to a vector with movd (S2V+shuffle to zero extend). 5790 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5791 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5792 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5793 5794 // Now we have our 32-bit value zero extended in the low element of 5795 // a vector. If Idx != 0, swizzle it into place. 5796 if (Idx != 0) { 5797 SmallVector<int, 4> Mask; 5798 Mask.push_back(Idx); 5799 for (unsigned i = 1; i != VecElts; ++i) 5800 Mask.push_back(i); 5801 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT), 5802 &Mask[0]); 5803 } 5804 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5805 } 5806 } 5807 5808 // If we have a constant or non-constant insertion into the low element of 5809 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5810 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5811 // depending on what the source datatype is. 5812 if (Idx == 0) { 5813 if (NumZero == 0) 5814 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5815 5816 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5817 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5818 if (VT.is256BitVector()) { 5819 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl); 5820 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec, 5821 Item, DAG.getIntPtrConstant(0)); 5822 } 5823 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5824 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5825 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5826 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5827 } 5828 5829 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5830 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5831 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item); 5832 if (VT.is256BitVector()) { 5833 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl); 5834 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl); 5835 } else { 5836 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5837 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5838 } 5839 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5840 } 5841 } 5842 5843 // Is it a vector logical left shift? 5844 if (NumElems == 2 && Idx == 1 && 5845 X86::isZeroNode(Op.getOperand(0)) && 5846 !X86::isZeroNode(Op.getOperand(1))) { 5847 unsigned NumBits = VT.getSizeInBits(); 5848 return getVShift(true, VT, 5849 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5850 VT, Op.getOperand(1)), 5851 NumBits/2, DAG, *this, dl); 5852 } 5853 5854 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5855 return SDValue(); 5856 5857 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5858 // is a non-constant being inserted into an element other than the low one, 5859 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5860 // movd/movss) to move this into the low element, then shuffle it into 5861 // place. 5862 if (EVTBits == 32) { 5863 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5864 5865 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5866 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG); 5867 SmallVector<int, 8> MaskVec; 5868 for (unsigned i = 0; i != NumElems; ++i) 5869 MaskVec.push_back(i == Idx ? 0 : 1); 5870 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5871 } 5872 } 5873 5874 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5875 if (Values.size() == 1) { 5876 if (EVTBits == 32) { 5877 // Instead of a shuffle like this: 5878 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5879 // Check if it's possible to issue this instead. 5880 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5881 unsigned Idx = countTrailingZeros(NonZeros); 5882 SDValue Item = Op.getOperand(Idx); 5883 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5884 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5885 } 5886 return SDValue(); 5887 } 5888 5889 // A vector full of immediates; various special cases are already 5890 // handled, so this is best done with a single constant-pool load. 5891 if (IsAllConstants) 5892 return SDValue(); 5893 5894 // For AVX-length vectors, build the individual 128-bit pieces and use 5895 // shuffles to put them in place. 5896 if (VT.is256BitVector()) { 5897 SmallVector<SDValue, 32> V; 5898 for (unsigned i = 0; i != NumElems; ++i) 5899 V.push_back(Op.getOperand(i)); 5900 5901 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5902 5903 // Build both the lower and upper subvector. 5904 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5905 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5906 NumElems/2); 5907 5908 // Recreate the wider vector with the lower and upper part. 5909 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl); 5910 } 5911 5912 // Let legalizer expand 2-wide build_vectors. 5913 if (EVTBits == 64) { 5914 if (NumNonZero == 1) { 5915 // One half is zero or undef. 5916 unsigned Idx = countTrailingZeros(NonZeros); 5917 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5918 Op.getOperand(Idx)); 5919 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG); 5920 } 5921 return SDValue(); 5922 } 5923 5924 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5925 if (EVTBits == 8 && NumElems == 16) { 5926 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5927 Subtarget, *this); 5928 if (V.getNode()) return V; 5929 } 5930 5931 if (EVTBits == 16 && NumElems == 8) { 5932 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5933 Subtarget, *this); 5934 if (V.getNode()) return V; 5935 } 5936 5937 // If element VT is == 32 bits, turn it into a number of shuffles. 5938 SmallVector<SDValue, 8> V(NumElems); 5939 if (NumElems == 4 && NumZero > 0) { 5940 for (unsigned i = 0; i < 4; ++i) { 5941 bool isZero = !(NonZeros & (1 << i)); 5942 if (isZero) 5943 V[i] = getZeroVector(VT, Subtarget, DAG, dl); 5944 else 5945 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5946 } 5947 5948 for (unsigned i = 0; i < 2; ++i) { 5949 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5950 default: break; 5951 case 0: 5952 V[i] = V[i*2]; // Must be a zero vector. 5953 break; 5954 case 1: 5955 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5956 break; 5957 case 2: 5958 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5959 break; 5960 case 3: 5961 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5962 break; 5963 } 5964 } 5965 5966 bool Reverse1 = (NonZeros & 0x3) == 2; 5967 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5968 int MaskVec[] = { 5969 Reverse1 ? 1 : 0, 5970 Reverse1 ? 0 : 1, 5971 static_cast<int>(Reverse2 ? NumElems+1 : NumElems), 5972 static_cast<int>(Reverse2 ? NumElems : NumElems+1) 5973 }; 5974 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5975 } 5976 5977 if (Values.size() > 1 && VT.is128BitVector()) { 5978 // Check for a build vector of consecutive loads. 5979 for (unsigned i = 0; i < NumElems; ++i) 5980 V[i] = Op.getOperand(i); 5981 5982 // Check for elements which are consecutive loads. 5983 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5984 if (LD.getNode()) 5985 return LD; 5986 5987 // Check for a build vector from mostly shuffle plus few inserting. 5988 SDValue Sh = buildFromShuffleMostly(Op, DAG); 5989 if (Sh.getNode()) 5990 return Sh; 5991 5992 // For SSE 4.1, use insertps to put the high elements into the low element. 5993 if (getSubtarget()->hasSSE41()) { 5994 SDValue Result; 5995 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5996 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5997 else 5998 Result = DAG.getUNDEF(VT); 5999 6000 for (unsigned i = 1; i < NumElems; ++i) { 6001 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 6002 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 6003 Op.getOperand(i), DAG.getIntPtrConstant(i)); 6004 } 6005 return Result; 6006 } 6007 6008 // Otherwise, expand into a number of unpckl*, start by extending each of 6009 // our (non-undef) elements to the full vector width with the element in the 6010 // bottom slot of the vector (which generates no code for SSE). 6011 for (unsigned i = 0; i < NumElems; ++i) { 6012 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 6013 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 6014 else 6015 V[i] = DAG.getUNDEF(VT); 6016 } 6017 6018 // Next, we iteratively mix elements, e.g. for v4f32: 6019 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 6020 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 6021 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 6022 unsigned EltStride = NumElems >> 1; 6023 while (EltStride != 0) { 6024 for (unsigned i = 0; i < EltStride; ++i) { 6025 // If V[i+EltStride] is undef and this is the first round of mixing, 6026 // then it is safe to just drop this shuffle: V[i] is already in the 6027 // right place, the one element (since it's the first round) being 6028 // inserted as undef can be dropped. This isn't safe for successive 6029 // rounds because they will permute elements within both vectors. 6030 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 6031 EltStride == NumElems/2) 6032 continue; 6033 6034 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 6035 } 6036 EltStride >>= 1; 6037 } 6038 return V[0]; 6039 } 6040 return SDValue(); 6041 } 6042 6043 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 6044 // to create 256-bit vectors from two other 128-bit ones. 6045 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6046 SDLoc dl(Op); 6047 MVT ResVT = Op.getValueType().getSimpleVT(); 6048 6049 assert((ResVT.is256BitVector() || 6050 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide"); 6051 6052 SDValue V1 = Op.getOperand(0); 6053 SDValue V2 = Op.getOperand(1); 6054 unsigned NumElems = ResVT.getVectorNumElements(); 6055 if(ResVT.is256BitVector()) 6056 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl); 6057 6058 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl); 6059 } 6060 6061 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 6062 assert(Op.getNumOperands() == 2); 6063 6064 // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors 6065 // from two other 128-bit ones. 6066 return LowerAVXCONCAT_VECTORS(Op, DAG); 6067 } 6068 6069 // Try to lower a shuffle node into a simple blend instruction. 6070 static SDValue 6071 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp, 6072 const X86Subtarget *Subtarget, SelectionDAG &DAG) { 6073 SDValue V1 = SVOp->getOperand(0); 6074 SDValue V2 = SVOp->getOperand(1); 6075 SDLoc dl(SVOp); 6076 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6077 MVT EltVT = VT.getVectorElementType(); 6078 unsigned NumElems = VT.getVectorNumElements(); 6079 6080 if (!Subtarget->hasSSE41() || EltVT == MVT::i8) 6081 return SDValue(); 6082 if (!Subtarget->hasInt256() && VT == MVT::v16i16) 6083 return SDValue(); 6084 6085 // Check the mask for BLEND and build the value. 6086 unsigned MaskValue = 0; 6087 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise. 6088 unsigned NumLanes = (NumElems-1)/8 + 1; 6089 unsigned NumElemsInLane = NumElems / NumLanes; 6090 6091 // Blend for v16i16 should be symetric for the both lanes. 6092 for (unsigned i = 0; i < NumElemsInLane; ++i) { 6093 6094 int SndLaneEltIdx = (NumLanes == 2) ? 6095 SVOp->getMaskElt(i + NumElemsInLane) : -1; 6096 int EltIdx = SVOp->getMaskElt(i); 6097 6098 if ((EltIdx < 0 || EltIdx == (int)i) && 6099 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane))) 6100 continue; 6101 6102 if (((unsigned)EltIdx == (i + NumElems)) && 6103 (SndLaneEltIdx < 0 || 6104 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane)) 6105 MaskValue |= (1<<i); 6106 else 6107 return SDValue(); 6108 } 6109 6110 // Convert i32 vectors to floating point if it is not AVX2. 6111 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors. 6112 MVT BlendVT = VT; 6113 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) { 6114 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()), 6115 NumElems); 6116 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1); 6117 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2); 6118 } 6119 6120 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2, 6121 DAG.getConstant(MaskValue, MVT::i32)); 6122 return DAG.getNode(ISD::BITCAST, dl, VT, Ret); 6123 } 6124 6125 // v8i16 shuffles - Prefer shuffles in the following order: 6126 // 1. [all] pshuflw, pshufhw, optional move 6127 // 2. [ssse3] 1 x pshufb 6128 // 3. [ssse3] 2 x pshufb + 1 x por 6129 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 6130 static SDValue 6131 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget, 6132 SelectionDAG &DAG) { 6133 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6134 SDValue V1 = SVOp->getOperand(0); 6135 SDValue V2 = SVOp->getOperand(1); 6136 SDLoc dl(SVOp); 6137 SmallVector<int, 8> MaskVals; 6138 6139 // Determine if more than 1 of the words in each of the low and high quadwords 6140 // of the result come from the same quadword of one of the two inputs. Undef 6141 // mask values count as coming from any quadword, for better codegen. 6142 unsigned LoQuad[] = { 0, 0, 0, 0 }; 6143 unsigned HiQuad[] = { 0, 0, 0, 0 }; 6144 std::bitset<4> InputQuads; 6145 for (unsigned i = 0; i < 8; ++i) { 6146 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 6147 int EltIdx = SVOp->getMaskElt(i); 6148 MaskVals.push_back(EltIdx); 6149 if (EltIdx < 0) { 6150 ++Quad[0]; 6151 ++Quad[1]; 6152 ++Quad[2]; 6153 ++Quad[3]; 6154 continue; 6155 } 6156 ++Quad[EltIdx / 4]; 6157 InputQuads.set(EltIdx / 4); 6158 } 6159 6160 int BestLoQuad = -1; 6161 unsigned MaxQuad = 1; 6162 for (unsigned i = 0; i < 4; ++i) { 6163 if (LoQuad[i] > MaxQuad) { 6164 BestLoQuad = i; 6165 MaxQuad = LoQuad[i]; 6166 } 6167 } 6168 6169 int BestHiQuad = -1; 6170 MaxQuad = 1; 6171 for (unsigned i = 0; i < 4; ++i) { 6172 if (HiQuad[i] > MaxQuad) { 6173 BestHiQuad = i; 6174 MaxQuad = HiQuad[i]; 6175 } 6176 } 6177 6178 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 6179 // of the two input vectors, shuffle them into one input vector so only a 6180 // single pshufb instruction is necessary. If There are more than 2 input 6181 // quads, disable the next transformation since it does not help SSSE3. 6182 bool V1Used = InputQuads[0] || InputQuads[1]; 6183 bool V2Used = InputQuads[2] || InputQuads[3]; 6184 if (Subtarget->hasSSSE3()) { 6185 if (InputQuads.count() == 2 && V1Used && V2Used) { 6186 BestLoQuad = InputQuads[0] ? 0 : 1; 6187 BestHiQuad = InputQuads[2] ? 2 : 3; 6188 } 6189 if (InputQuads.count() > 2) { 6190 BestLoQuad = -1; 6191 BestHiQuad = -1; 6192 } 6193 } 6194 6195 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 6196 // the shuffle mask. If a quad is scored as -1, that means that it contains 6197 // words from all 4 input quadwords. 6198 SDValue NewV; 6199 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 6200 int MaskV[] = { 6201 BestLoQuad < 0 ? 0 : BestLoQuad, 6202 BestHiQuad < 0 ? 1 : BestHiQuad 6203 }; 6204 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 6205 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 6206 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 6207 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 6208 6209 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 6210 // source words for the shuffle, to aid later transformations. 6211 bool AllWordsInNewV = true; 6212 bool InOrder[2] = { true, true }; 6213 for (unsigned i = 0; i != 8; ++i) { 6214 int idx = MaskVals[i]; 6215 if (idx != (int)i) 6216 InOrder[i/4] = false; 6217 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 6218 continue; 6219 AllWordsInNewV = false; 6220 break; 6221 } 6222 6223 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 6224 if (AllWordsInNewV) { 6225 for (int i = 0; i != 8; ++i) { 6226 int idx = MaskVals[i]; 6227 if (idx < 0) 6228 continue; 6229 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 6230 if ((idx != i) && idx < 4) 6231 pshufhw = false; 6232 if ((idx != i) && idx > 3) 6233 pshuflw = false; 6234 } 6235 V1 = NewV; 6236 V2Used = false; 6237 BestLoQuad = 0; 6238 BestHiQuad = 1; 6239 } 6240 6241 // If we've eliminated the use of V2, and the new mask is a pshuflw or 6242 // pshufhw, that's as cheap as it gets. Return the new shuffle. 6243 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 6244 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 6245 unsigned TargetMask = 0; 6246 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 6247 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 6248 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 6249 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp): 6250 getShufflePSHUFLWImmediate(SVOp); 6251 V1 = NewV.getOperand(0); 6252 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 6253 } 6254 } 6255 6256 // Promote splats to a larger type which usually leads to more efficient code. 6257 // FIXME: Is this true if pshufb is available? 6258 if (SVOp->isSplat()) 6259 return PromoteSplat(SVOp, DAG); 6260 6261 // If we have SSSE3, and all words of the result are from 1 input vector, 6262 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 6263 // is present, fall back to case 4. 6264 if (Subtarget->hasSSSE3()) { 6265 SmallVector<SDValue,16> pshufbMask; 6266 6267 // If we have elements from both input vectors, set the high bit of the 6268 // shuffle mask element to zero out elements that come from V2 in the V1 6269 // mask, and elements that come from V1 in the V2 mask, so that the two 6270 // results can be OR'd together. 6271 bool TwoInputs = V1Used && V2Used; 6272 for (unsigned i = 0; i != 8; ++i) { 6273 int EltIdx = MaskVals[i] * 2; 6274 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx; 6275 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1; 6276 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 6277 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 6278 } 6279 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 6280 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 6281 DAG.getNode(ISD::BUILD_VECTOR, dl, 6282 MVT::v16i8, &pshufbMask[0], 16)); 6283 if (!TwoInputs) 6284 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 6285 6286 // Calculate the shuffle mask for the second input, shuffle it, and 6287 // OR it with the first shuffled input. 6288 pshufbMask.clear(); 6289 for (unsigned i = 0; i != 8; ++i) { 6290 int EltIdx = MaskVals[i] * 2; 6291 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16; 6292 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15; 6293 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 6294 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 6295 } 6296 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 6297 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 6298 DAG.getNode(ISD::BUILD_VECTOR, dl, 6299 MVT::v16i8, &pshufbMask[0], 16)); 6300 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 6301 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 6302 } 6303 6304 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 6305 // and update MaskVals with new element order. 6306 std::bitset<8> InOrder; 6307 if (BestLoQuad >= 0) { 6308 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 }; 6309 for (int i = 0; i != 4; ++i) { 6310 int idx = MaskVals[i]; 6311 if (idx < 0) { 6312 InOrder.set(i); 6313 } else if ((idx / 4) == BestLoQuad) { 6314 MaskV[i] = idx & 3; 6315 InOrder.set(i); 6316 } 6317 } 6318 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 6319 &MaskV[0]); 6320 6321 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 6322 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 6323 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 6324 NewV.getOperand(0), 6325 getShufflePSHUFLWImmediate(SVOp), DAG); 6326 } 6327 } 6328 6329 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 6330 // and update MaskVals with the new element order. 6331 if (BestHiQuad >= 0) { 6332 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 }; 6333 for (unsigned i = 4; i != 8; ++i) { 6334 int idx = MaskVals[i]; 6335 if (idx < 0) { 6336 InOrder.set(i); 6337 } else if ((idx / 4) == BestHiQuad) { 6338 MaskV[i] = (idx & 3) + 4; 6339 InOrder.set(i); 6340 } 6341 } 6342 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 6343 &MaskV[0]); 6344 6345 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 6346 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 6347 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 6348 NewV.getOperand(0), 6349 getShufflePSHUFHWImmediate(SVOp), DAG); 6350 } 6351 } 6352 6353 // In case BestHi & BestLo were both -1, which means each quadword has a word 6354 // from each of the four input quadwords, calculate the InOrder bitvector now 6355 // before falling through to the insert/extract cleanup. 6356 if (BestLoQuad == -1 && BestHiQuad == -1) { 6357 NewV = V1; 6358 for (int i = 0; i != 8; ++i) 6359 if (MaskVals[i] < 0 || MaskVals[i] == i) 6360 InOrder.set(i); 6361 } 6362 6363 // The other elements are put in the right place using pextrw and pinsrw. 6364 for (unsigned i = 0; i != 8; ++i) { 6365 if (InOrder[i]) 6366 continue; 6367 int EltIdx = MaskVals[i]; 6368 if (EltIdx < 0) 6369 continue; 6370 SDValue ExtOp = (EltIdx < 8) ? 6371 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 6372 DAG.getIntPtrConstant(EltIdx)) : 6373 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 6374 DAG.getIntPtrConstant(EltIdx - 8)); 6375 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 6376 DAG.getIntPtrConstant(i)); 6377 } 6378 return NewV; 6379 } 6380 6381 // v16i8 shuffles - Prefer shuffles in the following order: 6382 // 1. [ssse3] 1 x pshufb 6383 // 2. [ssse3] 2 x pshufb + 1 x por 6384 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 6385 static 6386 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 6387 SelectionDAG &DAG, 6388 const X86TargetLowering &TLI) { 6389 SDValue V1 = SVOp->getOperand(0); 6390 SDValue V2 = SVOp->getOperand(1); 6391 SDLoc dl(SVOp); 6392 ArrayRef<int> MaskVals = SVOp->getMask(); 6393 6394 // Promote splats to a larger type which usually leads to more efficient code. 6395 // FIXME: Is this true if pshufb is available? 6396 if (SVOp->isSplat()) 6397 return PromoteSplat(SVOp, DAG); 6398 6399 // If we have SSSE3, case 1 is generated when all result bytes come from 6400 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 6401 // present, fall back to case 3. 6402 6403 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 6404 if (TLI.getSubtarget()->hasSSSE3()) { 6405 SmallVector<SDValue,16> pshufbMask; 6406 6407 // If all result elements are from one input vector, then only translate 6408 // undef mask values to 0x80 (zero out result) in the pshufb mask. 6409 // 6410 // Otherwise, we have elements from both input vectors, and must zero out 6411 // elements that come from V2 in the first mask, and V1 in the second mask 6412 // so that we can OR them together. 6413 for (unsigned i = 0; i != 16; ++i) { 6414 int EltIdx = MaskVals[i]; 6415 if (EltIdx < 0 || EltIdx >= 16) 6416 EltIdx = 0x80; 6417 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6418 } 6419 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 6420 DAG.getNode(ISD::BUILD_VECTOR, dl, 6421 MVT::v16i8, &pshufbMask[0], 16)); 6422 6423 // As PSHUFB will zero elements with negative indices, it's safe to ignore 6424 // the 2nd operand if it's undefined or zero. 6425 if (V2.getOpcode() == ISD::UNDEF || 6426 ISD::isBuildVectorAllZeros(V2.getNode())) 6427 return V1; 6428 6429 // Calculate the shuffle mask for the second input, shuffle it, and 6430 // OR it with the first shuffled input. 6431 pshufbMask.clear(); 6432 for (unsigned i = 0; i != 16; ++i) { 6433 int EltIdx = MaskVals[i]; 6434 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16; 6435 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6436 } 6437 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 6438 DAG.getNode(ISD::BUILD_VECTOR, dl, 6439 MVT::v16i8, &pshufbMask[0], 16)); 6440 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 6441 } 6442 6443 // No SSSE3 - Calculate in place words and then fix all out of place words 6444 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 6445 // the 16 different words that comprise the two doublequadword input vectors. 6446 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 6447 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 6448 SDValue NewV = V1; 6449 for (int i = 0; i != 8; ++i) { 6450 int Elt0 = MaskVals[i*2]; 6451 int Elt1 = MaskVals[i*2+1]; 6452 6453 // This word of the result is all undef, skip it. 6454 if (Elt0 < 0 && Elt1 < 0) 6455 continue; 6456 6457 // This word of the result is already in the correct place, skip it. 6458 if ((Elt0 == i*2) && (Elt1 == i*2+1)) 6459 continue; 6460 6461 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 6462 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 6463 SDValue InsElt; 6464 6465 // If Elt0 and Elt1 are defined, are consecutive, and can be load 6466 // using a single extract together, load it and store it. 6467 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 6468 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6469 DAG.getIntPtrConstant(Elt1 / 2)); 6470 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6471 DAG.getIntPtrConstant(i)); 6472 continue; 6473 } 6474 6475 // If Elt1 is defined, extract it from the appropriate source. If the 6476 // source byte is not also odd, shift the extracted word left 8 bits 6477 // otherwise clear the bottom 8 bits if we need to do an or. 6478 if (Elt1 >= 0) { 6479 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6480 DAG.getIntPtrConstant(Elt1 / 2)); 6481 if ((Elt1 & 1) == 0) 6482 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 6483 DAG.getConstant(8, 6484 TLI.getShiftAmountTy(InsElt.getValueType()))); 6485 else if (Elt0 >= 0) 6486 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 6487 DAG.getConstant(0xFF00, MVT::i16)); 6488 } 6489 // If Elt0 is defined, extract it from the appropriate source. If the 6490 // source byte is not also even, shift the extracted word right 8 bits. If 6491 // Elt1 was also defined, OR the extracted values together before 6492 // inserting them in the result. 6493 if (Elt0 >= 0) { 6494 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 6495 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 6496 if ((Elt0 & 1) != 0) 6497 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 6498 DAG.getConstant(8, 6499 TLI.getShiftAmountTy(InsElt0.getValueType()))); 6500 else if (Elt1 >= 0) 6501 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 6502 DAG.getConstant(0x00FF, MVT::i16)); 6503 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 6504 : InsElt0; 6505 } 6506 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6507 DAG.getIntPtrConstant(i)); 6508 } 6509 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 6510 } 6511 6512 // v32i8 shuffles - Translate to VPSHUFB if possible. 6513 static 6514 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp, 6515 const X86Subtarget *Subtarget, 6516 SelectionDAG &DAG) { 6517 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6518 SDValue V1 = SVOp->getOperand(0); 6519 SDValue V2 = SVOp->getOperand(1); 6520 SDLoc dl(SVOp); 6521 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end()); 6522 6523 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6524 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode()); 6525 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode()); 6526 6527 // VPSHUFB may be generated if 6528 // (1) one of input vector is undefined or zeroinitializer. 6529 // The mask value 0x80 puts 0 in the corresponding slot of the vector. 6530 // And (2) the mask indexes don't cross the 128-bit lane. 6531 if (VT != MVT::v32i8 || !Subtarget->hasInt256() || 6532 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero)) 6533 return SDValue(); 6534 6535 if (V1IsAllZero && !V2IsAllZero) { 6536 CommuteVectorShuffleMask(MaskVals, 32); 6537 V1 = V2; 6538 } 6539 SmallVector<SDValue, 32> pshufbMask; 6540 for (unsigned i = 0; i != 32; i++) { 6541 int EltIdx = MaskVals[i]; 6542 if (EltIdx < 0 || EltIdx >= 32) 6543 EltIdx = 0x80; 6544 else { 6545 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16)) 6546 // Cross lane is not allowed. 6547 return SDValue(); 6548 EltIdx &= 0xf; 6549 } 6550 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6551 } 6552 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1, 6553 DAG.getNode(ISD::BUILD_VECTOR, dl, 6554 MVT::v32i8, &pshufbMask[0], 32)); 6555 } 6556 6557 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 6558 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 6559 /// done when every pair / quad of shuffle mask elements point to elements in 6560 /// the right sequence. e.g. 6561 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 6562 static 6563 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 6564 SelectionDAG &DAG) { 6565 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6566 SDLoc dl(SVOp); 6567 unsigned NumElems = VT.getVectorNumElements(); 6568 MVT NewVT; 6569 unsigned Scale; 6570 switch (VT.SimpleTy) { 6571 default: llvm_unreachable("Unexpected!"); 6572 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break; 6573 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break; 6574 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break; 6575 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break; 6576 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break; 6577 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break; 6578 } 6579 6580 SmallVector<int, 8> MaskVec; 6581 for (unsigned i = 0; i != NumElems; i += Scale) { 6582 int StartIdx = -1; 6583 for (unsigned j = 0; j != Scale; ++j) { 6584 int EltIdx = SVOp->getMaskElt(i+j); 6585 if (EltIdx < 0) 6586 continue; 6587 if (StartIdx < 0) 6588 StartIdx = (EltIdx / Scale); 6589 if (EltIdx != (int)(StartIdx*Scale + j)) 6590 return SDValue(); 6591 } 6592 MaskVec.push_back(StartIdx); 6593 } 6594 6595 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0)); 6596 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1)); 6597 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 6598 } 6599 6600 /// getVZextMovL - Return a zero-extending vector move low node. 6601 /// 6602 static SDValue getVZextMovL(MVT VT, EVT OpVT, 6603 SDValue SrcOp, SelectionDAG &DAG, 6604 const X86Subtarget *Subtarget, SDLoc dl) { 6605 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 6606 LoadSDNode *LD = NULL; 6607 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 6608 LD = dyn_cast<LoadSDNode>(SrcOp); 6609 if (!LD) { 6610 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 6611 // instead. 6612 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 6613 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 6614 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 6615 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 6616 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 6617 // PR2108 6618 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 6619 return DAG.getNode(ISD::BITCAST, dl, VT, 6620 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6621 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6622 OpVT, 6623 SrcOp.getOperand(0) 6624 .getOperand(0)))); 6625 } 6626 } 6627 } 6628 6629 return DAG.getNode(ISD::BITCAST, dl, VT, 6630 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6631 DAG.getNode(ISD::BITCAST, dl, 6632 OpVT, SrcOp))); 6633 } 6634 6635 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6636 /// which could not be matched by any known target speficic shuffle 6637 static SDValue 6638 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6639 6640 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG); 6641 if (NewOp.getNode()) 6642 return NewOp; 6643 6644 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6645 6646 unsigned NumElems = VT.getVectorNumElements(); 6647 unsigned NumLaneElems = NumElems / 2; 6648 6649 SDLoc dl(SVOp); 6650 MVT EltVT = VT.getVectorElementType(); 6651 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems); 6652 SDValue Output[2]; 6653 6654 SmallVector<int, 16> Mask; 6655 for (unsigned l = 0; l < 2; ++l) { 6656 // Build a shuffle mask for the output, discovering on the fly which 6657 // input vectors to use as shuffle operands (recorded in InputUsed). 6658 // If building a suitable shuffle vector proves too hard, then bail 6659 // out with UseBuildVector set. 6660 bool UseBuildVector = false; 6661 int InputUsed[2] = { -1, -1 }; // Not yet discovered. 6662 unsigned LaneStart = l * NumLaneElems; 6663 for (unsigned i = 0; i != NumLaneElems; ++i) { 6664 // The mask element. This indexes into the input. 6665 int Idx = SVOp->getMaskElt(i+LaneStart); 6666 if (Idx < 0) { 6667 // the mask element does not index into any input vector. 6668 Mask.push_back(-1); 6669 continue; 6670 } 6671 6672 // The input vector this mask element indexes into. 6673 int Input = Idx / NumLaneElems; 6674 6675 // Turn the index into an offset from the start of the input vector. 6676 Idx -= Input * NumLaneElems; 6677 6678 // Find or create a shuffle vector operand to hold this input. 6679 unsigned OpNo; 6680 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) { 6681 if (InputUsed[OpNo] == Input) 6682 // This input vector is already an operand. 6683 break; 6684 if (InputUsed[OpNo] < 0) { 6685 // Create a new operand for this input vector. 6686 InputUsed[OpNo] = Input; 6687 break; 6688 } 6689 } 6690 6691 if (OpNo >= array_lengthof(InputUsed)) { 6692 // More than two input vectors used! Give up on trying to create a 6693 // shuffle vector. Insert all elements into a BUILD_VECTOR instead. 6694 UseBuildVector = true; 6695 break; 6696 } 6697 6698 // Add the mask index for the new shuffle vector. 6699 Mask.push_back(Idx + OpNo * NumLaneElems); 6700 } 6701 6702 if (UseBuildVector) { 6703 SmallVector<SDValue, 16> SVOps; 6704 for (unsigned i = 0; i != NumLaneElems; ++i) { 6705 // The mask element. This indexes into the input. 6706 int Idx = SVOp->getMaskElt(i+LaneStart); 6707 if (Idx < 0) { 6708 SVOps.push_back(DAG.getUNDEF(EltVT)); 6709 continue; 6710 } 6711 6712 // The input vector this mask element indexes into. 6713 int Input = Idx / NumElems; 6714 6715 // Turn the index into an offset from the start of the input vector. 6716 Idx -= Input * NumElems; 6717 6718 // Extract the vector element by hand. 6719 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6720 SVOp->getOperand(Input), 6721 DAG.getIntPtrConstant(Idx))); 6722 } 6723 6724 // Construct the output using a BUILD_VECTOR. 6725 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0], 6726 SVOps.size()); 6727 } else if (InputUsed[0] < 0) { 6728 // No input vectors were used! The result is undefined. 6729 Output[l] = DAG.getUNDEF(NVT); 6730 } else { 6731 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2), 6732 (InputUsed[0] % 2) * NumLaneElems, 6733 DAG, dl); 6734 // If only one input was used, use an undefined vector for the other. 6735 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) : 6736 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2), 6737 (InputUsed[1] % 2) * NumLaneElems, DAG, dl); 6738 // At least one input vector was used. Create a new shuffle vector. 6739 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]); 6740 } 6741 6742 Mask.clear(); 6743 } 6744 6745 // Concatenate the result back 6746 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]); 6747 } 6748 6749 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6750 /// 4 elements, and match them with several different shuffle types. 6751 static SDValue 6752 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6753 SDValue V1 = SVOp->getOperand(0); 6754 SDValue V2 = SVOp->getOperand(1); 6755 SDLoc dl(SVOp); 6756 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6757 6758 assert(VT.is128BitVector() && "Unsupported vector size"); 6759 6760 std::pair<int, int> Locs[4]; 6761 int Mask1[] = { -1, -1, -1, -1 }; 6762 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end()); 6763 6764 unsigned NumHi = 0; 6765 unsigned NumLo = 0; 6766 for (unsigned i = 0; i != 4; ++i) { 6767 int Idx = PermMask[i]; 6768 if (Idx < 0) { 6769 Locs[i] = std::make_pair(-1, -1); 6770 } else { 6771 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6772 if (Idx < 4) { 6773 Locs[i] = std::make_pair(0, NumLo); 6774 Mask1[NumLo] = Idx; 6775 NumLo++; 6776 } else { 6777 Locs[i] = std::make_pair(1, NumHi); 6778 if (2+NumHi < 4) 6779 Mask1[2+NumHi] = Idx; 6780 NumHi++; 6781 } 6782 } 6783 } 6784 6785 if (NumLo <= 2 && NumHi <= 2) { 6786 // If no more than two elements come from either vector. This can be 6787 // implemented with two shuffles. First shuffle gather the elements. 6788 // The second shuffle, which takes the first shuffle as both of its 6789 // vector operands, put the elements into the right order. 6790 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6791 6792 int Mask2[] = { -1, -1, -1, -1 }; 6793 6794 for (unsigned i = 0; i != 4; ++i) 6795 if (Locs[i].first != -1) { 6796 unsigned Idx = (i < 2) ? 0 : 4; 6797 Idx += Locs[i].first * 2 + Locs[i].second; 6798 Mask2[i] = Idx; 6799 } 6800 6801 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6802 } 6803 6804 if (NumLo == 3 || NumHi == 3) { 6805 // Otherwise, we must have three elements from one vector, call it X, and 6806 // one element from the other, call it Y. First, use a shufps to build an 6807 // intermediate vector with the one element from Y and the element from X 6808 // that will be in the same half in the final destination (the indexes don't 6809 // matter). Then, use a shufps to build the final vector, taking the half 6810 // containing the element from Y from the intermediate, and the other half 6811 // from X. 6812 if (NumHi == 3) { 6813 // Normalize it so the 3 elements come from V1. 6814 CommuteVectorShuffleMask(PermMask, 4); 6815 std::swap(V1, V2); 6816 } 6817 6818 // Find the element from V2. 6819 unsigned HiIndex; 6820 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6821 int Val = PermMask[HiIndex]; 6822 if (Val < 0) 6823 continue; 6824 if (Val >= 4) 6825 break; 6826 } 6827 6828 Mask1[0] = PermMask[HiIndex]; 6829 Mask1[1] = -1; 6830 Mask1[2] = PermMask[HiIndex^1]; 6831 Mask1[3] = -1; 6832 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6833 6834 if (HiIndex >= 2) { 6835 Mask1[0] = PermMask[0]; 6836 Mask1[1] = PermMask[1]; 6837 Mask1[2] = HiIndex & 1 ? 6 : 4; 6838 Mask1[3] = HiIndex & 1 ? 4 : 6; 6839 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6840 } 6841 6842 Mask1[0] = HiIndex & 1 ? 2 : 0; 6843 Mask1[1] = HiIndex & 1 ? 0 : 2; 6844 Mask1[2] = PermMask[2]; 6845 Mask1[3] = PermMask[3]; 6846 if (Mask1[2] >= 0) 6847 Mask1[2] += 4; 6848 if (Mask1[3] >= 0) 6849 Mask1[3] += 4; 6850 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6851 } 6852 6853 // Break it into (shuffle shuffle_hi, shuffle_lo). 6854 int LoMask[] = { -1, -1, -1, -1 }; 6855 int HiMask[] = { -1, -1, -1, -1 }; 6856 6857 int *MaskPtr = LoMask; 6858 unsigned MaskIdx = 0; 6859 unsigned LoIdx = 0; 6860 unsigned HiIdx = 2; 6861 for (unsigned i = 0; i != 4; ++i) { 6862 if (i == 2) { 6863 MaskPtr = HiMask; 6864 MaskIdx = 1; 6865 LoIdx = 0; 6866 HiIdx = 2; 6867 } 6868 int Idx = PermMask[i]; 6869 if (Idx < 0) { 6870 Locs[i] = std::make_pair(-1, -1); 6871 } else if (Idx < 4) { 6872 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6873 MaskPtr[LoIdx] = Idx; 6874 LoIdx++; 6875 } else { 6876 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6877 MaskPtr[HiIdx] = Idx; 6878 HiIdx++; 6879 } 6880 } 6881 6882 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6883 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6884 int MaskOps[] = { -1, -1, -1, -1 }; 6885 for (unsigned i = 0; i != 4; ++i) 6886 if (Locs[i].first != -1) 6887 MaskOps[i] = Locs[i].first * 4 + Locs[i].second; 6888 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6889 } 6890 6891 static bool MayFoldVectorLoad(SDValue V) { 6892 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6893 V = V.getOperand(0); 6894 6895 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6896 V = V.getOperand(0); 6897 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6898 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6899 // BUILD_VECTOR (load), undef 6900 V = V.getOperand(0); 6901 6902 return MayFoldLoad(V); 6903 } 6904 6905 static 6906 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) { 6907 EVT VT = Op.getValueType(); 6908 6909 // Canonizalize to v2f64. 6910 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6911 return DAG.getNode(ISD::BITCAST, dl, VT, 6912 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6913 V1, DAG)); 6914 } 6915 6916 static 6917 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, 6918 bool HasSSE2) { 6919 SDValue V1 = Op.getOperand(0); 6920 SDValue V2 = Op.getOperand(1); 6921 EVT VT = Op.getValueType(); 6922 6923 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6924 6925 if (HasSSE2 && VT == MVT::v2f64) 6926 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6927 6928 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6929 return DAG.getNode(ISD::BITCAST, dl, VT, 6930 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6931 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6932 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6933 } 6934 6935 static 6936 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) { 6937 SDValue V1 = Op.getOperand(0); 6938 SDValue V2 = Op.getOperand(1); 6939 EVT VT = Op.getValueType(); 6940 6941 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6942 "unsupported shuffle type"); 6943 6944 if (V2.getOpcode() == ISD::UNDEF) 6945 V2 = V1; 6946 6947 // v4i32 or v4f32 6948 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6949 } 6950 6951 static 6952 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 6953 SDValue V1 = Op.getOperand(0); 6954 SDValue V2 = Op.getOperand(1); 6955 EVT VT = Op.getValueType(); 6956 unsigned NumElems = VT.getVectorNumElements(); 6957 6958 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6959 // operand of these instructions is only memory, so check if there's a 6960 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6961 // same masks. 6962 bool CanFoldLoad = false; 6963 6964 // Trivial case, when V2 comes from a load. 6965 if (MayFoldVectorLoad(V2)) 6966 CanFoldLoad = true; 6967 6968 // When V1 is a load, it can be folded later into a store in isel, example: 6969 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6970 // turns into: 6971 // (MOVLPSmr addr:$src1, VR128:$src2) 6972 // So, recognize this potential and also use MOVLPS or MOVLPD 6973 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6974 CanFoldLoad = true; 6975 6976 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6977 if (CanFoldLoad) { 6978 if (HasSSE2 && NumElems == 2) 6979 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6980 6981 if (NumElems == 4) 6982 // If we don't care about the second element, proceed to use movss. 6983 if (SVOp->getMaskElt(1) != -1) 6984 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6985 } 6986 6987 // movl and movlp will both match v2i64, but v2i64 is never matched by 6988 // movl earlier because we make it strict to avoid messing with the movlp load 6989 // folding logic (see the code above getMOVLP call). Match it here then, 6990 // this is horrible, but will stay like this until we move all shuffle 6991 // matching to x86 specific nodes. Note that for the 1st condition all 6992 // types are matched with movsd. 6993 if (HasSSE2) { 6994 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6995 // as to remove this logic from here, as much as possible 6996 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT)) 6997 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6998 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6999 } 7000 7001 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 7002 7003 // Invert the operand order and use SHUFPS to match it. 7004 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1, 7005 getShuffleSHUFImmediate(SVOp), DAG); 7006 } 7007 7008 // Reduce a vector shuffle to zext. 7009 SDValue 7010 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const { 7011 // PMOVZX is only available from SSE41. 7012 if (!Subtarget->hasSSE41()) 7013 return SDValue(); 7014 7015 EVT VT = Op.getValueType(); 7016 7017 // Only AVX2 support 256-bit vector integer extending. 7018 if (!Subtarget->hasInt256() && VT.is256BitVector()) 7019 return SDValue(); 7020 7021 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7022 SDLoc DL(Op); 7023 SDValue V1 = Op.getOperand(0); 7024 SDValue V2 = Op.getOperand(1); 7025 unsigned NumElems = VT.getVectorNumElements(); 7026 7027 // Extending is an unary operation and the element type of the source vector 7028 // won't be equal to or larger than i64. 7029 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() || 7030 VT.getVectorElementType() == MVT::i64) 7031 return SDValue(); 7032 7033 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4. 7034 unsigned Shift = 1; // Start from 2, i.e. 1 << 1. 7035 while ((1U << Shift) < NumElems) { 7036 if (SVOp->getMaskElt(1U << Shift) == 1) 7037 break; 7038 Shift += 1; 7039 // The maximal ratio is 8, i.e. from i8 to i64. 7040 if (Shift > 3) 7041 return SDValue(); 7042 } 7043 7044 // Check the shuffle mask. 7045 unsigned Mask = (1U << Shift) - 1; 7046 for (unsigned i = 0; i != NumElems; ++i) { 7047 int EltIdx = SVOp->getMaskElt(i); 7048 if ((i & Mask) != 0 && EltIdx != -1) 7049 return SDValue(); 7050 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift)) 7051 return SDValue(); 7052 } 7053 7054 LLVMContext *Context = DAG.getContext(); 7055 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift; 7056 EVT NeVT = EVT::getIntegerVT(*Context, NBits); 7057 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift); 7058 7059 if (!isTypeLegal(NVT)) 7060 return SDValue(); 7061 7062 // Simplify the operand as it's prepared to be fed into shuffle. 7063 unsigned SignificantBits = NVT.getSizeInBits() >> Shift; 7064 if (V1.getOpcode() == ISD::BITCAST && 7065 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 7066 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7067 V1.getOperand(0) 7068 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) { 7069 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x) 7070 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0); 7071 ConstantSDNode *CIdx = 7072 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1)); 7073 // If it's foldable, i.e. normal load with single use, we will let code 7074 // selection to fold it. Otherwise, we will short the conversion sequence. 7075 if (CIdx && CIdx->getZExtValue() == 0 && 7076 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) { 7077 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) { 7078 // The "ext_vec_elt" node is wider than the result node. 7079 // In this case we should extract subvector from V. 7080 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)). 7081 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits(); 7082 EVT FullVT = V.getValueType(); 7083 EVT SubVecVT = EVT::getVectorVT(*Context, 7084 FullVT.getVectorElementType(), 7085 FullVT.getVectorNumElements()/Ratio); 7086 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 7087 DAG.getIntPtrConstant(0)); 7088 } 7089 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V); 7090 } 7091 } 7092 7093 return DAG.getNode(ISD::BITCAST, DL, VT, 7094 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1)); 7095 } 7096 7097 SDValue 7098 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const { 7099 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7100 MVT VT = Op.getValueType().getSimpleVT(); 7101 SDLoc dl(Op); 7102 SDValue V1 = Op.getOperand(0); 7103 SDValue V2 = Op.getOperand(1); 7104 7105 if (isZeroShuffle(SVOp)) 7106 return getZeroVector(VT, Subtarget, DAG, dl); 7107 7108 // Handle splat operations 7109 if (SVOp->isSplat()) { 7110 // Use vbroadcast whenever the splat comes from a foldable load 7111 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 7112 if (Broadcast.getNode()) 7113 return Broadcast; 7114 } 7115 7116 // Check integer expanding shuffles. 7117 SDValue NewOp = LowerVectorIntExtend(Op, DAG); 7118 if (NewOp.getNode()) 7119 return NewOp; 7120 7121 // If the shuffle can be profitably rewritten as a narrower shuffle, then 7122 // do it! 7123 if (VT == MVT::v8i16 || VT == MVT::v16i8 || 7124 VT == MVT::v16i16 || VT == MVT::v32i8) { 7125 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 7126 if (NewOp.getNode()) 7127 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 7128 } else if ((VT == MVT::v4i32 || 7129 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 7130 // FIXME: Figure out a cleaner way to do this. 7131 // Try to make use of movq to zero out the top part. 7132 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 7133 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 7134 if (NewOp.getNode()) { 7135 MVT NewVT = NewOp.getValueType().getSimpleVT(); 7136 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), 7137 NewVT, true, false)) 7138 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), 7139 DAG, Subtarget, dl); 7140 } 7141 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 7142 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 7143 if (NewOp.getNode()) { 7144 MVT NewVT = NewOp.getValueType().getSimpleVT(); 7145 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT)) 7146 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), 7147 DAG, Subtarget, dl); 7148 } 7149 } 7150 } 7151 return SDValue(); 7152 } 7153 7154 SDValue 7155 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 7156 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 7157 SDValue V1 = Op.getOperand(0); 7158 SDValue V2 = Op.getOperand(1); 7159 MVT VT = Op.getValueType().getSimpleVT(); 7160 SDLoc dl(Op); 7161 unsigned NumElems = VT.getVectorNumElements(); 7162 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 7163 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 7164 bool V1IsSplat = false; 7165 bool V2IsSplat = false; 7166 bool HasSSE2 = Subtarget->hasSSE2(); 7167 bool HasFp256 = Subtarget->hasFp256(); 7168 bool HasInt256 = Subtarget->hasInt256(); 7169 MachineFunction &MF = DAG.getMachineFunction(); 7170 bool OptForSize = MF.getFunction()->getAttributes(). 7171 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 7172 7173 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 7174 7175 if (V1IsUndef && V2IsUndef) 7176 return DAG.getUNDEF(VT); 7177 7178 assert(!V1IsUndef && "Op 1 of shuffle should not be undef"); 7179 7180 // Vector shuffle lowering takes 3 steps: 7181 // 7182 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 7183 // narrowing and commutation of operands should be handled. 7184 // 2) Matching of shuffles with known shuffle masks to x86 target specific 7185 // shuffle nodes. 7186 // 3) Rewriting of unmatched masks into new generic shuffle operations, 7187 // so the shuffle can be broken into other shuffles and the legalizer can 7188 // try the lowering again. 7189 // 7190 // The general idea is that no vector_shuffle operation should be left to 7191 // be matched during isel, all of them must be converted to a target specific 7192 // node here. 7193 7194 // Normalize the input vectors. Here splats, zeroed vectors, profitable 7195 // narrowing and commutation of operands should be handled. The actual code 7196 // doesn't include all of those, work in progress... 7197 SDValue NewOp = NormalizeVectorShuffle(Op, DAG); 7198 if (NewOp.getNode()) 7199 return NewOp; 7200 7201 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end()); 7202 7203 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 7204 // unpckh_undef). Only use pshufd if speed is more important than size. 7205 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 7206 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 7207 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 7208 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 7209 7210 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() && 7211 V2IsUndef && MayFoldVectorLoad(V1)) 7212 return getMOVDDup(Op, dl, V1, DAG); 7213 7214 if (isMOVHLPS_v_undef_Mask(M, VT)) 7215 return getMOVHighToLow(Op, dl, DAG); 7216 7217 // Use to match splats 7218 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef && 7219 (VT == MVT::v2f64 || VT == MVT::v2i64)) 7220 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 7221 7222 if (isPSHUFDMask(M, VT)) { 7223 // The actual implementation will match the mask in the if above and then 7224 // during isel it can match several different instructions, not only pshufd 7225 // as its name says, sad but true, emulate the behavior for now... 7226 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 7227 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 7228 7229 unsigned TargetMask = getShuffleSHUFImmediate(SVOp); 7230 7231 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 7232 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 7233 7234 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64)) 7235 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, 7236 DAG); 7237 7238 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1, 7239 TargetMask, DAG); 7240 } 7241 7242 if (isPALIGNRMask(M, VT, Subtarget)) 7243 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2, 7244 getShufflePALIGNRImmediate(SVOp), 7245 DAG); 7246 7247 // Check if this can be converted into a logical shift. 7248 bool isLeft = false; 7249 unsigned ShAmt = 0; 7250 SDValue ShVal; 7251 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 7252 if (isShift && ShVal.hasOneUse()) { 7253 // If the shifted value has multiple uses, it may be cheaper to use 7254 // v_set0 + movlhps or movhlps, etc. 7255 MVT EltVT = VT.getVectorElementType(); 7256 ShAmt *= EltVT.getSizeInBits(); 7257 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 7258 } 7259 7260 if (isMOVLMask(M, VT)) { 7261 if (ISD::isBuildVectorAllZeros(V1.getNode())) 7262 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 7263 if (!isMOVLPMask(M, VT)) { 7264 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 7265 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 7266 7267 if (VT == MVT::v4i32 || VT == MVT::v4f32) 7268 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 7269 } 7270 } 7271 7272 // FIXME: fold these into legal mask. 7273 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256)) 7274 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 7275 7276 if (isMOVHLPSMask(M, VT)) 7277 return getMOVHighToLow(Op, dl, DAG); 7278 7279 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget)) 7280 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 7281 7282 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget)) 7283 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 7284 7285 if (isMOVLPMask(M, VT)) 7286 return getMOVLP(Op, dl, DAG, HasSSE2); 7287 7288 if (ShouldXformToMOVHLPS(M, VT) || 7289 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT)) 7290 return CommuteVectorShuffle(SVOp, DAG); 7291 7292 if (isShift) { 7293 // No better options. Use a vshldq / vsrldq. 7294 MVT EltVT = VT.getVectorElementType(); 7295 ShAmt *= EltVT.getSizeInBits(); 7296 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 7297 } 7298 7299 bool Commuted = false; 7300 // FIXME: This should also accept a bitcast of a splat? Be careful, not 7301 // 1,1,1,1 -> v8i16 though. 7302 V1IsSplat = isSplatVector(V1.getNode()); 7303 V2IsSplat = isSplatVector(V2.getNode()); 7304 7305 // Canonicalize the splat or undef, if present, to be on the RHS. 7306 if (!V2IsUndef && V1IsSplat && !V2IsSplat) { 7307 CommuteVectorShuffleMask(M, NumElems); 7308 std::swap(V1, V2); 7309 std::swap(V1IsSplat, V2IsSplat); 7310 Commuted = true; 7311 } 7312 7313 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) { 7314 // Shuffling low element of v1 into undef, just return v1. 7315 if (V2IsUndef) 7316 return V1; 7317 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 7318 // the instruction selector will not match, so get a canonical MOVL with 7319 // swapped operands to undo the commute. 7320 return getMOVL(DAG, dl, VT, V2, V1); 7321 } 7322 7323 if (isUNPCKLMask(M, VT, HasInt256)) 7324 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 7325 7326 if (isUNPCKHMask(M, VT, HasInt256)) 7327 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 7328 7329 if (V2IsSplat) { 7330 // Normalize mask so all entries that point to V2 points to its first 7331 // element then try to match unpck{h|l} again. If match, return a 7332 // new vector_shuffle with the corrected mask.p 7333 SmallVector<int, 8> NewMask(M.begin(), M.end()); 7334 NormalizeMask(NewMask, NumElems); 7335 if (isUNPCKLMask(NewMask, VT, HasInt256, true)) 7336 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 7337 if (isUNPCKHMask(NewMask, VT, HasInt256, true)) 7338 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 7339 } 7340 7341 if (Commuted) { 7342 // Commute is back and try unpck* again. 7343 // FIXME: this seems wrong. 7344 CommuteVectorShuffleMask(M, NumElems); 7345 std::swap(V1, V2); 7346 std::swap(V1IsSplat, V2IsSplat); 7347 Commuted = false; 7348 7349 if (isUNPCKLMask(M, VT, HasInt256)) 7350 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 7351 7352 if (isUNPCKHMask(M, VT, HasInt256)) 7353 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 7354 } 7355 7356 // Normalize the node to match x86 shuffle ops if needed 7357 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true))) 7358 return CommuteVectorShuffle(SVOp, DAG); 7359 7360 // The checks below are all present in isShuffleMaskLegal, but they are 7361 // inlined here right now to enable us to directly emit target specific 7362 // nodes, and remove one by one until they don't return Op anymore. 7363 7364 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 7365 SVOp->getSplatIndex() == 0 && V2IsUndef) { 7366 if (VT == MVT::v2f64 || VT == MVT::v2i64) 7367 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 7368 } 7369 7370 if (isPSHUFHWMask(M, VT, HasInt256)) 7371 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 7372 getShufflePSHUFHWImmediate(SVOp), 7373 DAG); 7374 7375 if (isPSHUFLWMask(M, VT, HasInt256)) 7376 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 7377 getShufflePSHUFLWImmediate(SVOp), 7378 DAG); 7379 7380 if (isSHUFPMask(M, VT, HasFp256)) 7381 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2, 7382 getShuffleSHUFImmediate(SVOp), DAG); 7383 7384 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 7385 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 7386 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 7387 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 7388 7389 //===--------------------------------------------------------------------===// 7390 // Generate target specific nodes for 128 or 256-bit shuffles only 7391 // supported in the AVX instruction set. 7392 // 7393 7394 // Handle VMOVDDUPY permutations 7395 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256)) 7396 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 7397 7398 // Handle VPERMILPS/D* permutations 7399 if (isVPERMILPMask(M, VT, HasFp256)) { 7400 if (HasInt256 && VT == MVT::v8i32) 7401 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, 7402 getShuffleSHUFImmediate(SVOp), DAG); 7403 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, 7404 getShuffleSHUFImmediate(SVOp), DAG); 7405 } 7406 7407 // Handle VPERM2F128/VPERM2I128 permutations 7408 if (isVPERM2X128Mask(M, VT, HasFp256)) 7409 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1, 7410 V2, getShuffleVPERM2X128Immediate(SVOp), DAG); 7411 7412 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG); 7413 if (BlendOp.getNode()) 7414 return BlendOp; 7415 7416 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) { 7417 SmallVector<SDValue, 8> permclMask; 7418 for (unsigned i = 0; i != 8; ++i) { 7419 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32)); 7420 } 7421 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, 7422 &permclMask[0], 8); 7423 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32 7424 return DAG.getNode(X86ISD::VPERMV, dl, VT, 7425 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1); 7426 } 7427 7428 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64)) 7429 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, 7430 getShuffleCLImmediate(SVOp), DAG); 7431 7432 //===--------------------------------------------------------------------===// 7433 // Since no target specific shuffle was selected for this generic one, 7434 // lower it into other known shuffles. FIXME: this isn't true yet, but 7435 // this is the plan. 7436 // 7437 7438 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 7439 if (VT == MVT::v8i16) { 7440 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG); 7441 if (NewOp.getNode()) 7442 return NewOp; 7443 } 7444 7445 if (VT == MVT::v16i8) { 7446 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 7447 if (NewOp.getNode()) 7448 return NewOp; 7449 } 7450 7451 if (VT == MVT::v32i8) { 7452 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG); 7453 if (NewOp.getNode()) 7454 return NewOp; 7455 } 7456 7457 // Handle all 128-bit wide vectors with 4 elements, and match them with 7458 // several different shuffle types. 7459 if (NumElems == 4 && VT.is128BitVector()) 7460 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 7461 7462 // Handle general 256-bit shuffles 7463 if (VT.is256BitVector()) 7464 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 7465 7466 return SDValue(); 7467 } 7468 7469 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) { 7470 MVT VT = Op.getValueType().getSimpleVT(); 7471 SDLoc dl(Op); 7472 7473 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector()) 7474 return SDValue(); 7475 7476 if (VT.getSizeInBits() == 8) { 7477 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 7478 Op.getOperand(0), Op.getOperand(1)); 7479 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7480 DAG.getValueType(VT)); 7481 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7482 } 7483 7484 if (VT.getSizeInBits() == 16) { 7485 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7486 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 7487 if (Idx == 0) 7488 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7489 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7490 DAG.getNode(ISD::BITCAST, dl, 7491 MVT::v4i32, 7492 Op.getOperand(0)), 7493 Op.getOperand(1))); 7494 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 7495 Op.getOperand(0), Op.getOperand(1)); 7496 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7497 DAG.getValueType(VT)); 7498 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7499 } 7500 7501 if (VT == MVT::f32) { 7502 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 7503 // the result back to FR32 register. It's only worth matching if the 7504 // result has a single use which is a store or a bitcast to i32. And in 7505 // the case of a store, it's not worth it if the index is a constant 0, 7506 // because a MOVSSmr can be used instead, which is smaller and faster. 7507 if (!Op.hasOneUse()) 7508 return SDValue(); 7509 SDNode *User = *Op.getNode()->use_begin(); 7510 if ((User->getOpcode() != ISD::STORE || 7511 (isa<ConstantSDNode>(Op.getOperand(1)) && 7512 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 7513 (User->getOpcode() != ISD::BITCAST || 7514 User->getValueType(0) != MVT::i32)) 7515 return SDValue(); 7516 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7517 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 7518 Op.getOperand(0)), 7519 Op.getOperand(1)); 7520 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 7521 } 7522 7523 if (VT == MVT::i32 || VT == MVT::i64) { 7524 // ExtractPS/pextrq works with constant index. 7525 if (isa<ConstantSDNode>(Op.getOperand(1))) 7526 return Op; 7527 } 7528 return SDValue(); 7529 } 7530 7531 SDValue 7532 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7533 SelectionDAG &DAG) const { 7534 SDLoc dl(Op); 7535 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7536 return SDValue(); 7537 7538 SDValue Vec = Op.getOperand(0); 7539 MVT VecVT = Vec.getValueType().getSimpleVT(); 7540 7541 // If this is a 256-bit vector result, first extract the 128-bit vector and 7542 // then extract the element from the 128-bit vector. 7543 if (VecVT.is256BitVector() || VecVT.is512BitVector()) { 7544 SDValue Idx = Op.getOperand(1); 7545 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7546 7547 // Get the 128-bit vector. 7548 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl); 7549 EVT EltVT = VecVT.getVectorElementType(); 7550 7551 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits(); 7552 7553 //if (IdxVal >= NumElems/2) 7554 // IdxVal -= NumElems/2; 7555 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk; 7556 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 7557 DAG.getConstant(IdxVal, MVT::i32)); 7558 } 7559 7560 assert(VecVT.is128BitVector() && "Unexpected vector length"); 7561 7562 if (Subtarget->hasSSE41()) { 7563 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 7564 if (Res.getNode()) 7565 return Res; 7566 } 7567 7568 MVT VT = Op.getValueType().getSimpleVT(); 7569 // TODO: handle v16i8. 7570 if (VT.getSizeInBits() == 16) { 7571 SDValue Vec = Op.getOperand(0); 7572 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7573 if (Idx == 0) 7574 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7575 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7576 DAG.getNode(ISD::BITCAST, dl, 7577 MVT::v4i32, Vec), 7578 Op.getOperand(1))); 7579 // Transform it so it match pextrw which produces a 32-bit result. 7580 MVT EltVT = MVT::i32; 7581 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 7582 Op.getOperand(0), Op.getOperand(1)); 7583 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 7584 DAG.getValueType(VT)); 7585 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7586 } 7587 7588 if (VT.getSizeInBits() == 32) { 7589 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7590 if (Idx == 0) 7591 return Op; 7592 7593 // SHUFPS the element to the lowest double word, then movss. 7594 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 7595 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT(); 7596 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7597 DAG.getUNDEF(VVT), Mask); 7598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7599 DAG.getIntPtrConstant(0)); 7600 } 7601 7602 if (VT.getSizeInBits() == 64) { 7603 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 7604 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 7605 // to match extract_elt for f64. 7606 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7607 if (Idx == 0) 7608 return Op; 7609 7610 // UNPCKHPD the element to the lowest double word, then movsd. 7611 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 7612 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 7613 int Mask[2] = { 1, -1 }; 7614 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT(); 7615 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7616 DAG.getUNDEF(VVT), Mask); 7617 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7618 DAG.getIntPtrConstant(0)); 7619 } 7620 7621 return SDValue(); 7622 } 7623 7624 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) { 7625 MVT VT = Op.getValueType().getSimpleVT(); 7626 MVT EltVT = VT.getVectorElementType(); 7627 SDLoc dl(Op); 7628 7629 SDValue N0 = Op.getOperand(0); 7630 SDValue N1 = Op.getOperand(1); 7631 SDValue N2 = Op.getOperand(2); 7632 7633 if (!VT.is128BitVector()) 7634 return SDValue(); 7635 7636 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 7637 isa<ConstantSDNode>(N2)) { 7638 unsigned Opc; 7639 if (VT == MVT::v8i16) 7640 Opc = X86ISD::PINSRW; 7641 else if (VT == MVT::v16i8) 7642 Opc = X86ISD::PINSRB; 7643 else 7644 Opc = X86ISD::PINSRB; 7645 7646 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 7647 // argument. 7648 if (N1.getValueType() != MVT::i32) 7649 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7650 if (N2.getValueType() != MVT::i32) 7651 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7652 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 7653 } 7654 7655 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 7656 // Bits [7:6] of the constant are the source select. This will always be 7657 // zero here. The DAG Combiner may combine an extract_elt index into these 7658 // bits. For example (insert (extract, 3), 2) could be matched by putting 7659 // the '3' into bits [7:6] of X86ISD::INSERTPS. 7660 // Bits [5:4] of the constant are the destination select. This is the 7661 // value of the incoming immediate. 7662 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 7663 // combine either bitwise AND or insert of float 0.0 to set these bits. 7664 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 7665 // Create this as a scalar to vector.. 7666 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7667 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7668 } 7669 7670 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) { 7671 // PINSR* works with constant index. 7672 return Op; 7673 } 7674 return SDValue(); 7675 } 7676 7677 SDValue 7678 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7679 MVT VT = Op.getValueType().getSimpleVT(); 7680 MVT EltVT = VT.getVectorElementType(); 7681 7682 SDLoc dl(Op); 7683 SDValue N0 = Op.getOperand(0); 7684 SDValue N1 = Op.getOperand(1); 7685 SDValue N2 = Op.getOperand(2); 7686 7687 // If this is a 256-bit vector result, first extract the 128-bit vector, 7688 // insert the element into the extracted half and then place it back. 7689 if (VT.is256BitVector() || VT.is512BitVector()) { 7690 if (!isa<ConstantSDNode>(N2)) 7691 return SDValue(); 7692 7693 // Get the desired 128-bit vector half. 7694 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7695 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl); 7696 7697 // Insert the element into the desired half. 7698 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits(); 7699 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128; 7700 7701 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1, 7702 DAG.getConstant(IdxIn128, MVT::i32)); 7703 7704 // Insert the changed part back to the 256-bit vector 7705 return Insert128BitVector(N0, V, IdxVal, DAG, dl); 7706 } 7707 7708 if (Subtarget->hasSSE41()) 7709 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7710 7711 if (EltVT == MVT::i8) 7712 return SDValue(); 7713 7714 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7715 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7716 // as its second argument. 7717 if (N1.getValueType() != MVT::i32) 7718 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7719 if (N2.getValueType() != MVT::i32) 7720 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7721 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7722 } 7723 return SDValue(); 7724 } 7725 7726 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) { 7727 LLVMContext *Context = DAG.getContext(); 7728 SDLoc dl(Op); 7729 MVT OpVT = Op.getValueType().getSimpleVT(); 7730 7731 // If this is a 256-bit vector result, first insert into a 128-bit 7732 // vector and then insert into the 256-bit vector. 7733 if (!OpVT.is128BitVector()) { 7734 // Insert into a 128-bit vector. 7735 unsigned SizeFactor = OpVT.getSizeInBits()/128; 7736 EVT VT128 = EVT::getVectorVT(*Context, 7737 OpVT.getVectorElementType(), 7738 OpVT.getVectorNumElements() / SizeFactor); 7739 7740 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7741 7742 // Insert the 128-bit vector. 7743 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl); 7744 } 7745 7746 if (OpVT == MVT::v1i64 && 7747 Op.getOperand(0).getValueType() == MVT::i64) 7748 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7749 7750 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7751 assert(OpVT.is128BitVector() && "Expected an SSE type!"); 7752 return DAG.getNode(ISD::BITCAST, dl, OpVT, 7753 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7754 } 7755 7756 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7757 // a simple subregister reference or explicit instructions to grab 7758 // upper bits of a vector. 7759 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7760 SelectionDAG &DAG) { 7761 SDLoc dl(Op); 7762 SDValue In = Op.getOperand(0); 7763 SDValue Idx = Op.getOperand(1); 7764 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7765 EVT ResVT = Op.getValueType(); 7766 EVT InVT = In.getValueType(); 7767 7768 if (Subtarget->hasFp256()) { 7769 if (ResVT.is128BitVector() && 7770 (InVT.is256BitVector() || InVT.is512BitVector()) && 7771 isa<ConstantSDNode>(Idx)) { 7772 return Extract128BitVector(In, IdxVal, DAG, dl); 7773 } 7774 if (ResVT.is256BitVector() && InVT.is512BitVector() && 7775 isa<ConstantSDNode>(Idx)) { 7776 return Extract256BitVector(In, IdxVal, DAG, dl); 7777 } 7778 } 7779 return SDValue(); 7780 } 7781 7782 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7783 // simple superregister reference or explicit instructions to insert 7784 // the upper bits of a vector. 7785 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7786 SelectionDAG &DAG) { 7787 if (Subtarget->hasFp256()) { 7788 SDLoc dl(Op.getNode()); 7789 SDValue Vec = Op.getNode()->getOperand(0); 7790 SDValue SubVec = Op.getNode()->getOperand(1); 7791 SDValue Idx = Op.getNode()->getOperand(2); 7792 7793 if ((Op.getNode()->getValueType(0).is256BitVector() || 7794 Op.getNode()->getValueType(0).is512BitVector()) && 7795 SubVec.getNode()->getValueType(0).is128BitVector() && 7796 isa<ConstantSDNode>(Idx)) { 7797 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7798 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl); 7799 } 7800 7801 if (Op.getNode()->getValueType(0).is512BitVector() && 7802 SubVec.getNode()->getValueType(0).is256BitVector() && 7803 isa<ConstantSDNode>(Idx)) { 7804 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7805 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl); 7806 } 7807 } 7808 return SDValue(); 7809 } 7810 7811 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7812 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7813 // one of the above mentioned nodes. It has to be wrapped because otherwise 7814 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7815 // be used to form addressing mode. These wrapped nodes will be selected 7816 // into MOV32ri. 7817 SDValue 7818 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7819 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7820 7821 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7822 // global base reg. 7823 unsigned char OpFlag = 0; 7824 unsigned WrapperKind = X86ISD::Wrapper; 7825 CodeModel::Model M = getTargetMachine().getCodeModel(); 7826 7827 if (Subtarget->isPICStyleRIPRel() && 7828 (M == CodeModel::Small || M == CodeModel::Kernel)) 7829 WrapperKind = X86ISD::WrapperRIP; 7830 else if (Subtarget->isPICStyleGOT()) 7831 OpFlag = X86II::MO_GOTOFF; 7832 else if (Subtarget->isPICStyleStubPIC()) 7833 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7834 7835 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7836 CP->getAlignment(), 7837 CP->getOffset(), OpFlag); 7838 SDLoc DL(CP); 7839 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7840 // With PIC, the address is actually $g + Offset. 7841 if (OpFlag) { 7842 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7843 DAG.getNode(X86ISD::GlobalBaseReg, 7844 SDLoc(), getPointerTy()), 7845 Result); 7846 } 7847 7848 return Result; 7849 } 7850 7851 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7852 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7853 7854 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7855 // global base reg. 7856 unsigned char OpFlag = 0; 7857 unsigned WrapperKind = X86ISD::Wrapper; 7858 CodeModel::Model M = getTargetMachine().getCodeModel(); 7859 7860 if (Subtarget->isPICStyleRIPRel() && 7861 (M == CodeModel::Small || M == CodeModel::Kernel)) 7862 WrapperKind = X86ISD::WrapperRIP; 7863 else if (Subtarget->isPICStyleGOT()) 7864 OpFlag = X86II::MO_GOTOFF; 7865 else if (Subtarget->isPICStyleStubPIC()) 7866 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7867 7868 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7869 OpFlag); 7870 SDLoc DL(JT); 7871 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7872 7873 // With PIC, the address is actually $g + Offset. 7874 if (OpFlag) 7875 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7876 DAG.getNode(X86ISD::GlobalBaseReg, 7877 SDLoc(), getPointerTy()), 7878 Result); 7879 7880 return Result; 7881 } 7882 7883 SDValue 7884 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7885 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7886 7887 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7888 // global base reg. 7889 unsigned char OpFlag = 0; 7890 unsigned WrapperKind = X86ISD::Wrapper; 7891 CodeModel::Model M = getTargetMachine().getCodeModel(); 7892 7893 if (Subtarget->isPICStyleRIPRel() && 7894 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7895 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7896 OpFlag = X86II::MO_GOTPCREL; 7897 WrapperKind = X86ISD::WrapperRIP; 7898 } else if (Subtarget->isPICStyleGOT()) { 7899 OpFlag = X86II::MO_GOT; 7900 } else if (Subtarget->isPICStyleStubPIC()) { 7901 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7902 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7903 OpFlag = X86II::MO_DARWIN_NONLAZY; 7904 } 7905 7906 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7907 7908 SDLoc DL(Op); 7909 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7910 7911 // With PIC, the address is actually $g + Offset. 7912 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7913 !Subtarget->is64Bit()) { 7914 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7915 DAG.getNode(X86ISD::GlobalBaseReg, 7916 SDLoc(), getPointerTy()), 7917 Result); 7918 } 7919 7920 // For symbols that require a load from a stub to get the address, emit the 7921 // load. 7922 if (isGlobalStubReference(OpFlag)) 7923 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7924 MachinePointerInfo::getGOT(), false, false, false, 0); 7925 7926 return Result; 7927 } 7928 7929 SDValue 7930 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7931 // Create the TargetBlockAddressAddress node. 7932 unsigned char OpFlags = 7933 Subtarget->ClassifyBlockAddressReference(); 7934 CodeModel::Model M = getTargetMachine().getCodeModel(); 7935 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7936 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset(); 7937 SDLoc dl(Op); 7938 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset, 7939 OpFlags); 7940 7941 if (Subtarget->isPICStyleRIPRel() && 7942 (M == CodeModel::Small || M == CodeModel::Kernel)) 7943 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7944 else 7945 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7946 7947 // With PIC, the address is actually $g + Offset. 7948 if (isGlobalRelativeToPICBase(OpFlags)) { 7949 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7950 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7951 Result); 7952 } 7953 7954 return Result; 7955 } 7956 7957 SDValue 7958 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl, 7959 int64_t Offset, SelectionDAG &DAG) const { 7960 // Create the TargetGlobalAddress node, folding in the constant 7961 // offset if it is legal. 7962 unsigned char OpFlags = 7963 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7964 CodeModel::Model M = getTargetMachine().getCodeModel(); 7965 SDValue Result; 7966 if (OpFlags == X86II::MO_NO_FLAG && 7967 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7968 // A direct static reference to a global. 7969 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7970 Offset = 0; 7971 } else { 7972 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7973 } 7974 7975 if (Subtarget->isPICStyleRIPRel() && 7976 (M == CodeModel::Small || M == CodeModel::Kernel)) 7977 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7978 else 7979 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7980 7981 // With PIC, the address is actually $g + Offset. 7982 if (isGlobalRelativeToPICBase(OpFlags)) { 7983 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7984 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7985 Result); 7986 } 7987 7988 // For globals that require a load from a stub to get the address, emit the 7989 // load. 7990 if (isGlobalStubReference(OpFlags)) 7991 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7992 MachinePointerInfo::getGOT(), false, false, false, 0); 7993 7994 // If there was a non-zero offset that we didn't fold, create an explicit 7995 // addition for it. 7996 if (Offset != 0) 7997 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7998 DAG.getConstant(Offset, getPointerTy())); 7999 8000 return Result; 8001 } 8002 8003 SDValue 8004 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 8005 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 8006 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 8007 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG); 8008 } 8009 8010 static SDValue 8011 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 8012 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 8013 unsigned char OperandFlags, bool LocalDynamic = false) { 8014 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8015 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8016 SDLoc dl(GA); 8017 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 8018 GA->getValueType(0), 8019 GA->getOffset(), 8020 OperandFlags); 8021 8022 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR 8023 : X86ISD::TLSADDR; 8024 8025 if (InFlag) { 8026 SDValue Ops[] = { Chain, TGA, *InFlag }; 8027 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops)); 8028 } else { 8029 SDValue Ops[] = { Chain, TGA }; 8030 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops)); 8031 } 8032 8033 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 8034 MFI->setAdjustsStack(true); 8035 8036 SDValue Flag = Chain.getValue(1); 8037 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 8038 } 8039 8040 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 8041 static SDValue 8042 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 8043 const EVT PtrVT) { 8044 SDValue InFlag; 8045 SDLoc dl(GA); // ? function entry point might be better 8046 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 8047 DAG.getNode(X86ISD::GlobalBaseReg, 8048 SDLoc(), PtrVT), InFlag); 8049 InFlag = Chain.getValue(1); 8050 8051 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 8052 } 8053 8054 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 8055 static SDValue 8056 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 8057 const EVT PtrVT) { 8058 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 8059 X86::RAX, X86II::MO_TLSGD); 8060 } 8061 8062 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA, 8063 SelectionDAG &DAG, 8064 const EVT PtrVT, 8065 bool is64Bit) { 8066 SDLoc dl(GA); 8067 8068 // Get the start address of the TLS block for this module. 8069 X86MachineFunctionInfo* MFI = DAG.getMachineFunction() 8070 .getInfo<X86MachineFunctionInfo>(); 8071 MFI->incNumLocalDynamicTLSAccesses(); 8072 8073 SDValue Base; 8074 if (is64Bit) { 8075 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX, 8076 X86II::MO_TLSLD, /*LocalDynamic=*/true); 8077 } else { 8078 SDValue InFlag; 8079 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 8080 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag); 8081 InFlag = Chain.getValue(1); 8082 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, 8083 X86II::MO_TLSLDM, /*LocalDynamic=*/true); 8084 } 8085 8086 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations 8087 // of Base. 8088 8089 // Build x@dtpoff. 8090 unsigned char OperandFlags = X86II::MO_DTPOFF; 8091 unsigned WrapperKind = X86ISD::Wrapper; 8092 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 8093 GA->getValueType(0), 8094 GA->getOffset(), OperandFlags); 8095 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 8096 8097 // Add x@dtpoff with the base. 8098 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base); 8099 } 8100 8101 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model. 8102 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 8103 const EVT PtrVT, TLSModel::Model model, 8104 bool is64Bit, bool isPIC) { 8105 SDLoc dl(GA); 8106 8107 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 8108 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 8109 is64Bit ? 257 : 256)); 8110 8111 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 8112 DAG.getIntPtrConstant(0), 8113 MachinePointerInfo(Ptr), 8114 false, false, false, 0); 8115 8116 unsigned char OperandFlags = 0; 8117 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 8118 // initialexec. 8119 unsigned WrapperKind = X86ISD::Wrapper; 8120 if (model == TLSModel::LocalExec) { 8121 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 8122 } else if (model == TLSModel::InitialExec) { 8123 if (is64Bit) { 8124 OperandFlags = X86II::MO_GOTTPOFF; 8125 WrapperKind = X86ISD::WrapperRIP; 8126 } else { 8127 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF; 8128 } 8129 } else { 8130 llvm_unreachable("Unexpected model"); 8131 } 8132 8133 // emit "addl x@ntpoff,%eax" (local exec) 8134 // or "addl x@indntpoff,%eax" (initial exec) 8135 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic) 8136 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 8137 GA->getValueType(0), 8138 GA->getOffset(), OperandFlags); 8139 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 8140 8141 if (model == TLSModel::InitialExec) { 8142 if (isPIC && !is64Bit) { 8143 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, 8144 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), 8145 Offset); 8146 } 8147 8148 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 8149 MachinePointerInfo::getGOT(), false, false, false, 8150 0); 8151 } 8152 8153 // The address of the thread local variable is the add of the thread 8154 // pointer with the offset of the variable. 8155 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 8156 } 8157 8158 SDValue 8159 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 8160 8161 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 8162 const GlobalValue *GV = GA->getGlobal(); 8163 8164 if (Subtarget->isTargetELF()) { 8165 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 8166 8167 switch (model) { 8168 case TLSModel::GeneralDynamic: 8169 if (Subtarget->is64Bit()) 8170 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 8171 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 8172 case TLSModel::LocalDynamic: 8173 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(), 8174 Subtarget->is64Bit()); 8175 case TLSModel::InitialExec: 8176 case TLSModel::LocalExec: 8177 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 8178 Subtarget->is64Bit(), 8179 getTargetMachine().getRelocationModel() == Reloc::PIC_); 8180 } 8181 llvm_unreachable("Unknown TLS model."); 8182 } 8183 8184 if (Subtarget->isTargetDarwin()) { 8185 // Darwin only has one model of TLS. Lower to that. 8186 unsigned char OpFlag = 0; 8187 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 8188 X86ISD::WrapperRIP : X86ISD::Wrapper; 8189 8190 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 8191 // global base reg. 8192 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 8193 !Subtarget->is64Bit(); 8194 if (PIC32) 8195 OpFlag = X86II::MO_TLVP_PIC_BASE; 8196 else 8197 OpFlag = X86II::MO_TLVP; 8198 SDLoc DL(Op); 8199 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 8200 GA->getValueType(0), 8201 GA->getOffset(), OpFlag); 8202 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 8203 8204 // With PIC32, the address is actually $g + Offset. 8205 if (PIC32) 8206 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 8207 DAG.getNode(X86ISD::GlobalBaseReg, 8208 SDLoc(), getPointerTy()), 8209 Offset); 8210 8211 // Lowering the machine isd will make sure everything is in the right 8212 // location. 8213 SDValue Chain = DAG.getEntryNode(); 8214 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8215 SDValue Args[] = { Chain, Offset }; 8216 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 8217 8218 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 8219 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8220 MFI->setAdjustsStack(true); 8221 8222 // And our return value (tls address) is in the standard call return value 8223 // location. 8224 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 8225 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 8226 Chain.getValue(1)); 8227 } 8228 8229 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) { 8230 // Just use the implicit TLS architecture 8231 // Need to generate someting similar to: 8232 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage 8233 // ; from TEB 8234 // mov ecx, dword [rel _tls_index]: Load index (from C runtime) 8235 // mov rcx, qword [rdx+rcx*8] 8236 // mov eax, .tls$:tlsvar 8237 // [rax+rcx] contains the address 8238 // Windows 64bit: gs:0x58 8239 // Windows 32bit: fs:__tls_array 8240 8241 // If GV is an alias then use the aliasee for determining 8242 // thread-localness. 8243 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 8244 GV = GA->resolveAliasedGlobal(false); 8245 SDLoc dl(GA); 8246 SDValue Chain = DAG.getEntryNode(); 8247 8248 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or 8249 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly 8250 // use its literal value of 0x2C. 8251 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit() 8252 ? Type::getInt8PtrTy(*DAG.getContext(), 8253 256) 8254 : Type::getInt32PtrTy(*DAG.getContext(), 8255 257)); 8256 8257 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) : 8258 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) : 8259 DAG.getExternalSymbol("_tls_array", getPointerTy())); 8260 8261 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray, 8262 MachinePointerInfo(Ptr), 8263 false, false, false, 0); 8264 8265 // Load the _tls_index variable 8266 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy()); 8267 if (Subtarget->is64Bit()) 8268 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, 8269 IDX, MachinePointerInfo(), MVT::i32, 8270 false, false, 0); 8271 else 8272 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(), 8273 false, false, false, 0); 8274 8275 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), 8276 getPointerTy()); 8277 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale); 8278 8279 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX); 8280 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(), 8281 false, false, false, 0); 8282 8283 // Get the offset of start of .tls section 8284 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 8285 GA->getValueType(0), 8286 GA->getOffset(), X86II::MO_SECREL); 8287 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA); 8288 8289 // The address of the thread local variable is the add of the thread 8290 // pointer with the offset of the variable. 8291 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset); 8292 } 8293 8294 llvm_unreachable("TLS not implemented for this target."); 8295 } 8296 8297 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values 8298 /// and take a 2 x i32 value to shift plus a shift amount. 8299 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{ 8300 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 8301 EVT VT = Op.getValueType(); 8302 unsigned VTBits = VT.getSizeInBits(); 8303 SDLoc dl(Op); 8304 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 8305 SDValue ShOpLo = Op.getOperand(0); 8306 SDValue ShOpHi = Op.getOperand(1); 8307 SDValue ShAmt = Op.getOperand(2); 8308 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 8309 DAG.getConstant(VTBits - 1, MVT::i8)) 8310 : DAG.getConstant(0, VT); 8311 8312 SDValue Tmp2, Tmp3; 8313 if (Op.getOpcode() == ISD::SHL_PARTS) { 8314 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 8315 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 8316 } else { 8317 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 8318 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 8319 } 8320 8321 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 8322 DAG.getConstant(VTBits, MVT::i8)); 8323 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 8324 AndNode, DAG.getConstant(0, MVT::i8)); 8325 8326 SDValue Hi, Lo; 8327 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8328 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 8329 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 8330 8331 if (Op.getOpcode() == ISD::SHL_PARTS) { 8332 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 8333 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 8334 } else { 8335 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 8336 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 8337 } 8338 8339 SDValue Ops[2] = { Lo, Hi }; 8340 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl); 8341 } 8342 8343 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 8344 SelectionDAG &DAG) const { 8345 EVT SrcVT = Op.getOperand(0).getValueType(); 8346 8347 if (SrcVT.isVector()) 8348 return SDValue(); 8349 8350 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 8351 "Unknown SINT_TO_FP to lower!"); 8352 8353 // These are really Legal; return the operand so the caller accepts it as 8354 // Legal. 8355 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 8356 return Op; 8357 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 8358 Subtarget->is64Bit()) { 8359 return Op; 8360 } 8361 8362 SDLoc dl(Op); 8363 unsigned Size = SrcVT.getSizeInBits()/8; 8364 MachineFunction &MF = DAG.getMachineFunction(); 8365 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 8366 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8367 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8368 StackSlot, 8369 MachinePointerInfo::getFixedStack(SSFI), 8370 false, false, 0); 8371 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 8372 } 8373 8374 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 8375 SDValue StackSlot, 8376 SelectionDAG &DAG) const { 8377 // Build the FILD 8378 SDLoc DL(Op); 8379 SDVTList Tys; 8380 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 8381 if (useSSE) 8382 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 8383 else 8384 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 8385 8386 unsigned ByteSize = SrcVT.getSizeInBits()/8; 8387 8388 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 8389 MachineMemOperand *MMO; 8390 if (FI) { 8391 int SSFI = FI->getIndex(); 8392 MMO = 8393 DAG.getMachineFunction() 8394 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8395 MachineMemOperand::MOLoad, ByteSize, ByteSize); 8396 } else { 8397 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 8398 StackSlot = StackSlot.getOperand(1); 8399 } 8400 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 8401 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 8402 X86ISD::FILD, DL, 8403 Tys, Ops, array_lengthof(Ops), 8404 SrcVT, MMO); 8405 8406 if (useSSE) { 8407 Chain = Result.getValue(1); 8408 SDValue InFlag = Result.getValue(2); 8409 8410 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 8411 // shouldn't be necessary except that RFP cannot be live across 8412 // multiple blocks. When stackifier is fixed, they can be uncoupled. 8413 MachineFunction &MF = DAG.getMachineFunction(); 8414 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 8415 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 8416 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8417 Tys = DAG.getVTList(MVT::Other); 8418 SDValue Ops[] = { 8419 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 8420 }; 8421 MachineMemOperand *MMO = 8422 DAG.getMachineFunction() 8423 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8424 MachineMemOperand::MOStore, SSFISize, SSFISize); 8425 8426 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 8427 Ops, array_lengthof(Ops), 8428 Op.getValueType(), MMO); 8429 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 8430 MachinePointerInfo::getFixedStack(SSFI), 8431 false, false, false, 0); 8432 } 8433 8434 return Result; 8435 } 8436 8437 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 8438 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 8439 SelectionDAG &DAG) const { 8440 // This algorithm is not obvious. Here it is what we're trying to output: 8441 /* 8442 movq %rax, %xmm0 8443 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U } 8444 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 } 8445 #ifdef __SSE3__ 8446 haddpd %xmm0, %xmm0 8447 #else 8448 pshufd $0x4e, %xmm0, %xmm1 8449 addpd %xmm1, %xmm0 8450 #endif 8451 */ 8452 8453 SDLoc dl(Op); 8454 LLVMContext *Context = DAG.getContext(); 8455 8456 // Build some magic constants. 8457 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 }; 8458 Constant *C0 = ConstantDataVector::get(*Context, CV0); 8459 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 8460 8461 SmallVector<Constant*,2> CV1; 8462 CV1.push_back( 8463 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8464 APInt(64, 0x4330000000000000ULL)))); 8465 CV1.push_back( 8466 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8467 APInt(64, 0x4530000000000000ULL)))); 8468 Constant *C1 = ConstantVector::get(CV1); 8469 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 8470 8471 // Load the 64-bit value into an XMM register. 8472 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 8473 Op.getOperand(0)); 8474 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 8475 MachinePointerInfo::getConstantPool(), 8476 false, false, false, 16); 8477 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, 8478 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1), 8479 CLod0); 8480 8481 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 8482 MachinePointerInfo::getConstantPool(), 8483 false, false, false, 16); 8484 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1); 8485 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 8486 SDValue Result; 8487 8488 if (Subtarget->hasSSE3()) { 8489 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'. 8490 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub); 8491 } else { 8492 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub); 8493 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32, 8494 S2F, 0x4E, DAG); 8495 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, 8496 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle), 8497 Sub); 8498 } 8499 8500 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result, 8501 DAG.getIntPtrConstant(0)); 8502 } 8503 8504 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 8505 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 8506 SelectionDAG &DAG) const { 8507 SDLoc dl(Op); 8508 // FP constant to bias correct the final result. 8509 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 8510 MVT::f64); 8511 8512 // Load the 32-bit value into an XMM register. 8513 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 8514 Op.getOperand(0)); 8515 8516 // Zero out the upper parts of the register. 8517 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG); 8518 8519 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8520 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 8521 DAG.getIntPtrConstant(0)); 8522 8523 // Or the load with the bias. 8524 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 8525 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8526 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8527 MVT::v2f64, Load)), 8528 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8529 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8530 MVT::v2f64, Bias))); 8531 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8532 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 8533 DAG.getIntPtrConstant(0)); 8534 8535 // Subtract the bias. 8536 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 8537 8538 // Handle final rounding. 8539 EVT DestVT = Op.getValueType(); 8540 8541 if (DestVT.bitsLT(MVT::f64)) 8542 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 8543 DAG.getIntPtrConstant(0)); 8544 if (DestVT.bitsGT(MVT::f64)) 8545 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 8546 8547 // Handle final rounding. 8548 return Sub; 8549 } 8550 8551 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op, 8552 SelectionDAG &DAG) const { 8553 SDValue N0 = Op.getOperand(0); 8554 EVT SVT = N0.getValueType(); 8555 SDLoc dl(Op); 8556 8557 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 || 8558 SVT == MVT::v8i8 || SVT == MVT::v8i16) && 8559 "Custom UINT_TO_FP is not supported!"); 8560 8561 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 8562 SVT.getVectorNumElements()); 8563 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), 8564 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0)); 8565 } 8566 8567 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 8568 SelectionDAG &DAG) const { 8569 SDValue N0 = Op.getOperand(0); 8570 SDLoc dl(Op); 8571 8572 if (Op.getValueType().isVector()) 8573 return lowerUINT_TO_FP_vec(Op, DAG); 8574 8575 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 8576 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 8577 // the optimization here. 8578 if (DAG.SignBitIsZero(N0)) 8579 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 8580 8581 EVT SrcVT = N0.getValueType(); 8582 EVT DstVT = Op.getValueType(); 8583 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 8584 return LowerUINT_TO_FP_i64(Op, DAG); 8585 if (SrcVT == MVT::i32 && X86ScalarSSEf64) 8586 return LowerUINT_TO_FP_i32(Op, DAG); 8587 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32) 8588 return SDValue(); 8589 8590 // Make a 64-bit buffer, and use it to build an FILD. 8591 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 8592 if (SrcVT == MVT::i32) { 8593 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 8594 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 8595 getPointerTy(), StackSlot, WordOff); 8596 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8597 StackSlot, MachinePointerInfo(), 8598 false, false, 0); 8599 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 8600 OffsetSlot, MachinePointerInfo(), 8601 false, false, 0); 8602 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 8603 return Fild; 8604 } 8605 8606 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 8607 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8608 StackSlot, MachinePointerInfo(), 8609 false, false, 0); 8610 // For i64 source, we need to add the appropriate power of 2 if the input 8611 // was negative. This is the same as the optimization in 8612 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 8613 // we must be careful to do the computation in x87 extended precision, not 8614 // in SSE. (The generic code can't know it's OK to do this, or how to.) 8615 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 8616 MachineMemOperand *MMO = 8617 DAG.getMachineFunction() 8618 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8619 MachineMemOperand::MOLoad, 8, 8); 8620 8621 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 8622 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 8623 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 8624 array_lengthof(Ops), MVT::i64, MMO); 8625 8626 APInt FF(32, 0x5F800000ULL); 8627 8628 // Check whether the sign bit is set. 8629 SDValue SignSet = DAG.getSetCC(dl, 8630 getSetCCResultType(*DAG.getContext(), MVT::i64), 8631 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 8632 ISD::SETLT); 8633 8634 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 8635 SDValue FudgePtr = DAG.getConstantPool( 8636 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 8637 getPointerTy()); 8638 8639 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 8640 SDValue Zero = DAG.getIntPtrConstant(0); 8641 SDValue Four = DAG.getIntPtrConstant(4); 8642 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 8643 Zero, Four); 8644 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 8645 8646 // Load the value out, extending it from f32 to f80. 8647 // FIXME: Avoid the extend by constructing the right constant pool? 8648 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 8649 FudgePtr, MachinePointerInfo::getConstantPool(), 8650 MVT::f32, false, false, 4); 8651 // Extend everything to 80 bits to force it to be done on x87. 8652 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 8653 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 8654 } 8655 8656 std::pair<SDValue,SDValue> 8657 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, 8658 bool IsSigned, bool IsReplace) const { 8659 SDLoc DL(Op); 8660 8661 EVT DstTy = Op.getValueType(); 8662 8663 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) { 8664 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 8665 DstTy = MVT::i64; 8666 } 8667 8668 assert(DstTy.getSimpleVT() <= MVT::i64 && 8669 DstTy.getSimpleVT() >= MVT::i16 && 8670 "Unknown FP_TO_INT to lower!"); 8671 8672 // These are really Legal. 8673 if (DstTy == MVT::i32 && 8674 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8675 return std::make_pair(SDValue(), SDValue()); 8676 if (Subtarget->is64Bit() && 8677 DstTy == MVT::i64 && 8678 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8679 return std::make_pair(SDValue(), SDValue()); 8680 8681 // We lower FP->int64 either into FISTP64 followed by a load from a temporary 8682 // stack slot, or into the FTOL runtime function. 8683 MachineFunction &MF = DAG.getMachineFunction(); 8684 unsigned MemSize = DstTy.getSizeInBits()/8; 8685 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8686 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8687 8688 unsigned Opc; 8689 if (!IsSigned && isIntegerTypeFTOL(DstTy)) 8690 Opc = X86ISD::WIN_FTOL; 8691 else 8692 switch (DstTy.getSimpleVT().SimpleTy) { 8693 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 8694 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 8695 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 8696 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 8697 } 8698 8699 SDValue Chain = DAG.getEntryNode(); 8700 SDValue Value = Op.getOperand(0); 8701 EVT TheVT = Op.getOperand(0).getValueType(); 8702 // FIXME This causes a redundant load/store if the SSE-class value is already 8703 // in memory, such as if it is on the callstack. 8704 if (isScalarFPTypeInSSEReg(TheVT)) { 8705 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 8706 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 8707 MachinePointerInfo::getFixedStack(SSFI), 8708 false, false, 0); 8709 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 8710 SDValue Ops[] = { 8711 Chain, StackSlot, DAG.getValueType(TheVT) 8712 }; 8713 8714 MachineMemOperand *MMO = 8715 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8716 MachineMemOperand::MOLoad, MemSize, MemSize); 8717 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 8718 array_lengthof(Ops), DstTy, MMO); 8719 Chain = Value.getValue(1); 8720 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8721 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8722 } 8723 8724 MachineMemOperand *MMO = 8725 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8726 MachineMemOperand::MOStore, MemSize, MemSize); 8727 8728 if (Opc != X86ISD::WIN_FTOL) { 8729 // Build the FP_TO_INT*_IN_MEM 8730 SDValue Ops[] = { Chain, Value, StackSlot }; 8731 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8732 Ops, array_lengthof(Ops), DstTy, 8733 MMO); 8734 return std::make_pair(FIST, StackSlot); 8735 } else { 8736 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL, 8737 DAG.getVTList(MVT::Other, MVT::Glue), 8738 Chain, Value); 8739 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX, 8740 MVT::i32, ftol.getValue(1)); 8741 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX, 8742 MVT::i32, eax.getValue(2)); 8743 SDValue Ops[] = { eax, edx }; 8744 SDValue pair = IsReplace 8745 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops)) 8746 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL); 8747 return std::make_pair(pair, SDValue()); 8748 } 8749 } 8750 8751 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG, 8752 const X86Subtarget *Subtarget) { 8753 MVT VT = Op->getValueType(0).getSimpleVT(); 8754 SDValue In = Op->getOperand(0); 8755 MVT InVT = In.getValueType().getSimpleVT(); 8756 SDLoc dl(Op); 8757 8758 // Optimize vectors in AVX mode: 8759 // 8760 // v8i16 -> v8i32 8761 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32. 8762 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32. 8763 // Concat upper and lower parts. 8764 // 8765 // v4i32 -> v4i64 8766 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64. 8767 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64. 8768 // Concat upper and lower parts. 8769 // 8770 8771 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) && 8772 ((VT != MVT::v4i64) || (InVT != MVT::v4i32))) 8773 return SDValue(); 8774 8775 if (Subtarget->hasInt256()) 8776 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In); 8777 8778 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl); 8779 SDValue Undef = DAG.getUNDEF(InVT); 8780 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND; 8781 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8782 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8783 8784 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(), 8785 VT.getVectorNumElements()/2); 8786 8787 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo); 8788 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi); 8789 8790 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 8791 } 8792 8793 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op, 8794 SelectionDAG &DAG) const { 8795 if (Subtarget->hasFp256()) { 8796 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8797 if (Res.getNode()) 8798 return Res; 8799 } 8800 8801 return SDValue(); 8802 } 8803 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op, 8804 SelectionDAG &DAG) const { 8805 SDLoc DL(Op); 8806 MVT VT = Op.getValueType().getSimpleVT(); 8807 SDValue In = Op.getOperand(0); 8808 MVT SVT = In.getValueType().getSimpleVT(); 8809 8810 if (Subtarget->hasFp256()) { 8811 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8812 if (Res.getNode()) 8813 return Res; 8814 } 8815 8816 if (!VT.is256BitVector() || !SVT.is128BitVector() || 8817 VT.getVectorNumElements() != SVT.getVectorNumElements()) 8818 return SDValue(); 8819 8820 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!"); 8821 8822 // AVX2 has better support of integer extending. 8823 if (Subtarget->hasInt256()) 8824 return DAG.getNode(X86ISD::VZEXT, DL, VT, In); 8825 8826 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In); 8827 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1}; 8828 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, 8829 DAG.getVectorShuffle(MVT::v8i16, DL, In, 8830 DAG.getUNDEF(MVT::v8i16), 8831 &Mask[0])); 8832 8833 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi); 8834 } 8835 8836 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 8837 SDLoc DL(Op); 8838 MVT VT = Op.getValueType().getSimpleVT(); 8839 SDValue In = Op.getOperand(0); 8840 MVT SVT = In.getValueType().getSimpleVT(); 8841 8842 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) { 8843 // On AVX2, v4i64 -> v4i32 becomes VPERMD. 8844 if (Subtarget->hasInt256()) { 8845 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1}; 8846 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In); 8847 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32), 8848 ShufMask); 8849 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In, 8850 DAG.getIntPtrConstant(0)); 8851 } 8852 8853 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS. 8854 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8855 DAG.getIntPtrConstant(0)); 8856 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8857 DAG.getIntPtrConstant(2)); 8858 8859 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8860 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8861 8862 // The PSHUFD mask: 8863 static const int ShufMask1[] = {0, 2, 0, 0}; 8864 SDValue Undef = DAG.getUNDEF(VT); 8865 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1); 8866 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1); 8867 8868 // The MOVLHPS mask: 8869 static const int ShufMask2[] = {0, 1, 4, 5}; 8870 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2); 8871 } 8872 8873 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) { 8874 // On AVX2, v8i32 -> v8i16 becomed PSHUFB. 8875 if (Subtarget->hasInt256()) { 8876 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In); 8877 8878 SmallVector<SDValue,32> pshufbMask; 8879 for (unsigned i = 0; i < 2; ++i) { 8880 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8)); 8881 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8)); 8882 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8)); 8883 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8)); 8884 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8)); 8885 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8)); 8886 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8)); 8887 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8)); 8888 for (unsigned j = 0; j < 8; ++j) 8889 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 8890 } 8891 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, 8892 &pshufbMask[0], 32); 8893 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV); 8894 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In); 8895 8896 static const int ShufMask[] = {0, 2, -1, -1}; 8897 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64), 8898 &ShufMask[0]); 8899 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8900 DAG.getIntPtrConstant(0)); 8901 return DAG.getNode(ISD::BITCAST, DL, VT, In); 8902 } 8903 8904 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8905 DAG.getIntPtrConstant(0)); 8906 8907 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8908 DAG.getIntPtrConstant(4)); 8909 8910 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo); 8911 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi); 8912 8913 // The PSHUFB mask: 8914 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13, 8915 -1, -1, -1, -1, -1, -1, -1, -1}; 8916 8917 SDValue Undef = DAG.getUNDEF(MVT::v16i8); 8918 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1); 8919 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1); 8920 8921 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8922 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8923 8924 // The MOVLHPS Mask: 8925 static const int ShufMask2[] = {0, 1, 4, 5}; 8926 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2); 8927 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res); 8928 } 8929 8930 // Handle truncation of V256 to V128 using shuffles. 8931 if (!VT.is128BitVector() || !SVT.is256BitVector()) 8932 return SDValue(); 8933 8934 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() && 8935 "Invalid op"); 8936 assert(Subtarget->hasFp256() && "256-bit vector without AVX!"); 8937 8938 unsigned NumElems = VT.getVectorNumElements(); 8939 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8940 NumElems * 2); 8941 8942 SmallVector<int, 16> MaskVec(NumElems * 2, -1); 8943 // Prepare truncation shuffle mask 8944 for (unsigned i = 0; i != NumElems; ++i) 8945 MaskVec[i] = i * 2; 8946 SDValue V = DAG.getVectorShuffle(NVT, DL, 8947 DAG.getNode(ISD::BITCAST, DL, NVT, In), 8948 DAG.getUNDEF(NVT), &MaskVec[0]); 8949 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, 8950 DAG.getIntPtrConstant(0)); 8951 } 8952 8953 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8954 SelectionDAG &DAG) const { 8955 MVT VT = Op.getValueType().getSimpleVT(); 8956 if (VT.isVector()) { 8957 if (VT == MVT::v8i16) 8958 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT, 8959 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op), 8960 MVT::v8i32, Op.getOperand(0))); 8961 return SDValue(); 8962 } 8963 8964 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8965 /*IsSigned=*/ true, /*IsReplace=*/ false); 8966 SDValue FIST = Vals.first, StackSlot = Vals.second; 8967 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8968 if (FIST.getNode() == 0) return Op; 8969 8970 if (StackSlot.getNode()) 8971 // Load the result. 8972 return DAG.getLoad(Op.getValueType(), SDLoc(Op), 8973 FIST, StackSlot, MachinePointerInfo(), 8974 false, false, false, 0); 8975 8976 // The node is the result. 8977 return FIST; 8978 } 8979 8980 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8981 SelectionDAG &DAG) const { 8982 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8983 /*IsSigned=*/ false, /*IsReplace=*/ false); 8984 SDValue FIST = Vals.first, StackSlot = Vals.second; 8985 assert(FIST.getNode() && "Unexpected failure"); 8986 8987 if (StackSlot.getNode()) 8988 // Load the result. 8989 return DAG.getLoad(Op.getValueType(), SDLoc(Op), 8990 FIST, StackSlot, MachinePointerInfo(), 8991 false, false, false, 0); 8992 8993 // The node is the result. 8994 return FIST; 8995 } 8996 8997 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) { 8998 SDLoc DL(Op); 8999 MVT VT = Op.getValueType().getSimpleVT(); 9000 SDValue In = Op.getOperand(0); 9001 MVT SVT = In.getValueType().getSimpleVT(); 9002 9003 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!"); 9004 9005 return DAG.getNode(X86ISD::VFPEXT, DL, VT, 9006 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, 9007 In, DAG.getUNDEF(SVT))); 9008 } 9009 9010 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const { 9011 LLVMContext *Context = DAG.getContext(); 9012 SDLoc dl(Op); 9013 MVT VT = Op.getValueType().getSimpleVT(); 9014 MVT EltVT = VT; 9015 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 9016 if (VT.isVector()) { 9017 EltVT = VT.getVectorElementType(); 9018 NumElts = VT.getVectorNumElements(); 9019 } 9020 Constant *C; 9021 if (EltVT == MVT::f64) 9022 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 9023 APInt(64, ~(1ULL << 63)))); 9024 else 9025 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle, 9026 APInt(32, ~(1U << 31)))); 9027 C = ConstantVector::getSplat(NumElts, C); 9028 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 9029 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 9030 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9031 MachinePointerInfo::getConstantPool(), 9032 false, false, false, Alignment); 9033 if (VT.isVector()) { 9034 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 9035 return DAG.getNode(ISD::BITCAST, dl, VT, 9036 DAG.getNode(ISD::AND, dl, ANDVT, 9037 DAG.getNode(ISD::BITCAST, dl, ANDVT, 9038 Op.getOperand(0)), 9039 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask))); 9040 } 9041 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 9042 } 9043 9044 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 9045 LLVMContext *Context = DAG.getContext(); 9046 SDLoc dl(Op); 9047 MVT VT = Op.getValueType().getSimpleVT(); 9048 MVT EltVT = VT; 9049 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 9050 if (VT.isVector()) { 9051 EltVT = VT.getVectorElementType(); 9052 NumElts = VT.getVectorNumElements(); 9053 } 9054 Constant *C; 9055 if (EltVT == MVT::f64) 9056 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 9057 APInt(64, 1ULL << 63))); 9058 else 9059 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle, 9060 APInt(32, 1U << 31))); 9061 C = ConstantVector::getSplat(NumElts, C); 9062 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 9063 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 9064 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9065 MachinePointerInfo::getConstantPool(), 9066 false, false, false, Alignment); 9067 if (VT.isVector()) { 9068 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 9069 return DAG.getNode(ISD::BITCAST, dl, VT, 9070 DAG.getNode(ISD::XOR, dl, XORVT, 9071 DAG.getNode(ISD::BITCAST, dl, XORVT, 9072 Op.getOperand(0)), 9073 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask))); 9074 } 9075 9076 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 9077 } 9078 9079 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 9080 LLVMContext *Context = DAG.getContext(); 9081 SDValue Op0 = Op.getOperand(0); 9082 SDValue Op1 = Op.getOperand(1); 9083 SDLoc dl(Op); 9084 MVT VT = Op.getValueType().getSimpleVT(); 9085 MVT SrcVT = Op1.getValueType().getSimpleVT(); 9086 9087 // If second operand is smaller, extend it first. 9088 if (SrcVT.bitsLT(VT)) { 9089 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 9090 SrcVT = VT; 9091 } 9092 // And if it is bigger, shrink it first. 9093 if (SrcVT.bitsGT(VT)) { 9094 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 9095 SrcVT = VT; 9096 } 9097 9098 // At this point the operands and the result should have the same 9099 // type, and that won't be f80 since that is not custom lowered. 9100 9101 // First get the sign bit of second operand. 9102 SmallVector<Constant*,4> CV; 9103 if (SrcVT == MVT::f64) { 9104 const fltSemantics &Sem = APFloat::IEEEdouble; 9105 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63)))); 9106 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0)))); 9107 } else { 9108 const fltSemantics &Sem = APFloat::IEEEsingle; 9109 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31)))); 9110 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9111 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9112 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9113 } 9114 Constant *C = ConstantVector::get(CV); 9115 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 9116 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 9117 MachinePointerInfo::getConstantPool(), 9118 false, false, false, 16); 9119 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 9120 9121 // Shift sign bit right or left if the two operands have different types. 9122 if (SrcVT.bitsGT(VT)) { 9123 // Op0 is MVT::f32, Op1 is MVT::f64. 9124 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 9125 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 9126 DAG.getConstant(32, MVT::i32)); 9127 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 9128 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 9129 DAG.getIntPtrConstant(0)); 9130 } 9131 9132 // Clear first operand sign bit. 9133 CV.clear(); 9134 if (VT == MVT::f64) { 9135 const fltSemantics &Sem = APFloat::IEEEdouble; 9136 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, 9137 APInt(64, ~(1ULL << 63))))); 9138 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0)))); 9139 } else { 9140 const fltSemantics &Sem = APFloat::IEEEsingle; 9141 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, 9142 APInt(32, ~(1U << 31))))); 9143 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9144 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9145 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 9146 } 9147 C = ConstantVector::get(CV); 9148 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 9149 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 9150 MachinePointerInfo::getConstantPool(), 9151 false, false, false, 16); 9152 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 9153 9154 // Or the value with the sign bit. 9155 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 9156 } 9157 9158 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) { 9159 SDValue N0 = Op.getOperand(0); 9160 SDLoc dl(Op); 9161 MVT VT = Op.getValueType().getSimpleVT(); 9162 9163 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 9164 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 9165 DAG.getConstant(1, VT)); 9166 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 9167 } 9168 9169 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able. 9170 // 9171 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, 9172 SelectionDAG &DAG) const { 9173 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree."); 9174 9175 if (!Subtarget->hasSSE41()) 9176 return SDValue(); 9177 9178 if (!Op->hasOneUse()) 9179 return SDValue(); 9180 9181 SDNode *N = Op.getNode(); 9182 SDLoc DL(N); 9183 9184 SmallVector<SDValue, 8> Opnds; 9185 DenseMap<SDValue, unsigned> VecInMap; 9186 EVT VT = MVT::Other; 9187 9188 // Recognize a special case where a vector is casted into wide integer to 9189 // test all 0s. 9190 Opnds.push_back(N->getOperand(0)); 9191 Opnds.push_back(N->getOperand(1)); 9192 9193 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) { 9194 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot; 9195 // BFS traverse all OR'd operands. 9196 if (I->getOpcode() == ISD::OR) { 9197 Opnds.push_back(I->getOperand(0)); 9198 Opnds.push_back(I->getOperand(1)); 9199 // Re-evaluate the number of nodes to be traversed. 9200 e += 2; // 2 more nodes (LHS and RHS) are pushed. 9201 continue; 9202 } 9203 9204 // Quit if a non-EXTRACT_VECTOR_ELT 9205 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9206 return SDValue(); 9207 9208 // Quit if without a constant index. 9209 SDValue Idx = I->getOperand(1); 9210 if (!isa<ConstantSDNode>(Idx)) 9211 return SDValue(); 9212 9213 SDValue ExtractedFromVec = I->getOperand(0); 9214 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec); 9215 if (M == VecInMap.end()) { 9216 VT = ExtractedFromVec.getValueType(); 9217 // Quit if not 128/256-bit vector. 9218 if (!VT.is128BitVector() && !VT.is256BitVector()) 9219 return SDValue(); 9220 // Quit if not the same type. 9221 if (VecInMap.begin() != VecInMap.end() && 9222 VT != VecInMap.begin()->first.getValueType()) 9223 return SDValue(); 9224 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first; 9225 } 9226 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue(); 9227 } 9228 9229 assert((VT.is128BitVector() || VT.is256BitVector()) && 9230 "Not extracted from 128-/256-bit vector."); 9231 9232 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U; 9233 SmallVector<SDValue, 8> VecIns; 9234 9235 for (DenseMap<SDValue, unsigned>::const_iterator 9236 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) { 9237 // Quit if not all elements are used. 9238 if (I->second != FullMask) 9239 return SDValue(); 9240 VecIns.push_back(I->first); 9241 } 9242 9243 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 9244 9245 // Cast all vectors into TestVT for PTEST. 9246 for (unsigned i = 0, e = VecIns.size(); i < e; ++i) 9247 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]); 9248 9249 // If more than one full vectors are evaluated, OR them first before PTEST. 9250 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) { 9251 // Each iteration will OR 2 nodes and append the result until there is only 9252 // 1 node left, i.e. the final OR'd value of all vectors. 9253 SDValue LHS = VecIns[Slot]; 9254 SDValue RHS = VecIns[Slot + 1]; 9255 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS)); 9256 } 9257 9258 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, 9259 VecIns.back(), VecIns.back()); 9260 } 9261 9262 /// Emit nodes that will be selected as "test Op0,Op0", or something 9263 /// equivalent. 9264 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 9265 SelectionDAG &DAG) const { 9266 SDLoc dl(Op); 9267 9268 // CF and OF aren't always set the way we want. Determine which 9269 // of these we need. 9270 bool NeedCF = false; 9271 bool NeedOF = false; 9272 switch (X86CC) { 9273 default: break; 9274 case X86::COND_A: case X86::COND_AE: 9275 case X86::COND_B: case X86::COND_BE: 9276 NeedCF = true; 9277 break; 9278 case X86::COND_G: case X86::COND_GE: 9279 case X86::COND_L: case X86::COND_LE: 9280 case X86::COND_O: case X86::COND_NO: 9281 NeedOF = true; 9282 break; 9283 } 9284 9285 // See if we can use the EFLAGS value from the operand instead of 9286 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 9287 // we prove that the arithmetic won't overflow, we can't use OF or CF. 9288 if (Op.getResNo() != 0 || NeedOF || NeedCF) 9289 // Emit a CMP with 0, which is the TEST pattern. 9290 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 9291 DAG.getConstant(0, Op.getValueType())); 9292 9293 unsigned Opcode = 0; 9294 unsigned NumOperands = 0; 9295 9296 // Truncate operations may prevent the merge of the SETCC instruction 9297 // and the arithmetic intruction before it. Attempt to truncate the operands 9298 // of the arithmetic instruction and use a reduced bit-width instruction. 9299 bool NeedTruncation = false; 9300 SDValue ArithOp = Op; 9301 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) { 9302 SDValue Arith = Op->getOperand(0); 9303 // Both the trunc and the arithmetic op need to have one user each. 9304 if (Arith->hasOneUse()) 9305 switch (Arith.getOpcode()) { 9306 default: break; 9307 case ISD::ADD: 9308 case ISD::SUB: 9309 case ISD::AND: 9310 case ISD::OR: 9311 case ISD::XOR: { 9312 NeedTruncation = true; 9313 ArithOp = Arith; 9314 } 9315 } 9316 } 9317 9318 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation 9319 // which may be the result of a CAST. We use the variable 'Op', which is the 9320 // non-casted variable when we check for possible users. 9321 switch (ArithOp.getOpcode()) { 9322 case ISD::ADD: 9323 // Due to an isel shortcoming, be conservative if this add is likely to be 9324 // selected as part of a load-modify-store instruction. When the root node 9325 // in a match is a store, isel doesn't know how to remap non-chain non-flag 9326 // uses of other nodes in the match, such as the ADD in this case. This 9327 // leads to the ADD being left around and reselected, with the result being 9328 // two adds in the output. Alas, even if none our users are stores, that 9329 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 9330 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 9331 // climbing the DAG back to the root, and it doesn't seem to be worth the 9332 // effort. 9333 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 9334 UE = Op.getNode()->use_end(); UI != UE; ++UI) 9335 if (UI->getOpcode() != ISD::CopyToReg && 9336 UI->getOpcode() != ISD::SETCC && 9337 UI->getOpcode() != ISD::STORE) 9338 goto default_case; 9339 9340 if (ConstantSDNode *C = 9341 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) { 9342 // An add of one will be selected as an INC. 9343 if (C->getAPIntValue() == 1) { 9344 Opcode = X86ISD::INC; 9345 NumOperands = 1; 9346 break; 9347 } 9348 9349 // An add of negative one (subtract of one) will be selected as a DEC. 9350 if (C->getAPIntValue().isAllOnesValue()) { 9351 Opcode = X86ISD::DEC; 9352 NumOperands = 1; 9353 break; 9354 } 9355 } 9356 9357 // Otherwise use a regular EFLAGS-setting add. 9358 Opcode = X86ISD::ADD; 9359 NumOperands = 2; 9360 break; 9361 case ISD::AND: { 9362 // If the primary and result isn't used, don't bother using X86ISD::AND, 9363 // because a TEST instruction will be better. 9364 bool NonFlagUse = false; 9365 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 9366 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 9367 SDNode *User = *UI; 9368 unsigned UOpNo = UI.getOperandNo(); 9369 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 9370 // Look pass truncate. 9371 UOpNo = User->use_begin().getOperandNo(); 9372 User = *User->use_begin(); 9373 } 9374 9375 if (User->getOpcode() != ISD::BRCOND && 9376 User->getOpcode() != ISD::SETCC && 9377 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) { 9378 NonFlagUse = true; 9379 break; 9380 } 9381 } 9382 9383 if (!NonFlagUse) 9384 break; 9385 } 9386 // FALL THROUGH 9387 case ISD::SUB: 9388 case ISD::OR: 9389 case ISD::XOR: 9390 // Due to the ISEL shortcoming noted above, be conservative if this op is 9391 // likely to be selected as part of a load-modify-store instruction. 9392 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 9393 UE = Op.getNode()->use_end(); UI != UE; ++UI) 9394 if (UI->getOpcode() == ISD::STORE) 9395 goto default_case; 9396 9397 // Otherwise use a regular EFLAGS-setting instruction. 9398 switch (ArithOp.getOpcode()) { 9399 default: llvm_unreachable("unexpected operator!"); 9400 case ISD::SUB: Opcode = X86ISD::SUB; break; 9401 case ISD::XOR: Opcode = X86ISD::XOR; break; 9402 case ISD::AND: Opcode = X86ISD::AND; break; 9403 case ISD::OR: { 9404 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) { 9405 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG); 9406 if (EFLAGS.getNode()) 9407 return EFLAGS; 9408 } 9409 Opcode = X86ISD::OR; 9410 break; 9411 } 9412 } 9413 9414 NumOperands = 2; 9415 break; 9416 case X86ISD::ADD: 9417 case X86ISD::SUB: 9418 case X86ISD::INC: 9419 case X86ISD::DEC: 9420 case X86ISD::OR: 9421 case X86ISD::XOR: 9422 case X86ISD::AND: 9423 return SDValue(Op.getNode(), 1); 9424 default: 9425 default_case: 9426 break; 9427 } 9428 9429 // If we found that truncation is beneficial, perform the truncation and 9430 // update 'Op'. 9431 if (NeedTruncation) { 9432 EVT VT = Op.getValueType(); 9433 SDValue WideVal = Op->getOperand(0); 9434 EVT WideVT = WideVal.getValueType(); 9435 unsigned ConvertedOp = 0; 9436 // Use a target machine opcode to prevent further DAGCombine 9437 // optimizations that may separate the arithmetic operations 9438 // from the setcc node. 9439 switch (WideVal.getOpcode()) { 9440 default: break; 9441 case ISD::ADD: ConvertedOp = X86ISD::ADD; break; 9442 case ISD::SUB: ConvertedOp = X86ISD::SUB; break; 9443 case ISD::AND: ConvertedOp = X86ISD::AND; break; 9444 case ISD::OR: ConvertedOp = X86ISD::OR; break; 9445 case ISD::XOR: ConvertedOp = X86ISD::XOR; break; 9446 } 9447 9448 if (ConvertedOp) { 9449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9450 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) { 9451 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0)); 9452 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1)); 9453 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1); 9454 } 9455 } 9456 } 9457 9458 if (Opcode == 0) 9459 // Emit a CMP with 0, which is the TEST pattern. 9460 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 9461 DAG.getConstant(0, Op.getValueType())); 9462 9463 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 9464 SmallVector<SDValue, 4> Ops; 9465 for (unsigned i = 0; i != NumOperands; ++i) 9466 Ops.push_back(Op.getOperand(i)); 9467 9468 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 9469 DAG.ReplaceAllUsesWith(Op, New); 9470 return SDValue(New.getNode(), 1); 9471 } 9472 9473 /// Emit nodes that will be selected as "cmp Op0,Op1", or something 9474 /// equivalent. 9475 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 9476 SelectionDAG &DAG) const { 9477 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 9478 if (C->getAPIntValue() == 0) 9479 return EmitTest(Op0, X86CC, DAG); 9480 9481 SDLoc dl(Op0); 9482 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 || 9483 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) { 9484 // Use SUB instead of CMP to enable CSE between SUB and CMP. 9485 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32); 9486 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, 9487 Op0, Op1); 9488 return SDValue(Sub.getNode(), 1); 9489 } 9490 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 9491 } 9492 9493 /// Convert a comparison if required by the subtarget. 9494 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp, 9495 SelectionDAG &DAG) const { 9496 // If the subtarget does not support the FUCOMI instruction, floating-point 9497 // comparisons have to be converted. 9498 if (Subtarget->hasCMov() || 9499 Cmp.getOpcode() != X86ISD::CMP || 9500 !Cmp.getOperand(0).getValueType().isFloatingPoint() || 9501 !Cmp.getOperand(1).getValueType().isFloatingPoint()) 9502 return Cmp; 9503 9504 // The instruction selector will select an FUCOM instruction instead of 9505 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence 9506 // build an SDNode sequence that transfers the result from FPSW into EFLAGS: 9507 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8)))) 9508 SDLoc dl(Cmp); 9509 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp); 9510 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW); 9511 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW, 9512 DAG.getConstant(8, MVT::i8)); 9513 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl); 9514 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl); 9515 } 9516 9517 static bool isAllOnes(SDValue V) { 9518 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9519 return C && C->isAllOnesValue(); 9520 } 9521 9522 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 9523 /// if it's possible. 9524 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 9525 SDLoc dl, SelectionDAG &DAG) const { 9526 SDValue Op0 = And.getOperand(0); 9527 SDValue Op1 = And.getOperand(1); 9528 if (Op0.getOpcode() == ISD::TRUNCATE) 9529 Op0 = Op0.getOperand(0); 9530 if (Op1.getOpcode() == ISD::TRUNCATE) 9531 Op1 = Op1.getOperand(0); 9532 9533 SDValue LHS, RHS; 9534 if (Op1.getOpcode() == ISD::SHL) 9535 std::swap(Op0, Op1); 9536 if (Op0.getOpcode() == ISD::SHL) { 9537 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 9538 if (And00C->getZExtValue() == 1) { 9539 // If we looked past a truncate, check that it's only truncating away 9540 // known zeros. 9541 unsigned BitWidth = Op0.getValueSizeInBits(); 9542 unsigned AndBitWidth = And.getValueSizeInBits(); 9543 if (BitWidth > AndBitWidth) { 9544 APInt Zeros, Ones; 9545 DAG.ComputeMaskedBits(Op0, Zeros, Ones); 9546 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 9547 return SDValue(); 9548 } 9549 LHS = Op1; 9550 RHS = Op0.getOperand(1); 9551 } 9552 } else if (Op1.getOpcode() == ISD::Constant) { 9553 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 9554 uint64_t AndRHSVal = AndRHS->getZExtValue(); 9555 SDValue AndLHS = Op0; 9556 9557 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) { 9558 LHS = AndLHS.getOperand(0); 9559 RHS = AndLHS.getOperand(1); 9560 } 9561 9562 // Use BT if the immediate can't be encoded in a TEST instruction. 9563 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) { 9564 LHS = AndLHS; 9565 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType()); 9566 } 9567 } 9568 9569 if (LHS.getNode()) { 9570 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 9571 // instruction. Since the shift amount is in-range-or-undefined, we know 9572 // that doing a bittest on the i32 value is ok. We extend to i32 because 9573 // the encoding for the i16 version is larger than the i32 version. 9574 // Also promote i16 to i32 for performance / code size reason. 9575 if (LHS.getValueType() == MVT::i8 || 9576 LHS.getValueType() == MVT::i16) 9577 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 9578 9579 // If the operand types disagree, extend the shift amount to match. Since 9580 // BT ignores high bits (like shifts) we can use anyextend. 9581 if (LHS.getValueType() != RHS.getValueType()) 9582 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 9583 9584 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 9585 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 9586 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9587 DAG.getConstant(Cond, MVT::i8), BT); 9588 } 9589 9590 return SDValue(); 9591 } 9592 9593 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point 9594 /// mask CMPs. 9595 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0, 9596 SDValue &Op1) { 9597 unsigned SSECC; 9598 bool Swap = false; 9599 9600 // SSE Condition code mapping: 9601 // 0 - EQ 9602 // 1 - LT 9603 // 2 - LE 9604 // 3 - UNORD 9605 // 4 - NEQ 9606 // 5 - NLT 9607 // 6 - NLE 9608 // 7 - ORD 9609 switch (SetCCOpcode) { 9610 default: llvm_unreachable("Unexpected SETCC condition"); 9611 case ISD::SETOEQ: 9612 case ISD::SETEQ: SSECC = 0; break; 9613 case ISD::SETOGT: 9614 case ISD::SETGT: Swap = true; // Fallthrough 9615 case ISD::SETLT: 9616 case ISD::SETOLT: SSECC = 1; break; 9617 case ISD::SETOGE: 9618 case ISD::SETGE: Swap = true; // Fallthrough 9619 case ISD::SETLE: 9620 case ISD::SETOLE: SSECC = 2; break; 9621 case ISD::SETUO: SSECC = 3; break; 9622 case ISD::SETUNE: 9623 case ISD::SETNE: SSECC = 4; break; 9624 case ISD::SETULE: Swap = true; // Fallthrough 9625 case ISD::SETUGE: SSECC = 5; break; 9626 case ISD::SETULT: Swap = true; // Fallthrough 9627 case ISD::SETUGT: SSECC = 6; break; 9628 case ISD::SETO: SSECC = 7; break; 9629 case ISD::SETUEQ: 9630 case ISD::SETONE: SSECC = 8; break; 9631 } 9632 if (Swap) 9633 std::swap(Op0, Op1); 9634 9635 return SSECC; 9636 } 9637 9638 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 9639 // ones, and then concatenate the result back. 9640 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 9641 MVT VT = Op.getValueType().getSimpleVT(); 9642 9643 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC && 9644 "Unsupported value type for operation"); 9645 9646 unsigned NumElems = VT.getVectorNumElements(); 9647 SDLoc dl(Op); 9648 SDValue CC = Op.getOperand(2); 9649 9650 // Extract the LHS vectors 9651 SDValue LHS = Op.getOperand(0); 9652 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 9653 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 9654 9655 // Extract the RHS vectors 9656 SDValue RHS = Op.getOperand(1); 9657 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 9658 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 9659 9660 // Issue the operation on the smaller types and concatenate the result back 9661 MVT EltVT = VT.getVectorElementType(); 9662 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 9663 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9664 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 9665 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 9666 } 9667 9668 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget, 9669 SelectionDAG &DAG) { 9670 SDValue Cond; 9671 SDValue Op0 = Op.getOperand(0); 9672 SDValue Op1 = Op.getOperand(1); 9673 SDValue CC = Op.getOperand(2); 9674 MVT VT = Op.getValueType().getSimpleVT(); 9675 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 9676 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint(); 9677 SDLoc dl(Op); 9678 9679 if (isFP) { 9680 #ifndef NDEBUG 9681 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT(); 9682 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 9683 #endif 9684 9685 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1); 9686 9687 // In the two special cases we can't handle, emit two comparisons. 9688 if (SSECC == 8) { 9689 unsigned CC0, CC1; 9690 unsigned CombineOpc; 9691 if (SetCCOpcode == ISD::SETUEQ) { 9692 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR; 9693 } else { 9694 assert(SetCCOpcode == ISD::SETONE); 9695 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND; 9696 } 9697 9698 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9699 DAG.getConstant(CC0, MVT::i8)); 9700 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9701 DAG.getConstant(CC1, MVT::i8)); 9702 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1); 9703 } 9704 // Handle all other FP comparisons here. 9705 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9706 DAG.getConstant(SSECC, MVT::i8)); 9707 } 9708 9709 // Break 256-bit integer vector compare into smaller ones. 9710 if (VT.is256BitVector() && !Subtarget->hasInt256()) 9711 return Lower256IntVSETCC(Op, DAG); 9712 9713 // We are handling one of the integer comparisons here. Since SSE only has 9714 // GT and EQ comparisons for integer, swapping operands and multiple 9715 // operations may be required for some comparisons. 9716 unsigned Opc; 9717 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false; 9718 9719 switch (SetCCOpcode) { 9720 default: llvm_unreachable("Unexpected SETCC condition"); 9721 case ISD::SETNE: Invert = true; 9722 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break; 9723 case ISD::SETLT: Swap = true; 9724 case ISD::SETGT: Opc = X86ISD::PCMPGT; break; 9725 case ISD::SETGE: Swap = true; 9726 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break; 9727 case ISD::SETULT: Swap = true; 9728 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break; 9729 case ISD::SETUGE: Swap = true; 9730 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break; 9731 } 9732 9733 // Special case: Use min/max operations for SETULE/SETUGE 9734 MVT VET = VT.getVectorElementType(); 9735 bool hasMinMax = 9736 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32)) 9737 || (Subtarget->hasSSE2() && (VET == MVT::i8)); 9738 9739 if (hasMinMax) { 9740 switch (SetCCOpcode) { 9741 default: break; 9742 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break; 9743 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break; 9744 } 9745 9746 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; } 9747 } 9748 9749 if (Swap) 9750 std::swap(Op0, Op1); 9751 9752 // Check that the operation in question is available (most are plain SSE2, 9753 // but PCMPGTQ and PCMPEQQ have different requirements). 9754 if (VT == MVT::v2i64) { 9755 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) { 9756 assert(Subtarget->hasSSE2() && "Don't know how to lower!"); 9757 9758 // First cast everything to the right type. 9759 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0); 9760 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1); 9761 9762 // Since SSE has no unsigned integer comparisons, we need to flip the sign 9763 // bits of the inputs before performing those operations. The lower 9764 // compare is always unsigned. 9765 SDValue SB; 9766 if (FlipSigns) { 9767 SB = DAG.getConstant(0x80000000U, MVT::v4i32); 9768 } else { 9769 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32); 9770 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32); 9771 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, 9772 Sign, Zero, Sign, Zero); 9773 } 9774 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB); 9775 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB); 9776 9777 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2)) 9778 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1); 9779 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1); 9780 9781 // Create masks for only the low parts/high parts of the 64 bit integers. 9782 static const int MaskHi[] = { 1, 1, 3, 3 }; 9783 static const int MaskLo[] = { 0, 0, 2, 2 }; 9784 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi); 9785 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo); 9786 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi); 9787 9788 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo); 9789 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi); 9790 9791 if (Invert) 9792 Result = DAG.getNOT(dl, Result, MVT::v4i32); 9793 9794 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9795 } 9796 9797 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) { 9798 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with 9799 // pcmpeqd + pshufd + pand. 9800 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!"); 9801 9802 // First cast everything to the right type. 9803 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0); 9804 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1); 9805 9806 // Do the compare. 9807 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1); 9808 9809 // Make sure the lower and upper halves are both all-ones. 9810 static const int Mask[] = { 1, 0, 3, 2 }; 9811 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask); 9812 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf); 9813 9814 if (Invert) 9815 Result = DAG.getNOT(dl, Result, MVT::v4i32); 9816 9817 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9818 } 9819 } 9820 9821 // Since SSE has no unsigned integer comparisons, we need to flip the sign 9822 // bits of the inputs before performing those operations. 9823 if (FlipSigns) { 9824 EVT EltVT = VT.getVectorElementType(); 9825 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT); 9826 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB); 9827 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB); 9828 } 9829 9830 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 9831 9832 // If the logical-not of the result is required, perform that now. 9833 if (Invert) 9834 Result = DAG.getNOT(dl, Result, VT); 9835 9836 if (MinMax) 9837 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result); 9838 9839 return Result; 9840 } 9841 9842 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 9843 9844 MVT VT = Op.getValueType().getSimpleVT(); 9845 9846 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG); 9847 9848 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer"); 9849 SDValue Op0 = Op.getOperand(0); 9850 SDValue Op1 = Op.getOperand(1); 9851 SDLoc dl(Op); 9852 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 9853 9854 // Optimize to BT if possible. 9855 // Lower (X & (1 << N)) == 0 to BT(X, N). 9856 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 9857 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 9858 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 9859 Op1.getOpcode() == ISD::Constant && 9860 cast<ConstantSDNode>(Op1)->isNullValue() && 9861 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9862 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 9863 if (NewSetCC.getNode()) 9864 return NewSetCC; 9865 } 9866 9867 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 9868 // these. 9869 if (Op1.getOpcode() == ISD::Constant && 9870 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 9871 cast<ConstantSDNode>(Op1)->isNullValue()) && 9872 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9873 9874 // If the input is a setcc, then reuse the input setcc or use a new one with 9875 // the inverted condition. 9876 if (Op0.getOpcode() == X86ISD::SETCC) { 9877 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 9878 bool Invert = (CC == ISD::SETNE) ^ 9879 cast<ConstantSDNode>(Op1)->isNullValue(); 9880 if (!Invert) return Op0; 9881 9882 CCode = X86::GetOppositeBranchCondition(CCode); 9883 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9884 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 9885 } 9886 } 9887 9888 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint(); 9889 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 9890 if (X86CC == X86::COND_INVALID) 9891 return SDValue(); 9892 9893 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 9894 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG); 9895 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9896 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 9897 } 9898 9899 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 9900 static bool isX86LogicalCmp(SDValue Op) { 9901 unsigned Opc = Op.getNode()->getOpcode(); 9902 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI || 9903 Opc == X86ISD::SAHF) 9904 return true; 9905 if (Op.getResNo() == 1 && 9906 (Opc == X86ISD::ADD || 9907 Opc == X86ISD::SUB || 9908 Opc == X86ISD::ADC || 9909 Opc == X86ISD::SBB || 9910 Opc == X86ISD::SMUL || 9911 Opc == X86ISD::UMUL || 9912 Opc == X86ISD::INC || 9913 Opc == X86ISD::DEC || 9914 Opc == X86ISD::OR || 9915 Opc == X86ISD::XOR || 9916 Opc == X86ISD::AND)) 9917 return true; 9918 9919 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 9920 return true; 9921 9922 return false; 9923 } 9924 9925 static bool isZero(SDValue V) { 9926 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9927 return C && C->isNullValue(); 9928 } 9929 9930 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) { 9931 if (V.getOpcode() != ISD::TRUNCATE) 9932 return false; 9933 9934 SDValue VOp0 = V.getOperand(0); 9935 unsigned InBits = VOp0.getValueSizeInBits(); 9936 unsigned Bits = V.getValueSizeInBits(); 9937 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits)); 9938 } 9939 9940 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 9941 bool addTest = true; 9942 SDValue Cond = Op.getOperand(0); 9943 SDValue Op1 = Op.getOperand(1); 9944 SDValue Op2 = Op.getOperand(2); 9945 SDLoc DL(Op); 9946 EVT VT = Op1.getValueType(); 9947 SDValue CC; 9948 9949 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops 9950 // are available. Otherwise fp cmovs get lowered into a less efficient branch 9951 // sequence later on. 9952 if (Cond.getOpcode() == ISD::SETCC && 9953 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) || 9954 (Subtarget->hasSSE1() && VT == MVT::f32)) && 9955 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) { 9956 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1); 9957 int SSECC = translateX86FSETCC( 9958 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1); 9959 9960 if (SSECC != 8) { 9961 unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd; 9962 SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1, 9963 DAG.getConstant(SSECC, MVT::i8)); 9964 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2); 9965 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1); 9966 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And); 9967 } 9968 } 9969 9970 if (Cond.getOpcode() == ISD::SETCC) { 9971 SDValue NewCond = LowerSETCC(Cond, DAG); 9972 if (NewCond.getNode()) 9973 Cond = NewCond; 9974 } 9975 9976 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 9977 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 9978 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 9979 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 9980 if (Cond.getOpcode() == X86ISD::SETCC && 9981 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 9982 isZero(Cond.getOperand(1).getOperand(1))) { 9983 SDValue Cmp = Cond.getOperand(1); 9984 9985 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 9986 9987 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 9988 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 9989 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 9990 9991 SDValue CmpOp0 = Cmp.getOperand(0); 9992 // Apply further optimizations for special cases 9993 // (select (x != 0), -1, 0) -> neg & sbb 9994 // (select (x == 0), 0, -1) -> neg & sbb 9995 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y)) 9996 if (YC->isNullValue() && 9997 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) { 9998 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32); 9999 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 10000 DAG.getConstant(0, CmpOp0.getValueType()), 10001 CmpOp0); 10002 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 10003 DAG.getConstant(X86::COND_B, MVT::i8), 10004 SDValue(Neg.getNode(), 1)); 10005 return Res; 10006 } 10007 10008 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 10009 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 10010 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 10011 10012 SDValue Res = // Res = 0 or -1. 10013 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 10014 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 10015 10016 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 10017 Res = DAG.getNOT(DL, Res, Res.getValueType()); 10018 10019 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 10020 if (N2C == 0 || !N2C->isNullValue()) 10021 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 10022 return Res; 10023 } 10024 } 10025 10026 // Look past (and (setcc_carry (cmp ...)), 1). 10027 if (Cond.getOpcode() == ISD::AND && 10028 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 10029 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 10030 if (C && C->getAPIntValue() == 1) 10031 Cond = Cond.getOperand(0); 10032 } 10033 10034 // If condition flag is set by a X86ISD::CMP, then use it as the condition 10035 // setting operand in place of the X86ISD::SETCC. 10036 unsigned CondOpcode = Cond.getOpcode(); 10037 if (CondOpcode == X86ISD::SETCC || 10038 CondOpcode == X86ISD::SETCC_CARRY) { 10039 CC = Cond.getOperand(0); 10040 10041 SDValue Cmp = Cond.getOperand(1); 10042 unsigned Opc = Cmp.getOpcode(); 10043 MVT VT = Op.getValueType().getSimpleVT(); 10044 10045 bool IllegalFPCMov = false; 10046 if (VT.isFloatingPoint() && !VT.isVector() && 10047 !isScalarFPTypeInSSEReg(VT)) // FPStack? 10048 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 10049 10050 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 10051 Opc == X86ISD::BT) { // FIXME 10052 Cond = Cmp; 10053 addTest = false; 10054 } 10055 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 10056 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 10057 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 10058 Cond.getOperand(0).getValueType() != MVT::i8)) { 10059 SDValue LHS = Cond.getOperand(0); 10060 SDValue RHS = Cond.getOperand(1); 10061 unsigned X86Opcode; 10062 unsigned X86Cond; 10063 SDVTList VTs; 10064 switch (CondOpcode) { 10065 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 10066 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 10067 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 10068 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 10069 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 10070 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 10071 default: llvm_unreachable("unexpected overflowing operator"); 10072 } 10073 if (CondOpcode == ISD::UMULO) 10074 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 10075 MVT::i32); 10076 else 10077 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 10078 10079 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 10080 10081 if (CondOpcode == ISD::UMULO) 10082 Cond = X86Op.getValue(2); 10083 else 10084 Cond = X86Op.getValue(1); 10085 10086 CC = DAG.getConstant(X86Cond, MVT::i8); 10087 addTest = false; 10088 } 10089 10090 if (addTest) { 10091 // Look pass the truncate if the high bits are known zero. 10092 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 10093 Cond = Cond.getOperand(0); 10094 10095 // We know the result of AND is compared against zero. Try to match 10096 // it to BT. 10097 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 10098 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 10099 if (NewSetCC.getNode()) { 10100 CC = NewSetCC.getOperand(0); 10101 Cond = NewSetCC.getOperand(1); 10102 addTest = false; 10103 } 10104 } 10105 } 10106 10107 if (addTest) { 10108 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10109 Cond = EmitTest(Cond, X86::COND_NE, DAG); 10110 } 10111 10112 // a < b ? -1 : 0 -> RES = ~setcc_carry 10113 // a < b ? 0 : -1 -> RES = setcc_carry 10114 // a >= b ? -1 : 0 -> RES = setcc_carry 10115 // a >= b ? 0 : -1 -> RES = ~setcc_carry 10116 if (Cond.getOpcode() == X86ISD::SUB) { 10117 Cond = ConvertCmpIfNecessary(Cond, DAG); 10118 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 10119 10120 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 10121 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 10122 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 10123 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 10124 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 10125 return DAG.getNOT(DL, Res, Res.getValueType()); 10126 return Res; 10127 } 10128 } 10129 10130 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate 10131 // widen the cmov and push the truncate through. This avoids introducing a new 10132 // branch during isel and doesn't add any extensions. 10133 if (Op.getValueType() == MVT::i8 && 10134 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) { 10135 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0); 10136 if (T1.getValueType() == T2.getValueType() && 10137 // Blacklist CopyFromReg to avoid partial register stalls. 10138 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){ 10139 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue); 10140 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond); 10141 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov); 10142 } 10143 } 10144 10145 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 10146 // condition is true. 10147 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 10148 SDValue Ops[] = { Op2, Op1, CC, Cond }; 10149 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 10150 } 10151 10152 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op, 10153 SelectionDAG &DAG) const { 10154 MVT VT = Op->getValueType(0).getSimpleVT(); 10155 SDValue In = Op->getOperand(0); 10156 MVT InVT = In.getValueType().getSimpleVT(); 10157 SDLoc dl(Op); 10158 10159 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) && 10160 (VT != MVT::v8i32 || InVT != MVT::v8i16)) 10161 return SDValue(); 10162 10163 if (Subtarget->hasInt256()) 10164 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In); 10165 10166 // Optimize vectors in AVX mode 10167 // Sign extend v8i16 to v8i32 and 10168 // v4i32 to v4i64 10169 // 10170 // Divide input vector into two parts 10171 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1} 10172 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32 10173 // concat the vectors to original VT 10174 10175 unsigned NumElems = InVT.getVectorNumElements(); 10176 SDValue Undef = DAG.getUNDEF(InVT); 10177 10178 SmallVector<int,8> ShufMask1(NumElems, -1); 10179 for (unsigned i = 0; i != NumElems/2; ++i) 10180 ShufMask1[i] = i; 10181 10182 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]); 10183 10184 SmallVector<int,8> ShufMask2(NumElems, -1); 10185 for (unsigned i = 0; i != NumElems/2; ++i) 10186 ShufMask2[i] = i + NumElems/2; 10187 10188 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]); 10189 10190 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(), 10191 VT.getVectorNumElements()/2); 10192 10193 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 10194 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi); 10195 10196 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 10197 } 10198 10199 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 10200 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 10201 // from the AND / OR. 10202 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 10203 Opc = Op.getOpcode(); 10204 if (Opc != ISD::OR && Opc != ISD::AND) 10205 return false; 10206 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 10207 Op.getOperand(0).hasOneUse() && 10208 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 10209 Op.getOperand(1).hasOneUse()); 10210 } 10211 10212 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 10213 // 1 and that the SETCC node has a single use. 10214 static bool isXor1OfSetCC(SDValue Op) { 10215 if (Op.getOpcode() != ISD::XOR) 10216 return false; 10217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10218 if (N1C && N1C->getAPIntValue() == 1) { 10219 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 10220 Op.getOperand(0).hasOneUse(); 10221 } 10222 return false; 10223 } 10224 10225 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 10226 bool addTest = true; 10227 SDValue Chain = Op.getOperand(0); 10228 SDValue Cond = Op.getOperand(1); 10229 SDValue Dest = Op.getOperand(2); 10230 SDLoc dl(Op); 10231 SDValue CC; 10232 bool Inverted = false; 10233 10234 if (Cond.getOpcode() == ISD::SETCC) { 10235 // Check for setcc([su]{add,sub,mul}o == 0). 10236 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 10237 isa<ConstantSDNode>(Cond.getOperand(1)) && 10238 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 10239 Cond.getOperand(0).getResNo() == 1 && 10240 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 10241 Cond.getOperand(0).getOpcode() == ISD::UADDO || 10242 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 10243 Cond.getOperand(0).getOpcode() == ISD::USUBO || 10244 Cond.getOperand(0).getOpcode() == ISD::SMULO || 10245 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 10246 Inverted = true; 10247 Cond = Cond.getOperand(0); 10248 } else { 10249 SDValue NewCond = LowerSETCC(Cond, DAG); 10250 if (NewCond.getNode()) 10251 Cond = NewCond; 10252 } 10253 } 10254 #if 0 10255 // FIXME: LowerXALUO doesn't handle these!! 10256 else if (Cond.getOpcode() == X86ISD::ADD || 10257 Cond.getOpcode() == X86ISD::SUB || 10258 Cond.getOpcode() == X86ISD::SMUL || 10259 Cond.getOpcode() == X86ISD::UMUL) 10260 Cond = LowerXALUO(Cond, DAG); 10261 #endif 10262 10263 // Look pass (and (setcc_carry (cmp ...)), 1). 10264 if (Cond.getOpcode() == ISD::AND && 10265 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 10266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 10267 if (C && C->getAPIntValue() == 1) 10268 Cond = Cond.getOperand(0); 10269 } 10270 10271 // If condition flag is set by a X86ISD::CMP, then use it as the condition 10272 // setting operand in place of the X86ISD::SETCC. 10273 unsigned CondOpcode = Cond.getOpcode(); 10274 if (CondOpcode == X86ISD::SETCC || 10275 CondOpcode == X86ISD::SETCC_CARRY) { 10276 CC = Cond.getOperand(0); 10277 10278 SDValue Cmp = Cond.getOperand(1); 10279 unsigned Opc = Cmp.getOpcode(); 10280 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 10281 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 10282 Cond = Cmp; 10283 addTest = false; 10284 } else { 10285 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 10286 default: break; 10287 case X86::COND_O: 10288 case X86::COND_B: 10289 // These can only come from an arithmetic instruction with overflow, 10290 // e.g. SADDO, UADDO. 10291 Cond = Cond.getNode()->getOperand(1); 10292 addTest = false; 10293 break; 10294 } 10295 } 10296 } 10297 CondOpcode = Cond.getOpcode(); 10298 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 10299 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 10300 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 10301 Cond.getOperand(0).getValueType() != MVT::i8)) { 10302 SDValue LHS = Cond.getOperand(0); 10303 SDValue RHS = Cond.getOperand(1); 10304 unsigned X86Opcode; 10305 unsigned X86Cond; 10306 SDVTList VTs; 10307 switch (CondOpcode) { 10308 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 10309 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 10310 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 10311 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 10312 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 10313 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 10314 default: llvm_unreachable("unexpected overflowing operator"); 10315 } 10316 if (Inverted) 10317 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 10318 if (CondOpcode == ISD::UMULO) 10319 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 10320 MVT::i32); 10321 else 10322 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 10323 10324 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 10325 10326 if (CondOpcode == ISD::UMULO) 10327 Cond = X86Op.getValue(2); 10328 else 10329 Cond = X86Op.getValue(1); 10330 10331 CC = DAG.getConstant(X86Cond, MVT::i8); 10332 addTest = false; 10333 } else { 10334 unsigned CondOpc; 10335 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 10336 SDValue Cmp = Cond.getOperand(0).getOperand(1); 10337 if (CondOpc == ISD::OR) { 10338 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 10339 // two branches instead of an explicit OR instruction with a 10340 // separate test. 10341 if (Cmp == Cond.getOperand(1).getOperand(1) && 10342 isX86LogicalCmp(Cmp)) { 10343 CC = Cond.getOperand(0).getOperand(0); 10344 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10345 Chain, Dest, CC, Cmp); 10346 CC = Cond.getOperand(1).getOperand(0); 10347 Cond = Cmp; 10348 addTest = false; 10349 } 10350 } else { // ISD::AND 10351 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 10352 // two branches instead of an explicit AND instruction with a 10353 // separate test. However, we only do this if this block doesn't 10354 // have a fall-through edge, because this requires an explicit 10355 // jmp when the condition is false. 10356 if (Cmp == Cond.getOperand(1).getOperand(1) && 10357 isX86LogicalCmp(Cmp) && 10358 Op.getNode()->hasOneUse()) { 10359 X86::CondCode CCode = 10360 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 10361 CCode = X86::GetOppositeBranchCondition(CCode); 10362 CC = DAG.getConstant(CCode, MVT::i8); 10363 SDNode *User = *Op.getNode()->use_begin(); 10364 // Look for an unconditional branch following this conditional branch. 10365 // We need this because we need to reverse the successors in order 10366 // to implement FCMP_OEQ. 10367 if (User->getOpcode() == ISD::BR) { 10368 SDValue FalseBB = User->getOperand(1); 10369 SDNode *NewBR = 10370 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 10371 assert(NewBR == User); 10372 (void)NewBR; 10373 Dest = FalseBB; 10374 10375 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10376 Chain, Dest, CC, Cmp); 10377 X86::CondCode CCode = 10378 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 10379 CCode = X86::GetOppositeBranchCondition(CCode); 10380 CC = DAG.getConstant(CCode, MVT::i8); 10381 Cond = Cmp; 10382 addTest = false; 10383 } 10384 } 10385 } 10386 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 10387 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 10388 // It should be transformed during dag combiner except when the condition 10389 // is set by a arithmetics with overflow node. 10390 X86::CondCode CCode = 10391 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 10392 CCode = X86::GetOppositeBranchCondition(CCode); 10393 CC = DAG.getConstant(CCode, MVT::i8); 10394 Cond = Cond.getOperand(0).getOperand(1); 10395 addTest = false; 10396 } else if (Cond.getOpcode() == ISD::SETCC && 10397 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 10398 // For FCMP_OEQ, we can emit 10399 // two branches instead of an explicit AND instruction with a 10400 // separate test. However, we only do this if this block doesn't 10401 // have a fall-through edge, because this requires an explicit 10402 // jmp when the condition is false. 10403 if (Op.getNode()->hasOneUse()) { 10404 SDNode *User = *Op.getNode()->use_begin(); 10405 // Look for an unconditional branch following this conditional branch. 10406 // We need this because we need to reverse the successors in order 10407 // to implement FCMP_OEQ. 10408 if (User->getOpcode() == ISD::BR) { 10409 SDValue FalseBB = User->getOperand(1); 10410 SDNode *NewBR = 10411 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 10412 assert(NewBR == User); 10413 (void)NewBR; 10414 Dest = FalseBB; 10415 10416 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 10417 Cond.getOperand(0), Cond.getOperand(1)); 10418 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 10419 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10420 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10421 Chain, Dest, CC, Cmp); 10422 CC = DAG.getConstant(X86::COND_P, MVT::i8); 10423 Cond = Cmp; 10424 addTest = false; 10425 } 10426 } 10427 } else if (Cond.getOpcode() == ISD::SETCC && 10428 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 10429 // For FCMP_UNE, we can emit 10430 // two branches instead of an explicit AND instruction with a 10431 // separate test. However, we only do this if this block doesn't 10432 // have a fall-through edge, because this requires an explicit 10433 // jmp when the condition is false. 10434 if (Op.getNode()->hasOneUse()) { 10435 SDNode *User = *Op.getNode()->use_begin(); 10436 // Look for an unconditional branch following this conditional branch. 10437 // We need this because we need to reverse the successors in order 10438 // to implement FCMP_UNE. 10439 if (User->getOpcode() == ISD::BR) { 10440 SDValue FalseBB = User->getOperand(1); 10441 SDNode *NewBR = 10442 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 10443 assert(NewBR == User); 10444 (void)NewBR; 10445 10446 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 10447 Cond.getOperand(0), Cond.getOperand(1)); 10448 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 10449 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10450 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10451 Chain, Dest, CC, Cmp); 10452 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 10453 Cond = Cmp; 10454 addTest = false; 10455 Dest = FalseBB; 10456 } 10457 } 10458 } 10459 } 10460 10461 if (addTest) { 10462 // Look pass the truncate if the high bits are known zero. 10463 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 10464 Cond = Cond.getOperand(0); 10465 10466 // We know the result of AND is compared against zero. Try to match 10467 // it to BT. 10468 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 10469 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 10470 if (NewSetCC.getNode()) { 10471 CC = NewSetCC.getOperand(0); 10472 Cond = NewSetCC.getOperand(1); 10473 addTest = false; 10474 } 10475 } 10476 } 10477 10478 if (addTest) { 10479 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10480 Cond = EmitTest(Cond, X86::COND_NE, DAG); 10481 } 10482 Cond = ConvertCmpIfNecessary(Cond, DAG); 10483 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10484 Chain, Dest, CC, Cond); 10485 } 10486 10487 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 10488 // Calls to _alloca is needed to probe the stack when allocating more than 4k 10489 // bytes in one go. Touching the stack at 4K increments is necessary to ensure 10490 // that the guard pages used by the OS virtual memory manager are allocated in 10491 // correct sequence. 10492 SDValue 10493 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 10494 SelectionDAG &DAG) const { 10495 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 10496 getTargetMachine().Options.EnableSegmentedStacks) && 10497 "This should be used only on Windows targets or when segmented stacks " 10498 "are being used"); 10499 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 10500 SDLoc dl(Op); 10501 10502 // Get the inputs. 10503 SDValue Chain = Op.getOperand(0); 10504 SDValue Size = Op.getOperand(1); 10505 // FIXME: Ensure alignment here 10506 10507 bool Is64Bit = Subtarget->is64Bit(); 10508 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 10509 10510 if (getTargetMachine().Options.EnableSegmentedStacks) { 10511 MachineFunction &MF = DAG.getMachineFunction(); 10512 MachineRegisterInfo &MRI = MF.getRegInfo(); 10513 10514 if (Is64Bit) { 10515 // The 64 bit implementation of segmented stacks needs to clobber both r10 10516 // r11. This makes it impossible to use it along with nested parameters. 10517 const Function *F = MF.getFunction(); 10518 10519 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 10520 I != E; ++I) 10521 if (I->hasNestAttr()) 10522 report_fatal_error("Cannot use segmented stacks with functions that " 10523 "have nested arguments."); 10524 } 10525 10526 const TargetRegisterClass *AddrRegClass = 10527 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 10528 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 10529 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 10530 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 10531 DAG.getRegister(Vreg, SPTy)); 10532 SDValue Ops1[2] = { Value, Chain }; 10533 return DAG.getMergeValues(Ops1, 2, dl); 10534 } else { 10535 SDValue Flag; 10536 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 10537 10538 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 10539 Flag = Chain.getValue(1); 10540 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10541 10542 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 10543 Flag = Chain.getValue(1); 10544 10545 const X86RegisterInfo *RegInfo = 10546 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 10547 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 10548 SPTy).getValue(1); 10549 10550 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 10551 return DAG.getMergeValues(Ops1, 2, dl); 10552 } 10553 } 10554 10555 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 10556 MachineFunction &MF = DAG.getMachineFunction(); 10557 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 10558 10559 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10560 SDLoc DL(Op); 10561 10562 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 10563 // vastart just stores the address of the VarArgsFrameIndex slot into the 10564 // memory location argument. 10565 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10566 getPointerTy()); 10567 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 10568 MachinePointerInfo(SV), false, false, 0); 10569 } 10570 10571 // __va_list_tag: 10572 // gp_offset (0 - 6 * 8) 10573 // fp_offset (48 - 48 + 8 * 16) 10574 // overflow_arg_area (point to parameters coming in memory). 10575 // reg_save_area 10576 SmallVector<SDValue, 8> MemOps; 10577 SDValue FIN = Op.getOperand(1); 10578 // Store gp_offset 10579 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 10580 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 10581 MVT::i32), 10582 FIN, MachinePointerInfo(SV), false, false, 0); 10583 MemOps.push_back(Store); 10584 10585 // Store fp_offset 10586 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10587 FIN, DAG.getIntPtrConstant(4)); 10588 Store = DAG.getStore(Op.getOperand(0), DL, 10589 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 10590 MVT::i32), 10591 FIN, MachinePointerInfo(SV, 4), false, false, 0); 10592 MemOps.push_back(Store); 10593 10594 // Store ptr to overflow_arg_area 10595 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10596 FIN, DAG.getIntPtrConstant(4)); 10597 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10598 getPointerTy()); 10599 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 10600 MachinePointerInfo(SV, 8), 10601 false, false, 0); 10602 MemOps.push_back(Store); 10603 10604 // Store ptr to reg_save_area. 10605 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10606 FIN, DAG.getIntPtrConstant(8)); 10607 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 10608 getPointerTy()); 10609 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 10610 MachinePointerInfo(SV, 16), false, false, 0); 10611 MemOps.push_back(Store); 10612 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 10613 &MemOps[0], MemOps.size()); 10614 } 10615 10616 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 10617 assert(Subtarget->is64Bit() && 10618 "LowerVAARG only handles 64-bit va_arg!"); 10619 assert((Subtarget->isTargetLinux() || 10620 Subtarget->isTargetDarwin()) && 10621 "Unhandled target in LowerVAARG"); 10622 assert(Op.getNode()->getNumOperands() == 4); 10623 SDValue Chain = Op.getOperand(0); 10624 SDValue SrcPtr = Op.getOperand(1); 10625 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10626 unsigned Align = Op.getConstantOperandVal(3); 10627 SDLoc dl(Op); 10628 10629 EVT ArgVT = Op.getNode()->getValueType(0); 10630 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 10631 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy); 10632 uint8_t ArgMode; 10633 10634 // Decide which area this value should be read from. 10635 // TODO: Implement the AMD64 ABI in its entirety. This simple 10636 // selection mechanism works only for the basic types. 10637 if (ArgVT == MVT::f80) { 10638 llvm_unreachable("va_arg for f80 not yet implemented"); 10639 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 10640 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 10641 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 10642 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 10643 } else { 10644 llvm_unreachable("Unhandled argument type in LowerVAARG"); 10645 } 10646 10647 if (ArgMode == 2) { 10648 // Sanity Check: Make sure using fp_offset makes sense. 10649 assert(!getTargetMachine().Options.UseSoftFloat && 10650 !(DAG.getMachineFunction() 10651 .getFunction()->getAttributes() 10652 .hasAttribute(AttributeSet::FunctionIndex, 10653 Attribute::NoImplicitFloat)) && 10654 Subtarget->hasSSE1()); 10655 } 10656 10657 // Insert VAARG_64 node into the DAG 10658 // VAARG_64 returns two values: Variable Argument Address, Chain 10659 SmallVector<SDValue, 11> InstOps; 10660 InstOps.push_back(Chain); 10661 InstOps.push_back(SrcPtr); 10662 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 10663 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 10664 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 10665 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 10666 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 10667 VTs, &InstOps[0], InstOps.size(), 10668 MVT::i64, 10669 MachinePointerInfo(SV), 10670 /*Align=*/0, 10671 /*Volatile=*/false, 10672 /*ReadMem=*/true, 10673 /*WriteMem=*/true); 10674 Chain = VAARG.getValue(1); 10675 10676 // Load the next argument and return it 10677 return DAG.getLoad(ArgVT, dl, 10678 Chain, 10679 VAARG, 10680 MachinePointerInfo(), 10681 false, false, false, 0); 10682 } 10683 10684 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget, 10685 SelectionDAG &DAG) { 10686 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 10687 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 10688 SDValue Chain = Op.getOperand(0); 10689 SDValue DstPtr = Op.getOperand(1); 10690 SDValue SrcPtr = Op.getOperand(2); 10691 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 10692 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 10693 SDLoc DL(Op); 10694 10695 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 10696 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 10697 false, 10698 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 10699 } 10700 10701 // getTargetVShiftNode - Handle vector element shifts where the shift amount 10702 // may or may not be a constant. Takes immediate version of shift as input. 10703 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT, 10704 SDValue SrcOp, SDValue ShAmt, 10705 SelectionDAG &DAG) { 10706 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32"); 10707 10708 if (isa<ConstantSDNode>(ShAmt)) { 10709 // Constant may be a TargetConstant. Use a regular constant. 10710 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10711 switch (Opc) { 10712 default: llvm_unreachable("Unknown target vector shift node"); 10713 case X86ISD::VSHLI: 10714 case X86ISD::VSRLI: 10715 case X86ISD::VSRAI: 10716 return DAG.getNode(Opc, dl, VT, SrcOp, 10717 DAG.getConstant(ShiftAmt, MVT::i32)); 10718 } 10719 } 10720 10721 // Change opcode to non-immediate version 10722 switch (Opc) { 10723 default: llvm_unreachable("Unknown target vector shift node"); 10724 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break; 10725 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break; 10726 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break; 10727 } 10728 10729 // Need to build a vector containing shift amount 10730 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0 10731 SDValue ShOps[4]; 10732 ShOps[0] = ShAmt; 10733 ShOps[1] = DAG.getConstant(0, MVT::i32); 10734 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32); 10735 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4); 10736 10737 // The return type has to be a 128-bit type with the same element 10738 // type as the input type. 10739 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10740 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits()); 10741 10742 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt); 10743 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt); 10744 } 10745 10746 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) { 10747 SDLoc dl(Op); 10748 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10749 switch (IntNo) { 10750 default: return SDValue(); // Don't custom lower most intrinsics. 10751 // Comparison intrinsics. 10752 case Intrinsic::x86_sse_comieq_ss: 10753 case Intrinsic::x86_sse_comilt_ss: 10754 case Intrinsic::x86_sse_comile_ss: 10755 case Intrinsic::x86_sse_comigt_ss: 10756 case Intrinsic::x86_sse_comige_ss: 10757 case Intrinsic::x86_sse_comineq_ss: 10758 case Intrinsic::x86_sse_ucomieq_ss: 10759 case Intrinsic::x86_sse_ucomilt_ss: 10760 case Intrinsic::x86_sse_ucomile_ss: 10761 case Intrinsic::x86_sse_ucomigt_ss: 10762 case Intrinsic::x86_sse_ucomige_ss: 10763 case Intrinsic::x86_sse_ucomineq_ss: 10764 case Intrinsic::x86_sse2_comieq_sd: 10765 case Intrinsic::x86_sse2_comilt_sd: 10766 case Intrinsic::x86_sse2_comile_sd: 10767 case Intrinsic::x86_sse2_comigt_sd: 10768 case Intrinsic::x86_sse2_comige_sd: 10769 case Intrinsic::x86_sse2_comineq_sd: 10770 case Intrinsic::x86_sse2_ucomieq_sd: 10771 case Intrinsic::x86_sse2_ucomilt_sd: 10772 case Intrinsic::x86_sse2_ucomile_sd: 10773 case Intrinsic::x86_sse2_ucomigt_sd: 10774 case Intrinsic::x86_sse2_ucomige_sd: 10775 case Intrinsic::x86_sse2_ucomineq_sd: { 10776 unsigned Opc; 10777 ISD::CondCode CC; 10778 switch (IntNo) { 10779 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10780 case Intrinsic::x86_sse_comieq_ss: 10781 case Intrinsic::x86_sse2_comieq_sd: 10782 Opc = X86ISD::COMI; 10783 CC = ISD::SETEQ; 10784 break; 10785 case Intrinsic::x86_sse_comilt_ss: 10786 case Intrinsic::x86_sse2_comilt_sd: 10787 Opc = X86ISD::COMI; 10788 CC = ISD::SETLT; 10789 break; 10790 case Intrinsic::x86_sse_comile_ss: 10791 case Intrinsic::x86_sse2_comile_sd: 10792 Opc = X86ISD::COMI; 10793 CC = ISD::SETLE; 10794 break; 10795 case Intrinsic::x86_sse_comigt_ss: 10796 case Intrinsic::x86_sse2_comigt_sd: 10797 Opc = X86ISD::COMI; 10798 CC = ISD::SETGT; 10799 break; 10800 case Intrinsic::x86_sse_comige_ss: 10801 case Intrinsic::x86_sse2_comige_sd: 10802 Opc = X86ISD::COMI; 10803 CC = ISD::SETGE; 10804 break; 10805 case Intrinsic::x86_sse_comineq_ss: 10806 case Intrinsic::x86_sse2_comineq_sd: 10807 Opc = X86ISD::COMI; 10808 CC = ISD::SETNE; 10809 break; 10810 case Intrinsic::x86_sse_ucomieq_ss: 10811 case Intrinsic::x86_sse2_ucomieq_sd: 10812 Opc = X86ISD::UCOMI; 10813 CC = ISD::SETEQ; 10814 break; 10815 case Intrinsic::x86_sse_ucomilt_ss: 10816 case Intrinsic::x86_sse2_ucomilt_sd: 10817 Opc = X86ISD::UCOMI; 10818 CC = ISD::SETLT; 10819 break; 10820 case Intrinsic::x86_sse_ucomile_ss: 10821 case Intrinsic::x86_sse2_ucomile_sd: 10822 Opc = X86ISD::UCOMI; 10823 CC = ISD::SETLE; 10824 break; 10825 case Intrinsic::x86_sse_ucomigt_ss: 10826 case Intrinsic::x86_sse2_ucomigt_sd: 10827 Opc = X86ISD::UCOMI; 10828 CC = ISD::SETGT; 10829 break; 10830 case Intrinsic::x86_sse_ucomige_ss: 10831 case Intrinsic::x86_sse2_ucomige_sd: 10832 Opc = X86ISD::UCOMI; 10833 CC = ISD::SETGE; 10834 break; 10835 case Intrinsic::x86_sse_ucomineq_ss: 10836 case Intrinsic::x86_sse2_ucomineq_sd: 10837 Opc = X86ISD::UCOMI; 10838 CC = ISD::SETNE; 10839 break; 10840 } 10841 10842 SDValue LHS = Op.getOperand(1); 10843 SDValue RHS = Op.getOperand(2); 10844 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 10845 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 10846 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 10847 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 10848 DAG.getConstant(X86CC, MVT::i8), Cond); 10849 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10850 } 10851 10852 // Arithmetic intrinsics. 10853 case Intrinsic::x86_sse2_pmulu_dq: 10854 case Intrinsic::x86_avx2_pmulu_dq: 10855 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(), 10856 Op.getOperand(1), Op.getOperand(2)); 10857 10858 // SSE2/AVX2 sub with unsigned saturation intrinsics 10859 case Intrinsic::x86_sse2_psubus_b: 10860 case Intrinsic::x86_sse2_psubus_w: 10861 case Intrinsic::x86_avx2_psubus_b: 10862 case Intrinsic::x86_avx2_psubus_w: 10863 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(), 10864 Op.getOperand(1), Op.getOperand(2)); 10865 10866 // SSE3/AVX horizontal add/sub intrinsics 10867 case Intrinsic::x86_sse3_hadd_ps: 10868 case Intrinsic::x86_sse3_hadd_pd: 10869 case Intrinsic::x86_avx_hadd_ps_256: 10870 case Intrinsic::x86_avx_hadd_pd_256: 10871 case Intrinsic::x86_sse3_hsub_ps: 10872 case Intrinsic::x86_sse3_hsub_pd: 10873 case Intrinsic::x86_avx_hsub_ps_256: 10874 case Intrinsic::x86_avx_hsub_pd_256: 10875 case Intrinsic::x86_ssse3_phadd_w_128: 10876 case Intrinsic::x86_ssse3_phadd_d_128: 10877 case Intrinsic::x86_avx2_phadd_w: 10878 case Intrinsic::x86_avx2_phadd_d: 10879 case Intrinsic::x86_ssse3_phsub_w_128: 10880 case Intrinsic::x86_ssse3_phsub_d_128: 10881 case Intrinsic::x86_avx2_phsub_w: 10882 case Intrinsic::x86_avx2_phsub_d: { 10883 unsigned Opcode; 10884 switch (IntNo) { 10885 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10886 case Intrinsic::x86_sse3_hadd_ps: 10887 case Intrinsic::x86_sse3_hadd_pd: 10888 case Intrinsic::x86_avx_hadd_ps_256: 10889 case Intrinsic::x86_avx_hadd_pd_256: 10890 Opcode = X86ISD::FHADD; 10891 break; 10892 case Intrinsic::x86_sse3_hsub_ps: 10893 case Intrinsic::x86_sse3_hsub_pd: 10894 case Intrinsic::x86_avx_hsub_ps_256: 10895 case Intrinsic::x86_avx_hsub_pd_256: 10896 Opcode = X86ISD::FHSUB; 10897 break; 10898 case Intrinsic::x86_ssse3_phadd_w_128: 10899 case Intrinsic::x86_ssse3_phadd_d_128: 10900 case Intrinsic::x86_avx2_phadd_w: 10901 case Intrinsic::x86_avx2_phadd_d: 10902 Opcode = X86ISD::HADD; 10903 break; 10904 case Intrinsic::x86_ssse3_phsub_w_128: 10905 case Intrinsic::x86_ssse3_phsub_d_128: 10906 case Intrinsic::x86_avx2_phsub_w: 10907 case Intrinsic::x86_avx2_phsub_d: 10908 Opcode = X86ISD::HSUB; 10909 break; 10910 } 10911 return DAG.getNode(Opcode, dl, Op.getValueType(), 10912 Op.getOperand(1), Op.getOperand(2)); 10913 } 10914 10915 // SSE2/SSE41/AVX2 integer max/min intrinsics. 10916 case Intrinsic::x86_sse2_pmaxu_b: 10917 case Intrinsic::x86_sse41_pmaxuw: 10918 case Intrinsic::x86_sse41_pmaxud: 10919 case Intrinsic::x86_avx2_pmaxu_b: 10920 case Intrinsic::x86_avx2_pmaxu_w: 10921 case Intrinsic::x86_avx2_pmaxu_d: 10922 case Intrinsic::x86_sse2_pminu_b: 10923 case Intrinsic::x86_sse41_pminuw: 10924 case Intrinsic::x86_sse41_pminud: 10925 case Intrinsic::x86_avx2_pminu_b: 10926 case Intrinsic::x86_avx2_pminu_w: 10927 case Intrinsic::x86_avx2_pminu_d: 10928 case Intrinsic::x86_sse41_pmaxsb: 10929 case Intrinsic::x86_sse2_pmaxs_w: 10930 case Intrinsic::x86_sse41_pmaxsd: 10931 case Intrinsic::x86_avx2_pmaxs_b: 10932 case Intrinsic::x86_avx2_pmaxs_w: 10933 case Intrinsic::x86_avx2_pmaxs_d: 10934 case Intrinsic::x86_sse41_pminsb: 10935 case Intrinsic::x86_sse2_pmins_w: 10936 case Intrinsic::x86_sse41_pminsd: 10937 case Intrinsic::x86_avx2_pmins_b: 10938 case Intrinsic::x86_avx2_pmins_w: 10939 case Intrinsic::x86_avx2_pmins_d: { 10940 unsigned Opcode; 10941 switch (IntNo) { 10942 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10943 case Intrinsic::x86_sse2_pmaxu_b: 10944 case Intrinsic::x86_sse41_pmaxuw: 10945 case Intrinsic::x86_sse41_pmaxud: 10946 case Intrinsic::x86_avx2_pmaxu_b: 10947 case Intrinsic::x86_avx2_pmaxu_w: 10948 case Intrinsic::x86_avx2_pmaxu_d: 10949 Opcode = X86ISD::UMAX; 10950 break; 10951 case Intrinsic::x86_sse2_pminu_b: 10952 case Intrinsic::x86_sse41_pminuw: 10953 case Intrinsic::x86_sse41_pminud: 10954 case Intrinsic::x86_avx2_pminu_b: 10955 case Intrinsic::x86_avx2_pminu_w: 10956 case Intrinsic::x86_avx2_pminu_d: 10957 Opcode = X86ISD::UMIN; 10958 break; 10959 case Intrinsic::x86_sse41_pmaxsb: 10960 case Intrinsic::x86_sse2_pmaxs_w: 10961 case Intrinsic::x86_sse41_pmaxsd: 10962 case Intrinsic::x86_avx2_pmaxs_b: 10963 case Intrinsic::x86_avx2_pmaxs_w: 10964 case Intrinsic::x86_avx2_pmaxs_d: 10965 Opcode = X86ISD::SMAX; 10966 break; 10967 case Intrinsic::x86_sse41_pminsb: 10968 case Intrinsic::x86_sse2_pmins_w: 10969 case Intrinsic::x86_sse41_pminsd: 10970 case Intrinsic::x86_avx2_pmins_b: 10971 case Intrinsic::x86_avx2_pmins_w: 10972 case Intrinsic::x86_avx2_pmins_d: 10973 Opcode = X86ISD::SMIN; 10974 break; 10975 } 10976 return DAG.getNode(Opcode, dl, Op.getValueType(), 10977 Op.getOperand(1), Op.getOperand(2)); 10978 } 10979 10980 // SSE/SSE2/AVX floating point max/min intrinsics. 10981 case Intrinsic::x86_sse_max_ps: 10982 case Intrinsic::x86_sse2_max_pd: 10983 case Intrinsic::x86_avx_max_ps_256: 10984 case Intrinsic::x86_avx_max_pd_256: 10985 case Intrinsic::x86_sse_min_ps: 10986 case Intrinsic::x86_sse2_min_pd: 10987 case Intrinsic::x86_avx_min_ps_256: 10988 case Intrinsic::x86_avx_min_pd_256: { 10989 unsigned Opcode; 10990 switch (IntNo) { 10991 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10992 case Intrinsic::x86_sse_max_ps: 10993 case Intrinsic::x86_sse2_max_pd: 10994 case Intrinsic::x86_avx_max_ps_256: 10995 case Intrinsic::x86_avx_max_pd_256: 10996 Opcode = X86ISD::FMAX; 10997 break; 10998 case Intrinsic::x86_sse_min_ps: 10999 case Intrinsic::x86_sse2_min_pd: 11000 case Intrinsic::x86_avx_min_ps_256: 11001 case Intrinsic::x86_avx_min_pd_256: 11002 Opcode = X86ISD::FMIN; 11003 break; 11004 } 11005 return DAG.getNode(Opcode, dl, Op.getValueType(), 11006 Op.getOperand(1), Op.getOperand(2)); 11007 } 11008 11009 // AVX2 variable shift intrinsics 11010 case Intrinsic::x86_avx2_psllv_d: 11011 case Intrinsic::x86_avx2_psllv_q: 11012 case Intrinsic::x86_avx2_psllv_d_256: 11013 case Intrinsic::x86_avx2_psllv_q_256: 11014 case Intrinsic::x86_avx2_psrlv_d: 11015 case Intrinsic::x86_avx2_psrlv_q: 11016 case Intrinsic::x86_avx2_psrlv_d_256: 11017 case Intrinsic::x86_avx2_psrlv_q_256: 11018 case Intrinsic::x86_avx2_psrav_d: 11019 case Intrinsic::x86_avx2_psrav_d_256: { 11020 unsigned Opcode; 11021 switch (IntNo) { 11022 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 11023 case Intrinsic::x86_avx2_psllv_d: 11024 case Intrinsic::x86_avx2_psllv_q: 11025 case Intrinsic::x86_avx2_psllv_d_256: 11026 case Intrinsic::x86_avx2_psllv_q_256: 11027 Opcode = ISD::SHL; 11028 break; 11029 case Intrinsic::x86_avx2_psrlv_d: 11030 case Intrinsic::x86_avx2_psrlv_q: 11031 case Intrinsic::x86_avx2_psrlv_d_256: 11032 case Intrinsic::x86_avx2_psrlv_q_256: 11033 Opcode = ISD::SRL; 11034 break; 11035 case Intrinsic::x86_avx2_psrav_d: 11036 case Intrinsic::x86_avx2_psrav_d_256: 11037 Opcode = ISD::SRA; 11038 break; 11039 } 11040 return DAG.getNode(Opcode, dl, Op.getValueType(), 11041 Op.getOperand(1), Op.getOperand(2)); 11042 } 11043 11044 case Intrinsic::x86_ssse3_pshuf_b_128: 11045 case Intrinsic::x86_avx2_pshuf_b: 11046 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(), 11047 Op.getOperand(1), Op.getOperand(2)); 11048 11049 case Intrinsic::x86_ssse3_psign_b_128: 11050 case Intrinsic::x86_ssse3_psign_w_128: 11051 case Intrinsic::x86_ssse3_psign_d_128: 11052 case Intrinsic::x86_avx2_psign_b: 11053 case Intrinsic::x86_avx2_psign_w: 11054 case Intrinsic::x86_avx2_psign_d: 11055 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(), 11056 Op.getOperand(1), Op.getOperand(2)); 11057 11058 case Intrinsic::x86_sse41_insertps: 11059 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(), 11060 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 11061 11062 case Intrinsic::x86_avx_vperm2f128_ps_256: 11063 case Intrinsic::x86_avx_vperm2f128_pd_256: 11064 case Intrinsic::x86_avx_vperm2f128_si_256: 11065 case Intrinsic::x86_avx2_vperm2i128: 11066 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(), 11067 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 11068 11069 case Intrinsic::x86_avx2_permd: 11070 case Intrinsic::x86_avx2_permps: 11071 // Operands intentionally swapped. Mask is last operand to intrinsic, 11072 // but second operand for node/intruction. 11073 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(), 11074 Op.getOperand(2), Op.getOperand(1)); 11075 11076 case Intrinsic::x86_sse_sqrt_ps: 11077 case Intrinsic::x86_sse2_sqrt_pd: 11078 case Intrinsic::x86_avx_sqrt_ps_256: 11079 case Intrinsic::x86_avx_sqrt_pd_256: 11080 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1)); 11081 11082 // ptest and testp intrinsics. The intrinsic these come from are designed to 11083 // return an integer value, not just an instruction so lower it to the ptest 11084 // or testp pattern and a setcc for the result. 11085 case Intrinsic::x86_sse41_ptestz: 11086 case Intrinsic::x86_sse41_ptestc: 11087 case Intrinsic::x86_sse41_ptestnzc: 11088 case Intrinsic::x86_avx_ptestz_256: 11089 case Intrinsic::x86_avx_ptestc_256: 11090 case Intrinsic::x86_avx_ptestnzc_256: 11091 case Intrinsic::x86_avx_vtestz_ps: 11092 case Intrinsic::x86_avx_vtestc_ps: 11093 case Intrinsic::x86_avx_vtestnzc_ps: 11094 case Intrinsic::x86_avx_vtestz_pd: 11095 case Intrinsic::x86_avx_vtestc_pd: 11096 case Intrinsic::x86_avx_vtestnzc_pd: 11097 case Intrinsic::x86_avx_vtestz_ps_256: 11098 case Intrinsic::x86_avx_vtestc_ps_256: 11099 case Intrinsic::x86_avx_vtestnzc_ps_256: 11100 case Intrinsic::x86_avx_vtestz_pd_256: 11101 case Intrinsic::x86_avx_vtestc_pd_256: 11102 case Intrinsic::x86_avx_vtestnzc_pd_256: { 11103 bool IsTestPacked = false; 11104 unsigned X86CC; 11105 switch (IntNo) { 11106 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 11107 case Intrinsic::x86_avx_vtestz_ps: 11108 case Intrinsic::x86_avx_vtestz_pd: 11109 case Intrinsic::x86_avx_vtestz_ps_256: 11110 case Intrinsic::x86_avx_vtestz_pd_256: 11111 IsTestPacked = true; // Fallthrough 11112 case Intrinsic::x86_sse41_ptestz: 11113 case Intrinsic::x86_avx_ptestz_256: 11114 // ZF = 1 11115 X86CC = X86::COND_E; 11116 break; 11117 case Intrinsic::x86_avx_vtestc_ps: 11118 case Intrinsic::x86_avx_vtestc_pd: 11119 case Intrinsic::x86_avx_vtestc_ps_256: 11120 case Intrinsic::x86_avx_vtestc_pd_256: 11121 IsTestPacked = true; // Fallthrough 11122 case Intrinsic::x86_sse41_ptestc: 11123 case Intrinsic::x86_avx_ptestc_256: 11124 // CF = 1 11125 X86CC = X86::COND_B; 11126 break; 11127 case Intrinsic::x86_avx_vtestnzc_ps: 11128 case Intrinsic::x86_avx_vtestnzc_pd: 11129 case Intrinsic::x86_avx_vtestnzc_ps_256: 11130 case Intrinsic::x86_avx_vtestnzc_pd_256: 11131 IsTestPacked = true; // Fallthrough 11132 case Intrinsic::x86_sse41_ptestnzc: 11133 case Intrinsic::x86_avx_ptestnzc_256: 11134 // ZF and CF = 0 11135 X86CC = X86::COND_A; 11136 break; 11137 } 11138 11139 SDValue LHS = Op.getOperand(1); 11140 SDValue RHS = Op.getOperand(2); 11141 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 11142 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 11143 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 11144 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 11145 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 11146 } 11147 11148 // SSE/AVX shift intrinsics 11149 case Intrinsic::x86_sse2_psll_w: 11150 case Intrinsic::x86_sse2_psll_d: 11151 case Intrinsic::x86_sse2_psll_q: 11152 case Intrinsic::x86_avx2_psll_w: 11153 case Intrinsic::x86_avx2_psll_d: 11154 case Intrinsic::x86_avx2_psll_q: 11155 case Intrinsic::x86_sse2_psrl_w: 11156 case Intrinsic::x86_sse2_psrl_d: 11157 case Intrinsic::x86_sse2_psrl_q: 11158 case Intrinsic::x86_avx2_psrl_w: 11159 case Intrinsic::x86_avx2_psrl_d: 11160 case Intrinsic::x86_avx2_psrl_q: 11161 case Intrinsic::x86_sse2_psra_w: 11162 case Intrinsic::x86_sse2_psra_d: 11163 case Intrinsic::x86_avx2_psra_w: 11164 case Intrinsic::x86_avx2_psra_d: { 11165 unsigned Opcode; 11166 switch (IntNo) { 11167 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 11168 case Intrinsic::x86_sse2_psll_w: 11169 case Intrinsic::x86_sse2_psll_d: 11170 case Intrinsic::x86_sse2_psll_q: 11171 case Intrinsic::x86_avx2_psll_w: 11172 case Intrinsic::x86_avx2_psll_d: 11173 case Intrinsic::x86_avx2_psll_q: 11174 Opcode = X86ISD::VSHL; 11175 break; 11176 case Intrinsic::x86_sse2_psrl_w: 11177 case Intrinsic::x86_sse2_psrl_d: 11178 case Intrinsic::x86_sse2_psrl_q: 11179 case Intrinsic::x86_avx2_psrl_w: 11180 case Intrinsic::x86_avx2_psrl_d: 11181 case Intrinsic::x86_avx2_psrl_q: 11182 Opcode = X86ISD::VSRL; 11183 break; 11184 case Intrinsic::x86_sse2_psra_w: 11185 case Intrinsic::x86_sse2_psra_d: 11186 case Intrinsic::x86_avx2_psra_w: 11187 case Intrinsic::x86_avx2_psra_d: 11188 Opcode = X86ISD::VSRA; 11189 break; 11190 } 11191 return DAG.getNode(Opcode, dl, Op.getValueType(), 11192 Op.getOperand(1), Op.getOperand(2)); 11193 } 11194 11195 // SSE/AVX immediate shift intrinsics 11196 case Intrinsic::x86_sse2_pslli_w: 11197 case Intrinsic::x86_sse2_pslli_d: 11198 case Intrinsic::x86_sse2_pslli_q: 11199 case Intrinsic::x86_avx2_pslli_w: 11200 case Intrinsic::x86_avx2_pslli_d: 11201 case Intrinsic::x86_avx2_pslli_q: 11202 case Intrinsic::x86_sse2_psrli_w: 11203 case Intrinsic::x86_sse2_psrli_d: 11204 case Intrinsic::x86_sse2_psrli_q: 11205 case Intrinsic::x86_avx2_psrli_w: 11206 case Intrinsic::x86_avx2_psrli_d: 11207 case Intrinsic::x86_avx2_psrli_q: 11208 case Intrinsic::x86_sse2_psrai_w: 11209 case Intrinsic::x86_sse2_psrai_d: 11210 case Intrinsic::x86_avx2_psrai_w: 11211 case Intrinsic::x86_avx2_psrai_d: { 11212 unsigned Opcode; 11213 switch (IntNo) { 11214 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 11215 case Intrinsic::x86_sse2_pslli_w: 11216 case Intrinsic::x86_sse2_pslli_d: 11217 case Intrinsic::x86_sse2_pslli_q: 11218 case Intrinsic::x86_avx2_pslli_w: 11219 case Intrinsic::x86_avx2_pslli_d: 11220 case Intrinsic::x86_avx2_pslli_q: 11221 Opcode = X86ISD::VSHLI; 11222 break; 11223 case Intrinsic::x86_sse2_psrli_w: 11224 case Intrinsic::x86_sse2_psrli_d: 11225 case Intrinsic::x86_sse2_psrli_q: 11226 case Intrinsic::x86_avx2_psrli_w: 11227 case Intrinsic::x86_avx2_psrli_d: 11228 case Intrinsic::x86_avx2_psrli_q: 11229 Opcode = X86ISD::VSRLI; 11230 break; 11231 case Intrinsic::x86_sse2_psrai_w: 11232 case Intrinsic::x86_sse2_psrai_d: 11233 case Intrinsic::x86_avx2_psrai_w: 11234 case Intrinsic::x86_avx2_psrai_d: 11235 Opcode = X86ISD::VSRAI; 11236 break; 11237 } 11238 return getTargetVShiftNode(Opcode, dl, Op.getValueType(), 11239 Op.getOperand(1), Op.getOperand(2), DAG); 11240 } 11241 11242 case Intrinsic::x86_sse42_pcmpistria128: 11243 case Intrinsic::x86_sse42_pcmpestria128: 11244 case Intrinsic::x86_sse42_pcmpistric128: 11245 case Intrinsic::x86_sse42_pcmpestric128: 11246 case Intrinsic::x86_sse42_pcmpistrio128: 11247 case Intrinsic::x86_sse42_pcmpestrio128: 11248 case Intrinsic::x86_sse42_pcmpistris128: 11249 case Intrinsic::x86_sse42_pcmpestris128: 11250 case Intrinsic::x86_sse42_pcmpistriz128: 11251 case Intrinsic::x86_sse42_pcmpestriz128: { 11252 unsigned Opcode; 11253 unsigned X86CC; 11254 switch (IntNo) { 11255 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 11256 case Intrinsic::x86_sse42_pcmpistria128: 11257 Opcode = X86ISD::PCMPISTRI; 11258 X86CC = X86::COND_A; 11259 break; 11260 case Intrinsic::x86_sse42_pcmpestria128: 11261 Opcode = X86ISD::PCMPESTRI; 11262 X86CC = X86::COND_A; 11263 break; 11264 case Intrinsic::x86_sse42_pcmpistric128: 11265 Opcode = X86ISD::PCMPISTRI; 11266 X86CC = X86::COND_B; 11267 break; 11268 case Intrinsic::x86_sse42_pcmpestric128: 11269 Opcode = X86ISD::PCMPESTRI; 11270 X86CC = X86::COND_B; 11271 break; 11272 case Intrinsic::x86_sse42_pcmpistrio128: 11273 Opcode = X86ISD::PCMPISTRI; 11274 X86CC = X86::COND_O; 11275 break; 11276 case Intrinsic::x86_sse42_pcmpestrio128: 11277 Opcode = X86ISD::PCMPESTRI; 11278 X86CC = X86::COND_O; 11279 break; 11280 case Intrinsic::x86_sse42_pcmpistris128: 11281 Opcode = X86ISD::PCMPISTRI; 11282 X86CC = X86::COND_S; 11283 break; 11284 case Intrinsic::x86_sse42_pcmpestris128: 11285 Opcode = X86ISD::PCMPESTRI; 11286 X86CC = X86::COND_S; 11287 break; 11288 case Intrinsic::x86_sse42_pcmpistriz128: 11289 Opcode = X86ISD::PCMPISTRI; 11290 X86CC = X86::COND_E; 11291 break; 11292 case Intrinsic::x86_sse42_pcmpestriz128: 11293 Opcode = X86ISD::PCMPESTRI; 11294 X86CC = X86::COND_E; 11295 break; 11296 } 11297 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end()); 11298 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 11299 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 11300 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 11301 DAG.getConstant(X86CC, MVT::i8), 11302 SDValue(PCMP.getNode(), 1)); 11303 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 11304 } 11305 11306 case Intrinsic::x86_sse42_pcmpistri128: 11307 case Intrinsic::x86_sse42_pcmpestri128: { 11308 unsigned Opcode; 11309 if (IntNo == Intrinsic::x86_sse42_pcmpistri128) 11310 Opcode = X86ISD::PCMPISTRI; 11311 else 11312 Opcode = X86ISD::PCMPESTRI; 11313 11314 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end()); 11315 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 11316 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 11317 } 11318 case Intrinsic::x86_fma_vfmadd_ps: 11319 case Intrinsic::x86_fma_vfmadd_pd: 11320 case Intrinsic::x86_fma_vfmsub_ps: 11321 case Intrinsic::x86_fma_vfmsub_pd: 11322 case Intrinsic::x86_fma_vfnmadd_ps: 11323 case Intrinsic::x86_fma_vfnmadd_pd: 11324 case Intrinsic::x86_fma_vfnmsub_ps: 11325 case Intrinsic::x86_fma_vfnmsub_pd: 11326 case Intrinsic::x86_fma_vfmaddsub_ps: 11327 case Intrinsic::x86_fma_vfmaddsub_pd: 11328 case Intrinsic::x86_fma_vfmsubadd_ps: 11329 case Intrinsic::x86_fma_vfmsubadd_pd: 11330 case Intrinsic::x86_fma_vfmadd_ps_256: 11331 case Intrinsic::x86_fma_vfmadd_pd_256: 11332 case Intrinsic::x86_fma_vfmsub_ps_256: 11333 case Intrinsic::x86_fma_vfmsub_pd_256: 11334 case Intrinsic::x86_fma_vfnmadd_ps_256: 11335 case Intrinsic::x86_fma_vfnmadd_pd_256: 11336 case Intrinsic::x86_fma_vfnmsub_ps_256: 11337 case Intrinsic::x86_fma_vfnmsub_pd_256: 11338 case Intrinsic::x86_fma_vfmaddsub_ps_256: 11339 case Intrinsic::x86_fma_vfmaddsub_pd_256: 11340 case Intrinsic::x86_fma_vfmsubadd_ps_256: 11341 case Intrinsic::x86_fma_vfmsubadd_pd_256: { 11342 unsigned Opc; 11343 switch (IntNo) { 11344 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 11345 case Intrinsic::x86_fma_vfmadd_ps: 11346 case Intrinsic::x86_fma_vfmadd_pd: 11347 case Intrinsic::x86_fma_vfmadd_ps_256: 11348 case Intrinsic::x86_fma_vfmadd_pd_256: 11349 Opc = X86ISD::FMADD; 11350 break; 11351 case Intrinsic::x86_fma_vfmsub_ps: 11352 case Intrinsic::x86_fma_vfmsub_pd: 11353 case Intrinsic::x86_fma_vfmsub_ps_256: 11354 case Intrinsic::x86_fma_vfmsub_pd_256: 11355 Opc = X86ISD::FMSUB; 11356 break; 11357 case Intrinsic::x86_fma_vfnmadd_ps: 11358 case Intrinsic::x86_fma_vfnmadd_pd: 11359 case Intrinsic::x86_fma_vfnmadd_ps_256: 11360 case Intrinsic::x86_fma_vfnmadd_pd_256: 11361 Opc = X86ISD::FNMADD; 11362 break; 11363 case Intrinsic::x86_fma_vfnmsub_ps: 11364 case Intrinsic::x86_fma_vfnmsub_pd: 11365 case Intrinsic::x86_fma_vfnmsub_ps_256: 11366 case Intrinsic::x86_fma_vfnmsub_pd_256: 11367 Opc = X86ISD::FNMSUB; 11368 break; 11369 case Intrinsic::x86_fma_vfmaddsub_ps: 11370 case Intrinsic::x86_fma_vfmaddsub_pd: 11371 case Intrinsic::x86_fma_vfmaddsub_ps_256: 11372 case Intrinsic::x86_fma_vfmaddsub_pd_256: 11373 Opc = X86ISD::FMADDSUB; 11374 break; 11375 case Intrinsic::x86_fma_vfmsubadd_ps: 11376 case Intrinsic::x86_fma_vfmsubadd_pd: 11377 case Intrinsic::x86_fma_vfmsubadd_ps_256: 11378 case Intrinsic::x86_fma_vfmsubadd_pd_256: 11379 Opc = X86ISD::FMSUBADD; 11380 break; 11381 } 11382 11383 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1), 11384 Op.getOperand(2), Op.getOperand(3)); 11385 } 11386 } 11387 } 11388 11389 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) { 11390 SDLoc dl(Op); 11391 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 11392 switch (IntNo) { 11393 default: return SDValue(); // Don't custom lower most intrinsics. 11394 11395 // RDRAND/RDSEED intrinsics. 11396 case Intrinsic::x86_rdrand_16: 11397 case Intrinsic::x86_rdrand_32: 11398 case Intrinsic::x86_rdrand_64: 11399 case Intrinsic::x86_rdseed_16: 11400 case Intrinsic::x86_rdseed_32: 11401 case Intrinsic::x86_rdseed_64: { 11402 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 || 11403 IntNo == Intrinsic::x86_rdseed_32 || 11404 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED : 11405 X86ISD::RDRAND; 11406 // Emit the node with the right value type. 11407 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other); 11408 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0)); 11409 11410 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1. 11411 // Otherwise return the value from Rand, which is always 0, casted to i32. 11412 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)), 11413 DAG.getConstant(1, Op->getValueType(1)), 11414 DAG.getConstant(X86::COND_B, MVT::i32), 11415 SDValue(Result.getNode(), 1) }; 11416 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, 11417 DAG.getVTList(Op->getValueType(1), MVT::Glue), 11418 Ops, array_lengthof(Ops)); 11419 11420 // Return { result, isValid, chain }. 11421 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid, 11422 SDValue(Result.getNode(), 2)); 11423 } 11424 11425 // XTEST intrinsics. 11426 case Intrinsic::x86_xtest: { 11427 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other); 11428 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0)); 11429 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 11430 DAG.getConstant(X86::COND_NE, MVT::i8), 11431 InTrans); 11432 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC); 11433 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), 11434 Ret, SDValue(InTrans.getNode(), 1)); 11435 } 11436 } 11437 } 11438 11439 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 11440 SelectionDAG &DAG) const { 11441 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11442 MFI->setReturnAddressIsTaken(true); 11443 11444 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11445 SDLoc dl(Op); 11446 EVT PtrVT = getPointerTy(); 11447 11448 if (Depth > 0) { 11449 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 11450 const X86RegisterInfo *RegInfo = 11451 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11452 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT); 11453 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 11454 DAG.getNode(ISD::ADD, dl, PtrVT, 11455 FrameAddr, Offset), 11456 MachinePointerInfo(), false, false, false, 0); 11457 } 11458 11459 // Just load the return address. 11460 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 11461 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 11462 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 11463 } 11464 11465 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 11466 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11467 MFI->setFrameAddressIsTaken(true); 11468 11469 EVT VT = Op.getValueType(); 11470 SDLoc dl(Op); // FIXME probably not meaningful 11471 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11472 const X86RegisterInfo *RegInfo = 11473 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11474 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction()); 11475 assert(((FrameReg == X86::RBP && VT == MVT::i64) || 11476 (FrameReg == X86::EBP && VT == MVT::i32)) && 11477 "Invalid Frame Register!"); 11478 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 11479 while (Depth--) 11480 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 11481 MachinePointerInfo(), 11482 false, false, false, 0); 11483 return FrameAddr; 11484 } 11485 11486 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 11487 SelectionDAG &DAG) const { 11488 const X86RegisterInfo *RegInfo = 11489 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11490 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize()); 11491 } 11492 11493 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 11494 SDValue Chain = Op.getOperand(0); 11495 SDValue Offset = Op.getOperand(1); 11496 SDValue Handler = Op.getOperand(2); 11497 SDLoc dl (Op); 11498 11499 EVT PtrVT = getPointerTy(); 11500 const X86RegisterInfo *RegInfo = 11501 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11502 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction()); 11503 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) || 11504 (FrameReg == X86::EBP && PtrVT == MVT::i32)) && 11505 "Invalid Frame Register!"); 11506 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT); 11507 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX; 11508 11509 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame, 11510 DAG.getIntPtrConstant(RegInfo->getSlotSize())); 11511 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset); 11512 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 11513 false, false, 0); 11514 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 11515 11516 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain, 11517 DAG.getRegister(StoreAddrReg, PtrVT)); 11518 } 11519 11520 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 11521 SelectionDAG &DAG) const { 11522 SDLoc DL(Op); 11523 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL, 11524 DAG.getVTList(MVT::i32, MVT::Other), 11525 Op.getOperand(0), Op.getOperand(1)); 11526 } 11527 11528 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 11529 SelectionDAG &DAG) const { 11530 SDLoc DL(Op); 11531 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 11532 Op.getOperand(0), Op.getOperand(1)); 11533 } 11534 11535 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) { 11536 return Op.getOperand(0); 11537 } 11538 11539 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 11540 SelectionDAG &DAG) const { 11541 SDValue Root = Op.getOperand(0); 11542 SDValue Trmp = Op.getOperand(1); // trampoline 11543 SDValue FPtr = Op.getOperand(2); // nested function 11544 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 11545 SDLoc dl (Op); 11546 11547 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 11548 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 11549 11550 if (Subtarget->is64Bit()) { 11551 SDValue OutChains[6]; 11552 11553 // Large code-model. 11554 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 11555 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 11556 11557 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7; 11558 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7; 11559 11560 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 11561 11562 // Load the pointer to the nested function into R11. 11563 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 11564 SDValue Addr = Trmp; 11565 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11566 Addr, MachinePointerInfo(TrmpAddr), 11567 false, false, 0); 11568 11569 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11570 DAG.getConstant(2, MVT::i64)); 11571 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 11572 MachinePointerInfo(TrmpAddr, 2), 11573 false, false, 2); 11574 11575 // Load the 'nest' parameter value into R10. 11576 // R10 is specified in X86CallingConv.td 11577 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 11578 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11579 DAG.getConstant(10, MVT::i64)); 11580 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11581 Addr, MachinePointerInfo(TrmpAddr, 10), 11582 false, false, 0); 11583 11584 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11585 DAG.getConstant(12, MVT::i64)); 11586 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 11587 MachinePointerInfo(TrmpAddr, 12), 11588 false, false, 2); 11589 11590 // Jump to the nested function. 11591 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 11592 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11593 DAG.getConstant(20, MVT::i64)); 11594 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11595 Addr, MachinePointerInfo(TrmpAddr, 20), 11596 false, false, 0); 11597 11598 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 11599 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11600 DAG.getConstant(22, MVT::i64)); 11601 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 11602 MachinePointerInfo(TrmpAddr, 22), 11603 false, false, 0); 11604 11605 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 11606 } else { 11607 const Function *Func = 11608 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 11609 CallingConv::ID CC = Func->getCallingConv(); 11610 unsigned NestReg; 11611 11612 switch (CC) { 11613 default: 11614 llvm_unreachable("Unsupported calling convention"); 11615 case CallingConv::C: 11616 case CallingConv::X86_StdCall: { 11617 // Pass 'nest' parameter in ECX. 11618 // Must be kept in sync with X86CallingConv.td 11619 NestReg = X86::ECX; 11620 11621 // Check that ECX wasn't needed by an 'inreg' parameter. 11622 FunctionType *FTy = Func->getFunctionType(); 11623 const AttributeSet &Attrs = Func->getAttributes(); 11624 11625 if (!Attrs.isEmpty() && !Func->isVarArg()) { 11626 unsigned InRegCount = 0; 11627 unsigned Idx = 1; 11628 11629 for (FunctionType::param_iterator I = FTy->param_begin(), 11630 E = FTy->param_end(); I != E; ++I, ++Idx) 11631 if (Attrs.hasAttribute(Idx, Attribute::InReg)) 11632 // FIXME: should only count parameters that are lowered to integers. 11633 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 11634 11635 if (InRegCount > 2) { 11636 report_fatal_error("Nest register in use - reduce number of inreg" 11637 " parameters!"); 11638 } 11639 } 11640 break; 11641 } 11642 case CallingConv::X86_FastCall: 11643 case CallingConv::X86_ThisCall: 11644 case CallingConv::Fast: 11645 // Pass 'nest' parameter in EAX. 11646 // Must be kept in sync with X86CallingConv.td 11647 NestReg = X86::EAX; 11648 break; 11649 } 11650 11651 SDValue OutChains[4]; 11652 SDValue Addr, Disp; 11653 11654 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11655 DAG.getConstant(10, MVT::i32)); 11656 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 11657 11658 // This is storing the opcode for MOV32ri. 11659 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 11660 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7; 11661 OutChains[0] = DAG.getStore(Root, dl, 11662 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 11663 Trmp, MachinePointerInfo(TrmpAddr), 11664 false, false, 0); 11665 11666 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11667 DAG.getConstant(1, MVT::i32)); 11668 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 11669 MachinePointerInfo(TrmpAddr, 1), 11670 false, false, 1); 11671 11672 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 11673 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11674 DAG.getConstant(5, MVT::i32)); 11675 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 11676 MachinePointerInfo(TrmpAddr, 5), 11677 false, false, 1); 11678 11679 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11680 DAG.getConstant(6, MVT::i32)); 11681 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 11682 MachinePointerInfo(TrmpAddr, 6), 11683 false, false, 1); 11684 11685 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 11686 } 11687 } 11688 11689 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 11690 SelectionDAG &DAG) const { 11691 /* 11692 The rounding mode is in bits 11:10 of FPSR, and has the following 11693 settings: 11694 00 Round to nearest 11695 01 Round to -inf 11696 10 Round to +inf 11697 11 Round to 0 11698 11699 FLT_ROUNDS, on the other hand, expects the following: 11700 -1 Undefined 11701 0 Round to 0 11702 1 Round to nearest 11703 2 Round to +inf 11704 3 Round to -inf 11705 11706 To perform the conversion, we do: 11707 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 11708 */ 11709 11710 MachineFunction &MF = DAG.getMachineFunction(); 11711 const TargetMachine &TM = MF.getTarget(); 11712 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 11713 unsigned StackAlignment = TFI.getStackAlignment(); 11714 EVT VT = Op.getValueType(); 11715 SDLoc DL(Op); 11716 11717 // Save FP Control Word to stack slot 11718 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 11719 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 11720 11721 MachineMemOperand *MMO = 11722 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 11723 MachineMemOperand::MOStore, 2, 2); 11724 11725 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 11726 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 11727 DAG.getVTList(MVT::Other), 11728 Ops, array_lengthof(Ops), MVT::i16, 11729 MMO); 11730 11731 // Load FP Control Word from stack slot 11732 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 11733 MachinePointerInfo(), false, false, false, 0); 11734 11735 // Transform as necessary 11736 SDValue CWD1 = 11737 DAG.getNode(ISD::SRL, DL, MVT::i16, 11738 DAG.getNode(ISD::AND, DL, MVT::i16, 11739 CWD, DAG.getConstant(0x800, MVT::i16)), 11740 DAG.getConstant(11, MVT::i8)); 11741 SDValue CWD2 = 11742 DAG.getNode(ISD::SRL, DL, MVT::i16, 11743 DAG.getNode(ISD::AND, DL, MVT::i16, 11744 CWD, DAG.getConstant(0x400, MVT::i16)), 11745 DAG.getConstant(9, MVT::i8)); 11746 11747 SDValue RetVal = 11748 DAG.getNode(ISD::AND, DL, MVT::i16, 11749 DAG.getNode(ISD::ADD, DL, MVT::i16, 11750 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 11751 DAG.getConstant(1, MVT::i16)), 11752 DAG.getConstant(3, MVT::i16)); 11753 11754 return DAG.getNode((VT.getSizeInBits() < 16 ? 11755 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 11756 } 11757 11758 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) { 11759 EVT VT = Op.getValueType(); 11760 EVT OpVT = VT; 11761 unsigned NumBits = VT.getSizeInBits(); 11762 SDLoc dl(Op); 11763 11764 Op = Op.getOperand(0); 11765 if (VT == MVT::i8) { 11766 // Zero extend to i32 since there is not an i8 bsr. 11767 OpVT = MVT::i32; 11768 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11769 } 11770 11771 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 11772 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11773 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11774 11775 // If src is zero (i.e. bsr sets ZF), returns NumBits. 11776 SDValue Ops[] = { 11777 Op, 11778 DAG.getConstant(NumBits+NumBits-1, OpVT), 11779 DAG.getConstant(X86::COND_E, MVT::i8), 11780 Op.getValue(1) 11781 }; 11782 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 11783 11784 // Finally xor with NumBits-1. 11785 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11786 11787 if (VT == MVT::i8) 11788 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11789 return Op; 11790 } 11791 11792 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 11793 EVT VT = Op.getValueType(); 11794 EVT OpVT = VT; 11795 unsigned NumBits = VT.getSizeInBits(); 11796 SDLoc dl(Op); 11797 11798 Op = Op.getOperand(0); 11799 if (VT == MVT::i8) { 11800 // Zero extend to i32 since there is not an i8 bsr. 11801 OpVT = MVT::i32; 11802 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11803 } 11804 11805 // Issue a bsr (scan bits in reverse). 11806 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11807 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11808 11809 // And xor with NumBits-1. 11810 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11811 11812 if (VT == MVT::i8) 11813 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11814 return Op; 11815 } 11816 11817 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) { 11818 EVT VT = Op.getValueType(); 11819 unsigned NumBits = VT.getSizeInBits(); 11820 SDLoc dl(Op); 11821 Op = Op.getOperand(0); 11822 11823 // Issue a bsf (scan bits forward) which also sets EFLAGS. 11824 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 11825 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 11826 11827 // If src is zero (i.e. bsf sets ZF), returns NumBits. 11828 SDValue Ops[] = { 11829 Op, 11830 DAG.getConstant(NumBits, VT), 11831 DAG.getConstant(X86::COND_E, MVT::i8), 11832 Op.getValue(1) 11833 }; 11834 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops)); 11835 } 11836 11837 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 11838 // ones, and then concatenate the result back. 11839 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 11840 EVT VT = Op.getValueType(); 11841 11842 assert(VT.is256BitVector() && VT.isInteger() && 11843 "Unsupported value type for operation"); 11844 11845 unsigned NumElems = VT.getVectorNumElements(); 11846 SDLoc dl(Op); 11847 11848 // Extract the LHS vectors 11849 SDValue LHS = Op.getOperand(0); 11850 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 11851 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 11852 11853 // Extract the RHS vectors 11854 SDValue RHS = Op.getOperand(1); 11855 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 11856 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 11857 11858 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11859 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11860 11861 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 11862 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 11863 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 11864 } 11865 11866 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) { 11867 assert(Op.getValueType().is256BitVector() && 11868 Op.getValueType().isInteger() && 11869 "Only handle AVX 256-bit vector integer operation"); 11870 return Lower256IntArith(Op, DAG); 11871 } 11872 11873 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) { 11874 assert(Op.getValueType().is256BitVector() && 11875 Op.getValueType().isInteger() && 11876 "Only handle AVX 256-bit vector integer operation"); 11877 return Lower256IntArith(Op, DAG); 11878 } 11879 11880 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget, 11881 SelectionDAG &DAG) { 11882 SDLoc dl(Op); 11883 EVT VT = Op.getValueType(); 11884 11885 // Decompose 256-bit ops into smaller 128-bit ops. 11886 if (VT.is256BitVector() && !Subtarget->hasInt256()) 11887 return Lower256IntArith(Op, DAG); 11888 11889 SDValue A = Op.getOperand(0); 11890 SDValue B = Op.getOperand(1); 11891 11892 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle. 11893 if (VT == MVT::v4i32) { 11894 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() && 11895 "Should not custom lower when pmuldq is available!"); 11896 11897 // Extract the odd parts. 11898 static const int UnpackMask[] = { 1, -1, 3, -1 }; 11899 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask); 11900 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask); 11901 11902 // Multiply the even parts. 11903 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B); 11904 // Now multiply odd parts. 11905 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds); 11906 11907 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens); 11908 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds); 11909 11910 // Merge the two vectors back together with a shuffle. This expands into 2 11911 // shuffles. 11912 static const int ShufMask[] = { 0, 4, 2, 6 }; 11913 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask); 11914 } 11915 11916 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && 11917 "Only know how to lower V2I64/V4I64 multiply"); 11918 11919 // Ahi = psrlqi(a, 32); 11920 // Bhi = psrlqi(b, 32); 11921 // 11922 // AloBlo = pmuludq(a, b); 11923 // AloBhi = pmuludq(a, Bhi); 11924 // AhiBlo = pmuludq(Ahi, b); 11925 11926 // AloBhi = psllqi(AloBhi, 32); 11927 // AhiBlo = psllqi(AhiBlo, 32); 11928 // return AloBlo + AloBhi + AhiBlo; 11929 11930 SDValue ShAmt = DAG.getConstant(32, MVT::i32); 11931 11932 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt); 11933 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt); 11934 11935 // Bit cast to 32-bit vectors for MULUDQ 11936 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32; 11937 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A); 11938 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B); 11939 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi); 11940 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi); 11941 11942 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B); 11943 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi); 11944 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B); 11945 11946 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt); 11947 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt); 11948 11949 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 11950 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 11951 } 11952 11953 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const { 11954 EVT VT = Op.getValueType(); 11955 EVT EltTy = VT.getVectorElementType(); 11956 unsigned NumElts = VT.getVectorNumElements(); 11957 SDValue N0 = Op.getOperand(0); 11958 SDLoc dl(Op); 11959 11960 // Lower sdiv X, pow2-const. 11961 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1)); 11962 if (!C) 11963 return SDValue(); 11964 11965 APInt SplatValue, SplatUndef; 11966 unsigned SplatBitSize; 11967 bool HasAnyUndefs; 11968 if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 11969 HasAnyUndefs) || 11970 EltTy.getSizeInBits() < SplatBitSize) 11971 return SDValue(); 11972 11973 if ((SplatValue != 0) && 11974 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) { 11975 unsigned lg2 = SplatValue.countTrailingZeros(); 11976 // Splat the sign bit. 11977 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32); 11978 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG); 11979 // Add (N0 < 0) ? abs2 - 1 : 0; 11980 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32); 11981 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG); 11982 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL); 11983 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32); 11984 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG); 11985 11986 // If we're dividing by a positive value, we're done. Otherwise, we must 11987 // negate the result. 11988 if (SplatValue.isNonNegative()) 11989 return SRA; 11990 11991 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy)); 11992 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts); 11993 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA); 11994 } 11995 return SDValue(); 11996 } 11997 11998 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG, 11999 const X86Subtarget *Subtarget) { 12000 EVT VT = Op.getValueType(); 12001 SDLoc dl(Op); 12002 SDValue R = Op.getOperand(0); 12003 SDValue Amt = Op.getOperand(1); 12004 12005 // Optimize shl/srl/sra with constant shift amount. 12006 if (isSplatVector(Amt.getNode())) { 12007 SDValue SclrAmt = Amt->getOperand(0); 12008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 12009 uint64_t ShiftAmt = C->getZExtValue(); 12010 12011 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 12012 (Subtarget->hasInt256() && 12013 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) { 12014 if (Op.getOpcode() == ISD::SHL) 12015 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 12016 DAG.getConstant(ShiftAmt, MVT::i32)); 12017 if (Op.getOpcode() == ISD::SRL) 12018 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 12019 DAG.getConstant(ShiftAmt, MVT::i32)); 12020 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64) 12021 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 12022 DAG.getConstant(ShiftAmt, MVT::i32)); 12023 } 12024 12025 if (VT == MVT::v16i8) { 12026 if (Op.getOpcode() == ISD::SHL) { 12027 // Make a large shift. 12028 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R, 12029 DAG.getConstant(ShiftAmt, MVT::i32)); 12030 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 12031 // Zero out the rightmost bits. 12032 SmallVector<SDValue, 16> V(16, 12033 DAG.getConstant(uint8_t(-1U << ShiftAmt), 12034 MVT::i8)); 12035 return DAG.getNode(ISD::AND, dl, VT, SHL, 12036 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 12037 } 12038 if (Op.getOpcode() == ISD::SRL) { 12039 // Make a large shift. 12040 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R, 12041 DAG.getConstant(ShiftAmt, MVT::i32)); 12042 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 12043 // Zero out the leftmost bits. 12044 SmallVector<SDValue, 16> V(16, 12045 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 12046 MVT::i8)); 12047 return DAG.getNode(ISD::AND, dl, VT, SRL, 12048 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 12049 } 12050 if (Op.getOpcode() == ISD::SRA) { 12051 if (ShiftAmt == 7) { 12052 // R s>> 7 === R s< 0 12053 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 12054 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 12055 } 12056 12057 // R s>> a === ((R u>> a) ^ m) - m 12058 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 12059 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 12060 MVT::i8)); 12061 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 12062 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 12063 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 12064 return Res; 12065 } 12066 llvm_unreachable("Unknown shift opcode."); 12067 } 12068 12069 if (Subtarget->hasInt256() && VT == MVT::v32i8) { 12070 if (Op.getOpcode() == ISD::SHL) { 12071 // Make a large shift. 12072 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R, 12073 DAG.getConstant(ShiftAmt, MVT::i32)); 12074 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 12075 // Zero out the rightmost bits. 12076 SmallVector<SDValue, 32> V(32, 12077 DAG.getConstant(uint8_t(-1U << ShiftAmt), 12078 MVT::i8)); 12079 return DAG.getNode(ISD::AND, dl, VT, SHL, 12080 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 12081 } 12082 if (Op.getOpcode() == ISD::SRL) { 12083 // Make a large shift. 12084 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R, 12085 DAG.getConstant(ShiftAmt, MVT::i32)); 12086 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 12087 // Zero out the leftmost bits. 12088 SmallVector<SDValue, 32> V(32, 12089 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 12090 MVT::i8)); 12091 return DAG.getNode(ISD::AND, dl, VT, SRL, 12092 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 12093 } 12094 if (Op.getOpcode() == ISD::SRA) { 12095 if (ShiftAmt == 7) { 12096 // R s>> 7 === R s< 0 12097 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 12098 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 12099 } 12100 12101 // R s>> a === ((R u>> a) ^ m) - m 12102 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 12103 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt, 12104 MVT::i8)); 12105 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32); 12106 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 12107 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 12108 return Res; 12109 } 12110 llvm_unreachable("Unknown shift opcode."); 12111 } 12112 } 12113 } 12114 12115 // Special case in 32-bit mode, where i64 is expanded into high and low parts. 12116 if (!Subtarget->is64Bit() && 12117 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) && 12118 Amt.getOpcode() == ISD::BITCAST && 12119 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) { 12120 Amt = Amt.getOperand(0); 12121 unsigned Ratio = Amt.getValueType().getVectorNumElements() / 12122 VT.getVectorNumElements(); 12123 unsigned RatioInLog2 = Log2_32_Ceil(Ratio); 12124 uint64_t ShiftAmt = 0; 12125 for (unsigned i = 0; i != Ratio; ++i) { 12126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i)); 12127 if (C == 0) 12128 return SDValue(); 12129 // 6 == Log2(64) 12130 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2))); 12131 } 12132 // Check remaining shift amounts. 12133 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) { 12134 uint64_t ShAmt = 0; 12135 for (unsigned j = 0; j != Ratio; ++j) { 12136 ConstantSDNode *C = 12137 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j)); 12138 if (C == 0) 12139 return SDValue(); 12140 // 6 == Log2(64) 12141 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2))); 12142 } 12143 if (ShAmt != ShiftAmt) 12144 return SDValue(); 12145 } 12146 switch (Op.getOpcode()) { 12147 default: 12148 llvm_unreachable("Unknown shift opcode!"); 12149 case ISD::SHL: 12150 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 12151 DAG.getConstant(ShiftAmt, MVT::i32)); 12152 case ISD::SRL: 12153 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 12154 DAG.getConstant(ShiftAmt, MVT::i32)); 12155 case ISD::SRA: 12156 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 12157 DAG.getConstant(ShiftAmt, MVT::i32)); 12158 } 12159 } 12160 12161 return SDValue(); 12162 } 12163 12164 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG, 12165 const X86Subtarget* Subtarget) { 12166 EVT VT = Op.getValueType(); 12167 SDLoc dl(Op); 12168 SDValue R = Op.getOperand(0); 12169 SDValue Amt = Op.getOperand(1); 12170 12171 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) || 12172 VT == MVT::v4i32 || VT == MVT::v8i16 || 12173 (Subtarget->hasInt256() && 12174 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) || 12175 VT == MVT::v8i32 || VT == MVT::v16i16))) { 12176 SDValue BaseShAmt; 12177 EVT EltVT = VT.getVectorElementType(); 12178 12179 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 12180 unsigned NumElts = VT.getVectorNumElements(); 12181 unsigned i, j; 12182 for (i = 0; i != NumElts; ++i) { 12183 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF) 12184 continue; 12185 break; 12186 } 12187 for (j = i; j != NumElts; ++j) { 12188 SDValue Arg = Amt.getOperand(j); 12189 if (Arg.getOpcode() == ISD::UNDEF) continue; 12190 if (Arg != Amt.getOperand(i)) 12191 break; 12192 } 12193 if (i != NumElts && j == NumElts) 12194 BaseShAmt = Amt.getOperand(i); 12195 } else { 12196 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR) 12197 Amt = Amt.getOperand(0); 12198 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE && 12199 cast<ShuffleVectorSDNode>(Amt)->isSplat()) { 12200 SDValue InVec = Amt.getOperand(0); 12201 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 12202 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 12203 unsigned i = 0; 12204 for (; i != NumElts; ++i) { 12205 SDValue Arg = InVec.getOperand(i); 12206 if (Arg.getOpcode() == ISD::UNDEF) continue; 12207 BaseShAmt = Arg; 12208 break; 12209 } 12210 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 12211 if (ConstantSDNode *C = 12212 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 12213 unsigned SplatIdx = 12214 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex(); 12215 if (C->getZExtValue() == SplatIdx) 12216 BaseShAmt = InVec.getOperand(1); 12217 } 12218 } 12219 if (BaseShAmt.getNode() == 0) 12220 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt, 12221 DAG.getIntPtrConstant(0)); 12222 } 12223 } 12224 12225 if (BaseShAmt.getNode()) { 12226 if (EltVT.bitsGT(MVT::i32)) 12227 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt); 12228 else if (EltVT.bitsLT(MVT::i32)) 12229 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt); 12230 12231 switch (Op.getOpcode()) { 12232 default: 12233 llvm_unreachable("Unknown shift opcode!"); 12234 case ISD::SHL: 12235 switch (VT.getSimpleVT().SimpleTy) { 12236 default: return SDValue(); 12237 case MVT::v2i64: 12238 case MVT::v4i32: 12239 case MVT::v8i16: 12240 case MVT::v4i64: 12241 case MVT::v8i32: 12242 case MVT::v16i16: 12243 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG); 12244 } 12245 case ISD::SRA: 12246 switch (VT.getSimpleVT().SimpleTy) { 12247 default: return SDValue(); 12248 case MVT::v4i32: 12249 case MVT::v8i16: 12250 case MVT::v8i32: 12251 case MVT::v16i16: 12252 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG); 12253 } 12254 case ISD::SRL: 12255 switch (VT.getSimpleVT().SimpleTy) { 12256 default: return SDValue(); 12257 case MVT::v2i64: 12258 case MVT::v4i32: 12259 case MVT::v8i16: 12260 case MVT::v4i64: 12261 case MVT::v8i32: 12262 case MVT::v16i16: 12263 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG); 12264 } 12265 } 12266 } 12267 } 12268 12269 // Special case in 32-bit mode, where i64 is expanded into high and low parts. 12270 if (!Subtarget->is64Bit() && 12271 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) && 12272 Amt.getOpcode() == ISD::BITCAST && 12273 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) { 12274 Amt = Amt.getOperand(0); 12275 unsigned Ratio = Amt.getValueType().getVectorNumElements() / 12276 VT.getVectorNumElements(); 12277 std::vector<SDValue> Vals(Ratio); 12278 for (unsigned i = 0; i != Ratio; ++i) 12279 Vals[i] = Amt.getOperand(i); 12280 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) { 12281 for (unsigned j = 0; j != Ratio; ++j) 12282 if (Vals[j] != Amt.getOperand(i + j)) 12283 return SDValue(); 12284 } 12285 switch (Op.getOpcode()) { 12286 default: 12287 llvm_unreachable("Unknown shift opcode!"); 12288 case ISD::SHL: 12289 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1)); 12290 case ISD::SRL: 12291 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1)); 12292 case ISD::SRA: 12293 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1)); 12294 } 12295 } 12296 12297 return SDValue(); 12298 } 12299 12300 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 12301 12302 EVT VT = Op.getValueType(); 12303 SDLoc dl(Op); 12304 SDValue R = Op.getOperand(0); 12305 SDValue Amt = Op.getOperand(1); 12306 SDValue V; 12307 12308 if (!Subtarget->hasSSE2()) 12309 return SDValue(); 12310 12311 V = LowerScalarImmediateShift(Op, DAG, Subtarget); 12312 if (V.getNode()) 12313 return V; 12314 12315 V = LowerScalarVariableShift(Op, DAG, Subtarget); 12316 if (V.getNode()) 12317 return V; 12318 12319 // AVX2 has VPSLLV/VPSRAV/VPSRLV. 12320 if (Subtarget->hasInt256()) { 12321 if (Op.getOpcode() == ISD::SRL && 12322 (VT == MVT::v2i64 || VT == MVT::v4i32 || 12323 VT == MVT::v4i64 || VT == MVT::v8i32)) 12324 return Op; 12325 if (Op.getOpcode() == ISD::SHL && 12326 (VT == MVT::v2i64 || VT == MVT::v4i32 || 12327 VT == MVT::v4i64 || VT == MVT::v8i32)) 12328 return Op; 12329 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32)) 12330 return Op; 12331 } 12332 12333 // Lower SHL with variable shift amount. 12334 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 12335 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT)); 12336 12337 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT)); 12338 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 12339 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 12340 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 12341 } 12342 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 12343 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq."); 12344 12345 // a = a << 5; 12346 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT)); 12347 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op); 12348 12349 // Turn 'a' into a mask suitable for VSELECT 12350 SDValue VSelM = DAG.getConstant(0x80, VT); 12351 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 12352 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 12353 12354 SDValue CM1 = DAG.getConstant(0x0f, VT); 12355 SDValue CM2 = DAG.getConstant(0x3f, VT); 12356 12357 // r = VSELECT(r, psllw(r & (char16)15, 4), a); 12358 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1); 12359 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 12360 DAG.getConstant(4, MVT::i32), DAG); 12361 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 12362 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 12363 12364 // a += a 12365 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 12366 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 12367 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 12368 12369 // r = VSELECT(r, psllw(r & (char16)63, 2), a); 12370 M = DAG.getNode(ISD::AND, dl, VT, R, CM2); 12371 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 12372 DAG.getConstant(2, MVT::i32), DAG); 12373 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 12374 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 12375 12376 // a += a 12377 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 12378 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 12379 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 12380 12381 // return VSELECT(r, r+r, a); 12382 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, 12383 DAG.getNode(ISD::ADD, dl, VT, R, R), R); 12384 return R; 12385 } 12386 12387 // Decompose 256-bit shifts into smaller 128-bit shifts. 12388 if (VT.is256BitVector()) { 12389 unsigned NumElems = VT.getVectorNumElements(); 12390 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 12391 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 12392 12393 // Extract the two vectors 12394 SDValue V1 = Extract128BitVector(R, 0, DAG, dl); 12395 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl); 12396 12397 // Recreate the shift amount vectors 12398 SDValue Amt1, Amt2; 12399 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 12400 // Constant shift amount 12401 SmallVector<SDValue, 4> Amt1Csts; 12402 SmallVector<SDValue, 4> Amt2Csts; 12403 for (unsigned i = 0; i != NumElems/2; ++i) 12404 Amt1Csts.push_back(Amt->getOperand(i)); 12405 for (unsigned i = NumElems/2; i != NumElems; ++i) 12406 Amt2Csts.push_back(Amt->getOperand(i)); 12407 12408 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 12409 &Amt1Csts[0], NumElems/2); 12410 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 12411 &Amt2Csts[0], NumElems/2); 12412 } else { 12413 // Variable shift amount 12414 Amt1 = Extract128BitVector(Amt, 0, DAG, dl); 12415 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl); 12416 } 12417 12418 // Issue new vector shifts for the smaller types 12419 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 12420 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 12421 12422 // Concatenate the result back 12423 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 12424 } 12425 12426 return SDValue(); 12427 } 12428 12429 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 12430 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 12431 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 12432 // looks for this combo and may remove the "setcc" instruction if the "setcc" 12433 // has only one use. 12434 SDNode *N = Op.getNode(); 12435 SDValue LHS = N->getOperand(0); 12436 SDValue RHS = N->getOperand(1); 12437 unsigned BaseOp = 0; 12438 unsigned Cond = 0; 12439 SDLoc DL(Op); 12440 switch (Op.getOpcode()) { 12441 default: llvm_unreachable("Unknown ovf instruction!"); 12442 case ISD::SADDO: 12443 // A subtract of one will be selected as a INC. Note that INC doesn't 12444 // set CF, so we can't do this for UADDO. 12445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 12446 if (C->isOne()) { 12447 BaseOp = X86ISD::INC; 12448 Cond = X86::COND_O; 12449 break; 12450 } 12451 BaseOp = X86ISD::ADD; 12452 Cond = X86::COND_O; 12453 break; 12454 case ISD::UADDO: 12455 BaseOp = X86ISD::ADD; 12456 Cond = X86::COND_B; 12457 break; 12458 case ISD::SSUBO: 12459 // A subtract of one will be selected as a DEC. Note that DEC doesn't 12460 // set CF, so we can't do this for USUBO. 12461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 12462 if (C->isOne()) { 12463 BaseOp = X86ISD::DEC; 12464 Cond = X86::COND_O; 12465 break; 12466 } 12467 BaseOp = X86ISD::SUB; 12468 Cond = X86::COND_O; 12469 break; 12470 case ISD::USUBO: 12471 BaseOp = X86ISD::SUB; 12472 Cond = X86::COND_B; 12473 break; 12474 case ISD::SMULO: 12475 BaseOp = X86ISD::SMUL; 12476 Cond = X86::COND_O; 12477 break; 12478 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 12479 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 12480 MVT::i32); 12481 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 12482 12483 SDValue SetCC = 12484 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 12485 DAG.getConstant(X86::COND_O, MVT::i32), 12486 SDValue(Sum.getNode(), 2)); 12487 12488 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 12489 } 12490 } 12491 12492 // Also sets EFLAGS. 12493 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 12494 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 12495 12496 SDValue SetCC = 12497 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 12498 DAG.getConstant(Cond, MVT::i32), 12499 SDValue(Sum.getNode(), 1)); 12500 12501 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 12502 } 12503 12504 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 12505 SelectionDAG &DAG) const { 12506 SDLoc dl(Op); 12507 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 12508 EVT VT = Op.getValueType(); 12509 12510 if (!Subtarget->hasSSE2() || !VT.isVector()) 12511 return SDValue(); 12512 12513 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 12514 ExtraVT.getScalarType().getSizeInBits(); 12515 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 12516 12517 switch (VT.getSimpleVT().SimpleTy) { 12518 default: return SDValue(); 12519 case MVT::v8i32: 12520 case MVT::v16i16: 12521 if (!Subtarget->hasFp256()) 12522 return SDValue(); 12523 if (!Subtarget->hasInt256()) { 12524 // needs to be split 12525 unsigned NumElems = VT.getVectorNumElements(); 12526 12527 // Extract the LHS vectors 12528 SDValue LHS = Op.getOperand(0); 12529 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 12530 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 12531 12532 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 12533 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 12534 12535 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 12536 unsigned ExtraNumElems = ExtraVT.getVectorNumElements(); 12537 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT, 12538 ExtraNumElems/2); 12539 SDValue Extra = DAG.getValueType(ExtraVT); 12540 12541 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra); 12542 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra); 12543 12544 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2); 12545 } 12546 // fall through 12547 case MVT::v4i32: 12548 case MVT::v8i16: { 12549 // (sext (vzext x)) -> (vsext x) 12550 SDValue Op0 = Op.getOperand(0); 12551 SDValue Op00 = Op0.getOperand(0); 12552 SDValue Tmp1; 12553 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT. 12554 if (Op0.getOpcode() == ISD::BITCAST && 12555 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) 12556 Tmp1 = LowerVectorIntExtend(Op00, DAG); 12557 if (Tmp1.getNode()) { 12558 SDValue Tmp1Op0 = Tmp1.getOperand(0); 12559 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT && 12560 "This optimization is invalid without a VZEXT."); 12561 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0)); 12562 } 12563 12564 // If the above didn't work, then just use Shift-Left + Shift-Right. 12565 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG); 12566 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG); 12567 } 12568 } 12569 } 12570 12571 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget, 12572 SelectionDAG &DAG) { 12573 SDLoc dl(Op); 12574 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 12575 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 12576 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 12577 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 12578 12579 // The only fence that needs an instruction is a sequentially-consistent 12580 // cross-thread fence. 12581 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 12582 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 12583 // no-sse2). There isn't any reason to disable it if the target processor 12584 // supports it. 12585 if (Subtarget->hasSSE2() || Subtarget->is64Bit()) 12586 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 12587 12588 SDValue Chain = Op.getOperand(0); 12589 SDValue Zero = DAG.getConstant(0, MVT::i32); 12590 SDValue Ops[] = { 12591 DAG.getRegister(X86::ESP, MVT::i32), // Base 12592 DAG.getTargetConstant(1, MVT::i8), // Scale 12593 DAG.getRegister(0, MVT::i32), // Index 12594 DAG.getTargetConstant(0, MVT::i32), // Disp 12595 DAG.getRegister(0, MVT::i32), // Segment. 12596 Zero, 12597 Chain 12598 }; 12599 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops); 12600 return SDValue(Res, 0); 12601 } 12602 12603 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 12604 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 12605 } 12606 12607 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget, 12608 SelectionDAG &DAG) { 12609 EVT T = Op.getValueType(); 12610 SDLoc DL(Op); 12611 unsigned Reg = 0; 12612 unsigned size = 0; 12613 switch(T.getSimpleVT().SimpleTy) { 12614 default: llvm_unreachable("Invalid value type!"); 12615 case MVT::i8: Reg = X86::AL; size = 1; break; 12616 case MVT::i16: Reg = X86::AX; size = 2; break; 12617 case MVT::i32: Reg = X86::EAX; size = 4; break; 12618 case MVT::i64: 12619 assert(Subtarget->is64Bit() && "Node not type legal!"); 12620 Reg = X86::RAX; size = 8; 12621 break; 12622 } 12623 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 12624 Op.getOperand(2), SDValue()); 12625 SDValue Ops[] = { cpIn.getValue(0), 12626 Op.getOperand(1), 12627 Op.getOperand(3), 12628 DAG.getTargetConstant(size, MVT::i8), 12629 cpIn.getValue(1) }; 12630 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12631 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 12632 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 12633 Ops, array_lengthof(Ops), T, MMO); 12634 SDValue cpOut = 12635 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 12636 return cpOut; 12637 } 12638 12639 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget, 12640 SelectionDAG &DAG) { 12641 assert(Subtarget->is64Bit() && "Result not type legalized?"); 12642 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12643 SDValue TheChain = Op.getOperand(0); 12644 SDLoc dl(Op); 12645 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 12646 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 12647 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 12648 rax.getValue(2)); 12649 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 12650 DAG.getConstant(32, MVT::i8)); 12651 SDValue Ops[] = { 12652 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 12653 rdx.getValue(1) 12654 }; 12655 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl); 12656 } 12657 12658 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 12659 EVT SrcVT = Op.getOperand(0).getValueType(); 12660 EVT DstVT = Op.getValueType(); 12661 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 12662 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 12663 assert((DstVT == MVT::i64 || 12664 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 12665 "Unexpected custom BITCAST"); 12666 // i64 <=> MMX conversions are Legal. 12667 if (SrcVT==MVT::i64 && DstVT.isVector()) 12668 return Op; 12669 if (DstVT==MVT::i64 && SrcVT.isVector()) 12670 return Op; 12671 // MMX <=> MMX conversions are Legal. 12672 if (SrcVT.isVector() && DstVT.isVector()) 12673 return Op; 12674 // All other conversions need to be expanded. 12675 return SDValue(); 12676 } 12677 12678 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) { 12679 SDNode *Node = Op.getNode(); 12680 SDLoc dl(Node); 12681 EVT T = Node->getValueType(0); 12682 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 12683 DAG.getConstant(0, T), Node->getOperand(2)); 12684 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 12685 cast<AtomicSDNode>(Node)->getMemoryVT(), 12686 Node->getOperand(0), 12687 Node->getOperand(1), negOp, 12688 cast<AtomicSDNode>(Node)->getSrcValue(), 12689 cast<AtomicSDNode>(Node)->getAlignment(), 12690 cast<AtomicSDNode>(Node)->getOrdering(), 12691 cast<AtomicSDNode>(Node)->getSynchScope()); 12692 } 12693 12694 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 12695 SDNode *Node = Op.getNode(); 12696 SDLoc dl(Node); 12697 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 12698 12699 // Convert seq_cst store -> xchg 12700 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 12701 // FIXME: On 32-bit, store -> fist or movq would be more efficient 12702 // (The only way to get a 16-byte store is cmpxchg16b) 12703 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 12704 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 12705 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12706 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 12707 cast<AtomicSDNode>(Node)->getMemoryVT(), 12708 Node->getOperand(0), 12709 Node->getOperand(1), Node->getOperand(2), 12710 cast<AtomicSDNode>(Node)->getMemOperand(), 12711 cast<AtomicSDNode>(Node)->getOrdering(), 12712 cast<AtomicSDNode>(Node)->getSynchScope()); 12713 return Swap.getValue(1); 12714 } 12715 // Other atomic stores have a simple pattern. 12716 return Op; 12717 } 12718 12719 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 12720 EVT VT = Op.getNode()->getValueType(0); 12721 12722 // Let legalize expand this if it isn't a legal type yet. 12723 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12724 return SDValue(); 12725 12726 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12727 12728 unsigned Opc; 12729 bool ExtraOp = false; 12730 switch (Op.getOpcode()) { 12731 default: llvm_unreachable("Invalid code"); 12732 case ISD::ADDC: Opc = X86ISD::ADD; break; 12733 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 12734 case ISD::SUBC: Opc = X86ISD::SUB; break; 12735 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 12736 } 12737 12738 if (!ExtraOp) 12739 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 12740 Op.getOperand(1)); 12741 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 12742 Op.getOperand(1), Op.getOperand(2)); 12743 } 12744 12745 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 12746 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit()); 12747 12748 // For MacOSX, we want to call an alternative entry point: __sincos_stret, 12749 // which returns the values as { float, float } (in XMM0) or 12750 // { double, double } (which is returned in XMM0, XMM1). 12751 SDLoc dl(Op); 12752 SDValue Arg = Op.getOperand(0); 12753 EVT ArgVT = Arg.getValueType(); 12754 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 12755 12756 ArgListTy Args; 12757 ArgListEntry Entry; 12758 12759 Entry.Node = Arg; 12760 Entry.Ty = ArgTy; 12761 Entry.isSExt = false; 12762 Entry.isZExt = false; 12763 Args.push_back(Entry); 12764 12765 bool isF64 = ArgVT == MVT::f64; 12766 // Only optimize x86_64 for now. i386 is a bit messy. For f32, 12767 // the small struct {f32, f32} is returned in (eax, edx). For f64, 12768 // the results are returned via SRet in memory. 12769 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret"; 12770 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy()); 12771 12772 Type *RetTy = isF64 12773 ? (Type*)StructType::get(ArgTy, ArgTy, NULL) 12774 : (Type*)VectorType::get(ArgTy, 4); 12775 TargetLowering:: 12776 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, 12777 false, false, false, false, 0, 12778 CallingConv::C, /*isTaillCall=*/false, 12779 /*doesNotRet=*/false, /*isReturnValueUsed*/true, 12780 Callee, Args, DAG, dl); 12781 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12782 12783 if (isF64) 12784 // Returned in xmm0 and xmm1. 12785 return CallResult.first; 12786 12787 // Returned in bits 0:31 and 32:64 xmm0. 12788 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, 12789 CallResult.first, DAG.getIntPtrConstant(0)); 12790 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, 12791 CallResult.first, DAG.getIntPtrConstant(1)); 12792 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 12793 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal); 12794 } 12795 12796 /// LowerOperation - Provide custom lowering hooks for some operations. 12797 /// 12798 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 12799 switch (Op.getOpcode()) { 12800 default: llvm_unreachable("Should not custom lower this!"); 12801 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 12802 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG); 12803 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG); 12804 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 12805 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 12806 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 12807 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 12808 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 12809 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 12810 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 12811 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG); 12812 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG); 12813 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 12814 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 12815 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 12816 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 12817 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 12818 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 12819 case ISD::SHL_PARTS: 12820 case ISD::SRA_PARTS: 12821 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 12822 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 12823 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 12824 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 12825 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG); 12826 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG); 12827 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG); 12828 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 12829 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 12830 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 12831 case ISD::FABS: return LowerFABS(Op, DAG); 12832 case ISD::FNEG: return LowerFNEG(Op, DAG); 12833 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 12834 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 12835 case ISD::SETCC: return LowerSETCC(Op, DAG); 12836 case ISD::SELECT: return LowerSELECT(Op, DAG); 12837 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 12838 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 12839 case ISD::VASTART: return LowerVASTART(Op, DAG); 12840 case ISD::VAARG: return LowerVAARG(Op, DAG); 12841 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG); 12842 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 12843 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 12844 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 12845 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 12846 case ISD::FRAME_TO_ARGS_OFFSET: 12847 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 12848 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 12849 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 12850 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 12851 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 12852 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 12853 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 12854 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 12855 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 12856 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG); 12857 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 12858 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG); 12859 case ISD::SRA: 12860 case ISD::SRL: 12861 case ISD::SHL: return LowerShift(Op, DAG); 12862 case ISD::SADDO: 12863 case ISD::UADDO: 12864 case ISD::SSUBO: 12865 case ISD::USUBO: 12866 case ISD::SMULO: 12867 case ISD::UMULO: return LowerXALUO(Op, DAG); 12868 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG); 12869 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 12870 case ISD::ADDC: 12871 case ISD::ADDE: 12872 case ISD::SUBC: 12873 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 12874 case ISD::ADD: return LowerADD(Op, DAG); 12875 case ISD::SUB: return LowerSUB(Op, DAG); 12876 case ISD::SDIV: return LowerSDIV(Op, DAG); 12877 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 12878 } 12879 } 12880 12881 static void ReplaceATOMIC_LOAD(SDNode *Node, 12882 SmallVectorImpl<SDValue> &Results, 12883 SelectionDAG &DAG) { 12884 SDLoc dl(Node); 12885 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 12886 12887 // Convert wide load -> cmpxchg8b/cmpxchg16b 12888 // FIXME: On 32-bit, load -> fild or movq would be more efficient 12889 // (The only way to get a 16-byte load is cmpxchg16b) 12890 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 12891 SDValue Zero = DAG.getConstant(0, VT); 12892 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 12893 Node->getOperand(0), 12894 Node->getOperand(1), Zero, Zero, 12895 cast<AtomicSDNode>(Node)->getMemOperand(), 12896 cast<AtomicSDNode>(Node)->getOrdering(), 12897 cast<AtomicSDNode>(Node)->getSynchScope()); 12898 Results.push_back(Swap.getValue(0)); 12899 Results.push_back(Swap.getValue(1)); 12900 } 12901 12902 static void 12903 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 12904 SelectionDAG &DAG, unsigned NewOp) { 12905 SDLoc dl(Node); 12906 assert (Node->getValueType(0) == MVT::i64 && 12907 "Only know how to expand i64 atomics"); 12908 12909 SDValue Chain = Node->getOperand(0); 12910 SDValue In1 = Node->getOperand(1); 12911 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12912 Node->getOperand(2), DAG.getIntPtrConstant(0)); 12913 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12914 Node->getOperand(2), DAG.getIntPtrConstant(1)); 12915 SDValue Ops[] = { Chain, In1, In2L, In2H }; 12916 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 12917 SDValue Result = 12918 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64, 12919 cast<MemSDNode>(Node)->getMemOperand()); 12920 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 12921 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 12922 Results.push_back(Result.getValue(2)); 12923 } 12924 12925 /// ReplaceNodeResults - Replace a node with an illegal result type 12926 /// with a new node built out of custom code. 12927 void X86TargetLowering::ReplaceNodeResults(SDNode *N, 12928 SmallVectorImpl<SDValue>&Results, 12929 SelectionDAG &DAG) const { 12930 SDLoc dl(N); 12931 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12932 switch (N->getOpcode()) { 12933 default: 12934 llvm_unreachable("Do not know how to custom type legalize this operation!"); 12935 case ISD::SIGN_EXTEND_INREG: 12936 case ISD::ADDC: 12937 case ISD::ADDE: 12938 case ISD::SUBC: 12939 case ISD::SUBE: 12940 // We don't want to expand or promote these. 12941 return; 12942 case ISD::FP_TO_SINT: 12943 case ISD::FP_TO_UINT: { 12944 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12945 12946 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType())) 12947 return; 12948 12949 std::pair<SDValue,SDValue> Vals = 12950 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true); 12951 SDValue FIST = Vals.first, StackSlot = Vals.second; 12952 if (FIST.getNode() != 0) { 12953 EVT VT = N->getValueType(0); 12954 // Return a load from the stack slot. 12955 if (StackSlot.getNode() != 0) 12956 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 12957 MachinePointerInfo(), 12958 false, false, false, 0)); 12959 else 12960 Results.push_back(FIST); 12961 } 12962 return; 12963 } 12964 case ISD::UINT_TO_FP: { 12965 assert(Subtarget->hasSSE2() && "Requires at least SSE2!"); 12966 if (N->getOperand(0).getValueType() != MVT::v2i32 || 12967 N->getValueType(0) != MVT::v2f32) 12968 return; 12969 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, 12970 N->getOperand(0)); 12971 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 12972 MVT::f64); 12973 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias); 12974 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn, 12975 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias)); 12976 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or); 12977 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias); 12978 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub)); 12979 return; 12980 } 12981 case ISD::FP_ROUND: { 12982 if (!TLI.isTypeLegal(N->getOperand(0).getValueType())) 12983 return; 12984 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0)); 12985 Results.push_back(V); 12986 return; 12987 } 12988 case ISD::READCYCLECOUNTER: { 12989 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12990 SDValue TheChain = N->getOperand(0); 12991 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 12992 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 12993 rd.getValue(1)); 12994 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 12995 eax.getValue(2)); 12996 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 12997 SDValue Ops[] = { eax, edx }; 12998 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 12999 array_lengthof(Ops))); 13000 Results.push_back(edx.getValue(1)); 13001 return; 13002 } 13003 case ISD::ATOMIC_CMP_SWAP: { 13004 EVT T = N->getValueType(0); 13005 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 13006 bool Regs64bit = T == MVT::i128; 13007 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 13008 SDValue cpInL, cpInH; 13009 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 13010 DAG.getConstant(0, HalfT)); 13011 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 13012 DAG.getConstant(1, HalfT)); 13013 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 13014 Regs64bit ? X86::RAX : X86::EAX, 13015 cpInL, SDValue()); 13016 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 13017 Regs64bit ? X86::RDX : X86::EDX, 13018 cpInH, cpInL.getValue(1)); 13019 SDValue swapInL, swapInH; 13020 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 13021 DAG.getConstant(0, HalfT)); 13022 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 13023 DAG.getConstant(1, HalfT)); 13024 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 13025 Regs64bit ? X86::RBX : X86::EBX, 13026 swapInL, cpInH.getValue(1)); 13027 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 13028 Regs64bit ? X86::RCX : X86::ECX, 13029 swapInH, swapInL.getValue(1)); 13030 SDValue Ops[] = { swapInH.getValue(0), 13031 N->getOperand(1), 13032 swapInH.getValue(1) }; 13033 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 13034 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 13035 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 13036 X86ISD::LCMPXCHG8_DAG; 13037 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 13038 Ops, array_lengthof(Ops), T, MMO); 13039 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 13040 Regs64bit ? X86::RAX : X86::EAX, 13041 HalfT, Result.getValue(1)); 13042 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 13043 Regs64bit ? X86::RDX : X86::EDX, 13044 HalfT, cpOutL.getValue(2)); 13045 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 13046 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 13047 Results.push_back(cpOutH.getValue(1)); 13048 return; 13049 } 13050 case ISD::ATOMIC_LOAD_ADD: 13051 case ISD::ATOMIC_LOAD_AND: 13052 case ISD::ATOMIC_LOAD_NAND: 13053 case ISD::ATOMIC_LOAD_OR: 13054 case ISD::ATOMIC_LOAD_SUB: 13055 case ISD::ATOMIC_LOAD_XOR: 13056 case ISD::ATOMIC_LOAD_MAX: 13057 case ISD::ATOMIC_LOAD_MIN: 13058 case ISD::ATOMIC_LOAD_UMAX: 13059 case ISD::ATOMIC_LOAD_UMIN: 13060 case ISD::ATOMIC_SWAP: { 13061 unsigned Opc; 13062 switch (N->getOpcode()) { 13063 default: llvm_unreachable("Unexpected opcode"); 13064 case ISD::ATOMIC_LOAD_ADD: 13065 Opc = X86ISD::ATOMADD64_DAG; 13066 break; 13067 case ISD::ATOMIC_LOAD_AND: 13068 Opc = X86ISD::ATOMAND64_DAG; 13069 break; 13070 case ISD::ATOMIC_LOAD_NAND: 13071 Opc = X86ISD::ATOMNAND64_DAG; 13072 break; 13073 case ISD::ATOMIC_LOAD_OR: 13074 Opc = X86ISD::ATOMOR64_DAG; 13075 break; 13076 case ISD::ATOMIC_LOAD_SUB: 13077 Opc = X86ISD::ATOMSUB64_DAG; 13078 break; 13079 case ISD::ATOMIC_LOAD_XOR: 13080 Opc = X86ISD::ATOMXOR64_DAG; 13081 break; 13082 case ISD::ATOMIC_LOAD_MAX: 13083 Opc = X86ISD::ATOMMAX64_DAG; 13084 break; 13085 case ISD::ATOMIC_LOAD_MIN: 13086 Opc = X86ISD::ATOMMIN64_DAG; 13087 break; 13088 case ISD::ATOMIC_LOAD_UMAX: 13089 Opc = X86ISD::ATOMUMAX64_DAG; 13090 break; 13091 case ISD::ATOMIC_LOAD_UMIN: 13092 Opc = X86ISD::ATOMUMIN64_DAG; 13093 break; 13094 case ISD::ATOMIC_SWAP: 13095 Opc = X86ISD::ATOMSWAP64_DAG; 13096 break; 13097 } 13098 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc); 13099 return; 13100 } 13101 case ISD::ATOMIC_LOAD: 13102 ReplaceATOMIC_LOAD(N, Results, DAG); 13103 } 13104 } 13105 13106 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 13107 switch (Opcode) { 13108 default: return NULL; 13109 case X86ISD::BSF: return "X86ISD::BSF"; 13110 case X86ISD::BSR: return "X86ISD::BSR"; 13111 case X86ISD::SHLD: return "X86ISD::SHLD"; 13112 case X86ISD::SHRD: return "X86ISD::SHRD"; 13113 case X86ISD::FAND: return "X86ISD::FAND"; 13114 case X86ISD::FANDN: return "X86ISD::FANDN"; 13115 case X86ISD::FOR: return "X86ISD::FOR"; 13116 case X86ISD::FXOR: return "X86ISD::FXOR"; 13117 case X86ISD::FSRL: return "X86ISD::FSRL"; 13118 case X86ISD::FILD: return "X86ISD::FILD"; 13119 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 13120 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 13121 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 13122 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 13123 case X86ISD::FLD: return "X86ISD::FLD"; 13124 case X86ISD::FST: return "X86ISD::FST"; 13125 case X86ISD::CALL: return "X86ISD::CALL"; 13126 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 13127 case X86ISD::BT: return "X86ISD::BT"; 13128 case X86ISD::CMP: return "X86ISD::CMP"; 13129 case X86ISD::COMI: return "X86ISD::COMI"; 13130 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 13131 case X86ISD::SETCC: return "X86ISD::SETCC"; 13132 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 13133 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 13134 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 13135 case X86ISD::CMOV: return "X86ISD::CMOV"; 13136 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 13137 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 13138 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 13139 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 13140 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 13141 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 13142 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 13143 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 13144 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 13145 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 13146 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 13147 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 13148 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 13149 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 13150 case X86ISD::PSIGN: return "X86ISD::PSIGN"; 13151 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 13152 case X86ISD::BLENDI: return "X86ISD::BLENDI"; 13153 case X86ISD::SUBUS: return "X86ISD::SUBUS"; 13154 case X86ISD::HADD: return "X86ISD::HADD"; 13155 case X86ISD::HSUB: return "X86ISD::HSUB"; 13156 case X86ISD::FHADD: return "X86ISD::FHADD"; 13157 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 13158 case X86ISD::UMAX: return "X86ISD::UMAX"; 13159 case X86ISD::UMIN: return "X86ISD::UMIN"; 13160 case X86ISD::SMAX: return "X86ISD::SMAX"; 13161 case X86ISD::SMIN: return "X86ISD::SMIN"; 13162 case X86ISD::FMAX: return "X86ISD::FMAX"; 13163 case X86ISD::FMIN: return "X86ISD::FMIN"; 13164 case X86ISD::FMAXC: return "X86ISD::FMAXC"; 13165 case X86ISD::FMINC: return "X86ISD::FMINC"; 13166 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 13167 case X86ISD::FRCP: return "X86ISD::FRCP"; 13168 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 13169 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR"; 13170 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 13171 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP"; 13172 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP"; 13173 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 13174 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 13175 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 13176 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r"; 13177 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 13178 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 13179 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 13180 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 13181 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 13182 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 13183 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 13184 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 13185 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 13186 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL"; 13187 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 13188 case X86ISD::VZEXT: return "X86ISD::VZEXT"; 13189 case X86ISD::VSEXT: return "X86ISD::VSEXT"; 13190 case X86ISD::VFPEXT: return "X86ISD::VFPEXT"; 13191 case X86ISD::VFPROUND: return "X86ISD::VFPROUND"; 13192 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ"; 13193 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ"; 13194 case X86ISD::VSHL: return "X86ISD::VSHL"; 13195 case X86ISD::VSRL: return "X86ISD::VSRL"; 13196 case X86ISD::VSRA: return "X86ISD::VSRA"; 13197 case X86ISD::VSHLI: return "X86ISD::VSHLI"; 13198 case X86ISD::VSRLI: return "X86ISD::VSRLI"; 13199 case X86ISD::VSRAI: return "X86ISD::VSRAI"; 13200 case X86ISD::CMPP: return "X86ISD::CMPP"; 13201 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ"; 13202 case X86ISD::PCMPGT: return "X86ISD::PCMPGT"; 13203 case X86ISD::ADD: return "X86ISD::ADD"; 13204 case X86ISD::SUB: return "X86ISD::SUB"; 13205 case X86ISD::ADC: return "X86ISD::ADC"; 13206 case X86ISD::SBB: return "X86ISD::SBB"; 13207 case X86ISD::SMUL: return "X86ISD::SMUL"; 13208 case X86ISD::UMUL: return "X86ISD::UMUL"; 13209 case X86ISD::INC: return "X86ISD::INC"; 13210 case X86ISD::DEC: return "X86ISD::DEC"; 13211 case X86ISD::OR: return "X86ISD::OR"; 13212 case X86ISD::XOR: return "X86ISD::XOR"; 13213 case X86ISD::AND: return "X86ISD::AND"; 13214 case X86ISD::BLSI: return "X86ISD::BLSI"; 13215 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 13216 case X86ISD::BLSR: return "X86ISD::BLSR"; 13217 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 13218 case X86ISD::PTEST: return "X86ISD::PTEST"; 13219 case X86ISD::TESTP: return "X86ISD::TESTP"; 13220 case X86ISD::PALIGNR: return "X86ISD::PALIGNR"; 13221 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 13222 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 13223 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 13224 case X86ISD::SHUFP: return "X86ISD::SHUFP"; 13225 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 13226 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 13227 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 13228 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 13229 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 13230 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 13231 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 13232 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 13233 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 13234 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 13235 case X86ISD::UNPCKL: return "X86ISD::UNPCKL"; 13236 case X86ISD::UNPCKH: return "X86ISD::UNPCKH"; 13237 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 13238 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM"; 13239 case X86ISD::VPERMILP: return "X86ISD::VPERMILP"; 13240 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128"; 13241 case X86ISD::VPERMV: return "X86ISD::VPERMV"; 13242 case X86ISD::VPERMI: return "X86ISD::VPERMI"; 13243 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ"; 13244 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 13245 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 13246 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 13247 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 13248 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 13249 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL"; 13250 case X86ISD::SAHF: return "X86ISD::SAHF"; 13251 case X86ISD::RDRAND: return "X86ISD::RDRAND"; 13252 case X86ISD::RDSEED: return "X86ISD::RDSEED"; 13253 case X86ISD::FMADD: return "X86ISD::FMADD"; 13254 case X86ISD::FMSUB: return "X86ISD::FMSUB"; 13255 case X86ISD::FNMADD: return "X86ISD::FNMADD"; 13256 case X86ISD::FNMSUB: return "X86ISD::FNMSUB"; 13257 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB"; 13258 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD"; 13259 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI"; 13260 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI"; 13261 case X86ISD::XTEST: return "X86ISD::XTEST"; 13262 } 13263 } 13264 13265 // isLegalAddressingMode - Return true if the addressing mode represented 13266 // by AM is legal for this target, for a load/store of the specified type. 13267 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 13268 Type *Ty) const { 13269 // X86 supports extremely general addressing modes. 13270 CodeModel::Model M = getTargetMachine().getCodeModel(); 13271 Reloc::Model R = getTargetMachine().getRelocationModel(); 13272 13273 // X86 allows a sign-extended 32-bit immediate field as a displacement. 13274 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 13275 return false; 13276 13277 if (AM.BaseGV) { 13278 unsigned GVFlags = 13279 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 13280 13281 // If a reference to this global requires an extra load, we can't fold it. 13282 if (isGlobalStubReference(GVFlags)) 13283 return false; 13284 13285 // If BaseGV requires a register for the PIC base, we cannot also have a 13286 // BaseReg specified. 13287 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 13288 return false; 13289 13290 // If lower 4G is not available, then we must use rip-relative addressing. 13291 if ((M != CodeModel::Small || R != Reloc::Static) && 13292 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 13293 return false; 13294 } 13295 13296 switch (AM.Scale) { 13297 case 0: 13298 case 1: 13299 case 2: 13300 case 4: 13301 case 8: 13302 // These scales always work. 13303 break; 13304 case 3: 13305 case 5: 13306 case 9: 13307 // These scales are formed with basereg+scalereg. Only accept if there is 13308 // no basereg yet. 13309 if (AM.HasBaseReg) 13310 return false; 13311 break; 13312 default: // Other stuff never works. 13313 return false; 13314 } 13315 13316 return true; 13317 } 13318 13319 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13320 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13321 return false; 13322 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13323 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13324 return NumBits1 > NumBits2; 13325 } 13326 13327 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const { 13328 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13329 return false; 13330 13331 if (!isTypeLegal(EVT::getEVT(Ty1))) 13332 return false; 13333 13334 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"); 13335 13336 // Assuming the caller doesn't have a zeroext or signext return parameter, 13337 // truncation all the way down to i1 is valid. 13338 return true; 13339 } 13340 13341 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13342 return isInt<32>(Imm); 13343 } 13344 13345 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const { 13346 // Can also use sub to handle negated immediates. 13347 return isInt<32>(Imm); 13348 } 13349 13350 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13351 if (!VT1.isInteger() || !VT2.isInteger()) 13352 return false; 13353 unsigned NumBits1 = VT1.getSizeInBits(); 13354 unsigned NumBits2 = VT2.getSizeInBits(); 13355 return NumBits1 > NumBits2; 13356 } 13357 13358 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 13359 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 13360 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 13361 } 13362 13363 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 13364 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 13365 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 13366 } 13367 13368 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13369 EVT VT1 = Val.getValueType(); 13370 if (isZExtFree(VT1, VT2)) 13371 return true; 13372 13373 if (Val.getOpcode() != ISD::LOAD) 13374 return false; 13375 13376 if (!VT1.isSimple() || !VT1.isInteger() || 13377 !VT2.isSimple() || !VT2.isInteger()) 13378 return false; 13379 13380 switch (VT1.getSimpleVT().SimpleTy) { 13381 default: break; 13382 case MVT::i8: 13383 case MVT::i16: 13384 case MVT::i32: 13385 // X86 has 8, 16, and 32-bit zero-extending loads. 13386 return true; 13387 } 13388 13389 return false; 13390 } 13391 13392 bool 13393 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13394 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4())) 13395 return false; 13396 13397 VT = VT.getScalarType(); 13398 13399 if (!VT.isSimple()) 13400 return false; 13401 13402 switch (VT.getSimpleVT().SimpleTy) { 13403 case MVT::f32: 13404 case MVT::f64: 13405 return true; 13406 default: 13407 break; 13408 } 13409 13410 return false; 13411 } 13412 13413 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 13414 // i16 instructions are longer (0x66 prefix) and potentially slower. 13415 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 13416 } 13417 13418 /// isShuffleMaskLegal - Targets can use this to indicate that they only 13419 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 13420 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 13421 /// are assumed to be legal. 13422 bool 13423 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 13424 EVT VT) const { 13425 // Very little shuffling can be done for 64-bit vectors right now. 13426 if (VT.getSizeInBits() == 64) 13427 return false; 13428 13429 // FIXME: pshufb, blends, shifts. 13430 return (VT.getVectorNumElements() == 2 || 13431 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 13432 isMOVLMask(M, VT) || 13433 isSHUFPMask(M, VT, Subtarget->hasFp256()) || 13434 isPSHUFDMask(M, VT) || 13435 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) || 13436 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) || 13437 isPALIGNRMask(M, VT, Subtarget) || 13438 isUNPCKLMask(M, VT, Subtarget->hasInt256()) || 13439 isUNPCKHMask(M, VT, Subtarget->hasInt256()) || 13440 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) || 13441 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256())); 13442 } 13443 13444 bool 13445 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 13446 EVT VT) const { 13447 unsigned NumElts = VT.getVectorNumElements(); 13448 // FIXME: This collection of masks seems suspect. 13449 if (NumElts == 2) 13450 return true; 13451 if (NumElts == 4 && VT.is128BitVector()) { 13452 return (isMOVLMask(Mask, VT) || 13453 isCommutedMOVLMask(Mask, VT, true) || 13454 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) || 13455 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true)); 13456 } 13457 return false; 13458 } 13459 13460 //===----------------------------------------------------------------------===// 13461 // X86 Scheduler Hooks 13462 //===----------------------------------------------------------------------===// 13463 13464 /// Utility function to emit xbegin specifying the start of an RTM region. 13465 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB, 13466 const TargetInstrInfo *TII) { 13467 DebugLoc DL = MI->getDebugLoc(); 13468 13469 const BasicBlock *BB = MBB->getBasicBlock(); 13470 MachineFunction::iterator I = MBB; 13471 ++I; 13472 13473 // For the v = xbegin(), we generate 13474 // 13475 // thisMBB: 13476 // xbegin sinkMBB 13477 // 13478 // mainMBB: 13479 // eax = -1 13480 // 13481 // sinkMBB: 13482 // v = eax 13483 13484 MachineBasicBlock *thisMBB = MBB; 13485 MachineFunction *MF = MBB->getParent(); 13486 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13487 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13488 MF->insert(I, mainMBB); 13489 MF->insert(I, sinkMBB); 13490 13491 // Transfer the remainder of BB and its successor edges to sinkMBB. 13492 sinkMBB->splice(sinkMBB->begin(), MBB, 13493 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13494 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13495 13496 // thisMBB: 13497 // xbegin sinkMBB 13498 // # fallthrough to mainMBB 13499 // # abortion to sinkMBB 13500 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB); 13501 thisMBB->addSuccessor(mainMBB); 13502 thisMBB->addSuccessor(sinkMBB); 13503 13504 // mainMBB: 13505 // EAX = -1 13506 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1); 13507 mainMBB->addSuccessor(sinkMBB); 13508 13509 // sinkMBB: 13510 // EAX is live into the sinkMBB 13511 sinkMBB->addLiveIn(X86::EAX); 13512 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13513 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13514 .addReg(X86::EAX); 13515 13516 MI->eraseFromParent(); 13517 return sinkMBB; 13518 } 13519 13520 // Get CMPXCHG opcode for the specified data type. 13521 static unsigned getCmpXChgOpcode(EVT VT) { 13522 switch (VT.getSimpleVT().SimpleTy) { 13523 case MVT::i8: return X86::LCMPXCHG8; 13524 case MVT::i16: return X86::LCMPXCHG16; 13525 case MVT::i32: return X86::LCMPXCHG32; 13526 case MVT::i64: return X86::LCMPXCHG64; 13527 default: 13528 break; 13529 } 13530 llvm_unreachable("Invalid operand size!"); 13531 } 13532 13533 // Get LOAD opcode for the specified data type. 13534 static unsigned getLoadOpcode(EVT VT) { 13535 switch (VT.getSimpleVT().SimpleTy) { 13536 case MVT::i8: return X86::MOV8rm; 13537 case MVT::i16: return X86::MOV16rm; 13538 case MVT::i32: return X86::MOV32rm; 13539 case MVT::i64: return X86::MOV64rm; 13540 default: 13541 break; 13542 } 13543 llvm_unreachable("Invalid operand size!"); 13544 } 13545 13546 // Get opcode of the non-atomic one from the specified atomic instruction. 13547 static unsigned getNonAtomicOpcode(unsigned Opc) { 13548 switch (Opc) { 13549 case X86::ATOMAND8: return X86::AND8rr; 13550 case X86::ATOMAND16: return X86::AND16rr; 13551 case X86::ATOMAND32: return X86::AND32rr; 13552 case X86::ATOMAND64: return X86::AND64rr; 13553 case X86::ATOMOR8: return X86::OR8rr; 13554 case X86::ATOMOR16: return X86::OR16rr; 13555 case X86::ATOMOR32: return X86::OR32rr; 13556 case X86::ATOMOR64: return X86::OR64rr; 13557 case X86::ATOMXOR8: return X86::XOR8rr; 13558 case X86::ATOMXOR16: return X86::XOR16rr; 13559 case X86::ATOMXOR32: return X86::XOR32rr; 13560 case X86::ATOMXOR64: return X86::XOR64rr; 13561 } 13562 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13563 } 13564 13565 // Get opcode of the non-atomic one from the specified atomic instruction with 13566 // extra opcode. 13567 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc, 13568 unsigned &ExtraOpc) { 13569 switch (Opc) { 13570 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr; 13571 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr; 13572 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr; 13573 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr; 13574 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr; 13575 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr; 13576 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr; 13577 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr; 13578 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr; 13579 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr; 13580 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr; 13581 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr; 13582 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr; 13583 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr; 13584 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr; 13585 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr; 13586 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr; 13587 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr; 13588 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr; 13589 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr; 13590 } 13591 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13592 } 13593 13594 // Get opcode of the non-atomic one from the specified atomic instruction for 13595 // 64-bit data type on 32-bit target. 13596 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) { 13597 switch (Opc) { 13598 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr; 13599 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr; 13600 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr; 13601 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr; 13602 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr; 13603 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr; 13604 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr; 13605 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr; 13606 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr; 13607 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr; 13608 } 13609 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13610 } 13611 13612 // Get opcode of the non-atomic one from the specified atomic instruction for 13613 // 64-bit data type on 32-bit target with extra opcode. 13614 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc, 13615 unsigned &HiOpc, 13616 unsigned &ExtraOpc) { 13617 switch (Opc) { 13618 case X86::ATOMNAND6432: 13619 ExtraOpc = X86::NOT32r; 13620 HiOpc = X86::AND32rr; 13621 return X86::AND32rr; 13622 } 13623 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13624 } 13625 13626 // Get pseudo CMOV opcode from the specified data type. 13627 static unsigned getPseudoCMOVOpc(EVT VT) { 13628 switch (VT.getSimpleVT().SimpleTy) { 13629 case MVT::i8: return X86::CMOV_GR8; 13630 case MVT::i16: return X86::CMOV_GR16; 13631 case MVT::i32: return X86::CMOV_GR32; 13632 default: 13633 break; 13634 } 13635 llvm_unreachable("Unknown CMOV opcode!"); 13636 } 13637 13638 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions. 13639 // They will be translated into a spin-loop or compare-exchange loop from 13640 // 13641 // ... 13642 // dst = atomic-fetch-op MI.addr, MI.val 13643 // ... 13644 // 13645 // to 13646 // 13647 // ... 13648 // t1 = LOAD MI.addr 13649 // loop: 13650 // t4 = phi(t1, t3 / loop) 13651 // t2 = OP MI.val, t4 13652 // EAX = t4 13653 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined] 13654 // t3 = EAX 13655 // JNE loop 13656 // sink: 13657 // dst = t3 13658 // ... 13659 MachineBasicBlock * 13660 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI, 13661 MachineBasicBlock *MBB) const { 13662 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13663 DebugLoc DL = MI->getDebugLoc(); 13664 13665 MachineFunction *MF = MBB->getParent(); 13666 MachineRegisterInfo &MRI = MF->getRegInfo(); 13667 13668 const BasicBlock *BB = MBB->getBasicBlock(); 13669 MachineFunction::iterator I = MBB; 13670 ++I; 13671 13672 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 && 13673 "Unexpected number of operands"); 13674 13675 assert(MI->hasOneMemOperand() && 13676 "Expected atomic-load-op to have one memoperand"); 13677 13678 // Memory Reference 13679 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13680 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13681 13682 unsigned DstReg, SrcReg; 13683 unsigned MemOpndSlot; 13684 13685 unsigned CurOp = 0; 13686 13687 DstReg = MI->getOperand(CurOp++).getReg(); 13688 MemOpndSlot = CurOp; 13689 CurOp += X86::AddrNumOperands; 13690 SrcReg = MI->getOperand(CurOp++).getReg(); 13691 13692 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 13693 MVT::SimpleValueType VT = *RC->vt_begin(); 13694 unsigned t1 = MRI.createVirtualRegister(RC); 13695 unsigned t2 = MRI.createVirtualRegister(RC); 13696 unsigned t3 = MRI.createVirtualRegister(RC); 13697 unsigned t4 = MRI.createVirtualRegister(RC); 13698 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT); 13699 13700 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT); 13701 unsigned LOADOpc = getLoadOpcode(VT); 13702 13703 // For the atomic load-arith operator, we generate 13704 // 13705 // thisMBB: 13706 // t1 = LOAD [MI.addr] 13707 // mainMBB: 13708 // t4 = phi(t1 / thisMBB, t3 / mainMBB) 13709 // t1 = OP MI.val, EAX 13710 // EAX = t4 13711 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined] 13712 // t3 = EAX 13713 // JNE mainMBB 13714 // sinkMBB: 13715 // dst = t3 13716 13717 MachineBasicBlock *thisMBB = MBB; 13718 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13719 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13720 MF->insert(I, mainMBB); 13721 MF->insert(I, sinkMBB); 13722 13723 MachineInstrBuilder MIB; 13724 13725 // Transfer the remainder of BB and its successor edges to sinkMBB. 13726 sinkMBB->splice(sinkMBB->begin(), MBB, 13727 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13728 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13729 13730 // thisMBB: 13731 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1); 13732 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13733 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13734 if (NewMO.isReg()) 13735 NewMO.setIsKill(false); 13736 MIB.addOperand(NewMO); 13737 } 13738 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) { 13739 unsigned flags = (*MMOI)->getFlags(); 13740 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad; 13741 MachineMemOperand *MMO = 13742 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags, 13743 (*MMOI)->getSize(), 13744 (*MMOI)->getBaseAlignment(), 13745 (*MMOI)->getTBAAInfo(), 13746 (*MMOI)->getRanges()); 13747 MIB.addMemOperand(MMO); 13748 } 13749 13750 thisMBB->addSuccessor(mainMBB); 13751 13752 // mainMBB: 13753 MachineBasicBlock *origMainMBB = mainMBB; 13754 13755 // Add a PHI. 13756 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4) 13757 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB); 13758 13759 unsigned Opc = MI->getOpcode(); 13760 switch (Opc) { 13761 default: 13762 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13763 case X86::ATOMAND8: 13764 case X86::ATOMAND16: 13765 case X86::ATOMAND32: 13766 case X86::ATOMAND64: 13767 case X86::ATOMOR8: 13768 case X86::ATOMOR16: 13769 case X86::ATOMOR32: 13770 case X86::ATOMOR64: 13771 case X86::ATOMXOR8: 13772 case X86::ATOMXOR16: 13773 case X86::ATOMXOR32: 13774 case X86::ATOMXOR64: { 13775 unsigned ARITHOpc = getNonAtomicOpcode(Opc); 13776 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg) 13777 .addReg(t4); 13778 break; 13779 } 13780 case X86::ATOMNAND8: 13781 case X86::ATOMNAND16: 13782 case X86::ATOMNAND32: 13783 case X86::ATOMNAND64: { 13784 unsigned Tmp = MRI.createVirtualRegister(RC); 13785 unsigned NOTOpc; 13786 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc); 13787 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg) 13788 .addReg(t4); 13789 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp); 13790 break; 13791 } 13792 case X86::ATOMMAX8: 13793 case X86::ATOMMAX16: 13794 case X86::ATOMMAX32: 13795 case X86::ATOMMAX64: 13796 case X86::ATOMMIN8: 13797 case X86::ATOMMIN16: 13798 case X86::ATOMMIN32: 13799 case X86::ATOMMIN64: 13800 case X86::ATOMUMAX8: 13801 case X86::ATOMUMAX16: 13802 case X86::ATOMUMAX32: 13803 case X86::ATOMUMAX64: 13804 case X86::ATOMUMIN8: 13805 case X86::ATOMUMIN16: 13806 case X86::ATOMUMIN32: 13807 case X86::ATOMUMIN64: { 13808 unsigned CMPOpc; 13809 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc); 13810 13811 BuildMI(mainMBB, DL, TII->get(CMPOpc)) 13812 .addReg(SrcReg) 13813 .addReg(t4); 13814 13815 if (Subtarget->hasCMov()) { 13816 if (VT != MVT::i8) { 13817 // Native support 13818 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2) 13819 .addReg(SrcReg) 13820 .addReg(t4); 13821 } else { 13822 // Promote i8 to i32 to use CMOV32 13823 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 13824 const TargetRegisterClass *RC32 = 13825 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit); 13826 unsigned SrcReg32 = MRI.createVirtualRegister(RC32); 13827 unsigned AccReg32 = MRI.createVirtualRegister(RC32); 13828 unsigned Tmp = MRI.createVirtualRegister(RC32); 13829 13830 unsigned Undef = MRI.createVirtualRegister(RC32); 13831 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef); 13832 13833 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32) 13834 .addReg(Undef) 13835 .addReg(SrcReg) 13836 .addImm(X86::sub_8bit); 13837 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32) 13838 .addReg(Undef) 13839 .addReg(t4) 13840 .addImm(X86::sub_8bit); 13841 13842 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp) 13843 .addReg(SrcReg32) 13844 .addReg(AccReg32); 13845 13846 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2) 13847 .addReg(Tmp, 0, X86::sub_8bit); 13848 } 13849 } else { 13850 // Use pseudo select and lower them. 13851 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 13852 "Invalid atomic-load-op transformation!"); 13853 unsigned SelOpc = getPseudoCMOVOpc(VT); 13854 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc); 13855 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!"); 13856 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2) 13857 .addReg(SrcReg).addReg(t4) 13858 .addImm(CC); 13859 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13860 // Replace the original PHI node as mainMBB is changed after CMOV 13861 // lowering. 13862 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4) 13863 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB); 13864 Phi->eraseFromParent(); 13865 } 13866 break; 13867 } 13868 } 13869 13870 // Copy PhyReg back from virtual register. 13871 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg) 13872 .addReg(t4); 13873 13874 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 13875 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13876 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13877 if (NewMO.isReg()) 13878 NewMO.setIsKill(false); 13879 MIB.addOperand(NewMO); 13880 } 13881 MIB.addReg(t2); 13882 MIB.setMemRefs(MMOBegin, MMOEnd); 13883 13884 // Copy PhyReg back to virtual register. 13885 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3) 13886 .addReg(PhyReg); 13887 13888 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 13889 13890 mainMBB->addSuccessor(origMainMBB); 13891 mainMBB->addSuccessor(sinkMBB); 13892 13893 // sinkMBB: 13894 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13895 TII->get(TargetOpcode::COPY), DstReg) 13896 .addReg(t3); 13897 13898 MI->eraseFromParent(); 13899 return sinkMBB; 13900 } 13901 13902 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic 13903 // instructions. They will be translated into a spin-loop or compare-exchange 13904 // loop from 13905 // 13906 // ... 13907 // dst = atomic-fetch-op MI.addr, MI.val 13908 // ... 13909 // 13910 // to 13911 // 13912 // ... 13913 // t1L = LOAD [MI.addr + 0] 13914 // t1H = LOAD [MI.addr + 4] 13915 // loop: 13916 // t4L = phi(t1L, t3L / loop) 13917 // t4H = phi(t1H, t3H / loop) 13918 // t2L = OP MI.val.lo, t4L 13919 // t2H = OP MI.val.hi, t4H 13920 // EAX = t4L 13921 // EDX = t4H 13922 // EBX = t2L 13923 // ECX = t2H 13924 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13925 // t3L = EAX 13926 // t3H = EDX 13927 // JNE loop 13928 // sink: 13929 // dstL = t3L 13930 // dstH = t3H 13931 // ... 13932 MachineBasicBlock * 13933 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI, 13934 MachineBasicBlock *MBB) const { 13935 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13936 DebugLoc DL = MI->getDebugLoc(); 13937 13938 MachineFunction *MF = MBB->getParent(); 13939 MachineRegisterInfo &MRI = MF->getRegInfo(); 13940 13941 const BasicBlock *BB = MBB->getBasicBlock(); 13942 MachineFunction::iterator I = MBB; 13943 ++I; 13944 13945 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 && 13946 "Unexpected number of operands"); 13947 13948 assert(MI->hasOneMemOperand() && 13949 "Expected atomic-load-op32 to have one memoperand"); 13950 13951 // Memory Reference 13952 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13953 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13954 13955 unsigned DstLoReg, DstHiReg; 13956 unsigned SrcLoReg, SrcHiReg; 13957 unsigned MemOpndSlot; 13958 13959 unsigned CurOp = 0; 13960 13961 DstLoReg = MI->getOperand(CurOp++).getReg(); 13962 DstHiReg = MI->getOperand(CurOp++).getReg(); 13963 MemOpndSlot = CurOp; 13964 CurOp += X86::AddrNumOperands; 13965 SrcLoReg = MI->getOperand(CurOp++).getReg(); 13966 SrcHiReg = MI->getOperand(CurOp++).getReg(); 13967 13968 const TargetRegisterClass *RC = &X86::GR32RegClass; 13969 const TargetRegisterClass *RC8 = &X86::GR8RegClass; 13970 13971 unsigned t1L = MRI.createVirtualRegister(RC); 13972 unsigned t1H = MRI.createVirtualRegister(RC); 13973 unsigned t2L = MRI.createVirtualRegister(RC); 13974 unsigned t2H = MRI.createVirtualRegister(RC); 13975 unsigned t3L = MRI.createVirtualRegister(RC); 13976 unsigned t3H = MRI.createVirtualRegister(RC); 13977 unsigned t4L = MRI.createVirtualRegister(RC); 13978 unsigned t4H = MRI.createVirtualRegister(RC); 13979 13980 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B; 13981 unsigned LOADOpc = X86::MOV32rm; 13982 13983 // For the atomic load-arith operator, we generate 13984 // 13985 // thisMBB: 13986 // t1L = LOAD [MI.addr + 0] 13987 // t1H = LOAD [MI.addr + 4] 13988 // mainMBB: 13989 // t4L = phi(t1L / thisMBB, t3L / mainMBB) 13990 // t4H = phi(t1H / thisMBB, t3H / mainMBB) 13991 // t2L = OP MI.val.lo, t4L 13992 // t2H = OP MI.val.hi, t4H 13993 // EBX = t2L 13994 // ECX = t2H 13995 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13996 // t3L = EAX 13997 // t3H = EDX 13998 // JNE loop 13999 // sinkMBB: 14000 // dstL = t3L 14001 // dstH = t3H 14002 14003 MachineBasicBlock *thisMBB = MBB; 14004 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 14005 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 14006 MF->insert(I, mainMBB); 14007 MF->insert(I, sinkMBB); 14008 14009 MachineInstrBuilder MIB; 14010 14011 // Transfer the remainder of BB and its successor edges to sinkMBB. 14012 sinkMBB->splice(sinkMBB->begin(), MBB, 14013 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 14014 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 14015 14016 // thisMBB: 14017 // Lo 14018 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L); 14019 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14020 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 14021 if (NewMO.isReg()) 14022 NewMO.setIsKill(false); 14023 MIB.addOperand(NewMO); 14024 } 14025 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) { 14026 unsigned flags = (*MMOI)->getFlags(); 14027 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad; 14028 MachineMemOperand *MMO = 14029 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags, 14030 (*MMOI)->getSize(), 14031 (*MMOI)->getBaseAlignment(), 14032 (*MMOI)->getTBAAInfo(), 14033 (*MMOI)->getRanges()); 14034 MIB.addMemOperand(MMO); 14035 }; 14036 MachineInstr *LowMI = MIB; 14037 14038 // Hi 14039 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H); 14040 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14041 if (i == X86::AddrDisp) { 14042 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32) 14043 } else { 14044 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 14045 if (NewMO.isReg()) 14046 NewMO.setIsKill(false); 14047 MIB.addOperand(NewMO); 14048 } 14049 } 14050 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end()); 14051 14052 thisMBB->addSuccessor(mainMBB); 14053 14054 // mainMBB: 14055 MachineBasicBlock *origMainMBB = mainMBB; 14056 14057 // Add PHIs. 14058 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L) 14059 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB); 14060 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H) 14061 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB); 14062 14063 unsigned Opc = MI->getOpcode(); 14064 switch (Opc) { 14065 default: 14066 llvm_unreachable("Unhandled atomic-load-op6432 opcode!"); 14067 case X86::ATOMAND6432: 14068 case X86::ATOMOR6432: 14069 case X86::ATOMXOR6432: 14070 case X86::ATOMADD6432: 14071 case X86::ATOMSUB6432: { 14072 unsigned HiOpc; 14073 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 14074 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L) 14075 .addReg(SrcLoReg); 14076 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H) 14077 .addReg(SrcHiReg); 14078 break; 14079 } 14080 case X86::ATOMNAND6432: { 14081 unsigned HiOpc, NOTOpc; 14082 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc); 14083 unsigned TmpL = MRI.createVirtualRegister(RC); 14084 unsigned TmpH = MRI.createVirtualRegister(RC); 14085 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg) 14086 .addReg(t4L); 14087 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg) 14088 .addReg(t4H); 14089 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL); 14090 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH); 14091 break; 14092 } 14093 case X86::ATOMMAX6432: 14094 case X86::ATOMMIN6432: 14095 case X86::ATOMUMAX6432: 14096 case X86::ATOMUMIN6432: { 14097 unsigned HiOpc; 14098 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 14099 unsigned cL = MRI.createVirtualRegister(RC8); 14100 unsigned cH = MRI.createVirtualRegister(RC8); 14101 unsigned cL32 = MRI.createVirtualRegister(RC); 14102 unsigned cH32 = MRI.createVirtualRegister(RC); 14103 unsigned cc = MRI.createVirtualRegister(RC); 14104 // cl := cmp src_lo, lo 14105 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 14106 .addReg(SrcLoReg).addReg(t4L); 14107 BuildMI(mainMBB, DL, TII->get(LoOpc), cL); 14108 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL); 14109 // ch := cmp src_hi, hi 14110 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 14111 .addReg(SrcHiReg).addReg(t4H); 14112 BuildMI(mainMBB, DL, TII->get(HiOpc), cH); 14113 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH); 14114 // cc := if (src_hi == hi) ? cl : ch; 14115 if (Subtarget->hasCMov()) { 14116 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc) 14117 .addReg(cH32).addReg(cL32); 14118 } else { 14119 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc) 14120 .addReg(cH32).addReg(cL32) 14121 .addImm(X86::COND_E); 14122 mainMBB = EmitLoweredSelect(MIB, mainMBB); 14123 } 14124 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc); 14125 if (Subtarget->hasCMov()) { 14126 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L) 14127 .addReg(SrcLoReg).addReg(t4L); 14128 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H) 14129 .addReg(SrcHiReg).addReg(t4H); 14130 } else { 14131 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L) 14132 .addReg(SrcLoReg).addReg(t4L) 14133 .addImm(X86::COND_NE); 14134 mainMBB = EmitLoweredSelect(MIB, mainMBB); 14135 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the 14136 // 2nd CMOV lowering. 14137 mainMBB->addLiveIn(X86::EFLAGS); 14138 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H) 14139 .addReg(SrcHiReg).addReg(t4H) 14140 .addImm(X86::COND_NE); 14141 mainMBB = EmitLoweredSelect(MIB, mainMBB); 14142 // Replace the original PHI node as mainMBB is changed after CMOV 14143 // lowering. 14144 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L) 14145 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB); 14146 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H) 14147 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB); 14148 PhiL->eraseFromParent(); 14149 PhiH->eraseFromParent(); 14150 } 14151 break; 14152 } 14153 case X86::ATOMSWAP6432: { 14154 unsigned HiOpc; 14155 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 14156 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg); 14157 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg); 14158 break; 14159 } 14160 } 14161 14162 // Copy EDX:EAX back from HiReg:LoReg 14163 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L); 14164 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H); 14165 // Copy ECX:EBX from t1H:t1L 14166 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L); 14167 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H); 14168 14169 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 14170 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14171 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 14172 if (NewMO.isReg()) 14173 NewMO.setIsKill(false); 14174 MIB.addOperand(NewMO); 14175 } 14176 MIB.setMemRefs(MMOBegin, MMOEnd); 14177 14178 // Copy EDX:EAX back to t3H:t3L 14179 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX); 14180 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX); 14181 14182 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 14183 14184 mainMBB->addSuccessor(origMainMBB); 14185 mainMBB->addSuccessor(sinkMBB); 14186 14187 // sinkMBB: 14188 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14189 TII->get(TargetOpcode::COPY), DstLoReg) 14190 .addReg(t3L); 14191 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14192 TII->get(TargetOpcode::COPY), DstHiReg) 14193 .addReg(t3H); 14194 14195 MI->eraseFromParent(); 14196 return sinkMBB; 14197 } 14198 14199 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 14200 // or XMM0_V32I8 in AVX all of this code can be replaced with that 14201 // in the .td file. 14202 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB, 14203 const TargetInstrInfo *TII) { 14204 unsigned Opc; 14205 switch (MI->getOpcode()) { 14206 default: llvm_unreachable("illegal opcode!"); 14207 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break; 14208 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break; 14209 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break; 14210 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break; 14211 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break; 14212 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break; 14213 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break; 14214 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break; 14215 } 14216 14217 DebugLoc dl = MI->getDebugLoc(); 14218 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 14219 14220 unsigned NumArgs = MI->getNumOperands(); 14221 for (unsigned i = 1; i < NumArgs; ++i) { 14222 MachineOperand &Op = MI->getOperand(i); 14223 if (!(Op.isReg() && Op.isImplicit())) 14224 MIB.addOperand(Op); 14225 } 14226 if (MI->hasOneMemOperand()) 14227 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 14228 14229 BuildMI(*BB, MI, dl, 14230 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 14231 .addReg(X86::XMM0); 14232 14233 MI->eraseFromParent(); 14234 return BB; 14235 } 14236 14237 // FIXME: Custom handling because TableGen doesn't support multiple implicit 14238 // defs in an instruction pattern 14239 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB, 14240 const TargetInstrInfo *TII) { 14241 unsigned Opc; 14242 switch (MI->getOpcode()) { 14243 default: llvm_unreachable("illegal opcode!"); 14244 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break; 14245 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break; 14246 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break; 14247 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break; 14248 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break; 14249 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break; 14250 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break; 14251 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break; 14252 } 14253 14254 DebugLoc dl = MI->getDebugLoc(); 14255 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 14256 14257 unsigned NumArgs = MI->getNumOperands(); // remove the results 14258 for (unsigned i = 1; i < NumArgs; ++i) { 14259 MachineOperand &Op = MI->getOperand(i); 14260 if (!(Op.isReg() && Op.isImplicit())) 14261 MIB.addOperand(Op); 14262 } 14263 if (MI->hasOneMemOperand()) 14264 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 14265 14266 BuildMI(*BB, MI, dl, 14267 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 14268 .addReg(X86::ECX); 14269 14270 MI->eraseFromParent(); 14271 return BB; 14272 } 14273 14274 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB, 14275 const TargetInstrInfo *TII, 14276 const X86Subtarget* Subtarget) { 14277 DebugLoc dl = MI->getDebugLoc(); 14278 14279 // Address into RAX/EAX, other two args into ECX, EDX. 14280 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 14281 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 14282 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 14283 for (int i = 0; i < X86::AddrNumOperands; ++i) 14284 MIB.addOperand(MI->getOperand(i)); 14285 14286 unsigned ValOps = X86::AddrNumOperands; 14287 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 14288 .addReg(MI->getOperand(ValOps).getReg()); 14289 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 14290 .addReg(MI->getOperand(ValOps+1).getReg()); 14291 14292 // The instruction doesn't actually take any operands though. 14293 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 14294 14295 MI->eraseFromParent(); // The pseudo is gone now. 14296 return BB; 14297 } 14298 14299 MachineBasicBlock * 14300 X86TargetLowering::EmitVAARG64WithCustomInserter( 14301 MachineInstr *MI, 14302 MachineBasicBlock *MBB) const { 14303 // Emit va_arg instruction on X86-64. 14304 14305 // Operands to this pseudo-instruction: 14306 // 0 ) Output : destination address (reg) 14307 // 1-5) Input : va_list address (addr, i64mem) 14308 // 6 ) ArgSize : Size (in bytes) of vararg type 14309 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 14310 // 8 ) Align : Alignment of type 14311 // 9 ) EFLAGS (implicit-def) 14312 14313 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 14314 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 14315 14316 unsigned DestReg = MI->getOperand(0).getReg(); 14317 MachineOperand &Base = MI->getOperand(1); 14318 MachineOperand &Scale = MI->getOperand(2); 14319 MachineOperand &Index = MI->getOperand(3); 14320 MachineOperand &Disp = MI->getOperand(4); 14321 MachineOperand &Segment = MI->getOperand(5); 14322 unsigned ArgSize = MI->getOperand(6).getImm(); 14323 unsigned ArgMode = MI->getOperand(7).getImm(); 14324 unsigned Align = MI->getOperand(8).getImm(); 14325 14326 // Memory Reference 14327 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 14328 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14329 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14330 14331 // Machine Information 14332 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14333 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 14334 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 14335 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 14336 DebugLoc DL = MI->getDebugLoc(); 14337 14338 // struct va_list { 14339 // i32 gp_offset 14340 // i32 fp_offset 14341 // i64 overflow_area (address) 14342 // i64 reg_save_area (address) 14343 // } 14344 // sizeof(va_list) = 24 14345 // alignment(va_list) = 8 14346 14347 unsigned TotalNumIntRegs = 6; 14348 unsigned TotalNumXMMRegs = 8; 14349 bool UseGPOffset = (ArgMode == 1); 14350 bool UseFPOffset = (ArgMode == 2); 14351 unsigned MaxOffset = TotalNumIntRegs * 8 + 14352 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 14353 14354 /* Align ArgSize to a multiple of 8 */ 14355 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 14356 bool NeedsAlign = (Align > 8); 14357 14358 MachineBasicBlock *thisMBB = MBB; 14359 MachineBasicBlock *overflowMBB; 14360 MachineBasicBlock *offsetMBB; 14361 MachineBasicBlock *endMBB; 14362 14363 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 14364 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 14365 unsigned OffsetReg = 0; 14366 14367 if (!UseGPOffset && !UseFPOffset) { 14368 // If we only pull from the overflow region, we don't create a branch. 14369 // We don't need to alter control flow. 14370 OffsetDestReg = 0; // unused 14371 OverflowDestReg = DestReg; 14372 14373 offsetMBB = NULL; 14374 overflowMBB = thisMBB; 14375 endMBB = thisMBB; 14376 } else { 14377 // First emit code to check if gp_offset (or fp_offset) is below the bound. 14378 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 14379 // If not, pull from overflow_area. (branch to overflowMBB) 14380 // 14381 // thisMBB 14382 // | . 14383 // | . 14384 // offsetMBB overflowMBB 14385 // | . 14386 // | . 14387 // endMBB 14388 14389 // Registers for the PHI in endMBB 14390 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 14391 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 14392 14393 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 14394 MachineFunction *MF = MBB->getParent(); 14395 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14396 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14397 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14398 14399 MachineFunction::iterator MBBIter = MBB; 14400 ++MBBIter; 14401 14402 // Insert the new basic blocks 14403 MF->insert(MBBIter, offsetMBB); 14404 MF->insert(MBBIter, overflowMBB); 14405 MF->insert(MBBIter, endMBB); 14406 14407 // Transfer the remainder of MBB and its successor edges to endMBB. 14408 endMBB->splice(endMBB->begin(), thisMBB, 14409 llvm::next(MachineBasicBlock::iterator(MI)), 14410 thisMBB->end()); 14411 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 14412 14413 // Make offsetMBB and overflowMBB successors of thisMBB 14414 thisMBB->addSuccessor(offsetMBB); 14415 thisMBB->addSuccessor(overflowMBB); 14416 14417 // endMBB is a successor of both offsetMBB and overflowMBB 14418 offsetMBB->addSuccessor(endMBB); 14419 overflowMBB->addSuccessor(endMBB); 14420 14421 // Load the offset value into a register 14422 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 14423 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 14424 .addOperand(Base) 14425 .addOperand(Scale) 14426 .addOperand(Index) 14427 .addDisp(Disp, UseFPOffset ? 4 : 0) 14428 .addOperand(Segment) 14429 .setMemRefs(MMOBegin, MMOEnd); 14430 14431 // Check if there is enough room left to pull this argument. 14432 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 14433 .addReg(OffsetReg) 14434 .addImm(MaxOffset + 8 - ArgSizeA8); 14435 14436 // Branch to "overflowMBB" if offset >= max 14437 // Fall through to "offsetMBB" otherwise 14438 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 14439 .addMBB(overflowMBB); 14440 } 14441 14442 // In offsetMBB, emit code to use the reg_save_area. 14443 if (offsetMBB) { 14444 assert(OffsetReg != 0); 14445 14446 // Read the reg_save_area address. 14447 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 14448 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 14449 .addOperand(Base) 14450 .addOperand(Scale) 14451 .addOperand(Index) 14452 .addDisp(Disp, 16) 14453 .addOperand(Segment) 14454 .setMemRefs(MMOBegin, MMOEnd); 14455 14456 // Zero-extend the offset 14457 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 14458 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 14459 .addImm(0) 14460 .addReg(OffsetReg) 14461 .addImm(X86::sub_32bit); 14462 14463 // Add the offset to the reg_save_area to get the final address. 14464 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 14465 .addReg(OffsetReg64) 14466 .addReg(RegSaveReg); 14467 14468 // Compute the offset for the next argument 14469 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 14470 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 14471 .addReg(OffsetReg) 14472 .addImm(UseFPOffset ? 16 : 8); 14473 14474 // Store it back into the va_list. 14475 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 14476 .addOperand(Base) 14477 .addOperand(Scale) 14478 .addOperand(Index) 14479 .addDisp(Disp, UseFPOffset ? 4 : 0) 14480 .addOperand(Segment) 14481 .addReg(NextOffsetReg) 14482 .setMemRefs(MMOBegin, MMOEnd); 14483 14484 // Jump to endMBB 14485 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 14486 .addMBB(endMBB); 14487 } 14488 14489 // 14490 // Emit code to use overflow area 14491 // 14492 14493 // Load the overflow_area address into a register. 14494 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 14495 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 14496 .addOperand(Base) 14497 .addOperand(Scale) 14498 .addOperand(Index) 14499 .addDisp(Disp, 8) 14500 .addOperand(Segment) 14501 .setMemRefs(MMOBegin, MMOEnd); 14502 14503 // If we need to align it, do so. Otherwise, just copy the address 14504 // to OverflowDestReg. 14505 if (NeedsAlign) { 14506 // Align the overflow address 14507 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 14508 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 14509 14510 // aligned_addr = (addr + (align-1)) & ~(align-1) 14511 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 14512 .addReg(OverflowAddrReg) 14513 .addImm(Align-1); 14514 14515 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 14516 .addReg(TmpReg) 14517 .addImm(~(uint64_t)(Align-1)); 14518 } else { 14519 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 14520 .addReg(OverflowAddrReg); 14521 } 14522 14523 // Compute the next overflow address after this argument. 14524 // (the overflow address should be kept 8-byte aligned) 14525 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 14526 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 14527 .addReg(OverflowDestReg) 14528 .addImm(ArgSizeA8); 14529 14530 // Store the new overflow address. 14531 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 14532 .addOperand(Base) 14533 .addOperand(Scale) 14534 .addOperand(Index) 14535 .addDisp(Disp, 8) 14536 .addOperand(Segment) 14537 .addReg(NextAddrReg) 14538 .setMemRefs(MMOBegin, MMOEnd); 14539 14540 // If we branched, emit the PHI to the front of endMBB. 14541 if (offsetMBB) { 14542 BuildMI(*endMBB, endMBB->begin(), DL, 14543 TII->get(X86::PHI), DestReg) 14544 .addReg(OffsetDestReg).addMBB(offsetMBB) 14545 .addReg(OverflowDestReg).addMBB(overflowMBB); 14546 } 14547 14548 // Erase the pseudo instruction 14549 MI->eraseFromParent(); 14550 14551 return endMBB; 14552 } 14553 14554 MachineBasicBlock * 14555 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 14556 MachineInstr *MI, 14557 MachineBasicBlock *MBB) const { 14558 // Emit code to save XMM registers to the stack. The ABI says that the 14559 // number of registers to save is given in %al, so it's theoretically 14560 // possible to do an indirect jump trick to avoid saving all of them, 14561 // however this code takes a simpler approach and just executes all 14562 // of the stores if %al is non-zero. It's less code, and it's probably 14563 // easier on the hardware branch predictor, and stores aren't all that 14564 // expensive anyway. 14565 14566 // Create the new basic blocks. One block contains all the XMM stores, 14567 // and one block is the final destination regardless of whether any 14568 // stores were performed. 14569 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 14570 MachineFunction *F = MBB->getParent(); 14571 MachineFunction::iterator MBBIter = MBB; 14572 ++MBBIter; 14573 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 14574 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 14575 F->insert(MBBIter, XMMSaveMBB); 14576 F->insert(MBBIter, EndMBB); 14577 14578 // Transfer the remainder of MBB and its successor edges to EndMBB. 14579 EndMBB->splice(EndMBB->begin(), MBB, 14580 llvm::next(MachineBasicBlock::iterator(MI)), 14581 MBB->end()); 14582 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 14583 14584 // The original block will now fall through to the XMM save block. 14585 MBB->addSuccessor(XMMSaveMBB); 14586 // The XMMSaveMBB will fall through to the end block. 14587 XMMSaveMBB->addSuccessor(EndMBB); 14588 14589 // Now add the instructions. 14590 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14591 DebugLoc DL = MI->getDebugLoc(); 14592 14593 unsigned CountReg = MI->getOperand(0).getReg(); 14594 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 14595 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 14596 14597 if (!Subtarget->isTargetWin64()) { 14598 // If %al is 0, branch around the XMM save block. 14599 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 14600 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 14601 MBB->addSuccessor(EndMBB); 14602 } 14603 14604 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr; 14605 // In the XMM save block, save all the XMM argument registers. 14606 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 14607 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 14608 MachineMemOperand *MMO = 14609 F->getMachineMemOperand( 14610 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 14611 MachineMemOperand::MOStore, 14612 /*Size=*/16, /*Align=*/16); 14613 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 14614 .addFrameIndex(RegSaveFrameIndex) 14615 .addImm(/*Scale=*/1) 14616 .addReg(/*IndexReg=*/0) 14617 .addImm(/*Disp=*/Offset) 14618 .addReg(/*Segment=*/0) 14619 .addReg(MI->getOperand(i).getReg()) 14620 .addMemOperand(MMO); 14621 } 14622 14623 MI->eraseFromParent(); // The pseudo instruction is gone now. 14624 14625 return EndMBB; 14626 } 14627 14628 // The EFLAGS operand of SelectItr might be missing a kill marker 14629 // because there were multiple uses of EFLAGS, and ISel didn't know 14630 // which to mark. Figure out whether SelectItr should have had a 14631 // kill marker, and set it if it should. Returns the correct kill 14632 // marker value. 14633 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr, 14634 MachineBasicBlock* BB, 14635 const TargetRegisterInfo* TRI) { 14636 // Scan forward through BB for a use/def of EFLAGS. 14637 MachineBasicBlock::iterator miI(llvm::next(SelectItr)); 14638 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 14639 const MachineInstr& mi = *miI; 14640 if (mi.readsRegister(X86::EFLAGS)) 14641 return false; 14642 if (mi.definesRegister(X86::EFLAGS)) 14643 break; // Should have kill-flag - update below. 14644 } 14645 14646 // If we hit the end of the block, check whether EFLAGS is live into a 14647 // successor. 14648 if (miI == BB->end()) { 14649 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 14650 sEnd = BB->succ_end(); 14651 sItr != sEnd; ++sItr) { 14652 MachineBasicBlock* succ = *sItr; 14653 if (succ->isLiveIn(X86::EFLAGS)) 14654 return false; 14655 } 14656 } 14657 14658 // We found a def, or hit the end of the basic block and EFLAGS wasn't live 14659 // out. SelectMI should have a kill flag on EFLAGS. 14660 SelectItr->addRegisterKilled(X86::EFLAGS, TRI); 14661 return true; 14662 } 14663 14664 MachineBasicBlock * 14665 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 14666 MachineBasicBlock *BB) const { 14667 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14668 DebugLoc DL = MI->getDebugLoc(); 14669 14670 // To "insert" a SELECT_CC instruction, we actually have to insert the 14671 // diamond control-flow pattern. The incoming instruction knows the 14672 // destination vreg to set, the condition code register to branch on, the 14673 // true/false values to select between, and a branch opcode to use. 14674 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 14675 MachineFunction::iterator It = BB; 14676 ++It; 14677 14678 // thisMBB: 14679 // ... 14680 // TrueVal = ... 14681 // cmpTY ccX, r1, r2 14682 // bCC copy1MBB 14683 // fallthrough --> copy0MBB 14684 MachineBasicBlock *thisMBB = BB; 14685 MachineFunction *F = BB->getParent(); 14686 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 14687 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 14688 F->insert(It, copy0MBB); 14689 F->insert(It, sinkMBB); 14690 14691 // If the EFLAGS register isn't dead in the terminator, then claim that it's 14692 // live into the sink and copy blocks. 14693 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 14694 if (!MI->killsRegister(X86::EFLAGS) && 14695 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) { 14696 copy0MBB->addLiveIn(X86::EFLAGS); 14697 sinkMBB->addLiveIn(X86::EFLAGS); 14698 } 14699 14700 // Transfer the remainder of BB and its successor edges to sinkMBB. 14701 sinkMBB->splice(sinkMBB->begin(), BB, 14702 llvm::next(MachineBasicBlock::iterator(MI)), 14703 BB->end()); 14704 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 14705 14706 // Add the true and fallthrough blocks as its successors. 14707 BB->addSuccessor(copy0MBB); 14708 BB->addSuccessor(sinkMBB); 14709 14710 // Create the conditional branch instruction. 14711 unsigned Opc = 14712 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 14713 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 14714 14715 // copy0MBB: 14716 // %FalseValue = ... 14717 // # fallthrough to sinkMBB 14718 copy0MBB->addSuccessor(sinkMBB); 14719 14720 // sinkMBB: 14721 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 14722 // ... 14723 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14724 TII->get(X86::PHI), MI->getOperand(0).getReg()) 14725 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 14726 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 14727 14728 MI->eraseFromParent(); // The pseudo instruction is gone now. 14729 return sinkMBB; 14730 } 14731 14732 MachineBasicBlock * 14733 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 14734 bool Is64Bit) const { 14735 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14736 DebugLoc DL = MI->getDebugLoc(); 14737 MachineFunction *MF = BB->getParent(); 14738 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 14739 14740 assert(getTargetMachine().Options.EnableSegmentedStacks); 14741 14742 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 14743 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 14744 14745 // BB: 14746 // ... [Till the alloca] 14747 // If stacklet is not large enough, jump to mallocMBB 14748 // 14749 // bumpMBB: 14750 // Allocate by subtracting from RSP 14751 // Jump to continueMBB 14752 // 14753 // mallocMBB: 14754 // Allocate by call to runtime 14755 // 14756 // continueMBB: 14757 // ... 14758 // [rest of original BB] 14759 // 14760 14761 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14762 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14763 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14764 14765 MachineRegisterInfo &MRI = MF->getRegInfo(); 14766 const TargetRegisterClass *AddrRegClass = 14767 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 14768 14769 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 14770 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 14771 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 14772 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 14773 sizeVReg = MI->getOperand(1).getReg(), 14774 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 14775 14776 MachineFunction::iterator MBBIter = BB; 14777 ++MBBIter; 14778 14779 MF->insert(MBBIter, bumpMBB); 14780 MF->insert(MBBIter, mallocMBB); 14781 MF->insert(MBBIter, continueMBB); 14782 14783 continueMBB->splice(continueMBB->begin(), BB, llvm::next 14784 (MachineBasicBlock::iterator(MI)), BB->end()); 14785 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 14786 14787 // Add code to the main basic block to check if the stack limit has been hit, 14788 // and if so, jump to mallocMBB otherwise to bumpMBB. 14789 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 14790 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 14791 .addReg(tmpSPVReg).addReg(sizeVReg); 14792 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 14793 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg) 14794 .addReg(SPLimitVReg); 14795 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 14796 14797 // bumpMBB simply decreases the stack pointer, since we know the current 14798 // stacklet has enough space. 14799 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 14800 .addReg(SPLimitVReg); 14801 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 14802 .addReg(SPLimitVReg); 14803 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 14804 14805 // Calls into a routine in libgcc to allocate more space from the heap. 14806 const uint32_t *RegMask = 14807 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 14808 if (Is64Bit) { 14809 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 14810 .addReg(sizeVReg); 14811 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 14812 .addExternalSymbol("__morestack_allocate_stack_space") 14813 .addRegMask(RegMask) 14814 .addReg(X86::RDI, RegState::Implicit) 14815 .addReg(X86::RAX, RegState::ImplicitDefine); 14816 } else { 14817 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 14818 .addImm(12); 14819 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 14820 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 14821 .addExternalSymbol("__morestack_allocate_stack_space") 14822 .addRegMask(RegMask) 14823 .addReg(X86::EAX, RegState::ImplicitDefine); 14824 } 14825 14826 if (!Is64Bit) 14827 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 14828 .addImm(16); 14829 14830 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 14831 .addReg(Is64Bit ? X86::RAX : X86::EAX); 14832 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 14833 14834 // Set up the CFG correctly. 14835 BB->addSuccessor(bumpMBB); 14836 BB->addSuccessor(mallocMBB); 14837 mallocMBB->addSuccessor(continueMBB); 14838 bumpMBB->addSuccessor(continueMBB); 14839 14840 // Take care of the PHI nodes. 14841 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 14842 MI->getOperand(0).getReg()) 14843 .addReg(mallocPtrVReg).addMBB(mallocMBB) 14844 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 14845 14846 // Delete the original pseudo instruction. 14847 MI->eraseFromParent(); 14848 14849 // And we're done. 14850 return continueMBB; 14851 } 14852 14853 MachineBasicBlock * 14854 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 14855 MachineBasicBlock *BB) const { 14856 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14857 DebugLoc DL = MI->getDebugLoc(); 14858 14859 assert(!Subtarget->isTargetEnvMacho()); 14860 14861 // The lowering is pretty easy: we're just emitting the call to _alloca. The 14862 // non-trivial part is impdef of ESP. 14863 14864 if (Subtarget->isTargetWin64()) { 14865 if (Subtarget->isTargetCygMing()) { 14866 // ___chkstk(Mingw64): 14867 // Clobbers R10, R11, RAX and EFLAGS. 14868 // Updates RSP. 14869 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 14870 .addExternalSymbol("___chkstk") 14871 .addReg(X86::RAX, RegState::Implicit) 14872 .addReg(X86::RSP, RegState::Implicit) 14873 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 14874 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 14875 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14876 } else { 14877 // __chkstk(MSVCRT): does not update stack pointer. 14878 // Clobbers R10, R11 and EFLAGS. 14879 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 14880 .addExternalSymbol("__chkstk") 14881 .addReg(X86::RAX, RegState::Implicit) 14882 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14883 // RAX has the offset to be subtracted from RSP. 14884 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 14885 .addReg(X86::RSP) 14886 .addReg(X86::RAX); 14887 } 14888 } else { 14889 const char *StackProbeSymbol = 14890 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 14891 14892 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 14893 .addExternalSymbol(StackProbeSymbol) 14894 .addReg(X86::EAX, RegState::Implicit) 14895 .addReg(X86::ESP, RegState::Implicit) 14896 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 14897 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 14898 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14899 } 14900 14901 MI->eraseFromParent(); // The pseudo instruction is gone now. 14902 return BB; 14903 } 14904 14905 MachineBasicBlock * 14906 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 14907 MachineBasicBlock *BB) const { 14908 // This is pretty easy. We're taking the value that we received from 14909 // our load from the relocation, sticking it in either RDI (x86-64) 14910 // or EAX and doing an indirect call. The return value will then 14911 // be in the normal return register. 14912 const X86InstrInfo *TII 14913 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 14914 DebugLoc DL = MI->getDebugLoc(); 14915 MachineFunction *F = BB->getParent(); 14916 14917 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 14918 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 14919 14920 // Get a register mask for the lowered call. 14921 // FIXME: The 32-bit calls have non-standard calling conventions. Use a 14922 // proper register mask. 14923 const uint32_t *RegMask = 14924 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 14925 if (Subtarget->is64Bit()) { 14926 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14927 TII->get(X86::MOV64rm), X86::RDI) 14928 .addReg(X86::RIP) 14929 .addImm(0).addReg(0) 14930 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14931 MI->getOperand(3).getTargetFlags()) 14932 .addReg(0); 14933 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 14934 addDirectMem(MIB, X86::RDI); 14935 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask); 14936 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 14937 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14938 TII->get(X86::MOV32rm), X86::EAX) 14939 .addReg(0) 14940 .addImm(0).addReg(0) 14941 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14942 MI->getOperand(3).getTargetFlags()) 14943 .addReg(0); 14944 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14945 addDirectMem(MIB, X86::EAX); 14946 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14947 } else { 14948 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14949 TII->get(X86::MOV32rm), X86::EAX) 14950 .addReg(TII->getGlobalBaseReg(F)) 14951 .addImm(0).addReg(0) 14952 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14953 MI->getOperand(3).getTargetFlags()) 14954 .addReg(0); 14955 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14956 addDirectMem(MIB, X86::EAX); 14957 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14958 } 14959 14960 MI->eraseFromParent(); // The pseudo instruction is gone now. 14961 return BB; 14962 } 14963 14964 MachineBasicBlock * 14965 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 14966 MachineBasicBlock *MBB) const { 14967 DebugLoc DL = MI->getDebugLoc(); 14968 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14969 14970 MachineFunction *MF = MBB->getParent(); 14971 MachineRegisterInfo &MRI = MF->getRegInfo(); 14972 14973 const BasicBlock *BB = MBB->getBasicBlock(); 14974 MachineFunction::iterator I = MBB; 14975 ++I; 14976 14977 // Memory Reference 14978 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14979 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14980 14981 unsigned DstReg; 14982 unsigned MemOpndSlot = 0; 14983 14984 unsigned CurOp = 0; 14985 14986 DstReg = MI->getOperand(CurOp++).getReg(); 14987 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 14988 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 14989 unsigned mainDstReg = MRI.createVirtualRegister(RC); 14990 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 14991 14992 MemOpndSlot = CurOp; 14993 14994 MVT PVT = getPointerTy(); 14995 assert((PVT == MVT::i64 || PVT == MVT::i32) && 14996 "Invalid Pointer Size!"); 14997 14998 // For v = setjmp(buf), we generate 14999 // 15000 // thisMBB: 15001 // buf[LabelOffset] = restoreMBB 15002 // SjLjSetup restoreMBB 15003 // 15004 // mainMBB: 15005 // v_main = 0 15006 // 15007 // sinkMBB: 15008 // v = phi(main, restore) 15009 // 15010 // restoreMBB: 15011 // v_restore = 1 15012 15013 MachineBasicBlock *thisMBB = MBB; 15014 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 15015 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 15016 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB); 15017 MF->insert(I, mainMBB); 15018 MF->insert(I, sinkMBB); 15019 MF->push_back(restoreMBB); 15020 15021 MachineInstrBuilder MIB; 15022 15023 // Transfer the remainder of BB and its successor edges to sinkMBB. 15024 sinkMBB->splice(sinkMBB->begin(), MBB, 15025 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 15026 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 15027 15028 // thisMBB: 15029 unsigned PtrStoreOpc = 0; 15030 unsigned LabelReg = 0; 15031 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 15032 Reloc::Model RM = getTargetMachine().getRelocationModel(); 15033 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) && 15034 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC); 15035 15036 // Prepare IP either in reg or imm. 15037 if (!UseImmLabel) { 15038 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr; 15039 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 15040 LabelReg = MRI.createVirtualRegister(PtrRC); 15041 if (Subtarget->is64Bit()) { 15042 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg) 15043 .addReg(X86::RIP) 15044 .addImm(0) 15045 .addReg(0) 15046 .addMBB(restoreMBB) 15047 .addReg(0); 15048 } else { 15049 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII); 15050 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg) 15051 .addReg(XII->getGlobalBaseReg(MF)) 15052 .addImm(0) 15053 .addReg(0) 15054 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference()) 15055 .addReg(0); 15056 } 15057 } else 15058 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi; 15059 // Store IP 15060 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc)); 15061 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 15062 if (i == X86::AddrDisp) 15063 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset); 15064 else 15065 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 15066 } 15067 if (!UseImmLabel) 15068 MIB.addReg(LabelReg); 15069 else 15070 MIB.addMBB(restoreMBB); 15071 MIB.setMemRefs(MMOBegin, MMOEnd); 15072 // Setup 15073 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup)) 15074 .addMBB(restoreMBB); 15075 15076 const X86RegisterInfo *RegInfo = 15077 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 15078 MIB.addRegMask(RegInfo->getNoPreservedMask()); 15079 thisMBB->addSuccessor(mainMBB); 15080 thisMBB->addSuccessor(restoreMBB); 15081 15082 // mainMBB: 15083 // EAX = 0 15084 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg); 15085 mainMBB->addSuccessor(sinkMBB); 15086 15087 // sinkMBB: 15088 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 15089 TII->get(X86::PHI), DstReg) 15090 .addReg(mainDstReg).addMBB(mainMBB) 15091 .addReg(restoreDstReg).addMBB(restoreMBB); 15092 15093 // restoreMBB: 15094 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1); 15095 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB); 15096 restoreMBB->addSuccessor(sinkMBB); 15097 15098 MI->eraseFromParent(); 15099 return sinkMBB; 15100 } 15101 15102 MachineBasicBlock * 15103 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 15104 MachineBasicBlock *MBB) const { 15105 DebugLoc DL = MI->getDebugLoc(); 15106 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 15107 15108 MachineFunction *MF = MBB->getParent(); 15109 MachineRegisterInfo &MRI = MF->getRegInfo(); 15110 15111 // Memory Reference 15112 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 15113 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 15114 15115 MVT PVT = getPointerTy(); 15116 assert((PVT == MVT::i64 || PVT == MVT::i32) && 15117 "Invalid Pointer Size!"); 15118 15119 const TargetRegisterClass *RC = 15120 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass; 15121 unsigned Tmp = MRI.createVirtualRegister(RC); 15122 // Since FP is only updated here but NOT referenced, it's treated as GPR. 15123 const X86RegisterInfo *RegInfo = 15124 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 15125 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP; 15126 unsigned SP = RegInfo->getStackRegister(); 15127 15128 MachineInstrBuilder MIB; 15129 15130 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 15131 const int64_t SPOffset = 2 * PVT.getStoreSize(); 15132 15133 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm; 15134 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r; 15135 15136 // Reload FP 15137 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP); 15138 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 15139 MIB.addOperand(MI->getOperand(i)); 15140 MIB.setMemRefs(MMOBegin, MMOEnd); 15141 // Reload IP 15142 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp); 15143 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 15144 if (i == X86::AddrDisp) 15145 MIB.addDisp(MI->getOperand(i), LabelOffset); 15146 else 15147 MIB.addOperand(MI->getOperand(i)); 15148 } 15149 MIB.setMemRefs(MMOBegin, MMOEnd); 15150 // Reload SP 15151 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP); 15152 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 15153 if (i == X86::AddrDisp) 15154 MIB.addDisp(MI->getOperand(i), SPOffset); 15155 else 15156 MIB.addOperand(MI->getOperand(i)); 15157 } 15158 MIB.setMemRefs(MMOBegin, MMOEnd); 15159 // Jump 15160 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp); 15161 15162 MI->eraseFromParent(); 15163 return MBB; 15164 } 15165 15166 MachineBasicBlock * 15167 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 15168 MachineBasicBlock *BB) const { 15169 switch (MI->getOpcode()) { 15170 default: llvm_unreachable("Unexpected instr type to insert"); 15171 case X86::TAILJMPd64: 15172 case X86::TAILJMPr64: 15173 case X86::TAILJMPm64: 15174 llvm_unreachable("TAILJMP64 would not be touched here."); 15175 case X86::TCRETURNdi64: 15176 case X86::TCRETURNri64: 15177 case X86::TCRETURNmi64: 15178 return BB; 15179 case X86::WIN_ALLOCA: 15180 return EmitLoweredWinAlloca(MI, BB); 15181 case X86::SEG_ALLOCA_32: 15182 return EmitLoweredSegAlloca(MI, BB, false); 15183 case X86::SEG_ALLOCA_64: 15184 return EmitLoweredSegAlloca(MI, BB, true); 15185 case X86::TLSCall_32: 15186 case X86::TLSCall_64: 15187 return EmitLoweredTLSCall(MI, BB); 15188 case X86::CMOV_GR8: 15189 case X86::CMOV_FR32: 15190 case X86::CMOV_FR64: 15191 case X86::CMOV_V4F32: 15192 case X86::CMOV_V2F64: 15193 case X86::CMOV_V2I64: 15194 case X86::CMOV_V8F32: 15195 case X86::CMOV_V4F64: 15196 case X86::CMOV_V4I64: 15197 case X86::CMOV_GR16: 15198 case X86::CMOV_GR32: 15199 case X86::CMOV_RFP32: 15200 case X86::CMOV_RFP64: 15201 case X86::CMOV_RFP80: 15202 return EmitLoweredSelect(MI, BB); 15203 15204 case X86::FP32_TO_INT16_IN_MEM: 15205 case X86::FP32_TO_INT32_IN_MEM: 15206 case X86::FP32_TO_INT64_IN_MEM: 15207 case X86::FP64_TO_INT16_IN_MEM: 15208 case X86::FP64_TO_INT32_IN_MEM: 15209 case X86::FP64_TO_INT64_IN_MEM: 15210 case X86::FP80_TO_INT16_IN_MEM: 15211 case X86::FP80_TO_INT32_IN_MEM: 15212 case X86::FP80_TO_INT64_IN_MEM: { 15213 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 15214 DebugLoc DL = MI->getDebugLoc(); 15215 15216 // Change the floating point control register to use "round towards zero" 15217 // mode when truncating to an integer value. 15218 MachineFunction *F = BB->getParent(); 15219 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 15220 addFrameReference(BuildMI(*BB, MI, DL, 15221 TII->get(X86::FNSTCW16m)), CWFrameIdx); 15222 15223 // Load the old value of the high byte of the control word... 15224 unsigned OldCW = 15225 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass); 15226 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 15227 CWFrameIdx); 15228 15229 // Set the high part to be round to zero... 15230 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 15231 .addImm(0xC7F); 15232 15233 // Reload the modified control word now... 15234 addFrameReference(BuildMI(*BB, MI, DL, 15235 TII->get(X86::FLDCW16m)), CWFrameIdx); 15236 15237 // Restore the memory image of control word to original value 15238 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 15239 .addReg(OldCW); 15240 15241 // Get the X86 opcode to use. 15242 unsigned Opc; 15243 switch (MI->getOpcode()) { 15244 default: llvm_unreachable("illegal opcode!"); 15245 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 15246 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 15247 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 15248 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 15249 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 15250 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 15251 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 15252 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 15253 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 15254 } 15255 15256 X86AddressMode AM; 15257 MachineOperand &Op = MI->getOperand(0); 15258 if (Op.isReg()) { 15259 AM.BaseType = X86AddressMode::RegBase; 15260 AM.Base.Reg = Op.getReg(); 15261 } else { 15262 AM.BaseType = X86AddressMode::FrameIndexBase; 15263 AM.Base.FrameIndex = Op.getIndex(); 15264 } 15265 Op = MI->getOperand(1); 15266 if (Op.isImm()) 15267 AM.Scale = Op.getImm(); 15268 Op = MI->getOperand(2); 15269 if (Op.isImm()) 15270 AM.IndexReg = Op.getImm(); 15271 Op = MI->getOperand(3); 15272 if (Op.isGlobal()) { 15273 AM.GV = Op.getGlobal(); 15274 } else { 15275 AM.Disp = Op.getImm(); 15276 } 15277 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 15278 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 15279 15280 // Reload the original control word now. 15281 addFrameReference(BuildMI(*BB, MI, DL, 15282 TII->get(X86::FLDCW16m)), CWFrameIdx); 15283 15284 MI->eraseFromParent(); // The pseudo instruction is gone now. 15285 return BB; 15286 } 15287 // String/text processing lowering. 15288 case X86::PCMPISTRM128REG: 15289 case X86::VPCMPISTRM128REG: 15290 case X86::PCMPISTRM128MEM: 15291 case X86::VPCMPISTRM128MEM: 15292 case X86::PCMPESTRM128REG: 15293 case X86::VPCMPESTRM128REG: 15294 case X86::PCMPESTRM128MEM: 15295 case X86::VPCMPESTRM128MEM: 15296 assert(Subtarget->hasSSE42() && 15297 "Target must have SSE4.2 or AVX features enabled"); 15298 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo()); 15299 15300 // String/text processing lowering. 15301 case X86::PCMPISTRIREG: 15302 case X86::VPCMPISTRIREG: 15303 case X86::PCMPISTRIMEM: 15304 case X86::VPCMPISTRIMEM: 15305 case X86::PCMPESTRIREG: 15306 case X86::VPCMPESTRIREG: 15307 case X86::PCMPESTRIMEM: 15308 case X86::VPCMPESTRIMEM: 15309 assert(Subtarget->hasSSE42() && 15310 "Target must have SSE4.2 or AVX features enabled"); 15311 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo()); 15312 15313 // Thread synchronization. 15314 case X86::MONITOR: 15315 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget); 15316 15317 // xbegin 15318 case X86::XBEGIN: 15319 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo()); 15320 15321 // Atomic Lowering. 15322 case X86::ATOMAND8: 15323 case X86::ATOMAND16: 15324 case X86::ATOMAND32: 15325 case X86::ATOMAND64: 15326 // Fall through 15327 case X86::ATOMOR8: 15328 case X86::ATOMOR16: 15329 case X86::ATOMOR32: 15330 case X86::ATOMOR64: 15331 // Fall through 15332 case X86::ATOMXOR16: 15333 case X86::ATOMXOR8: 15334 case X86::ATOMXOR32: 15335 case X86::ATOMXOR64: 15336 // Fall through 15337 case X86::ATOMNAND8: 15338 case X86::ATOMNAND16: 15339 case X86::ATOMNAND32: 15340 case X86::ATOMNAND64: 15341 // Fall through 15342 case X86::ATOMMAX8: 15343 case X86::ATOMMAX16: 15344 case X86::ATOMMAX32: 15345 case X86::ATOMMAX64: 15346 // Fall through 15347 case X86::ATOMMIN8: 15348 case X86::ATOMMIN16: 15349 case X86::ATOMMIN32: 15350 case X86::ATOMMIN64: 15351 // Fall through 15352 case X86::ATOMUMAX8: 15353 case X86::ATOMUMAX16: 15354 case X86::ATOMUMAX32: 15355 case X86::ATOMUMAX64: 15356 // Fall through 15357 case X86::ATOMUMIN8: 15358 case X86::ATOMUMIN16: 15359 case X86::ATOMUMIN32: 15360 case X86::ATOMUMIN64: 15361 return EmitAtomicLoadArith(MI, BB); 15362 15363 // This group does 64-bit operations on a 32-bit host. 15364 case X86::ATOMAND6432: 15365 case X86::ATOMOR6432: 15366 case X86::ATOMXOR6432: 15367 case X86::ATOMNAND6432: 15368 case X86::ATOMADD6432: 15369 case X86::ATOMSUB6432: 15370 case X86::ATOMMAX6432: 15371 case X86::ATOMMIN6432: 15372 case X86::ATOMUMAX6432: 15373 case X86::ATOMUMIN6432: 15374 case X86::ATOMSWAP6432: 15375 return EmitAtomicLoadArith6432(MI, BB); 15376 15377 case X86::VASTART_SAVE_XMM_REGS: 15378 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 15379 15380 case X86::VAARG_64: 15381 return EmitVAARG64WithCustomInserter(MI, BB); 15382 15383 case X86::EH_SjLj_SetJmp32: 15384 case X86::EH_SjLj_SetJmp64: 15385 return emitEHSjLjSetJmp(MI, BB); 15386 15387 case X86::EH_SjLj_LongJmp32: 15388 case X86::EH_SjLj_LongJmp64: 15389 return emitEHSjLjLongJmp(MI, BB); 15390 } 15391 } 15392 15393 //===----------------------------------------------------------------------===// 15394 // X86 Optimization Hooks 15395 //===----------------------------------------------------------------------===// 15396 15397 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 15398 APInt &KnownZero, 15399 APInt &KnownOne, 15400 const SelectionDAG &DAG, 15401 unsigned Depth) const { 15402 unsigned BitWidth = KnownZero.getBitWidth(); 15403 unsigned Opc = Op.getOpcode(); 15404 assert((Opc >= ISD::BUILTIN_OP_END || 15405 Opc == ISD::INTRINSIC_WO_CHAIN || 15406 Opc == ISD::INTRINSIC_W_CHAIN || 15407 Opc == ISD::INTRINSIC_VOID) && 15408 "Should use MaskedValueIsZero if you don't know whether Op" 15409 " is a target node!"); 15410 15411 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 15412 switch (Opc) { 15413 default: break; 15414 case X86ISD::ADD: 15415 case X86ISD::SUB: 15416 case X86ISD::ADC: 15417 case X86ISD::SBB: 15418 case X86ISD::SMUL: 15419 case X86ISD::UMUL: 15420 case X86ISD::INC: 15421 case X86ISD::DEC: 15422 case X86ISD::OR: 15423 case X86ISD::XOR: 15424 case X86ISD::AND: 15425 // These nodes' second result is a boolean. 15426 if (Op.getResNo() == 0) 15427 break; 15428 // Fallthrough 15429 case X86ISD::SETCC: 15430 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 15431 break; 15432 case ISD::INTRINSIC_WO_CHAIN: { 15433 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 15434 unsigned NumLoBits = 0; 15435 switch (IntId) { 15436 default: break; 15437 case Intrinsic::x86_sse_movmsk_ps: 15438 case Intrinsic::x86_avx_movmsk_ps_256: 15439 case Intrinsic::x86_sse2_movmsk_pd: 15440 case Intrinsic::x86_avx_movmsk_pd_256: 15441 case Intrinsic::x86_mmx_pmovmskb: 15442 case Intrinsic::x86_sse2_pmovmskb_128: 15443 case Intrinsic::x86_avx2_pmovmskb: { 15444 // High bits of movmskp{s|d}, pmovmskb are known zero. 15445 switch (IntId) { 15446 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 15447 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 15448 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 15449 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 15450 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 15451 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 15452 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 15453 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break; 15454 } 15455 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits); 15456 break; 15457 } 15458 } 15459 break; 15460 } 15461 } 15462 } 15463 15464 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 15465 unsigned Depth) const { 15466 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 15467 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 15468 return Op.getValueType().getScalarType().getSizeInBits(); 15469 15470 // Fallback case. 15471 return 1; 15472 } 15473 15474 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 15475 /// node is a GlobalAddress + offset. 15476 bool X86TargetLowering::isGAPlusOffset(SDNode *N, 15477 const GlobalValue* &GA, 15478 int64_t &Offset) const { 15479 if (N->getOpcode() == X86ISD::Wrapper) { 15480 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 15481 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 15482 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 15483 return true; 15484 } 15485 } 15486 return TargetLowering::isGAPlusOffset(N, GA, Offset); 15487 } 15488 15489 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 15490 /// same as extracting the high 128-bit part of 256-bit vector and then 15491 /// inserting the result into the low part of a new 256-bit vector 15492 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 15493 EVT VT = SVOp->getValueType(0); 15494 unsigned NumElems = VT.getVectorNumElements(); 15495 15496 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 15497 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j) 15498 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 15499 SVOp->getMaskElt(j) >= 0) 15500 return false; 15501 15502 return true; 15503 } 15504 15505 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 15506 /// same as extracting the low 128-bit part of 256-bit vector and then 15507 /// inserting the result into the high part of a new 256-bit vector 15508 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 15509 EVT VT = SVOp->getValueType(0); 15510 unsigned NumElems = VT.getVectorNumElements(); 15511 15512 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 15513 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j) 15514 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 15515 SVOp->getMaskElt(j) >= 0) 15516 return false; 15517 15518 return true; 15519 } 15520 15521 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 15522 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 15523 TargetLowering::DAGCombinerInfo &DCI, 15524 const X86Subtarget* Subtarget) { 15525 SDLoc dl(N); 15526 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 15527 SDValue V1 = SVOp->getOperand(0); 15528 SDValue V2 = SVOp->getOperand(1); 15529 EVT VT = SVOp->getValueType(0); 15530 unsigned NumElems = VT.getVectorNumElements(); 15531 15532 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 15533 V2.getOpcode() == ISD::CONCAT_VECTORS) { 15534 // 15535 // 0,0,0,... 15536 // | 15537 // V UNDEF BUILD_VECTOR UNDEF 15538 // \ / \ / 15539 // CONCAT_VECTOR CONCAT_VECTOR 15540 // \ / 15541 // \ / 15542 // RESULT: V + zero extended 15543 // 15544 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 15545 V2.getOperand(1).getOpcode() != ISD::UNDEF || 15546 V1.getOperand(1).getOpcode() != ISD::UNDEF) 15547 return SDValue(); 15548 15549 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 15550 return SDValue(); 15551 15552 // To match the shuffle mask, the first half of the mask should 15553 // be exactly the first vector, and all the rest a splat with the 15554 // first element of the second one. 15555 for (unsigned i = 0; i != NumElems/2; ++i) 15556 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 15557 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 15558 return SDValue(); 15559 15560 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD. 15561 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) { 15562 if (Ld->hasNUsesOfValue(1, 0)) { 15563 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other); 15564 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() }; 15565 SDValue ResNode = 15566 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 15567 array_lengthof(Ops), 15568 Ld->getMemoryVT(), 15569 Ld->getPointerInfo(), 15570 Ld->getAlignment(), 15571 false/*isVolatile*/, true/*ReadMem*/, 15572 false/*WriteMem*/); 15573 15574 // Make sure the newly-created LOAD is in the same position as Ld in 15575 // terms of dependency. We create a TokenFactor for Ld and ResNode, 15576 // and update uses of Ld's output chain to use the TokenFactor. 15577 if (Ld->hasAnyUseOfValue(1)) { 15578 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15579 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1)); 15580 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain); 15581 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1), 15582 SDValue(ResNode.getNode(), 1)); 15583 } 15584 15585 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode); 15586 } 15587 } 15588 15589 // Emit a zeroed vector and insert the desired subvector on its 15590 // first half. 15591 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 15592 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl); 15593 return DCI.CombineTo(N, InsV); 15594 } 15595 15596 //===--------------------------------------------------------------------===// 15597 // Combine some shuffles into subvector extracts and inserts: 15598 // 15599 15600 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 15601 if (isShuffleHigh128VectorInsertLow(SVOp)) { 15602 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl); 15603 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl); 15604 return DCI.CombineTo(N, InsV); 15605 } 15606 15607 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 15608 if (isShuffleLow128VectorInsertHigh(SVOp)) { 15609 SDValue V = Extract128BitVector(V1, 0, DAG, dl); 15610 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl); 15611 return DCI.CombineTo(N, InsV); 15612 } 15613 15614 return SDValue(); 15615 } 15616 15617 /// PerformShuffleCombine - Performs several different shuffle combines. 15618 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 15619 TargetLowering::DAGCombinerInfo &DCI, 15620 const X86Subtarget *Subtarget) { 15621 SDLoc dl(N); 15622 EVT VT = N->getValueType(0); 15623 15624 // Don't create instructions with illegal types after legalize types has run. 15625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15626 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 15627 return SDValue(); 15628 15629 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 15630 if (Subtarget->hasFp256() && VT.is256BitVector() && 15631 N->getOpcode() == ISD::VECTOR_SHUFFLE) 15632 return PerformShuffleCombine256(N, DAG, DCI, Subtarget); 15633 15634 // Only handle 128 wide vector from here on. 15635 if (!VT.is128BitVector()) 15636 return SDValue(); 15637 15638 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 15639 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 15640 // consecutive, non-overlapping, and in the right order. 15641 SmallVector<SDValue, 16> Elts; 15642 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 15643 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 15644 15645 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 15646 } 15647 15648 /// PerformTruncateCombine - Converts truncate operation to 15649 /// a sequence of vector shuffle operations. 15650 /// It is possible when we truncate 256-bit vector to 128-bit vector 15651 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 15652 TargetLowering::DAGCombinerInfo &DCI, 15653 const X86Subtarget *Subtarget) { 15654 return SDValue(); 15655 } 15656 15657 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target 15658 /// specific shuffle of a load can be folded into a single element load. 15659 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but 15660 /// shuffles have been customed lowered so we need to handle those here. 15661 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG, 15662 TargetLowering::DAGCombinerInfo &DCI) { 15663 if (DCI.isBeforeLegalizeOps()) 15664 return SDValue(); 15665 15666 SDValue InVec = N->getOperand(0); 15667 SDValue EltNo = N->getOperand(1); 15668 15669 if (!isa<ConstantSDNode>(EltNo)) 15670 return SDValue(); 15671 15672 EVT VT = InVec.getValueType(); 15673 15674 bool HasShuffleIntoBitcast = false; 15675 if (InVec.getOpcode() == ISD::BITCAST) { 15676 // Don't duplicate a load with other uses. 15677 if (!InVec.hasOneUse()) 15678 return SDValue(); 15679 EVT BCVT = InVec.getOperand(0).getValueType(); 15680 if (BCVT.getVectorNumElements() != VT.getVectorNumElements()) 15681 return SDValue(); 15682 InVec = InVec.getOperand(0); 15683 HasShuffleIntoBitcast = true; 15684 } 15685 15686 if (!isTargetShuffle(InVec.getOpcode())) 15687 return SDValue(); 15688 15689 // Don't duplicate a load with other uses. 15690 if (!InVec.hasOneUse()) 15691 return SDValue(); 15692 15693 SmallVector<int, 16> ShuffleMask; 15694 bool UnaryShuffle; 15695 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask, 15696 UnaryShuffle)) 15697 return SDValue(); 15698 15699 // Select the input vector, guarding against out of range extract vector. 15700 unsigned NumElems = VT.getVectorNumElements(); 15701 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 15702 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt]; 15703 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0) 15704 : InVec.getOperand(1); 15705 15706 // If inputs to shuffle are the same for both ops, then allow 2 uses 15707 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1; 15708 15709 if (LdNode.getOpcode() == ISD::BITCAST) { 15710 // Don't duplicate a load with other uses. 15711 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0)) 15712 return SDValue(); 15713 15714 AllowedUses = 1; // only allow 1 load use if we have a bitcast 15715 LdNode = LdNode.getOperand(0); 15716 } 15717 15718 if (!ISD::isNormalLoad(LdNode.getNode())) 15719 return SDValue(); 15720 15721 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode); 15722 15723 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile()) 15724 return SDValue(); 15725 15726 if (HasShuffleIntoBitcast) { 15727 // If there's a bitcast before the shuffle, check if the load type and 15728 // alignment is valid. 15729 unsigned Align = LN0->getAlignment(); 15730 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15731 unsigned NewAlign = TLI.getDataLayout()-> 15732 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 15733 15734 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 15735 return SDValue(); 15736 } 15737 15738 // All checks match so transform back to vector_shuffle so that DAG combiner 15739 // can finish the job 15740 SDLoc dl(N); 15741 15742 // Create shuffle node taking into account the case that its a unary shuffle 15743 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1); 15744 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl, 15745 InVec.getOperand(0), Shuffle, 15746 &ShuffleMask[0]); 15747 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 15748 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle, 15749 EltNo); 15750 } 15751 15752 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 15753 /// generation and convert it from being a bunch of shuffles and extracts 15754 /// to a simple store and scalar loads to extract the elements. 15755 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 15756 TargetLowering::DAGCombinerInfo &DCI) { 15757 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI); 15758 if (NewOp.getNode()) 15759 return NewOp; 15760 15761 SDValue InputVector = N->getOperand(0); 15762 // Detect whether we are trying to convert from mmx to i32 and the bitcast 15763 // from mmx to v2i32 has a single usage. 15764 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST && 15765 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx && 15766 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32) 15767 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector), 15768 N->getValueType(0), 15769 InputVector.getNode()->getOperand(0)); 15770 15771 // Only operate on vectors of 4 elements, where the alternative shuffling 15772 // gets to be more expensive. 15773 if (InputVector.getValueType() != MVT::v4i32) 15774 return SDValue(); 15775 15776 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 15777 // single use which is a sign-extend or zero-extend, and all elements are 15778 // used. 15779 SmallVector<SDNode *, 4> Uses; 15780 unsigned ExtractedElements = 0; 15781 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 15782 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 15783 if (UI.getUse().getResNo() != InputVector.getResNo()) 15784 return SDValue(); 15785 15786 SDNode *Extract = *UI; 15787 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 15788 return SDValue(); 15789 15790 if (Extract->getValueType(0) != MVT::i32) 15791 return SDValue(); 15792 if (!Extract->hasOneUse()) 15793 return SDValue(); 15794 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 15795 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 15796 return SDValue(); 15797 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 15798 return SDValue(); 15799 15800 // Record which element was extracted. 15801 ExtractedElements |= 15802 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 15803 15804 Uses.push_back(Extract); 15805 } 15806 15807 // If not all the elements were used, this may not be worthwhile. 15808 if (ExtractedElements != 15) 15809 return SDValue(); 15810 15811 // Ok, we've now decided to do the transformation. 15812 SDLoc dl(InputVector); 15813 15814 // Store the value to a temporary stack slot. 15815 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 15816 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 15817 MachinePointerInfo(), false, false, 0); 15818 15819 // Replace each use (extract) with a load of the appropriate element. 15820 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 15821 UE = Uses.end(); UI != UE; ++UI) { 15822 SDNode *Extract = *UI; 15823 15824 // cOMpute the element's address. 15825 SDValue Idx = Extract->getOperand(1); 15826 unsigned EltSize = 15827 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 15828 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 15829 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15830 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 15831 15832 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 15833 StackPtr, OffsetVal); 15834 15835 // Load the scalar. 15836 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 15837 ScalarAddr, MachinePointerInfo(), 15838 false, false, false, 0); 15839 15840 // Replace the exact with the load. 15841 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 15842 } 15843 15844 // The replacement was made in place; don't return anything. 15845 return SDValue(); 15846 } 15847 15848 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match. 15849 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, 15850 SDValue RHS, SelectionDAG &DAG, 15851 const X86Subtarget *Subtarget) { 15852 if (!VT.isVector()) 15853 return 0; 15854 15855 switch (VT.getSimpleVT().SimpleTy) { 15856 default: return 0; 15857 case MVT::v32i8: 15858 case MVT::v16i16: 15859 case MVT::v8i32: 15860 if (!Subtarget->hasAVX2()) 15861 return 0; 15862 case MVT::v16i8: 15863 case MVT::v8i16: 15864 case MVT::v4i32: 15865 if (!Subtarget->hasSSE2()) 15866 return 0; 15867 } 15868 15869 // SSE2 has only a small subset of the operations. 15870 bool hasUnsigned = Subtarget->hasSSE41() || 15871 (Subtarget->hasSSE2() && VT == MVT::v16i8); 15872 bool hasSigned = Subtarget->hasSSE41() || 15873 (Subtarget->hasSSE2() && VT == MVT::v8i16); 15874 15875 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15876 15877 // Check for x CC y ? x : y. 15878 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15879 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15880 switch (CC) { 15881 default: break; 15882 case ISD::SETULT: 15883 case ISD::SETULE: 15884 return hasUnsigned ? X86ISD::UMIN : 0; 15885 case ISD::SETUGT: 15886 case ISD::SETUGE: 15887 return hasUnsigned ? X86ISD::UMAX : 0; 15888 case ISD::SETLT: 15889 case ISD::SETLE: 15890 return hasSigned ? X86ISD::SMIN : 0; 15891 case ISD::SETGT: 15892 case ISD::SETGE: 15893 return hasSigned ? X86ISD::SMAX : 0; 15894 } 15895 // Check for x CC y ? y : x -- a min/max with reversed arms. 15896 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 15897 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 15898 switch (CC) { 15899 default: break; 15900 case ISD::SETULT: 15901 case ISD::SETULE: 15902 return hasUnsigned ? X86ISD::UMAX : 0; 15903 case ISD::SETUGT: 15904 case ISD::SETUGE: 15905 return hasUnsigned ? X86ISD::UMIN : 0; 15906 case ISD::SETLT: 15907 case ISD::SETLE: 15908 return hasSigned ? X86ISD::SMAX : 0; 15909 case ISD::SETGT: 15910 case ISD::SETGE: 15911 return hasSigned ? X86ISD::SMIN : 0; 15912 } 15913 } 15914 15915 return 0; 15916 } 15917 15918 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 15919 /// nodes. 15920 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 15921 TargetLowering::DAGCombinerInfo &DCI, 15922 const X86Subtarget *Subtarget) { 15923 SDLoc DL(N); 15924 SDValue Cond = N->getOperand(0); 15925 // Get the LHS/RHS of the select. 15926 SDValue LHS = N->getOperand(1); 15927 SDValue RHS = N->getOperand(2); 15928 EVT VT = LHS.getValueType(); 15929 15930 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 15931 // instructions match the semantics of the common C idiom x<y?x:y but not 15932 // x<=y?x:y, because of how they handle negative zero (which can be 15933 // ignored in unsafe-math mode). 15934 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 15935 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 15936 (Subtarget->hasSSE2() || 15937 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 15938 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15939 15940 unsigned Opcode = 0; 15941 // Check for x CC y ? x : y. 15942 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15943 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15944 switch (CC) { 15945 default: break; 15946 case ISD::SETULT: 15947 // Converting this to a min would handle NaNs incorrectly, and swapping 15948 // the operands would cause it to handle comparisons between positive 15949 // and negative zero incorrectly. 15950 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15951 if (!DAG.getTarget().Options.UnsafeFPMath && 15952 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15953 break; 15954 std::swap(LHS, RHS); 15955 } 15956 Opcode = X86ISD::FMIN; 15957 break; 15958 case ISD::SETOLE: 15959 // Converting this to a min would handle comparisons between positive 15960 // and negative zero incorrectly. 15961 if (!DAG.getTarget().Options.UnsafeFPMath && 15962 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15963 break; 15964 Opcode = X86ISD::FMIN; 15965 break; 15966 case ISD::SETULE: 15967 // Converting this to a min would handle both negative zeros and NaNs 15968 // incorrectly, but we can swap the operands to fix both. 15969 std::swap(LHS, RHS); 15970 case ISD::SETOLT: 15971 case ISD::SETLT: 15972 case ISD::SETLE: 15973 Opcode = X86ISD::FMIN; 15974 break; 15975 15976 case ISD::SETOGE: 15977 // Converting this to a max would handle comparisons between positive 15978 // and negative zero incorrectly. 15979 if (!DAG.getTarget().Options.UnsafeFPMath && 15980 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15981 break; 15982 Opcode = X86ISD::FMAX; 15983 break; 15984 case ISD::SETUGT: 15985 // Converting this to a max would handle NaNs incorrectly, and swapping 15986 // the operands would cause it to handle comparisons between positive 15987 // and negative zero incorrectly. 15988 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15989 if (!DAG.getTarget().Options.UnsafeFPMath && 15990 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15991 break; 15992 std::swap(LHS, RHS); 15993 } 15994 Opcode = X86ISD::FMAX; 15995 break; 15996 case ISD::SETUGE: 15997 // Converting this to a max would handle both negative zeros and NaNs 15998 // incorrectly, but we can swap the operands to fix both. 15999 std::swap(LHS, RHS); 16000 case ISD::SETOGT: 16001 case ISD::SETGT: 16002 case ISD::SETGE: 16003 Opcode = X86ISD::FMAX; 16004 break; 16005 } 16006 // Check for x CC y ? y : x -- a min/max with reversed arms. 16007 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 16008 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 16009 switch (CC) { 16010 default: break; 16011 case ISD::SETOGE: 16012 // Converting this to a min would handle comparisons between positive 16013 // and negative zero incorrectly, and swapping the operands would 16014 // cause it to handle NaNs incorrectly. 16015 if (!DAG.getTarget().Options.UnsafeFPMath && 16016 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 16017 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 16018 break; 16019 std::swap(LHS, RHS); 16020 } 16021 Opcode = X86ISD::FMIN; 16022 break; 16023 case ISD::SETUGT: 16024 // Converting this to a min would handle NaNs incorrectly. 16025 if (!DAG.getTarget().Options.UnsafeFPMath && 16026 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 16027 break; 16028 Opcode = X86ISD::FMIN; 16029 break; 16030 case ISD::SETUGE: 16031 // Converting this to a min would handle both negative zeros and NaNs 16032 // incorrectly, but we can swap the operands to fix both. 16033 std::swap(LHS, RHS); 16034 case ISD::SETOGT: 16035 case ISD::SETGT: 16036 case ISD::SETGE: 16037 Opcode = X86ISD::FMIN; 16038 break; 16039 16040 case ISD::SETULT: 16041 // Converting this to a max would handle NaNs incorrectly. 16042 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 16043 break; 16044 Opcode = X86ISD::FMAX; 16045 break; 16046 case ISD::SETOLE: 16047 // Converting this to a max would handle comparisons between positive 16048 // and negative zero incorrectly, and swapping the operands would 16049 // cause it to handle NaNs incorrectly. 16050 if (!DAG.getTarget().Options.UnsafeFPMath && 16051 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 16052 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 16053 break; 16054 std::swap(LHS, RHS); 16055 } 16056 Opcode = X86ISD::FMAX; 16057 break; 16058 case ISD::SETULE: 16059 // Converting this to a max would handle both negative zeros and NaNs 16060 // incorrectly, but we can swap the operands to fix both. 16061 std::swap(LHS, RHS); 16062 case ISD::SETOLT: 16063 case ISD::SETLT: 16064 case ISD::SETLE: 16065 Opcode = X86ISD::FMAX; 16066 break; 16067 } 16068 } 16069 16070 if (Opcode) 16071 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 16072 } 16073 16074 // If this is a select between two integer constants, try to do some 16075 // optimizations. 16076 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 16077 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 16078 // Don't do this for crazy integer types. 16079 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 16080 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 16081 // so that TrueC (the true value) is larger than FalseC. 16082 bool NeedsCondInvert = false; 16083 16084 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 16085 // Efficiently invertible. 16086 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 16087 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 16088 isa<ConstantSDNode>(Cond.getOperand(1))))) { 16089 NeedsCondInvert = true; 16090 std::swap(TrueC, FalseC); 16091 } 16092 16093 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 16094 if (FalseC->getAPIntValue() == 0 && 16095 TrueC->getAPIntValue().isPowerOf2()) { 16096 if (NeedsCondInvert) // Invert the condition if needed. 16097 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 16098 DAG.getConstant(1, Cond.getValueType())); 16099 16100 // Zero extend the condition if needed. 16101 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 16102 16103 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 16104 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 16105 DAG.getConstant(ShAmt, MVT::i8)); 16106 } 16107 16108 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 16109 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 16110 if (NeedsCondInvert) // Invert the condition if needed. 16111 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 16112 DAG.getConstant(1, Cond.getValueType())); 16113 16114 // Zero extend the condition if needed. 16115 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 16116 FalseC->getValueType(0), Cond); 16117 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16118 SDValue(FalseC, 0)); 16119 } 16120 16121 // Optimize cases that will turn into an LEA instruction. This requires 16122 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 16123 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 16124 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 16125 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 16126 16127 bool isFastMultiplier = false; 16128 if (Diff < 10) { 16129 switch ((unsigned char)Diff) { 16130 default: break; 16131 case 1: // result = add base, cond 16132 case 2: // result = lea base( , cond*2) 16133 case 3: // result = lea base(cond, cond*2) 16134 case 4: // result = lea base( , cond*4) 16135 case 5: // result = lea base(cond, cond*4) 16136 case 8: // result = lea base( , cond*8) 16137 case 9: // result = lea base(cond, cond*8) 16138 isFastMultiplier = true; 16139 break; 16140 } 16141 } 16142 16143 if (isFastMultiplier) { 16144 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 16145 if (NeedsCondInvert) // Invert the condition if needed. 16146 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 16147 DAG.getConstant(1, Cond.getValueType())); 16148 16149 // Zero extend the condition if needed. 16150 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 16151 Cond); 16152 // Scale the condition by the difference. 16153 if (Diff != 1) 16154 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 16155 DAG.getConstant(Diff, Cond.getValueType())); 16156 16157 // Add the base if non-zero. 16158 if (FalseC->getAPIntValue() != 0) 16159 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16160 SDValue(FalseC, 0)); 16161 return Cond; 16162 } 16163 } 16164 } 16165 } 16166 16167 // Canonicalize max and min: 16168 // (x > y) ? x : y -> (x >= y) ? x : y 16169 // (x < y) ? x : y -> (x <= y) ? x : y 16170 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates 16171 // the need for an extra compare 16172 // against zero. e.g. 16173 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0 16174 // subl %esi, %edi 16175 // testl %edi, %edi 16176 // movl $0, %eax 16177 // cmovgl %edi, %eax 16178 // => 16179 // xorl %eax, %eax 16180 // subl %esi, $edi 16181 // cmovsl %eax, %edi 16182 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC && 16183 DAG.isEqualTo(LHS, Cond.getOperand(0)) && 16184 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 16185 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16186 switch (CC) { 16187 default: break; 16188 case ISD::SETLT: 16189 case ISD::SETGT: { 16190 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE; 16191 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), 16192 Cond.getOperand(0), Cond.getOperand(1), NewCC); 16193 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS); 16194 } 16195 } 16196 } 16197 16198 // Match VSELECTs into subs with unsigned saturation. 16199 if (!DCI.isBeforeLegalize() && 16200 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC && 16201 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors. 16202 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) || 16203 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) { 16204 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 16205 16206 // Check if one of the arms of the VSELECT is a zero vector. If it's on the 16207 // left side invert the predicate to simplify logic below. 16208 SDValue Other; 16209 if (ISD::isBuildVectorAllZeros(LHS.getNode())) { 16210 Other = RHS; 16211 CC = ISD::getSetCCInverse(CC, true); 16212 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) { 16213 Other = LHS; 16214 } 16215 16216 if (Other.getNode() && Other->getNumOperands() == 2 && 16217 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) { 16218 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1); 16219 SDValue CondRHS = Cond->getOperand(1); 16220 16221 // Look for a general sub with unsigned saturation first. 16222 // x >= y ? x-y : 0 --> subus x, y 16223 // x > y ? x-y : 0 --> subus x, y 16224 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) && 16225 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS)) 16226 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 16227 16228 // If the RHS is a constant we have to reverse the const canonicalization. 16229 // x > C-1 ? x+-C : 0 --> subus x, C 16230 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD && 16231 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) { 16232 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 16233 if (CondRHS.getConstantOperandVal(0) == -A-1) 16234 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, 16235 DAG.getConstant(-A, VT)); 16236 } 16237 16238 // Another special case: If C was a sign bit, the sub has been 16239 // canonicalized into a xor. 16240 // FIXME: Would it be better to use ComputeMaskedBits to determine whether 16241 // it's safe to decanonicalize the xor? 16242 // x s< 0 ? x^C : 0 --> subus x, C 16243 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR && 16244 ISD::isBuildVectorAllZeros(CondRHS.getNode()) && 16245 isSplatVector(OpRHS.getNode())) { 16246 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 16247 if (A.isSignBit()) 16248 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 16249 } 16250 } 16251 } 16252 16253 // Try to match a min/max vector operation. 16254 if (!DCI.isBeforeLegalize() && 16255 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) 16256 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget)) 16257 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS); 16258 16259 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*. 16260 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT && 16261 Cond.getOpcode() == ISD::SETCC) { 16262 16263 assert(Cond.getValueType().isVector() && 16264 "vector select expects a vector selector!"); 16265 16266 EVT IntVT = Cond.getValueType(); 16267 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode()); 16268 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 16269 16270 if (!TValIsAllOnes && !FValIsAllZeros) { 16271 // Try invert the condition if true value is not all 1s and false value 16272 // is not all 0s. 16273 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode()); 16274 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode()); 16275 16276 if (TValIsAllZeros || FValIsAllOnes) { 16277 SDValue CC = Cond.getOperand(2); 16278 ISD::CondCode NewCC = 16279 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 16280 Cond.getOperand(0).getValueType().isInteger()); 16281 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC); 16282 std::swap(LHS, RHS); 16283 TValIsAllOnes = FValIsAllOnes; 16284 FValIsAllZeros = TValIsAllZeros; 16285 } 16286 } 16287 16288 if (TValIsAllOnes || FValIsAllZeros) { 16289 SDValue Ret; 16290 16291 if (TValIsAllOnes && FValIsAllZeros) 16292 Ret = Cond; 16293 else if (TValIsAllOnes) 16294 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond, 16295 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS)); 16296 else if (FValIsAllZeros) 16297 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond, 16298 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS)); 16299 16300 return DAG.getNode(ISD::BITCAST, DL, VT, Ret); 16301 } 16302 } 16303 16304 // If we know that this node is legal then we know that it is going to be 16305 // matched by one of the SSE/AVX BLEND instructions. These instructions only 16306 // depend on the highest bit in each word. Try to use SimplifyDemandedBits 16307 // to simplify previous instructions. 16308 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16309 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() && 16310 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) { 16311 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits(); 16312 16313 // Don't optimize vector selects that map to mask-registers. 16314 if (BitWidth == 1) 16315 return SDValue(); 16316 16317 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size"); 16318 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1); 16319 16320 APInt KnownZero, KnownOne; 16321 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 16322 DCI.isBeforeLegalizeOps()); 16323 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) || 16324 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO)) 16325 DCI.CommitTargetLoweringOpt(TLO); 16326 } 16327 16328 return SDValue(); 16329 } 16330 16331 // Check whether a boolean test is testing a boolean value generated by 16332 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition 16333 // code. 16334 // 16335 // Simplify the following patterns: 16336 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or 16337 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ) 16338 // to (Op EFLAGS Cond) 16339 // 16340 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or 16341 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ) 16342 // to (Op EFLAGS !Cond) 16343 // 16344 // where Op could be BRCOND or CMOV. 16345 // 16346 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) { 16347 // Quit if not CMP and SUB with its value result used. 16348 if (Cmp.getOpcode() != X86ISD::CMP && 16349 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0))) 16350 return SDValue(); 16351 16352 // Quit if not used as a boolean value. 16353 if (CC != X86::COND_E && CC != X86::COND_NE) 16354 return SDValue(); 16355 16356 // Check CMP operands. One of them should be 0 or 1 and the other should be 16357 // an SetCC or extended from it. 16358 SDValue Op1 = Cmp.getOperand(0); 16359 SDValue Op2 = Cmp.getOperand(1); 16360 16361 SDValue SetCC; 16362 const ConstantSDNode* C = 0; 16363 bool needOppositeCond = (CC == X86::COND_E); 16364 bool checkAgainstTrue = false; // Is it a comparison against 1? 16365 16366 if ((C = dyn_cast<ConstantSDNode>(Op1))) 16367 SetCC = Op2; 16368 else if ((C = dyn_cast<ConstantSDNode>(Op2))) 16369 SetCC = Op1; 16370 else // Quit if all operands are not constants. 16371 return SDValue(); 16372 16373 if (C->getZExtValue() == 1) { 16374 needOppositeCond = !needOppositeCond; 16375 checkAgainstTrue = true; 16376 } else if (C->getZExtValue() != 0) 16377 // Quit if the constant is neither 0 or 1. 16378 return SDValue(); 16379 16380 bool truncatedToBoolWithAnd = false; 16381 // Skip (zext $x), (trunc $x), or (and $x, 1) node. 16382 while (SetCC.getOpcode() == ISD::ZERO_EXTEND || 16383 SetCC.getOpcode() == ISD::TRUNCATE || 16384 SetCC.getOpcode() == ISD::AND) { 16385 if (SetCC.getOpcode() == ISD::AND) { 16386 int OpIdx = -1; 16387 ConstantSDNode *CS; 16388 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) && 16389 CS->getZExtValue() == 1) 16390 OpIdx = 1; 16391 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) && 16392 CS->getZExtValue() == 1) 16393 OpIdx = 0; 16394 if (OpIdx == -1) 16395 break; 16396 SetCC = SetCC.getOperand(OpIdx); 16397 truncatedToBoolWithAnd = true; 16398 } else 16399 SetCC = SetCC.getOperand(0); 16400 } 16401 16402 switch (SetCC.getOpcode()) { 16403 case X86ISD::SETCC_CARRY: 16404 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to 16405 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1, 16406 // i.e. it's a comparison against true but the result of SETCC_CARRY is not 16407 // truncated to i1 using 'and'. 16408 if (checkAgainstTrue && !truncatedToBoolWithAnd) 16409 break; 16410 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && 16411 "Invalid use of SETCC_CARRY!"); 16412 // FALL THROUGH 16413 case X86ISD::SETCC: 16414 // Set the condition code or opposite one if necessary. 16415 CC = X86::CondCode(SetCC.getConstantOperandVal(0)); 16416 if (needOppositeCond) 16417 CC = X86::GetOppositeBranchCondition(CC); 16418 return SetCC.getOperand(1); 16419 case X86ISD::CMOV: { 16420 // Check whether false/true value has canonical one, i.e. 0 or 1. 16421 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0)); 16422 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1)); 16423 // Quit if true value is not a constant. 16424 if (!TVal) 16425 return SDValue(); 16426 // Quit if false value is not a constant. 16427 if (!FVal) { 16428 SDValue Op = SetCC.getOperand(0); 16429 // Skip 'zext' or 'trunc' node. 16430 if (Op.getOpcode() == ISD::ZERO_EXTEND || 16431 Op.getOpcode() == ISD::TRUNCATE) 16432 Op = Op.getOperand(0); 16433 // A special case for rdrand/rdseed, where 0 is set if false cond is 16434 // found. 16435 if ((Op.getOpcode() != X86ISD::RDRAND && 16436 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0) 16437 return SDValue(); 16438 } 16439 // Quit if false value is not the constant 0 or 1. 16440 bool FValIsFalse = true; 16441 if (FVal && FVal->getZExtValue() != 0) { 16442 if (FVal->getZExtValue() != 1) 16443 return SDValue(); 16444 // If FVal is 1, opposite cond is needed. 16445 needOppositeCond = !needOppositeCond; 16446 FValIsFalse = false; 16447 } 16448 // Quit if TVal is not the constant opposite of FVal. 16449 if (FValIsFalse && TVal->getZExtValue() != 1) 16450 return SDValue(); 16451 if (!FValIsFalse && TVal->getZExtValue() != 0) 16452 return SDValue(); 16453 CC = X86::CondCode(SetCC.getConstantOperandVal(2)); 16454 if (needOppositeCond) 16455 CC = X86::GetOppositeBranchCondition(CC); 16456 return SetCC.getOperand(3); 16457 } 16458 } 16459 16460 return SDValue(); 16461 } 16462 16463 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 16464 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 16465 TargetLowering::DAGCombinerInfo &DCI, 16466 const X86Subtarget *Subtarget) { 16467 SDLoc DL(N); 16468 16469 // If the flag operand isn't dead, don't touch this CMOV. 16470 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 16471 return SDValue(); 16472 16473 SDValue FalseOp = N->getOperand(0); 16474 SDValue TrueOp = N->getOperand(1); 16475 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 16476 SDValue Cond = N->getOperand(3); 16477 16478 if (CC == X86::COND_E || CC == X86::COND_NE) { 16479 switch (Cond.getOpcode()) { 16480 default: break; 16481 case X86ISD::BSR: 16482 case X86ISD::BSF: 16483 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 16484 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 16485 return (CC == X86::COND_E) ? FalseOp : TrueOp; 16486 } 16487 } 16488 16489 SDValue Flags; 16490 16491 Flags = checkBoolTestSetCCCombine(Cond, CC); 16492 if (Flags.getNode() && 16493 // Extra check as FCMOV only supports a subset of X86 cond. 16494 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) { 16495 SDValue Ops[] = { FalseOp, TrueOp, 16496 DAG.getConstant(CC, MVT::i8), Flags }; 16497 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), 16498 Ops, array_lengthof(Ops)); 16499 } 16500 16501 // If this is a select between two integer constants, try to do some 16502 // optimizations. Note that the operands are ordered the opposite of SELECT 16503 // operands. 16504 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 16505 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 16506 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 16507 // larger than FalseC (the false value). 16508 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 16509 CC = X86::GetOppositeBranchCondition(CC); 16510 std::swap(TrueC, FalseC); 16511 std::swap(TrueOp, FalseOp); 16512 } 16513 16514 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 16515 // This is efficient for any integer data type (including i8/i16) and 16516 // shift amount. 16517 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 16518 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16519 DAG.getConstant(CC, MVT::i8), Cond); 16520 16521 // Zero extend the condition if needed. 16522 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 16523 16524 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 16525 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 16526 DAG.getConstant(ShAmt, MVT::i8)); 16527 if (N->getNumValues() == 2) // Dead flag value? 16528 return DCI.CombineTo(N, Cond, SDValue()); 16529 return Cond; 16530 } 16531 16532 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 16533 // for any integer data type, including i8/i16. 16534 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 16535 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16536 DAG.getConstant(CC, MVT::i8), Cond); 16537 16538 // Zero extend the condition if needed. 16539 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 16540 FalseC->getValueType(0), Cond); 16541 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16542 SDValue(FalseC, 0)); 16543 16544 if (N->getNumValues() == 2) // Dead flag value? 16545 return DCI.CombineTo(N, Cond, SDValue()); 16546 return Cond; 16547 } 16548 16549 // Optimize cases that will turn into an LEA instruction. This requires 16550 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 16551 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 16552 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 16553 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 16554 16555 bool isFastMultiplier = false; 16556 if (Diff < 10) { 16557 switch ((unsigned char)Diff) { 16558 default: break; 16559 case 1: // result = add base, cond 16560 case 2: // result = lea base( , cond*2) 16561 case 3: // result = lea base(cond, cond*2) 16562 case 4: // result = lea base( , cond*4) 16563 case 5: // result = lea base(cond, cond*4) 16564 case 8: // result = lea base( , cond*8) 16565 case 9: // result = lea base(cond, cond*8) 16566 isFastMultiplier = true; 16567 break; 16568 } 16569 } 16570 16571 if (isFastMultiplier) { 16572 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 16573 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16574 DAG.getConstant(CC, MVT::i8), Cond); 16575 // Zero extend the condition if needed. 16576 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 16577 Cond); 16578 // Scale the condition by the difference. 16579 if (Diff != 1) 16580 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 16581 DAG.getConstant(Diff, Cond.getValueType())); 16582 16583 // Add the base if non-zero. 16584 if (FalseC->getAPIntValue() != 0) 16585 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16586 SDValue(FalseC, 0)); 16587 if (N->getNumValues() == 2) // Dead flag value? 16588 return DCI.CombineTo(N, Cond, SDValue()); 16589 return Cond; 16590 } 16591 } 16592 } 16593 } 16594 16595 // Handle these cases: 16596 // (select (x != c), e, c) -> select (x != c), e, x), 16597 // (select (x == c), c, e) -> select (x == c), x, e) 16598 // where the c is an integer constant, and the "select" is the combination 16599 // of CMOV and CMP. 16600 // 16601 // The rationale for this change is that the conditional-move from a constant 16602 // needs two instructions, however, conditional-move from a register needs 16603 // only one instruction. 16604 // 16605 // CAVEAT: By replacing a constant with a symbolic value, it may obscure 16606 // some instruction-combining opportunities. This opt needs to be 16607 // postponed as late as possible. 16608 // 16609 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) { 16610 // the DCI.xxxx conditions are provided to postpone the optimization as 16611 // late as possible. 16612 16613 ConstantSDNode *CmpAgainst = 0; 16614 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) && 16615 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) && 16616 !isa<ConstantSDNode>(Cond.getOperand(0))) { 16617 16618 if (CC == X86::COND_NE && 16619 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) { 16620 CC = X86::GetOppositeBranchCondition(CC); 16621 std::swap(TrueOp, FalseOp); 16622 } 16623 16624 if (CC == X86::COND_E && 16625 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) { 16626 SDValue Ops[] = { FalseOp, Cond.getOperand(0), 16627 DAG.getConstant(CC, MVT::i8), Cond }; 16628 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops, 16629 array_lengthof(Ops)); 16630 } 16631 } 16632 } 16633 16634 return SDValue(); 16635 } 16636 16637 /// PerformMulCombine - Optimize a single multiply with constant into two 16638 /// in order to implement it with two cheaper instructions, e.g. 16639 /// LEA + SHL, LEA + LEA. 16640 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 16641 TargetLowering::DAGCombinerInfo &DCI) { 16642 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 16643 return SDValue(); 16644 16645 EVT VT = N->getValueType(0); 16646 if (VT != MVT::i64) 16647 return SDValue(); 16648 16649 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16650 if (!C) 16651 return SDValue(); 16652 uint64_t MulAmt = C->getZExtValue(); 16653 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 16654 return SDValue(); 16655 16656 uint64_t MulAmt1 = 0; 16657 uint64_t MulAmt2 = 0; 16658 if ((MulAmt % 9) == 0) { 16659 MulAmt1 = 9; 16660 MulAmt2 = MulAmt / 9; 16661 } else if ((MulAmt % 5) == 0) { 16662 MulAmt1 = 5; 16663 MulAmt2 = MulAmt / 5; 16664 } else if ((MulAmt % 3) == 0) { 16665 MulAmt1 = 3; 16666 MulAmt2 = MulAmt / 3; 16667 } 16668 if (MulAmt2 && 16669 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 16670 SDLoc DL(N); 16671 16672 if (isPowerOf2_64(MulAmt2) && 16673 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 16674 // If second multiplifer is pow2, issue it first. We want the multiply by 16675 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 16676 // is an add. 16677 std::swap(MulAmt1, MulAmt2); 16678 16679 SDValue NewMul; 16680 if (isPowerOf2_64(MulAmt1)) 16681 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16682 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 16683 else 16684 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 16685 DAG.getConstant(MulAmt1, VT)); 16686 16687 if (isPowerOf2_64(MulAmt2)) 16688 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 16689 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 16690 else 16691 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 16692 DAG.getConstant(MulAmt2, VT)); 16693 16694 // Do not add new nodes to DAG combiner worklist. 16695 DCI.CombineTo(N, NewMul, false); 16696 } 16697 return SDValue(); 16698 } 16699 16700 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 16701 SDValue N0 = N->getOperand(0); 16702 SDValue N1 = N->getOperand(1); 16703 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 16704 EVT VT = N0.getValueType(); 16705 16706 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 16707 // since the result of setcc_c is all zero's or all ones. 16708 if (VT.isInteger() && !VT.isVector() && 16709 N1C && N0.getOpcode() == ISD::AND && 16710 N0.getOperand(1).getOpcode() == ISD::Constant) { 16711 SDValue N00 = N0.getOperand(0); 16712 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 16713 ((N00.getOpcode() == ISD::ANY_EXTEND || 16714 N00.getOpcode() == ISD::ZERO_EXTEND) && 16715 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 16716 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 16717 APInt ShAmt = N1C->getAPIntValue(); 16718 Mask = Mask.shl(ShAmt); 16719 if (Mask != 0) 16720 return DAG.getNode(ISD::AND, SDLoc(N), VT, 16721 N00, DAG.getConstant(Mask, VT)); 16722 } 16723 } 16724 16725 // Hardware support for vector shifts is sparse which makes us scalarize the 16726 // vector operations in many cases. Also, on sandybridge ADD is faster than 16727 // shl. 16728 // (shl V, 1) -> add V,V 16729 if (isSplatVector(N1.getNode())) { 16730 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 16731 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 16732 // We shift all of the values by one. In many cases we do not have 16733 // hardware support for this operation. This is better expressed as an ADD 16734 // of two values. 16735 if (N1C && (1 == N1C->getZExtValue())) { 16736 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0); 16737 } 16738 } 16739 16740 return SDValue(); 16741 } 16742 16743 /// \brief Returns a vector of 0s if the node in input is a vector logical 16744 /// shift by a constant amount which is known to be bigger than or equal 16745 /// to the vector element size in bits. 16746 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG, 16747 const X86Subtarget *Subtarget) { 16748 EVT VT = N->getValueType(0); 16749 16750 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 && 16751 (!Subtarget->hasInt256() || 16752 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16))) 16753 return SDValue(); 16754 16755 SDValue Amt = N->getOperand(1); 16756 SDLoc DL(N); 16757 if (isSplatVector(Amt.getNode())) { 16758 SDValue SclrAmt = Amt->getOperand(0); 16759 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 16760 APInt ShiftAmt = C->getAPIntValue(); 16761 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits(); 16762 16763 // SSE2/AVX2 logical shifts always return a vector of 0s 16764 // if the shift amount is bigger than or equal to 16765 // the element size. The constant shift amount will be 16766 // encoded as a 8-bit immediate. 16767 if (ShiftAmt.trunc(8).uge(MaxAmount)) 16768 return getZeroVector(VT, Subtarget, DAG, DL); 16769 } 16770 } 16771 16772 return SDValue(); 16773 } 16774 16775 /// PerformShiftCombine - Combine shifts. 16776 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 16777 TargetLowering::DAGCombinerInfo &DCI, 16778 const X86Subtarget *Subtarget) { 16779 if (N->getOpcode() == ISD::SHL) { 16780 SDValue V = PerformSHLCombine(N, DAG); 16781 if (V.getNode()) return V; 16782 } 16783 16784 if (N->getOpcode() != ISD::SRA) { 16785 // Try to fold this logical shift into a zero vector. 16786 SDValue V = performShiftToAllZeros(N, DAG, Subtarget); 16787 if (V.getNode()) return V; 16788 } 16789 16790 return SDValue(); 16791 } 16792 16793 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 16794 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS 16795 // and friends. Likewise for OR -> CMPNEQSS. 16796 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 16797 TargetLowering::DAGCombinerInfo &DCI, 16798 const X86Subtarget *Subtarget) { 16799 unsigned opcode; 16800 16801 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 16802 // we're requiring SSE2 for both. 16803 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 16804 SDValue N0 = N->getOperand(0); 16805 SDValue N1 = N->getOperand(1); 16806 SDValue CMP0 = N0->getOperand(1); 16807 SDValue CMP1 = N1->getOperand(1); 16808 SDLoc DL(N); 16809 16810 // The SETCCs should both refer to the same CMP. 16811 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 16812 return SDValue(); 16813 16814 SDValue CMP00 = CMP0->getOperand(0); 16815 SDValue CMP01 = CMP0->getOperand(1); 16816 EVT VT = CMP00.getValueType(); 16817 16818 if (VT == MVT::f32 || VT == MVT::f64) { 16819 bool ExpectingFlags = false; 16820 // Check for any users that want flags: 16821 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 16822 !ExpectingFlags && UI != UE; ++UI) 16823 switch (UI->getOpcode()) { 16824 default: 16825 case ISD::BR_CC: 16826 case ISD::BRCOND: 16827 case ISD::SELECT: 16828 ExpectingFlags = true; 16829 break; 16830 case ISD::CopyToReg: 16831 case ISD::SIGN_EXTEND: 16832 case ISD::ZERO_EXTEND: 16833 case ISD::ANY_EXTEND: 16834 break; 16835 } 16836 16837 if (!ExpectingFlags) { 16838 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 16839 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 16840 16841 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 16842 X86::CondCode tmp = cc0; 16843 cc0 = cc1; 16844 cc1 = tmp; 16845 } 16846 16847 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 16848 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 16849 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 16850 X86ISD::NodeType NTOperator = is64BitFP ? 16851 X86ISD::FSETCCsd : X86ISD::FSETCCss; 16852 // FIXME: need symbolic constants for these magic numbers. 16853 // See X86ATTInstPrinter.cpp:printSSECC(). 16854 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 16855 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 16856 DAG.getConstant(x86cc, MVT::i8)); 16857 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 16858 OnesOrZeroesF); 16859 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 16860 DAG.getConstant(1, MVT::i32)); 16861 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 16862 return OneBitOfTruth; 16863 } 16864 } 16865 } 16866 } 16867 return SDValue(); 16868 } 16869 16870 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 16871 /// so it can be folded inside ANDNP. 16872 static bool CanFoldXORWithAllOnes(const SDNode *N) { 16873 EVT VT = N->getValueType(0); 16874 16875 // Match direct AllOnes for 128 and 256-bit vectors 16876 if (ISD::isBuildVectorAllOnes(N)) 16877 return true; 16878 16879 // Look through a bit convert. 16880 if (N->getOpcode() == ISD::BITCAST) 16881 N = N->getOperand(0).getNode(); 16882 16883 // Sometimes the operand may come from a insert_subvector building a 256-bit 16884 // allones vector 16885 if (VT.is256BitVector() && 16886 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 16887 SDValue V1 = N->getOperand(0); 16888 SDValue V2 = N->getOperand(1); 16889 16890 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 16891 V1.getOperand(0).getOpcode() == ISD::UNDEF && 16892 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 16893 ISD::isBuildVectorAllOnes(V2.getNode())) 16894 return true; 16895 } 16896 16897 return false; 16898 } 16899 16900 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized 16901 // register. In most cases we actually compare or select YMM-sized registers 16902 // and mixing the two types creates horrible code. This method optimizes 16903 // some of the transition sequences. 16904 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG, 16905 TargetLowering::DAGCombinerInfo &DCI, 16906 const X86Subtarget *Subtarget) { 16907 EVT VT = N->getValueType(0); 16908 if (!VT.is256BitVector()) 16909 return SDValue(); 16910 16911 assert((N->getOpcode() == ISD::ANY_EXTEND || 16912 N->getOpcode() == ISD::ZERO_EXTEND || 16913 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node"); 16914 16915 SDValue Narrow = N->getOperand(0); 16916 EVT NarrowVT = Narrow->getValueType(0); 16917 if (!NarrowVT.is128BitVector()) 16918 return SDValue(); 16919 16920 if (Narrow->getOpcode() != ISD::XOR && 16921 Narrow->getOpcode() != ISD::AND && 16922 Narrow->getOpcode() != ISD::OR) 16923 return SDValue(); 16924 16925 SDValue N0 = Narrow->getOperand(0); 16926 SDValue N1 = Narrow->getOperand(1); 16927 SDLoc DL(Narrow); 16928 16929 // The Left side has to be a trunc. 16930 if (N0.getOpcode() != ISD::TRUNCATE) 16931 return SDValue(); 16932 16933 // The type of the truncated inputs. 16934 EVT WideVT = N0->getOperand(0)->getValueType(0); 16935 if (WideVT != VT) 16936 return SDValue(); 16937 16938 // The right side has to be a 'trunc' or a constant vector. 16939 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE; 16940 bool RHSConst = (isSplatVector(N1.getNode()) && 16941 isa<ConstantSDNode>(N1->getOperand(0))); 16942 if (!RHSTrunc && !RHSConst) 16943 return SDValue(); 16944 16945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16946 16947 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT)) 16948 return SDValue(); 16949 16950 // Set N0 and N1 to hold the inputs to the new wide operation. 16951 N0 = N0->getOperand(0); 16952 if (RHSConst) { 16953 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(), 16954 N1->getOperand(0)); 16955 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1); 16956 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size()); 16957 } else if (RHSTrunc) { 16958 N1 = N1->getOperand(0); 16959 } 16960 16961 // Generate the wide operation. 16962 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1); 16963 unsigned Opcode = N->getOpcode(); 16964 switch (Opcode) { 16965 case ISD::ANY_EXTEND: 16966 return Op; 16967 case ISD::ZERO_EXTEND: { 16968 unsigned InBits = NarrowVT.getScalarType().getSizeInBits(); 16969 APInt Mask = APInt::getAllOnesValue(InBits); 16970 Mask = Mask.zext(VT.getScalarType().getSizeInBits()); 16971 return DAG.getNode(ISD::AND, DL, VT, 16972 Op, DAG.getConstant(Mask, VT)); 16973 } 16974 case ISD::SIGN_EXTEND: 16975 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, 16976 Op, DAG.getValueType(NarrowVT)); 16977 default: 16978 llvm_unreachable("Unexpected opcode"); 16979 } 16980 } 16981 16982 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 16983 TargetLowering::DAGCombinerInfo &DCI, 16984 const X86Subtarget *Subtarget) { 16985 EVT VT = N->getValueType(0); 16986 if (DCI.isBeforeLegalizeOps()) 16987 return SDValue(); 16988 16989 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 16990 if (R.getNode()) 16991 return R; 16992 16993 // Create BLSI, and BLSR instructions 16994 // BLSI is X & (-X) 16995 // BLSR is X & (X-1) 16996 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 16997 SDValue N0 = N->getOperand(0); 16998 SDValue N1 = N->getOperand(1); 16999 SDLoc DL(N); 17000 17001 // Check LHS for neg 17002 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 17003 isZero(N0.getOperand(0))) 17004 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 17005 17006 // Check RHS for neg 17007 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 17008 isZero(N1.getOperand(0))) 17009 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 17010 17011 // Check LHS for X-1 17012 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 17013 isAllOnes(N0.getOperand(1))) 17014 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 17015 17016 // Check RHS for X-1 17017 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 17018 isAllOnes(N1.getOperand(1))) 17019 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 17020 17021 return SDValue(); 17022 } 17023 17024 // Want to form ANDNP nodes: 17025 // 1) In the hopes of then easily combining them with OR and AND nodes 17026 // to form PBLEND/PSIGN. 17027 // 2) To match ANDN packed intrinsics 17028 if (VT != MVT::v2i64 && VT != MVT::v4i64) 17029 return SDValue(); 17030 17031 SDValue N0 = N->getOperand(0); 17032 SDValue N1 = N->getOperand(1); 17033 SDLoc DL(N); 17034 17035 // Check LHS for vnot 17036 if (N0.getOpcode() == ISD::XOR && 17037 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 17038 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 17039 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 17040 17041 // Check RHS for vnot 17042 if (N1.getOpcode() == ISD::XOR && 17043 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 17044 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 17045 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 17046 17047 return SDValue(); 17048 } 17049 17050 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 17051 TargetLowering::DAGCombinerInfo &DCI, 17052 const X86Subtarget *Subtarget) { 17053 EVT VT = N->getValueType(0); 17054 if (DCI.isBeforeLegalizeOps()) 17055 return SDValue(); 17056 17057 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 17058 if (R.getNode()) 17059 return R; 17060 17061 SDValue N0 = N->getOperand(0); 17062 SDValue N1 = N->getOperand(1); 17063 17064 // look for psign/blend 17065 if (VT == MVT::v2i64 || VT == MVT::v4i64) { 17066 if (!Subtarget->hasSSSE3() || 17067 (VT == MVT::v4i64 && !Subtarget->hasInt256())) 17068 return SDValue(); 17069 17070 // Canonicalize pandn to RHS 17071 if (N0.getOpcode() == X86ISD::ANDNP) 17072 std::swap(N0, N1); 17073 // or (and (m, y), (pandn m, x)) 17074 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 17075 SDValue Mask = N1.getOperand(0); 17076 SDValue X = N1.getOperand(1); 17077 SDValue Y; 17078 if (N0.getOperand(0) == Mask) 17079 Y = N0.getOperand(1); 17080 if (N0.getOperand(1) == Mask) 17081 Y = N0.getOperand(0); 17082 17083 // Check to see if the mask appeared in both the AND and ANDNP and 17084 if (!Y.getNode()) 17085 return SDValue(); 17086 17087 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 17088 // Look through mask bitcast. 17089 if (Mask.getOpcode() == ISD::BITCAST) 17090 Mask = Mask.getOperand(0); 17091 if (X.getOpcode() == ISD::BITCAST) 17092 X = X.getOperand(0); 17093 if (Y.getOpcode() == ISD::BITCAST) 17094 Y = Y.getOperand(0); 17095 17096 EVT MaskVT = Mask.getValueType(); 17097 17098 // Validate that the Mask operand is a vector sra node. 17099 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 17100 // there is no psrai.b 17101 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 17102 unsigned SraAmt = ~0; 17103 if (Mask.getOpcode() == ISD::SRA) { 17104 SDValue Amt = Mask.getOperand(1); 17105 if (isSplatVector(Amt.getNode())) { 17106 SDValue SclrAmt = Amt->getOperand(0); 17107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) 17108 SraAmt = C->getZExtValue(); 17109 } 17110 } else if (Mask.getOpcode() == X86ISD::VSRAI) { 17111 SDValue SraC = Mask.getOperand(1); 17112 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 17113 } 17114 if ((SraAmt + 1) != EltBits) 17115 return SDValue(); 17116 17117 SDLoc DL(N); 17118 17119 // Now we know we at least have a plendvb with the mask val. See if 17120 // we can form a psignb/w/d. 17121 // psign = x.type == y.type == mask.type && y = sub(0, x); 17122 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 17123 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 17124 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) { 17125 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) && 17126 "Unsupported VT for PSIGN"); 17127 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0)); 17128 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 17129 } 17130 // PBLENDVB only available on SSE 4.1 17131 if (!Subtarget->hasSSE41()) 17132 return SDValue(); 17133 17134 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8; 17135 17136 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X); 17137 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y); 17138 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask); 17139 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); 17140 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 17141 } 17142 } 17143 17144 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 17145 return SDValue(); 17146 17147 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 17148 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 17149 std::swap(N0, N1); 17150 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 17151 return SDValue(); 17152 if (!N0.hasOneUse() || !N1.hasOneUse()) 17153 return SDValue(); 17154 17155 SDValue ShAmt0 = N0.getOperand(1); 17156 if (ShAmt0.getValueType() != MVT::i8) 17157 return SDValue(); 17158 SDValue ShAmt1 = N1.getOperand(1); 17159 if (ShAmt1.getValueType() != MVT::i8) 17160 return SDValue(); 17161 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 17162 ShAmt0 = ShAmt0.getOperand(0); 17163 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 17164 ShAmt1 = ShAmt1.getOperand(0); 17165 17166 SDLoc DL(N); 17167 unsigned Opc = X86ISD::SHLD; 17168 SDValue Op0 = N0.getOperand(0); 17169 SDValue Op1 = N1.getOperand(0); 17170 if (ShAmt0.getOpcode() == ISD::SUB) { 17171 Opc = X86ISD::SHRD; 17172 std::swap(Op0, Op1); 17173 std::swap(ShAmt0, ShAmt1); 17174 } 17175 17176 unsigned Bits = VT.getSizeInBits(); 17177 if (ShAmt1.getOpcode() == ISD::SUB) { 17178 SDValue Sum = ShAmt1.getOperand(0); 17179 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 17180 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 17181 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 17182 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 17183 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 17184 return DAG.getNode(Opc, DL, VT, 17185 Op0, Op1, 17186 DAG.getNode(ISD::TRUNCATE, DL, 17187 MVT::i8, ShAmt0)); 17188 } 17189 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 17190 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 17191 if (ShAmt0C && 17192 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 17193 return DAG.getNode(Opc, DL, VT, 17194 N0.getOperand(0), N1.getOperand(0), 17195 DAG.getNode(ISD::TRUNCATE, DL, 17196 MVT::i8, ShAmt0)); 17197 } 17198 17199 return SDValue(); 17200 } 17201 17202 // Generate NEG and CMOV for integer abs. 17203 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 17204 EVT VT = N->getValueType(0); 17205 17206 // Since X86 does not have CMOV for 8-bit integer, we don't convert 17207 // 8-bit integer abs to NEG and CMOV. 17208 if (VT.isInteger() && VT.getSizeInBits() == 8) 17209 return SDValue(); 17210 17211 SDValue N0 = N->getOperand(0); 17212 SDValue N1 = N->getOperand(1); 17213 SDLoc DL(N); 17214 17215 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 17216 // and change it to SUB and CMOV. 17217 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 17218 N0.getOpcode() == ISD::ADD && 17219 N0.getOperand(1) == N1 && 17220 N1.getOpcode() == ISD::SRA && 17221 N1.getOperand(0) == N0.getOperand(0)) 17222 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 17223 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) { 17224 // Generate SUB & CMOV. 17225 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32), 17226 DAG.getConstant(0, VT), N0.getOperand(0)); 17227 17228 SDValue Ops[] = { N0.getOperand(0), Neg, 17229 DAG.getConstant(X86::COND_GE, MVT::i8), 17230 SDValue(Neg.getNode(), 1) }; 17231 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), 17232 Ops, array_lengthof(Ops)); 17233 } 17234 return SDValue(); 17235 } 17236 17237 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes 17238 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 17239 TargetLowering::DAGCombinerInfo &DCI, 17240 const X86Subtarget *Subtarget) { 17241 EVT VT = N->getValueType(0); 17242 if (DCI.isBeforeLegalizeOps()) 17243 return SDValue(); 17244 17245 if (Subtarget->hasCMov()) { 17246 SDValue RV = performIntegerAbsCombine(N, DAG); 17247 if (RV.getNode()) 17248 return RV; 17249 } 17250 17251 // Try forming BMI if it is available. 17252 if (!Subtarget->hasBMI()) 17253 return SDValue(); 17254 17255 if (VT != MVT::i32 && VT != MVT::i64) 17256 return SDValue(); 17257 17258 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions"); 17259 17260 // Create BLSMSK instructions by finding X ^ (X-1) 17261 SDValue N0 = N->getOperand(0); 17262 SDValue N1 = N->getOperand(1); 17263 SDLoc DL(N); 17264 17265 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 17266 isAllOnes(N0.getOperand(1))) 17267 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 17268 17269 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 17270 isAllOnes(N1.getOperand(1))) 17271 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 17272 17273 return SDValue(); 17274 } 17275 17276 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 17277 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 17278 TargetLowering::DAGCombinerInfo &DCI, 17279 const X86Subtarget *Subtarget) { 17280 LoadSDNode *Ld = cast<LoadSDNode>(N); 17281 EVT RegVT = Ld->getValueType(0); 17282 EVT MemVT = Ld->getMemoryVT(); 17283 SDLoc dl(Ld); 17284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17285 unsigned RegSz = RegVT.getSizeInBits(); 17286 17287 // On Sandybridge unaligned 256bit loads are inefficient. 17288 ISD::LoadExtType Ext = Ld->getExtensionType(); 17289 unsigned Alignment = Ld->getAlignment(); 17290 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8; 17291 if (RegVT.is256BitVector() && !Subtarget->hasInt256() && 17292 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) { 17293 unsigned NumElems = RegVT.getVectorNumElements(); 17294 if (NumElems < 2) 17295 return SDValue(); 17296 17297 SDValue Ptr = Ld->getBasePtr(); 17298 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy()); 17299 17300 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 17301 NumElems/2); 17302 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, 17303 Ld->getPointerInfo(), Ld->isVolatile(), 17304 Ld->isNonTemporal(), Ld->isInvariant(), 17305 Alignment); 17306 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 17307 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, 17308 Ld->getPointerInfo(), Ld->isVolatile(), 17309 Ld->isNonTemporal(), Ld->isInvariant(), 17310 std::min(16U, Alignment)); 17311 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 17312 Load1.getValue(1), 17313 Load2.getValue(1)); 17314 17315 SDValue NewVec = DAG.getUNDEF(RegVT); 17316 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl); 17317 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl); 17318 return DCI.CombineTo(N, NewVec, TF, true); 17319 } 17320 17321 // If this is a vector EXT Load then attempt to optimize it using a 17322 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the 17323 // expansion is still better than scalar code. 17324 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll 17325 // emit a shuffle and a arithmetic shift. 17326 // TODO: It is possible to support ZExt by zeroing the undef values 17327 // during the shuffle phase or after the shuffle. 17328 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() && 17329 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) { 17330 assert(MemVT != RegVT && "Cannot extend to the same type"); 17331 assert(MemVT.isVector() && "Must load a vector from memory"); 17332 17333 unsigned NumElems = RegVT.getVectorNumElements(); 17334 unsigned MemSz = MemVT.getSizeInBits(); 17335 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 17336 17337 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) 17338 return SDValue(); 17339 17340 // All sizes must be a power of two. 17341 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) 17342 return SDValue(); 17343 17344 // Attempt to load the original value using scalar loads. 17345 // Find the largest scalar type that divides the total loaded size. 17346 MVT SclrLoadTy = MVT::i8; 17347 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 17348 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 17349 MVT Tp = (MVT::SimpleValueType)tp; 17350 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) { 17351 SclrLoadTy = Tp; 17352 } 17353 } 17354 17355 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 17356 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 && 17357 (64 <= MemSz)) 17358 SclrLoadTy = MVT::f64; 17359 17360 // Calculate the number of scalar loads that we need to perform 17361 // in order to load our vector from memory. 17362 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits(); 17363 if (Ext == ISD::SEXTLOAD && NumLoads > 1) 17364 return SDValue(); 17365 17366 unsigned loadRegZize = RegSz; 17367 if (Ext == ISD::SEXTLOAD && RegSz == 256) 17368 loadRegZize /= 2; 17369 17370 // Represent our vector as a sequence of elements which are the 17371 // largest scalar that we can load. 17372 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 17373 loadRegZize/SclrLoadTy.getSizeInBits()); 17374 17375 // Represent the data using the same element type that is stored in 17376 // memory. In practice, we ''widen'' MemVT. 17377 EVT WideVecVT = 17378 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 17379 loadRegZize/MemVT.getScalarType().getSizeInBits()); 17380 17381 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && 17382 "Invalid vector type"); 17383 17384 // We can't shuffle using an illegal type. 17385 if (!TLI.isTypeLegal(WideVecVT)) 17386 return SDValue(); 17387 17388 SmallVector<SDValue, 8> Chains; 17389 SDValue Ptr = Ld->getBasePtr(); 17390 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8, 17391 TLI.getPointerTy()); 17392 SDValue Res = DAG.getUNDEF(LoadUnitVecVT); 17393 17394 for (unsigned i = 0; i < NumLoads; ++i) { 17395 // Perform a single load. 17396 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 17397 Ptr, Ld->getPointerInfo(), 17398 Ld->isVolatile(), Ld->isNonTemporal(), 17399 Ld->isInvariant(), Ld->getAlignment()); 17400 Chains.push_back(ScalarLoad.getValue(1)); 17401 // Create the first element type using SCALAR_TO_VECTOR in order to avoid 17402 // another round of DAGCombining. 17403 if (i == 0) 17404 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad); 17405 else 17406 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res, 17407 ScalarLoad, DAG.getIntPtrConstant(i)); 17408 17409 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 17410 } 17411 17412 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 17413 Chains.size()); 17414 17415 // Bitcast the loaded value to a vector of the original element type, in 17416 // the size of the target vector type. 17417 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res); 17418 unsigned SizeRatio = RegSz/MemSz; 17419 17420 if (Ext == ISD::SEXTLOAD) { 17421 // If we have SSE4.1 we can directly emit a VSEXT node. 17422 if (Subtarget->hasSSE41()) { 17423 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec); 17424 return DCI.CombineTo(N, Sext, TF, true); 17425 } 17426 17427 // Otherwise we'll shuffle the small elements in the high bits of the 17428 // larger type and perform an arithmetic shift. If the shift is not legal 17429 // it's better to scalarize. 17430 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT)) 17431 return SDValue(); 17432 17433 // Redistribute the loaded elements into the different locations. 17434 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 17435 for (unsigned i = 0; i != NumElems; ++i) 17436 ShuffleVec[i*SizeRatio + SizeRatio-1] = i; 17437 17438 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 17439 DAG.getUNDEF(WideVecVT), 17440 &ShuffleVec[0]); 17441 17442 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 17443 17444 // Build the arithmetic shift. 17445 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() - 17446 MemVT.getVectorElementType().getSizeInBits(); 17447 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, 17448 DAG.getConstant(Amt, RegVT)); 17449 17450 return DCI.CombineTo(N, Shuff, TF, true); 17451 } 17452 17453 // Redistribute the loaded elements into the different locations. 17454 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 17455 for (unsigned i = 0; i != NumElems; ++i) 17456 ShuffleVec[i*SizeRatio] = i; 17457 17458 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 17459 DAG.getUNDEF(WideVecVT), 17460 &ShuffleVec[0]); 17461 17462 // Bitcast to the requested type. 17463 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 17464 // Replace the original load with the new sequence 17465 // and return the new chain. 17466 return DCI.CombineTo(N, Shuff, TF, true); 17467 } 17468 17469 return SDValue(); 17470 } 17471 17472 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 17473 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 17474 const X86Subtarget *Subtarget) { 17475 StoreSDNode *St = cast<StoreSDNode>(N); 17476 EVT VT = St->getValue().getValueType(); 17477 EVT StVT = St->getMemoryVT(); 17478 SDLoc dl(St); 17479 SDValue StoredVal = St->getOperand(1); 17480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17481 17482 // If we are saving a concatenation of two XMM registers, perform two stores. 17483 // On Sandy Bridge, 256-bit memory operations are executed by two 17484 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit 17485 // memory operation. 17486 unsigned Alignment = St->getAlignment(); 17487 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8; 17488 if (VT.is256BitVector() && !Subtarget->hasInt256() && 17489 StVT == VT && !IsAligned) { 17490 unsigned NumElems = VT.getVectorNumElements(); 17491 if (NumElems < 2) 17492 return SDValue(); 17493 17494 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl); 17495 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl); 17496 17497 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 17498 SDValue Ptr0 = St->getBasePtr(); 17499 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 17500 17501 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 17502 St->getPointerInfo(), St->isVolatile(), 17503 St->isNonTemporal(), Alignment); 17504 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 17505 St->getPointerInfo(), St->isVolatile(), 17506 St->isNonTemporal(), 17507 std::min(16U, Alignment)); 17508 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 17509 } 17510 17511 // Optimize trunc store (of multiple scalars) to shuffle and store. 17512 // First, pack all of the elements in one place. Next, store to memory 17513 // in fewer chunks. 17514 if (St->isTruncatingStore() && VT.isVector()) { 17515 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17516 unsigned NumElems = VT.getVectorNumElements(); 17517 assert(StVT != VT && "Cannot truncate to the same type"); 17518 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 17519 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 17520 17521 // From, To sizes and ElemCount must be pow of two 17522 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 17523 // We are going to use the original vector elt for storing. 17524 // Accumulated smaller vector elements must be a multiple of the store size. 17525 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 17526 17527 unsigned SizeRatio = FromSz / ToSz; 17528 17529 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 17530 17531 // Create a type on which we perform the shuffle 17532 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 17533 StVT.getScalarType(), NumElems*SizeRatio); 17534 17535 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 17536 17537 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 17538 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 17539 for (unsigned i = 0; i != NumElems; ++i) 17540 ShuffleVec[i] = i * SizeRatio; 17541 17542 // Can't shuffle using an illegal type. 17543 if (!TLI.isTypeLegal(WideVecVT)) 17544 return SDValue(); 17545 17546 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 17547 DAG.getUNDEF(WideVecVT), 17548 &ShuffleVec[0]); 17549 // At this point all of the data is stored at the bottom of the 17550 // register. We now need to save it to mem. 17551 17552 // Find the largest store unit 17553 MVT StoreType = MVT::i8; 17554 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 17555 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 17556 MVT Tp = (MVT::SimpleValueType)tp; 17557 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz) 17558 StoreType = Tp; 17559 } 17560 17561 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 17562 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 && 17563 (64 <= NumElems * ToSz)) 17564 StoreType = MVT::f64; 17565 17566 // Bitcast the original vector into a vector of store-size units 17567 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 17568 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits()); 17569 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 17570 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 17571 SmallVector<SDValue, 8> Chains; 17572 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 17573 TLI.getPointerTy()); 17574 SDValue Ptr = St->getBasePtr(); 17575 17576 // Perform one or more big stores into memory. 17577 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) { 17578 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 17579 StoreType, ShuffWide, 17580 DAG.getIntPtrConstant(i)); 17581 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 17582 St->getPointerInfo(), St->isVolatile(), 17583 St->isNonTemporal(), St->getAlignment()); 17584 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 17585 Chains.push_back(Ch); 17586 } 17587 17588 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 17589 Chains.size()); 17590 } 17591 17592 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 17593 // the FP state in cases where an emms may be missing. 17594 // A preferable solution to the general problem is to figure out the right 17595 // places to insert EMMS. This qualifies as a quick hack. 17596 17597 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 17598 if (VT.getSizeInBits() != 64) 17599 return SDValue(); 17600 17601 const Function *F = DAG.getMachineFunction().getFunction(); 17602 bool NoImplicitFloatOps = F->getAttributes(). 17603 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 17604 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps 17605 && Subtarget->hasSSE2(); 17606 if ((VT.isVector() || 17607 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 17608 isa<LoadSDNode>(St->getValue()) && 17609 !cast<LoadSDNode>(St->getValue())->isVolatile() && 17610 St->getChain().hasOneUse() && !St->isVolatile()) { 17611 SDNode* LdVal = St->getValue().getNode(); 17612 LoadSDNode *Ld = 0; 17613 int TokenFactorIndex = -1; 17614 SmallVector<SDValue, 8> Ops; 17615 SDNode* ChainVal = St->getChain().getNode(); 17616 // Must be a store of a load. We currently handle two cases: the load 17617 // is a direct child, and it's under an intervening TokenFactor. It is 17618 // possible to dig deeper under nested TokenFactors. 17619 if (ChainVal == LdVal) 17620 Ld = cast<LoadSDNode>(St->getChain()); 17621 else if (St->getValue().hasOneUse() && 17622 ChainVal->getOpcode() == ISD::TokenFactor) { 17623 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) { 17624 if (ChainVal->getOperand(i).getNode() == LdVal) { 17625 TokenFactorIndex = i; 17626 Ld = cast<LoadSDNode>(St->getValue()); 17627 } else 17628 Ops.push_back(ChainVal->getOperand(i)); 17629 } 17630 } 17631 17632 if (!Ld || !ISD::isNormalLoad(Ld)) 17633 return SDValue(); 17634 17635 // If this is not the MMX case, i.e. we are just turning i64 load/store 17636 // into f64 load/store, avoid the transformation if there are multiple 17637 // uses of the loaded value. 17638 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 17639 return SDValue(); 17640 17641 SDLoc LdDL(Ld); 17642 SDLoc StDL(N); 17643 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 17644 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 17645 // pair instead. 17646 if (Subtarget->is64Bit() || F64IsLegal) { 17647 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 17648 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 17649 Ld->getPointerInfo(), Ld->isVolatile(), 17650 Ld->isNonTemporal(), Ld->isInvariant(), 17651 Ld->getAlignment()); 17652 SDValue NewChain = NewLd.getValue(1); 17653 if (TokenFactorIndex != -1) { 17654 Ops.push_back(NewChain); 17655 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 17656 Ops.size()); 17657 } 17658 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 17659 St->getPointerInfo(), 17660 St->isVolatile(), St->isNonTemporal(), 17661 St->getAlignment()); 17662 } 17663 17664 // Otherwise, lower to two pairs of 32-bit loads / stores. 17665 SDValue LoAddr = Ld->getBasePtr(); 17666 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 17667 DAG.getConstant(4, MVT::i32)); 17668 17669 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 17670 Ld->getPointerInfo(), 17671 Ld->isVolatile(), Ld->isNonTemporal(), 17672 Ld->isInvariant(), Ld->getAlignment()); 17673 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 17674 Ld->getPointerInfo().getWithOffset(4), 17675 Ld->isVolatile(), Ld->isNonTemporal(), 17676 Ld->isInvariant(), 17677 MinAlign(Ld->getAlignment(), 4)); 17678 17679 SDValue NewChain = LoLd.getValue(1); 17680 if (TokenFactorIndex != -1) { 17681 Ops.push_back(LoLd); 17682 Ops.push_back(HiLd); 17683 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 17684 Ops.size()); 17685 } 17686 17687 LoAddr = St->getBasePtr(); 17688 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 17689 DAG.getConstant(4, MVT::i32)); 17690 17691 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 17692 St->getPointerInfo(), 17693 St->isVolatile(), St->isNonTemporal(), 17694 St->getAlignment()); 17695 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 17696 St->getPointerInfo().getWithOffset(4), 17697 St->isVolatile(), 17698 St->isNonTemporal(), 17699 MinAlign(St->getAlignment(), 4)); 17700 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 17701 } 17702 return SDValue(); 17703 } 17704 17705 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 17706 /// and return the operands for the horizontal operation in LHS and RHS. A 17707 /// horizontal operation performs the binary operation on successive elements 17708 /// of its first operand, then on successive elements of its second operand, 17709 /// returning the resulting values in a vector. For example, if 17710 /// A = < float a0, float a1, float a2, float a3 > 17711 /// and 17712 /// B = < float b0, float b1, float b2, float b3 > 17713 /// then the result of doing a horizontal operation on A and B is 17714 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 17715 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 17716 /// A horizontal-op B, for some already available A and B, and if so then LHS is 17717 /// set to A, RHS to B, and the routine returns 'true'. 17718 /// Note that the binary operation should have the property that if one of the 17719 /// operands is UNDEF then the result is UNDEF. 17720 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) { 17721 // Look for the following pattern: if 17722 // A = < float a0, float a1, float a2, float a3 > 17723 // B = < float b0, float b1, float b2, float b3 > 17724 // and 17725 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 17726 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 17727 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 17728 // which is A horizontal-op B. 17729 17730 // At least one of the operands should be a vector shuffle. 17731 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 17732 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 17733 return false; 17734 17735 MVT VT = LHS.getValueType().getSimpleVT(); 17736 17737 assert((VT.is128BitVector() || VT.is256BitVector()) && 17738 "Unsupported vector type for horizontal add/sub"); 17739 17740 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to 17741 // operate independently on 128-bit lanes. 17742 unsigned NumElts = VT.getVectorNumElements(); 17743 unsigned NumLanes = VT.getSizeInBits()/128; 17744 unsigned NumLaneElts = NumElts / NumLanes; 17745 assert((NumLaneElts % 2 == 0) && 17746 "Vector type should have an even number of elements in each lane"); 17747 unsigned HalfLaneElts = NumLaneElts/2; 17748 17749 // View LHS in the form 17750 // LHS = VECTOR_SHUFFLE A, B, LMask 17751 // If LHS is not a shuffle then pretend it is the shuffle 17752 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 17753 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 17754 // type VT. 17755 SDValue A, B; 17756 SmallVector<int, 16> LMask(NumElts); 17757 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 17758 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 17759 A = LHS.getOperand(0); 17760 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 17761 B = LHS.getOperand(1); 17762 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(); 17763 std::copy(Mask.begin(), Mask.end(), LMask.begin()); 17764 } else { 17765 if (LHS.getOpcode() != ISD::UNDEF) 17766 A = LHS; 17767 for (unsigned i = 0; i != NumElts; ++i) 17768 LMask[i] = i; 17769 } 17770 17771 // Likewise, view RHS in the form 17772 // RHS = VECTOR_SHUFFLE C, D, RMask 17773 SDValue C, D; 17774 SmallVector<int, 16> RMask(NumElts); 17775 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 17776 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 17777 C = RHS.getOperand(0); 17778 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 17779 D = RHS.getOperand(1); 17780 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(); 17781 std::copy(Mask.begin(), Mask.end(), RMask.begin()); 17782 } else { 17783 if (RHS.getOpcode() != ISD::UNDEF) 17784 C = RHS; 17785 for (unsigned i = 0; i != NumElts; ++i) 17786 RMask[i] = i; 17787 } 17788 17789 // Check that the shuffles are both shuffling the same vectors. 17790 if (!(A == C && B == D) && !(A == D && B == C)) 17791 return false; 17792 17793 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 17794 if (!A.getNode() && !B.getNode()) 17795 return false; 17796 17797 // If A and B occur in reverse order in RHS, then "swap" them (which means 17798 // rewriting the mask). 17799 if (A != C) 17800 CommuteVectorShuffleMask(RMask, NumElts); 17801 17802 // At this point LHS and RHS are equivalent to 17803 // LHS = VECTOR_SHUFFLE A, B, LMask 17804 // RHS = VECTOR_SHUFFLE A, B, RMask 17805 // Check that the masks correspond to performing a horizontal operation. 17806 for (unsigned l = 0; l != NumElts; l += NumLaneElts) { 17807 for (unsigned i = 0; i != NumLaneElts; ++i) { 17808 int LIdx = LMask[i+l], RIdx = RMask[i+l]; 17809 17810 // Ignore any UNDEF components. 17811 if (LIdx < 0 || RIdx < 0 || 17812 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) || 17813 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts))) 17814 continue; 17815 17816 // Check that successive elements are being operated on. If not, this is 17817 // not a horizontal operation. 17818 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs 17819 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l; 17820 if (!(LIdx == Index && RIdx == Index + 1) && 17821 !(IsCommutative && LIdx == Index + 1 && RIdx == Index)) 17822 return false; 17823 } 17824 } 17825 17826 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 17827 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 17828 return true; 17829 } 17830 17831 /// PerformFADDCombine - Do target-specific dag combines on floating point adds. 17832 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 17833 const X86Subtarget *Subtarget) { 17834 EVT VT = N->getValueType(0); 17835 SDValue LHS = N->getOperand(0); 17836 SDValue RHS = N->getOperand(1); 17837 17838 // Try to synthesize horizontal adds from adds of shuffles. 17839 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 17840 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 17841 isHorizontalBinOp(LHS, RHS, true)) 17842 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS); 17843 return SDValue(); 17844 } 17845 17846 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 17847 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 17848 const X86Subtarget *Subtarget) { 17849 EVT VT = N->getValueType(0); 17850 SDValue LHS = N->getOperand(0); 17851 SDValue RHS = N->getOperand(1); 17852 17853 // Try to synthesize horizontal subs from subs of shuffles. 17854 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 17855 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 17856 isHorizontalBinOp(LHS, RHS, false)) 17857 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS); 17858 return SDValue(); 17859 } 17860 17861 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 17862 /// X86ISD::FXOR nodes. 17863 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 17864 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 17865 // F[X]OR(0.0, x) -> x 17866 // F[X]OR(x, 0.0) -> x 17867 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 17868 if (C->getValueAPF().isPosZero()) 17869 return N->getOperand(1); 17870 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 17871 if (C->getValueAPF().isPosZero()) 17872 return N->getOperand(0); 17873 return SDValue(); 17874 } 17875 17876 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and 17877 /// X86ISD::FMAX nodes. 17878 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) { 17879 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX); 17880 17881 // Only perform optimizations if UnsafeMath is used. 17882 if (!DAG.getTarget().Options.UnsafeFPMath) 17883 return SDValue(); 17884 17885 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes 17886 // into FMINC and FMAXC, which are Commutative operations. 17887 unsigned NewOp = 0; 17888 switch (N->getOpcode()) { 17889 default: llvm_unreachable("unknown opcode"); 17890 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break; 17891 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break; 17892 } 17893 17894 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0), 17895 N->getOperand(0), N->getOperand(1)); 17896 } 17897 17898 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 17899 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 17900 // FAND(0.0, x) -> 0.0 17901 // FAND(x, 0.0) -> 0.0 17902 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 17903 if (C->getValueAPF().isPosZero()) 17904 return N->getOperand(0); 17905 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 17906 if (C->getValueAPF().isPosZero()) 17907 return N->getOperand(1); 17908 return SDValue(); 17909 } 17910 17911 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes 17912 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) { 17913 // FANDN(x, 0.0) -> 0.0 17914 // FANDN(0.0, x) -> x 17915 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 17916 if (C->getValueAPF().isPosZero()) 17917 return N->getOperand(1); 17918 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 17919 if (C->getValueAPF().isPosZero()) 17920 return N->getOperand(1); 17921 return SDValue(); 17922 } 17923 17924 static SDValue PerformBTCombine(SDNode *N, 17925 SelectionDAG &DAG, 17926 TargetLowering::DAGCombinerInfo &DCI) { 17927 // BT ignores high bits in the bit index operand. 17928 SDValue Op1 = N->getOperand(1); 17929 if (Op1.hasOneUse()) { 17930 unsigned BitWidth = Op1.getValueSizeInBits(); 17931 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 17932 APInt KnownZero, KnownOne; 17933 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 17934 !DCI.isBeforeLegalizeOps()); 17935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17936 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 17937 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 17938 DCI.CommitTargetLoweringOpt(TLO); 17939 } 17940 return SDValue(); 17941 } 17942 17943 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 17944 SDValue Op = N->getOperand(0); 17945 if (Op.getOpcode() == ISD::BITCAST) 17946 Op = Op.getOperand(0); 17947 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 17948 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 17949 VT.getVectorElementType().getSizeInBits() == 17950 OpVT.getVectorElementType().getSizeInBits()) { 17951 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 17952 } 17953 return SDValue(); 17954 } 17955 17956 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 17957 const X86Subtarget *Subtarget) { 17958 EVT VT = N->getValueType(0); 17959 if (!VT.isVector()) 17960 return SDValue(); 17961 17962 SDValue N0 = N->getOperand(0); 17963 SDValue N1 = N->getOperand(1); 17964 EVT ExtraVT = cast<VTSDNode>(N1)->getVT(); 17965 SDLoc dl(N); 17966 17967 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the 17968 // both SSE and AVX2 since there is no sign-extended shift right 17969 // operation on a vector with 64-bit elements. 17970 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) -> 17971 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT))) 17972 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND || 17973 N0.getOpcode() == ISD::SIGN_EXTEND)) { 17974 SDValue N00 = N0.getOperand(0); 17975 17976 // EXTLOAD has a better solution on AVX2, 17977 // it may be replaced with X86ISD::VSEXT node. 17978 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256()) 17979 if (!ISD::isNormalLoad(N00.getNode())) 17980 return SDValue(); 17981 17982 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) { 17983 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 17984 N00, N1); 17985 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp); 17986 } 17987 } 17988 return SDValue(); 17989 } 17990 17991 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG, 17992 TargetLowering::DAGCombinerInfo &DCI, 17993 const X86Subtarget *Subtarget) { 17994 if (!DCI.isBeforeLegalizeOps()) 17995 return SDValue(); 17996 17997 if (!Subtarget->hasFp256()) 17998 return SDValue(); 17999 18000 EVT VT = N->getValueType(0); 18001 if (VT.isVector() && VT.getSizeInBits() == 256) { 18002 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 18003 if (R.getNode()) 18004 return R; 18005 } 18006 18007 return SDValue(); 18008 } 18009 18010 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG, 18011 const X86Subtarget* Subtarget) { 18012 SDLoc dl(N); 18013 EVT VT = N->getValueType(0); 18014 18015 // Let legalize expand this if it isn't a legal type yet. 18016 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 18017 return SDValue(); 18018 18019 EVT ScalarVT = VT.getScalarType(); 18020 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || 18021 (!Subtarget->hasFMA() && !Subtarget->hasFMA4())) 18022 return SDValue(); 18023 18024 SDValue A = N->getOperand(0); 18025 SDValue B = N->getOperand(1); 18026 SDValue C = N->getOperand(2); 18027 18028 bool NegA = (A.getOpcode() == ISD::FNEG); 18029 bool NegB = (B.getOpcode() == ISD::FNEG); 18030 bool NegC = (C.getOpcode() == ISD::FNEG); 18031 18032 // Negative multiplication when NegA xor NegB 18033 bool NegMul = (NegA != NegB); 18034 if (NegA) 18035 A = A.getOperand(0); 18036 if (NegB) 18037 B = B.getOperand(0); 18038 if (NegC) 18039 C = C.getOperand(0); 18040 18041 unsigned Opcode; 18042 if (!NegMul) 18043 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB; 18044 else 18045 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB; 18046 18047 return DAG.getNode(Opcode, dl, VT, A, B, C); 18048 } 18049 18050 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG, 18051 TargetLowering::DAGCombinerInfo &DCI, 18052 const X86Subtarget *Subtarget) { 18053 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 18054 // (and (i32 x86isd::setcc_carry), 1) 18055 // This eliminates the zext. This transformation is necessary because 18056 // ISD::SETCC is always legalized to i8. 18057 SDLoc dl(N); 18058 SDValue N0 = N->getOperand(0); 18059 EVT VT = N->getValueType(0); 18060 18061 if (N0.getOpcode() == ISD::AND && 18062 N0.hasOneUse() && 18063 N0.getOperand(0).hasOneUse()) { 18064 SDValue N00 = N0.getOperand(0); 18065 if (N00.getOpcode() == X86ISD::SETCC_CARRY) { 18066 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 18067 if (!C || C->getZExtValue() != 1) 18068 return SDValue(); 18069 return DAG.getNode(ISD::AND, dl, VT, 18070 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 18071 N00.getOperand(0), N00.getOperand(1)), 18072 DAG.getConstant(1, VT)); 18073 } 18074 } 18075 18076 if (VT.is256BitVector()) { 18077 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 18078 if (R.getNode()) 18079 return R; 18080 } 18081 18082 return SDValue(); 18083 } 18084 18085 // Optimize x == -y --> x+y == 0 18086 // x != -y --> x+y != 0 18087 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) { 18088 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 18089 SDValue LHS = N->getOperand(0); 18090 SDValue RHS = N->getOperand(1); 18091 18092 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB) 18093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0))) 18094 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) { 18095 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), 18096 LHS.getValueType(), RHS, LHS.getOperand(1)); 18097 return DAG.getSetCC(SDLoc(N), N->getValueType(0), 18098 addV, DAG.getConstant(0, addV.getValueType()), CC); 18099 } 18100 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB) 18101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0))) 18102 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) { 18103 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), 18104 RHS.getValueType(), LHS, RHS.getOperand(1)); 18105 return DAG.getSetCC(SDLoc(N), N->getValueType(0), 18106 addV, DAG.getConstant(0, addV.getValueType()), CC); 18107 } 18108 return SDValue(); 18109 } 18110 18111 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 18112 // as "sbb reg,reg", since it can be extended without zext and produces 18113 // an all-ones bit which is more useful than 0/1 in some cases. 18114 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) { 18115 return DAG.getNode(ISD::AND, DL, MVT::i8, 18116 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 18117 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS), 18118 DAG.getConstant(1, MVT::i8)); 18119 } 18120 18121 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 18122 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG, 18123 TargetLowering::DAGCombinerInfo &DCI, 18124 const X86Subtarget *Subtarget) { 18125 SDLoc DL(N); 18126 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0)); 18127 SDValue EFLAGS = N->getOperand(1); 18128 18129 if (CC == X86::COND_A) { 18130 // Try to convert COND_A into COND_B in an attempt to facilitate 18131 // materializing "setb reg". 18132 // 18133 // Do not flip "e > c", where "c" is a constant, because Cmp instruction 18134 // cannot take an immediate as its first operand. 18135 // 18136 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 18137 EFLAGS.getValueType().isInteger() && 18138 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) { 18139 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), 18140 EFLAGS.getNode()->getVTList(), 18141 EFLAGS.getOperand(1), EFLAGS.getOperand(0)); 18142 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo()); 18143 return MaterializeSETB(DL, NewEFLAGS, DAG); 18144 } 18145 } 18146 18147 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 18148 // a zext and produces an all-ones bit which is more useful than 0/1 in some 18149 // cases. 18150 if (CC == X86::COND_B) 18151 return MaterializeSETB(DL, EFLAGS, DAG); 18152 18153 SDValue Flags; 18154 18155 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 18156 if (Flags.getNode()) { 18157 SDValue Cond = DAG.getConstant(CC, MVT::i8); 18158 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags); 18159 } 18160 18161 return SDValue(); 18162 } 18163 18164 // Optimize branch condition evaluation. 18165 // 18166 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG, 18167 TargetLowering::DAGCombinerInfo &DCI, 18168 const X86Subtarget *Subtarget) { 18169 SDLoc DL(N); 18170 SDValue Chain = N->getOperand(0); 18171 SDValue Dest = N->getOperand(1); 18172 SDValue EFLAGS = N->getOperand(3); 18173 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2)); 18174 18175 SDValue Flags; 18176 18177 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 18178 if (Flags.getNode()) { 18179 SDValue Cond = DAG.getConstant(CC, MVT::i8); 18180 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond, 18181 Flags); 18182 } 18183 18184 return SDValue(); 18185 } 18186 18187 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 18188 const X86TargetLowering *XTLI) { 18189 SDValue Op0 = N->getOperand(0); 18190 EVT InVT = Op0->getValueType(0); 18191 18192 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32)) 18193 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) { 18194 SDLoc dl(N); 18195 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 18196 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0); 18197 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P); 18198 } 18199 18200 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 18201 // a 32-bit target where SSE doesn't support i64->FP operations. 18202 if (Op0.getOpcode() == ISD::LOAD) { 18203 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 18204 EVT VT = Ld->getValueType(0); 18205 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 18206 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 18207 !XTLI->getSubtarget()->is64Bit() && 18208 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 18209 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 18210 Ld->getChain(), Op0, DAG); 18211 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 18212 return FILDChain; 18213 } 18214 } 18215 return SDValue(); 18216 } 18217 18218 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 18219 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 18220 X86TargetLowering::DAGCombinerInfo &DCI) { 18221 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 18222 // the result is either zero or one (depending on the input carry bit). 18223 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 18224 if (X86::isZeroNode(N->getOperand(0)) && 18225 X86::isZeroNode(N->getOperand(1)) && 18226 // We don't have a good way to replace an EFLAGS use, so only do this when 18227 // dead right now. 18228 SDValue(N, 1).use_empty()) { 18229 SDLoc DL(N); 18230 EVT VT = N->getValueType(0); 18231 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 18232 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 18233 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 18234 DAG.getConstant(X86::COND_B,MVT::i8), 18235 N->getOperand(2)), 18236 DAG.getConstant(1, VT)); 18237 return DCI.CombineTo(N, Res1, CarryOut); 18238 } 18239 18240 return SDValue(); 18241 } 18242 18243 // fold (add Y, (sete X, 0)) -> adc 0, Y 18244 // (add Y, (setne X, 0)) -> sbb -1, Y 18245 // (sub (sete X, 0), Y) -> sbb 0, Y 18246 // (sub (setne X, 0), Y) -> adc -1, Y 18247 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 18248 SDLoc DL(N); 18249 18250 // Look through ZExts. 18251 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 18252 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 18253 return SDValue(); 18254 18255 SDValue SetCC = Ext.getOperand(0); 18256 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 18257 return SDValue(); 18258 18259 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 18260 if (CC != X86::COND_E && CC != X86::COND_NE) 18261 return SDValue(); 18262 18263 SDValue Cmp = SetCC.getOperand(1); 18264 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 18265 !X86::isZeroNode(Cmp.getOperand(1)) || 18266 !Cmp.getOperand(0).getValueType().isInteger()) 18267 return SDValue(); 18268 18269 SDValue CmpOp0 = Cmp.getOperand(0); 18270 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 18271 DAG.getConstant(1, CmpOp0.getValueType())); 18272 18273 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 18274 if (CC == X86::COND_NE) 18275 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 18276 DL, OtherVal.getValueType(), OtherVal, 18277 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 18278 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 18279 DL, OtherVal.getValueType(), OtherVal, 18280 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 18281 } 18282 18283 /// PerformADDCombine - Do target-specific dag combines on integer adds. 18284 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG, 18285 const X86Subtarget *Subtarget) { 18286 EVT VT = N->getValueType(0); 18287 SDValue Op0 = N->getOperand(0); 18288 SDValue Op1 = N->getOperand(1); 18289 18290 // Try to synthesize horizontal adds from adds of shuffles. 18291 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 18292 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 18293 isHorizontalBinOp(Op0, Op1, true)) 18294 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1); 18295 18296 return OptimizeConditionalInDecrement(N, DAG); 18297 } 18298 18299 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG, 18300 const X86Subtarget *Subtarget) { 18301 SDValue Op0 = N->getOperand(0); 18302 SDValue Op1 = N->getOperand(1); 18303 18304 // X86 can't encode an immediate LHS of a sub. See if we can push the 18305 // negation into a preceding instruction. 18306 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 18307 // If the RHS of the sub is a XOR with one use and a constant, invert the 18308 // immediate. Then add one to the LHS of the sub so we can turn 18309 // X-Y -> X+~Y+1, saving one register. 18310 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 18311 isa<ConstantSDNode>(Op1.getOperand(1))) { 18312 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 18313 EVT VT = Op0.getValueType(); 18314 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, 18315 Op1.getOperand(0), 18316 DAG.getConstant(~XorC, VT)); 18317 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor, 18318 DAG.getConstant(C->getAPIntValue()+1, VT)); 18319 } 18320 } 18321 18322 // Try to synthesize horizontal adds from adds of shuffles. 18323 EVT VT = N->getValueType(0); 18324 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 18325 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 18326 isHorizontalBinOp(Op0, Op1, true)) 18327 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1); 18328 18329 return OptimizeConditionalInDecrement(N, DAG); 18330 } 18331 18332 /// performVZEXTCombine - Performs build vector combines 18333 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG, 18334 TargetLowering::DAGCombinerInfo &DCI, 18335 const X86Subtarget *Subtarget) { 18336 // (vzext (bitcast (vzext (x)) -> (vzext x) 18337 SDValue In = N->getOperand(0); 18338 while (In.getOpcode() == ISD::BITCAST) 18339 In = In.getOperand(0); 18340 18341 if (In.getOpcode() != X86ISD::VZEXT) 18342 return SDValue(); 18343 18344 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0), 18345 In.getOperand(0)); 18346 } 18347 18348 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 18349 DAGCombinerInfo &DCI) const { 18350 SelectionDAG &DAG = DCI.DAG; 18351 switch (N->getOpcode()) { 18352 default: break; 18353 case ISD::EXTRACT_VECTOR_ELT: 18354 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI); 18355 case ISD::VSELECT: 18356 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget); 18357 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget); 18358 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget); 18359 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget); 18360 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 18361 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 18362 case ISD::SHL: 18363 case ISD::SRA: 18364 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget); 18365 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 18366 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 18367 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 18368 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget); 18369 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 18370 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 18371 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 18372 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 18373 case X86ISD::FXOR: 18374 case X86ISD::FOR: return PerformFORCombine(N, DAG); 18375 case X86ISD::FMIN: 18376 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG); 18377 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 18378 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG); 18379 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 18380 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 18381 case ISD::ANY_EXTEND: 18382 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget); 18383 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget); 18384 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 18385 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget); 18386 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG); 18387 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget); 18388 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget); 18389 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget); 18390 case X86ISD::SHUFP: // Handle all target specific shuffles 18391 case X86ISD::PALIGNR: 18392 case X86ISD::UNPCKH: 18393 case X86ISD::UNPCKL: 18394 case X86ISD::MOVHLPS: 18395 case X86ISD::MOVLHPS: 18396 case X86ISD::PSHUFD: 18397 case X86ISD::PSHUFHW: 18398 case X86ISD::PSHUFLW: 18399 case X86ISD::MOVSS: 18400 case X86ISD::MOVSD: 18401 case X86ISD::VPERMILP: 18402 case X86ISD::VPERM2X128: 18403 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 18404 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget); 18405 } 18406 18407 return SDValue(); 18408 } 18409 18410 /// isTypeDesirableForOp - Return true if the target has native support for 18411 /// the specified value type and it is 'desirable' to use the type for the 18412 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16 18413 /// instruction encodings are longer and some i16 instructions are slow. 18414 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 18415 if (!isTypeLegal(VT)) 18416 return false; 18417 if (VT != MVT::i16) 18418 return true; 18419 18420 switch (Opc) { 18421 default: 18422 return true; 18423 case ISD::LOAD: 18424 case ISD::SIGN_EXTEND: 18425 case ISD::ZERO_EXTEND: 18426 case ISD::ANY_EXTEND: 18427 case ISD::SHL: 18428 case ISD::SRL: 18429 case ISD::SUB: 18430 case ISD::ADD: 18431 case ISD::MUL: 18432 case ISD::AND: 18433 case ISD::OR: 18434 case ISD::XOR: 18435 return false; 18436 } 18437 } 18438 18439 /// IsDesirableToPromoteOp - This method query the target whether it is 18440 /// beneficial for dag combiner to promote the specified node. If true, it 18441 /// should return the desired promotion type by reference. 18442 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 18443 EVT VT = Op.getValueType(); 18444 if (VT != MVT::i16) 18445 return false; 18446 18447 bool Promote = false; 18448 bool Commute = false; 18449 switch (Op.getOpcode()) { 18450 default: break; 18451 case ISD::LOAD: { 18452 LoadSDNode *LD = cast<LoadSDNode>(Op); 18453 // If the non-extending load has a single use and it's not live out, then it 18454 // might be folded. 18455 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 18456 Op.hasOneUse()*/) { 18457 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 18458 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 18459 // The only case where we'd want to promote LOAD (rather then it being 18460 // promoted as an operand is when it's only use is liveout. 18461 if (UI->getOpcode() != ISD::CopyToReg) 18462 return false; 18463 } 18464 } 18465 Promote = true; 18466 break; 18467 } 18468 case ISD::SIGN_EXTEND: 18469 case ISD::ZERO_EXTEND: 18470 case ISD::ANY_EXTEND: 18471 Promote = true; 18472 break; 18473 case ISD::SHL: 18474 case ISD::SRL: { 18475 SDValue N0 = Op.getOperand(0); 18476 // Look out for (store (shl (load), x)). 18477 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 18478 return false; 18479 Promote = true; 18480 break; 18481 } 18482 case ISD::ADD: 18483 case ISD::MUL: 18484 case ISD::AND: 18485 case ISD::OR: 18486 case ISD::XOR: 18487 Commute = true; 18488 // fallthrough 18489 case ISD::SUB: { 18490 SDValue N0 = Op.getOperand(0); 18491 SDValue N1 = Op.getOperand(1); 18492 if (!Commute && MayFoldLoad(N1)) 18493 return false; 18494 // Avoid disabling potential load folding opportunities. 18495 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 18496 return false; 18497 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 18498 return false; 18499 Promote = true; 18500 } 18501 } 18502 18503 PVT = MVT::i32; 18504 return Promote; 18505 } 18506 18507 //===----------------------------------------------------------------------===// 18508 // X86 Inline Assembly Support 18509 //===----------------------------------------------------------------------===// 18510 18511 namespace { 18512 // Helper to match a string separated by whitespace. 18513 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) { 18514 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace. 18515 18516 for (unsigned i = 0, e = args.size(); i != e; ++i) { 18517 StringRef piece(*args[i]); 18518 if (!s.startswith(piece)) // Check if the piece matches. 18519 return false; 18520 18521 s = s.substr(piece.size()); 18522 StringRef::size_type pos = s.find_first_not_of(" \t"); 18523 if (pos == 0) // We matched a prefix. 18524 return false; 18525 18526 s = s.substr(pos); 18527 } 18528 18529 return s.empty(); 18530 } 18531 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={}; 18532 } 18533 18534 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 18535 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 18536 18537 std::string AsmStr = IA->getAsmString(); 18538 18539 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 18540 if (!Ty || Ty->getBitWidth() % 16 != 0) 18541 return false; 18542 18543 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 18544 SmallVector<StringRef, 4> AsmPieces; 18545 SplitString(AsmStr, AsmPieces, ";\n"); 18546 18547 switch (AsmPieces.size()) { 18548 default: return false; 18549 case 1: 18550 // FIXME: this should verify that we are targeting a 486 or better. If not, 18551 // we will turn this bswap into something that will be lowered to logical 18552 // ops instead of emitting the bswap asm. For now, we don't support 486 or 18553 // lower so don't worry about this. 18554 // bswap $0 18555 if (matchAsm(AsmPieces[0], "bswap", "$0") || 18556 matchAsm(AsmPieces[0], "bswapl", "$0") || 18557 matchAsm(AsmPieces[0], "bswapq", "$0") || 18558 matchAsm(AsmPieces[0], "bswap", "${0:q}") || 18559 matchAsm(AsmPieces[0], "bswapl", "${0:q}") || 18560 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) { 18561 // No need to check constraints, nothing other than the equivalent of 18562 // "=r,0" would be valid here. 18563 return IntrinsicLowering::LowerToByteSwap(CI); 18564 } 18565 18566 // rorw $$8, ${0:w} --> llvm.bswap.i16 18567 if (CI->getType()->isIntegerTy(16) && 18568 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 18569 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") || 18570 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) { 18571 AsmPieces.clear(); 18572 const std::string &ConstraintsStr = IA->getConstraintString(); 18573 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 18574 array_pod_sort(AsmPieces.begin(), AsmPieces.end()); 18575 if (AsmPieces.size() == 4 && 18576 AsmPieces[0] == "~{cc}" && 18577 AsmPieces[1] == "~{dirflag}" && 18578 AsmPieces[2] == "~{flags}" && 18579 AsmPieces[3] == "~{fpsr}") 18580 return IntrinsicLowering::LowerToByteSwap(CI); 18581 } 18582 break; 18583 case 3: 18584 if (CI->getType()->isIntegerTy(32) && 18585 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 18586 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") && 18587 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") && 18588 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) { 18589 AsmPieces.clear(); 18590 const std::string &ConstraintsStr = IA->getConstraintString(); 18591 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 18592 array_pod_sort(AsmPieces.begin(), AsmPieces.end()); 18593 if (AsmPieces.size() == 4 && 18594 AsmPieces[0] == "~{cc}" && 18595 AsmPieces[1] == "~{dirflag}" && 18596 AsmPieces[2] == "~{flags}" && 18597 AsmPieces[3] == "~{fpsr}") 18598 return IntrinsicLowering::LowerToByteSwap(CI); 18599 } 18600 18601 if (CI->getType()->isIntegerTy(64)) { 18602 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 18603 if (Constraints.size() >= 2 && 18604 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 18605 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 18606 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 18607 if (matchAsm(AsmPieces[0], "bswap", "%eax") && 18608 matchAsm(AsmPieces[1], "bswap", "%edx") && 18609 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx")) 18610 return IntrinsicLowering::LowerToByteSwap(CI); 18611 } 18612 } 18613 break; 18614 } 18615 return false; 18616 } 18617 18618 /// getConstraintType - Given a constraint letter, return the type of 18619 /// constraint it is for this target. 18620 X86TargetLowering::ConstraintType 18621 X86TargetLowering::getConstraintType(const std::string &Constraint) const { 18622 if (Constraint.size() == 1) { 18623 switch (Constraint[0]) { 18624 case 'R': 18625 case 'q': 18626 case 'Q': 18627 case 'f': 18628 case 't': 18629 case 'u': 18630 case 'y': 18631 case 'x': 18632 case 'Y': 18633 case 'l': 18634 return C_RegisterClass; 18635 case 'a': 18636 case 'b': 18637 case 'c': 18638 case 'd': 18639 case 'S': 18640 case 'D': 18641 case 'A': 18642 return C_Register; 18643 case 'I': 18644 case 'J': 18645 case 'K': 18646 case 'L': 18647 case 'M': 18648 case 'N': 18649 case 'G': 18650 case 'C': 18651 case 'e': 18652 case 'Z': 18653 return C_Other; 18654 default: 18655 break; 18656 } 18657 } 18658 return TargetLowering::getConstraintType(Constraint); 18659 } 18660 18661 /// Examine constraint type and operand type and determine a weight value. 18662 /// This object must already have been set up with the operand type 18663 /// and the current alternative constraint selected. 18664 TargetLowering::ConstraintWeight 18665 X86TargetLowering::getSingleConstraintMatchWeight( 18666 AsmOperandInfo &info, const char *constraint) const { 18667 ConstraintWeight weight = CW_Invalid; 18668 Value *CallOperandVal = info.CallOperandVal; 18669 // If we don't have a value, we can't do a match, 18670 // but allow it at the lowest weight. 18671 if (CallOperandVal == NULL) 18672 return CW_Default; 18673 Type *type = CallOperandVal->getType(); 18674 // Look at the constraint type. 18675 switch (*constraint) { 18676 default: 18677 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 18678 case 'R': 18679 case 'q': 18680 case 'Q': 18681 case 'a': 18682 case 'b': 18683 case 'c': 18684 case 'd': 18685 case 'S': 18686 case 'D': 18687 case 'A': 18688 if (CallOperandVal->getType()->isIntegerTy()) 18689 weight = CW_SpecificReg; 18690 break; 18691 case 'f': 18692 case 't': 18693 case 'u': 18694 if (type->isFloatingPointTy()) 18695 weight = CW_SpecificReg; 18696 break; 18697 case 'y': 18698 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 18699 weight = CW_SpecificReg; 18700 break; 18701 case 'x': 18702 case 'Y': 18703 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) || 18704 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256())) 18705 weight = CW_Register; 18706 break; 18707 case 'I': 18708 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 18709 if (C->getZExtValue() <= 31) 18710 weight = CW_Constant; 18711 } 18712 break; 18713 case 'J': 18714 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18715 if (C->getZExtValue() <= 63) 18716 weight = CW_Constant; 18717 } 18718 break; 18719 case 'K': 18720 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18721 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 18722 weight = CW_Constant; 18723 } 18724 break; 18725 case 'L': 18726 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18727 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 18728 weight = CW_Constant; 18729 } 18730 break; 18731 case 'M': 18732 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18733 if (C->getZExtValue() <= 3) 18734 weight = CW_Constant; 18735 } 18736 break; 18737 case 'N': 18738 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18739 if (C->getZExtValue() <= 0xff) 18740 weight = CW_Constant; 18741 } 18742 break; 18743 case 'G': 18744 case 'C': 18745 if (dyn_cast<ConstantFP>(CallOperandVal)) { 18746 weight = CW_Constant; 18747 } 18748 break; 18749 case 'e': 18750 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18751 if ((C->getSExtValue() >= -0x80000000LL) && 18752 (C->getSExtValue() <= 0x7fffffffLL)) 18753 weight = CW_Constant; 18754 } 18755 break; 18756 case 'Z': 18757 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18758 if (C->getZExtValue() <= 0xffffffff) 18759 weight = CW_Constant; 18760 } 18761 break; 18762 } 18763 return weight; 18764 } 18765 18766 /// LowerXConstraint - try to replace an X constraint, which matches anything, 18767 /// with another that has more specific requirements based on the type of the 18768 /// corresponding operand. 18769 const char *X86TargetLowering:: 18770 LowerXConstraint(EVT ConstraintVT) const { 18771 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 18772 // 'f' like normal targets. 18773 if (ConstraintVT.isFloatingPoint()) { 18774 if (Subtarget->hasSSE2()) 18775 return "Y"; 18776 if (Subtarget->hasSSE1()) 18777 return "x"; 18778 } 18779 18780 return TargetLowering::LowerXConstraint(ConstraintVT); 18781 } 18782 18783 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 18784 /// vector. If it is invalid, don't add anything to Ops. 18785 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 18786 std::string &Constraint, 18787 std::vector<SDValue>&Ops, 18788 SelectionDAG &DAG) const { 18789 SDValue Result(0, 0); 18790 18791 // Only support length 1 constraints for now. 18792 if (Constraint.length() > 1) return; 18793 18794 char ConstraintLetter = Constraint[0]; 18795 switch (ConstraintLetter) { 18796 default: break; 18797 case 'I': 18798 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18799 if (C->getZExtValue() <= 31) { 18800 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18801 break; 18802 } 18803 } 18804 return; 18805 case 'J': 18806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18807 if (C->getZExtValue() <= 63) { 18808 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18809 break; 18810 } 18811 } 18812 return; 18813 case 'K': 18814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18815 if (isInt<8>(C->getSExtValue())) { 18816 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18817 break; 18818 } 18819 } 18820 return; 18821 case 'N': 18822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18823 if (C->getZExtValue() <= 255) { 18824 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18825 break; 18826 } 18827 } 18828 return; 18829 case 'e': { 18830 // 32-bit signed value 18831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18832 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 18833 C->getSExtValue())) { 18834 // Widen to 64 bits here to get it sign extended. 18835 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 18836 break; 18837 } 18838 // FIXME gcc accepts some relocatable values here too, but only in certain 18839 // memory models; it's complicated. 18840 } 18841 return; 18842 } 18843 case 'Z': { 18844 // 32-bit unsigned value 18845 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18846 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 18847 C->getZExtValue())) { 18848 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18849 break; 18850 } 18851 } 18852 // FIXME gcc accepts some relocatable values here too, but only in certain 18853 // memory models; it's complicated. 18854 return; 18855 } 18856 case 'i': { 18857 // Literal immediates are always ok. 18858 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 18859 // Widen to 64 bits here to get it sign extended. 18860 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 18861 break; 18862 } 18863 18864 // In any sort of PIC mode addresses need to be computed at runtime by 18865 // adding in a register or some sort of table lookup. These can't 18866 // be used as immediates. 18867 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 18868 return; 18869 18870 // If we are in non-pic codegen mode, we allow the address of a global (with 18871 // an optional displacement) to be used with 'i'. 18872 GlobalAddressSDNode *GA = 0; 18873 int64_t Offset = 0; 18874 18875 // Match either (GA), (GA+C), (GA+C1+C2), etc. 18876 while (1) { 18877 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 18878 Offset += GA->getOffset(); 18879 break; 18880 } else if (Op.getOpcode() == ISD::ADD) { 18881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 18882 Offset += C->getZExtValue(); 18883 Op = Op.getOperand(0); 18884 continue; 18885 } 18886 } else if (Op.getOpcode() == ISD::SUB) { 18887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 18888 Offset += -C->getZExtValue(); 18889 Op = Op.getOperand(0); 18890 continue; 18891 } 18892 } 18893 18894 // Otherwise, this isn't something we can handle, reject it. 18895 return; 18896 } 18897 18898 const GlobalValue *GV = GA->getGlobal(); 18899 // If we require an extra load to get this address, as in PIC mode, we 18900 // can't accept it. 18901 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 18902 getTargetMachine()))) 18903 return; 18904 18905 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), 18906 GA->getValueType(0), Offset); 18907 break; 18908 } 18909 } 18910 18911 if (Result.getNode()) { 18912 Ops.push_back(Result); 18913 return; 18914 } 18915 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 18916 } 18917 18918 std::pair<unsigned, const TargetRegisterClass*> 18919 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 18920 MVT VT) const { 18921 // First, see if this is a constraint that directly corresponds to an LLVM 18922 // register class. 18923 if (Constraint.size() == 1) { 18924 // GCC Constraint Letters 18925 switch (Constraint[0]) { 18926 default: break; 18927 // TODO: Slight differences here in allocation order and leaving 18928 // RIP in the class. Do they matter any more here than they do 18929 // in the normal allocation? 18930 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 18931 if (Subtarget->is64Bit()) { 18932 if (VT == MVT::i32 || VT == MVT::f32) 18933 return std::make_pair(0U, &X86::GR32RegClass); 18934 if (VT == MVT::i16) 18935 return std::make_pair(0U, &X86::GR16RegClass); 18936 if (VT == MVT::i8 || VT == MVT::i1) 18937 return std::make_pair(0U, &X86::GR8RegClass); 18938 if (VT == MVT::i64 || VT == MVT::f64) 18939 return std::make_pair(0U, &X86::GR64RegClass); 18940 break; 18941 } 18942 // 32-bit fallthrough 18943 case 'Q': // Q_REGS 18944 if (VT == MVT::i32 || VT == MVT::f32) 18945 return std::make_pair(0U, &X86::GR32_ABCDRegClass); 18946 if (VT == MVT::i16) 18947 return std::make_pair(0U, &X86::GR16_ABCDRegClass); 18948 if (VT == MVT::i8 || VT == MVT::i1) 18949 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass); 18950 if (VT == MVT::i64) 18951 return std::make_pair(0U, &X86::GR64_ABCDRegClass); 18952 break; 18953 case 'r': // GENERAL_REGS 18954 case 'l': // INDEX_REGS 18955 if (VT == MVT::i8 || VT == MVT::i1) 18956 return std::make_pair(0U, &X86::GR8RegClass); 18957 if (VT == MVT::i16) 18958 return std::make_pair(0U, &X86::GR16RegClass); 18959 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 18960 return std::make_pair(0U, &X86::GR32RegClass); 18961 return std::make_pair(0U, &X86::GR64RegClass); 18962 case 'R': // LEGACY_REGS 18963 if (VT == MVT::i8 || VT == MVT::i1) 18964 return std::make_pair(0U, &X86::GR8_NOREXRegClass); 18965 if (VT == MVT::i16) 18966 return std::make_pair(0U, &X86::GR16_NOREXRegClass); 18967 if (VT == MVT::i32 || !Subtarget->is64Bit()) 18968 return std::make_pair(0U, &X86::GR32_NOREXRegClass); 18969 return std::make_pair(0U, &X86::GR64_NOREXRegClass); 18970 case 'f': // FP Stack registers. 18971 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 18972 // value to the correct fpstack register class. 18973 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 18974 return std::make_pair(0U, &X86::RFP32RegClass); 18975 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 18976 return std::make_pair(0U, &X86::RFP64RegClass); 18977 return std::make_pair(0U, &X86::RFP80RegClass); 18978 case 'y': // MMX_REGS if MMX allowed. 18979 if (!Subtarget->hasMMX()) break; 18980 return std::make_pair(0U, &X86::VR64RegClass); 18981 case 'Y': // SSE_REGS if SSE2 allowed 18982 if (!Subtarget->hasSSE2()) break; 18983 // FALL THROUGH. 18984 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed 18985 if (!Subtarget->hasSSE1()) break; 18986 18987 switch (VT.SimpleTy) { 18988 default: break; 18989 // Scalar SSE types. 18990 case MVT::f32: 18991 case MVT::i32: 18992 return std::make_pair(0U, &X86::FR32RegClass); 18993 case MVT::f64: 18994 case MVT::i64: 18995 return std::make_pair(0U, &X86::FR64RegClass); 18996 // Vector types. 18997 case MVT::v16i8: 18998 case MVT::v8i16: 18999 case MVT::v4i32: 19000 case MVT::v2i64: 19001 case MVT::v4f32: 19002 case MVT::v2f64: 19003 return std::make_pair(0U, &X86::VR128RegClass); 19004 // AVX types. 19005 case MVT::v32i8: 19006 case MVT::v16i16: 19007 case MVT::v8i32: 19008 case MVT::v4i64: 19009 case MVT::v8f32: 19010 case MVT::v4f64: 19011 return std::make_pair(0U, &X86::VR256RegClass); 19012 case MVT::v8f64: 19013 case MVT::v16f32: 19014 case MVT::v16i32: 19015 case MVT::v8i64: 19016 return std::make_pair(0U, &X86::VR512RegClass); 19017 } 19018 break; 19019 } 19020 } 19021 19022 // Use the default implementation in TargetLowering to convert the register 19023 // constraint into a member of a register class. 19024 std::pair<unsigned, const TargetRegisterClass*> Res; 19025 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 19026 19027 // Not found as a standard register? 19028 if (Res.second == 0) { 19029 // Map st(0) -> st(7) -> ST0 19030 if (Constraint.size() == 7 && Constraint[0] == '{' && 19031 std::tolower(Constraint[1]) == 's' && 19032 std::tolower(Constraint[2]) == 't' && 19033 Constraint[3] == '(' && 19034 (Constraint[4] >= '0' && Constraint[4] <= '7') && 19035 Constraint[5] == ')' && 19036 Constraint[6] == '}') { 19037 19038 Res.first = X86::ST0+Constraint[4]-'0'; 19039 Res.second = &X86::RFP80RegClass; 19040 return Res; 19041 } 19042 19043 // GCC allows "st(0)" to be called just plain "st". 19044 if (StringRef("{st}").equals_lower(Constraint)) { 19045 Res.first = X86::ST0; 19046 Res.second = &X86::RFP80RegClass; 19047 return Res; 19048 } 19049 19050 // flags -> EFLAGS 19051 if (StringRef("{flags}").equals_lower(Constraint)) { 19052 Res.first = X86::EFLAGS; 19053 Res.second = &X86::CCRRegClass; 19054 return Res; 19055 } 19056 19057 // 'A' means EAX + EDX. 19058 if (Constraint == "A") { 19059 Res.first = X86::EAX; 19060 Res.second = &X86::GR32_ADRegClass; 19061 return Res; 19062 } 19063 return Res; 19064 } 19065 19066 // Otherwise, check to see if this is a register class of the wrong value 19067 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 19068 // turn into {ax},{dx}. 19069 if (Res.second->hasType(VT)) 19070 return Res; // Correct type already, nothing to do. 19071 19072 // All of the single-register GCC register classes map their values onto 19073 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 19074 // really want an 8-bit or 32-bit register, map to the appropriate register 19075 // class and return the appropriate register. 19076 if (Res.second == &X86::GR16RegClass) { 19077 if (VT == MVT::i8 || VT == MVT::i1) { 19078 unsigned DestReg = 0; 19079 switch (Res.first) { 19080 default: break; 19081 case X86::AX: DestReg = X86::AL; break; 19082 case X86::DX: DestReg = X86::DL; break; 19083 case X86::CX: DestReg = X86::CL; break; 19084 case X86::BX: DestReg = X86::BL; break; 19085 } 19086 if (DestReg) { 19087 Res.first = DestReg; 19088 Res.second = &X86::GR8RegClass; 19089 } 19090 } else if (VT == MVT::i32 || VT == MVT::f32) { 19091 unsigned DestReg = 0; 19092 switch (Res.first) { 19093 default: break; 19094 case X86::AX: DestReg = X86::EAX; break; 19095 case X86::DX: DestReg = X86::EDX; break; 19096 case X86::CX: DestReg = X86::ECX; break; 19097 case X86::BX: DestReg = X86::EBX; break; 19098 case X86::SI: DestReg = X86::ESI; break; 19099 case X86::DI: DestReg = X86::EDI; break; 19100 case X86::BP: DestReg = X86::EBP; break; 19101 case X86::SP: DestReg = X86::ESP; break; 19102 } 19103 if (DestReg) { 19104 Res.first = DestReg; 19105 Res.second = &X86::GR32RegClass; 19106 } 19107 } else if (VT == MVT::i64 || VT == MVT::f64) { 19108 unsigned DestReg = 0; 19109 switch (Res.first) { 19110 default: break; 19111 case X86::AX: DestReg = X86::RAX; break; 19112 case X86::DX: DestReg = X86::RDX; break; 19113 case X86::CX: DestReg = X86::RCX; break; 19114 case X86::BX: DestReg = X86::RBX; break; 19115 case X86::SI: DestReg = X86::RSI; break; 19116 case X86::DI: DestReg = X86::RDI; break; 19117 case X86::BP: DestReg = X86::RBP; break; 19118 case X86::SP: DestReg = X86::RSP; break; 19119 } 19120 if (DestReg) { 19121 Res.first = DestReg; 19122 Res.second = &X86::GR64RegClass; 19123 } 19124 } 19125 } else if (Res.second == &X86::FR32RegClass || 19126 Res.second == &X86::FR64RegClass || 19127 Res.second == &X86::VR128RegClass || 19128 Res.second == &X86::VR256RegClass || 19129 Res.second == &X86::FR32XRegClass || 19130 Res.second == &X86::FR64XRegClass || 19131 Res.second == &X86::VR128XRegClass || 19132 Res.second == &X86::VR256XRegClass || 19133 Res.second == &X86::VR512RegClass) { 19134 // Handle references to XMM physical registers that got mapped into the 19135 // wrong class. This can happen with constraints like {xmm0} where the 19136 // target independent register mapper will just pick the first match it can 19137 // find, ignoring the required type. 19138 19139 if (VT == MVT::f32 || VT == MVT::i32) 19140 Res.second = &X86::FR32RegClass; 19141 else if (VT == MVT::f64 || VT == MVT::i64) 19142 Res.second = &X86::FR64RegClass; 19143 else if (X86::VR128RegClass.hasType(VT)) 19144 Res.second = &X86::VR128RegClass; 19145 else if (X86::VR256RegClass.hasType(VT)) 19146 Res.second = &X86::VR256RegClass; 19147 else if (X86::VR512RegClass.hasType(VT)) 19148 Res.second = &X86::VR512RegClass; 19149 } 19150 19151 return Res; 19152 } 19153