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 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This 62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a 63 /// simple subregister reference. Idx is an index in the 128 bits we 64 /// want. It need not be aligned to a 128-bit bounday. That makes 65 /// lowering EXTRACT_VECTOR_ELT operations easier. 66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal, 67 SelectionDAG &DAG, SDLoc dl) { 68 EVT VT = Vec.getValueType(); 69 assert(VT.is256BitVector() && "Unexpected vector size!"); 70 EVT ElVT = VT.getVectorElementType(); 71 unsigned Factor = VT.getSizeInBits()/128; 72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 73 VT.getVectorNumElements()/Factor); 74 75 // Extract from UNDEF is UNDEF. 76 if (Vec.getOpcode() == ISD::UNDEF) 77 return DAG.getUNDEF(ResultVT); 78 79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 80 // we can match to VEXTRACTF128. 81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 82 83 // This is the index of the first element of the 128-bit chunk 84 // we want. 85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 86 * ElemsPerChunk); 87 88 // If the input is a buildvector just emit a smaller one. 89 if (Vec.getOpcode() == ISD::BUILD_VECTOR) 90 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT, 91 Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk); 92 93 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 94 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 95 VecIdx); 96 97 return Result; 98 } 99 100 /// Generate a DAG to put 128-bits into a vector > 128 bits. This 101 /// sets things up to match to an AVX VINSERTF128 instruction or a 102 /// simple superregister reference. Idx is an index in the 128 bits 103 /// we want. It need not be aligned to a 128-bit bounday. That makes 104 /// lowering INSERT_VECTOR_ELT operations easier. 105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, 106 unsigned IdxVal, SelectionDAG &DAG, 107 SDLoc dl) { 108 // Inserting UNDEF is Result 109 if (Vec.getOpcode() == ISD::UNDEF) 110 return Result; 111 112 EVT VT = Vec.getValueType(); 113 assert(VT.is128BitVector() && "Unexpected vector size!"); 114 115 EVT ElVT = VT.getVectorElementType(); 116 EVT ResultVT = Result.getValueType(); 117 118 // Insert the relevant 128 bits. 119 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 120 121 // This is the index of the first element of the 128-bit chunk 122 // we want. 123 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 124 * ElemsPerChunk); 125 126 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 127 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 128 VecIdx); 129 } 130 131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128 132 /// instructions. This is used because creating CONCAT_VECTOR nodes of 133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower 134 /// large BUILD_VECTORS. 135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT, 136 unsigned NumElems, SelectionDAG &DAG, 137 SDLoc dl) { 138 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl); 139 return Insert128BitVector(V, V2, NumElems/2, DAG, dl); 140 } 141 142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 143 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 144 bool is64Bit = Subtarget->is64Bit(); 145 146 if (Subtarget->isTargetEnvMacho()) { 147 if (is64Bit) 148 return new X86_64MachoTargetObjectFile(); 149 return new TargetLoweringObjectFileMachO(); 150 } 151 152 if (Subtarget->isTargetLinux()) 153 return new X86LinuxTargetObjectFile(); 154 if (Subtarget->isTargetELF()) 155 return new TargetLoweringObjectFileELF(); 156 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 157 return new TargetLoweringObjectFileCOFF(); 158 llvm_unreachable("unknown subtarget type"); 159 } 160 161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 162 : TargetLowering(TM, createTLOF(TM)) { 163 Subtarget = &TM.getSubtarget<X86Subtarget>(); 164 X86ScalarSSEf64 = Subtarget->hasSSE2(); 165 X86ScalarSSEf32 = Subtarget->hasSSE1(); 166 TD = getDataLayout(); 167 168 resetOperationActions(); 169 } 170 171 void X86TargetLowering::resetOperationActions() { 172 const TargetMachine &TM = getTargetMachine(); 173 static bool FirstTimeThrough = true; 174 175 // If none of the target options have changed, then we don't need to reset the 176 // operation actions. 177 if (!FirstTimeThrough && TO == TM.Options) return; 178 179 if (!FirstTimeThrough) { 180 // Reinitialize the actions. 181 initActions(); 182 FirstTimeThrough = false; 183 } 184 185 TO = TM.Options; 186 187 // Set up the TargetLowering object. 188 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 189 190 // X86 is weird, it always uses i8 for shift amounts and setcc results. 191 setBooleanContents(ZeroOrOneBooleanContent); 192 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 193 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 194 195 // For 64-bit since we have so many registers use the ILP scheduler, for 196 // 32-bit code use the register pressure specific scheduling. 197 // For Atom, always use ILP scheduling. 198 if (Subtarget->isAtom()) 199 setSchedulingPreference(Sched::ILP); 200 else if (Subtarget->is64Bit()) 201 setSchedulingPreference(Sched::ILP); 202 else 203 setSchedulingPreference(Sched::RegPressure); 204 const X86RegisterInfo *RegInfo = 205 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo()); 206 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister()); 207 208 // Bypass expensive divides on Atom when compiling with O2 209 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) { 210 addBypassSlowDiv(32, 8); 211 if (Subtarget->is64Bit()) 212 addBypassSlowDiv(64, 16); 213 } 214 215 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 216 // Setup Windows compiler runtime calls. 217 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 218 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 219 setLibcallName(RTLIB::SREM_I64, "_allrem"); 220 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 221 setLibcallName(RTLIB::MUL_I64, "_allmul"); 222 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 223 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 224 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 225 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 226 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 227 228 // The _ftol2 runtime function has an unusual calling conv, which 229 // is modeled by a special pseudo-instruction. 230 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0); 231 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0); 232 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0); 233 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0); 234 } 235 236 if (Subtarget->isTargetDarwin()) { 237 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 238 setUseUnderscoreSetJmp(false); 239 setUseUnderscoreLongJmp(false); 240 } else if (Subtarget->isTargetMingw()) { 241 // MS runtime is weird: it exports _setjmp, but longjmp! 242 setUseUnderscoreSetJmp(true); 243 setUseUnderscoreLongJmp(false); 244 } else { 245 setUseUnderscoreSetJmp(true); 246 setUseUnderscoreLongJmp(true); 247 } 248 249 // Set up the register classes. 250 addRegisterClass(MVT::i8, &X86::GR8RegClass); 251 addRegisterClass(MVT::i16, &X86::GR16RegClass); 252 addRegisterClass(MVT::i32, &X86::GR32RegClass); 253 if (Subtarget->is64Bit()) 254 addRegisterClass(MVT::i64, &X86::GR64RegClass); 255 256 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 257 258 // We don't accept any truncstore of integer registers. 259 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 260 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 261 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 262 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 263 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 264 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 265 266 // SETOEQ and SETUNE require checking two conditions. 267 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 268 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 269 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 270 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 271 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 272 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 273 274 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 275 // operation. 276 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 277 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 278 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 279 280 if (Subtarget->is64Bit()) { 281 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 282 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 283 } else if (!TM.Options.UseSoftFloat) { 284 // We have an algorithm for SSE2->double, and we turn this into a 285 // 64-bit FILD followed by conditional FADD for other targets. 286 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 287 // We have an algorithm for SSE2, and we turn this into a 64-bit 288 // FILD for other targets. 289 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 290 } 291 292 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 293 // this operation. 294 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 295 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 296 297 if (!TM.Options.UseSoftFloat) { 298 // SSE has no i16 to fp conversion, only i32 299 if (X86ScalarSSEf32) { 300 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 301 // f32 and f64 cases are Legal, f80 case is not 302 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 303 } else { 304 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 305 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 306 } 307 } else { 308 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 309 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 310 } 311 312 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 313 // are Legal, f80 is custom lowered. 314 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 315 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 316 317 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 318 // this operation. 319 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 320 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 321 322 if (X86ScalarSSEf32) { 323 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 324 // f32 and f64 cases are Legal, f80 case is not 325 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 326 } else { 327 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 328 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 329 } 330 331 // Handle FP_TO_UINT by promoting the destination to a larger signed 332 // conversion. 333 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 334 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 335 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 336 337 if (Subtarget->is64Bit()) { 338 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 339 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 340 } else if (!TM.Options.UseSoftFloat) { 341 // Since AVX is a superset of SSE3, only check for SSE here. 342 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 343 // Expand FP_TO_UINT into a select. 344 // FIXME: We would like to use a Custom expander here eventually to do 345 // the optimal thing for SSE vs. the default expansion in the legalizer. 346 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 347 else 348 // With SSE3 we can use fisttpll to convert to a signed i64; without 349 // SSE, we're stuck with a fistpll. 350 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 351 } 352 353 if (isTargetFTOL()) { 354 // Use the _ftol2 runtime function, which has a pseudo-instruction 355 // to handle its weird calling convention. 356 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom); 357 } 358 359 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 360 if (!X86ScalarSSEf64) { 361 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 362 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 363 if (Subtarget->is64Bit()) { 364 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 365 // Without SSE, i64->f64 goes through memory. 366 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 367 } 368 } 369 370 // Scalar integer divide and remainder are lowered to use operations that 371 // produce two results, to match the available instructions. This exposes 372 // the two-result form to trivial CSE, which is able to combine x/y and x%y 373 // into a single instruction. 374 // 375 // Scalar integer multiply-high is also lowered to use two-result 376 // operations, to match the available instructions. However, plain multiply 377 // (low) operations are left as Legal, as there are single-result 378 // instructions for this in x86. Using the two-result multiply instructions 379 // when both high and low results are needed must be arranged by dagcombine. 380 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 381 MVT VT = IntVTs[i]; 382 setOperationAction(ISD::MULHS, VT, Expand); 383 setOperationAction(ISD::MULHU, VT, Expand); 384 setOperationAction(ISD::SDIV, VT, Expand); 385 setOperationAction(ISD::UDIV, VT, Expand); 386 setOperationAction(ISD::SREM, VT, Expand); 387 setOperationAction(ISD::UREM, VT, Expand); 388 389 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 390 setOperationAction(ISD::ADDC, VT, Custom); 391 setOperationAction(ISD::ADDE, VT, Custom); 392 setOperationAction(ISD::SUBC, VT, Custom); 393 setOperationAction(ISD::SUBE, VT, Custom); 394 } 395 396 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 397 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 398 setOperationAction(ISD::BR_CC , MVT::f32, Expand); 399 setOperationAction(ISD::BR_CC , MVT::f64, Expand); 400 setOperationAction(ISD::BR_CC , MVT::f80, Expand); 401 setOperationAction(ISD::BR_CC , MVT::i8, Expand); 402 setOperationAction(ISD::BR_CC , MVT::i16, Expand); 403 setOperationAction(ISD::BR_CC , MVT::i32, Expand); 404 setOperationAction(ISD::BR_CC , MVT::i64, Expand); 405 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 406 if (Subtarget->is64Bit()) 407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 411 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 412 setOperationAction(ISD::FREM , MVT::f32 , Expand); 413 setOperationAction(ISD::FREM , MVT::f64 , Expand); 414 setOperationAction(ISD::FREM , MVT::f80 , Expand); 415 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 416 417 // Promote the i8 variants and force them on up to i32 which has a shorter 418 // encoding. 419 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 420 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32); 421 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote); 422 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32); 423 if (Subtarget->hasBMI()) { 424 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand); 425 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand); 426 if (Subtarget->is64Bit()) 427 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 428 } else { 429 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 430 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 431 if (Subtarget->is64Bit()) 432 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 433 } 434 435 if (Subtarget->hasLZCNT()) { 436 // When promoting the i8 variants, force them to i32 for a shorter 437 // encoding. 438 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 439 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32); 440 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote); 441 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32); 442 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand); 443 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand); 444 if (Subtarget->is64Bit()) 445 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 446 } else { 447 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 448 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 449 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 450 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom); 451 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom); 452 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom); 453 if (Subtarget->is64Bit()) { 454 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 455 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom); 456 } 457 } 458 459 if (Subtarget->hasPOPCNT()) { 460 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 461 } else { 462 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 463 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 464 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 465 if (Subtarget->is64Bit()) 466 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 467 } 468 469 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 470 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 471 472 // These should be promoted to a larger select which is supported. 473 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 474 // X86 wants to expand cmov itself. 475 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 476 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 477 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 478 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 479 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 480 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 481 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 482 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 483 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 484 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 485 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 486 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 487 if (Subtarget->is64Bit()) { 488 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 489 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 490 } 491 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 492 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 493 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 494 // support continuation, user-level threading, and etc.. As a result, no 495 // other SjLj exception interfaces are implemented and please don't build 496 // your own exception handling based on them. 497 // LLVM/Clang supports zero-cost DWARF exception handling. 498 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 499 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 500 501 // Darwin ABI issue. 502 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 503 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 504 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 505 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 506 if (Subtarget->is64Bit()) 507 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 508 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 509 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 510 if (Subtarget->is64Bit()) { 511 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 512 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 513 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 514 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 515 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 516 } 517 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 518 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 519 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 520 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 521 if (Subtarget->is64Bit()) { 522 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 523 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 524 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 525 } 526 527 if (Subtarget->hasSSE1()) 528 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 529 530 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 531 532 // Expand certain atomics 533 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 534 MVT VT = IntVTs[i]; 535 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 536 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 537 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 538 } 539 540 if (!Subtarget->is64Bit()) { 541 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 542 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 543 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 544 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 545 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 546 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 547 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 548 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 549 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom); 550 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom); 551 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom); 552 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom); 553 } 554 555 if (Subtarget->hasCmpxchg16b()) { 556 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 557 } 558 559 // FIXME - use subtarget debug flags 560 if (!Subtarget->isTargetDarwin() && 561 !Subtarget->isTargetELF() && 562 !Subtarget->isTargetCygMing()) { 563 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 564 } 565 566 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 567 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 568 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 569 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 570 if (Subtarget->is64Bit()) { 571 setExceptionPointerRegister(X86::RAX); 572 setExceptionSelectorRegister(X86::RDX); 573 } else { 574 setExceptionPointerRegister(X86::EAX); 575 setExceptionSelectorRegister(X86::EDX); 576 } 577 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 578 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 579 580 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 581 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 582 583 setOperationAction(ISD::TRAP, MVT::Other, Legal); 584 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 585 586 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 587 setOperationAction(ISD::VASTART , MVT::Other, Custom); 588 setOperationAction(ISD::VAEND , MVT::Other, Expand); 589 if (Subtarget->is64Bit()) { 590 setOperationAction(ISD::VAARG , MVT::Other, Custom); 591 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 592 } else { 593 setOperationAction(ISD::VAARG , MVT::Other, Expand); 594 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 595 } 596 597 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 598 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 599 600 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 601 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 602 MVT::i64 : MVT::i32, Custom); 603 else if (TM.Options.EnableSegmentedStacks) 604 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 605 MVT::i64 : MVT::i32, Custom); 606 else 607 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 608 MVT::i64 : MVT::i32, Expand); 609 610 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) { 611 // f32 and f64 use SSE. 612 // Set up the FP register classes. 613 addRegisterClass(MVT::f32, &X86::FR32RegClass); 614 addRegisterClass(MVT::f64, &X86::FR64RegClass); 615 616 // Use ANDPD to simulate FABS. 617 setOperationAction(ISD::FABS , MVT::f64, Custom); 618 setOperationAction(ISD::FABS , MVT::f32, Custom); 619 620 // Use XORP to simulate FNEG. 621 setOperationAction(ISD::FNEG , MVT::f64, Custom); 622 setOperationAction(ISD::FNEG , MVT::f32, Custom); 623 624 // Use ANDPD and ORPD to simulate FCOPYSIGN. 625 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 626 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 627 628 // Lower this to FGETSIGNx86 plus an AND. 629 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 630 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 631 632 // We don't support sin/cos/fmod 633 setOperationAction(ISD::FSIN , MVT::f64, Expand); 634 setOperationAction(ISD::FCOS , MVT::f64, Expand); 635 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 636 setOperationAction(ISD::FSIN , MVT::f32, Expand); 637 setOperationAction(ISD::FCOS , MVT::f32, Expand); 638 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 639 640 // Expand FP immediates into loads from the stack, except for the special 641 // cases we handle. 642 addLegalFPImmediate(APFloat(+0.0)); // xorpd 643 addLegalFPImmediate(APFloat(+0.0f)); // xorps 644 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) { 645 // Use SSE for f32, x87 for f64. 646 // Set up the FP register classes. 647 addRegisterClass(MVT::f32, &X86::FR32RegClass); 648 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 649 650 // Use ANDPS to simulate FABS. 651 setOperationAction(ISD::FABS , MVT::f32, Custom); 652 653 // Use XORP to simulate FNEG. 654 setOperationAction(ISD::FNEG , MVT::f32, Custom); 655 656 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 657 658 // Use ANDPS and ORPS to simulate FCOPYSIGN. 659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 661 662 // We don't support sin/cos/fmod 663 setOperationAction(ISD::FSIN , MVT::f32, Expand); 664 setOperationAction(ISD::FCOS , MVT::f32, Expand); 665 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 666 667 // Special cases we handle for FP constants. 668 addLegalFPImmediate(APFloat(+0.0f)); // xorps 669 addLegalFPImmediate(APFloat(+0.0)); // FLD0 670 addLegalFPImmediate(APFloat(+1.0)); // FLD1 671 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 672 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 673 674 if (!TM.Options.UnsafeFPMath) { 675 setOperationAction(ISD::FSIN , MVT::f64, Expand); 676 setOperationAction(ISD::FCOS , MVT::f64, Expand); 677 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 678 } 679 } else if (!TM.Options.UseSoftFloat) { 680 // f32 and f64 in x87. 681 // Set up the FP register classes. 682 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 683 addRegisterClass(MVT::f32, &X86::RFP32RegClass); 684 685 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 686 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 687 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 688 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 689 690 if (!TM.Options.UnsafeFPMath) { 691 setOperationAction(ISD::FSIN , MVT::f64, Expand); 692 setOperationAction(ISD::FSIN , MVT::f32, Expand); 693 setOperationAction(ISD::FCOS , MVT::f64, Expand); 694 setOperationAction(ISD::FCOS , MVT::f32, Expand); 695 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 696 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 697 } 698 addLegalFPImmediate(APFloat(+0.0)); // FLD0 699 addLegalFPImmediate(APFloat(+1.0)); // FLD1 700 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 701 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 702 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 703 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 704 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 705 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 706 } 707 708 // We don't support FMA. 709 setOperationAction(ISD::FMA, MVT::f64, Expand); 710 setOperationAction(ISD::FMA, MVT::f32, Expand); 711 712 // Long double always uses X87. 713 if (!TM.Options.UseSoftFloat) { 714 addRegisterClass(MVT::f80, &X86::RFP80RegClass); 715 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 716 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 717 { 718 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 719 addLegalFPImmediate(TmpFlt); // FLD0 720 TmpFlt.changeSign(); 721 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 722 723 bool ignored; 724 APFloat TmpFlt2(+1.0); 725 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 726 &ignored); 727 addLegalFPImmediate(TmpFlt2); // FLD1 728 TmpFlt2.changeSign(); 729 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 730 } 731 732 if (!TM.Options.UnsafeFPMath) { 733 setOperationAction(ISD::FSIN , MVT::f80, Expand); 734 setOperationAction(ISD::FCOS , MVT::f80, Expand); 735 setOperationAction(ISD::FSINCOS, MVT::f80, Expand); 736 } 737 738 setOperationAction(ISD::FFLOOR, MVT::f80, Expand); 739 setOperationAction(ISD::FCEIL, MVT::f80, Expand); 740 setOperationAction(ISD::FTRUNC, MVT::f80, Expand); 741 setOperationAction(ISD::FRINT, MVT::f80, Expand); 742 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand); 743 setOperationAction(ISD::FMA, MVT::f80, Expand); 744 } 745 746 // Always use a library call for pow. 747 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 748 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 749 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 750 751 setOperationAction(ISD::FLOG, MVT::f80, Expand); 752 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 753 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 754 setOperationAction(ISD::FEXP, MVT::f80, Expand); 755 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 756 757 // First set operation action for all vector types to either promote 758 // (for widening) or expand (for scalarization). Then we will selectively 759 // turn on ones that can be effectively codegen'd. 760 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 761 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 762 MVT VT = (MVT::SimpleValueType)i; 763 setOperationAction(ISD::ADD , VT, Expand); 764 setOperationAction(ISD::SUB , VT, Expand); 765 setOperationAction(ISD::FADD, VT, Expand); 766 setOperationAction(ISD::FNEG, VT, Expand); 767 setOperationAction(ISD::FSUB, VT, Expand); 768 setOperationAction(ISD::MUL , VT, Expand); 769 setOperationAction(ISD::FMUL, VT, Expand); 770 setOperationAction(ISD::SDIV, VT, Expand); 771 setOperationAction(ISD::UDIV, VT, Expand); 772 setOperationAction(ISD::FDIV, VT, Expand); 773 setOperationAction(ISD::SREM, VT, Expand); 774 setOperationAction(ISD::UREM, VT, Expand); 775 setOperationAction(ISD::LOAD, VT, Expand); 776 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand); 777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand); 778 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 779 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand); 780 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand); 781 setOperationAction(ISD::FABS, VT, Expand); 782 setOperationAction(ISD::FSIN, VT, Expand); 783 setOperationAction(ISD::FSINCOS, VT, Expand); 784 setOperationAction(ISD::FCOS, VT, Expand); 785 setOperationAction(ISD::FSINCOS, VT, Expand); 786 setOperationAction(ISD::FREM, VT, Expand); 787 setOperationAction(ISD::FMA, VT, Expand); 788 setOperationAction(ISD::FPOWI, VT, Expand); 789 setOperationAction(ISD::FSQRT, VT, Expand); 790 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 791 setOperationAction(ISD::FFLOOR, VT, Expand); 792 setOperationAction(ISD::FCEIL, VT, Expand); 793 setOperationAction(ISD::FTRUNC, VT, Expand); 794 setOperationAction(ISD::FRINT, VT, Expand); 795 setOperationAction(ISD::FNEARBYINT, VT, Expand); 796 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 797 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 798 setOperationAction(ISD::SDIVREM, VT, Expand); 799 setOperationAction(ISD::UDIVREM, VT, Expand); 800 setOperationAction(ISD::FPOW, VT, Expand); 801 setOperationAction(ISD::CTPOP, VT, Expand); 802 setOperationAction(ISD::CTTZ, VT, Expand); 803 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 804 setOperationAction(ISD::CTLZ, VT, Expand); 805 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 806 setOperationAction(ISD::SHL, VT, Expand); 807 setOperationAction(ISD::SRA, VT, Expand); 808 setOperationAction(ISD::SRL, VT, Expand); 809 setOperationAction(ISD::ROTL, VT, Expand); 810 setOperationAction(ISD::ROTR, VT, Expand); 811 setOperationAction(ISD::BSWAP, VT, Expand); 812 setOperationAction(ISD::SETCC, VT, Expand); 813 setOperationAction(ISD::FLOG, VT, Expand); 814 setOperationAction(ISD::FLOG2, VT, Expand); 815 setOperationAction(ISD::FLOG10, VT, Expand); 816 setOperationAction(ISD::FEXP, VT, Expand); 817 setOperationAction(ISD::FEXP2, VT, Expand); 818 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 819 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 820 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 821 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 822 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand); 823 setOperationAction(ISD::TRUNCATE, VT, Expand); 824 setOperationAction(ISD::SIGN_EXTEND, VT, Expand); 825 setOperationAction(ISD::ZERO_EXTEND, VT, Expand); 826 setOperationAction(ISD::ANY_EXTEND, VT, Expand); 827 setOperationAction(ISD::VSELECT, VT, Expand); 828 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE; 829 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 830 setTruncStoreAction(VT, 831 (MVT::SimpleValueType)InnerVT, Expand); 832 setLoadExtAction(ISD::SEXTLOAD, VT, Expand); 833 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand); 834 setLoadExtAction(ISD::EXTLOAD, VT, Expand); 835 } 836 837 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 838 // with -msoft-float, disable use of MMX as well. 839 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) { 840 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass); 841 // No operations on x86mmx supported, everything uses intrinsics. 842 } 843 844 // MMX-sized vectors (other than x86mmx) are expected to be expanded 845 // into smaller operations. 846 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 847 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 848 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 849 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 850 setOperationAction(ISD::AND, MVT::v8i8, Expand); 851 setOperationAction(ISD::AND, MVT::v4i16, Expand); 852 setOperationAction(ISD::AND, MVT::v2i32, Expand); 853 setOperationAction(ISD::AND, MVT::v1i64, Expand); 854 setOperationAction(ISD::OR, MVT::v8i8, Expand); 855 setOperationAction(ISD::OR, MVT::v4i16, Expand); 856 setOperationAction(ISD::OR, MVT::v2i32, Expand); 857 setOperationAction(ISD::OR, MVT::v1i64, Expand); 858 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 859 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 860 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 861 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 862 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 863 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 864 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 865 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 866 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 867 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 868 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 869 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 870 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 871 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 872 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 873 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 874 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 875 876 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) { 877 addRegisterClass(MVT::v4f32, &X86::VR128RegClass); 878 879 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 880 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 881 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 882 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 883 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 884 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 885 setOperationAction(ISD::FABS, MVT::v4f32, Custom); 886 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 887 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 888 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 889 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 890 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 891 } 892 893 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) { 894 addRegisterClass(MVT::v2f64, &X86::VR128RegClass); 895 896 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 897 // registers cannot be used even for integer operations. 898 addRegisterClass(MVT::v16i8, &X86::VR128RegClass); 899 addRegisterClass(MVT::v8i16, &X86::VR128RegClass); 900 addRegisterClass(MVT::v4i32, &X86::VR128RegClass); 901 addRegisterClass(MVT::v2i64, &X86::VR128RegClass); 902 903 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 904 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 905 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 906 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 907 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 908 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 909 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 910 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 911 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 912 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 913 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 914 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 915 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 916 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 917 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 918 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 919 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 920 setOperationAction(ISD::FABS, MVT::v2f64, Custom); 921 922 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 923 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 924 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 925 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 926 927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 932 933 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 934 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 935 MVT VT = (MVT::SimpleValueType)i; 936 // Do not attempt to custom lower non-power-of-2 vectors 937 if (!isPowerOf2_32(VT.getVectorNumElements())) 938 continue; 939 // Do not attempt to custom lower non-128-bit vectors 940 if (!VT.is128BitVector()) 941 continue; 942 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 943 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 945 } 946 947 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 948 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 949 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 950 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 953 954 if (Subtarget->is64Bit()) { 955 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 956 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 957 } 958 959 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 960 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 961 MVT VT = (MVT::SimpleValueType)i; 962 963 // Do not attempt to promote non-128-bit vectors 964 if (!VT.is128BitVector()) 965 continue; 966 967 setOperationAction(ISD::AND, VT, Promote); 968 AddPromotedToType (ISD::AND, VT, MVT::v2i64); 969 setOperationAction(ISD::OR, VT, Promote); 970 AddPromotedToType (ISD::OR, VT, MVT::v2i64); 971 setOperationAction(ISD::XOR, VT, Promote); 972 AddPromotedToType (ISD::XOR, VT, MVT::v2i64); 973 setOperationAction(ISD::LOAD, VT, Promote); 974 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64); 975 setOperationAction(ISD::SELECT, VT, Promote); 976 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64); 977 } 978 979 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 980 981 // Custom lower v2i64 and v2f64 selects. 982 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 983 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 984 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 985 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 986 987 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 988 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 989 990 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 991 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 992 // As there is no 64-bit GPR available, we need build a special custom 993 // sequence to convert from v2i32 to v2f32. 994 if (!Subtarget->is64Bit()) 995 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom); 996 997 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 998 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom); 999 1000 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal); 1001 } 1002 1003 if (Subtarget->hasSSE41()) { 1004 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 1005 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 1006 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 1007 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1008 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1009 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 1010 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 1011 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 1012 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1013 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1014 1015 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1016 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1017 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1018 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 1021 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 1022 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 1023 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 1024 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 1025 1026 // FIXME: Do we need to handle scalar-to-vector here? 1027 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 1028 1029 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 1030 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 1031 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 1032 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 1033 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1034 1035 // i8 and i16 vectors are custom , because the source register and source 1036 // source memory operand types are not the same width. f32 vectors are 1037 // custom since the immediate controlling the insert encodes additional 1038 // information. 1039 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1040 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1041 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1042 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1043 1044 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 1045 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 1047 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 1048 1049 // FIXME: these should be Legal but thats only for the case where 1050 // the index is constant. For now custom expand to deal with that. 1051 if (Subtarget->is64Bit()) { 1052 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1053 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 1054 } 1055 } 1056 1057 if (Subtarget->hasSSE2()) { 1058 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 1059 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 1060 1061 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 1062 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 1063 1064 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 1065 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 1066 1067 // In the customized shift lowering, the legal cases in AVX2 will be 1068 // recognized. 1069 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 1070 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 1071 1072 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 1073 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 1074 1075 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 1076 1077 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1078 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1079 } 1080 1081 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) { 1082 addRegisterClass(MVT::v32i8, &X86::VR256RegClass); 1083 addRegisterClass(MVT::v16i16, &X86::VR256RegClass); 1084 addRegisterClass(MVT::v8i32, &X86::VR256RegClass); 1085 addRegisterClass(MVT::v8f32, &X86::VR256RegClass); 1086 addRegisterClass(MVT::v4i64, &X86::VR256RegClass); 1087 addRegisterClass(MVT::v4f64, &X86::VR256RegClass); 1088 1089 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 1090 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 1091 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 1092 1093 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 1094 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1095 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1096 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1097 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1098 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal); 1099 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal); 1100 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal); 1101 setOperationAction(ISD::FRINT, MVT::v8f32, Legal); 1102 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal); 1103 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1104 setOperationAction(ISD::FABS, MVT::v8f32, Custom); 1105 1106 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1107 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1108 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1109 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1110 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1111 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1112 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1113 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1114 setOperationAction(ISD::FRINT, MVT::v4f64, Legal); 1115 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal); 1116 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1117 setOperationAction(ISD::FABS, MVT::v4f64, Custom); 1118 1119 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom); 1120 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom); 1121 1122 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 1123 1124 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1125 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 1126 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1127 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1128 1129 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1130 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom); 1131 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 1132 1133 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal); 1134 1135 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1136 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1137 1138 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1139 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1140 1141 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1142 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1143 1144 setOperationAction(ISD::SDIV, MVT::v16i16, Custom); 1145 1146 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1147 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1148 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1149 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1150 1151 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1152 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1153 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1154 1155 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1156 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1157 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1158 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1159 1160 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom); 1161 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom); 1162 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom); 1163 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1164 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom); 1165 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom); 1166 1167 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) { 1168 setOperationAction(ISD::FMA, MVT::v8f32, Legal); 1169 setOperationAction(ISD::FMA, MVT::v4f64, Legal); 1170 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 1171 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1172 setOperationAction(ISD::FMA, MVT::f32, Legal); 1173 setOperationAction(ISD::FMA, MVT::f64, Legal); 1174 } 1175 1176 if (Subtarget->hasInt256()) { 1177 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1178 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1179 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1180 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1181 1182 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1183 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1184 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1185 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1186 1187 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1188 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1189 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1190 // Don't lower v32i8 because there is no 128-bit byte mul 1191 1192 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1193 1194 setOperationAction(ISD::SDIV, MVT::v8i32, Custom); 1195 } else { 1196 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1197 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1198 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1199 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1200 1201 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1202 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1203 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1204 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1205 1206 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1207 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1208 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1209 // Don't lower v32i8 because there is no 128-bit byte mul 1210 } 1211 1212 // In the customized shift lowering, the legal cases in AVX2 will be 1213 // recognized. 1214 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1215 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1216 1217 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1218 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1219 1220 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1221 1222 // Custom lower several nodes for 256-bit types. 1223 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 1224 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 1225 MVT VT = (MVT::SimpleValueType)i; 1226 1227 // Extract subvector is special because the value type 1228 // (result) is 128-bit but the source is 256-bit wide. 1229 if (VT.is128BitVector()) 1230 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1231 1232 // Do not attempt to custom lower other non-256-bit vectors 1233 if (!VT.is256BitVector()) 1234 continue; 1235 1236 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1237 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1238 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1239 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1240 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 1241 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1242 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1243 } 1244 1245 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1246 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) { 1247 MVT VT = (MVT::SimpleValueType)i; 1248 1249 // Do not attempt to promote non-256-bit vectors 1250 if (!VT.is256BitVector()) 1251 continue; 1252 1253 setOperationAction(ISD::AND, VT, Promote); 1254 AddPromotedToType (ISD::AND, VT, MVT::v4i64); 1255 setOperationAction(ISD::OR, VT, Promote); 1256 AddPromotedToType (ISD::OR, VT, MVT::v4i64); 1257 setOperationAction(ISD::XOR, VT, Promote); 1258 AddPromotedToType (ISD::XOR, VT, MVT::v4i64); 1259 setOperationAction(ISD::LOAD, VT, Promote); 1260 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64); 1261 setOperationAction(ISD::SELECT, VT, Promote); 1262 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64); 1263 } 1264 } 1265 1266 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1267 // of this type with custom code. 1268 for (int VT = MVT::FIRST_VECTOR_VALUETYPE; 1269 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) { 1270 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, 1271 Custom); 1272 } 1273 1274 // We want to custom lower some of our intrinsics. 1275 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1276 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 1277 1278 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1279 // handle type legalization for these operations here. 1280 // 1281 // FIXME: We really should do custom legalization for addition and 1282 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1283 // than generic legalization for 64-bit multiplication-with-overflow, though. 1284 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1285 // Add/Sub/Mul with overflow operations are custom lowered. 1286 MVT VT = IntVTs[i]; 1287 setOperationAction(ISD::SADDO, VT, Custom); 1288 setOperationAction(ISD::UADDO, VT, Custom); 1289 setOperationAction(ISD::SSUBO, VT, Custom); 1290 setOperationAction(ISD::USUBO, VT, Custom); 1291 setOperationAction(ISD::SMULO, VT, Custom); 1292 setOperationAction(ISD::UMULO, VT, Custom); 1293 } 1294 1295 // There are no 8-bit 3-address imul/mul instructions 1296 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1297 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1298 1299 if (!Subtarget->is64Bit()) { 1300 // These libcalls are not available in 32-bit. 1301 setLibcallName(RTLIB::SHL_I128, 0); 1302 setLibcallName(RTLIB::SRL_I128, 0); 1303 setLibcallName(RTLIB::SRA_I128, 0); 1304 } 1305 1306 // Combine sin / cos into one node or libcall if possible. 1307 if (Subtarget->hasSinCos()) { 1308 setLibcallName(RTLIB::SINCOS_F32, "sincosf"); 1309 setLibcallName(RTLIB::SINCOS_F64, "sincos"); 1310 if (Subtarget->isTargetDarwin()) { 1311 // For MacOSX, we don't want to the normal expansion of a libcall to 1312 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 1313 // traffic. 1314 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 1315 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 1316 } 1317 } 1318 1319 // We have target-specific dag combine patterns for the following nodes: 1320 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1321 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1322 setTargetDAGCombine(ISD::VSELECT); 1323 setTargetDAGCombine(ISD::SELECT); 1324 setTargetDAGCombine(ISD::SHL); 1325 setTargetDAGCombine(ISD::SRA); 1326 setTargetDAGCombine(ISD::SRL); 1327 setTargetDAGCombine(ISD::OR); 1328 setTargetDAGCombine(ISD::AND); 1329 setTargetDAGCombine(ISD::ADD); 1330 setTargetDAGCombine(ISD::FADD); 1331 setTargetDAGCombine(ISD::FSUB); 1332 setTargetDAGCombine(ISD::FMA); 1333 setTargetDAGCombine(ISD::SUB); 1334 setTargetDAGCombine(ISD::LOAD); 1335 setTargetDAGCombine(ISD::STORE); 1336 setTargetDAGCombine(ISD::ZERO_EXTEND); 1337 setTargetDAGCombine(ISD::ANY_EXTEND); 1338 setTargetDAGCombine(ISD::SIGN_EXTEND); 1339 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 1340 setTargetDAGCombine(ISD::TRUNCATE); 1341 setTargetDAGCombine(ISD::SINT_TO_FP); 1342 setTargetDAGCombine(ISD::SETCC); 1343 if (Subtarget->is64Bit()) 1344 setTargetDAGCombine(ISD::MUL); 1345 setTargetDAGCombine(ISD::XOR); 1346 1347 computeRegisterProperties(); 1348 1349 // On Darwin, -Os means optimize for size without hurting performance, 1350 // do not reduce the limit. 1351 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1352 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1353 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1354 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1355 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1356 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1357 setPrefLoopAlignment(4); // 2^4 bytes. 1358 1359 // Predictable cmov don't hurt on atom because it's in-order. 1360 PredictableSelectIsExpensive = !Subtarget->isAtom(); 1361 1362 setPrefFunctionAlignment(4); // 2^4 bytes. 1363 } 1364 1365 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const { 1366 if (!VT.isVector()) return MVT::i8; 1367 return VT.changeVectorElementTypeToInteger(); 1368 } 1369 1370 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1371 /// the desired ByVal argument alignment. 1372 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1373 if (MaxAlign == 16) 1374 return; 1375 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1376 if (VTy->getBitWidth() == 128) 1377 MaxAlign = 16; 1378 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1379 unsigned EltAlign = 0; 1380 getMaxByValAlign(ATy->getElementType(), EltAlign); 1381 if (EltAlign > MaxAlign) 1382 MaxAlign = EltAlign; 1383 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1384 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1385 unsigned EltAlign = 0; 1386 getMaxByValAlign(STy->getElementType(i), EltAlign); 1387 if (EltAlign > MaxAlign) 1388 MaxAlign = EltAlign; 1389 if (MaxAlign == 16) 1390 break; 1391 } 1392 } 1393 } 1394 1395 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1396 /// function arguments in the caller parameter area. For X86, aggregates 1397 /// that contain SSE vectors are placed at 16-byte boundaries while the rest 1398 /// are at 4-byte boundaries. 1399 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1400 if (Subtarget->is64Bit()) { 1401 // Max of 8 and alignment of type. 1402 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1403 if (TyAlign > 8) 1404 return TyAlign; 1405 return 8; 1406 } 1407 1408 unsigned Align = 4; 1409 if (Subtarget->hasSSE1()) 1410 getMaxByValAlign(Ty, Align); 1411 return Align; 1412 } 1413 1414 /// getOptimalMemOpType - Returns the target specific optimal type for load 1415 /// and store operations as a result of memset, memcpy, and memmove 1416 /// lowering. If DstAlign is zero that means it's safe to destination 1417 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1418 /// means there isn't a need to check it against alignment requirement, 1419 /// probably because the source does not need to be loaded. If 'IsMemset' is 1420 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 1421 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 1422 /// source is constant so it does not need to be loaded. 1423 /// It returns EVT::Other if the type should be determined using generic 1424 /// target-independent logic. 1425 EVT 1426 X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1427 unsigned DstAlign, unsigned SrcAlign, 1428 bool IsMemset, bool ZeroMemset, 1429 bool MemcpyStrSrc, 1430 MachineFunction &MF) const { 1431 const Function *F = MF.getFunction(); 1432 if ((!IsMemset || ZeroMemset) && 1433 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1434 Attribute::NoImplicitFloat)) { 1435 if (Size >= 16 && 1436 (Subtarget->isUnalignedMemAccessFast() || 1437 ((DstAlign == 0 || DstAlign >= 16) && 1438 (SrcAlign == 0 || SrcAlign >= 16)))) { 1439 if (Size >= 32) { 1440 if (Subtarget->hasInt256()) 1441 return MVT::v8i32; 1442 if (Subtarget->hasFp256()) 1443 return MVT::v8f32; 1444 } 1445 if (Subtarget->hasSSE2()) 1446 return MVT::v4i32; 1447 if (Subtarget->hasSSE1()) 1448 return MVT::v4f32; 1449 } else if (!MemcpyStrSrc && Size >= 8 && 1450 !Subtarget->is64Bit() && 1451 Subtarget->hasSSE2()) { 1452 // Do not use f64 to lower memcpy if source is string constant. It's 1453 // better to use i32 to avoid the loads. 1454 return MVT::f64; 1455 } 1456 } 1457 if (Subtarget->is64Bit() && Size >= 8) 1458 return MVT::i64; 1459 return MVT::i32; 1460 } 1461 1462 bool X86TargetLowering::isSafeMemOpType(MVT VT) const { 1463 if (VT == MVT::f32) 1464 return X86ScalarSSEf32; 1465 else if (VT == MVT::f64) 1466 return X86ScalarSSEf64; 1467 return true; 1468 } 1469 1470 bool 1471 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const { 1472 if (Fast) 1473 *Fast = Subtarget->isUnalignedMemAccessFast(); 1474 return true; 1475 } 1476 1477 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 1478 /// current function. The returned value is a member of the 1479 /// MachineJumpTableInfo::JTEntryKind enum. 1480 unsigned X86TargetLowering::getJumpTableEncoding() const { 1481 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1482 // symbol. 1483 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1484 Subtarget->isPICStyleGOT()) 1485 return MachineJumpTableInfo::EK_Custom32; 1486 1487 // Otherwise, use the normal jump table encoding heuristics. 1488 return TargetLowering::getJumpTableEncoding(); 1489 } 1490 1491 const MCExpr * 1492 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1493 const MachineBasicBlock *MBB, 1494 unsigned uid,MCContext &Ctx) const{ 1495 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1496 Subtarget->isPICStyleGOT()); 1497 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1498 // entries. 1499 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1500 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1501 } 1502 1503 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1504 /// jumptable. 1505 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1506 SelectionDAG &DAG) const { 1507 if (!Subtarget->is64Bit()) 1508 // This doesn't have SDLoc associated with it, but is not really the 1509 // same as a Register. 1510 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy()); 1511 return Table; 1512 } 1513 1514 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1515 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1516 /// MCExpr. 1517 const MCExpr *X86TargetLowering:: 1518 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1519 MCContext &Ctx) const { 1520 // X86-64 uses RIP relative addressing based on the jump table label. 1521 if (Subtarget->isPICStyleRIPRel()) 1522 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1523 1524 // Otherwise, the reference is relative to the PIC base. 1525 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1526 } 1527 1528 // FIXME: Why this routine is here? Move to RegInfo! 1529 std::pair<const TargetRegisterClass*, uint8_t> 1530 X86TargetLowering::findRepresentativeClass(MVT VT) const{ 1531 const TargetRegisterClass *RRC = 0; 1532 uint8_t Cost = 1; 1533 switch (VT.SimpleTy) { 1534 default: 1535 return TargetLowering::findRepresentativeClass(VT); 1536 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1537 RRC = Subtarget->is64Bit() ? 1538 (const TargetRegisterClass*)&X86::GR64RegClass : 1539 (const TargetRegisterClass*)&X86::GR32RegClass; 1540 break; 1541 case MVT::x86mmx: 1542 RRC = &X86::VR64RegClass; 1543 break; 1544 case MVT::f32: case MVT::f64: 1545 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1546 case MVT::v4f32: case MVT::v2f64: 1547 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1548 case MVT::v4f64: 1549 RRC = &X86::VR128RegClass; 1550 break; 1551 } 1552 return std::make_pair(RRC, Cost); 1553 } 1554 1555 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1556 unsigned &Offset) const { 1557 if (!Subtarget->isTargetLinux()) 1558 return false; 1559 1560 if (Subtarget->is64Bit()) { 1561 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1562 Offset = 0x28; 1563 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1564 AddressSpace = 256; 1565 else 1566 AddressSpace = 257; 1567 } else { 1568 // %gs:0x14 on i386 1569 Offset = 0x14; 1570 AddressSpace = 256; 1571 } 1572 return true; 1573 } 1574 1575 //===----------------------------------------------------------------------===// 1576 // Return Value Calling Convention Implementation 1577 //===----------------------------------------------------------------------===// 1578 1579 #include "X86GenCallingConv.inc" 1580 1581 bool 1582 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1583 MachineFunction &MF, bool isVarArg, 1584 const SmallVectorImpl<ISD::OutputArg> &Outs, 1585 LLVMContext &Context) const { 1586 SmallVector<CCValAssign, 16> RVLocs; 1587 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1588 RVLocs, Context); 1589 return CCInfo.CheckReturn(Outs, RetCC_X86); 1590 } 1591 1592 SDValue 1593 X86TargetLowering::LowerReturn(SDValue Chain, 1594 CallingConv::ID CallConv, bool isVarArg, 1595 const SmallVectorImpl<ISD::OutputArg> &Outs, 1596 const SmallVectorImpl<SDValue> &OutVals, 1597 SDLoc dl, SelectionDAG &DAG) const { 1598 MachineFunction &MF = DAG.getMachineFunction(); 1599 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1600 1601 SmallVector<CCValAssign, 16> RVLocs; 1602 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1603 RVLocs, *DAG.getContext()); 1604 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1605 1606 SDValue Flag; 1607 SmallVector<SDValue, 6> RetOps; 1608 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1609 // Operand #1 = Bytes To Pop 1610 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1611 MVT::i16)); 1612 1613 // Copy the result values into the output registers. 1614 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1615 CCValAssign &VA = RVLocs[i]; 1616 assert(VA.isRegLoc() && "Can only return in registers!"); 1617 SDValue ValToCopy = OutVals[i]; 1618 EVT ValVT = ValToCopy.getValueType(); 1619 1620 // Promote values to the appropriate types 1621 if (VA.getLocInfo() == CCValAssign::SExt) 1622 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy); 1623 else if (VA.getLocInfo() == CCValAssign::ZExt) 1624 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy); 1625 else if (VA.getLocInfo() == CCValAssign::AExt) 1626 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy); 1627 else if (VA.getLocInfo() == CCValAssign::BCvt) 1628 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy); 1629 1630 // If this is x86-64, and we disabled SSE, we can't return FP values, 1631 // or SSE or MMX vectors. 1632 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1633 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1634 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) { 1635 report_fatal_error("SSE register return with SSE disabled"); 1636 } 1637 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1638 // llvm-gcc has never done it right and no one has noticed, so this 1639 // should be OK for now. 1640 if (ValVT == MVT::f64 && 1641 (Subtarget->is64Bit() && !Subtarget->hasSSE2())) 1642 report_fatal_error("SSE2 register return with SSE2 disabled"); 1643 1644 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1645 // the RET instruction and handled by the FP Stackifier. 1646 if (VA.getLocReg() == X86::ST0 || 1647 VA.getLocReg() == X86::ST1) { 1648 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1649 // change the value to the FP stack register class. 1650 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1651 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1652 RetOps.push_back(ValToCopy); 1653 // Don't emit a copytoreg. 1654 continue; 1655 } 1656 1657 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1658 // which is returned in RAX / RDX. 1659 if (Subtarget->is64Bit()) { 1660 if (ValVT == MVT::x86mmx) { 1661 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1662 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1663 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1664 ValToCopy); 1665 // If we don't have SSE2 available, convert to v4f32 so the generated 1666 // register is legal. 1667 if (!Subtarget->hasSSE2()) 1668 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1669 } 1670 } 1671 } 1672 1673 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1674 Flag = Chain.getValue(1); 1675 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1676 } 1677 1678 // The x86-64 ABIs require that for returning structs by value we copy 1679 // the sret argument into %rax/%eax (depending on ABI) for the return. 1680 // Win32 requires us to put the sret argument to %eax as well. 1681 // We saved the argument into a virtual register in the entry block, 1682 // so now we copy the value out and into %rax/%eax. 1683 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() && 1684 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 1685 MachineFunction &MF = DAG.getMachineFunction(); 1686 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1687 unsigned Reg = FuncInfo->getSRetReturnReg(); 1688 assert(Reg && 1689 "SRetReturnReg should have been set in LowerFormalArguments()."); 1690 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1691 1692 unsigned RetValReg 1693 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ? 1694 X86::RAX : X86::EAX; 1695 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag); 1696 Flag = Chain.getValue(1); 1697 1698 // RAX/EAX now acts like a return value. 1699 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy())); 1700 } 1701 1702 RetOps[0] = Chain; // Update chain. 1703 1704 // Add the flag if we have it. 1705 if (Flag.getNode()) 1706 RetOps.push_back(Flag); 1707 1708 return DAG.getNode(X86ISD::RET_FLAG, dl, 1709 MVT::Other, &RetOps[0], RetOps.size()); 1710 } 1711 1712 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 1713 if (N->getNumValues() != 1) 1714 return false; 1715 if (!N->hasNUsesOfValue(1, 0)) 1716 return false; 1717 1718 SDValue TCChain = Chain; 1719 SDNode *Copy = *N->use_begin(); 1720 if (Copy->getOpcode() == ISD::CopyToReg) { 1721 // If the copy has a glue operand, we conservatively assume it isn't safe to 1722 // perform a tail call. 1723 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 1724 return false; 1725 TCChain = Copy->getOperand(0); 1726 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 1727 return false; 1728 1729 bool HasRet = false; 1730 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1731 UI != UE; ++UI) { 1732 if (UI->getOpcode() != X86ISD::RET_FLAG) 1733 return false; 1734 HasRet = true; 1735 } 1736 1737 if (!HasRet) 1738 return false; 1739 1740 Chain = TCChain; 1741 return true; 1742 } 1743 1744 MVT 1745 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT, 1746 ISD::NodeType ExtendKind) const { 1747 MVT ReturnMVT; 1748 // TODO: Is this also valid on 32-bit? 1749 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1750 ReturnMVT = MVT::i8; 1751 else 1752 ReturnMVT = MVT::i32; 1753 1754 MVT MinVT = getRegisterType(ReturnMVT); 1755 return VT.bitsLT(MinVT) ? MinVT : VT; 1756 } 1757 1758 /// LowerCallResult - Lower the result values of a call into the 1759 /// appropriate copies out of appropriate physical registers. 1760 /// 1761 SDValue 1762 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1763 CallingConv::ID CallConv, bool isVarArg, 1764 const SmallVectorImpl<ISD::InputArg> &Ins, 1765 SDLoc dl, SelectionDAG &DAG, 1766 SmallVectorImpl<SDValue> &InVals) const { 1767 1768 // Assign locations to each value returned by this call. 1769 SmallVector<CCValAssign, 16> RVLocs; 1770 bool Is64Bit = Subtarget->is64Bit(); 1771 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1772 getTargetMachine(), RVLocs, *DAG.getContext()); 1773 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1774 1775 // Copy all of the result registers out of their specified physreg. 1776 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 1777 CCValAssign &VA = RVLocs[i]; 1778 EVT CopyVT = VA.getValVT(); 1779 1780 // If this is x86-64, and we disabled SSE, we can't return FP values 1781 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1782 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 1783 report_fatal_error("SSE register return with SSE disabled"); 1784 } 1785 1786 SDValue Val; 1787 1788 // If this is a call to a function that returns an fp value on the floating 1789 // point stack, we must guarantee the value is popped from the stack, so 1790 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1791 // if the return value is not used. We use the FpPOP_RETVAL instruction 1792 // instead. 1793 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1794 // If we prefer to use the value in xmm registers, copy it out as f80 and 1795 // use a truncate to move it from fp stack reg to xmm reg. 1796 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1797 SDValue Ops[] = { Chain, InFlag }; 1798 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1799 MVT::Other, MVT::Glue, Ops), 1); 1800 Val = Chain.getValue(0); 1801 1802 // Round the f80 to the right size, which also moves it to the appropriate 1803 // xmm register. 1804 if (CopyVT != VA.getValVT()) 1805 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1806 // This truncation won't change the value. 1807 DAG.getIntPtrConstant(1)); 1808 } else { 1809 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1810 CopyVT, InFlag).getValue(1); 1811 Val = Chain.getValue(0); 1812 } 1813 InFlag = Chain.getValue(2); 1814 InVals.push_back(Val); 1815 } 1816 1817 return Chain; 1818 } 1819 1820 //===----------------------------------------------------------------------===// 1821 // C & StdCall & Fast Calling Convention implementation 1822 //===----------------------------------------------------------------------===// 1823 // StdCall calling convention seems to be standard for many Windows' API 1824 // routines and around. It differs from C calling convention just a little: 1825 // callee should clean up the stack, not caller. Symbols should be also 1826 // decorated in some fancy way :) It doesn't support any vector arguments. 1827 // For info on fast calling convention see Fast Calling Convention (tail call) 1828 // implementation LowerX86_32FastCCCallTo. 1829 1830 /// CallIsStructReturn - Determines whether a call uses struct return 1831 /// semantics. 1832 enum StructReturnType { 1833 NotStructReturn, 1834 RegStructReturn, 1835 StackStructReturn 1836 }; 1837 static StructReturnType 1838 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1839 if (Outs.empty()) 1840 return NotStructReturn; 1841 1842 const ISD::ArgFlagsTy &Flags = Outs[0].Flags; 1843 if (!Flags.isSRet()) 1844 return NotStructReturn; 1845 if (Flags.isInReg()) 1846 return RegStructReturn; 1847 return StackStructReturn; 1848 } 1849 1850 /// ArgsAreStructReturn - Determines whether a function uses struct 1851 /// return semantics. 1852 static StructReturnType 1853 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1854 if (Ins.empty()) 1855 return NotStructReturn; 1856 1857 const ISD::ArgFlagsTy &Flags = Ins[0].Flags; 1858 if (!Flags.isSRet()) 1859 return NotStructReturn; 1860 if (Flags.isInReg()) 1861 return RegStructReturn; 1862 return StackStructReturn; 1863 } 1864 1865 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1866 /// by "Src" to address "Dst" with size and alignment information specified by 1867 /// the specific parameter attribute. The copy will be passed as a byval 1868 /// function parameter. 1869 static SDValue 1870 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1871 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1872 SDLoc dl) { 1873 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1874 1875 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1876 /*isVolatile*/false, /*AlwaysInline=*/true, 1877 MachinePointerInfo(), MachinePointerInfo()); 1878 } 1879 1880 /// IsTailCallConvention - Return true if the calling convention is one that 1881 /// supports tail call optimization. 1882 static bool IsTailCallConvention(CallingConv::ID CC) { 1883 return (CC == CallingConv::Fast || CC == CallingConv::GHC || 1884 CC == CallingConv::HiPE); 1885 } 1886 1887 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1888 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 1889 return false; 1890 1891 CallSite CS(CI); 1892 CallingConv::ID CalleeCC = CS.getCallingConv(); 1893 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1894 return false; 1895 1896 return true; 1897 } 1898 1899 /// FuncIsMadeTailCallSafe - Return true if the function is being made into 1900 /// a tailcall target by changing its ABI. 1901 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC, 1902 bool GuaranteedTailCallOpt) { 1903 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1904 } 1905 1906 SDValue 1907 X86TargetLowering::LowerMemArgument(SDValue Chain, 1908 CallingConv::ID CallConv, 1909 const SmallVectorImpl<ISD::InputArg> &Ins, 1910 SDLoc dl, SelectionDAG &DAG, 1911 const CCValAssign &VA, 1912 MachineFrameInfo *MFI, 1913 unsigned i) const { 1914 // Create the nodes corresponding to a load from this parameter slot. 1915 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1916 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv, 1917 getTargetMachine().Options.GuaranteedTailCallOpt); 1918 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1919 EVT ValVT; 1920 1921 // If value is passed by pointer we have address passed instead of the value 1922 // itself. 1923 if (VA.getLocInfo() == CCValAssign::Indirect) 1924 ValVT = VA.getLocVT(); 1925 else 1926 ValVT = VA.getValVT(); 1927 1928 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1929 // changed with more analysis. 1930 // In case of tail call optimization mark all arguments mutable. Since they 1931 // could be overwritten by lowering of arguments in case of a tail call. 1932 if (Flags.isByVal()) { 1933 unsigned Bytes = Flags.getByValSize(); 1934 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1935 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1936 return DAG.getFrameIndex(FI, getPointerTy()); 1937 } else { 1938 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1939 VA.getLocMemOffset(), isImmutable); 1940 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1941 return DAG.getLoad(ValVT, dl, Chain, FIN, 1942 MachinePointerInfo::getFixedStack(FI), 1943 false, false, false, 0); 1944 } 1945 } 1946 1947 SDValue 1948 X86TargetLowering::LowerFormalArguments(SDValue Chain, 1949 CallingConv::ID CallConv, 1950 bool isVarArg, 1951 const SmallVectorImpl<ISD::InputArg> &Ins, 1952 SDLoc dl, 1953 SelectionDAG &DAG, 1954 SmallVectorImpl<SDValue> &InVals) 1955 const { 1956 MachineFunction &MF = DAG.getMachineFunction(); 1957 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1958 1959 const Function* Fn = MF.getFunction(); 1960 if (Fn->hasExternalLinkage() && 1961 Subtarget->isTargetCygMing() && 1962 Fn->getName() == "main") 1963 FuncInfo->setForceFramePointer(true); 1964 1965 MachineFrameInfo *MFI = MF.getFrameInfo(); 1966 bool Is64Bit = Subtarget->is64Bit(); 1967 bool IsWindows = Subtarget->isTargetWindows(); 1968 bool IsWin64 = Subtarget->isTargetWin64(); 1969 1970 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1971 "Var args not supported with calling convention fastcc, ghc or hipe"); 1972 1973 // Assign locations to all of the incoming arguments. 1974 SmallVector<CCValAssign, 16> ArgLocs; 1975 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1976 ArgLocs, *DAG.getContext()); 1977 1978 // Allocate shadow area for Win64 1979 if (IsWin64) { 1980 CCInfo.AllocateStack(32, 8); 1981 } 1982 1983 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1984 1985 unsigned LastVal = ~0U; 1986 SDValue ArgValue; 1987 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1988 CCValAssign &VA = ArgLocs[i]; 1989 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1990 // places. 1991 assert(VA.getValNo() != LastVal && 1992 "Don't support value assigned to multiple locs yet"); 1993 (void)LastVal; 1994 LastVal = VA.getValNo(); 1995 1996 if (VA.isRegLoc()) { 1997 EVT RegVT = VA.getLocVT(); 1998 const TargetRegisterClass *RC; 1999 if (RegVT == MVT::i32) 2000 RC = &X86::GR32RegClass; 2001 else if (Is64Bit && RegVT == MVT::i64) 2002 RC = &X86::GR64RegClass; 2003 else if (RegVT == MVT::f32) 2004 RC = &X86::FR32RegClass; 2005 else if (RegVT == MVT::f64) 2006 RC = &X86::FR64RegClass; 2007 else if (RegVT.is256BitVector()) 2008 RC = &X86::VR256RegClass; 2009 else if (RegVT.is128BitVector()) 2010 RC = &X86::VR128RegClass; 2011 else if (RegVT == MVT::x86mmx) 2012 RC = &X86::VR64RegClass; 2013 else 2014 llvm_unreachable("Unknown argument type!"); 2015 2016 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2017 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 2018 2019 // If this is an 8 or 16-bit value, it is really passed promoted to 32 2020 // bits. Insert an assert[sz]ext to capture this, then truncate to the 2021 // right size. 2022 if (VA.getLocInfo() == CCValAssign::SExt) 2023 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 2024 DAG.getValueType(VA.getValVT())); 2025 else if (VA.getLocInfo() == CCValAssign::ZExt) 2026 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 2027 DAG.getValueType(VA.getValVT())); 2028 else if (VA.getLocInfo() == CCValAssign::BCvt) 2029 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 2030 2031 if (VA.isExtInLoc()) { 2032 // Handle MMX values passed in XMM regs. 2033 if (RegVT.isVector()) 2034 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue); 2035 else 2036 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 2037 } 2038 } else { 2039 assert(VA.isMemLoc()); 2040 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 2041 } 2042 2043 // If value is passed via pointer - do a load. 2044 if (VA.getLocInfo() == CCValAssign::Indirect) 2045 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 2046 MachinePointerInfo(), false, false, false, 0); 2047 2048 InVals.push_back(ArgValue); 2049 } 2050 2051 // The x86-64 ABIs require that for returning structs by value we copy 2052 // the sret argument into %rax/%eax (depending on ABI) for the return. 2053 // Win32 requires us to put the sret argument to %eax as well. 2054 // Save the argument into a virtual register so that we can access it 2055 // from the return points. 2056 if (MF.getFunction()->hasStructRetAttr() && 2057 (Subtarget->is64Bit() || Subtarget->isTargetWindows())) { 2058 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2059 unsigned Reg = FuncInfo->getSRetReturnReg(); 2060 if (!Reg) { 2061 MVT PtrTy = getPointerTy(); 2062 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 2063 FuncInfo->setSRetReturnReg(Reg); 2064 } 2065 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 2066 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 2067 } 2068 2069 unsigned StackSize = CCInfo.getNextStackOffset(); 2070 // Align stack specially for tail calls. 2071 if (FuncIsMadeTailCallSafe(CallConv, 2072 MF.getTarget().Options.GuaranteedTailCallOpt)) 2073 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 2074 2075 // If the function takes variable number of arguments, make a frame index for 2076 // the start of the first vararg value... for expansion of llvm.va_start. 2077 if (isVarArg) { 2078 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 2079 CallConv != CallingConv::X86_ThisCall)) { 2080 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 2081 } 2082 if (Is64Bit) { 2083 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 2084 2085 // FIXME: We should really autogenerate these arrays 2086 static const uint16_t GPR64ArgRegsWin64[] = { 2087 X86::RCX, X86::RDX, X86::R8, X86::R9 2088 }; 2089 static const uint16_t GPR64ArgRegs64Bit[] = { 2090 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 2091 }; 2092 static const uint16_t XMMArgRegs64Bit[] = { 2093 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2094 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2095 }; 2096 const uint16_t *GPR64ArgRegs; 2097 unsigned NumXMMRegs = 0; 2098 2099 if (IsWin64) { 2100 // The XMM registers which might contain var arg parameters are shadowed 2101 // in their paired GPR. So we only need to save the GPR to their home 2102 // slots. 2103 TotalNumIntRegs = 4; 2104 GPR64ArgRegs = GPR64ArgRegsWin64; 2105 } else { 2106 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 2107 GPR64ArgRegs = GPR64ArgRegs64Bit; 2108 2109 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, 2110 TotalNumXMMRegs); 2111 } 2112 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 2113 TotalNumIntRegs); 2114 2115 bool NoImplicitFloatOps = Fn->getAttributes(). 2116 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 2117 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) && 2118 "SSE register cannot be used when SSE is disabled!"); 2119 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat && 2120 NoImplicitFloatOps) && 2121 "SSE register cannot be used when SSE is disabled!"); 2122 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps || 2123 !Subtarget->hasSSE1()) 2124 // Kernel mode asks for SSE to be disabled, so don't push them 2125 // on the stack. 2126 TotalNumXMMRegs = 0; 2127 2128 if (IsWin64) { 2129 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 2130 // Get to the caller-allocated home save location. Add 8 to account 2131 // for the return address. 2132 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 2133 FuncInfo->setRegSaveFrameIndex( 2134 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 2135 // Fixup to set vararg frame on shadow area (4 x i64). 2136 if (NumIntRegs < 4) 2137 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 2138 } else { 2139 // For X86-64, if there are vararg parameters that are passed via 2140 // registers, then we must store them to their spots on the stack so 2141 // they may be loaded by deferencing the result of va_next. 2142 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 2143 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 2144 FuncInfo->setRegSaveFrameIndex( 2145 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 2146 false)); 2147 } 2148 2149 // Store the integer parameter registers. 2150 SmallVector<SDValue, 8> MemOps; 2151 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 2152 getPointerTy()); 2153 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 2154 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 2155 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 2156 DAG.getIntPtrConstant(Offset)); 2157 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 2158 &X86::GR64RegClass); 2159 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2160 SDValue Store = 2161 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2162 MachinePointerInfo::getFixedStack( 2163 FuncInfo->getRegSaveFrameIndex(), Offset), 2164 false, false, 0); 2165 MemOps.push_back(Store); 2166 Offset += 8; 2167 } 2168 2169 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 2170 // Now store the XMM (fp + vector) parameter registers. 2171 SmallVector<SDValue, 11> SaveXMMOps; 2172 SaveXMMOps.push_back(Chain); 2173 2174 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass); 2175 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 2176 SaveXMMOps.push_back(ALVal); 2177 2178 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2179 FuncInfo->getRegSaveFrameIndex())); 2180 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2181 FuncInfo->getVarArgsFPOffset())); 2182 2183 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 2184 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 2185 &X86::VR128RegClass); 2186 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 2187 SaveXMMOps.push_back(Val); 2188 } 2189 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 2190 MVT::Other, 2191 &SaveXMMOps[0], SaveXMMOps.size())); 2192 } 2193 2194 if (!MemOps.empty()) 2195 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2196 &MemOps[0], MemOps.size()); 2197 } 2198 } 2199 2200 // Some CCs need callee pop. 2201 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2202 MF.getTarget().Options.GuaranteedTailCallOpt)) { 2203 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2204 } else { 2205 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2206 // If this is an sret function, the return should pop the hidden pointer. 2207 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2208 argsAreStructReturn(Ins) == StackStructReturn) 2209 FuncInfo->setBytesToPopOnReturn(4); 2210 } 2211 2212 if (!Is64Bit) { 2213 // RegSaveFrameIndex is X86-64 only. 2214 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2215 if (CallConv == CallingConv::X86_FastCall || 2216 CallConv == CallingConv::X86_ThisCall) 2217 // fastcc functions can't have varargs. 2218 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2219 } 2220 2221 FuncInfo->setArgumentStackSize(StackSize); 2222 2223 return Chain; 2224 } 2225 2226 SDValue 2227 X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2228 SDValue StackPtr, SDValue Arg, 2229 SDLoc dl, SelectionDAG &DAG, 2230 const CCValAssign &VA, 2231 ISD::ArgFlagsTy Flags) const { 2232 unsigned LocMemOffset = VA.getLocMemOffset(); 2233 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2234 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2235 if (Flags.isByVal()) 2236 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2237 2238 return DAG.getStore(Chain, dl, Arg, PtrOff, 2239 MachinePointerInfo::getStack(LocMemOffset), 2240 false, false, 0); 2241 } 2242 2243 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2244 /// optimization is performed and it is required. 2245 SDValue 2246 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2247 SDValue &OutRetAddr, SDValue Chain, 2248 bool IsTailCall, bool Is64Bit, 2249 int FPDiff, SDLoc dl) const { 2250 // Adjust the Return address stack slot. 2251 EVT VT = getPointerTy(); 2252 OutRetAddr = getReturnAddressFrameIndex(DAG); 2253 2254 // Load the "old" Return address. 2255 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2256 false, false, false, 0); 2257 return SDValue(OutRetAddr.getNode(), 1); 2258 } 2259 2260 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2261 /// optimization is performed and it is required (FPDiff!=0). 2262 static SDValue 2263 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2264 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT, 2265 unsigned SlotSize, int FPDiff, SDLoc dl) { 2266 // Store the return address to the appropriate stack slot. 2267 if (!FPDiff) return Chain; 2268 // Calculate the new stack slot for the return address. 2269 int NewReturnAddrFI = 2270 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2271 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT); 2272 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2273 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2274 false, false, 0); 2275 return Chain; 2276 } 2277 2278 SDValue 2279 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2280 SmallVectorImpl<SDValue> &InVals) const { 2281 SelectionDAG &DAG = CLI.DAG; 2282 SDLoc &dl = CLI.DL; 2283 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2284 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2285 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2286 SDValue Chain = CLI.Chain; 2287 SDValue Callee = CLI.Callee; 2288 CallingConv::ID CallConv = CLI.CallConv; 2289 bool &isTailCall = CLI.IsTailCall; 2290 bool isVarArg = CLI.IsVarArg; 2291 2292 MachineFunction &MF = DAG.getMachineFunction(); 2293 bool Is64Bit = Subtarget->is64Bit(); 2294 bool IsWin64 = Subtarget->isTargetWin64(); 2295 bool IsWindows = Subtarget->isTargetWindows(); 2296 StructReturnType SR = callIsStructReturn(Outs); 2297 bool IsSibcall = false; 2298 2299 if (MF.getTarget().Options.DisableTailCalls) 2300 isTailCall = false; 2301 2302 if (isTailCall) { 2303 // Check if it's really possible to do a tail call. 2304 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2305 isVarArg, SR != NotStructReturn, 2306 MF.getFunction()->hasStructRetAttr(), CLI.RetTy, 2307 Outs, OutVals, Ins, DAG); 2308 2309 // Sibcalls are automatically detected tailcalls which do not require 2310 // ABI changes. 2311 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall) 2312 IsSibcall = true; 2313 2314 if (isTailCall) 2315 ++NumTailCalls; 2316 } 2317 2318 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2319 "Var args not supported with calling convention fastcc, ghc or hipe"); 2320 2321 // Analyze operands of the call, assigning locations to each operand. 2322 SmallVector<CCValAssign, 16> ArgLocs; 2323 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2324 ArgLocs, *DAG.getContext()); 2325 2326 // Allocate shadow area for Win64 2327 if (IsWin64) { 2328 CCInfo.AllocateStack(32, 8); 2329 } 2330 2331 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2332 2333 // Get a count of how many bytes are to be pushed on the stack. 2334 unsigned NumBytes = CCInfo.getNextStackOffset(); 2335 if (IsSibcall) 2336 // This is a sibcall. The memory operands are available in caller's 2337 // own caller's stack. 2338 NumBytes = 0; 2339 else if (getTargetMachine().Options.GuaranteedTailCallOpt && 2340 IsTailCallConvention(CallConv)) 2341 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2342 2343 int FPDiff = 0; 2344 if (isTailCall && !IsSibcall) { 2345 // Lower arguments at fp - stackoffset + fpdiff. 2346 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>(); 2347 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn(); 2348 2349 FPDiff = NumBytesCallerPushed - NumBytes; 2350 2351 // Set the delta of movement of the returnaddr stackslot. 2352 // But only set if delta is greater than previous delta. 2353 if (FPDiff < X86Info->getTCReturnAddrDelta()) 2354 X86Info->setTCReturnAddrDelta(FPDiff); 2355 } 2356 2357 if (!IsSibcall) 2358 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), 2359 dl); 2360 2361 SDValue RetAddrFrIdx; 2362 // Load return address for tail calls. 2363 if (isTailCall && FPDiff) 2364 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2365 Is64Bit, FPDiff, dl); 2366 2367 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2368 SmallVector<SDValue, 8> MemOpChains; 2369 SDValue StackPtr; 2370 2371 // Walk the register/memloc assignments, inserting copies/loads. In the case 2372 // of tail call optimization arguments are handle later. 2373 const X86RegisterInfo *RegInfo = 2374 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 2375 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2376 CCValAssign &VA = ArgLocs[i]; 2377 EVT RegVT = VA.getLocVT(); 2378 SDValue Arg = OutVals[i]; 2379 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2380 bool isByVal = Flags.isByVal(); 2381 2382 // Promote the value if needed. 2383 switch (VA.getLocInfo()) { 2384 default: llvm_unreachable("Unknown loc info!"); 2385 case CCValAssign::Full: break; 2386 case CCValAssign::SExt: 2387 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2388 break; 2389 case CCValAssign::ZExt: 2390 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2391 break; 2392 case CCValAssign::AExt: 2393 if (RegVT.is128BitVector()) { 2394 // Special case: passing MMX values in XMM registers. 2395 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2396 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2397 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2398 } else 2399 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2400 break; 2401 case CCValAssign::BCvt: 2402 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2403 break; 2404 case CCValAssign::Indirect: { 2405 // Store the argument. 2406 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2407 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2408 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2409 MachinePointerInfo::getFixedStack(FI), 2410 false, false, 0); 2411 Arg = SpillSlot; 2412 break; 2413 } 2414 } 2415 2416 if (VA.isRegLoc()) { 2417 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2418 if (isVarArg && IsWin64) { 2419 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2420 // shadow reg if callee is a varargs function. 2421 unsigned ShadowReg = 0; 2422 switch (VA.getLocReg()) { 2423 case X86::XMM0: ShadowReg = X86::RCX; break; 2424 case X86::XMM1: ShadowReg = X86::RDX; break; 2425 case X86::XMM2: ShadowReg = X86::R8; break; 2426 case X86::XMM3: ShadowReg = X86::R9; break; 2427 } 2428 if (ShadowReg) 2429 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2430 } 2431 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2432 assert(VA.isMemLoc()); 2433 if (StackPtr.getNode() == 0) 2434 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 2435 getPointerTy()); 2436 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2437 dl, DAG, VA, Flags)); 2438 } 2439 } 2440 2441 if (!MemOpChains.empty()) 2442 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2443 &MemOpChains[0], MemOpChains.size()); 2444 2445 if (Subtarget->isPICStyleGOT()) { 2446 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2447 // GOT pointer. 2448 if (!isTailCall) { 2449 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX), 2450 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy()))); 2451 } else { 2452 // If we are tail calling and generating PIC/GOT style code load the 2453 // address of the callee into ECX. The value in ecx is used as target of 2454 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2455 // for tail calls on PIC/GOT architectures. Normally we would just put the 2456 // address of GOT into ebx and then call target@PLT. But for tail calls 2457 // ebx would be restored (since ebx is callee saved) before jumping to the 2458 // target@PLT. 2459 2460 // Note: The actual moving to ECX is done further down. 2461 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2462 if (G && !G->getGlobal()->hasHiddenVisibility() && 2463 !G->getGlobal()->hasProtectedVisibility()) 2464 Callee = LowerGlobalAddress(Callee, DAG); 2465 else if (isa<ExternalSymbolSDNode>(Callee)) 2466 Callee = LowerExternalSymbol(Callee, DAG); 2467 } 2468 } 2469 2470 if (Is64Bit && isVarArg && !IsWin64) { 2471 // From AMD64 ABI document: 2472 // For calls that may call functions that use varargs or stdargs 2473 // (prototype-less calls or calls to functions containing ellipsis (...) in 2474 // the declaration) %al is used as hidden argument to specify the number 2475 // of SSE registers used. The contents of %al do not need to match exactly 2476 // the number of registers, but must be an ubound on the number of SSE 2477 // registers used and is in the range 0 - 8 inclusive. 2478 2479 // Count the number of XMM registers allocated. 2480 static const uint16_t XMMArgRegs[] = { 2481 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2482 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2483 }; 2484 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2485 assert((Subtarget->hasSSE1() || !NumXMMRegs) 2486 && "SSE registers cannot be used when SSE is disabled"); 2487 2488 RegsToPass.push_back(std::make_pair(unsigned(X86::AL), 2489 DAG.getConstant(NumXMMRegs, MVT::i8))); 2490 } 2491 2492 // For tail calls lower the arguments to the 'real' stack slot. 2493 if (isTailCall) { 2494 // Force all the incoming stack arguments to be loaded from the stack 2495 // before any new outgoing arguments are stored to the stack, because the 2496 // outgoing stack slots may alias the incoming argument stack slots, and 2497 // the alias isn't otherwise explicit. This is slightly more conservative 2498 // than necessary, because it means that each store effectively depends 2499 // on every argument instead of just those arguments it would clobber. 2500 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2501 2502 SmallVector<SDValue, 8> MemOpChains2; 2503 SDValue FIN; 2504 int FI = 0; 2505 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2506 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2507 CCValAssign &VA = ArgLocs[i]; 2508 if (VA.isRegLoc()) 2509 continue; 2510 assert(VA.isMemLoc()); 2511 SDValue Arg = OutVals[i]; 2512 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2513 // Create frame index. 2514 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2515 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2516 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2517 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2518 2519 if (Flags.isByVal()) { 2520 // Copy relative to framepointer. 2521 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2522 if (StackPtr.getNode() == 0) 2523 StackPtr = DAG.getCopyFromReg(Chain, dl, 2524 RegInfo->getStackRegister(), 2525 getPointerTy()); 2526 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2527 2528 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2529 ArgChain, 2530 Flags, DAG, dl)); 2531 } else { 2532 // Store relative to framepointer. 2533 MemOpChains2.push_back( 2534 DAG.getStore(ArgChain, dl, Arg, FIN, 2535 MachinePointerInfo::getFixedStack(FI), 2536 false, false, 0)); 2537 } 2538 } 2539 } 2540 2541 if (!MemOpChains2.empty()) 2542 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2543 &MemOpChains2[0], MemOpChains2.size()); 2544 2545 // Store the return address to the appropriate stack slot. 2546 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, 2547 getPointerTy(), RegInfo->getSlotSize(), 2548 FPDiff, dl); 2549 } 2550 2551 // Build a sequence of copy-to-reg nodes chained together with token chain 2552 // and flag operands which copy the outgoing args into registers. 2553 SDValue InFlag; 2554 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2555 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2556 RegsToPass[i].second, InFlag); 2557 InFlag = Chain.getValue(1); 2558 } 2559 2560 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2561 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2562 // In the 64-bit large code model, we have to make all calls 2563 // through a register, since the call instruction's 32-bit 2564 // pc-relative offset may not be large enough to hold the whole 2565 // address. 2566 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2567 // If the callee is a GlobalAddress node (quite common, every direct call 2568 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2569 // it. 2570 2571 // We should use extra load for direct calls to dllimported functions in 2572 // non-JIT mode. 2573 const GlobalValue *GV = G->getGlobal(); 2574 if (!GV->hasDLLImportLinkage()) { 2575 unsigned char OpFlags = 0; 2576 bool ExtraLoad = false; 2577 unsigned WrapperKind = ISD::DELETED_NODE; 2578 2579 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2580 // external symbols most go through the PLT in PIC mode. If the symbol 2581 // has hidden or protected visibility, or if it is static or local, then 2582 // we don't need to use the PLT - we can directly call it. 2583 if (Subtarget->isTargetELF() && 2584 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2585 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2586 OpFlags = X86II::MO_PLT; 2587 } else if (Subtarget->isPICStyleStubAny() && 2588 (GV->isDeclaration() || GV->isWeakForLinker()) && 2589 (!Subtarget->getTargetTriple().isMacOSX() || 2590 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2591 // PC-relative references to external symbols should go through $stub, 2592 // unless we're building with the leopard linker or later, which 2593 // automatically synthesizes these stubs. 2594 OpFlags = X86II::MO_DARWIN_STUB; 2595 } else if (Subtarget->isPICStyleRIPRel() && 2596 isa<Function>(GV) && 2597 cast<Function>(GV)->getAttributes(). 2598 hasAttribute(AttributeSet::FunctionIndex, 2599 Attribute::NonLazyBind)) { 2600 // If the function is marked as non-lazy, generate an indirect call 2601 // which loads from the GOT directly. This avoids runtime overhead 2602 // at the cost of eager binding (and one extra byte of encoding). 2603 OpFlags = X86II::MO_GOTPCREL; 2604 WrapperKind = X86ISD::WrapperRIP; 2605 ExtraLoad = true; 2606 } 2607 2608 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2609 G->getOffset(), OpFlags); 2610 2611 // Add a wrapper if needed. 2612 if (WrapperKind != ISD::DELETED_NODE) 2613 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2614 // Add extra indirection if needed. 2615 if (ExtraLoad) 2616 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2617 MachinePointerInfo::getGOT(), 2618 false, false, false, 0); 2619 } 2620 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2621 unsigned char OpFlags = 0; 2622 2623 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2624 // external symbols should go through the PLT. 2625 if (Subtarget->isTargetELF() && 2626 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2627 OpFlags = X86II::MO_PLT; 2628 } else if (Subtarget->isPICStyleStubAny() && 2629 (!Subtarget->getTargetTriple().isMacOSX() || 2630 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2631 // PC-relative references to external symbols should go through $stub, 2632 // unless we're building with the leopard linker or later, which 2633 // automatically synthesizes these stubs. 2634 OpFlags = X86II::MO_DARWIN_STUB; 2635 } 2636 2637 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2638 OpFlags); 2639 } 2640 2641 // Returns a chain & a flag for retval copy to use. 2642 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2643 SmallVector<SDValue, 8> Ops; 2644 2645 if (!IsSibcall && isTailCall) { 2646 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2647 DAG.getIntPtrConstant(0, true), InFlag, dl); 2648 InFlag = Chain.getValue(1); 2649 } 2650 2651 Ops.push_back(Chain); 2652 Ops.push_back(Callee); 2653 2654 if (isTailCall) 2655 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2656 2657 // Add argument registers to the end of the list so that they are known live 2658 // into the call. 2659 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2660 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2661 RegsToPass[i].second.getValueType())); 2662 2663 // Add a register mask operand representing the call-preserved registers. 2664 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 2665 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 2666 assert(Mask && "Missing call preserved mask for calling convention"); 2667 Ops.push_back(DAG.getRegisterMask(Mask)); 2668 2669 if (InFlag.getNode()) 2670 Ops.push_back(InFlag); 2671 2672 if (isTailCall) { 2673 // We used to do: 2674 //// If this is the first return lowered for this function, add the regs 2675 //// to the liveout set for the function. 2676 // This isn't right, although it's probably harmless on x86; liveouts 2677 // should be computed from returns not tail calls. Consider a void 2678 // function making a tail call to a function returning int. 2679 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size()); 2680 } 2681 2682 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2683 InFlag = Chain.getValue(1); 2684 2685 // Create the CALLSEQ_END node. 2686 unsigned NumBytesForCalleeToPush; 2687 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2688 getTargetMachine().Options.GuaranteedTailCallOpt)) 2689 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2690 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2691 SR == StackStructReturn) 2692 // If this is a call to a struct-return function, the callee 2693 // pops the hidden struct pointer, so we have to push it back. 2694 // This is common for Darwin/X86, Linux & Mingw32 targets. 2695 // For MSVC Win32 targets, the caller pops the hidden struct pointer. 2696 NumBytesForCalleeToPush = 4; 2697 else 2698 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2699 2700 // Returns a flag for retval copy to use. 2701 if (!IsSibcall) { 2702 Chain = DAG.getCALLSEQ_END(Chain, 2703 DAG.getIntPtrConstant(NumBytes, true), 2704 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2705 true), 2706 InFlag, dl); 2707 InFlag = Chain.getValue(1); 2708 } 2709 2710 // Handle result values, copying them out of physregs into vregs that we 2711 // return. 2712 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2713 Ins, dl, DAG, InVals); 2714 } 2715 2716 //===----------------------------------------------------------------------===// 2717 // Fast Calling Convention (tail call) implementation 2718 //===----------------------------------------------------------------------===// 2719 2720 // Like std call, callee cleans arguments, convention except that ECX is 2721 // reserved for storing the tail called function address. Only 2 registers are 2722 // free for argument passing (inreg). Tail call optimization is performed 2723 // provided: 2724 // * tailcallopt is enabled 2725 // * caller/callee are fastcc 2726 // On X86_64 architecture with GOT-style position independent code only local 2727 // (within module) calls are supported at the moment. 2728 // To keep the stack aligned according to platform abi the function 2729 // GetAlignedArgumentStackSize ensures that argument delta is always multiples 2730 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2731 // If a tail called function callee has more arguments than the caller the 2732 // caller needs to make sure that there is room to move the RETADDR to. This is 2733 // achieved by reserving an area the size of the argument delta right after the 2734 // original REtADDR, but before the saved framepointer or the spilled registers 2735 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2736 // stack layout: 2737 // arg1 2738 // arg2 2739 // RETADDR 2740 // [ new RETADDR 2741 // move area ] 2742 // (possible EBP) 2743 // ESI 2744 // EDI 2745 // local1 .. 2746 2747 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2748 /// for a 16 byte align requirement. 2749 unsigned 2750 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2751 SelectionDAG& DAG) const { 2752 MachineFunction &MF = DAG.getMachineFunction(); 2753 const TargetMachine &TM = MF.getTarget(); 2754 const X86RegisterInfo *RegInfo = 2755 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo()); 2756 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2757 unsigned StackAlignment = TFI.getStackAlignment(); 2758 uint64_t AlignMask = StackAlignment - 1; 2759 int64_t Offset = StackSize; 2760 unsigned SlotSize = RegInfo->getSlotSize(); 2761 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2762 // Number smaller than 12 so just add the difference. 2763 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2764 } else { 2765 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2766 Offset = ((~AlignMask) & Offset) + StackAlignment + 2767 (StackAlignment-SlotSize); 2768 } 2769 return Offset; 2770 } 2771 2772 /// MatchingStackOffset - Return true if the given stack call argument is 2773 /// already available in the same position (relatively) of the caller's 2774 /// incoming argument stack. 2775 static 2776 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2777 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2778 const X86InstrInfo *TII) { 2779 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2780 int FI = INT_MAX; 2781 if (Arg.getOpcode() == ISD::CopyFromReg) { 2782 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2783 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2784 return false; 2785 MachineInstr *Def = MRI->getVRegDef(VR); 2786 if (!Def) 2787 return false; 2788 if (!Flags.isByVal()) { 2789 if (!TII->isLoadFromStackSlot(Def, FI)) 2790 return false; 2791 } else { 2792 unsigned Opcode = Def->getOpcode(); 2793 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2794 Def->getOperand(1).isFI()) { 2795 FI = Def->getOperand(1).getIndex(); 2796 Bytes = Flags.getByValSize(); 2797 } else 2798 return false; 2799 } 2800 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2801 if (Flags.isByVal()) 2802 // ByVal argument is passed in as a pointer but it's now being 2803 // dereferenced. e.g. 2804 // define @foo(%struct.X* %A) { 2805 // tail call @bar(%struct.X* byval %A) 2806 // } 2807 return false; 2808 SDValue Ptr = Ld->getBasePtr(); 2809 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2810 if (!FINode) 2811 return false; 2812 FI = FINode->getIndex(); 2813 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2814 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2815 FI = FINode->getIndex(); 2816 Bytes = Flags.getByValSize(); 2817 } else 2818 return false; 2819 2820 assert(FI != INT_MAX); 2821 if (!MFI->isFixedObjectIndex(FI)) 2822 return false; 2823 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2824 } 2825 2826 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 2827 /// for tail call optimization. Targets which want to do tail call 2828 /// optimization should implement this function. 2829 bool 2830 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2831 CallingConv::ID CalleeCC, 2832 bool isVarArg, 2833 bool isCalleeStructRet, 2834 bool isCallerStructRet, 2835 Type *RetTy, 2836 const SmallVectorImpl<ISD::OutputArg> &Outs, 2837 const SmallVectorImpl<SDValue> &OutVals, 2838 const SmallVectorImpl<ISD::InputArg> &Ins, 2839 SelectionDAG &DAG) const { 2840 if (!IsTailCallConvention(CalleeCC) && 2841 CalleeCC != CallingConv::C) 2842 return false; 2843 2844 // If -tailcallopt is specified, make fastcc functions tail-callable. 2845 const MachineFunction &MF = DAG.getMachineFunction(); 2846 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2847 2848 // If the function return type is x86_fp80 and the callee return type is not, 2849 // then the FP_EXTEND of the call result is not a nop. It's not safe to 2850 // perform a tailcall optimization here. 2851 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty()) 2852 return false; 2853 2854 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2855 bool CCMatch = CallerCC == CalleeCC; 2856 2857 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2858 if (IsTailCallConvention(CalleeCC) && CCMatch) 2859 return true; 2860 return false; 2861 } 2862 2863 // Look for obvious safe cases to perform tail call optimization that do not 2864 // require ABI changes. This is what gcc calls sibcall. 2865 2866 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2867 // emit a special epilogue. 2868 const X86RegisterInfo *RegInfo = 2869 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 2870 if (RegInfo->needsStackRealignment(MF)) 2871 return false; 2872 2873 // Also avoid sibcall optimization if either caller or callee uses struct 2874 // return semantics. 2875 if (isCalleeStructRet || isCallerStructRet) 2876 return false; 2877 2878 // An stdcall caller is expected to clean up its arguments; the callee 2879 // isn't going to do that. 2880 if (!CCMatch && CallerCC == CallingConv::X86_StdCall) 2881 return false; 2882 2883 // Do not sibcall optimize vararg calls unless all arguments are passed via 2884 // registers. 2885 if (isVarArg && !Outs.empty()) { 2886 2887 // Optimizing for varargs on Win64 is unlikely to be safe without 2888 // additional testing. 2889 if (Subtarget->isTargetWin64()) 2890 return false; 2891 2892 SmallVector<CCValAssign, 16> ArgLocs; 2893 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2894 getTargetMachine(), ArgLocs, *DAG.getContext()); 2895 2896 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2897 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2898 if (!ArgLocs[i].isRegLoc()) 2899 return false; 2900 } 2901 2902 // If the call result is in ST0 / ST1, it needs to be popped off the x87 2903 // stack. Therefore, if it's not used by the call it is not safe to optimize 2904 // this into a sibcall. 2905 bool Unused = false; 2906 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2907 if (!Ins[i].Used) { 2908 Unused = true; 2909 break; 2910 } 2911 } 2912 if (Unused) { 2913 SmallVector<CCValAssign, 16> RVLocs; 2914 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2915 getTargetMachine(), RVLocs, *DAG.getContext()); 2916 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2917 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2918 CCValAssign &VA = RVLocs[i]; 2919 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2920 return false; 2921 } 2922 } 2923 2924 // If the calling conventions do not match, then we'd better make sure the 2925 // results are returned in the same way as what the caller expects. 2926 if (!CCMatch) { 2927 SmallVector<CCValAssign, 16> RVLocs1; 2928 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2929 getTargetMachine(), RVLocs1, *DAG.getContext()); 2930 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2931 2932 SmallVector<CCValAssign, 16> RVLocs2; 2933 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2934 getTargetMachine(), RVLocs2, *DAG.getContext()); 2935 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2936 2937 if (RVLocs1.size() != RVLocs2.size()) 2938 return false; 2939 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2940 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2941 return false; 2942 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2943 return false; 2944 if (RVLocs1[i].isRegLoc()) { 2945 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2946 return false; 2947 } else { 2948 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2949 return false; 2950 } 2951 } 2952 } 2953 2954 // If the callee takes no arguments then go on to check the results of the 2955 // call. 2956 if (!Outs.empty()) { 2957 // Check if stack adjustment is needed. For now, do not do this if any 2958 // argument is passed on the stack. 2959 SmallVector<CCValAssign, 16> ArgLocs; 2960 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2961 getTargetMachine(), ArgLocs, *DAG.getContext()); 2962 2963 // Allocate shadow area for Win64 2964 if (Subtarget->isTargetWin64()) { 2965 CCInfo.AllocateStack(32, 8); 2966 } 2967 2968 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2969 if (CCInfo.getNextStackOffset()) { 2970 MachineFunction &MF = DAG.getMachineFunction(); 2971 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2972 return false; 2973 2974 // Check if the arguments are already laid out in the right way as 2975 // the caller's fixed stack objects. 2976 MachineFrameInfo *MFI = MF.getFrameInfo(); 2977 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2978 const X86InstrInfo *TII = 2979 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2980 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2981 CCValAssign &VA = ArgLocs[i]; 2982 SDValue Arg = OutVals[i]; 2983 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2984 if (VA.getLocInfo() == CCValAssign::Indirect) 2985 return false; 2986 if (!VA.isRegLoc()) { 2987 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2988 MFI, MRI, TII)) 2989 return false; 2990 } 2991 } 2992 } 2993 2994 // If the tailcall address may be in a register, then make sure it's 2995 // possible to register allocate for it. In 32-bit, the call address can 2996 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2997 // callee-saved registers are restored. These happen to be the same 2998 // registers used to pass 'inreg' arguments so watch out for those. 2999 if (!Subtarget->is64Bit() && 3000 ((!isa<GlobalAddressSDNode>(Callee) && 3001 !isa<ExternalSymbolSDNode>(Callee)) || 3002 getTargetMachine().getRelocationModel() == Reloc::PIC_)) { 3003 unsigned NumInRegs = 0; 3004 // In PIC we need an extra register to formulate the address computation 3005 // for the callee. 3006 unsigned MaxInRegs = 3007 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3; 3008 3009 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3010 CCValAssign &VA = ArgLocs[i]; 3011 if (!VA.isRegLoc()) 3012 continue; 3013 unsigned Reg = VA.getLocReg(); 3014 switch (Reg) { 3015 default: break; 3016 case X86::EAX: case X86::EDX: case X86::ECX: 3017 if (++NumInRegs == MaxInRegs) 3018 return false; 3019 break; 3020 } 3021 } 3022 } 3023 } 3024 3025 return true; 3026 } 3027 3028 FastISel * 3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 3030 const TargetLibraryInfo *libInfo) const { 3031 return X86::createFastISel(funcInfo, libInfo); 3032 } 3033 3034 //===----------------------------------------------------------------------===// 3035 // Other Lowering Hooks 3036 //===----------------------------------------------------------------------===// 3037 3038 static bool MayFoldLoad(SDValue Op) { 3039 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 3040 } 3041 3042 static bool MayFoldIntoStore(SDValue Op) { 3043 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 3044 } 3045 3046 static bool isTargetShuffle(unsigned Opcode) { 3047 switch(Opcode) { 3048 default: return false; 3049 case X86ISD::PSHUFD: 3050 case X86ISD::PSHUFHW: 3051 case X86ISD::PSHUFLW: 3052 case X86ISD::SHUFP: 3053 case X86ISD::PALIGNR: 3054 case X86ISD::MOVLHPS: 3055 case X86ISD::MOVLHPD: 3056 case X86ISD::MOVHLPS: 3057 case X86ISD::MOVLPS: 3058 case X86ISD::MOVLPD: 3059 case X86ISD::MOVSHDUP: 3060 case X86ISD::MOVSLDUP: 3061 case X86ISD::MOVDDUP: 3062 case X86ISD::MOVSS: 3063 case X86ISD::MOVSD: 3064 case X86ISD::UNPCKL: 3065 case X86ISD::UNPCKH: 3066 case X86ISD::VPERMILP: 3067 case X86ISD::VPERM2X128: 3068 case X86ISD::VPERMI: 3069 return true; 3070 } 3071 } 3072 3073 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3074 SDValue V1, SelectionDAG &DAG) { 3075 switch(Opc) { 3076 default: llvm_unreachable("Unknown x86 shuffle node"); 3077 case X86ISD::MOVSHDUP: 3078 case X86ISD::MOVSLDUP: 3079 case X86ISD::MOVDDUP: 3080 return DAG.getNode(Opc, dl, VT, V1); 3081 } 3082 } 3083 3084 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3085 SDValue V1, unsigned TargetMask, 3086 SelectionDAG &DAG) { 3087 switch(Opc) { 3088 default: llvm_unreachable("Unknown x86 shuffle node"); 3089 case X86ISD::PSHUFD: 3090 case X86ISD::PSHUFHW: 3091 case X86ISD::PSHUFLW: 3092 case X86ISD::VPERMILP: 3093 case X86ISD::VPERMI: 3094 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 3095 } 3096 } 3097 3098 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3099 SDValue V1, SDValue V2, unsigned TargetMask, 3100 SelectionDAG &DAG) { 3101 switch(Opc) { 3102 default: llvm_unreachable("Unknown x86 shuffle node"); 3103 case X86ISD::PALIGNR: 3104 case X86ISD::SHUFP: 3105 case X86ISD::VPERM2X128: 3106 return DAG.getNode(Opc, dl, VT, V1, V2, 3107 DAG.getConstant(TargetMask, MVT::i8)); 3108 } 3109 } 3110 3111 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT, 3112 SDValue V1, SDValue V2, SelectionDAG &DAG) { 3113 switch(Opc) { 3114 default: llvm_unreachable("Unknown x86 shuffle node"); 3115 case X86ISD::MOVLHPS: 3116 case X86ISD::MOVLHPD: 3117 case X86ISD::MOVHLPS: 3118 case X86ISD::MOVLPS: 3119 case X86ISD::MOVLPD: 3120 case X86ISD::MOVSS: 3121 case X86ISD::MOVSD: 3122 case X86ISD::UNPCKL: 3123 case X86ISD::UNPCKH: 3124 return DAG.getNode(Opc, dl, VT, V1, V2); 3125 } 3126 } 3127 3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 3129 MachineFunction &MF = DAG.getMachineFunction(); 3130 const X86RegisterInfo *RegInfo = 3131 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 3132 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 3133 int ReturnAddrIndex = FuncInfo->getRAIndex(); 3134 3135 if (ReturnAddrIndex == 0) { 3136 // Set up a frame object for the return address. 3137 unsigned SlotSize = RegInfo->getSlotSize(); 3138 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 3139 false); 3140 FuncInfo->setRAIndex(ReturnAddrIndex); 3141 } 3142 3143 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 3144 } 3145 3146 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 3147 bool hasSymbolicDisplacement) { 3148 // Offset should fit into 32 bit immediate field. 3149 if (!isInt<32>(Offset)) 3150 return false; 3151 3152 // If we don't have a symbolic displacement - we don't have any extra 3153 // restrictions. 3154 if (!hasSymbolicDisplacement) 3155 return true; 3156 3157 // FIXME: Some tweaks might be needed for medium code model. 3158 if (M != CodeModel::Small && M != CodeModel::Kernel) 3159 return false; 3160 3161 // For small code model we assume that latest object is 16MB before end of 31 3162 // bits boundary. We may also accept pretty large negative constants knowing 3163 // that all objects are in the positive half of address space. 3164 if (M == CodeModel::Small && Offset < 16*1024*1024) 3165 return true; 3166 3167 // For kernel code model we know that all object resist in the negative half 3168 // of 32bits address space. We may not accept negative offsets, since they may 3169 // be just off and we may accept pretty large positive ones. 3170 if (M == CodeModel::Kernel && Offset > 0) 3171 return true; 3172 3173 return false; 3174 } 3175 3176 /// isCalleePop - Determines whether the callee is required to pop its 3177 /// own arguments. Callee pop is necessary to support tail calls. 3178 bool X86::isCalleePop(CallingConv::ID CallingConv, 3179 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 3180 if (IsVarArg) 3181 return false; 3182 3183 switch (CallingConv) { 3184 default: 3185 return false; 3186 case CallingConv::X86_StdCall: 3187 return !is64Bit; 3188 case CallingConv::X86_FastCall: 3189 return !is64Bit; 3190 case CallingConv::X86_ThisCall: 3191 return !is64Bit; 3192 case CallingConv::Fast: 3193 return TailCallOpt; 3194 case CallingConv::GHC: 3195 return TailCallOpt; 3196 case CallingConv::HiPE: 3197 return TailCallOpt; 3198 } 3199 } 3200 3201 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 3202 /// specific condition code, returning the condition code and the LHS/RHS of the 3203 /// comparison to make. 3204 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 3205 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 3206 if (!isFP) { 3207 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3208 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 3209 // X > -1 -> X == 0, jump !sign. 3210 RHS = DAG.getConstant(0, RHS.getValueType()); 3211 return X86::COND_NS; 3212 } 3213 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3214 // X < 0 -> X == 0, jump on sign. 3215 return X86::COND_S; 3216 } 3217 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3218 // X < 1 -> X <= 0 3219 RHS = DAG.getConstant(0, RHS.getValueType()); 3220 return X86::COND_LE; 3221 } 3222 } 3223 3224 switch (SetCCOpcode) { 3225 default: llvm_unreachable("Invalid integer condition!"); 3226 case ISD::SETEQ: return X86::COND_E; 3227 case ISD::SETGT: return X86::COND_G; 3228 case ISD::SETGE: return X86::COND_GE; 3229 case ISD::SETLT: return X86::COND_L; 3230 case ISD::SETLE: return X86::COND_LE; 3231 case ISD::SETNE: return X86::COND_NE; 3232 case ISD::SETULT: return X86::COND_B; 3233 case ISD::SETUGT: return X86::COND_A; 3234 case ISD::SETULE: return X86::COND_BE; 3235 case ISD::SETUGE: return X86::COND_AE; 3236 } 3237 } 3238 3239 // First determine if it is required or is profitable to flip the operands. 3240 3241 // If LHS is a foldable load, but RHS is not, flip the condition. 3242 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3243 !ISD::isNON_EXTLoad(RHS.getNode())) { 3244 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3245 std::swap(LHS, RHS); 3246 } 3247 3248 switch (SetCCOpcode) { 3249 default: break; 3250 case ISD::SETOLT: 3251 case ISD::SETOLE: 3252 case ISD::SETUGT: 3253 case ISD::SETUGE: 3254 std::swap(LHS, RHS); 3255 break; 3256 } 3257 3258 // On a floating point condition, the flags are set as follows: 3259 // ZF PF CF op 3260 // 0 | 0 | 0 | X > Y 3261 // 0 | 0 | 1 | X < Y 3262 // 1 | 0 | 0 | X == Y 3263 // 1 | 1 | 1 | unordered 3264 switch (SetCCOpcode) { 3265 default: llvm_unreachable("Condcode should be pre-legalized away"); 3266 case ISD::SETUEQ: 3267 case ISD::SETEQ: return X86::COND_E; 3268 case ISD::SETOLT: // flipped 3269 case ISD::SETOGT: 3270 case ISD::SETGT: return X86::COND_A; 3271 case ISD::SETOLE: // flipped 3272 case ISD::SETOGE: 3273 case ISD::SETGE: return X86::COND_AE; 3274 case ISD::SETUGT: // flipped 3275 case ISD::SETULT: 3276 case ISD::SETLT: return X86::COND_B; 3277 case ISD::SETUGE: // flipped 3278 case ISD::SETULE: 3279 case ISD::SETLE: return X86::COND_BE; 3280 case ISD::SETONE: 3281 case ISD::SETNE: return X86::COND_NE; 3282 case ISD::SETUO: return X86::COND_P; 3283 case ISD::SETO: return X86::COND_NP; 3284 case ISD::SETOEQ: 3285 case ISD::SETUNE: return X86::COND_INVALID; 3286 } 3287 } 3288 3289 /// hasFPCMov - is there a floating point cmov for the specific X86 condition 3290 /// code. Current x86 isa includes the following FP cmov instructions: 3291 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3292 static bool hasFPCMov(unsigned X86CC) { 3293 switch (X86CC) { 3294 default: 3295 return false; 3296 case X86::COND_B: 3297 case X86::COND_BE: 3298 case X86::COND_E: 3299 case X86::COND_P: 3300 case X86::COND_A: 3301 case X86::COND_AE: 3302 case X86::COND_NE: 3303 case X86::COND_NP: 3304 return true; 3305 } 3306 } 3307 3308 /// isFPImmLegal - Returns true if the target can instruction select the 3309 /// specified FP immediate natively. If false, the legalizer will 3310 /// materialize the FP immediate as a load from a constant pool. 3311 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3312 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3313 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3314 return true; 3315 } 3316 return false; 3317 } 3318 3319 /// isUndefOrInRange - Return true if Val is undef or if its value falls within 3320 /// the specified range (L, H]. 3321 static bool isUndefOrInRange(int Val, int Low, int Hi) { 3322 return (Val < 0) || (Val >= Low && Val < Hi); 3323 } 3324 3325 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3326 /// specified value. 3327 static bool isUndefOrEqual(int Val, int CmpVal) { 3328 return (Val < 0 || Val == CmpVal); 3329 } 3330 3331 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning 3332 /// from position Pos and ending in Pos+Size, falls within the specified 3333 /// sequential range (L, L+Pos]. or is undef. 3334 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, 3335 unsigned Pos, unsigned Size, int Low) { 3336 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3337 if (!isUndefOrEqual(Mask[i], Low)) 3338 return false; 3339 return true; 3340 } 3341 3342 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3343 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3344 /// the second operand. 3345 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) { 3346 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3347 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3348 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3349 return (Mask[0] < 2 && Mask[1] < 2); 3350 return false; 3351 } 3352 3353 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3354 /// is suitable for input to PSHUFHW. 3355 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3356 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3357 return false; 3358 3359 // Lower quadword copied in order or undef. 3360 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0)) 3361 return false; 3362 3363 // Upper quadword shuffled. 3364 for (unsigned i = 4; i != 8; ++i) 3365 if (!isUndefOrInRange(Mask[i], 4, 8)) 3366 return false; 3367 3368 if (VT == MVT::v16i16) { 3369 // Lower quadword copied in order or undef. 3370 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8)) 3371 return false; 3372 3373 // Upper quadword shuffled. 3374 for (unsigned i = 12; i != 16; ++i) 3375 if (!isUndefOrInRange(Mask[i], 12, 16)) 3376 return false; 3377 } 3378 3379 return true; 3380 } 3381 3382 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3383 /// is suitable for input to PSHUFLW. 3384 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3385 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3386 return false; 3387 3388 // Upper quadword copied in order. 3389 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4)) 3390 return false; 3391 3392 // Lower quadword shuffled. 3393 for (unsigned i = 0; i != 4; ++i) 3394 if (!isUndefOrInRange(Mask[i], 0, 4)) 3395 return false; 3396 3397 if (VT == MVT::v16i16) { 3398 // Upper quadword copied in order. 3399 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12)) 3400 return false; 3401 3402 // Lower quadword shuffled. 3403 for (unsigned i = 8; i != 12; ++i) 3404 if (!isUndefOrInRange(Mask[i], 8, 12)) 3405 return false; 3406 } 3407 3408 return true; 3409 } 3410 3411 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3412 /// is suitable for input to PALIGNR. 3413 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT, 3414 const X86Subtarget *Subtarget) { 3415 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) || 3416 (VT.is256BitVector() && !Subtarget->hasInt256())) 3417 return false; 3418 3419 unsigned NumElts = VT.getVectorNumElements(); 3420 unsigned NumLanes = VT.getSizeInBits()/128; 3421 unsigned NumLaneElts = NumElts/NumLanes; 3422 3423 // Do not handle 64-bit element shuffles with palignr. 3424 if (NumLaneElts == 2) 3425 return false; 3426 3427 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) { 3428 unsigned i; 3429 for (i = 0; i != NumLaneElts; ++i) { 3430 if (Mask[i+l] >= 0) 3431 break; 3432 } 3433 3434 // Lane is all undef, go to next lane 3435 if (i == NumLaneElts) 3436 continue; 3437 3438 int Start = Mask[i+l]; 3439 3440 // Make sure its in this lane in one of the sources 3441 if (!isUndefOrInRange(Start, l, l+NumLaneElts) && 3442 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts)) 3443 return false; 3444 3445 // If not lane 0, then we must match lane 0 3446 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l)) 3447 return false; 3448 3449 // Correct second source to be contiguous with first source 3450 if (Start >= (int)NumElts) 3451 Start -= NumElts - NumLaneElts; 3452 3453 // Make sure we're shifting in the right direction. 3454 if (Start <= (int)(i+l)) 3455 return false; 3456 3457 Start -= i; 3458 3459 // Check the rest of the elements to see if they are consecutive. 3460 for (++i; i != NumLaneElts; ++i) { 3461 int Idx = Mask[i+l]; 3462 3463 // Make sure its in this lane 3464 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) && 3465 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts)) 3466 return false; 3467 3468 // If not lane 0, then we must match lane 0 3469 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l)) 3470 return false; 3471 3472 if (Idx >= (int)NumElts) 3473 Idx -= NumElts - NumLaneElts; 3474 3475 if (!isUndefOrEqual(Idx, Start+i)) 3476 return false; 3477 3478 } 3479 } 3480 3481 return true; 3482 } 3483 3484 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3485 /// the two vector operands have swapped position. 3486 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, 3487 unsigned NumElems) { 3488 for (unsigned i = 0; i != NumElems; ++i) { 3489 int idx = Mask[i]; 3490 if (idx < 0) 3491 continue; 3492 else if (idx < (int)NumElems) 3493 Mask[i] = idx + NumElems; 3494 else 3495 Mask[i] = idx - NumElems; 3496 } 3497 } 3498 3499 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3500 /// specifies a shuffle of elements that is suitable for input to 128/256-bit 3501 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be 3502 /// reverse of what x86 shuffles want. 3503 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256, 3504 bool Commuted = false) { 3505 if (!HasFp256 && VT.is256BitVector()) 3506 return false; 3507 3508 unsigned NumElems = VT.getVectorNumElements(); 3509 unsigned NumLanes = VT.getSizeInBits()/128; 3510 unsigned NumLaneElems = NumElems/NumLanes; 3511 3512 if (NumLaneElems != 2 && NumLaneElems != 4) 3513 return false; 3514 3515 // VSHUFPSY divides the resulting vector into 4 chunks. 3516 // The sources are also splitted into 4 chunks, and each destination 3517 // chunk must come from a different source chunk. 3518 // 3519 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3520 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3521 // 3522 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3523 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3524 // 3525 // VSHUFPDY divides the resulting vector into 4 chunks. 3526 // The sources are also splitted into 4 chunks, and each destination 3527 // chunk must come from a different source chunk. 3528 // 3529 // SRC1 => X3 X2 X1 X0 3530 // SRC2 => Y3 Y2 Y1 Y0 3531 // 3532 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3533 // 3534 unsigned HalfLaneElems = NumLaneElems/2; 3535 for (unsigned l = 0; l != NumElems; l += NumLaneElems) { 3536 for (unsigned i = 0; i != NumLaneElems; ++i) { 3537 int Idx = Mask[i+l]; 3538 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0); 3539 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems)) 3540 return false; 3541 // For VSHUFPSY, the mask of the second half must be the same as the 3542 // first but with the appropriate offsets. This works in the same way as 3543 // VPERMILPS works with masks. 3544 if (NumElems != 8 || l == 0 || Mask[i] < 0) 3545 continue; 3546 if (!isUndefOrEqual(Idx, Mask[i]+l)) 3547 return false; 3548 } 3549 } 3550 3551 return true; 3552 } 3553 3554 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3555 /// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3556 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) { 3557 if (!VT.is128BitVector()) 3558 return false; 3559 3560 unsigned NumElems = VT.getVectorNumElements(); 3561 3562 if (NumElems != 4) 3563 return false; 3564 3565 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3566 return isUndefOrEqual(Mask[0], 6) && 3567 isUndefOrEqual(Mask[1], 7) && 3568 isUndefOrEqual(Mask[2], 2) && 3569 isUndefOrEqual(Mask[3], 3); 3570 } 3571 3572 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3573 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3574 /// <2, 3, 2, 3> 3575 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) { 3576 if (!VT.is128BitVector()) 3577 return false; 3578 3579 unsigned NumElems = VT.getVectorNumElements(); 3580 3581 if (NumElems != 4) 3582 return false; 3583 3584 return isUndefOrEqual(Mask[0], 2) && 3585 isUndefOrEqual(Mask[1], 3) && 3586 isUndefOrEqual(Mask[2], 2) && 3587 isUndefOrEqual(Mask[3], 3); 3588 } 3589 3590 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3591 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3592 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) { 3593 if (!VT.is128BitVector()) 3594 return false; 3595 3596 unsigned NumElems = VT.getVectorNumElements(); 3597 3598 if (NumElems != 2 && NumElems != 4) 3599 return false; 3600 3601 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3602 if (!isUndefOrEqual(Mask[i], i + NumElems)) 3603 return false; 3604 3605 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 3606 if (!isUndefOrEqual(Mask[i], i)) 3607 return false; 3608 3609 return true; 3610 } 3611 3612 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3613 /// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3614 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) { 3615 if (!VT.is128BitVector()) 3616 return false; 3617 3618 unsigned NumElems = VT.getVectorNumElements(); 3619 3620 if (NumElems != 2 && NumElems != 4) 3621 return false; 3622 3623 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3624 if (!isUndefOrEqual(Mask[i], i)) 3625 return false; 3626 3627 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3628 if (!isUndefOrEqual(Mask[i + e], i + NumElems)) 3629 return false; 3630 3631 return true; 3632 } 3633 3634 // 3635 // Some special combinations that can be optimized. 3636 // 3637 static 3638 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp, 3639 SelectionDAG &DAG) { 3640 MVT VT = SVOp->getValueType(0).getSimpleVT(); 3641 SDLoc dl(SVOp); 3642 3643 if (VT != MVT::v8i32 && VT != MVT::v8f32) 3644 return SDValue(); 3645 3646 ArrayRef<int> Mask = SVOp->getMask(); 3647 3648 // These are the special masks that may be optimized. 3649 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14}; 3650 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15}; 3651 bool MatchEvenMask = true; 3652 bool MatchOddMask = true; 3653 for (int i=0; i<8; ++i) { 3654 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i])) 3655 MatchEvenMask = false; 3656 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i])) 3657 MatchOddMask = false; 3658 } 3659 3660 if (!MatchEvenMask && !MatchOddMask) 3661 return SDValue(); 3662 3663 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT); 3664 3665 SDValue Op0 = SVOp->getOperand(0); 3666 SDValue Op1 = SVOp->getOperand(1); 3667 3668 if (MatchEvenMask) { 3669 // Shift the second operand right to 32 bits. 3670 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 }; 3671 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask); 3672 } else { 3673 // Shift the first operand left to 32 bits. 3674 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 }; 3675 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask); 3676 } 3677 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15}; 3678 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask); 3679 } 3680 3681 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3682 /// specifies a shuffle of elements that is suitable for input to UNPCKL. 3683 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT, 3684 bool HasInt256, bool V2IsSplat = false) { 3685 unsigned NumElts = VT.getVectorNumElements(); 3686 3687 assert((VT.is128BitVector() || VT.is256BitVector()) && 3688 "Unsupported vector type for unpckh"); 3689 3690 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3691 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3692 return false; 3693 3694 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3695 // independently on 128-bit lanes. 3696 unsigned NumLanes = VT.getSizeInBits()/128; 3697 unsigned NumLaneElts = NumElts/NumLanes; 3698 3699 for (unsigned l = 0; l != NumLanes; ++l) { 3700 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3701 i != (l+1)*NumLaneElts; 3702 i += 2, ++j) { 3703 int BitI = Mask[i]; 3704 int BitI1 = Mask[i+1]; 3705 if (!isUndefOrEqual(BitI, j)) 3706 return false; 3707 if (V2IsSplat) { 3708 if (!isUndefOrEqual(BitI1, NumElts)) 3709 return false; 3710 } else { 3711 if (!isUndefOrEqual(BitI1, j + NumElts)) 3712 return false; 3713 } 3714 } 3715 } 3716 3717 return true; 3718 } 3719 3720 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3721 /// specifies a shuffle of elements that is suitable for input to UNPCKH. 3722 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT, 3723 bool HasInt256, bool V2IsSplat = false) { 3724 unsigned NumElts = VT.getVectorNumElements(); 3725 3726 assert((VT.is128BitVector() || VT.is256BitVector()) && 3727 "Unsupported vector type for unpckh"); 3728 3729 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3730 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3731 return false; 3732 3733 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3734 // independently on 128-bit lanes. 3735 unsigned NumLanes = VT.getSizeInBits()/128; 3736 unsigned NumLaneElts = NumElts/NumLanes; 3737 3738 for (unsigned l = 0; l != NumLanes; ++l) { 3739 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3740 i != (l+1)*NumLaneElts; i += 2, ++j) { 3741 int BitI = Mask[i]; 3742 int BitI1 = Mask[i+1]; 3743 if (!isUndefOrEqual(BitI, j)) 3744 return false; 3745 if (V2IsSplat) { 3746 if (isUndefOrEqual(BitI1, NumElts)) 3747 return false; 3748 } else { 3749 if (!isUndefOrEqual(BitI1, j+NumElts)) 3750 return false; 3751 } 3752 } 3753 } 3754 return true; 3755 } 3756 3757 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3758 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3759 /// <0, 0, 1, 1> 3760 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3761 unsigned NumElts = VT.getVectorNumElements(); 3762 bool Is256BitVec = VT.is256BitVector(); 3763 3764 assert((VT.is128BitVector() || VT.is256BitVector()) && 3765 "Unsupported vector type for unpckh"); 3766 3767 if (Is256BitVec && NumElts != 4 && NumElts != 8 && 3768 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3769 return false; 3770 3771 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3772 // FIXME: Need a better way to get rid of this, there's no latency difference 3773 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3774 // the former later. We should also remove the "_undef" special mask. 3775 if (NumElts == 4 && Is256BitVec) 3776 return false; 3777 3778 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3779 // independently on 128-bit lanes. 3780 unsigned NumLanes = VT.getSizeInBits()/128; 3781 unsigned NumLaneElts = NumElts/NumLanes; 3782 3783 for (unsigned l = 0; l != NumLanes; ++l) { 3784 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3785 i != (l+1)*NumLaneElts; 3786 i += 2, ++j) { 3787 int BitI = Mask[i]; 3788 int BitI1 = Mask[i+1]; 3789 3790 if (!isUndefOrEqual(BitI, j)) 3791 return false; 3792 if (!isUndefOrEqual(BitI1, j)) 3793 return false; 3794 } 3795 } 3796 3797 return true; 3798 } 3799 3800 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3801 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3802 /// <2, 2, 3, 3> 3803 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3804 unsigned NumElts = VT.getVectorNumElements(); 3805 3806 assert((VT.is128BitVector() || VT.is256BitVector()) && 3807 "Unsupported vector type for unpckh"); 3808 3809 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3810 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3811 return false; 3812 3813 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3814 // independently on 128-bit lanes. 3815 unsigned NumLanes = VT.getSizeInBits()/128; 3816 unsigned NumLaneElts = NumElts/NumLanes; 3817 3818 for (unsigned l = 0; l != NumLanes; ++l) { 3819 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3820 i != (l+1)*NumLaneElts; i += 2, ++j) { 3821 int BitI = Mask[i]; 3822 int BitI1 = Mask[i+1]; 3823 if (!isUndefOrEqual(BitI, j)) 3824 return false; 3825 if (!isUndefOrEqual(BitI1, j)) 3826 return false; 3827 } 3828 } 3829 return true; 3830 } 3831 3832 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3833 /// specifies a shuffle of elements that is suitable for input to MOVSS, 3834 /// MOVSD, and MOVD, i.e. setting the lowest element. 3835 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) { 3836 if (VT.getVectorElementType().getSizeInBits() < 32) 3837 return false; 3838 if (!VT.is128BitVector()) 3839 return false; 3840 3841 unsigned NumElts = VT.getVectorNumElements(); 3842 3843 if (!isUndefOrEqual(Mask[0], NumElts)) 3844 return false; 3845 3846 for (unsigned i = 1; i != NumElts; ++i) 3847 if (!isUndefOrEqual(Mask[i], i)) 3848 return false; 3849 3850 return true; 3851 } 3852 3853 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered 3854 /// as permutations between 128-bit chunks or halves. As an example: this 3855 /// shuffle bellow: 3856 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3857 /// The first half comes from the second half of V1 and the second half from the 3858 /// the second half of V2. 3859 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 3860 if (!HasFp256 || !VT.is256BitVector()) 3861 return false; 3862 3863 // The shuffle result is divided into half A and half B. In total the two 3864 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3865 // B must come from C, D, E or F. 3866 unsigned HalfSize = VT.getVectorNumElements()/2; 3867 bool MatchA = false, MatchB = false; 3868 3869 // Check if A comes from one of C, D, E, F. 3870 for (unsigned Half = 0; Half != 4; ++Half) { 3871 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3872 MatchA = true; 3873 break; 3874 } 3875 } 3876 3877 // Check if B comes from one of C, D, E, F. 3878 for (unsigned Half = 0; Half != 4; ++Half) { 3879 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3880 MatchB = true; 3881 break; 3882 } 3883 } 3884 3885 return MatchA && MatchB; 3886 } 3887 3888 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle 3889 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions. 3890 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) { 3891 MVT VT = SVOp->getValueType(0).getSimpleVT(); 3892 3893 unsigned HalfSize = VT.getVectorNumElements()/2; 3894 3895 unsigned FstHalf = 0, SndHalf = 0; 3896 for (unsigned i = 0; i < HalfSize; ++i) { 3897 if (SVOp->getMaskElt(i) > 0) { 3898 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3899 break; 3900 } 3901 } 3902 for (unsigned i = HalfSize; i < HalfSize*2; ++i) { 3903 if (SVOp->getMaskElt(i) > 0) { 3904 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3905 break; 3906 } 3907 } 3908 3909 return (FstHalf | (SndHalf << 4)); 3910 } 3911 3912 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand 3913 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3914 /// Note that VPERMIL mask matching is different depending whether theunderlying 3915 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3916 /// to the same elements of the low, but to the higher half of the source. 3917 /// In VPERMILPD the two lanes could be shuffled independently of each other 3918 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY. 3919 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 3920 if (!HasFp256) 3921 return false; 3922 3923 unsigned NumElts = VT.getVectorNumElements(); 3924 // Only match 256-bit with 32/64-bit types 3925 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8)) 3926 return false; 3927 3928 unsigned NumLanes = VT.getSizeInBits()/128; 3929 unsigned LaneSize = NumElts/NumLanes; 3930 for (unsigned l = 0; l != NumElts; l += LaneSize) { 3931 for (unsigned i = 0; i != LaneSize; ++i) { 3932 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize)) 3933 return false; 3934 if (NumElts != 8 || l == 0) 3935 continue; 3936 // VPERMILPS handling 3937 if (Mask[i] < 0) 3938 continue; 3939 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l)) 3940 return false; 3941 } 3942 } 3943 3944 return true; 3945 } 3946 3947 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse 3948 /// of what x86 movss want. X86 movs requires the lowest element to be lowest 3949 /// element of vector 2 and the other elements to come from vector 1 in order. 3950 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT, 3951 bool V2IsSplat = false, bool V2IsUndef = false) { 3952 if (!VT.is128BitVector()) 3953 return false; 3954 3955 unsigned NumOps = VT.getVectorNumElements(); 3956 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3957 return false; 3958 3959 if (!isUndefOrEqual(Mask[0], 0)) 3960 return false; 3961 3962 for (unsigned i = 1; i != NumOps; ++i) 3963 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3964 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3965 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3966 return false; 3967 3968 return true; 3969 } 3970 3971 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3972 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3973 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3974 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT, 3975 const X86Subtarget *Subtarget) { 3976 if (!Subtarget->hasSSE3()) 3977 return false; 3978 3979 unsigned NumElems = VT.getVectorNumElements(); 3980 3981 if ((VT.is128BitVector() && NumElems != 4) || 3982 (VT.is256BitVector() && NumElems != 8)) 3983 return false; 3984 3985 // "i+1" is the value the indexed mask element must have 3986 for (unsigned i = 0; i != NumElems; i += 2) 3987 if (!isUndefOrEqual(Mask[i], i+1) || 3988 !isUndefOrEqual(Mask[i+1], i+1)) 3989 return false; 3990 3991 return true; 3992 } 3993 3994 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3995 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3996 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3997 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT, 3998 const X86Subtarget *Subtarget) { 3999 if (!Subtarget->hasSSE3()) 4000 return false; 4001 4002 unsigned NumElems = VT.getVectorNumElements(); 4003 4004 if ((VT.is128BitVector() && NumElems != 4) || 4005 (VT.is256BitVector() && NumElems != 8)) 4006 return false; 4007 4008 // "i" is the value the indexed mask element must have 4009 for (unsigned i = 0; i != NumElems; i += 2) 4010 if (!isUndefOrEqual(Mask[i], i) || 4011 !isUndefOrEqual(Mask[i+1], i)) 4012 return false; 4013 4014 return true; 4015 } 4016 4017 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 4018 /// specifies a shuffle of elements that is suitable for input to 256-bit 4019 /// version of MOVDDUP. 4020 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 4021 if (!HasFp256 || !VT.is256BitVector()) 4022 return false; 4023 4024 unsigned NumElts = VT.getVectorNumElements(); 4025 if (NumElts != 4) 4026 return false; 4027 4028 for (unsigned i = 0; i != NumElts/2; ++i) 4029 if (!isUndefOrEqual(Mask[i], 0)) 4030 return false; 4031 for (unsigned i = NumElts/2; i != NumElts; ++i) 4032 if (!isUndefOrEqual(Mask[i], NumElts/2)) 4033 return false; 4034 return true; 4035 } 4036 4037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 4038 /// specifies a shuffle of elements that is suitable for input to 128-bit 4039 /// version of MOVDDUP. 4040 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) { 4041 if (!VT.is128BitVector()) 4042 return false; 4043 4044 unsigned e = VT.getVectorNumElements() / 2; 4045 for (unsigned i = 0; i != e; ++i) 4046 if (!isUndefOrEqual(Mask[i], i)) 4047 return false; 4048 for (unsigned i = 0; i != e; ++i) 4049 if (!isUndefOrEqual(Mask[e+i], i)) 4050 return false; 4051 return true; 4052 } 4053 4054 /// isVEXTRACTF128Index - Return true if the specified 4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is 4056 /// suitable for input to VEXTRACTF128. 4057 bool X86::isVEXTRACTF128Index(SDNode *N) { 4058 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4059 return false; 4060 4061 // The index should be aligned on a 128-bit boundary. 4062 uint64_t Index = 4063 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4064 4065 MVT VT = N->getValueType(0).getSimpleVT(); 4066 unsigned ElSize = VT.getVectorElementType().getSizeInBits(); 4067 bool Result = (Index * ElSize) % 128 == 0; 4068 4069 return Result; 4070 } 4071 4072 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 4073 /// operand specifies a subvector insert that is suitable for input to 4074 /// VINSERTF128. 4075 bool X86::isVINSERTF128Index(SDNode *N) { 4076 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4077 return false; 4078 4079 // The index should be aligned on a 128-bit boundary. 4080 uint64_t Index = 4081 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4082 4083 MVT VT = N->getValueType(0).getSimpleVT(); 4084 unsigned ElSize = VT.getVectorElementType().getSizeInBits(); 4085 bool Result = (Index * ElSize) % 128 == 0; 4086 4087 return Result; 4088 } 4089 4090 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4091 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4092 /// Handles 128-bit and 256-bit. 4093 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) { 4094 MVT VT = N->getValueType(0).getSimpleVT(); 4095 4096 assert((VT.is128BitVector() || VT.is256BitVector()) && 4097 "Unsupported vector type for PSHUF/SHUFP"); 4098 4099 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate 4100 // independently on 128-bit lanes. 4101 unsigned NumElts = VT.getVectorNumElements(); 4102 unsigned NumLanes = VT.getSizeInBits()/128; 4103 unsigned NumLaneElts = NumElts/NumLanes; 4104 4105 assert((NumLaneElts == 2 || NumLaneElts == 4) && 4106 "Only supports 2 or 4 elements per lane"); 4107 4108 unsigned Shift = (NumLaneElts == 4) ? 1 : 0; 4109 unsigned Mask = 0; 4110 for (unsigned i = 0; i != NumElts; ++i) { 4111 int Elt = N->getMaskElt(i); 4112 if (Elt < 0) continue; 4113 Elt &= NumLaneElts - 1; 4114 unsigned ShAmt = (i << Shift) % 8; 4115 Mask |= Elt << ShAmt; 4116 } 4117 4118 return Mask; 4119 } 4120 4121 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4122 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4123 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) { 4124 MVT VT = N->getValueType(0).getSimpleVT(); 4125 4126 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4127 "Unsupported vector type for PSHUFHW"); 4128 4129 unsigned NumElts = VT.getVectorNumElements(); 4130 4131 unsigned Mask = 0; 4132 for (unsigned l = 0; l != NumElts; l += 8) { 4133 // 8 nodes per lane, but we only care about the last 4. 4134 for (unsigned i = 0; i < 4; ++i) { 4135 int Elt = N->getMaskElt(l+i+4); 4136 if (Elt < 0) continue; 4137 Elt &= 0x3; // only 2-bits. 4138 Mask |= Elt << (i * 2); 4139 } 4140 } 4141 4142 return Mask; 4143 } 4144 4145 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4146 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4147 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) { 4148 MVT VT = N->getValueType(0).getSimpleVT(); 4149 4150 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4151 "Unsupported vector type for PSHUFHW"); 4152 4153 unsigned NumElts = VT.getVectorNumElements(); 4154 4155 unsigned Mask = 0; 4156 for (unsigned l = 0; l != NumElts; l += 8) { 4157 // 8 nodes per lane, but we only care about the first 4. 4158 for (unsigned i = 0; i < 4; ++i) { 4159 int Elt = N->getMaskElt(l+i); 4160 if (Elt < 0) continue; 4161 Elt &= 0x3; // only 2-bits 4162 Mask |= Elt << (i * 2); 4163 } 4164 } 4165 4166 return Mask; 4167 } 4168 4169 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4170 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4171 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) { 4172 MVT VT = SVOp->getValueType(0).getSimpleVT(); 4173 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3; 4174 4175 unsigned NumElts = VT.getVectorNumElements(); 4176 unsigned NumLanes = VT.getSizeInBits()/128; 4177 unsigned NumLaneElts = NumElts/NumLanes; 4178 4179 int Val = 0; 4180 unsigned i; 4181 for (i = 0; i != NumElts; ++i) { 4182 Val = SVOp->getMaskElt(i); 4183 if (Val >= 0) 4184 break; 4185 } 4186 if (Val >= (int)NumElts) 4187 Val -= NumElts - NumLaneElts; 4188 4189 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4190 return (Val - i) * EltSize; 4191 } 4192 4193 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4194 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4195 /// instructions. 4196 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4197 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4198 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4199 4200 uint64_t Index = 4201 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4202 4203 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT(); 4204 MVT ElVT = VecVT.getVectorElementType(); 4205 4206 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4207 return Index / NumElemsPerChunk; 4208 } 4209 4210 /// getInsertVINSERTF128Immediate - Return the appropriate immediate 4211 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4212 /// instructions. 4213 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4214 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4215 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4216 4217 uint64_t Index = 4218 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4219 4220 MVT VecVT = N->getValueType(0).getSimpleVT(); 4221 MVT ElVT = VecVT.getVectorElementType(); 4222 4223 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4224 return Index / NumElemsPerChunk; 4225 } 4226 4227 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle 4228 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions. 4229 /// Handles 256-bit. 4230 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) { 4231 MVT VT = N->getValueType(0).getSimpleVT(); 4232 4233 unsigned NumElts = VT.getVectorNumElements(); 4234 4235 assert((VT.is256BitVector() && NumElts == 4) && 4236 "Unsupported vector type for VPERMQ/VPERMPD"); 4237 4238 unsigned Mask = 0; 4239 for (unsigned i = 0; i != NumElts; ++i) { 4240 int Elt = N->getMaskElt(i); 4241 if (Elt < 0) 4242 continue; 4243 Mask |= Elt << (i*2); 4244 } 4245 4246 return Mask; 4247 } 4248 /// isZeroNode - Returns true if Elt is a constant zero or a floating point 4249 /// constant +0.0. 4250 bool X86::isZeroNode(SDValue Elt) { 4251 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt)) 4252 return CN->isNullValue(); 4253 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt)) 4254 return CFP->getValueAPF().isPosZero(); 4255 return false; 4256 } 4257 4258 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4259 /// their permute mask. 4260 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4261 SelectionDAG &DAG) { 4262 MVT VT = SVOp->getValueType(0).getSimpleVT(); 4263 unsigned NumElems = VT.getVectorNumElements(); 4264 SmallVector<int, 8> MaskVec; 4265 4266 for (unsigned i = 0; i != NumElems; ++i) { 4267 int Idx = SVOp->getMaskElt(i); 4268 if (Idx >= 0) { 4269 if (Idx < (int)NumElems) 4270 Idx += NumElems; 4271 else 4272 Idx -= NumElems; 4273 } 4274 MaskVec.push_back(Idx); 4275 } 4276 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1), 4277 SVOp->getOperand(0), &MaskVec[0]); 4278 } 4279 4280 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4281 /// match movhlps. The lower half elements should come from upper half of 4282 /// V1 (and in order), and the upper half elements should come from the upper 4283 /// half of V2 (and in order). 4284 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) { 4285 if (!VT.is128BitVector()) 4286 return false; 4287 if (VT.getVectorNumElements() != 4) 4288 return false; 4289 for (unsigned i = 0, e = 2; i != e; ++i) 4290 if (!isUndefOrEqual(Mask[i], i+2)) 4291 return false; 4292 for (unsigned i = 2; i != 4; ++i) 4293 if (!isUndefOrEqual(Mask[i], i+4)) 4294 return false; 4295 return true; 4296 } 4297 4298 /// isScalarLoadToVector - Returns true if the node is a scalar load that 4299 /// is promoted to a vector. It also returns the LoadSDNode by reference if 4300 /// required. 4301 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4302 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4303 return false; 4304 N = N->getOperand(0).getNode(); 4305 if (!ISD::isNON_EXTLoad(N)) 4306 return false; 4307 if (LD) 4308 *LD = cast<LoadSDNode>(N); 4309 return true; 4310 } 4311 4312 // Test whether the given value is a vector value which will be legalized 4313 // into a load. 4314 static bool WillBeConstantPoolLoad(SDNode *N) { 4315 if (N->getOpcode() != ISD::BUILD_VECTOR) 4316 return false; 4317 4318 // Check for any non-constant elements. 4319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4320 switch (N->getOperand(i).getNode()->getOpcode()) { 4321 case ISD::UNDEF: 4322 case ISD::ConstantFP: 4323 case ISD::Constant: 4324 break; 4325 default: 4326 return false; 4327 } 4328 4329 // Vectors of all-zeros and all-ones are materialized with special 4330 // instructions rather than being loaded. 4331 return !ISD::isBuildVectorAllZeros(N) && 4332 !ISD::isBuildVectorAllOnes(N); 4333 } 4334 4335 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4336 /// match movlp{s|d}. The lower half elements should come from lower half of 4337 /// V1 (and in order), and the upper half elements should come from the upper 4338 /// half of V2 (and in order). And since V1 will become the source of the 4339 /// MOVLP, it must be either a vector load or a scalar load to vector. 4340 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4341 ArrayRef<int> Mask, EVT VT) { 4342 if (!VT.is128BitVector()) 4343 return false; 4344 4345 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4346 return false; 4347 // Is V2 is a vector load, don't do this transformation. We will try to use 4348 // load folding shufps op. 4349 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4350 return false; 4351 4352 unsigned NumElems = VT.getVectorNumElements(); 4353 4354 if (NumElems != 2 && NumElems != 4) 4355 return false; 4356 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4357 if (!isUndefOrEqual(Mask[i], i)) 4358 return false; 4359 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 4360 if (!isUndefOrEqual(Mask[i], i+NumElems)) 4361 return false; 4362 return true; 4363 } 4364 4365 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4366 /// all the same. 4367 static bool isSplatVector(SDNode *N) { 4368 if (N->getOpcode() != ISD::BUILD_VECTOR) 4369 return false; 4370 4371 SDValue SplatValue = N->getOperand(0); 4372 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4373 if (N->getOperand(i) != SplatValue) 4374 return false; 4375 return true; 4376 } 4377 4378 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4379 /// to an zero vector. 4380 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4381 static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4382 SDValue V1 = N->getOperand(0); 4383 SDValue V2 = N->getOperand(1); 4384 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4385 for (unsigned i = 0; i != NumElems; ++i) { 4386 int Idx = N->getMaskElt(i); 4387 if (Idx >= (int)NumElems) { 4388 unsigned Opc = V2.getOpcode(); 4389 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4390 continue; 4391 if (Opc != ISD::BUILD_VECTOR || 4392 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4393 return false; 4394 } else if (Idx >= 0) { 4395 unsigned Opc = V1.getOpcode(); 4396 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4397 continue; 4398 if (Opc != ISD::BUILD_VECTOR || 4399 !X86::isZeroNode(V1.getOperand(Idx))) 4400 return false; 4401 } 4402 } 4403 return true; 4404 } 4405 4406 /// getZeroVector - Returns a vector of specified type with all zero elements. 4407 /// 4408 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget, 4409 SelectionDAG &DAG, SDLoc dl) { 4410 assert(VT.isVector() && "Expected a vector type"); 4411 4412 // Always build SSE zero vectors as <4 x i32> bitcasted 4413 // to their dest type. This ensures they get CSE'd. 4414 SDValue Vec; 4415 if (VT.is128BitVector()) { // SSE 4416 if (Subtarget->hasSSE2()) { // SSE2 4417 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4418 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4419 } else { // SSE1 4420 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4421 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4422 } 4423 } else if (VT.is256BitVector()) { // AVX 4424 if (Subtarget->hasInt256()) { // AVX2 4425 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4426 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4427 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 4428 array_lengthof(Ops)); 4429 } else { 4430 // 256-bit logic and arithmetic instructions in AVX are all 4431 // floating-point, no support for integer ops. Emit fp zeroed vectors. 4432 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4433 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4434 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 4435 array_lengthof(Ops)); 4436 } 4437 } else 4438 llvm_unreachable("Unexpected vector type"); 4439 4440 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4441 } 4442 4443 /// getOnesVector - Returns a vector of specified type with all bits set. 4444 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with 4445 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately. 4446 /// Then bitcast to their original type, ensuring they get CSE'd. 4447 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG, 4448 SDLoc dl) { 4449 assert(VT.isVector() && "Expected a vector type"); 4450 4451 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4452 SDValue Vec; 4453 if (VT.is256BitVector()) { 4454 if (HasInt256) { // AVX2 4455 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4456 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 4457 array_lengthof(Ops)); 4458 } else { // AVX 4459 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4460 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl); 4461 } 4462 } else if (VT.is128BitVector()) { 4463 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4464 } else 4465 llvm_unreachable("Unexpected vector type"); 4466 4467 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4468 } 4469 4470 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4471 /// that point to V2 points to its first element. 4472 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) { 4473 for (unsigned i = 0; i != NumElems; ++i) { 4474 if (Mask[i] > (int)NumElems) { 4475 Mask[i] = NumElems; 4476 } 4477 } 4478 } 4479 4480 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4481 /// operation of specified width. 4482 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4483 SDValue V2) { 4484 unsigned NumElems = VT.getVectorNumElements(); 4485 SmallVector<int, 8> Mask; 4486 Mask.push_back(NumElems); 4487 for (unsigned i = 1; i != NumElems; ++i) 4488 Mask.push_back(i); 4489 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4490 } 4491 4492 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4493 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4494 SDValue V2) { 4495 unsigned NumElems = VT.getVectorNumElements(); 4496 SmallVector<int, 8> Mask; 4497 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4498 Mask.push_back(i); 4499 Mask.push_back(i + NumElems); 4500 } 4501 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4502 } 4503 4504 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4505 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1, 4506 SDValue V2) { 4507 unsigned NumElems = VT.getVectorNumElements(); 4508 SmallVector<int, 8> Mask; 4509 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) { 4510 Mask.push_back(i + Half); 4511 Mask.push_back(i + NumElems + Half); 4512 } 4513 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4514 } 4515 4516 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4517 // a generic shuffle instruction because the target has no such instructions. 4518 // Generate shuffles which repeat i16 and i8 several times until they can be 4519 // represented by v4f32 and then be manipulated by target suported shuffles. 4520 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4521 EVT VT = V.getValueType(); 4522 int NumElems = VT.getVectorNumElements(); 4523 SDLoc dl(V); 4524 4525 while (NumElems > 4) { 4526 if (EltNo < NumElems/2) { 4527 V = getUnpackl(DAG, dl, VT, V, V); 4528 } else { 4529 V = getUnpackh(DAG, dl, VT, V, V); 4530 EltNo -= NumElems/2; 4531 } 4532 NumElems >>= 1; 4533 } 4534 return V; 4535 } 4536 4537 /// getLegalSplat - Generate a legal splat with supported x86 shuffles 4538 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4539 EVT VT = V.getValueType(); 4540 SDLoc dl(V); 4541 4542 if (VT.is128BitVector()) { 4543 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4544 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4545 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4546 &SplatMask[0]); 4547 } else if (VT.is256BitVector()) { 4548 // To use VPERMILPS to splat scalars, the second half of indicies must 4549 // refer to the higher part, which is a duplication of the lower one, 4550 // because VPERMILPS can only handle in-lane permutations. 4551 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4552 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4553 4554 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4555 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4556 &SplatMask[0]); 4557 } else 4558 llvm_unreachable("Vector size not supported"); 4559 4560 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4561 } 4562 4563 /// PromoteSplat - Splat is promoted to target supported vector shuffles. 4564 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4565 EVT SrcVT = SV->getValueType(0); 4566 SDValue V1 = SV->getOperand(0); 4567 SDLoc dl(SV); 4568 4569 int EltNo = SV->getSplatIndex(); 4570 int NumElems = SrcVT.getVectorNumElements(); 4571 bool Is256BitVec = SrcVT.is256BitVector(); 4572 4573 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) && 4574 "Unknown how to promote splat for type"); 4575 4576 // Extract the 128-bit part containing the splat element and update 4577 // the splat element index when it refers to the higher register. 4578 if (Is256BitVec) { 4579 V1 = Extract128BitVector(V1, EltNo, DAG, dl); 4580 if (EltNo >= NumElems/2) 4581 EltNo -= NumElems/2; 4582 } 4583 4584 // All i16 and i8 vector types can't be used directly by a generic shuffle 4585 // instruction because the target has no such instruction. Generate shuffles 4586 // which repeat i16 and i8 several times until they fit in i32, and then can 4587 // be manipulated by target suported shuffles. 4588 EVT EltVT = SrcVT.getVectorElementType(); 4589 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4590 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4591 4592 // Recreate the 256-bit vector and place the same 128-bit vector 4593 // into the low and high part. This is necessary because we want 4594 // to use VPERM* to shuffle the vectors 4595 if (Is256BitVec) { 4596 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1); 4597 } 4598 4599 return getLegalSplat(DAG, V1, EltNo); 4600 } 4601 4602 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4603 /// vector of zero or undef vector. This produces a shuffle where the low 4604 /// element of V2 is swizzled into the zero/undef vector, landing at element 4605 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4606 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4607 bool IsZero, 4608 const X86Subtarget *Subtarget, 4609 SelectionDAG &DAG) { 4610 EVT VT = V2.getValueType(); 4611 SDValue V1 = IsZero 4612 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT); 4613 unsigned NumElems = VT.getVectorNumElements(); 4614 SmallVector<int, 16> MaskVec; 4615 for (unsigned i = 0; i != NumElems; ++i) 4616 // If this is the insertion idx, put the low elt of V2 here. 4617 MaskVec.push_back(i == Idx ? NumElems : i); 4618 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]); 4619 } 4620 4621 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the 4622 /// target specific opcode. Returns true if the Mask could be calculated. 4623 /// Sets IsUnary to true if only uses one source. 4624 static bool getTargetShuffleMask(SDNode *N, MVT VT, 4625 SmallVectorImpl<int> &Mask, bool &IsUnary) { 4626 unsigned NumElems = VT.getVectorNumElements(); 4627 SDValue ImmN; 4628 4629 IsUnary = false; 4630 switch(N->getOpcode()) { 4631 case X86ISD::SHUFP: 4632 ImmN = N->getOperand(N->getNumOperands()-1); 4633 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4634 break; 4635 case X86ISD::UNPCKH: 4636 DecodeUNPCKHMask(VT, Mask); 4637 break; 4638 case X86ISD::UNPCKL: 4639 DecodeUNPCKLMask(VT, Mask); 4640 break; 4641 case X86ISD::MOVHLPS: 4642 DecodeMOVHLPSMask(NumElems, Mask); 4643 break; 4644 case X86ISD::MOVLHPS: 4645 DecodeMOVLHPSMask(NumElems, Mask); 4646 break; 4647 case X86ISD::PALIGNR: 4648 ImmN = N->getOperand(N->getNumOperands()-1); 4649 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4650 break; 4651 case X86ISD::PSHUFD: 4652 case X86ISD::VPERMILP: 4653 ImmN = N->getOperand(N->getNumOperands()-1); 4654 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4655 IsUnary = true; 4656 break; 4657 case X86ISD::PSHUFHW: 4658 ImmN = N->getOperand(N->getNumOperands()-1); 4659 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4660 IsUnary = true; 4661 break; 4662 case X86ISD::PSHUFLW: 4663 ImmN = N->getOperand(N->getNumOperands()-1); 4664 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4665 IsUnary = true; 4666 break; 4667 case X86ISD::VPERMI: 4668 ImmN = N->getOperand(N->getNumOperands()-1); 4669 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4670 IsUnary = true; 4671 break; 4672 case X86ISD::MOVSS: 4673 case X86ISD::MOVSD: { 4674 // The index 0 always comes from the first element of the second source, 4675 // this is why MOVSS and MOVSD are used in the first place. The other 4676 // elements come from the other positions of the first source vector 4677 Mask.push_back(NumElems); 4678 for (unsigned i = 1; i != NumElems; ++i) { 4679 Mask.push_back(i); 4680 } 4681 break; 4682 } 4683 case X86ISD::VPERM2X128: 4684 ImmN = N->getOperand(N->getNumOperands()-1); 4685 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4686 if (Mask.empty()) return false; 4687 break; 4688 case X86ISD::MOVDDUP: 4689 case X86ISD::MOVLHPD: 4690 case X86ISD::MOVLPD: 4691 case X86ISD::MOVLPS: 4692 case X86ISD::MOVSHDUP: 4693 case X86ISD::MOVSLDUP: 4694 // Not yet implemented 4695 return false; 4696 default: llvm_unreachable("unknown target shuffle node"); 4697 } 4698 4699 return true; 4700 } 4701 4702 /// getShuffleScalarElt - Returns the scalar element that will make up the ith 4703 /// element of the result of the vector shuffle. 4704 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG, 4705 unsigned Depth) { 4706 if (Depth == 6) 4707 return SDValue(); // Limit search depth. 4708 4709 SDValue V = SDValue(N, 0); 4710 EVT VT = V.getValueType(); 4711 unsigned Opcode = V.getOpcode(); 4712 4713 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4714 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4715 int Elt = SV->getMaskElt(Index); 4716 4717 if (Elt < 0) 4718 return DAG.getUNDEF(VT.getVectorElementType()); 4719 4720 unsigned NumElems = VT.getVectorNumElements(); 4721 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0) 4722 : SV->getOperand(1); 4723 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1); 4724 } 4725 4726 // Recurse into target specific vector shuffles to find scalars. 4727 if (isTargetShuffle(Opcode)) { 4728 MVT ShufVT = V.getValueType().getSimpleVT(); 4729 unsigned NumElems = ShufVT.getVectorNumElements(); 4730 SmallVector<int, 16> ShuffleMask; 4731 bool IsUnary; 4732 4733 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary)) 4734 return SDValue(); 4735 4736 int Elt = ShuffleMask[Index]; 4737 if (Elt < 0) 4738 return DAG.getUNDEF(ShufVT.getVectorElementType()); 4739 4740 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0) 4741 : N->getOperand(1); 4742 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, 4743 Depth+1); 4744 } 4745 4746 // Actual nodes that may contain scalar elements 4747 if (Opcode == ISD::BITCAST) { 4748 V = V.getOperand(0); 4749 EVT SrcVT = V.getValueType(); 4750 unsigned NumElems = VT.getVectorNumElements(); 4751 4752 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4753 return SDValue(); 4754 } 4755 4756 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4757 return (Index == 0) ? V.getOperand(0) 4758 : DAG.getUNDEF(VT.getVectorElementType()); 4759 4760 if (V.getOpcode() == ISD::BUILD_VECTOR) 4761 return V.getOperand(Index); 4762 4763 return SDValue(); 4764 } 4765 4766 /// getNumOfConsecutiveZeros - Return the number of elements of a vector 4767 /// shuffle operation which come from a consecutively from a zero. The 4768 /// search can start in two different directions, from left or right. 4769 /// We count undefs as zeros until PreferredNum is reached. 4770 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, 4771 unsigned NumElems, bool ZerosFromLeft, 4772 SelectionDAG &DAG, 4773 unsigned PreferredNum = -1U) { 4774 unsigned NumZeros = 0; 4775 for (unsigned i = 0; i != NumElems; ++i) { 4776 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1; 4777 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0); 4778 if (!Elt.getNode()) 4779 break; 4780 4781 if (X86::isZeroNode(Elt)) 4782 ++NumZeros; 4783 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum. 4784 NumZeros = std::min(NumZeros + 1, PreferredNum); 4785 else 4786 break; 4787 } 4788 4789 return NumZeros; 4790 } 4791 4792 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE) 4793 /// correspond consecutively to elements from one of the vector operands, 4794 /// starting from its index OpIdx. Also tell OpNum which source vector operand. 4795 static 4796 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, 4797 unsigned MaskI, unsigned MaskE, unsigned OpIdx, 4798 unsigned NumElems, unsigned &OpNum) { 4799 bool SeenV1 = false; 4800 bool SeenV2 = false; 4801 4802 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) { 4803 int Idx = SVOp->getMaskElt(i); 4804 // Ignore undef indicies 4805 if (Idx < 0) 4806 continue; 4807 4808 if (Idx < (int)NumElems) 4809 SeenV1 = true; 4810 else 4811 SeenV2 = true; 4812 4813 // Only accept consecutive elements from the same vector 4814 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4815 return false; 4816 } 4817 4818 OpNum = SeenV1 ? 0 : 1; 4819 return true; 4820 } 4821 4822 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4823 /// logical left shift of a vector. 4824 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4825 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4826 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4827 unsigned NumZeros = getNumOfConsecutiveZeros( 4828 SVOp, NumElems, false /* check zeros from right */, DAG, 4829 SVOp->getMaskElt(0)); 4830 unsigned OpSrc; 4831 4832 if (!NumZeros) 4833 return false; 4834 4835 // Considering the elements in the mask that are not consecutive zeros, 4836 // check if they consecutively come from only one of the source vectors. 4837 // 4838 // V1 = {X, A, B, C} 0 4839 // \ \ \ / 4840 // vector_shuffle V1, V2 <1, 2, 3, X> 4841 // 4842 if (!isShuffleMaskConsecutive(SVOp, 4843 0, // Mask Start Index 4844 NumElems-NumZeros, // Mask End Index(exclusive) 4845 NumZeros, // Where to start looking in the src vector 4846 NumElems, // Number of elements in vector 4847 OpSrc)) // Which source operand ? 4848 return false; 4849 4850 isLeft = false; 4851 ShAmt = NumZeros; 4852 ShVal = SVOp->getOperand(OpSrc); 4853 return true; 4854 } 4855 4856 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4857 /// logical left shift of a vector. 4858 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4859 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4860 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4861 unsigned NumZeros = getNumOfConsecutiveZeros( 4862 SVOp, NumElems, true /* check zeros from left */, DAG, 4863 NumElems - SVOp->getMaskElt(NumElems - 1) - 1); 4864 unsigned OpSrc; 4865 4866 if (!NumZeros) 4867 return false; 4868 4869 // Considering the elements in the mask that are not consecutive zeros, 4870 // check if they consecutively come from only one of the source vectors. 4871 // 4872 // 0 { A, B, X, X } = V2 4873 // / \ / / 4874 // vector_shuffle V1, V2 <X, X, 4, 5> 4875 // 4876 if (!isShuffleMaskConsecutive(SVOp, 4877 NumZeros, // Mask Start Index 4878 NumElems, // Mask End Index(exclusive) 4879 0, // Where to start looking in the src vector 4880 NumElems, // Number of elements in vector 4881 OpSrc)) // Which source operand ? 4882 return false; 4883 4884 isLeft = true; 4885 ShAmt = NumZeros; 4886 ShVal = SVOp->getOperand(OpSrc); 4887 return true; 4888 } 4889 4890 /// isVectorShift - Returns true if the shuffle can be implemented as a 4891 /// logical left or right shift of a vector. 4892 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4893 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4894 // Although the logic below support any bitwidth size, there are no 4895 // shift instructions which handle more than 128-bit vectors. 4896 if (!SVOp->getValueType(0).is128BitVector()) 4897 return false; 4898 4899 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4900 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4901 return true; 4902 4903 return false; 4904 } 4905 4906 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4907 /// 4908 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4909 unsigned NumNonZero, unsigned NumZero, 4910 SelectionDAG &DAG, 4911 const X86Subtarget* Subtarget, 4912 const TargetLowering &TLI) { 4913 if (NumNonZero > 8) 4914 return SDValue(); 4915 4916 SDLoc dl(Op); 4917 SDValue V(0, 0); 4918 bool First = true; 4919 for (unsigned i = 0; i < 16; ++i) { 4920 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4921 if (ThisIsNonZero && First) { 4922 if (NumZero) 4923 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4924 else 4925 V = DAG.getUNDEF(MVT::v8i16); 4926 First = false; 4927 } 4928 4929 if ((i & 1) != 0) { 4930 SDValue ThisElt(0, 0), LastElt(0, 0); 4931 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4932 if (LastIsNonZero) { 4933 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4934 MVT::i16, Op.getOperand(i-1)); 4935 } 4936 if (ThisIsNonZero) { 4937 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4938 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4939 ThisElt, DAG.getConstant(8, MVT::i8)); 4940 if (LastIsNonZero) 4941 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4942 } else 4943 ThisElt = LastElt; 4944 4945 if (ThisElt.getNode()) 4946 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4947 DAG.getIntPtrConstant(i/2)); 4948 } 4949 } 4950 4951 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4952 } 4953 4954 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4955 /// 4956 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4957 unsigned NumNonZero, unsigned NumZero, 4958 SelectionDAG &DAG, 4959 const X86Subtarget* Subtarget, 4960 const TargetLowering &TLI) { 4961 if (NumNonZero > 4) 4962 return SDValue(); 4963 4964 SDLoc dl(Op); 4965 SDValue V(0, 0); 4966 bool First = true; 4967 for (unsigned i = 0; i < 8; ++i) { 4968 bool isNonZero = (NonZeros & (1 << i)) != 0; 4969 if (isNonZero) { 4970 if (First) { 4971 if (NumZero) 4972 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4973 else 4974 V = DAG.getUNDEF(MVT::v8i16); 4975 First = false; 4976 } 4977 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4978 MVT::v8i16, V, Op.getOperand(i), 4979 DAG.getIntPtrConstant(i)); 4980 } 4981 } 4982 4983 return V; 4984 } 4985 4986 /// getVShift - Return a vector logical shift node. 4987 /// 4988 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4989 unsigned NumBits, SelectionDAG &DAG, 4990 const TargetLowering &TLI, SDLoc dl) { 4991 assert(VT.is128BitVector() && "Unknown type for VShift"); 4992 EVT ShVT = MVT::v2i64; 4993 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ; 4994 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4995 return DAG.getNode(ISD::BITCAST, dl, VT, 4996 DAG.getNode(Opc, dl, ShVT, SrcOp, 4997 DAG.getConstant(NumBits, 4998 TLI.getScalarShiftAmountTy(SrcOp.getValueType())))); 4999 } 5000 5001 SDValue 5002 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl, 5003 SelectionDAG &DAG) const { 5004 5005 // Check if the scalar load can be widened into a vector load. And if 5006 // the address is "base + cst" see if the cst can be "absorbed" into 5007 // the shuffle mask. 5008 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 5009 SDValue Ptr = LD->getBasePtr(); 5010 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 5011 return SDValue(); 5012 EVT PVT = LD->getValueType(0); 5013 if (PVT != MVT::i32 && PVT != MVT::f32) 5014 return SDValue(); 5015 5016 int FI = -1; 5017 int64_t Offset = 0; 5018 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 5019 FI = FINode->getIndex(); 5020 Offset = 0; 5021 } else if (DAG.isBaseWithConstantOffset(Ptr) && 5022 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 5023 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 5024 Offset = Ptr.getConstantOperandVal(1); 5025 Ptr = Ptr.getOperand(0); 5026 } else { 5027 return SDValue(); 5028 } 5029 5030 // FIXME: 256-bit vector instructions don't require a strict alignment, 5031 // improve this code to support it better. 5032 unsigned RequiredAlign = VT.getSizeInBits()/8; 5033 SDValue Chain = LD->getChain(); 5034 // Make sure the stack object alignment is at least 16 or 32. 5035 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 5036 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 5037 if (MFI->isFixedObjectIndex(FI)) { 5038 // Can't change the alignment. FIXME: It's possible to compute 5039 // the exact stack offset and reference FI + adjust offset instead. 5040 // If someone *really* cares about this. That's the way to implement it. 5041 return SDValue(); 5042 } else { 5043 MFI->setObjectAlignment(FI, RequiredAlign); 5044 } 5045 } 5046 5047 // (Offset % 16 or 32) must be multiple of 4. Then address is then 5048 // Ptr + (Offset & ~15). 5049 if (Offset < 0) 5050 return SDValue(); 5051 if ((Offset % RequiredAlign) & 3) 5052 return SDValue(); 5053 int64_t StartOffset = Offset & ~(RequiredAlign-1); 5054 if (StartOffset) 5055 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(), 5056 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 5057 5058 int EltNo = (Offset - StartOffset) >> 2; 5059 unsigned NumElems = VT.getVectorNumElements(); 5060 5061 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 5062 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 5063 LD->getPointerInfo().getWithOffset(StartOffset), 5064 false, false, false, 0); 5065 5066 SmallVector<int, 8> Mask; 5067 for (unsigned i = 0; i != NumElems; ++i) 5068 Mask.push_back(EltNo); 5069 5070 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]); 5071 } 5072 5073 return SDValue(); 5074 } 5075 5076 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 5077 /// vector of type 'VT', see if the elements can be replaced by a single large 5078 /// load which has the same value as a build_vector whose operands are 'elts'. 5079 /// 5080 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 5081 /// 5082 /// FIXME: we'd also like to handle the case where the last elements are zero 5083 /// rather than undef via VZEXT_LOAD, but we do not detect that case today. 5084 /// There's even a handy isZeroNode for that purpose. 5085 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 5086 SDLoc &DL, SelectionDAG &DAG) { 5087 EVT EltVT = VT.getVectorElementType(); 5088 unsigned NumElems = Elts.size(); 5089 5090 LoadSDNode *LDBase = NULL; 5091 unsigned LastLoadedElt = -1U; 5092 5093 // For each element in the initializer, see if we've found a load or an undef. 5094 // If we don't find an initial load element, or later load elements are 5095 // non-consecutive, bail out. 5096 for (unsigned i = 0; i < NumElems; ++i) { 5097 SDValue Elt = Elts[i]; 5098 5099 if (!Elt.getNode() || 5100 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 5101 return SDValue(); 5102 if (!LDBase) { 5103 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 5104 return SDValue(); 5105 LDBase = cast<LoadSDNode>(Elt.getNode()); 5106 LastLoadedElt = i; 5107 continue; 5108 } 5109 if (Elt.getOpcode() == ISD::UNDEF) 5110 continue; 5111 5112 LoadSDNode *LD = cast<LoadSDNode>(Elt); 5113 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 5114 return SDValue(); 5115 LastLoadedElt = i; 5116 } 5117 5118 // If we have found an entire vector of loads and undefs, then return a large 5119 // load of the entire vector width starting at the base pointer. If we found 5120 // consecutive loads for the low half, generate a vzext_load node. 5121 if (LastLoadedElt == NumElems - 1) { 5122 SDValue NewLd = SDValue(); 5123 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 5124 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5125 LDBase->getPointerInfo(), 5126 LDBase->isVolatile(), LDBase->isNonTemporal(), 5127 LDBase->isInvariant(), 0); 5128 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5129 LDBase->getPointerInfo(), 5130 LDBase->isVolatile(), LDBase->isNonTemporal(), 5131 LDBase->isInvariant(), LDBase->getAlignment()); 5132 5133 if (LDBase->hasAnyUseOfValue(1)) { 5134 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 5135 SDValue(LDBase, 1), 5136 SDValue(NewLd.getNode(), 1)); 5137 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain); 5138 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1), 5139 SDValue(NewLd.getNode(), 1)); 5140 } 5141 5142 return NewLd; 5143 } 5144 if (NumElems == 4 && LastLoadedElt == 1 && 5145 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5146 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5147 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5148 SDValue ResNode = 5149 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 5150 array_lengthof(Ops), MVT::i64, 5151 LDBase->getPointerInfo(), 5152 LDBase->getAlignment(), 5153 false/*isVolatile*/, true/*ReadMem*/, 5154 false/*WriteMem*/); 5155 5156 // Make sure the newly-created LOAD is in the same position as LDBase in 5157 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and 5158 // update uses of LDBase's output chain to use the TokenFactor. 5159 if (LDBase->hasAnyUseOfValue(1)) { 5160 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 5161 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1)); 5162 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain); 5163 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1), 5164 SDValue(ResNode.getNode(), 1)); 5165 } 5166 5167 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5168 } 5169 return SDValue(); 5170 } 5171 5172 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction 5173 /// to generate a splat value for the following cases: 5174 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant. 5175 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5176 /// a scalar load, or a constant. 5177 /// The VBROADCAST node is returned when a pattern is found, 5178 /// or SDValue() otherwise. 5179 SDValue 5180 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const { 5181 if (!Subtarget->hasFp256()) 5182 return SDValue(); 5183 5184 MVT VT = Op.getValueType().getSimpleVT(); 5185 SDLoc dl(Op); 5186 5187 assert((VT.is128BitVector() || VT.is256BitVector()) && 5188 "Unsupported vector type for broadcast."); 5189 5190 SDValue Ld; 5191 bool ConstSplatVal; 5192 5193 switch (Op.getOpcode()) { 5194 default: 5195 // Unknown pattern found. 5196 return SDValue(); 5197 5198 case ISD::BUILD_VECTOR: { 5199 // The BUILD_VECTOR node must be a splat. 5200 if (!isSplatVector(Op.getNode())) 5201 return SDValue(); 5202 5203 Ld = Op.getOperand(0); 5204 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5205 Ld.getOpcode() == ISD::ConstantFP); 5206 5207 // The suspected load node has several users. Make sure that all 5208 // of its users are from the BUILD_VECTOR node. 5209 // Constants may have multiple users. 5210 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5211 return SDValue(); 5212 break; 5213 } 5214 5215 case ISD::VECTOR_SHUFFLE: { 5216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5217 5218 // Shuffles must have a splat mask where the first element is 5219 // broadcasted. 5220 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5221 return SDValue(); 5222 5223 SDValue Sc = Op.getOperand(0); 5224 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR && 5225 Sc.getOpcode() != ISD::BUILD_VECTOR) { 5226 5227 if (!Subtarget->hasInt256()) 5228 return SDValue(); 5229 5230 // Use the register form of the broadcast instruction available on AVX2. 5231 if (VT.is256BitVector()) 5232 Sc = Extract128BitVector(Sc, 0, DAG, dl); 5233 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc); 5234 } 5235 5236 Ld = Sc.getOperand(0); 5237 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5238 Ld.getOpcode() == ISD::ConstantFP); 5239 5240 // The scalar_to_vector node and the suspected 5241 // load node must have exactly one user. 5242 // Constants may have multiple users. 5243 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse())) 5244 return SDValue(); 5245 break; 5246 } 5247 } 5248 5249 bool Is256 = VT.is256BitVector(); 5250 5251 // Handle the broadcasting a single constant scalar from the constant pool 5252 // into a vector. On Sandybridge it is still better to load a constant vector 5253 // from the constant pool and not to broadcast it from a scalar. 5254 if (ConstSplatVal && Subtarget->hasInt256()) { 5255 EVT CVT = Ld.getValueType(); 5256 assert(!CVT.isVector() && "Must not broadcast a vector type"); 5257 unsigned ScalarSize = CVT.getSizeInBits(); 5258 5259 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) { 5260 const Constant *C = 0; 5261 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld)) 5262 C = CI->getConstantIntValue(); 5263 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld)) 5264 C = CF->getConstantFPValue(); 5265 5266 assert(C && "Invalid constant type"); 5267 5268 SDValue CP = DAG.getConstantPool(C, getPointerTy()); 5269 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment(); 5270 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP, 5271 MachinePointerInfo::getConstantPool(), 5272 false, false, false, Alignment); 5273 5274 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5275 } 5276 } 5277 5278 bool IsLoad = ISD::isNormalLoad(Ld.getNode()); 5279 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5280 5281 // Handle AVX2 in-register broadcasts. 5282 if (!IsLoad && Subtarget->hasInt256() && 5283 (ScalarSize == 32 || (Is256 && ScalarSize == 64))) 5284 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5285 5286 // The scalar source must be a normal load. 5287 if (!IsLoad) 5288 return SDValue(); 5289 5290 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) 5291 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5292 5293 // The integer check is needed for the 64-bit into 128-bit so it doesn't match 5294 // double since there is no vbroadcastsd xmm 5295 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) { 5296 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64) 5297 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5298 } 5299 5300 // Unsupported broadcast. 5301 return SDValue(); 5302 } 5303 5304 SDValue 5305 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const { 5306 EVT VT = Op.getValueType(); 5307 5308 // Skip if insert_vec_elt is not supported. 5309 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT)) 5310 return SDValue(); 5311 5312 SDLoc DL(Op); 5313 unsigned NumElems = Op.getNumOperands(); 5314 5315 SDValue VecIn1; 5316 SDValue VecIn2; 5317 SmallVector<unsigned, 4> InsertIndices; 5318 SmallVector<int, 8> Mask(NumElems, -1); 5319 5320 for (unsigned i = 0; i != NumElems; ++i) { 5321 unsigned Opc = Op.getOperand(i).getOpcode(); 5322 5323 if (Opc == ISD::UNDEF) 5324 continue; 5325 5326 if (Opc != ISD::EXTRACT_VECTOR_ELT) { 5327 // Quit if more than 1 elements need inserting. 5328 if (InsertIndices.size() > 1) 5329 return SDValue(); 5330 5331 InsertIndices.push_back(i); 5332 continue; 5333 } 5334 5335 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0); 5336 SDValue ExtIdx = Op.getOperand(i).getOperand(1); 5337 5338 // Quit if extracted from vector of different type. 5339 if (ExtractedFromVec.getValueType() != VT) 5340 return SDValue(); 5341 5342 // Quit if non-constant index. 5343 if (!isa<ConstantSDNode>(ExtIdx)) 5344 return SDValue(); 5345 5346 if (VecIn1.getNode() == 0) 5347 VecIn1 = ExtractedFromVec; 5348 else if (VecIn1 != ExtractedFromVec) { 5349 if (VecIn2.getNode() == 0) 5350 VecIn2 = ExtractedFromVec; 5351 else if (VecIn2 != ExtractedFromVec) 5352 // Quit if more than 2 vectors to shuffle 5353 return SDValue(); 5354 } 5355 5356 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue(); 5357 5358 if (ExtractedFromVec == VecIn1) 5359 Mask[i] = Idx; 5360 else if (ExtractedFromVec == VecIn2) 5361 Mask[i] = Idx + NumElems; 5362 } 5363 5364 if (VecIn1.getNode() == 0) 5365 return SDValue(); 5366 5367 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 5368 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]); 5369 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) { 5370 unsigned Idx = InsertIndices[i]; 5371 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx), 5372 DAG.getIntPtrConstant(Idx)); 5373 } 5374 5375 return NV; 5376 } 5377 5378 SDValue 5379 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5380 SDLoc dl(Op); 5381 5382 MVT VT = Op.getValueType().getSimpleVT(); 5383 MVT ExtVT = VT.getVectorElementType(); 5384 unsigned NumElems = Op.getNumOperands(); 5385 5386 // Vectors containing all zeros can be matched by pxor and xorps later 5387 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5388 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5389 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5390 if (VT == MVT::v4i32 || VT == MVT::v8i32) 5391 return Op; 5392 5393 return getZeroVector(VT, Subtarget, DAG, dl); 5394 } 5395 5396 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5397 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use 5398 // vpcmpeqd on 256-bit vectors. 5399 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) { 5400 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256())) 5401 return Op; 5402 5403 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl); 5404 } 5405 5406 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 5407 if (Broadcast.getNode()) 5408 return Broadcast; 5409 5410 unsigned EVTBits = ExtVT.getSizeInBits(); 5411 5412 unsigned NumZero = 0; 5413 unsigned NumNonZero = 0; 5414 unsigned NonZeros = 0; 5415 bool IsAllConstants = true; 5416 SmallSet<SDValue, 8> Values; 5417 for (unsigned i = 0; i < NumElems; ++i) { 5418 SDValue Elt = Op.getOperand(i); 5419 if (Elt.getOpcode() == ISD::UNDEF) 5420 continue; 5421 Values.insert(Elt); 5422 if (Elt.getOpcode() != ISD::Constant && 5423 Elt.getOpcode() != ISD::ConstantFP) 5424 IsAllConstants = false; 5425 if (X86::isZeroNode(Elt)) 5426 NumZero++; 5427 else { 5428 NonZeros |= (1 << i); 5429 NumNonZero++; 5430 } 5431 } 5432 5433 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5434 if (NumNonZero == 0) 5435 return DAG.getUNDEF(VT); 5436 5437 // Special case for single non-zero, non-undef, element. 5438 if (NumNonZero == 1) { 5439 unsigned Idx = countTrailingZeros(NonZeros); 5440 SDValue Item = Op.getOperand(Idx); 5441 5442 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5443 // the value are obviously zero, truncate the value to i32 and do the 5444 // insertion that way. Only do this if the value is non-constant or if the 5445 // value is a constant being inserted into element 0. It is cheaper to do 5446 // a constant pool load than it is to do a movd + shuffle. 5447 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5448 (!IsAllConstants || Idx == 0)) { 5449 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5450 // Handle SSE only. 5451 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5452 EVT VecVT = MVT::v4i32; 5453 unsigned VecElts = 4; 5454 5455 // Truncate the value (which may itself be a constant) to i32, and 5456 // convert it to a vector with movd (S2V+shuffle to zero extend). 5457 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5458 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5459 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5460 5461 // Now we have our 32-bit value zero extended in the low element of 5462 // a vector. If Idx != 0, swizzle it into place. 5463 if (Idx != 0) { 5464 SmallVector<int, 4> Mask; 5465 Mask.push_back(Idx); 5466 for (unsigned i = 1; i != VecElts; ++i) 5467 Mask.push_back(i); 5468 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT), 5469 &Mask[0]); 5470 } 5471 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5472 } 5473 } 5474 5475 // If we have a constant or non-constant insertion into the low element of 5476 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5477 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5478 // depending on what the source datatype is. 5479 if (Idx == 0) { 5480 if (NumZero == 0) 5481 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5482 5483 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5484 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5485 if (VT.is256BitVector()) { 5486 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl); 5487 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec, 5488 Item, DAG.getIntPtrConstant(0)); 5489 } 5490 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5491 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5492 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5493 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5494 } 5495 5496 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5497 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5498 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item); 5499 if (VT.is256BitVector()) { 5500 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl); 5501 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl); 5502 } else { 5503 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5504 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5505 } 5506 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5507 } 5508 } 5509 5510 // Is it a vector logical left shift? 5511 if (NumElems == 2 && Idx == 1 && 5512 X86::isZeroNode(Op.getOperand(0)) && 5513 !X86::isZeroNode(Op.getOperand(1))) { 5514 unsigned NumBits = VT.getSizeInBits(); 5515 return getVShift(true, VT, 5516 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5517 VT, Op.getOperand(1)), 5518 NumBits/2, DAG, *this, dl); 5519 } 5520 5521 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5522 return SDValue(); 5523 5524 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5525 // is a non-constant being inserted into an element other than the low one, 5526 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5527 // movd/movss) to move this into the low element, then shuffle it into 5528 // place. 5529 if (EVTBits == 32) { 5530 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5531 5532 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5533 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG); 5534 SmallVector<int, 8> MaskVec; 5535 for (unsigned i = 0; i != NumElems; ++i) 5536 MaskVec.push_back(i == Idx ? 0 : 1); 5537 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5538 } 5539 } 5540 5541 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5542 if (Values.size() == 1) { 5543 if (EVTBits == 32) { 5544 // Instead of a shuffle like this: 5545 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5546 // Check if it's possible to issue this instead. 5547 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5548 unsigned Idx = countTrailingZeros(NonZeros); 5549 SDValue Item = Op.getOperand(Idx); 5550 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5551 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5552 } 5553 return SDValue(); 5554 } 5555 5556 // A vector full of immediates; various special cases are already 5557 // handled, so this is best done with a single constant-pool load. 5558 if (IsAllConstants) 5559 return SDValue(); 5560 5561 // For AVX-length vectors, build the individual 128-bit pieces and use 5562 // shuffles to put them in place. 5563 if (VT.is256BitVector()) { 5564 SmallVector<SDValue, 32> V; 5565 for (unsigned i = 0; i != NumElems; ++i) 5566 V.push_back(Op.getOperand(i)); 5567 5568 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5569 5570 // Build both the lower and upper subvector. 5571 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5572 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5573 NumElems/2); 5574 5575 // Recreate the wider vector with the lower and upper part. 5576 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl); 5577 } 5578 5579 // Let legalizer expand 2-wide build_vectors. 5580 if (EVTBits == 64) { 5581 if (NumNonZero == 1) { 5582 // One half is zero or undef. 5583 unsigned Idx = countTrailingZeros(NonZeros); 5584 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5585 Op.getOperand(Idx)); 5586 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG); 5587 } 5588 return SDValue(); 5589 } 5590 5591 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5592 if (EVTBits == 8 && NumElems == 16) { 5593 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5594 Subtarget, *this); 5595 if (V.getNode()) return V; 5596 } 5597 5598 if (EVTBits == 16 && NumElems == 8) { 5599 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5600 Subtarget, *this); 5601 if (V.getNode()) return V; 5602 } 5603 5604 // If element VT is == 32 bits, turn it into a number of shuffles. 5605 SmallVector<SDValue, 8> V(NumElems); 5606 if (NumElems == 4 && NumZero > 0) { 5607 for (unsigned i = 0; i < 4; ++i) { 5608 bool isZero = !(NonZeros & (1 << i)); 5609 if (isZero) 5610 V[i] = getZeroVector(VT, Subtarget, DAG, dl); 5611 else 5612 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5613 } 5614 5615 for (unsigned i = 0; i < 2; ++i) { 5616 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5617 default: break; 5618 case 0: 5619 V[i] = V[i*2]; // Must be a zero vector. 5620 break; 5621 case 1: 5622 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5623 break; 5624 case 2: 5625 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5626 break; 5627 case 3: 5628 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5629 break; 5630 } 5631 } 5632 5633 bool Reverse1 = (NonZeros & 0x3) == 2; 5634 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5635 int MaskVec[] = { 5636 Reverse1 ? 1 : 0, 5637 Reverse1 ? 0 : 1, 5638 static_cast<int>(Reverse2 ? NumElems+1 : NumElems), 5639 static_cast<int>(Reverse2 ? NumElems : NumElems+1) 5640 }; 5641 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5642 } 5643 5644 if (Values.size() > 1 && VT.is128BitVector()) { 5645 // Check for a build vector of consecutive loads. 5646 for (unsigned i = 0; i < NumElems; ++i) 5647 V[i] = Op.getOperand(i); 5648 5649 // Check for elements which are consecutive loads. 5650 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5651 if (LD.getNode()) 5652 return LD; 5653 5654 // Check for a build vector from mostly shuffle plus few inserting. 5655 SDValue Sh = buildFromShuffleMostly(Op, DAG); 5656 if (Sh.getNode()) 5657 return Sh; 5658 5659 // For SSE 4.1, use insertps to put the high elements into the low element. 5660 if (getSubtarget()->hasSSE41()) { 5661 SDValue Result; 5662 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5663 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5664 else 5665 Result = DAG.getUNDEF(VT); 5666 5667 for (unsigned i = 1; i < NumElems; ++i) { 5668 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5669 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5670 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5671 } 5672 return Result; 5673 } 5674 5675 // Otherwise, expand into a number of unpckl*, start by extending each of 5676 // our (non-undef) elements to the full vector width with the element in the 5677 // bottom slot of the vector (which generates no code for SSE). 5678 for (unsigned i = 0; i < NumElems; ++i) { 5679 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5680 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5681 else 5682 V[i] = DAG.getUNDEF(VT); 5683 } 5684 5685 // Next, we iteratively mix elements, e.g. for v4f32: 5686 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5687 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5688 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5689 unsigned EltStride = NumElems >> 1; 5690 while (EltStride != 0) { 5691 for (unsigned i = 0; i < EltStride; ++i) { 5692 // If V[i+EltStride] is undef and this is the first round of mixing, 5693 // then it is safe to just drop this shuffle: V[i] is already in the 5694 // right place, the one element (since it's the first round) being 5695 // inserted as undef can be dropped. This isn't safe for successive 5696 // rounds because they will permute elements within both vectors. 5697 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5698 EltStride == NumElems/2) 5699 continue; 5700 5701 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5702 } 5703 EltStride >>= 1; 5704 } 5705 return V[0]; 5706 } 5707 return SDValue(); 5708 } 5709 5710 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5711 // to create 256-bit vectors from two other 128-bit ones. 5712 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5713 SDLoc dl(Op); 5714 MVT ResVT = Op.getValueType().getSimpleVT(); 5715 5716 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide"); 5717 5718 SDValue V1 = Op.getOperand(0); 5719 SDValue V2 = Op.getOperand(1); 5720 unsigned NumElems = ResVT.getVectorNumElements(); 5721 5722 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl); 5723 } 5724 5725 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5726 assert(Op.getNumOperands() == 2); 5727 5728 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5729 // from two other 128-bit ones. 5730 return LowerAVXCONCAT_VECTORS(Op, DAG); 5731 } 5732 5733 // Try to lower a shuffle node into a simple blend instruction. 5734 static SDValue 5735 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp, 5736 const X86Subtarget *Subtarget, SelectionDAG &DAG) { 5737 SDValue V1 = SVOp->getOperand(0); 5738 SDValue V2 = SVOp->getOperand(1); 5739 SDLoc dl(SVOp); 5740 MVT VT = SVOp->getValueType(0).getSimpleVT(); 5741 MVT EltVT = VT.getVectorElementType(); 5742 unsigned NumElems = VT.getVectorNumElements(); 5743 5744 if (!Subtarget->hasSSE41() || EltVT == MVT::i8) 5745 return SDValue(); 5746 if (!Subtarget->hasInt256() && VT == MVT::v16i16) 5747 return SDValue(); 5748 5749 // Check the mask for BLEND and build the value. 5750 unsigned MaskValue = 0; 5751 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise. 5752 unsigned NumLanes = (NumElems-1)/8 + 1; 5753 unsigned NumElemsInLane = NumElems / NumLanes; 5754 5755 // Blend for v16i16 should be symetric for the both lanes. 5756 for (unsigned i = 0; i < NumElemsInLane; ++i) { 5757 5758 int SndLaneEltIdx = (NumLanes == 2) ? 5759 SVOp->getMaskElt(i + NumElemsInLane) : -1; 5760 int EltIdx = SVOp->getMaskElt(i); 5761 5762 if ((EltIdx < 0 || EltIdx == (int)i) && 5763 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane))) 5764 continue; 5765 5766 if (((unsigned)EltIdx == (i + NumElems)) && 5767 (SndLaneEltIdx < 0 || 5768 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane)) 5769 MaskValue |= (1<<i); 5770 else 5771 return SDValue(); 5772 } 5773 5774 // Convert i32 vectors to floating point if it is not AVX2. 5775 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors. 5776 MVT BlendVT = VT; 5777 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) { 5778 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()), 5779 NumElems); 5780 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1); 5781 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2); 5782 } 5783 5784 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2, 5785 DAG.getConstant(MaskValue, MVT::i32)); 5786 return DAG.getNode(ISD::BITCAST, dl, VT, Ret); 5787 } 5788 5789 // v8i16 shuffles - Prefer shuffles in the following order: 5790 // 1. [all] pshuflw, pshufhw, optional move 5791 // 2. [ssse3] 1 x pshufb 5792 // 3. [ssse3] 2 x pshufb + 1 x por 5793 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5794 static SDValue 5795 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget, 5796 SelectionDAG &DAG) { 5797 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5798 SDValue V1 = SVOp->getOperand(0); 5799 SDValue V2 = SVOp->getOperand(1); 5800 SDLoc dl(SVOp); 5801 SmallVector<int, 8> MaskVals; 5802 5803 // Determine if more than 1 of the words in each of the low and high quadwords 5804 // of the result come from the same quadword of one of the two inputs. Undef 5805 // mask values count as coming from any quadword, for better codegen. 5806 unsigned LoQuad[] = { 0, 0, 0, 0 }; 5807 unsigned HiQuad[] = { 0, 0, 0, 0 }; 5808 std::bitset<4> InputQuads; 5809 for (unsigned i = 0; i < 8; ++i) { 5810 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 5811 int EltIdx = SVOp->getMaskElt(i); 5812 MaskVals.push_back(EltIdx); 5813 if (EltIdx < 0) { 5814 ++Quad[0]; 5815 ++Quad[1]; 5816 ++Quad[2]; 5817 ++Quad[3]; 5818 continue; 5819 } 5820 ++Quad[EltIdx / 4]; 5821 InputQuads.set(EltIdx / 4); 5822 } 5823 5824 int BestLoQuad = -1; 5825 unsigned MaxQuad = 1; 5826 for (unsigned i = 0; i < 4; ++i) { 5827 if (LoQuad[i] > MaxQuad) { 5828 BestLoQuad = i; 5829 MaxQuad = LoQuad[i]; 5830 } 5831 } 5832 5833 int BestHiQuad = -1; 5834 MaxQuad = 1; 5835 for (unsigned i = 0; i < 4; ++i) { 5836 if (HiQuad[i] > MaxQuad) { 5837 BestHiQuad = i; 5838 MaxQuad = HiQuad[i]; 5839 } 5840 } 5841 5842 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5843 // of the two input vectors, shuffle them into one input vector so only a 5844 // single pshufb instruction is necessary. If There are more than 2 input 5845 // quads, disable the next transformation since it does not help SSSE3. 5846 bool V1Used = InputQuads[0] || InputQuads[1]; 5847 bool V2Used = InputQuads[2] || InputQuads[3]; 5848 if (Subtarget->hasSSSE3()) { 5849 if (InputQuads.count() == 2 && V1Used && V2Used) { 5850 BestLoQuad = InputQuads[0] ? 0 : 1; 5851 BestHiQuad = InputQuads[2] ? 2 : 3; 5852 } 5853 if (InputQuads.count() > 2) { 5854 BestLoQuad = -1; 5855 BestHiQuad = -1; 5856 } 5857 } 5858 5859 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5860 // the shuffle mask. If a quad is scored as -1, that means that it contains 5861 // words from all 4 input quadwords. 5862 SDValue NewV; 5863 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5864 int MaskV[] = { 5865 BestLoQuad < 0 ? 0 : BestLoQuad, 5866 BestHiQuad < 0 ? 1 : BestHiQuad 5867 }; 5868 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5869 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5870 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5871 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5872 5873 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5874 // source words for the shuffle, to aid later transformations. 5875 bool AllWordsInNewV = true; 5876 bool InOrder[2] = { true, true }; 5877 for (unsigned i = 0; i != 8; ++i) { 5878 int idx = MaskVals[i]; 5879 if (idx != (int)i) 5880 InOrder[i/4] = false; 5881 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5882 continue; 5883 AllWordsInNewV = false; 5884 break; 5885 } 5886 5887 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5888 if (AllWordsInNewV) { 5889 for (int i = 0; i != 8; ++i) { 5890 int idx = MaskVals[i]; 5891 if (idx < 0) 5892 continue; 5893 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5894 if ((idx != i) && idx < 4) 5895 pshufhw = false; 5896 if ((idx != i) && idx > 3) 5897 pshuflw = false; 5898 } 5899 V1 = NewV; 5900 V2Used = false; 5901 BestLoQuad = 0; 5902 BestHiQuad = 1; 5903 } 5904 5905 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5906 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5907 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5908 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5909 unsigned TargetMask = 0; 5910 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5911 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5912 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5913 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp): 5914 getShufflePSHUFLWImmediate(SVOp); 5915 V1 = NewV.getOperand(0); 5916 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5917 } 5918 } 5919 5920 // Promote splats to a larger type which usually leads to more efficient code. 5921 // FIXME: Is this true if pshufb is available? 5922 if (SVOp->isSplat()) 5923 return PromoteSplat(SVOp, DAG); 5924 5925 // If we have SSSE3, and all words of the result are from 1 input vector, 5926 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5927 // is present, fall back to case 4. 5928 if (Subtarget->hasSSSE3()) { 5929 SmallVector<SDValue,16> pshufbMask; 5930 5931 // If we have elements from both input vectors, set the high bit of the 5932 // shuffle mask element to zero out elements that come from V2 in the V1 5933 // mask, and elements that come from V1 in the V2 mask, so that the two 5934 // results can be OR'd together. 5935 bool TwoInputs = V1Used && V2Used; 5936 for (unsigned i = 0; i != 8; ++i) { 5937 int EltIdx = MaskVals[i] * 2; 5938 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx; 5939 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1; 5940 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5941 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5942 } 5943 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5944 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5945 DAG.getNode(ISD::BUILD_VECTOR, dl, 5946 MVT::v16i8, &pshufbMask[0], 16)); 5947 if (!TwoInputs) 5948 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5949 5950 // Calculate the shuffle mask for the second input, shuffle it, and 5951 // OR it with the first shuffled input. 5952 pshufbMask.clear(); 5953 for (unsigned i = 0; i != 8; ++i) { 5954 int EltIdx = MaskVals[i] * 2; 5955 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16; 5956 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15; 5957 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5958 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5959 } 5960 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5961 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5962 DAG.getNode(ISD::BUILD_VECTOR, dl, 5963 MVT::v16i8, &pshufbMask[0], 16)); 5964 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5965 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5966 } 5967 5968 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5969 // and update MaskVals with new element order. 5970 std::bitset<8> InOrder; 5971 if (BestLoQuad >= 0) { 5972 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 }; 5973 for (int i = 0; i != 4; ++i) { 5974 int idx = MaskVals[i]; 5975 if (idx < 0) { 5976 InOrder.set(i); 5977 } else if ((idx / 4) == BestLoQuad) { 5978 MaskV[i] = idx & 3; 5979 InOrder.set(i); 5980 } 5981 } 5982 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5983 &MaskV[0]); 5984 5985 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 5986 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5987 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5988 NewV.getOperand(0), 5989 getShufflePSHUFLWImmediate(SVOp), DAG); 5990 } 5991 } 5992 5993 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5994 // and update MaskVals with the new element order. 5995 if (BestHiQuad >= 0) { 5996 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 }; 5997 for (unsigned i = 4; i != 8; ++i) { 5998 int idx = MaskVals[i]; 5999 if (idx < 0) { 6000 InOrder.set(i); 6001 } else if ((idx / 4) == BestHiQuad) { 6002 MaskV[i] = (idx & 3) + 4; 6003 InOrder.set(i); 6004 } 6005 } 6006 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 6007 &MaskV[0]); 6008 6009 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 6010 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 6011 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 6012 NewV.getOperand(0), 6013 getShufflePSHUFHWImmediate(SVOp), DAG); 6014 } 6015 } 6016 6017 // In case BestHi & BestLo were both -1, which means each quadword has a word 6018 // from each of the four input quadwords, calculate the InOrder bitvector now 6019 // before falling through to the insert/extract cleanup. 6020 if (BestLoQuad == -1 && BestHiQuad == -1) { 6021 NewV = V1; 6022 for (int i = 0; i != 8; ++i) 6023 if (MaskVals[i] < 0 || MaskVals[i] == i) 6024 InOrder.set(i); 6025 } 6026 6027 // The other elements are put in the right place using pextrw and pinsrw. 6028 for (unsigned i = 0; i != 8; ++i) { 6029 if (InOrder[i]) 6030 continue; 6031 int EltIdx = MaskVals[i]; 6032 if (EltIdx < 0) 6033 continue; 6034 SDValue ExtOp = (EltIdx < 8) ? 6035 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 6036 DAG.getIntPtrConstant(EltIdx)) : 6037 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 6038 DAG.getIntPtrConstant(EltIdx - 8)); 6039 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 6040 DAG.getIntPtrConstant(i)); 6041 } 6042 return NewV; 6043 } 6044 6045 // v16i8 shuffles - Prefer shuffles in the following order: 6046 // 1. [ssse3] 1 x pshufb 6047 // 2. [ssse3] 2 x pshufb + 1 x por 6048 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 6049 static 6050 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 6051 SelectionDAG &DAG, 6052 const X86TargetLowering &TLI) { 6053 SDValue V1 = SVOp->getOperand(0); 6054 SDValue V2 = SVOp->getOperand(1); 6055 SDLoc dl(SVOp); 6056 ArrayRef<int> MaskVals = SVOp->getMask(); 6057 6058 // Promote splats to a larger type which usually leads to more efficient code. 6059 // FIXME: Is this true if pshufb is available? 6060 if (SVOp->isSplat()) 6061 return PromoteSplat(SVOp, DAG); 6062 6063 // If we have SSSE3, case 1 is generated when all result bytes come from 6064 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 6065 // present, fall back to case 3. 6066 6067 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 6068 if (TLI.getSubtarget()->hasSSSE3()) { 6069 SmallVector<SDValue,16> pshufbMask; 6070 6071 // If all result elements are from one input vector, then only translate 6072 // undef mask values to 0x80 (zero out result) in the pshufb mask. 6073 // 6074 // Otherwise, we have elements from both input vectors, and must zero out 6075 // elements that come from V2 in the first mask, and V1 in the second mask 6076 // so that we can OR them together. 6077 for (unsigned i = 0; i != 16; ++i) { 6078 int EltIdx = MaskVals[i]; 6079 if (EltIdx < 0 || EltIdx >= 16) 6080 EltIdx = 0x80; 6081 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6082 } 6083 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 6084 DAG.getNode(ISD::BUILD_VECTOR, dl, 6085 MVT::v16i8, &pshufbMask[0], 16)); 6086 6087 // As PSHUFB will zero elements with negative indices, it's safe to ignore 6088 // the 2nd operand if it's undefined or zero. 6089 if (V2.getOpcode() == ISD::UNDEF || 6090 ISD::isBuildVectorAllZeros(V2.getNode())) 6091 return V1; 6092 6093 // Calculate the shuffle mask for the second input, shuffle it, and 6094 // OR it with the first shuffled input. 6095 pshufbMask.clear(); 6096 for (unsigned i = 0; i != 16; ++i) { 6097 int EltIdx = MaskVals[i]; 6098 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16; 6099 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6100 } 6101 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 6102 DAG.getNode(ISD::BUILD_VECTOR, dl, 6103 MVT::v16i8, &pshufbMask[0], 16)); 6104 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 6105 } 6106 6107 // No SSSE3 - Calculate in place words and then fix all out of place words 6108 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 6109 // the 16 different words that comprise the two doublequadword input vectors. 6110 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 6111 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 6112 SDValue NewV = V1; 6113 for (int i = 0; i != 8; ++i) { 6114 int Elt0 = MaskVals[i*2]; 6115 int Elt1 = MaskVals[i*2+1]; 6116 6117 // This word of the result is all undef, skip it. 6118 if (Elt0 < 0 && Elt1 < 0) 6119 continue; 6120 6121 // This word of the result is already in the correct place, skip it. 6122 if ((Elt0 == i*2) && (Elt1 == i*2+1)) 6123 continue; 6124 6125 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 6126 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 6127 SDValue InsElt; 6128 6129 // If Elt0 and Elt1 are defined, are consecutive, and can be load 6130 // using a single extract together, load it and store it. 6131 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 6132 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6133 DAG.getIntPtrConstant(Elt1 / 2)); 6134 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6135 DAG.getIntPtrConstant(i)); 6136 continue; 6137 } 6138 6139 // If Elt1 is defined, extract it from the appropriate source. If the 6140 // source byte is not also odd, shift the extracted word left 8 bits 6141 // otherwise clear the bottom 8 bits if we need to do an or. 6142 if (Elt1 >= 0) { 6143 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6144 DAG.getIntPtrConstant(Elt1 / 2)); 6145 if ((Elt1 & 1) == 0) 6146 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 6147 DAG.getConstant(8, 6148 TLI.getShiftAmountTy(InsElt.getValueType()))); 6149 else if (Elt0 >= 0) 6150 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 6151 DAG.getConstant(0xFF00, MVT::i16)); 6152 } 6153 // If Elt0 is defined, extract it from the appropriate source. If the 6154 // source byte is not also even, shift the extracted word right 8 bits. If 6155 // Elt1 was also defined, OR the extracted values together before 6156 // inserting them in the result. 6157 if (Elt0 >= 0) { 6158 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 6159 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 6160 if ((Elt0 & 1) != 0) 6161 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 6162 DAG.getConstant(8, 6163 TLI.getShiftAmountTy(InsElt0.getValueType()))); 6164 else if (Elt1 >= 0) 6165 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 6166 DAG.getConstant(0x00FF, MVT::i16)); 6167 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 6168 : InsElt0; 6169 } 6170 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6171 DAG.getIntPtrConstant(i)); 6172 } 6173 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 6174 } 6175 6176 // v32i8 shuffles - Translate to VPSHUFB if possible. 6177 static 6178 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp, 6179 const X86Subtarget *Subtarget, 6180 SelectionDAG &DAG) { 6181 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6182 SDValue V1 = SVOp->getOperand(0); 6183 SDValue V2 = SVOp->getOperand(1); 6184 SDLoc dl(SVOp); 6185 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end()); 6186 6187 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6188 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode()); 6189 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode()); 6190 6191 // VPSHUFB may be generated if 6192 // (1) one of input vector is undefined or zeroinitializer. 6193 // The mask value 0x80 puts 0 in the corresponding slot of the vector. 6194 // And (2) the mask indexes don't cross the 128-bit lane. 6195 if (VT != MVT::v32i8 || !Subtarget->hasInt256() || 6196 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero)) 6197 return SDValue(); 6198 6199 if (V1IsAllZero && !V2IsAllZero) { 6200 CommuteVectorShuffleMask(MaskVals, 32); 6201 V1 = V2; 6202 } 6203 SmallVector<SDValue, 32> pshufbMask; 6204 for (unsigned i = 0; i != 32; i++) { 6205 int EltIdx = MaskVals[i]; 6206 if (EltIdx < 0 || EltIdx >= 32) 6207 EltIdx = 0x80; 6208 else { 6209 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16)) 6210 // Cross lane is not allowed. 6211 return SDValue(); 6212 EltIdx &= 0xf; 6213 } 6214 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6215 } 6216 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1, 6217 DAG.getNode(ISD::BUILD_VECTOR, dl, 6218 MVT::v32i8, &pshufbMask[0], 32)); 6219 } 6220 6221 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 6222 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 6223 /// done when every pair / quad of shuffle mask elements point to elements in 6224 /// the right sequence. e.g. 6225 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 6226 static 6227 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 6228 SelectionDAG &DAG) { 6229 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6230 SDLoc dl(SVOp); 6231 unsigned NumElems = VT.getVectorNumElements(); 6232 MVT NewVT; 6233 unsigned Scale; 6234 switch (VT.SimpleTy) { 6235 default: llvm_unreachable("Unexpected!"); 6236 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break; 6237 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break; 6238 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break; 6239 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break; 6240 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break; 6241 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break; 6242 } 6243 6244 SmallVector<int, 8> MaskVec; 6245 for (unsigned i = 0; i != NumElems; i += Scale) { 6246 int StartIdx = -1; 6247 for (unsigned j = 0; j != Scale; ++j) { 6248 int EltIdx = SVOp->getMaskElt(i+j); 6249 if (EltIdx < 0) 6250 continue; 6251 if (StartIdx < 0) 6252 StartIdx = (EltIdx / Scale); 6253 if (EltIdx != (int)(StartIdx*Scale + j)) 6254 return SDValue(); 6255 } 6256 MaskVec.push_back(StartIdx); 6257 } 6258 6259 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0)); 6260 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1)); 6261 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 6262 } 6263 6264 /// getVZextMovL - Return a zero-extending vector move low node. 6265 /// 6266 static SDValue getVZextMovL(MVT VT, EVT OpVT, 6267 SDValue SrcOp, SelectionDAG &DAG, 6268 const X86Subtarget *Subtarget, SDLoc dl) { 6269 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 6270 LoadSDNode *LD = NULL; 6271 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 6272 LD = dyn_cast<LoadSDNode>(SrcOp); 6273 if (!LD) { 6274 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 6275 // instead. 6276 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 6277 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 6278 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 6279 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 6280 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 6281 // PR2108 6282 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 6283 return DAG.getNode(ISD::BITCAST, dl, VT, 6284 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6285 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6286 OpVT, 6287 SrcOp.getOperand(0) 6288 .getOperand(0)))); 6289 } 6290 } 6291 } 6292 6293 return DAG.getNode(ISD::BITCAST, dl, VT, 6294 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6295 DAG.getNode(ISD::BITCAST, dl, 6296 OpVT, SrcOp))); 6297 } 6298 6299 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6300 /// which could not be matched by any known target speficic shuffle 6301 static SDValue 6302 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6303 6304 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG); 6305 if (NewOp.getNode()) 6306 return NewOp; 6307 6308 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6309 6310 unsigned NumElems = VT.getVectorNumElements(); 6311 unsigned NumLaneElems = NumElems / 2; 6312 6313 SDLoc dl(SVOp); 6314 MVT EltVT = VT.getVectorElementType(); 6315 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems); 6316 SDValue Output[2]; 6317 6318 SmallVector<int, 16> Mask; 6319 for (unsigned l = 0; l < 2; ++l) { 6320 // Build a shuffle mask for the output, discovering on the fly which 6321 // input vectors to use as shuffle operands (recorded in InputUsed). 6322 // If building a suitable shuffle vector proves too hard, then bail 6323 // out with UseBuildVector set. 6324 bool UseBuildVector = false; 6325 int InputUsed[2] = { -1, -1 }; // Not yet discovered. 6326 unsigned LaneStart = l * NumLaneElems; 6327 for (unsigned i = 0; i != NumLaneElems; ++i) { 6328 // The mask element. This indexes into the input. 6329 int Idx = SVOp->getMaskElt(i+LaneStart); 6330 if (Idx < 0) { 6331 // the mask element does not index into any input vector. 6332 Mask.push_back(-1); 6333 continue; 6334 } 6335 6336 // The input vector this mask element indexes into. 6337 int Input = Idx / NumLaneElems; 6338 6339 // Turn the index into an offset from the start of the input vector. 6340 Idx -= Input * NumLaneElems; 6341 6342 // Find or create a shuffle vector operand to hold this input. 6343 unsigned OpNo; 6344 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) { 6345 if (InputUsed[OpNo] == Input) 6346 // This input vector is already an operand. 6347 break; 6348 if (InputUsed[OpNo] < 0) { 6349 // Create a new operand for this input vector. 6350 InputUsed[OpNo] = Input; 6351 break; 6352 } 6353 } 6354 6355 if (OpNo >= array_lengthof(InputUsed)) { 6356 // More than two input vectors used! Give up on trying to create a 6357 // shuffle vector. Insert all elements into a BUILD_VECTOR instead. 6358 UseBuildVector = true; 6359 break; 6360 } 6361 6362 // Add the mask index for the new shuffle vector. 6363 Mask.push_back(Idx + OpNo * NumLaneElems); 6364 } 6365 6366 if (UseBuildVector) { 6367 SmallVector<SDValue, 16> SVOps; 6368 for (unsigned i = 0; i != NumLaneElems; ++i) { 6369 // The mask element. This indexes into the input. 6370 int Idx = SVOp->getMaskElt(i+LaneStart); 6371 if (Idx < 0) { 6372 SVOps.push_back(DAG.getUNDEF(EltVT)); 6373 continue; 6374 } 6375 6376 // The input vector this mask element indexes into. 6377 int Input = Idx / NumElems; 6378 6379 // Turn the index into an offset from the start of the input vector. 6380 Idx -= Input * NumElems; 6381 6382 // Extract the vector element by hand. 6383 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6384 SVOp->getOperand(Input), 6385 DAG.getIntPtrConstant(Idx))); 6386 } 6387 6388 // Construct the output using a BUILD_VECTOR. 6389 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0], 6390 SVOps.size()); 6391 } else if (InputUsed[0] < 0) { 6392 // No input vectors were used! The result is undefined. 6393 Output[l] = DAG.getUNDEF(NVT); 6394 } else { 6395 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2), 6396 (InputUsed[0] % 2) * NumLaneElems, 6397 DAG, dl); 6398 // If only one input was used, use an undefined vector for the other. 6399 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) : 6400 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2), 6401 (InputUsed[1] % 2) * NumLaneElems, DAG, dl); 6402 // At least one input vector was used. Create a new shuffle vector. 6403 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]); 6404 } 6405 6406 Mask.clear(); 6407 } 6408 6409 // Concatenate the result back 6410 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]); 6411 } 6412 6413 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6414 /// 4 elements, and match them with several different shuffle types. 6415 static SDValue 6416 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6417 SDValue V1 = SVOp->getOperand(0); 6418 SDValue V2 = SVOp->getOperand(1); 6419 SDLoc dl(SVOp); 6420 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6421 6422 assert(VT.is128BitVector() && "Unsupported vector size"); 6423 6424 std::pair<int, int> Locs[4]; 6425 int Mask1[] = { -1, -1, -1, -1 }; 6426 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end()); 6427 6428 unsigned NumHi = 0; 6429 unsigned NumLo = 0; 6430 for (unsigned i = 0; i != 4; ++i) { 6431 int Idx = PermMask[i]; 6432 if (Idx < 0) { 6433 Locs[i] = std::make_pair(-1, -1); 6434 } else { 6435 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6436 if (Idx < 4) { 6437 Locs[i] = std::make_pair(0, NumLo); 6438 Mask1[NumLo] = Idx; 6439 NumLo++; 6440 } else { 6441 Locs[i] = std::make_pair(1, NumHi); 6442 if (2+NumHi < 4) 6443 Mask1[2+NumHi] = Idx; 6444 NumHi++; 6445 } 6446 } 6447 } 6448 6449 if (NumLo <= 2 && NumHi <= 2) { 6450 // If no more than two elements come from either vector. This can be 6451 // implemented with two shuffles. First shuffle gather the elements. 6452 // The second shuffle, which takes the first shuffle as both of its 6453 // vector operands, put the elements into the right order. 6454 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6455 6456 int Mask2[] = { -1, -1, -1, -1 }; 6457 6458 for (unsigned i = 0; i != 4; ++i) 6459 if (Locs[i].first != -1) { 6460 unsigned Idx = (i < 2) ? 0 : 4; 6461 Idx += Locs[i].first * 2 + Locs[i].second; 6462 Mask2[i] = Idx; 6463 } 6464 6465 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6466 } 6467 6468 if (NumLo == 3 || NumHi == 3) { 6469 // Otherwise, we must have three elements from one vector, call it X, and 6470 // one element from the other, call it Y. First, use a shufps to build an 6471 // intermediate vector with the one element from Y and the element from X 6472 // that will be in the same half in the final destination (the indexes don't 6473 // matter). Then, use a shufps to build the final vector, taking the half 6474 // containing the element from Y from the intermediate, and the other half 6475 // from X. 6476 if (NumHi == 3) { 6477 // Normalize it so the 3 elements come from V1. 6478 CommuteVectorShuffleMask(PermMask, 4); 6479 std::swap(V1, V2); 6480 } 6481 6482 // Find the element from V2. 6483 unsigned HiIndex; 6484 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6485 int Val = PermMask[HiIndex]; 6486 if (Val < 0) 6487 continue; 6488 if (Val >= 4) 6489 break; 6490 } 6491 6492 Mask1[0] = PermMask[HiIndex]; 6493 Mask1[1] = -1; 6494 Mask1[2] = PermMask[HiIndex^1]; 6495 Mask1[3] = -1; 6496 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6497 6498 if (HiIndex >= 2) { 6499 Mask1[0] = PermMask[0]; 6500 Mask1[1] = PermMask[1]; 6501 Mask1[2] = HiIndex & 1 ? 6 : 4; 6502 Mask1[3] = HiIndex & 1 ? 4 : 6; 6503 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6504 } 6505 6506 Mask1[0] = HiIndex & 1 ? 2 : 0; 6507 Mask1[1] = HiIndex & 1 ? 0 : 2; 6508 Mask1[2] = PermMask[2]; 6509 Mask1[3] = PermMask[3]; 6510 if (Mask1[2] >= 0) 6511 Mask1[2] += 4; 6512 if (Mask1[3] >= 0) 6513 Mask1[3] += 4; 6514 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6515 } 6516 6517 // Break it into (shuffle shuffle_hi, shuffle_lo). 6518 int LoMask[] = { -1, -1, -1, -1 }; 6519 int HiMask[] = { -1, -1, -1, -1 }; 6520 6521 int *MaskPtr = LoMask; 6522 unsigned MaskIdx = 0; 6523 unsigned LoIdx = 0; 6524 unsigned HiIdx = 2; 6525 for (unsigned i = 0; i != 4; ++i) { 6526 if (i == 2) { 6527 MaskPtr = HiMask; 6528 MaskIdx = 1; 6529 LoIdx = 0; 6530 HiIdx = 2; 6531 } 6532 int Idx = PermMask[i]; 6533 if (Idx < 0) { 6534 Locs[i] = std::make_pair(-1, -1); 6535 } else if (Idx < 4) { 6536 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6537 MaskPtr[LoIdx] = Idx; 6538 LoIdx++; 6539 } else { 6540 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6541 MaskPtr[HiIdx] = Idx; 6542 HiIdx++; 6543 } 6544 } 6545 6546 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6547 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6548 int MaskOps[] = { -1, -1, -1, -1 }; 6549 for (unsigned i = 0; i != 4; ++i) 6550 if (Locs[i].first != -1) 6551 MaskOps[i] = Locs[i].first * 4 + Locs[i].second; 6552 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6553 } 6554 6555 static bool MayFoldVectorLoad(SDValue V) { 6556 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6557 V = V.getOperand(0); 6558 6559 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6560 V = V.getOperand(0); 6561 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6562 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6563 // BUILD_VECTOR (load), undef 6564 V = V.getOperand(0); 6565 6566 return MayFoldLoad(V); 6567 } 6568 6569 static 6570 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) { 6571 EVT VT = Op.getValueType(); 6572 6573 // Canonizalize to v2f64. 6574 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6575 return DAG.getNode(ISD::BITCAST, dl, VT, 6576 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6577 V1, DAG)); 6578 } 6579 6580 static 6581 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, 6582 bool HasSSE2) { 6583 SDValue V1 = Op.getOperand(0); 6584 SDValue V2 = Op.getOperand(1); 6585 EVT VT = Op.getValueType(); 6586 6587 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6588 6589 if (HasSSE2 && VT == MVT::v2f64) 6590 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6591 6592 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6593 return DAG.getNode(ISD::BITCAST, dl, VT, 6594 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6595 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6596 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6597 } 6598 6599 static 6600 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) { 6601 SDValue V1 = Op.getOperand(0); 6602 SDValue V2 = Op.getOperand(1); 6603 EVT VT = Op.getValueType(); 6604 6605 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6606 "unsupported shuffle type"); 6607 6608 if (V2.getOpcode() == ISD::UNDEF) 6609 V2 = V1; 6610 6611 // v4i32 or v4f32 6612 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6613 } 6614 6615 static 6616 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 6617 SDValue V1 = Op.getOperand(0); 6618 SDValue V2 = Op.getOperand(1); 6619 EVT VT = Op.getValueType(); 6620 unsigned NumElems = VT.getVectorNumElements(); 6621 6622 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6623 // operand of these instructions is only memory, so check if there's a 6624 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6625 // same masks. 6626 bool CanFoldLoad = false; 6627 6628 // Trivial case, when V2 comes from a load. 6629 if (MayFoldVectorLoad(V2)) 6630 CanFoldLoad = true; 6631 6632 // When V1 is a load, it can be folded later into a store in isel, example: 6633 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6634 // turns into: 6635 // (MOVLPSmr addr:$src1, VR128:$src2) 6636 // So, recognize this potential and also use MOVLPS or MOVLPD 6637 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6638 CanFoldLoad = true; 6639 6640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6641 if (CanFoldLoad) { 6642 if (HasSSE2 && NumElems == 2) 6643 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6644 6645 if (NumElems == 4) 6646 // If we don't care about the second element, proceed to use movss. 6647 if (SVOp->getMaskElt(1) != -1) 6648 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6649 } 6650 6651 // movl and movlp will both match v2i64, but v2i64 is never matched by 6652 // movl earlier because we make it strict to avoid messing with the movlp load 6653 // folding logic (see the code above getMOVLP call). Match it here then, 6654 // this is horrible, but will stay like this until we move all shuffle 6655 // matching to x86 specific nodes. Note that for the 1st condition all 6656 // types are matched with movsd. 6657 if (HasSSE2) { 6658 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6659 // as to remove this logic from here, as much as possible 6660 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT)) 6661 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6662 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6663 } 6664 6665 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6666 6667 // Invert the operand order and use SHUFPS to match it. 6668 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1, 6669 getShuffleSHUFImmediate(SVOp), DAG); 6670 } 6671 6672 // Reduce a vector shuffle to zext. 6673 SDValue 6674 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const { 6675 // PMOVZX is only available from SSE41. 6676 if (!Subtarget->hasSSE41()) 6677 return SDValue(); 6678 6679 EVT VT = Op.getValueType(); 6680 6681 // Only AVX2 support 256-bit vector integer extending. 6682 if (!Subtarget->hasInt256() && VT.is256BitVector()) 6683 return SDValue(); 6684 6685 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6686 SDLoc DL(Op); 6687 SDValue V1 = Op.getOperand(0); 6688 SDValue V2 = Op.getOperand(1); 6689 unsigned NumElems = VT.getVectorNumElements(); 6690 6691 // Extending is an unary operation and the element type of the source vector 6692 // won't be equal to or larger than i64. 6693 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() || 6694 VT.getVectorElementType() == MVT::i64) 6695 return SDValue(); 6696 6697 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4. 6698 unsigned Shift = 1; // Start from 2, i.e. 1 << 1. 6699 while ((1U << Shift) < NumElems) { 6700 if (SVOp->getMaskElt(1U << Shift) == 1) 6701 break; 6702 Shift += 1; 6703 // The maximal ratio is 8, i.e. from i8 to i64. 6704 if (Shift > 3) 6705 return SDValue(); 6706 } 6707 6708 // Check the shuffle mask. 6709 unsigned Mask = (1U << Shift) - 1; 6710 for (unsigned i = 0; i != NumElems; ++i) { 6711 int EltIdx = SVOp->getMaskElt(i); 6712 if ((i & Mask) != 0 && EltIdx != -1) 6713 return SDValue(); 6714 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift)) 6715 return SDValue(); 6716 } 6717 6718 LLVMContext *Context = DAG.getContext(); 6719 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift; 6720 EVT NeVT = EVT::getIntegerVT(*Context, NBits); 6721 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift); 6722 6723 if (!isTypeLegal(NVT)) 6724 return SDValue(); 6725 6726 // Simplify the operand as it's prepared to be fed into shuffle. 6727 unsigned SignificantBits = NVT.getSizeInBits() >> Shift; 6728 if (V1.getOpcode() == ISD::BITCAST && 6729 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 6730 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6731 V1.getOperand(0) 6732 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) { 6733 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x) 6734 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0); 6735 ConstantSDNode *CIdx = 6736 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1)); 6737 // If it's foldable, i.e. normal load with single use, we will let code 6738 // selection to fold it. Otherwise, we will short the conversion sequence. 6739 if (CIdx && CIdx->getZExtValue() == 0 && 6740 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) { 6741 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) { 6742 // The "ext_vec_elt" node is wider than the result node. 6743 // In this case we should extract subvector from V. 6744 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)). 6745 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits(); 6746 EVT FullVT = V.getValueType(); 6747 EVT SubVecVT = EVT::getVectorVT(*Context, 6748 FullVT.getVectorElementType(), 6749 FullVT.getVectorNumElements()/Ratio); 6750 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 6751 DAG.getIntPtrConstant(0)); 6752 } 6753 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V); 6754 } 6755 } 6756 6757 return DAG.getNode(ISD::BITCAST, DL, VT, 6758 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1)); 6759 } 6760 6761 SDValue 6762 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const { 6763 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6764 MVT VT = Op.getValueType().getSimpleVT(); 6765 SDLoc dl(Op); 6766 SDValue V1 = Op.getOperand(0); 6767 SDValue V2 = Op.getOperand(1); 6768 6769 if (isZeroShuffle(SVOp)) 6770 return getZeroVector(VT, Subtarget, DAG, dl); 6771 6772 // Handle splat operations 6773 if (SVOp->isSplat()) { 6774 // Use vbroadcast whenever the splat comes from a foldable load 6775 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 6776 if (Broadcast.getNode()) 6777 return Broadcast; 6778 } 6779 6780 // Check integer expanding shuffles. 6781 SDValue NewOp = LowerVectorIntExtend(Op, DAG); 6782 if (NewOp.getNode()) 6783 return NewOp; 6784 6785 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6786 // do it! 6787 if (VT == MVT::v8i16 || VT == MVT::v16i8 || 6788 VT == MVT::v16i16 || VT == MVT::v32i8) { 6789 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 6790 if (NewOp.getNode()) 6791 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6792 } else if ((VT == MVT::v4i32 || 6793 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 6794 // FIXME: Figure out a cleaner way to do this. 6795 // Try to make use of movq to zero out the top part. 6796 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6797 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 6798 if (NewOp.getNode()) { 6799 MVT NewVT = NewOp.getValueType().getSimpleVT(); 6800 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), 6801 NewVT, true, false)) 6802 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), 6803 DAG, Subtarget, dl); 6804 } 6805 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6806 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG); 6807 if (NewOp.getNode()) { 6808 MVT NewVT = NewOp.getValueType().getSimpleVT(); 6809 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT)) 6810 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), 6811 DAG, Subtarget, dl); 6812 } 6813 } 6814 } 6815 return SDValue(); 6816 } 6817 6818 SDValue 6819 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6820 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6821 SDValue V1 = Op.getOperand(0); 6822 SDValue V2 = Op.getOperand(1); 6823 MVT VT = Op.getValueType().getSimpleVT(); 6824 SDLoc dl(Op); 6825 unsigned NumElems = VT.getVectorNumElements(); 6826 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 6827 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6828 bool V1IsSplat = false; 6829 bool V2IsSplat = false; 6830 bool HasSSE2 = Subtarget->hasSSE2(); 6831 bool HasFp256 = Subtarget->hasFp256(); 6832 bool HasInt256 = Subtarget->hasInt256(); 6833 MachineFunction &MF = DAG.getMachineFunction(); 6834 bool OptForSize = MF.getFunction()->getAttributes(). 6835 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 6836 6837 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 6838 6839 if (V1IsUndef && V2IsUndef) 6840 return DAG.getUNDEF(VT); 6841 6842 assert(!V1IsUndef && "Op 1 of shuffle should not be undef"); 6843 6844 // Vector shuffle lowering takes 3 steps: 6845 // 6846 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6847 // narrowing and commutation of operands should be handled. 6848 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6849 // shuffle nodes. 6850 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6851 // so the shuffle can be broken into other shuffles and the legalizer can 6852 // try the lowering again. 6853 // 6854 // The general idea is that no vector_shuffle operation should be left to 6855 // be matched during isel, all of them must be converted to a target specific 6856 // node here. 6857 6858 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6859 // narrowing and commutation of operands should be handled. The actual code 6860 // doesn't include all of those, work in progress... 6861 SDValue NewOp = NormalizeVectorShuffle(Op, DAG); 6862 if (NewOp.getNode()) 6863 return NewOp; 6864 6865 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end()); 6866 6867 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6868 // unpckh_undef). Only use pshufd if speed is more important than size. 6869 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 6870 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6871 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 6872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6873 6874 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() && 6875 V2IsUndef && MayFoldVectorLoad(V1)) 6876 return getMOVDDup(Op, dl, V1, DAG); 6877 6878 if (isMOVHLPS_v_undef_Mask(M, VT)) 6879 return getMOVHighToLow(Op, dl, DAG); 6880 6881 // Use to match splats 6882 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef && 6883 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6884 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6885 6886 if (isPSHUFDMask(M, VT)) { 6887 // The actual implementation will match the mask in the if above and then 6888 // during isel it can match several different instructions, not only pshufd 6889 // as its name says, sad but true, emulate the behavior for now... 6890 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6891 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6892 6893 unsigned TargetMask = getShuffleSHUFImmediate(SVOp); 6894 6895 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6896 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6897 6898 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64)) 6899 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, 6900 DAG); 6901 6902 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1, 6903 TargetMask, DAG); 6904 } 6905 6906 if (isPALIGNRMask(M, VT, Subtarget)) 6907 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2, 6908 getShufflePALIGNRImmediate(SVOp), 6909 DAG); 6910 6911 // Check if this can be converted into a logical shift. 6912 bool isLeft = false; 6913 unsigned ShAmt = 0; 6914 SDValue ShVal; 6915 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6916 if (isShift && ShVal.hasOneUse()) { 6917 // If the shifted value has multiple uses, it may be cheaper to use 6918 // v_set0 + movlhps or movhlps, etc. 6919 MVT EltVT = VT.getVectorElementType(); 6920 ShAmt *= EltVT.getSizeInBits(); 6921 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6922 } 6923 6924 if (isMOVLMask(M, VT)) { 6925 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6926 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6927 if (!isMOVLPMask(M, VT)) { 6928 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6929 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6930 6931 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6932 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6933 } 6934 } 6935 6936 // FIXME: fold these into legal mask. 6937 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256)) 6938 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 6939 6940 if (isMOVHLPSMask(M, VT)) 6941 return getMOVHighToLow(Op, dl, DAG); 6942 6943 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget)) 6944 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6945 6946 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget)) 6947 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6948 6949 if (isMOVLPMask(M, VT)) 6950 return getMOVLP(Op, dl, DAG, HasSSE2); 6951 6952 if (ShouldXformToMOVHLPS(M, VT) || 6953 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT)) 6954 return CommuteVectorShuffle(SVOp, DAG); 6955 6956 if (isShift) { 6957 // No better options. Use a vshldq / vsrldq. 6958 MVT EltVT = VT.getVectorElementType(); 6959 ShAmt *= EltVT.getSizeInBits(); 6960 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6961 } 6962 6963 bool Commuted = false; 6964 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6965 // 1,1,1,1 -> v8i16 though. 6966 V1IsSplat = isSplatVector(V1.getNode()); 6967 V2IsSplat = isSplatVector(V2.getNode()); 6968 6969 // Canonicalize the splat or undef, if present, to be on the RHS. 6970 if (!V2IsUndef && V1IsSplat && !V2IsSplat) { 6971 CommuteVectorShuffleMask(M, NumElems); 6972 std::swap(V1, V2); 6973 std::swap(V1IsSplat, V2IsSplat); 6974 Commuted = true; 6975 } 6976 6977 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) { 6978 // Shuffling low element of v1 into undef, just return v1. 6979 if (V2IsUndef) 6980 return V1; 6981 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6982 // the instruction selector will not match, so get a canonical MOVL with 6983 // swapped operands to undo the commute. 6984 return getMOVL(DAG, dl, VT, V2, V1); 6985 } 6986 6987 if (isUNPCKLMask(M, VT, HasInt256)) 6988 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6989 6990 if (isUNPCKHMask(M, VT, HasInt256)) 6991 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6992 6993 if (V2IsSplat) { 6994 // Normalize mask so all entries that point to V2 points to its first 6995 // element then try to match unpck{h|l} again. If match, return a 6996 // new vector_shuffle with the corrected mask.p 6997 SmallVector<int, 8> NewMask(M.begin(), M.end()); 6998 NormalizeMask(NewMask, NumElems); 6999 if (isUNPCKLMask(NewMask, VT, HasInt256, true)) 7000 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 7001 if (isUNPCKHMask(NewMask, VT, HasInt256, true)) 7002 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 7003 } 7004 7005 if (Commuted) { 7006 // Commute is back and try unpck* again. 7007 // FIXME: this seems wrong. 7008 CommuteVectorShuffleMask(M, NumElems); 7009 std::swap(V1, V2); 7010 std::swap(V1IsSplat, V2IsSplat); 7011 Commuted = false; 7012 7013 if (isUNPCKLMask(M, VT, HasInt256)) 7014 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 7015 7016 if (isUNPCKHMask(M, VT, HasInt256)) 7017 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 7018 } 7019 7020 // Normalize the node to match x86 shuffle ops if needed 7021 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true))) 7022 return CommuteVectorShuffle(SVOp, DAG); 7023 7024 // The checks below are all present in isShuffleMaskLegal, but they are 7025 // inlined here right now to enable us to directly emit target specific 7026 // nodes, and remove one by one until they don't return Op anymore. 7027 7028 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 7029 SVOp->getSplatIndex() == 0 && V2IsUndef) { 7030 if (VT == MVT::v2f64 || VT == MVT::v2i64) 7031 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 7032 } 7033 7034 if (isPSHUFHWMask(M, VT, HasInt256)) 7035 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 7036 getShufflePSHUFHWImmediate(SVOp), 7037 DAG); 7038 7039 if (isPSHUFLWMask(M, VT, HasInt256)) 7040 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 7041 getShufflePSHUFLWImmediate(SVOp), 7042 DAG); 7043 7044 if (isSHUFPMask(M, VT, HasFp256)) 7045 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2, 7046 getShuffleSHUFImmediate(SVOp), DAG); 7047 7048 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 7049 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 7050 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 7051 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 7052 7053 //===--------------------------------------------------------------------===// 7054 // Generate target specific nodes for 128 or 256-bit shuffles only 7055 // supported in the AVX instruction set. 7056 // 7057 7058 // Handle VMOVDDUPY permutations 7059 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256)) 7060 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 7061 7062 // Handle VPERMILPS/D* permutations 7063 if (isVPERMILPMask(M, VT, HasFp256)) { 7064 if (HasInt256 && VT == MVT::v8i32) 7065 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, 7066 getShuffleSHUFImmediate(SVOp), DAG); 7067 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, 7068 getShuffleSHUFImmediate(SVOp), DAG); 7069 } 7070 7071 // Handle VPERM2F128/VPERM2I128 permutations 7072 if (isVPERM2X128Mask(M, VT, HasFp256)) 7073 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1, 7074 V2, getShuffleVPERM2X128Immediate(SVOp), DAG); 7075 7076 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG); 7077 if (BlendOp.getNode()) 7078 return BlendOp; 7079 7080 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) { 7081 SmallVector<SDValue, 8> permclMask; 7082 for (unsigned i = 0; i != 8; ++i) { 7083 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32)); 7084 } 7085 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, 7086 &permclMask[0], 8); 7087 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32 7088 return DAG.getNode(X86ISD::VPERMV, dl, VT, 7089 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1); 7090 } 7091 7092 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64)) 7093 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, 7094 getShuffleCLImmediate(SVOp), DAG); 7095 7096 //===--------------------------------------------------------------------===// 7097 // Since no target specific shuffle was selected for this generic one, 7098 // lower it into other known shuffles. FIXME: this isn't true yet, but 7099 // this is the plan. 7100 // 7101 7102 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 7103 if (VT == MVT::v8i16) { 7104 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG); 7105 if (NewOp.getNode()) 7106 return NewOp; 7107 } 7108 7109 if (VT == MVT::v16i8) { 7110 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 7111 if (NewOp.getNode()) 7112 return NewOp; 7113 } 7114 7115 if (VT == MVT::v32i8) { 7116 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG); 7117 if (NewOp.getNode()) 7118 return NewOp; 7119 } 7120 7121 // Handle all 128-bit wide vectors with 4 elements, and match them with 7122 // several different shuffle types. 7123 if (NumElems == 4 && VT.is128BitVector()) 7124 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 7125 7126 // Handle general 256-bit shuffles 7127 if (VT.is256BitVector()) 7128 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 7129 7130 return SDValue(); 7131 } 7132 7133 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) { 7134 MVT VT = Op.getValueType().getSimpleVT(); 7135 SDLoc dl(Op); 7136 7137 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector()) 7138 return SDValue(); 7139 7140 if (VT.getSizeInBits() == 8) { 7141 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 7142 Op.getOperand(0), Op.getOperand(1)); 7143 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7144 DAG.getValueType(VT)); 7145 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7146 } 7147 7148 if (VT.getSizeInBits() == 16) { 7149 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7150 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 7151 if (Idx == 0) 7152 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7153 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7154 DAG.getNode(ISD::BITCAST, dl, 7155 MVT::v4i32, 7156 Op.getOperand(0)), 7157 Op.getOperand(1))); 7158 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 7159 Op.getOperand(0), Op.getOperand(1)); 7160 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7161 DAG.getValueType(VT)); 7162 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7163 } 7164 7165 if (VT == MVT::f32) { 7166 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 7167 // the result back to FR32 register. It's only worth matching if the 7168 // result has a single use which is a store or a bitcast to i32. And in 7169 // the case of a store, it's not worth it if the index is a constant 0, 7170 // because a MOVSSmr can be used instead, which is smaller and faster. 7171 if (!Op.hasOneUse()) 7172 return SDValue(); 7173 SDNode *User = *Op.getNode()->use_begin(); 7174 if ((User->getOpcode() != ISD::STORE || 7175 (isa<ConstantSDNode>(Op.getOperand(1)) && 7176 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 7177 (User->getOpcode() != ISD::BITCAST || 7178 User->getValueType(0) != MVT::i32)) 7179 return SDValue(); 7180 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7181 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 7182 Op.getOperand(0)), 7183 Op.getOperand(1)); 7184 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 7185 } 7186 7187 if (VT == MVT::i32 || VT == MVT::i64) { 7188 // ExtractPS/pextrq works with constant index. 7189 if (isa<ConstantSDNode>(Op.getOperand(1))) 7190 return Op; 7191 } 7192 return SDValue(); 7193 } 7194 7195 SDValue 7196 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7197 SelectionDAG &DAG) const { 7198 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7199 return SDValue(); 7200 7201 SDValue Vec = Op.getOperand(0); 7202 MVT VecVT = Vec.getValueType().getSimpleVT(); 7203 7204 // If this is a 256-bit vector result, first extract the 128-bit vector and 7205 // then extract the element from the 128-bit vector. 7206 if (VecVT.is256BitVector()) { 7207 SDLoc dl(Op.getNode()); 7208 unsigned NumElems = VecVT.getVectorNumElements(); 7209 SDValue Idx = Op.getOperand(1); 7210 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7211 7212 // Get the 128-bit vector. 7213 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl); 7214 7215 if (IdxVal >= NumElems/2) 7216 IdxVal -= NumElems/2; 7217 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 7218 DAG.getConstant(IdxVal, MVT::i32)); 7219 } 7220 7221 assert(VecVT.is128BitVector() && "Unexpected vector length"); 7222 7223 if (Subtarget->hasSSE41()) { 7224 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 7225 if (Res.getNode()) 7226 return Res; 7227 } 7228 7229 MVT VT = Op.getValueType().getSimpleVT(); 7230 SDLoc dl(Op); 7231 // TODO: handle v16i8. 7232 if (VT.getSizeInBits() == 16) { 7233 SDValue Vec = Op.getOperand(0); 7234 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7235 if (Idx == 0) 7236 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7237 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7238 DAG.getNode(ISD::BITCAST, dl, 7239 MVT::v4i32, Vec), 7240 Op.getOperand(1))); 7241 // Transform it so it match pextrw which produces a 32-bit result. 7242 MVT EltVT = MVT::i32; 7243 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 7244 Op.getOperand(0), Op.getOperand(1)); 7245 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 7246 DAG.getValueType(VT)); 7247 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7248 } 7249 7250 if (VT.getSizeInBits() == 32) { 7251 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7252 if (Idx == 0) 7253 return Op; 7254 7255 // SHUFPS the element to the lowest double word, then movss. 7256 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 7257 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT(); 7258 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7259 DAG.getUNDEF(VVT), Mask); 7260 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7261 DAG.getIntPtrConstant(0)); 7262 } 7263 7264 if (VT.getSizeInBits() == 64) { 7265 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 7266 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 7267 // to match extract_elt for f64. 7268 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7269 if (Idx == 0) 7270 return Op; 7271 7272 // UNPCKHPD the element to the lowest double word, then movsd. 7273 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 7274 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 7275 int Mask[2] = { 1, -1 }; 7276 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT(); 7277 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7278 DAG.getUNDEF(VVT), Mask); 7279 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7280 DAG.getIntPtrConstant(0)); 7281 } 7282 7283 return SDValue(); 7284 } 7285 7286 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) { 7287 MVT VT = Op.getValueType().getSimpleVT(); 7288 MVT EltVT = VT.getVectorElementType(); 7289 SDLoc dl(Op); 7290 7291 SDValue N0 = Op.getOperand(0); 7292 SDValue N1 = Op.getOperand(1); 7293 SDValue N2 = Op.getOperand(2); 7294 7295 if (!VT.is128BitVector()) 7296 return SDValue(); 7297 7298 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 7299 isa<ConstantSDNode>(N2)) { 7300 unsigned Opc; 7301 if (VT == MVT::v8i16) 7302 Opc = X86ISD::PINSRW; 7303 else if (VT == MVT::v16i8) 7304 Opc = X86ISD::PINSRB; 7305 else 7306 Opc = X86ISD::PINSRB; 7307 7308 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 7309 // argument. 7310 if (N1.getValueType() != MVT::i32) 7311 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7312 if (N2.getValueType() != MVT::i32) 7313 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7314 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 7315 } 7316 7317 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 7318 // Bits [7:6] of the constant are the source select. This will always be 7319 // zero here. The DAG Combiner may combine an extract_elt index into these 7320 // bits. For example (insert (extract, 3), 2) could be matched by putting 7321 // the '3' into bits [7:6] of X86ISD::INSERTPS. 7322 // Bits [5:4] of the constant are the destination select. This is the 7323 // value of the incoming immediate. 7324 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 7325 // combine either bitwise AND or insert of float 0.0 to set these bits. 7326 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 7327 // Create this as a scalar to vector.. 7328 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7329 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7330 } 7331 7332 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) { 7333 // PINSR* works with constant index. 7334 return Op; 7335 } 7336 return SDValue(); 7337 } 7338 7339 SDValue 7340 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7341 MVT VT = Op.getValueType().getSimpleVT(); 7342 MVT EltVT = VT.getVectorElementType(); 7343 7344 SDLoc dl(Op); 7345 SDValue N0 = Op.getOperand(0); 7346 SDValue N1 = Op.getOperand(1); 7347 SDValue N2 = Op.getOperand(2); 7348 7349 // If this is a 256-bit vector result, first extract the 128-bit vector, 7350 // insert the element into the extracted half and then place it back. 7351 if (VT.is256BitVector()) { 7352 if (!isa<ConstantSDNode>(N2)) 7353 return SDValue(); 7354 7355 // Get the desired 128-bit vector half. 7356 unsigned NumElems = VT.getVectorNumElements(); 7357 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7358 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl); 7359 7360 // Insert the element into the desired half. 7361 bool Upper = IdxVal >= NumElems/2; 7362 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1, 7363 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32)); 7364 7365 // Insert the changed part back to the 256-bit vector 7366 return Insert128BitVector(N0, V, IdxVal, DAG, dl); 7367 } 7368 7369 if (Subtarget->hasSSE41()) 7370 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7371 7372 if (EltVT == MVT::i8) 7373 return SDValue(); 7374 7375 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7376 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7377 // as its second argument. 7378 if (N1.getValueType() != MVT::i32) 7379 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7380 if (N2.getValueType() != MVT::i32) 7381 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7382 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7383 } 7384 return SDValue(); 7385 } 7386 7387 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) { 7388 LLVMContext *Context = DAG.getContext(); 7389 SDLoc dl(Op); 7390 MVT OpVT = Op.getValueType().getSimpleVT(); 7391 7392 // If this is a 256-bit vector result, first insert into a 128-bit 7393 // vector and then insert into the 256-bit vector. 7394 if (!OpVT.is128BitVector()) { 7395 // Insert into a 128-bit vector. 7396 EVT VT128 = EVT::getVectorVT(*Context, 7397 OpVT.getVectorElementType(), 7398 OpVT.getVectorNumElements() / 2); 7399 7400 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7401 7402 // Insert the 128-bit vector. 7403 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl); 7404 } 7405 7406 if (OpVT == MVT::v1i64 && 7407 Op.getOperand(0).getValueType() == MVT::i64) 7408 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7409 7410 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7411 assert(OpVT.is128BitVector() && "Expected an SSE type!"); 7412 return DAG.getNode(ISD::BITCAST, dl, OpVT, 7413 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7414 } 7415 7416 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7417 // a simple subregister reference or explicit instructions to grab 7418 // upper bits of a vector. 7419 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7420 SelectionDAG &DAG) { 7421 if (Subtarget->hasFp256()) { 7422 SDLoc dl(Op.getNode()); 7423 SDValue Vec = Op.getNode()->getOperand(0); 7424 SDValue Idx = Op.getNode()->getOperand(1); 7425 7426 if (Op.getNode()->getValueType(0).is128BitVector() && 7427 Vec.getNode()->getValueType(0).is256BitVector() && 7428 isa<ConstantSDNode>(Idx)) { 7429 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7430 return Extract128BitVector(Vec, IdxVal, DAG, dl); 7431 } 7432 } 7433 return SDValue(); 7434 } 7435 7436 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7437 // simple superregister reference or explicit instructions to insert 7438 // the upper bits of a vector. 7439 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7440 SelectionDAG &DAG) { 7441 if (Subtarget->hasFp256()) { 7442 SDLoc dl(Op.getNode()); 7443 SDValue Vec = Op.getNode()->getOperand(0); 7444 SDValue SubVec = Op.getNode()->getOperand(1); 7445 SDValue Idx = Op.getNode()->getOperand(2); 7446 7447 if (Op.getNode()->getValueType(0).is256BitVector() && 7448 SubVec.getNode()->getValueType(0).is128BitVector() && 7449 isa<ConstantSDNode>(Idx)) { 7450 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7451 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl); 7452 } 7453 } 7454 return SDValue(); 7455 } 7456 7457 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7458 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7459 // one of the above mentioned nodes. It has to be wrapped because otherwise 7460 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7461 // be used to form addressing mode. These wrapped nodes will be selected 7462 // into MOV32ri. 7463 SDValue 7464 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7465 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7466 7467 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7468 // global base reg. 7469 unsigned char OpFlag = 0; 7470 unsigned WrapperKind = X86ISD::Wrapper; 7471 CodeModel::Model M = getTargetMachine().getCodeModel(); 7472 7473 if (Subtarget->isPICStyleRIPRel() && 7474 (M == CodeModel::Small || M == CodeModel::Kernel)) 7475 WrapperKind = X86ISD::WrapperRIP; 7476 else if (Subtarget->isPICStyleGOT()) 7477 OpFlag = X86II::MO_GOTOFF; 7478 else if (Subtarget->isPICStyleStubPIC()) 7479 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7480 7481 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7482 CP->getAlignment(), 7483 CP->getOffset(), OpFlag); 7484 SDLoc DL(CP); 7485 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7486 // With PIC, the address is actually $g + Offset. 7487 if (OpFlag) { 7488 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7489 DAG.getNode(X86ISD::GlobalBaseReg, 7490 SDLoc(), getPointerTy()), 7491 Result); 7492 } 7493 7494 return Result; 7495 } 7496 7497 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7498 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7499 7500 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7501 // global base reg. 7502 unsigned char OpFlag = 0; 7503 unsigned WrapperKind = X86ISD::Wrapper; 7504 CodeModel::Model M = getTargetMachine().getCodeModel(); 7505 7506 if (Subtarget->isPICStyleRIPRel() && 7507 (M == CodeModel::Small || M == CodeModel::Kernel)) 7508 WrapperKind = X86ISD::WrapperRIP; 7509 else if (Subtarget->isPICStyleGOT()) 7510 OpFlag = X86II::MO_GOTOFF; 7511 else if (Subtarget->isPICStyleStubPIC()) 7512 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7513 7514 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7515 OpFlag); 7516 SDLoc DL(JT); 7517 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7518 7519 // With PIC, the address is actually $g + Offset. 7520 if (OpFlag) 7521 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7522 DAG.getNode(X86ISD::GlobalBaseReg, 7523 SDLoc(), getPointerTy()), 7524 Result); 7525 7526 return Result; 7527 } 7528 7529 SDValue 7530 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7531 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7532 7533 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7534 // global base reg. 7535 unsigned char OpFlag = 0; 7536 unsigned WrapperKind = X86ISD::Wrapper; 7537 CodeModel::Model M = getTargetMachine().getCodeModel(); 7538 7539 if (Subtarget->isPICStyleRIPRel() && 7540 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7541 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7542 OpFlag = X86II::MO_GOTPCREL; 7543 WrapperKind = X86ISD::WrapperRIP; 7544 } else if (Subtarget->isPICStyleGOT()) { 7545 OpFlag = X86II::MO_GOT; 7546 } else if (Subtarget->isPICStyleStubPIC()) { 7547 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7548 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7549 OpFlag = X86II::MO_DARWIN_NONLAZY; 7550 } 7551 7552 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7553 7554 SDLoc DL(Op); 7555 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7556 7557 // With PIC, the address is actually $g + Offset. 7558 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7559 !Subtarget->is64Bit()) { 7560 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7561 DAG.getNode(X86ISD::GlobalBaseReg, 7562 SDLoc(), getPointerTy()), 7563 Result); 7564 } 7565 7566 // For symbols that require a load from a stub to get the address, emit the 7567 // load. 7568 if (isGlobalStubReference(OpFlag)) 7569 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7570 MachinePointerInfo::getGOT(), false, false, false, 0); 7571 7572 return Result; 7573 } 7574 7575 SDValue 7576 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7577 // Create the TargetBlockAddressAddress node. 7578 unsigned char OpFlags = 7579 Subtarget->ClassifyBlockAddressReference(); 7580 CodeModel::Model M = getTargetMachine().getCodeModel(); 7581 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7582 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset(); 7583 SDLoc dl(Op); 7584 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset, 7585 OpFlags); 7586 7587 if (Subtarget->isPICStyleRIPRel() && 7588 (M == CodeModel::Small || M == CodeModel::Kernel)) 7589 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7590 else 7591 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7592 7593 // With PIC, the address is actually $g + Offset. 7594 if (isGlobalRelativeToPICBase(OpFlags)) { 7595 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7596 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7597 Result); 7598 } 7599 7600 return Result; 7601 } 7602 7603 SDValue 7604 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl, 7605 int64_t Offset, SelectionDAG &DAG) const { 7606 // Create the TargetGlobalAddress node, folding in the constant 7607 // offset if it is legal. 7608 unsigned char OpFlags = 7609 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7610 CodeModel::Model M = getTargetMachine().getCodeModel(); 7611 SDValue Result; 7612 if (OpFlags == X86II::MO_NO_FLAG && 7613 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7614 // A direct static reference to a global. 7615 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7616 Offset = 0; 7617 } else { 7618 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7619 } 7620 7621 if (Subtarget->isPICStyleRIPRel() && 7622 (M == CodeModel::Small || M == CodeModel::Kernel)) 7623 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7624 else 7625 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7626 7627 // With PIC, the address is actually $g + Offset. 7628 if (isGlobalRelativeToPICBase(OpFlags)) { 7629 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7630 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7631 Result); 7632 } 7633 7634 // For globals that require a load from a stub to get the address, emit the 7635 // load. 7636 if (isGlobalStubReference(OpFlags)) 7637 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7638 MachinePointerInfo::getGOT(), false, false, false, 0); 7639 7640 // If there was a non-zero offset that we didn't fold, create an explicit 7641 // addition for it. 7642 if (Offset != 0) 7643 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7644 DAG.getConstant(Offset, getPointerTy())); 7645 7646 return Result; 7647 } 7648 7649 SDValue 7650 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7651 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7652 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7653 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG); 7654 } 7655 7656 static SDValue 7657 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7658 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7659 unsigned char OperandFlags, bool LocalDynamic = false) { 7660 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7662 SDLoc dl(GA); 7663 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7664 GA->getValueType(0), 7665 GA->getOffset(), 7666 OperandFlags); 7667 7668 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR 7669 : X86ISD::TLSADDR; 7670 7671 if (InFlag) { 7672 SDValue Ops[] = { Chain, TGA, *InFlag }; 7673 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops)); 7674 } else { 7675 SDValue Ops[] = { Chain, TGA }; 7676 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops)); 7677 } 7678 7679 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7680 MFI->setAdjustsStack(true); 7681 7682 SDValue Flag = Chain.getValue(1); 7683 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7684 } 7685 7686 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7687 static SDValue 7688 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7689 const EVT PtrVT) { 7690 SDValue InFlag; 7691 SDLoc dl(GA); // ? function entry point might be better 7692 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7693 DAG.getNode(X86ISD::GlobalBaseReg, 7694 SDLoc(), PtrVT), InFlag); 7695 InFlag = Chain.getValue(1); 7696 7697 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7698 } 7699 7700 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7701 static SDValue 7702 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7703 const EVT PtrVT) { 7704 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7705 X86::RAX, X86II::MO_TLSGD); 7706 } 7707 7708 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA, 7709 SelectionDAG &DAG, 7710 const EVT PtrVT, 7711 bool is64Bit) { 7712 SDLoc dl(GA); 7713 7714 // Get the start address of the TLS block for this module. 7715 X86MachineFunctionInfo* MFI = DAG.getMachineFunction() 7716 .getInfo<X86MachineFunctionInfo>(); 7717 MFI->incNumLocalDynamicTLSAccesses(); 7718 7719 SDValue Base; 7720 if (is64Bit) { 7721 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX, 7722 X86II::MO_TLSLD, /*LocalDynamic=*/true); 7723 } else { 7724 SDValue InFlag; 7725 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7726 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag); 7727 InFlag = Chain.getValue(1); 7728 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, 7729 X86II::MO_TLSLDM, /*LocalDynamic=*/true); 7730 } 7731 7732 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations 7733 // of Base. 7734 7735 // Build x@dtpoff. 7736 unsigned char OperandFlags = X86II::MO_DTPOFF; 7737 unsigned WrapperKind = X86ISD::Wrapper; 7738 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7739 GA->getValueType(0), 7740 GA->getOffset(), OperandFlags); 7741 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7742 7743 // Add x@dtpoff with the base. 7744 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base); 7745 } 7746 7747 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model. 7748 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7749 const EVT PtrVT, TLSModel::Model model, 7750 bool is64Bit, bool isPIC) { 7751 SDLoc dl(GA); 7752 7753 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7754 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7755 is64Bit ? 257 : 256)); 7756 7757 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7758 DAG.getIntPtrConstant(0), 7759 MachinePointerInfo(Ptr), 7760 false, false, false, 0); 7761 7762 unsigned char OperandFlags = 0; 7763 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7764 // initialexec. 7765 unsigned WrapperKind = X86ISD::Wrapper; 7766 if (model == TLSModel::LocalExec) { 7767 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7768 } else if (model == TLSModel::InitialExec) { 7769 if (is64Bit) { 7770 OperandFlags = X86II::MO_GOTTPOFF; 7771 WrapperKind = X86ISD::WrapperRIP; 7772 } else { 7773 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF; 7774 } 7775 } else { 7776 llvm_unreachable("Unexpected model"); 7777 } 7778 7779 // emit "addl x@ntpoff,%eax" (local exec) 7780 // or "addl x@indntpoff,%eax" (initial exec) 7781 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic) 7782 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7783 GA->getValueType(0), 7784 GA->getOffset(), OperandFlags); 7785 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7786 7787 if (model == TLSModel::InitialExec) { 7788 if (isPIC && !is64Bit) { 7789 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, 7790 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), 7791 Offset); 7792 } 7793 7794 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7795 MachinePointerInfo::getGOT(), false, false, false, 7796 0); 7797 } 7798 7799 // The address of the thread local variable is the add of the thread 7800 // pointer with the offset of the variable. 7801 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7802 } 7803 7804 SDValue 7805 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7806 7807 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7808 const GlobalValue *GV = GA->getGlobal(); 7809 7810 if (Subtarget->isTargetELF()) { 7811 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 7812 7813 switch (model) { 7814 case TLSModel::GeneralDynamic: 7815 if (Subtarget->is64Bit()) 7816 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7817 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7818 case TLSModel::LocalDynamic: 7819 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(), 7820 Subtarget->is64Bit()); 7821 case TLSModel::InitialExec: 7822 case TLSModel::LocalExec: 7823 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7824 Subtarget->is64Bit(), 7825 getTargetMachine().getRelocationModel() == Reloc::PIC_); 7826 } 7827 llvm_unreachable("Unknown TLS model."); 7828 } 7829 7830 if (Subtarget->isTargetDarwin()) { 7831 // Darwin only has one model of TLS. Lower to that. 7832 unsigned char OpFlag = 0; 7833 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7834 X86ISD::WrapperRIP : X86ISD::Wrapper; 7835 7836 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7837 // global base reg. 7838 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7839 !Subtarget->is64Bit(); 7840 if (PIC32) 7841 OpFlag = X86II::MO_TLVP_PIC_BASE; 7842 else 7843 OpFlag = X86II::MO_TLVP; 7844 SDLoc DL(Op); 7845 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7846 GA->getValueType(0), 7847 GA->getOffset(), OpFlag); 7848 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7849 7850 // With PIC32, the address is actually $g + Offset. 7851 if (PIC32) 7852 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7853 DAG.getNode(X86ISD::GlobalBaseReg, 7854 SDLoc(), getPointerTy()), 7855 Offset); 7856 7857 // Lowering the machine isd will make sure everything is in the right 7858 // location. 7859 SDValue Chain = DAG.getEntryNode(); 7860 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7861 SDValue Args[] = { Chain, Offset }; 7862 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7863 7864 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7865 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7866 MFI->setAdjustsStack(true); 7867 7868 // And our return value (tls address) is in the standard call return value 7869 // location. 7870 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7871 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 7872 Chain.getValue(1)); 7873 } 7874 7875 if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) { 7876 // Just use the implicit TLS architecture 7877 // Need to generate someting similar to: 7878 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage 7879 // ; from TEB 7880 // mov ecx, dword [rel _tls_index]: Load index (from C runtime) 7881 // mov rcx, qword [rdx+rcx*8] 7882 // mov eax, .tls$:tlsvar 7883 // [rax+rcx] contains the address 7884 // Windows 64bit: gs:0x58 7885 // Windows 32bit: fs:__tls_array 7886 7887 // If GV is an alias then use the aliasee for determining 7888 // thread-localness. 7889 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7890 GV = GA->resolveAliasedGlobal(false); 7891 SDLoc dl(GA); 7892 SDValue Chain = DAG.getEntryNode(); 7893 7894 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or 7895 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly 7896 // use its literal value of 0x2C. 7897 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit() 7898 ? Type::getInt8PtrTy(*DAG.getContext(), 7899 256) 7900 : Type::getInt32PtrTy(*DAG.getContext(), 7901 257)); 7902 7903 SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) : 7904 (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) : 7905 DAG.getExternalSymbol("_tls_array", getPointerTy())); 7906 7907 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray, 7908 MachinePointerInfo(Ptr), 7909 false, false, false, 0); 7910 7911 // Load the _tls_index variable 7912 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy()); 7913 if (Subtarget->is64Bit()) 7914 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, 7915 IDX, MachinePointerInfo(), MVT::i32, 7916 false, false, 0); 7917 else 7918 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(), 7919 false, false, false, 0); 7920 7921 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), 7922 getPointerTy()); 7923 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale); 7924 7925 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX); 7926 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(), 7927 false, false, false, 0); 7928 7929 // Get the offset of start of .tls section 7930 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7931 GA->getValueType(0), 7932 GA->getOffset(), X86II::MO_SECREL); 7933 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA); 7934 7935 // The address of the thread local variable is the add of the thread 7936 // pointer with the offset of the variable. 7937 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset); 7938 } 7939 7940 llvm_unreachable("TLS not implemented for this target."); 7941 } 7942 7943 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values 7944 /// and take a 2 x i32 value to shift plus a shift amount. 7945 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{ 7946 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7947 EVT VT = Op.getValueType(); 7948 unsigned VTBits = VT.getSizeInBits(); 7949 SDLoc dl(Op); 7950 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7951 SDValue ShOpLo = Op.getOperand(0); 7952 SDValue ShOpHi = Op.getOperand(1); 7953 SDValue ShAmt = Op.getOperand(2); 7954 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7955 DAG.getConstant(VTBits - 1, MVT::i8)) 7956 : DAG.getConstant(0, VT); 7957 7958 SDValue Tmp2, Tmp3; 7959 if (Op.getOpcode() == ISD::SHL_PARTS) { 7960 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7961 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7962 } else { 7963 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7964 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7965 } 7966 7967 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7968 DAG.getConstant(VTBits, MVT::i8)); 7969 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7970 AndNode, DAG.getConstant(0, MVT::i8)); 7971 7972 SDValue Hi, Lo; 7973 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7974 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7975 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7976 7977 if (Op.getOpcode() == ISD::SHL_PARTS) { 7978 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7979 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7980 } else { 7981 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7982 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7983 } 7984 7985 SDValue Ops[2] = { Lo, Hi }; 7986 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl); 7987 } 7988 7989 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7990 SelectionDAG &DAG) const { 7991 EVT SrcVT = Op.getOperand(0).getValueType(); 7992 7993 if (SrcVT.isVector()) 7994 return SDValue(); 7995 7996 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7997 "Unknown SINT_TO_FP to lower!"); 7998 7999 // These are really Legal; return the operand so the caller accepts it as 8000 // Legal. 8001 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 8002 return Op; 8003 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 8004 Subtarget->is64Bit()) { 8005 return Op; 8006 } 8007 8008 SDLoc dl(Op); 8009 unsigned Size = SrcVT.getSizeInBits()/8; 8010 MachineFunction &MF = DAG.getMachineFunction(); 8011 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 8012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8013 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8014 StackSlot, 8015 MachinePointerInfo::getFixedStack(SSFI), 8016 false, false, 0); 8017 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 8018 } 8019 8020 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 8021 SDValue StackSlot, 8022 SelectionDAG &DAG) const { 8023 // Build the FILD 8024 SDLoc DL(Op); 8025 SDVTList Tys; 8026 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 8027 if (useSSE) 8028 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 8029 else 8030 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 8031 8032 unsigned ByteSize = SrcVT.getSizeInBits()/8; 8033 8034 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 8035 MachineMemOperand *MMO; 8036 if (FI) { 8037 int SSFI = FI->getIndex(); 8038 MMO = 8039 DAG.getMachineFunction() 8040 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8041 MachineMemOperand::MOLoad, ByteSize, ByteSize); 8042 } else { 8043 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 8044 StackSlot = StackSlot.getOperand(1); 8045 } 8046 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 8047 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 8048 X86ISD::FILD, DL, 8049 Tys, Ops, array_lengthof(Ops), 8050 SrcVT, MMO); 8051 8052 if (useSSE) { 8053 Chain = Result.getValue(1); 8054 SDValue InFlag = Result.getValue(2); 8055 8056 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 8057 // shouldn't be necessary except that RFP cannot be live across 8058 // multiple blocks. When stackifier is fixed, they can be uncoupled. 8059 MachineFunction &MF = DAG.getMachineFunction(); 8060 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 8061 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 8062 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8063 Tys = DAG.getVTList(MVT::Other); 8064 SDValue Ops[] = { 8065 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 8066 }; 8067 MachineMemOperand *MMO = 8068 DAG.getMachineFunction() 8069 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8070 MachineMemOperand::MOStore, SSFISize, SSFISize); 8071 8072 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 8073 Ops, array_lengthof(Ops), 8074 Op.getValueType(), MMO); 8075 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 8076 MachinePointerInfo::getFixedStack(SSFI), 8077 false, false, false, 0); 8078 } 8079 8080 return Result; 8081 } 8082 8083 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 8084 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 8085 SelectionDAG &DAG) const { 8086 // This algorithm is not obvious. Here it is what we're trying to output: 8087 /* 8088 movq %rax, %xmm0 8089 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U } 8090 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 } 8091 #ifdef __SSE3__ 8092 haddpd %xmm0, %xmm0 8093 #else 8094 pshufd $0x4e, %xmm0, %xmm1 8095 addpd %xmm1, %xmm0 8096 #endif 8097 */ 8098 8099 SDLoc dl(Op); 8100 LLVMContext *Context = DAG.getContext(); 8101 8102 // Build some magic constants. 8103 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 }; 8104 Constant *C0 = ConstantDataVector::get(*Context, CV0); 8105 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 8106 8107 SmallVector<Constant*,2> CV1; 8108 CV1.push_back( 8109 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8110 APInt(64, 0x4330000000000000ULL)))); 8111 CV1.push_back( 8112 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8113 APInt(64, 0x4530000000000000ULL)))); 8114 Constant *C1 = ConstantVector::get(CV1); 8115 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 8116 8117 // Load the 64-bit value into an XMM register. 8118 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 8119 Op.getOperand(0)); 8120 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 8121 MachinePointerInfo::getConstantPool(), 8122 false, false, false, 16); 8123 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, 8124 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1), 8125 CLod0); 8126 8127 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 8128 MachinePointerInfo::getConstantPool(), 8129 false, false, false, 16); 8130 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1); 8131 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 8132 SDValue Result; 8133 8134 if (Subtarget->hasSSE3()) { 8135 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'. 8136 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub); 8137 } else { 8138 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub); 8139 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32, 8140 S2F, 0x4E, DAG); 8141 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, 8142 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle), 8143 Sub); 8144 } 8145 8146 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result, 8147 DAG.getIntPtrConstant(0)); 8148 } 8149 8150 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 8151 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 8152 SelectionDAG &DAG) const { 8153 SDLoc dl(Op); 8154 // FP constant to bias correct the final result. 8155 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 8156 MVT::f64); 8157 8158 // Load the 32-bit value into an XMM register. 8159 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 8160 Op.getOperand(0)); 8161 8162 // Zero out the upper parts of the register. 8163 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG); 8164 8165 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8166 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 8167 DAG.getIntPtrConstant(0)); 8168 8169 // Or the load with the bias. 8170 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 8171 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8172 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8173 MVT::v2f64, Load)), 8174 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8175 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8176 MVT::v2f64, Bias))); 8177 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8178 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 8179 DAG.getIntPtrConstant(0)); 8180 8181 // Subtract the bias. 8182 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 8183 8184 // Handle final rounding. 8185 EVT DestVT = Op.getValueType(); 8186 8187 if (DestVT.bitsLT(MVT::f64)) 8188 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 8189 DAG.getIntPtrConstant(0)); 8190 if (DestVT.bitsGT(MVT::f64)) 8191 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 8192 8193 // Handle final rounding. 8194 return Sub; 8195 } 8196 8197 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op, 8198 SelectionDAG &DAG) const { 8199 SDValue N0 = Op.getOperand(0); 8200 EVT SVT = N0.getValueType(); 8201 SDLoc dl(Op); 8202 8203 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 || 8204 SVT == MVT::v8i8 || SVT == MVT::v8i16) && 8205 "Custom UINT_TO_FP is not supported!"); 8206 8207 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 8208 SVT.getVectorNumElements()); 8209 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), 8210 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0)); 8211 } 8212 8213 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 8214 SelectionDAG &DAG) const { 8215 SDValue N0 = Op.getOperand(0); 8216 SDLoc dl(Op); 8217 8218 if (Op.getValueType().isVector()) 8219 return lowerUINT_TO_FP_vec(Op, DAG); 8220 8221 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 8222 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 8223 // the optimization here. 8224 if (DAG.SignBitIsZero(N0)) 8225 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 8226 8227 EVT SrcVT = N0.getValueType(); 8228 EVT DstVT = Op.getValueType(); 8229 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 8230 return LowerUINT_TO_FP_i64(Op, DAG); 8231 if (SrcVT == MVT::i32 && X86ScalarSSEf64) 8232 return LowerUINT_TO_FP_i32(Op, DAG); 8233 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32) 8234 return SDValue(); 8235 8236 // Make a 64-bit buffer, and use it to build an FILD. 8237 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 8238 if (SrcVT == MVT::i32) { 8239 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 8240 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 8241 getPointerTy(), StackSlot, WordOff); 8242 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8243 StackSlot, MachinePointerInfo(), 8244 false, false, 0); 8245 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 8246 OffsetSlot, MachinePointerInfo(), 8247 false, false, 0); 8248 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 8249 return Fild; 8250 } 8251 8252 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 8253 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8254 StackSlot, MachinePointerInfo(), 8255 false, false, 0); 8256 // For i64 source, we need to add the appropriate power of 2 if the input 8257 // was negative. This is the same as the optimization in 8258 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 8259 // we must be careful to do the computation in x87 extended precision, not 8260 // in SSE. (The generic code can't know it's OK to do this, or how to.) 8261 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 8262 MachineMemOperand *MMO = 8263 DAG.getMachineFunction() 8264 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8265 MachineMemOperand::MOLoad, 8, 8); 8266 8267 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 8268 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 8269 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 8270 array_lengthof(Ops), MVT::i64, MMO); 8271 8272 APInt FF(32, 0x5F800000ULL); 8273 8274 // Check whether the sign bit is set. 8275 SDValue SignSet = DAG.getSetCC(dl, 8276 getSetCCResultType(*DAG.getContext(), MVT::i64), 8277 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 8278 ISD::SETLT); 8279 8280 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 8281 SDValue FudgePtr = DAG.getConstantPool( 8282 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 8283 getPointerTy()); 8284 8285 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 8286 SDValue Zero = DAG.getIntPtrConstant(0); 8287 SDValue Four = DAG.getIntPtrConstant(4); 8288 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 8289 Zero, Four); 8290 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 8291 8292 // Load the value out, extending it from f32 to f80. 8293 // FIXME: Avoid the extend by constructing the right constant pool? 8294 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 8295 FudgePtr, MachinePointerInfo::getConstantPool(), 8296 MVT::f32, false, false, 4); 8297 // Extend everything to 80 bits to force it to be done on x87. 8298 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 8299 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 8300 } 8301 8302 std::pair<SDValue,SDValue> 8303 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, 8304 bool IsSigned, bool IsReplace) const { 8305 SDLoc DL(Op); 8306 8307 EVT DstTy = Op.getValueType(); 8308 8309 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) { 8310 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 8311 DstTy = MVT::i64; 8312 } 8313 8314 assert(DstTy.getSimpleVT() <= MVT::i64 && 8315 DstTy.getSimpleVT() >= MVT::i16 && 8316 "Unknown FP_TO_INT to lower!"); 8317 8318 // These are really Legal. 8319 if (DstTy == MVT::i32 && 8320 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8321 return std::make_pair(SDValue(), SDValue()); 8322 if (Subtarget->is64Bit() && 8323 DstTy == MVT::i64 && 8324 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8325 return std::make_pair(SDValue(), SDValue()); 8326 8327 // We lower FP->int64 either into FISTP64 followed by a load from a temporary 8328 // stack slot, or into the FTOL runtime function. 8329 MachineFunction &MF = DAG.getMachineFunction(); 8330 unsigned MemSize = DstTy.getSizeInBits()/8; 8331 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8332 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8333 8334 unsigned Opc; 8335 if (!IsSigned && isIntegerTypeFTOL(DstTy)) 8336 Opc = X86ISD::WIN_FTOL; 8337 else 8338 switch (DstTy.getSimpleVT().SimpleTy) { 8339 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 8340 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 8341 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 8342 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 8343 } 8344 8345 SDValue Chain = DAG.getEntryNode(); 8346 SDValue Value = Op.getOperand(0); 8347 EVT TheVT = Op.getOperand(0).getValueType(); 8348 // FIXME This causes a redundant load/store if the SSE-class value is already 8349 // in memory, such as if it is on the callstack. 8350 if (isScalarFPTypeInSSEReg(TheVT)) { 8351 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 8352 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 8353 MachinePointerInfo::getFixedStack(SSFI), 8354 false, false, 0); 8355 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 8356 SDValue Ops[] = { 8357 Chain, StackSlot, DAG.getValueType(TheVT) 8358 }; 8359 8360 MachineMemOperand *MMO = 8361 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8362 MachineMemOperand::MOLoad, MemSize, MemSize); 8363 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 8364 array_lengthof(Ops), DstTy, MMO); 8365 Chain = Value.getValue(1); 8366 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8367 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8368 } 8369 8370 MachineMemOperand *MMO = 8371 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8372 MachineMemOperand::MOStore, MemSize, MemSize); 8373 8374 if (Opc != X86ISD::WIN_FTOL) { 8375 // Build the FP_TO_INT*_IN_MEM 8376 SDValue Ops[] = { Chain, Value, StackSlot }; 8377 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8378 Ops, array_lengthof(Ops), DstTy, 8379 MMO); 8380 return std::make_pair(FIST, StackSlot); 8381 } else { 8382 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL, 8383 DAG.getVTList(MVT::Other, MVT::Glue), 8384 Chain, Value); 8385 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX, 8386 MVT::i32, ftol.getValue(1)); 8387 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX, 8388 MVT::i32, eax.getValue(2)); 8389 SDValue Ops[] = { eax, edx }; 8390 SDValue pair = IsReplace 8391 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops)) 8392 : DAG.getMergeValues(Ops, array_lengthof(Ops), DL); 8393 return std::make_pair(pair, SDValue()); 8394 } 8395 } 8396 8397 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG, 8398 const X86Subtarget *Subtarget) { 8399 MVT VT = Op->getValueType(0).getSimpleVT(); 8400 SDValue In = Op->getOperand(0); 8401 MVT InVT = In.getValueType().getSimpleVT(); 8402 SDLoc dl(Op); 8403 8404 // Optimize vectors in AVX mode: 8405 // 8406 // v8i16 -> v8i32 8407 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32. 8408 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32. 8409 // Concat upper and lower parts. 8410 // 8411 // v4i32 -> v4i64 8412 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64. 8413 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64. 8414 // Concat upper and lower parts. 8415 // 8416 8417 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) && 8418 ((VT != MVT::v4i64) || (InVT != MVT::v4i32))) 8419 return SDValue(); 8420 8421 if (Subtarget->hasInt256()) 8422 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In); 8423 8424 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl); 8425 SDValue Undef = DAG.getUNDEF(InVT); 8426 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND; 8427 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8428 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8429 8430 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(), 8431 VT.getVectorNumElements()/2); 8432 8433 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo); 8434 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi); 8435 8436 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 8437 } 8438 8439 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op, 8440 SelectionDAG &DAG) const { 8441 if (Subtarget->hasFp256()) { 8442 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8443 if (Res.getNode()) 8444 return Res; 8445 } 8446 8447 return SDValue(); 8448 } 8449 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op, 8450 SelectionDAG &DAG) const { 8451 SDLoc DL(Op); 8452 MVT VT = Op.getValueType().getSimpleVT(); 8453 SDValue In = Op.getOperand(0); 8454 MVT SVT = In.getValueType().getSimpleVT(); 8455 8456 if (Subtarget->hasFp256()) { 8457 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8458 if (Res.getNode()) 8459 return Res; 8460 } 8461 8462 if (!VT.is256BitVector() || !SVT.is128BitVector() || 8463 VT.getVectorNumElements() != SVT.getVectorNumElements()) 8464 return SDValue(); 8465 8466 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!"); 8467 8468 // AVX2 has better support of integer extending. 8469 if (Subtarget->hasInt256()) 8470 return DAG.getNode(X86ISD::VZEXT, DL, VT, In); 8471 8472 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In); 8473 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1}; 8474 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, 8475 DAG.getVectorShuffle(MVT::v8i16, DL, In, 8476 DAG.getUNDEF(MVT::v8i16), 8477 &Mask[0])); 8478 8479 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi); 8480 } 8481 8482 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 8483 SDLoc DL(Op); 8484 MVT VT = Op.getValueType().getSimpleVT(); 8485 SDValue In = Op.getOperand(0); 8486 MVT SVT = In.getValueType().getSimpleVT(); 8487 8488 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) { 8489 // On AVX2, v4i64 -> v4i32 becomes VPERMD. 8490 if (Subtarget->hasInt256()) { 8491 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1}; 8492 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In); 8493 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32), 8494 ShufMask); 8495 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In, 8496 DAG.getIntPtrConstant(0)); 8497 } 8498 8499 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS. 8500 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8501 DAG.getIntPtrConstant(0)); 8502 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8503 DAG.getIntPtrConstant(2)); 8504 8505 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8506 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8507 8508 // The PSHUFD mask: 8509 static const int ShufMask1[] = {0, 2, 0, 0}; 8510 SDValue Undef = DAG.getUNDEF(VT); 8511 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1); 8512 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1); 8513 8514 // The MOVLHPS mask: 8515 static const int ShufMask2[] = {0, 1, 4, 5}; 8516 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2); 8517 } 8518 8519 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) { 8520 // On AVX2, v8i32 -> v8i16 becomed PSHUFB. 8521 if (Subtarget->hasInt256()) { 8522 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In); 8523 8524 SmallVector<SDValue,32> pshufbMask; 8525 for (unsigned i = 0; i < 2; ++i) { 8526 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8)); 8527 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8)); 8528 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8)); 8529 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8)); 8530 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8)); 8531 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8)); 8532 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8)); 8533 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8)); 8534 for (unsigned j = 0; j < 8; ++j) 8535 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 8536 } 8537 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, 8538 &pshufbMask[0], 32); 8539 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV); 8540 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In); 8541 8542 static const int ShufMask[] = {0, 2, -1, -1}; 8543 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64), 8544 &ShufMask[0]); 8545 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8546 DAG.getIntPtrConstant(0)); 8547 return DAG.getNode(ISD::BITCAST, DL, VT, In); 8548 } 8549 8550 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8551 DAG.getIntPtrConstant(0)); 8552 8553 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8554 DAG.getIntPtrConstant(4)); 8555 8556 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo); 8557 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi); 8558 8559 // The PSHUFB mask: 8560 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13, 8561 -1, -1, -1, -1, -1, -1, -1, -1}; 8562 8563 SDValue Undef = DAG.getUNDEF(MVT::v16i8); 8564 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1); 8565 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1); 8566 8567 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8568 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8569 8570 // The MOVLHPS Mask: 8571 static const int ShufMask2[] = {0, 1, 4, 5}; 8572 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2); 8573 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res); 8574 } 8575 8576 // Handle truncation of V256 to V128 using shuffles. 8577 if (!VT.is128BitVector() || !SVT.is256BitVector()) 8578 return SDValue(); 8579 8580 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() && 8581 "Invalid op"); 8582 assert(Subtarget->hasFp256() && "256-bit vector without AVX!"); 8583 8584 unsigned NumElems = VT.getVectorNumElements(); 8585 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8586 NumElems * 2); 8587 8588 SmallVector<int, 16> MaskVec(NumElems * 2, -1); 8589 // Prepare truncation shuffle mask 8590 for (unsigned i = 0; i != NumElems; ++i) 8591 MaskVec[i] = i * 2; 8592 SDValue V = DAG.getVectorShuffle(NVT, DL, 8593 DAG.getNode(ISD::BITCAST, DL, NVT, In), 8594 DAG.getUNDEF(NVT), &MaskVec[0]); 8595 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, 8596 DAG.getIntPtrConstant(0)); 8597 } 8598 8599 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8600 SelectionDAG &DAG) const { 8601 MVT VT = Op.getValueType().getSimpleVT(); 8602 if (VT.isVector()) { 8603 if (VT == MVT::v8i16) 8604 return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT, 8605 DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op), 8606 MVT::v8i32, Op.getOperand(0))); 8607 return SDValue(); 8608 } 8609 8610 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8611 /*IsSigned=*/ true, /*IsReplace=*/ false); 8612 SDValue FIST = Vals.first, StackSlot = Vals.second; 8613 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8614 if (FIST.getNode() == 0) return Op; 8615 8616 if (StackSlot.getNode()) 8617 // Load the result. 8618 return DAG.getLoad(Op.getValueType(), SDLoc(Op), 8619 FIST, StackSlot, MachinePointerInfo(), 8620 false, false, false, 0); 8621 8622 // The node is the result. 8623 return FIST; 8624 } 8625 8626 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8627 SelectionDAG &DAG) const { 8628 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8629 /*IsSigned=*/ false, /*IsReplace=*/ false); 8630 SDValue FIST = Vals.first, StackSlot = Vals.second; 8631 assert(FIST.getNode() && "Unexpected failure"); 8632 8633 if (StackSlot.getNode()) 8634 // Load the result. 8635 return DAG.getLoad(Op.getValueType(), SDLoc(Op), 8636 FIST, StackSlot, MachinePointerInfo(), 8637 false, false, false, 0); 8638 8639 // The node is the result. 8640 return FIST; 8641 } 8642 8643 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) { 8644 SDLoc DL(Op); 8645 MVT VT = Op.getValueType().getSimpleVT(); 8646 SDValue In = Op.getOperand(0); 8647 MVT SVT = In.getValueType().getSimpleVT(); 8648 8649 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!"); 8650 8651 return DAG.getNode(X86ISD::VFPEXT, DL, VT, 8652 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, 8653 In, DAG.getUNDEF(SVT))); 8654 } 8655 8656 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const { 8657 LLVMContext *Context = DAG.getContext(); 8658 SDLoc dl(Op); 8659 MVT VT = Op.getValueType().getSimpleVT(); 8660 MVT EltVT = VT; 8661 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 8662 if (VT.isVector()) { 8663 EltVT = VT.getVectorElementType(); 8664 NumElts = VT.getVectorNumElements(); 8665 } 8666 Constant *C; 8667 if (EltVT == MVT::f64) 8668 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8669 APInt(64, ~(1ULL << 63)))); 8670 else 8671 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle, 8672 APInt(32, ~(1U << 31)))); 8673 C = ConstantVector::getSplat(NumElts, C); 8674 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 8675 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8676 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8677 MachinePointerInfo::getConstantPool(), 8678 false, false, false, Alignment); 8679 if (VT.isVector()) { 8680 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8681 return DAG.getNode(ISD::BITCAST, dl, VT, 8682 DAG.getNode(ISD::AND, dl, ANDVT, 8683 DAG.getNode(ISD::BITCAST, dl, ANDVT, 8684 Op.getOperand(0)), 8685 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask))); 8686 } 8687 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 8688 } 8689 8690 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 8691 LLVMContext *Context = DAG.getContext(); 8692 SDLoc dl(Op); 8693 MVT VT = Op.getValueType().getSimpleVT(); 8694 MVT EltVT = VT; 8695 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 8696 if (VT.isVector()) { 8697 EltVT = VT.getVectorElementType(); 8698 NumElts = VT.getVectorNumElements(); 8699 } 8700 Constant *C; 8701 if (EltVT == MVT::f64) 8702 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble, 8703 APInt(64, 1ULL << 63))); 8704 else 8705 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle, 8706 APInt(32, 1U << 31))); 8707 C = ConstantVector::getSplat(NumElts, C); 8708 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 8709 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8710 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8711 MachinePointerInfo::getConstantPool(), 8712 false, false, false, Alignment); 8713 if (VT.isVector()) { 8714 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8715 return DAG.getNode(ISD::BITCAST, dl, VT, 8716 DAG.getNode(ISD::XOR, dl, XORVT, 8717 DAG.getNode(ISD::BITCAST, dl, XORVT, 8718 Op.getOperand(0)), 8719 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask))); 8720 } 8721 8722 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8723 } 8724 8725 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8726 LLVMContext *Context = DAG.getContext(); 8727 SDValue Op0 = Op.getOperand(0); 8728 SDValue Op1 = Op.getOperand(1); 8729 SDLoc dl(Op); 8730 MVT VT = Op.getValueType().getSimpleVT(); 8731 MVT SrcVT = Op1.getValueType().getSimpleVT(); 8732 8733 // If second operand is smaller, extend it first. 8734 if (SrcVT.bitsLT(VT)) { 8735 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8736 SrcVT = VT; 8737 } 8738 // And if it is bigger, shrink it first. 8739 if (SrcVT.bitsGT(VT)) { 8740 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8741 SrcVT = VT; 8742 } 8743 8744 // At this point the operands and the result should have the same 8745 // type, and that won't be f80 since that is not custom lowered. 8746 8747 // First get the sign bit of second operand. 8748 SmallVector<Constant*,4> CV; 8749 if (SrcVT == MVT::f64) { 8750 const fltSemantics &Sem = APFloat::IEEEdouble; 8751 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63)))); 8752 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0)))); 8753 } else { 8754 const fltSemantics &Sem = APFloat::IEEEsingle; 8755 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31)))); 8756 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8757 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8758 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8759 } 8760 Constant *C = ConstantVector::get(CV); 8761 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8762 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8763 MachinePointerInfo::getConstantPool(), 8764 false, false, false, 16); 8765 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8766 8767 // Shift sign bit right or left if the two operands have different types. 8768 if (SrcVT.bitsGT(VT)) { 8769 // Op0 is MVT::f32, Op1 is MVT::f64. 8770 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8771 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8772 DAG.getConstant(32, MVT::i32)); 8773 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8774 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8775 DAG.getIntPtrConstant(0)); 8776 } 8777 8778 // Clear first operand sign bit. 8779 CV.clear(); 8780 if (VT == MVT::f64) { 8781 const fltSemantics &Sem = APFloat::IEEEdouble; 8782 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, 8783 APInt(64, ~(1ULL << 63))))); 8784 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0)))); 8785 } else { 8786 const fltSemantics &Sem = APFloat::IEEEsingle; 8787 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, 8788 APInt(32, ~(1U << 31))))); 8789 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8790 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8791 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0)))); 8792 } 8793 C = ConstantVector::get(CV); 8794 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8795 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8796 MachinePointerInfo::getConstantPool(), 8797 false, false, false, 16); 8798 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8799 8800 // Or the value with the sign bit. 8801 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8802 } 8803 8804 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) { 8805 SDValue N0 = Op.getOperand(0); 8806 SDLoc dl(Op); 8807 MVT VT = Op.getValueType().getSimpleVT(); 8808 8809 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8810 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8811 DAG.getConstant(1, VT)); 8812 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8813 } 8814 8815 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able. 8816 // 8817 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, 8818 SelectionDAG &DAG) const { 8819 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree."); 8820 8821 if (!Subtarget->hasSSE41()) 8822 return SDValue(); 8823 8824 if (!Op->hasOneUse()) 8825 return SDValue(); 8826 8827 SDNode *N = Op.getNode(); 8828 SDLoc DL(N); 8829 8830 SmallVector<SDValue, 8> Opnds; 8831 DenseMap<SDValue, unsigned> VecInMap; 8832 EVT VT = MVT::Other; 8833 8834 // Recognize a special case where a vector is casted into wide integer to 8835 // test all 0s. 8836 Opnds.push_back(N->getOperand(0)); 8837 Opnds.push_back(N->getOperand(1)); 8838 8839 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) { 8840 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot; 8841 // BFS traverse all OR'd operands. 8842 if (I->getOpcode() == ISD::OR) { 8843 Opnds.push_back(I->getOperand(0)); 8844 Opnds.push_back(I->getOperand(1)); 8845 // Re-evaluate the number of nodes to be traversed. 8846 e += 2; // 2 more nodes (LHS and RHS) are pushed. 8847 continue; 8848 } 8849 8850 // Quit if a non-EXTRACT_VECTOR_ELT 8851 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8852 return SDValue(); 8853 8854 // Quit if without a constant index. 8855 SDValue Idx = I->getOperand(1); 8856 if (!isa<ConstantSDNode>(Idx)) 8857 return SDValue(); 8858 8859 SDValue ExtractedFromVec = I->getOperand(0); 8860 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec); 8861 if (M == VecInMap.end()) { 8862 VT = ExtractedFromVec.getValueType(); 8863 // Quit if not 128/256-bit vector. 8864 if (!VT.is128BitVector() && !VT.is256BitVector()) 8865 return SDValue(); 8866 // Quit if not the same type. 8867 if (VecInMap.begin() != VecInMap.end() && 8868 VT != VecInMap.begin()->first.getValueType()) 8869 return SDValue(); 8870 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first; 8871 } 8872 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue(); 8873 } 8874 8875 assert((VT.is128BitVector() || VT.is256BitVector()) && 8876 "Not extracted from 128-/256-bit vector."); 8877 8878 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U; 8879 SmallVector<SDValue, 8> VecIns; 8880 8881 for (DenseMap<SDValue, unsigned>::const_iterator 8882 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) { 8883 // Quit if not all elements are used. 8884 if (I->second != FullMask) 8885 return SDValue(); 8886 VecIns.push_back(I->first); 8887 } 8888 8889 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8890 8891 // Cast all vectors into TestVT for PTEST. 8892 for (unsigned i = 0, e = VecIns.size(); i < e; ++i) 8893 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]); 8894 8895 // If more than one full vectors are evaluated, OR them first before PTEST. 8896 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) { 8897 // Each iteration will OR 2 nodes and append the result until there is only 8898 // 1 node left, i.e. the final OR'd value of all vectors. 8899 SDValue LHS = VecIns[Slot]; 8900 SDValue RHS = VecIns[Slot + 1]; 8901 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS)); 8902 } 8903 8904 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, 8905 VecIns.back(), VecIns.back()); 8906 } 8907 8908 /// Emit nodes that will be selected as "test Op0,Op0", or something 8909 /// equivalent. 8910 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8911 SelectionDAG &DAG) const { 8912 SDLoc dl(Op); 8913 8914 // CF and OF aren't always set the way we want. Determine which 8915 // of these we need. 8916 bool NeedCF = false; 8917 bool NeedOF = false; 8918 switch (X86CC) { 8919 default: break; 8920 case X86::COND_A: case X86::COND_AE: 8921 case X86::COND_B: case X86::COND_BE: 8922 NeedCF = true; 8923 break; 8924 case X86::COND_G: case X86::COND_GE: 8925 case X86::COND_L: case X86::COND_LE: 8926 case X86::COND_O: case X86::COND_NO: 8927 NeedOF = true; 8928 break; 8929 } 8930 8931 // See if we can use the EFLAGS value from the operand instead of 8932 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8933 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8934 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8935 // Emit a CMP with 0, which is the TEST pattern. 8936 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8937 DAG.getConstant(0, Op.getValueType())); 8938 8939 unsigned Opcode = 0; 8940 unsigned NumOperands = 0; 8941 8942 // Truncate operations may prevent the merge of the SETCC instruction 8943 // and the arithmetic intruction before it. Attempt to truncate the operands 8944 // of the arithmetic instruction and use a reduced bit-width instruction. 8945 bool NeedTruncation = false; 8946 SDValue ArithOp = Op; 8947 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) { 8948 SDValue Arith = Op->getOperand(0); 8949 // Both the trunc and the arithmetic op need to have one user each. 8950 if (Arith->hasOneUse()) 8951 switch (Arith.getOpcode()) { 8952 default: break; 8953 case ISD::ADD: 8954 case ISD::SUB: 8955 case ISD::AND: 8956 case ISD::OR: 8957 case ISD::XOR: { 8958 NeedTruncation = true; 8959 ArithOp = Arith; 8960 } 8961 } 8962 } 8963 8964 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation 8965 // which may be the result of a CAST. We use the variable 'Op', which is the 8966 // non-casted variable when we check for possible users. 8967 switch (ArithOp.getOpcode()) { 8968 case ISD::ADD: 8969 // Due to an isel shortcoming, be conservative if this add is likely to be 8970 // selected as part of a load-modify-store instruction. When the root node 8971 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8972 // uses of other nodes in the match, such as the ADD in this case. This 8973 // leads to the ADD being left around and reselected, with the result being 8974 // two adds in the output. Alas, even if none our users are stores, that 8975 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8976 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8977 // climbing the DAG back to the root, and it doesn't seem to be worth the 8978 // effort. 8979 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8980 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8981 if (UI->getOpcode() != ISD::CopyToReg && 8982 UI->getOpcode() != ISD::SETCC && 8983 UI->getOpcode() != ISD::STORE) 8984 goto default_case; 8985 8986 if (ConstantSDNode *C = 8987 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) { 8988 // An add of one will be selected as an INC. 8989 if (C->getAPIntValue() == 1) { 8990 Opcode = X86ISD::INC; 8991 NumOperands = 1; 8992 break; 8993 } 8994 8995 // An add of negative one (subtract of one) will be selected as a DEC. 8996 if (C->getAPIntValue().isAllOnesValue()) { 8997 Opcode = X86ISD::DEC; 8998 NumOperands = 1; 8999 break; 9000 } 9001 } 9002 9003 // Otherwise use a regular EFLAGS-setting add. 9004 Opcode = X86ISD::ADD; 9005 NumOperands = 2; 9006 break; 9007 case ISD::AND: { 9008 // If the primary and result isn't used, don't bother using X86ISD::AND, 9009 // because a TEST instruction will be better. 9010 bool NonFlagUse = false; 9011 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 9012 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 9013 SDNode *User = *UI; 9014 unsigned UOpNo = UI.getOperandNo(); 9015 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 9016 // Look pass truncate. 9017 UOpNo = User->use_begin().getOperandNo(); 9018 User = *User->use_begin(); 9019 } 9020 9021 if (User->getOpcode() != ISD::BRCOND && 9022 User->getOpcode() != ISD::SETCC && 9023 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) { 9024 NonFlagUse = true; 9025 break; 9026 } 9027 } 9028 9029 if (!NonFlagUse) 9030 break; 9031 } 9032 // FALL THROUGH 9033 case ISD::SUB: 9034 case ISD::OR: 9035 case ISD::XOR: 9036 // Due to the ISEL shortcoming noted above, be conservative if this op is 9037 // likely to be selected as part of a load-modify-store instruction. 9038 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 9039 UE = Op.getNode()->use_end(); UI != UE; ++UI) 9040 if (UI->getOpcode() == ISD::STORE) 9041 goto default_case; 9042 9043 // Otherwise use a regular EFLAGS-setting instruction. 9044 switch (ArithOp.getOpcode()) { 9045 default: llvm_unreachable("unexpected operator!"); 9046 case ISD::SUB: Opcode = X86ISD::SUB; break; 9047 case ISD::XOR: Opcode = X86ISD::XOR; break; 9048 case ISD::AND: Opcode = X86ISD::AND; break; 9049 case ISD::OR: { 9050 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) { 9051 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG); 9052 if (EFLAGS.getNode()) 9053 return EFLAGS; 9054 } 9055 Opcode = X86ISD::OR; 9056 break; 9057 } 9058 } 9059 9060 NumOperands = 2; 9061 break; 9062 case X86ISD::ADD: 9063 case X86ISD::SUB: 9064 case X86ISD::INC: 9065 case X86ISD::DEC: 9066 case X86ISD::OR: 9067 case X86ISD::XOR: 9068 case X86ISD::AND: 9069 return SDValue(Op.getNode(), 1); 9070 default: 9071 default_case: 9072 break; 9073 } 9074 9075 // If we found that truncation is beneficial, perform the truncation and 9076 // update 'Op'. 9077 if (NeedTruncation) { 9078 EVT VT = Op.getValueType(); 9079 SDValue WideVal = Op->getOperand(0); 9080 EVT WideVT = WideVal.getValueType(); 9081 unsigned ConvertedOp = 0; 9082 // Use a target machine opcode to prevent further DAGCombine 9083 // optimizations that may separate the arithmetic operations 9084 // from the setcc node. 9085 switch (WideVal.getOpcode()) { 9086 default: break; 9087 case ISD::ADD: ConvertedOp = X86ISD::ADD; break; 9088 case ISD::SUB: ConvertedOp = X86ISD::SUB; break; 9089 case ISD::AND: ConvertedOp = X86ISD::AND; break; 9090 case ISD::OR: ConvertedOp = X86ISD::OR; break; 9091 case ISD::XOR: ConvertedOp = X86ISD::XOR; break; 9092 } 9093 9094 if (ConvertedOp) { 9095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9096 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) { 9097 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0)); 9098 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1)); 9099 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1); 9100 } 9101 } 9102 } 9103 9104 if (Opcode == 0) 9105 // Emit a CMP with 0, which is the TEST pattern. 9106 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 9107 DAG.getConstant(0, Op.getValueType())); 9108 9109 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 9110 SmallVector<SDValue, 4> Ops; 9111 for (unsigned i = 0; i != NumOperands; ++i) 9112 Ops.push_back(Op.getOperand(i)); 9113 9114 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 9115 DAG.ReplaceAllUsesWith(Op, New); 9116 return SDValue(New.getNode(), 1); 9117 } 9118 9119 /// Emit nodes that will be selected as "cmp Op0,Op1", or something 9120 /// equivalent. 9121 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 9122 SelectionDAG &DAG) const { 9123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 9124 if (C->getAPIntValue() == 0) 9125 return EmitTest(Op0, X86CC, DAG); 9126 9127 SDLoc dl(Op0); 9128 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 || 9129 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) { 9130 // Use SUB instead of CMP to enable CSE between SUB and CMP. 9131 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32); 9132 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, 9133 Op0, Op1); 9134 return SDValue(Sub.getNode(), 1); 9135 } 9136 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 9137 } 9138 9139 /// Convert a comparison if required by the subtarget. 9140 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp, 9141 SelectionDAG &DAG) const { 9142 // If the subtarget does not support the FUCOMI instruction, floating-point 9143 // comparisons have to be converted. 9144 if (Subtarget->hasCMov() || 9145 Cmp.getOpcode() != X86ISD::CMP || 9146 !Cmp.getOperand(0).getValueType().isFloatingPoint() || 9147 !Cmp.getOperand(1).getValueType().isFloatingPoint()) 9148 return Cmp; 9149 9150 // The instruction selector will select an FUCOM instruction instead of 9151 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence 9152 // build an SDNode sequence that transfers the result from FPSW into EFLAGS: 9153 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8)))) 9154 SDLoc dl(Cmp); 9155 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp); 9156 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW); 9157 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW, 9158 DAG.getConstant(8, MVT::i8)); 9159 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl); 9160 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl); 9161 } 9162 9163 static bool isAllOnes(SDValue V) { 9164 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9165 return C && C->isAllOnesValue(); 9166 } 9167 9168 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 9169 /// if it's possible. 9170 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 9171 SDLoc dl, SelectionDAG &DAG) const { 9172 SDValue Op0 = And.getOperand(0); 9173 SDValue Op1 = And.getOperand(1); 9174 if (Op0.getOpcode() == ISD::TRUNCATE) 9175 Op0 = Op0.getOperand(0); 9176 if (Op1.getOpcode() == ISD::TRUNCATE) 9177 Op1 = Op1.getOperand(0); 9178 9179 SDValue LHS, RHS; 9180 if (Op1.getOpcode() == ISD::SHL) 9181 std::swap(Op0, Op1); 9182 if (Op0.getOpcode() == ISD::SHL) { 9183 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 9184 if (And00C->getZExtValue() == 1) { 9185 // If we looked past a truncate, check that it's only truncating away 9186 // known zeros. 9187 unsigned BitWidth = Op0.getValueSizeInBits(); 9188 unsigned AndBitWidth = And.getValueSizeInBits(); 9189 if (BitWidth > AndBitWidth) { 9190 APInt Zeros, Ones; 9191 DAG.ComputeMaskedBits(Op0, Zeros, Ones); 9192 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 9193 return SDValue(); 9194 } 9195 LHS = Op1; 9196 RHS = Op0.getOperand(1); 9197 } 9198 } else if (Op1.getOpcode() == ISD::Constant) { 9199 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 9200 uint64_t AndRHSVal = AndRHS->getZExtValue(); 9201 SDValue AndLHS = Op0; 9202 9203 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) { 9204 LHS = AndLHS.getOperand(0); 9205 RHS = AndLHS.getOperand(1); 9206 } 9207 9208 // Use BT if the immediate can't be encoded in a TEST instruction. 9209 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) { 9210 LHS = AndLHS; 9211 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType()); 9212 } 9213 } 9214 9215 if (LHS.getNode()) { 9216 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 9217 // instruction. Since the shift amount is in-range-or-undefined, we know 9218 // that doing a bittest on the i32 value is ok. We extend to i32 because 9219 // the encoding for the i16 version is larger than the i32 version. 9220 // Also promote i16 to i32 for performance / code size reason. 9221 if (LHS.getValueType() == MVT::i8 || 9222 LHS.getValueType() == MVT::i16) 9223 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 9224 9225 // If the operand types disagree, extend the shift amount to match. Since 9226 // BT ignores high bits (like shifts) we can use anyextend. 9227 if (LHS.getValueType() != RHS.getValueType()) 9228 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 9229 9230 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 9231 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 9232 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9233 DAG.getConstant(Cond, MVT::i8), BT); 9234 } 9235 9236 return SDValue(); 9237 } 9238 9239 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 9240 // ones, and then concatenate the result back. 9241 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 9242 MVT VT = Op.getValueType().getSimpleVT(); 9243 9244 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC && 9245 "Unsupported value type for operation"); 9246 9247 unsigned NumElems = VT.getVectorNumElements(); 9248 SDLoc dl(Op); 9249 SDValue CC = Op.getOperand(2); 9250 9251 // Extract the LHS vectors 9252 SDValue LHS = Op.getOperand(0); 9253 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 9254 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 9255 9256 // Extract the RHS vectors 9257 SDValue RHS = Op.getOperand(1); 9258 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 9259 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 9260 9261 // Issue the operation on the smaller types and concatenate the result back 9262 MVT EltVT = VT.getVectorElementType(); 9263 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 9264 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9265 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 9266 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 9267 } 9268 9269 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget, 9270 SelectionDAG &DAG) { 9271 SDValue Cond; 9272 SDValue Op0 = Op.getOperand(0); 9273 SDValue Op1 = Op.getOperand(1); 9274 SDValue CC = Op.getOperand(2); 9275 MVT VT = Op.getValueType().getSimpleVT(); 9276 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 9277 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint(); 9278 SDLoc dl(Op); 9279 9280 if (isFP) { 9281 #ifndef NDEBUG 9282 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT(); 9283 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 9284 #endif 9285 9286 unsigned SSECC; 9287 bool Swap = false; 9288 9289 // SSE Condition code mapping: 9290 // 0 - EQ 9291 // 1 - LT 9292 // 2 - LE 9293 // 3 - UNORD 9294 // 4 - NEQ 9295 // 5 - NLT 9296 // 6 - NLE 9297 // 7 - ORD 9298 switch (SetCCOpcode) { 9299 default: llvm_unreachable("Unexpected SETCC condition"); 9300 case ISD::SETOEQ: 9301 case ISD::SETEQ: SSECC = 0; break; 9302 case ISD::SETOGT: 9303 case ISD::SETGT: Swap = true; // Fallthrough 9304 case ISD::SETLT: 9305 case ISD::SETOLT: SSECC = 1; break; 9306 case ISD::SETOGE: 9307 case ISD::SETGE: Swap = true; // Fallthrough 9308 case ISD::SETLE: 9309 case ISD::SETOLE: SSECC = 2; break; 9310 case ISD::SETUO: SSECC = 3; break; 9311 case ISD::SETUNE: 9312 case ISD::SETNE: SSECC = 4; break; 9313 case ISD::SETULE: Swap = true; // Fallthrough 9314 case ISD::SETUGE: SSECC = 5; break; 9315 case ISD::SETULT: Swap = true; // Fallthrough 9316 case ISD::SETUGT: SSECC = 6; break; 9317 case ISD::SETO: SSECC = 7; break; 9318 case ISD::SETUEQ: 9319 case ISD::SETONE: SSECC = 8; break; 9320 } 9321 if (Swap) 9322 std::swap(Op0, Op1); 9323 9324 // In the two special cases we can't handle, emit two comparisons. 9325 if (SSECC == 8) { 9326 unsigned CC0, CC1; 9327 unsigned CombineOpc; 9328 if (SetCCOpcode == ISD::SETUEQ) { 9329 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR; 9330 } else { 9331 assert(SetCCOpcode == ISD::SETONE); 9332 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND; 9333 } 9334 9335 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9336 DAG.getConstant(CC0, MVT::i8)); 9337 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9338 DAG.getConstant(CC1, MVT::i8)); 9339 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1); 9340 } 9341 // Handle all other FP comparisons here. 9342 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9343 DAG.getConstant(SSECC, MVT::i8)); 9344 } 9345 9346 // Break 256-bit integer vector compare into smaller ones. 9347 if (VT.is256BitVector() && !Subtarget->hasInt256()) 9348 return Lower256IntVSETCC(Op, DAG); 9349 9350 // We are handling one of the integer comparisons here. Since SSE only has 9351 // GT and EQ comparisons for integer, swapping operands and multiple 9352 // operations may be required for some comparisons. 9353 unsigned Opc; 9354 bool Swap = false, Invert = false, FlipSigns = false; 9355 9356 switch (SetCCOpcode) { 9357 default: llvm_unreachable("Unexpected SETCC condition"); 9358 case ISD::SETNE: Invert = true; 9359 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break; 9360 case ISD::SETLT: Swap = true; 9361 case ISD::SETGT: Opc = X86ISD::PCMPGT; break; 9362 case ISD::SETGE: Swap = true; 9363 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break; 9364 case ISD::SETULT: Swap = true; 9365 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break; 9366 case ISD::SETUGE: Swap = true; 9367 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break; 9368 } 9369 if (Swap) 9370 std::swap(Op0, Op1); 9371 9372 // Check that the operation in question is available (most are plain SSE2, 9373 // but PCMPGTQ and PCMPEQQ have different requirements). 9374 if (VT == MVT::v2i64) { 9375 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) { 9376 assert(Subtarget->hasSSE2() && "Don't know how to lower!"); 9377 9378 // First cast everything to the right type. 9379 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0); 9380 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1); 9381 9382 // Since SSE has no unsigned integer comparisons, we need to flip the sign 9383 // bits of the inputs before performing those operations. The lower 9384 // compare is always unsigned. 9385 SDValue SB; 9386 if (FlipSigns) { 9387 SB = DAG.getConstant(0x80000000U, MVT::v4i32); 9388 } else { 9389 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32); 9390 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32); 9391 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, 9392 Sign, Zero, Sign, Zero); 9393 } 9394 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB); 9395 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB); 9396 9397 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2)) 9398 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1); 9399 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1); 9400 9401 // Create masks for only the low parts/high parts of the 64 bit integers. 9402 const int MaskHi[] = { 1, 1, 3, 3 }; 9403 const int MaskLo[] = { 0, 0, 2, 2 }; 9404 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi); 9405 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo); 9406 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi); 9407 9408 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo); 9409 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi); 9410 9411 if (Invert) 9412 Result = DAG.getNOT(dl, Result, MVT::v4i32); 9413 9414 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9415 } 9416 9417 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) { 9418 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with 9419 // pcmpeqd + pshufd + pand. 9420 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!"); 9421 9422 // First cast everything to the right type. 9423 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0); 9424 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1); 9425 9426 // Do the compare. 9427 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1); 9428 9429 // Make sure the lower and upper halves are both all-ones. 9430 const int Mask[] = { 1, 0, 3, 2 }; 9431 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask); 9432 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf); 9433 9434 if (Invert) 9435 Result = DAG.getNOT(dl, Result, MVT::v4i32); 9436 9437 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9438 } 9439 } 9440 9441 // Since SSE has no unsigned integer comparisons, we need to flip the sign 9442 // bits of the inputs before performing those operations. 9443 if (FlipSigns) { 9444 EVT EltVT = VT.getVectorElementType(); 9445 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT); 9446 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB); 9447 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB); 9448 } 9449 9450 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 9451 9452 // If the logical-not of the result is required, perform that now. 9453 if (Invert) 9454 Result = DAG.getNOT(dl, Result, VT); 9455 9456 return Result; 9457 } 9458 9459 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 9460 9461 MVT VT = Op.getValueType().getSimpleVT(); 9462 9463 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG); 9464 9465 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer"); 9466 SDValue Op0 = Op.getOperand(0); 9467 SDValue Op1 = Op.getOperand(1); 9468 SDLoc dl(Op); 9469 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 9470 9471 // Optimize to BT if possible. 9472 // Lower (X & (1 << N)) == 0 to BT(X, N). 9473 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 9474 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 9475 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 9476 Op1.getOpcode() == ISD::Constant && 9477 cast<ConstantSDNode>(Op1)->isNullValue() && 9478 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9479 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 9480 if (NewSetCC.getNode()) 9481 return NewSetCC; 9482 } 9483 9484 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 9485 // these. 9486 if (Op1.getOpcode() == ISD::Constant && 9487 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 9488 cast<ConstantSDNode>(Op1)->isNullValue()) && 9489 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9490 9491 // If the input is a setcc, then reuse the input setcc or use a new one with 9492 // the inverted condition. 9493 if (Op0.getOpcode() == X86ISD::SETCC) { 9494 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 9495 bool Invert = (CC == ISD::SETNE) ^ 9496 cast<ConstantSDNode>(Op1)->isNullValue(); 9497 if (!Invert) return Op0; 9498 9499 CCode = X86::GetOppositeBranchCondition(CCode); 9500 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9501 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 9502 } 9503 } 9504 9505 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint(); 9506 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 9507 if (X86CC == X86::COND_INVALID) 9508 return SDValue(); 9509 9510 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 9511 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG); 9512 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9513 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 9514 } 9515 9516 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 9517 static bool isX86LogicalCmp(SDValue Op) { 9518 unsigned Opc = Op.getNode()->getOpcode(); 9519 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI || 9520 Opc == X86ISD::SAHF) 9521 return true; 9522 if (Op.getResNo() == 1 && 9523 (Opc == X86ISD::ADD || 9524 Opc == X86ISD::SUB || 9525 Opc == X86ISD::ADC || 9526 Opc == X86ISD::SBB || 9527 Opc == X86ISD::SMUL || 9528 Opc == X86ISD::UMUL || 9529 Opc == X86ISD::INC || 9530 Opc == X86ISD::DEC || 9531 Opc == X86ISD::OR || 9532 Opc == X86ISD::XOR || 9533 Opc == X86ISD::AND)) 9534 return true; 9535 9536 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 9537 return true; 9538 9539 return false; 9540 } 9541 9542 static bool isZero(SDValue V) { 9543 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9544 return C && C->isNullValue(); 9545 } 9546 9547 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) { 9548 if (V.getOpcode() != ISD::TRUNCATE) 9549 return false; 9550 9551 SDValue VOp0 = V.getOperand(0); 9552 unsigned InBits = VOp0.getValueSizeInBits(); 9553 unsigned Bits = V.getValueSizeInBits(); 9554 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits)); 9555 } 9556 9557 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 9558 bool addTest = true; 9559 SDValue Cond = Op.getOperand(0); 9560 SDValue Op1 = Op.getOperand(1); 9561 SDValue Op2 = Op.getOperand(2); 9562 SDLoc DL(Op); 9563 SDValue CC; 9564 9565 if (Cond.getOpcode() == ISD::SETCC) { 9566 SDValue NewCond = LowerSETCC(Cond, DAG); 9567 if (NewCond.getNode()) 9568 Cond = NewCond; 9569 } 9570 9571 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 9572 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 9573 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 9574 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 9575 if (Cond.getOpcode() == X86ISD::SETCC && 9576 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 9577 isZero(Cond.getOperand(1).getOperand(1))) { 9578 SDValue Cmp = Cond.getOperand(1); 9579 9580 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 9581 9582 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 9583 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 9584 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 9585 9586 SDValue CmpOp0 = Cmp.getOperand(0); 9587 // Apply further optimizations for special cases 9588 // (select (x != 0), -1, 0) -> neg & sbb 9589 // (select (x == 0), 0, -1) -> neg & sbb 9590 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y)) 9591 if (YC->isNullValue() && 9592 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) { 9593 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32); 9594 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 9595 DAG.getConstant(0, CmpOp0.getValueType()), 9596 CmpOp0); 9597 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9598 DAG.getConstant(X86::COND_B, MVT::i8), 9599 SDValue(Neg.getNode(), 1)); 9600 return Res; 9601 } 9602 9603 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 9604 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 9605 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9606 9607 SDValue Res = // Res = 0 or -1. 9608 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9609 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 9610 9611 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 9612 Res = DAG.getNOT(DL, Res, Res.getValueType()); 9613 9614 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 9615 if (N2C == 0 || !N2C->isNullValue()) 9616 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 9617 return Res; 9618 } 9619 } 9620 9621 // Look past (and (setcc_carry (cmp ...)), 1). 9622 if (Cond.getOpcode() == ISD::AND && 9623 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 9624 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 9625 if (C && C->getAPIntValue() == 1) 9626 Cond = Cond.getOperand(0); 9627 } 9628 9629 // If condition flag is set by a X86ISD::CMP, then use it as the condition 9630 // setting operand in place of the X86ISD::SETCC. 9631 unsigned CondOpcode = Cond.getOpcode(); 9632 if (CondOpcode == X86ISD::SETCC || 9633 CondOpcode == X86ISD::SETCC_CARRY) { 9634 CC = Cond.getOperand(0); 9635 9636 SDValue Cmp = Cond.getOperand(1); 9637 unsigned Opc = Cmp.getOpcode(); 9638 MVT VT = Op.getValueType().getSimpleVT(); 9639 9640 bool IllegalFPCMov = false; 9641 if (VT.isFloatingPoint() && !VT.isVector() && 9642 !isScalarFPTypeInSSEReg(VT)) // FPStack? 9643 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 9644 9645 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 9646 Opc == X86ISD::BT) { // FIXME 9647 Cond = Cmp; 9648 addTest = false; 9649 } 9650 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 9651 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 9652 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 9653 Cond.getOperand(0).getValueType() != MVT::i8)) { 9654 SDValue LHS = Cond.getOperand(0); 9655 SDValue RHS = Cond.getOperand(1); 9656 unsigned X86Opcode; 9657 unsigned X86Cond; 9658 SDVTList VTs; 9659 switch (CondOpcode) { 9660 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9661 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9662 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9663 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9664 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9665 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9666 default: llvm_unreachable("unexpected overflowing operator"); 9667 } 9668 if (CondOpcode == ISD::UMULO) 9669 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9670 MVT::i32); 9671 else 9672 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9673 9674 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 9675 9676 if (CondOpcode == ISD::UMULO) 9677 Cond = X86Op.getValue(2); 9678 else 9679 Cond = X86Op.getValue(1); 9680 9681 CC = DAG.getConstant(X86Cond, MVT::i8); 9682 addTest = false; 9683 } 9684 9685 if (addTest) { 9686 // Look pass the truncate if the high bits are known zero. 9687 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 9688 Cond = Cond.getOperand(0); 9689 9690 // We know the result of AND is compared against zero. Try to match 9691 // it to BT. 9692 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9693 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 9694 if (NewSetCC.getNode()) { 9695 CC = NewSetCC.getOperand(0); 9696 Cond = NewSetCC.getOperand(1); 9697 addTest = false; 9698 } 9699 } 9700 } 9701 9702 if (addTest) { 9703 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9704 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9705 } 9706 9707 // a < b ? -1 : 0 -> RES = ~setcc_carry 9708 // a < b ? 0 : -1 -> RES = setcc_carry 9709 // a >= b ? -1 : 0 -> RES = setcc_carry 9710 // a >= b ? 0 : -1 -> RES = ~setcc_carry 9711 if (Cond.getOpcode() == X86ISD::SUB) { 9712 Cond = ConvertCmpIfNecessary(Cond, DAG); 9713 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 9714 9715 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 9716 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 9717 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9718 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 9719 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 9720 return DAG.getNOT(DL, Res, Res.getValueType()); 9721 return Res; 9722 } 9723 } 9724 9725 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate 9726 // widen the cmov and push the truncate through. This avoids introducing a new 9727 // branch during isel and doesn't add any extensions. 9728 if (Op.getValueType() == MVT::i8 && 9729 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) { 9730 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0); 9731 if (T1.getValueType() == T2.getValueType() && 9732 // Blacklist CopyFromReg to avoid partial register stalls. 9733 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){ 9734 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue); 9735 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond); 9736 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov); 9737 } 9738 } 9739 9740 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 9741 // condition is true. 9742 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 9743 SDValue Ops[] = { Op2, Op1, CC, Cond }; 9744 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 9745 } 9746 9747 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op, 9748 SelectionDAG &DAG) const { 9749 MVT VT = Op->getValueType(0).getSimpleVT(); 9750 SDValue In = Op->getOperand(0); 9751 MVT InVT = In.getValueType().getSimpleVT(); 9752 SDLoc dl(Op); 9753 9754 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) && 9755 (VT != MVT::v8i32 || InVT != MVT::v8i16)) 9756 return SDValue(); 9757 9758 if (Subtarget->hasInt256()) 9759 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In); 9760 9761 // Optimize vectors in AVX mode 9762 // Sign extend v8i16 to v8i32 and 9763 // v4i32 to v4i64 9764 // 9765 // Divide input vector into two parts 9766 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1} 9767 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32 9768 // concat the vectors to original VT 9769 9770 unsigned NumElems = InVT.getVectorNumElements(); 9771 SDValue Undef = DAG.getUNDEF(InVT); 9772 9773 SmallVector<int,8> ShufMask1(NumElems, -1); 9774 for (unsigned i = 0; i != NumElems/2; ++i) 9775 ShufMask1[i] = i; 9776 9777 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]); 9778 9779 SmallVector<int,8> ShufMask2(NumElems, -1); 9780 for (unsigned i = 0; i != NumElems/2; ++i) 9781 ShufMask2[i] = i + NumElems/2; 9782 9783 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]); 9784 9785 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(), 9786 VT.getVectorNumElements()/2); 9787 9788 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 9789 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi); 9790 9791 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 9792 } 9793 9794 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 9795 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 9796 // from the AND / OR. 9797 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 9798 Opc = Op.getOpcode(); 9799 if (Opc != ISD::OR && Opc != ISD::AND) 9800 return false; 9801 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 9802 Op.getOperand(0).hasOneUse() && 9803 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 9804 Op.getOperand(1).hasOneUse()); 9805 } 9806 9807 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 9808 // 1 and that the SETCC node has a single use. 9809 static bool isXor1OfSetCC(SDValue Op) { 9810 if (Op.getOpcode() != ISD::XOR) 9811 return false; 9812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9813 if (N1C && N1C->getAPIntValue() == 1) { 9814 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 9815 Op.getOperand(0).hasOneUse(); 9816 } 9817 return false; 9818 } 9819 9820 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 9821 bool addTest = true; 9822 SDValue Chain = Op.getOperand(0); 9823 SDValue Cond = Op.getOperand(1); 9824 SDValue Dest = Op.getOperand(2); 9825 SDLoc dl(Op); 9826 SDValue CC; 9827 bool Inverted = false; 9828 9829 if (Cond.getOpcode() == ISD::SETCC) { 9830 // Check for setcc([su]{add,sub,mul}o == 0). 9831 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 9832 isa<ConstantSDNode>(Cond.getOperand(1)) && 9833 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 9834 Cond.getOperand(0).getResNo() == 1 && 9835 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 9836 Cond.getOperand(0).getOpcode() == ISD::UADDO || 9837 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 9838 Cond.getOperand(0).getOpcode() == ISD::USUBO || 9839 Cond.getOperand(0).getOpcode() == ISD::SMULO || 9840 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 9841 Inverted = true; 9842 Cond = Cond.getOperand(0); 9843 } else { 9844 SDValue NewCond = LowerSETCC(Cond, DAG); 9845 if (NewCond.getNode()) 9846 Cond = NewCond; 9847 } 9848 } 9849 #if 0 9850 // FIXME: LowerXALUO doesn't handle these!! 9851 else if (Cond.getOpcode() == X86ISD::ADD || 9852 Cond.getOpcode() == X86ISD::SUB || 9853 Cond.getOpcode() == X86ISD::SMUL || 9854 Cond.getOpcode() == X86ISD::UMUL) 9855 Cond = LowerXALUO(Cond, DAG); 9856 #endif 9857 9858 // Look pass (and (setcc_carry (cmp ...)), 1). 9859 if (Cond.getOpcode() == ISD::AND && 9860 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 9861 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 9862 if (C && C->getAPIntValue() == 1) 9863 Cond = Cond.getOperand(0); 9864 } 9865 9866 // If condition flag is set by a X86ISD::CMP, then use it as the condition 9867 // setting operand in place of the X86ISD::SETCC. 9868 unsigned CondOpcode = Cond.getOpcode(); 9869 if (CondOpcode == X86ISD::SETCC || 9870 CondOpcode == X86ISD::SETCC_CARRY) { 9871 CC = Cond.getOperand(0); 9872 9873 SDValue Cmp = Cond.getOperand(1); 9874 unsigned Opc = Cmp.getOpcode(); 9875 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 9876 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 9877 Cond = Cmp; 9878 addTest = false; 9879 } else { 9880 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 9881 default: break; 9882 case X86::COND_O: 9883 case X86::COND_B: 9884 // These can only come from an arithmetic instruction with overflow, 9885 // e.g. SADDO, UADDO. 9886 Cond = Cond.getNode()->getOperand(1); 9887 addTest = false; 9888 break; 9889 } 9890 } 9891 } 9892 CondOpcode = Cond.getOpcode(); 9893 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 9894 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 9895 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 9896 Cond.getOperand(0).getValueType() != MVT::i8)) { 9897 SDValue LHS = Cond.getOperand(0); 9898 SDValue RHS = Cond.getOperand(1); 9899 unsigned X86Opcode; 9900 unsigned X86Cond; 9901 SDVTList VTs; 9902 switch (CondOpcode) { 9903 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9904 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9905 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9906 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9907 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9908 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9909 default: llvm_unreachable("unexpected overflowing operator"); 9910 } 9911 if (Inverted) 9912 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 9913 if (CondOpcode == ISD::UMULO) 9914 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9915 MVT::i32); 9916 else 9917 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9918 9919 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 9920 9921 if (CondOpcode == ISD::UMULO) 9922 Cond = X86Op.getValue(2); 9923 else 9924 Cond = X86Op.getValue(1); 9925 9926 CC = DAG.getConstant(X86Cond, MVT::i8); 9927 addTest = false; 9928 } else { 9929 unsigned CondOpc; 9930 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 9931 SDValue Cmp = Cond.getOperand(0).getOperand(1); 9932 if (CondOpc == ISD::OR) { 9933 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 9934 // two branches instead of an explicit OR instruction with a 9935 // separate test. 9936 if (Cmp == Cond.getOperand(1).getOperand(1) && 9937 isX86LogicalCmp(Cmp)) { 9938 CC = Cond.getOperand(0).getOperand(0); 9939 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9940 Chain, Dest, CC, Cmp); 9941 CC = Cond.getOperand(1).getOperand(0); 9942 Cond = Cmp; 9943 addTest = false; 9944 } 9945 } else { // ISD::AND 9946 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 9947 // two branches instead of an explicit AND instruction with a 9948 // separate test. However, we only do this if this block doesn't 9949 // have a fall-through edge, because this requires an explicit 9950 // jmp when the condition is false. 9951 if (Cmp == Cond.getOperand(1).getOperand(1) && 9952 isX86LogicalCmp(Cmp) && 9953 Op.getNode()->hasOneUse()) { 9954 X86::CondCode CCode = 9955 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9956 CCode = X86::GetOppositeBranchCondition(CCode); 9957 CC = DAG.getConstant(CCode, MVT::i8); 9958 SDNode *User = *Op.getNode()->use_begin(); 9959 // Look for an unconditional branch following this conditional branch. 9960 // We need this because we need to reverse the successors in order 9961 // to implement FCMP_OEQ. 9962 if (User->getOpcode() == ISD::BR) { 9963 SDValue FalseBB = User->getOperand(1); 9964 SDNode *NewBR = 9965 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9966 assert(NewBR == User); 9967 (void)NewBR; 9968 Dest = FalseBB; 9969 9970 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9971 Chain, Dest, CC, Cmp); 9972 X86::CondCode CCode = 9973 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 9974 CCode = X86::GetOppositeBranchCondition(CCode); 9975 CC = DAG.getConstant(CCode, MVT::i8); 9976 Cond = Cmp; 9977 addTest = false; 9978 } 9979 } 9980 } 9981 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 9982 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 9983 // It should be transformed during dag combiner except when the condition 9984 // is set by a arithmetics with overflow node. 9985 X86::CondCode CCode = 9986 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9987 CCode = X86::GetOppositeBranchCondition(CCode); 9988 CC = DAG.getConstant(CCode, MVT::i8); 9989 Cond = Cond.getOperand(0).getOperand(1); 9990 addTest = false; 9991 } else if (Cond.getOpcode() == ISD::SETCC && 9992 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 9993 // For FCMP_OEQ, we can emit 9994 // two branches instead of an explicit AND instruction with a 9995 // separate test. However, we only do this if this block doesn't 9996 // have a fall-through edge, because this requires an explicit 9997 // jmp when the condition is false. 9998 if (Op.getNode()->hasOneUse()) { 9999 SDNode *User = *Op.getNode()->use_begin(); 10000 // Look for an unconditional branch following this conditional branch. 10001 // We need this because we need to reverse the successors in order 10002 // to implement FCMP_OEQ. 10003 if (User->getOpcode() == ISD::BR) { 10004 SDValue FalseBB = User->getOperand(1); 10005 SDNode *NewBR = 10006 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 10007 assert(NewBR == User); 10008 (void)NewBR; 10009 Dest = FalseBB; 10010 10011 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 10012 Cond.getOperand(0), Cond.getOperand(1)); 10013 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 10014 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10015 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10016 Chain, Dest, CC, Cmp); 10017 CC = DAG.getConstant(X86::COND_P, MVT::i8); 10018 Cond = Cmp; 10019 addTest = false; 10020 } 10021 } 10022 } else if (Cond.getOpcode() == ISD::SETCC && 10023 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 10024 // For FCMP_UNE, we can emit 10025 // two branches instead of an explicit AND instruction with a 10026 // separate test. However, we only do this if this block doesn't 10027 // have a fall-through edge, because this requires an explicit 10028 // jmp when the condition is false. 10029 if (Op.getNode()->hasOneUse()) { 10030 SDNode *User = *Op.getNode()->use_begin(); 10031 // Look for an unconditional branch following this conditional branch. 10032 // We need this because we need to reverse the successors in order 10033 // to implement FCMP_UNE. 10034 if (User->getOpcode() == ISD::BR) { 10035 SDValue FalseBB = User->getOperand(1); 10036 SDNode *NewBR = 10037 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 10038 assert(NewBR == User); 10039 (void)NewBR; 10040 10041 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 10042 Cond.getOperand(0), Cond.getOperand(1)); 10043 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 10044 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10045 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10046 Chain, Dest, CC, Cmp); 10047 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 10048 Cond = Cmp; 10049 addTest = false; 10050 Dest = FalseBB; 10051 } 10052 } 10053 } 10054 } 10055 10056 if (addTest) { 10057 // Look pass the truncate if the high bits are known zero. 10058 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 10059 Cond = Cond.getOperand(0); 10060 10061 // We know the result of AND is compared against zero. Try to match 10062 // it to BT. 10063 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 10064 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 10065 if (NewSetCC.getNode()) { 10066 CC = NewSetCC.getOperand(0); 10067 Cond = NewSetCC.getOperand(1); 10068 addTest = false; 10069 } 10070 } 10071 } 10072 10073 if (addTest) { 10074 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 10075 Cond = EmitTest(Cond, X86::COND_NE, DAG); 10076 } 10077 Cond = ConvertCmpIfNecessary(Cond, DAG); 10078 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 10079 Chain, Dest, CC, Cond); 10080 } 10081 10082 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 10083 // Calls to _alloca is needed to probe the stack when allocating more than 4k 10084 // bytes in one go. Touching the stack at 4K increments is necessary to ensure 10085 // that the guard pages used by the OS virtual memory manager are allocated in 10086 // correct sequence. 10087 SDValue 10088 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 10089 SelectionDAG &DAG) const { 10090 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 10091 getTargetMachine().Options.EnableSegmentedStacks) && 10092 "This should be used only on Windows targets or when segmented stacks " 10093 "are being used"); 10094 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 10095 SDLoc dl(Op); 10096 10097 // Get the inputs. 10098 SDValue Chain = Op.getOperand(0); 10099 SDValue Size = Op.getOperand(1); 10100 // FIXME: Ensure alignment here 10101 10102 bool Is64Bit = Subtarget->is64Bit(); 10103 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 10104 10105 if (getTargetMachine().Options.EnableSegmentedStacks) { 10106 MachineFunction &MF = DAG.getMachineFunction(); 10107 MachineRegisterInfo &MRI = MF.getRegInfo(); 10108 10109 if (Is64Bit) { 10110 // The 64 bit implementation of segmented stacks needs to clobber both r10 10111 // r11. This makes it impossible to use it along with nested parameters. 10112 const Function *F = MF.getFunction(); 10113 10114 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 10115 I != E; ++I) 10116 if (I->hasNestAttr()) 10117 report_fatal_error("Cannot use segmented stacks with functions that " 10118 "have nested arguments."); 10119 } 10120 10121 const TargetRegisterClass *AddrRegClass = 10122 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 10123 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 10124 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 10125 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 10126 DAG.getRegister(Vreg, SPTy)); 10127 SDValue Ops1[2] = { Value, Chain }; 10128 return DAG.getMergeValues(Ops1, 2, dl); 10129 } else { 10130 SDValue Flag; 10131 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 10132 10133 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 10134 Flag = Chain.getValue(1); 10135 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10136 10137 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 10138 Flag = Chain.getValue(1); 10139 10140 const X86RegisterInfo *RegInfo = 10141 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 10142 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 10143 SPTy).getValue(1); 10144 10145 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 10146 return DAG.getMergeValues(Ops1, 2, dl); 10147 } 10148 } 10149 10150 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 10151 MachineFunction &MF = DAG.getMachineFunction(); 10152 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 10153 10154 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10155 SDLoc DL(Op); 10156 10157 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 10158 // vastart just stores the address of the VarArgsFrameIndex slot into the 10159 // memory location argument. 10160 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10161 getPointerTy()); 10162 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 10163 MachinePointerInfo(SV), false, false, 0); 10164 } 10165 10166 // __va_list_tag: 10167 // gp_offset (0 - 6 * 8) 10168 // fp_offset (48 - 48 + 8 * 16) 10169 // overflow_arg_area (point to parameters coming in memory). 10170 // reg_save_area 10171 SmallVector<SDValue, 8> MemOps; 10172 SDValue FIN = Op.getOperand(1); 10173 // Store gp_offset 10174 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 10175 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 10176 MVT::i32), 10177 FIN, MachinePointerInfo(SV), false, false, 0); 10178 MemOps.push_back(Store); 10179 10180 // Store fp_offset 10181 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10182 FIN, DAG.getIntPtrConstant(4)); 10183 Store = DAG.getStore(Op.getOperand(0), DL, 10184 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 10185 MVT::i32), 10186 FIN, MachinePointerInfo(SV, 4), false, false, 0); 10187 MemOps.push_back(Store); 10188 10189 // Store ptr to overflow_arg_area 10190 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10191 FIN, DAG.getIntPtrConstant(4)); 10192 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10193 getPointerTy()); 10194 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 10195 MachinePointerInfo(SV, 8), 10196 false, false, 0); 10197 MemOps.push_back(Store); 10198 10199 // Store ptr to reg_save_area. 10200 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10201 FIN, DAG.getIntPtrConstant(8)); 10202 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 10203 getPointerTy()); 10204 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 10205 MachinePointerInfo(SV, 16), false, false, 0); 10206 MemOps.push_back(Store); 10207 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 10208 &MemOps[0], MemOps.size()); 10209 } 10210 10211 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 10212 assert(Subtarget->is64Bit() && 10213 "LowerVAARG only handles 64-bit va_arg!"); 10214 assert((Subtarget->isTargetLinux() || 10215 Subtarget->isTargetDarwin()) && 10216 "Unhandled target in LowerVAARG"); 10217 assert(Op.getNode()->getNumOperands() == 4); 10218 SDValue Chain = Op.getOperand(0); 10219 SDValue SrcPtr = Op.getOperand(1); 10220 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10221 unsigned Align = Op.getConstantOperandVal(3); 10222 SDLoc dl(Op); 10223 10224 EVT ArgVT = Op.getNode()->getValueType(0); 10225 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 10226 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy); 10227 uint8_t ArgMode; 10228 10229 // Decide which area this value should be read from. 10230 // TODO: Implement the AMD64 ABI in its entirety. This simple 10231 // selection mechanism works only for the basic types. 10232 if (ArgVT == MVT::f80) { 10233 llvm_unreachable("va_arg for f80 not yet implemented"); 10234 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 10235 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 10236 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 10237 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 10238 } else { 10239 llvm_unreachable("Unhandled argument type in LowerVAARG"); 10240 } 10241 10242 if (ArgMode == 2) { 10243 // Sanity Check: Make sure using fp_offset makes sense. 10244 assert(!getTargetMachine().Options.UseSoftFloat && 10245 !(DAG.getMachineFunction() 10246 .getFunction()->getAttributes() 10247 .hasAttribute(AttributeSet::FunctionIndex, 10248 Attribute::NoImplicitFloat)) && 10249 Subtarget->hasSSE1()); 10250 } 10251 10252 // Insert VAARG_64 node into the DAG 10253 // VAARG_64 returns two values: Variable Argument Address, Chain 10254 SmallVector<SDValue, 11> InstOps; 10255 InstOps.push_back(Chain); 10256 InstOps.push_back(SrcPtr); 10257 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 10258 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 10259 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 10260 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 10261 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 10262 VTs, &InstOps[0], InstOps.size(), 10263 MVT::i64, 10264 MachinePointerInfo(SV), 10265 /*Align=*/0, 10266 /*Volatile=*/false, 10267 /*ReadMem=*/true, 10268 /*WriteMem=*/true); 10269 Chain = VAARG.getValue(1); 10270 10271 // Load the next argument and return it 10272 return DAG.getLoad(ArgVT, dl, 10273 Chain, 10274 VAARG, 10275 MachinePointerInfo(), 10276 false, false, false, 0); 10277 } 10278 10279 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget, 10280 SelectionDAG &DAG) { 10281 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 10282 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 10283 SDValue Chain = Op.getOperand(0); 10284 SDValue DstPtr = Op.getOperand(1); 10285 SDValue SrcPtr = Op.getOperand(2); 10286 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 10287 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 10288 SDLoc DL(Op); 10289 10290 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 10291 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 10292 false, 10293 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 10294 } 10295 10296 // getTargetVShiftNode - Handle vector element shifts where the shift amount 10297 // may or may not be a constant. Takes immediate version of shift as input. 10298 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT, 10299 SDValue SrcOp, SDValue ShAmt, 10300 SelectionDAG &DAG) { 10301 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32"); 10302 10303 if (isa<ConstantSDNode>(ShAmt)) { 10304 // Constant may be a TargetConstant. Use a regular constant. 10305 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10306 switch (Opc) { 10307 default: llvm_unreachable("Unknown target vector shift node"); 10308 case X86ISD::VSHLI: 10309 case X86ISD::VSRLI: 10310 case X86ISD::VSRAI: 10311 return DAG.getNode(Opc, dl, VT, SrcOp, 10312 DAG.getConstant(ShiftAmt, MVT::i32)); 10313 } 10314 } 10315 10316 // Change opcode to non-immediate version 10317 switch (Opc) { 10318 default: llvm_unreachable("Unknown target vector shift node"); 10319 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break; 10320 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break; 10321 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break; 10322 } 10323 10324 // Need to build a vector containing shift amount 10325 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0 10326 SDValue ShOps[4]; 10327 ShOps[0] = ShAmt; 10328 ShOps[1] = DAG.getConstant(0, MVT::i32); 10329 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32); 10330 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4); 10331 10332 // The return type has to be a 128-bit type with the same element 10333 // type as the input type. 10334 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10335 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits()); 10336 10337 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt); 10338 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt); 10339 } 10340 10341 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) { 10342 SDLoc dl(Op); 10343 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10344 switch (IntNo) { 10345 default: return SDValue(); // Don't custom lower most intrinsics. 10346 // Comparison intrinsics. 10347 case Intrinsic::x86_sse_comieq_ss: 10348 case Intrinsic::x86_sse_comilt_ss: 10349 case Intrinsic::x86_sse_comile_ss: 10350 case Intrinsic::x86_sse_comigt_ss: 10351 case Intrinsic::x86_sse_comige_ss: 10352 case Intrinsic::x86_sse_comineq_ss: 10353 case Intrinsic::x86_sse_ucomieq_ss: 10354 case Intrinsic::x86_sse_ucomilt_ss: 10355 case Intrinsic::x86_sse_ucomile_ss: 10356 case Intrinsic::x86_sse_ucomigt_ss: 10357 case Intrinsic::x86_sse_ucomige_ss: 10358 case Intrinsic::x86_sse_ucomineq_ss: 10359 case Intrinsic::x86_sse2_comieq_sd: 10360 case Intrinsic::x86_sse2_comilt_sd: 10361 case Intrinsic::x86_sse2_comile_sd: 10362 case Intrinsic::x86_sse2_comigt_sd: 10363 case Intrinsic::x86_sse2_comige_sd: 10364 case Intrinsic::x86_sse2_comineq_sd: 10365 case Intrinsic::x86_sse2_ucomieq_sd: 10366 case Intrinsic::x86_sse2_ucomilt_sd: 10367 case Intrinsic::x86_sse2_ucomile_sd: 10368 case Intrinsic::x86_sse2_ucomigt_sd: 10369 case Intrinsic::x86_sse2_ucomige_sd: 10370 case Intrinsic::x86_sse2_ucomineq_sd: { 10371 unsigned Opc; 10372 ISD::CondCode CC; 10373 switch (IntNo) { 10374 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10375 case Intrinsic::x86_sse_comieq_ss: 10376 case Intrinsic::x86_sse2_comieq_sd: 10377 Opc = X86ISD::COMI; 10378 CC = ISD::SETEQ; 10379 break; 10380 case Intrinsic::x86_sse_comilt_ss: 10381 case Intrinsic::x86_sse2_comilt_sd: 10382 Opc = X86ISD::COMI; 10383 CC = ISD::SETLT; 10384 break; 10385 case Intrinsic::x86_sse_comile_ss: 10386 case Intrinsic::x86_sse2_comile_sd: 10387 Opc = X86ISD::COMI; 10388 CC = ISD::SETLE; 10389 break; 10390 case Intrinsic::x86_sse_comigt_ss: 10391 case Intrinsic::x86_sse2_comigt_sd: 10392 Opc = X86ISD::COMI; 10393 CC = ISD::SETGT; 10394 break; 10395 case Intrinsic::x86_sse_comige_ss: 10396 case Intrinsic::x86_sse2_comige_sd: 10397 Opc = X86ISD::COMI; 10398 CC = ISD::SETGE; 10399 break; 10400 case Intrinsic::x86_sse_comineq_ss: 10401 case Intrinsic::x86_sse2_comineq_sd: 10402 Opc = X86ISD::COMI; 10403 CC = ISD::SETNE; 10404 break; 10405 case Intrinsic::x86_sse_ucomieq_ss: 10406 case Intrinsic::x86_sse2_ucomieq_sd: 10407 Opc = X86ISD::UCOMI; 10408 CC = ISD::SETEQ; 10409 break; 10410 case Intrinsic::x86_sse_ucomilt_ss: 10411 case Intrinsic::x86_sse2_ucomilt_sd: 10412 Opc = X86ISD::UCOMI; 10413 CC = ISD::SETLT; 10414 break; 10415 case Intrinsic::x86_sse_ucomile_ss: 10416 case Intrinsic::x86_sse2_ucomile_sd: 10417 Opc = X86ISD::UCOMI; 10418 CC = ISD::SETLE; 10419 break; 10420 case Intrinsic::x86_sse_ucomigt_ss: 10421 case Intrinsic::x86_sse2_ucomigt_sd: 10422 Opc = X86ISD::UCOMI; 10423 CC = ISD::SETGT; 10424 break; 10425 case Intrinsic::x86_sse_ucomige_ss: 10426 case Intrinsic::x86_sse2_ucomige_sd: 10427 Opc = X86ISD::UCOMI; 10428 CC = ISD::SETGE; 10429 break; 10430 case Intrinsic::x86_sse_ucomineq_ss: 10431 case Intrinsic::x86_sse2_ucomineq_sd: 10432 Opc = X86ISD::UCOMI; 10433 CC = ISD::SETNE; 10434 break; 10435 } 10436 10437 SDValue LHS = Op.getOperand(1); 10438 SDValue RHS = Op.getOperand(2); 10439 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 10440 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 10441 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 10442 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 10443 DAG.getConstant(X86CC, MVT::i8), Cond); 10444 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10445 } 10446 10447 // Arithmetic intrinsics. 10448 case Intrinsic::x86_sse2_pmulu_dq: 10449 case Intrinsic::x86_avx2_pmulu_dq: 10450 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(), 10451 Op.getOperand(1), Op.getOperand(2)); 10452 10453 // SSE2/AVX2 sub with unsigned saturation intrinsics 10454 case Intrinsic::x86_sse2_psubus_b: 10455 case Intrinsic::x86_sse2_psubus_w: 10456 case Intrinsic::x86_avx2_psubus_b: 10457 case Intrinsic::x86_avx2_psubus_w: 10458 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(), 10459 Op.getOperand(1), Op.getOperand(2)); 10460 10461 // SSE3/AVX horizontal add/sub intrinsics 10462 case Intrinsic::x86_sse3_hadd_ps: 10463 case Intrinsic::x86_sse3_hadd_pd: 10464 case Intrinsic::x86_avx_hadd_ps_256: 10465 case Intrinsic::x86_avx_hadd_pd_256: 10466 case Intrinsic::x86_sse3_hsub_ps: 10467 case Intrinsic::x86_sse3_hsub_pd: 10468 case Intrinsic::x86_avx_hsub_ps_256: 10469 case Intrinsic::x86_avx_hsub_pd_256: 10470 case Intrinsic::x86_ssse3_phadd_w_128: 10471 case Intrinsic::x86_ssse3_phadd_d_128: 10472 case Intrinsic::x86_avx2_phadd_w: 10473 case Intrinsic::x86_avx2_phadd_d: 10474 case Intrinsic::x86_ssse3_phsub_w_128: 10475 case Intrinsic::x86_ssse3_phsub_d_128: 10476 case Intrinsic::x86_avx2_phsub_w: 10477 case Intrinsic::x86_avx2_phsub_d: { 10478 unsigned Opcode; 10479 switch (IntNo) { 10480 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10481 case Intrinsic::x86_sse3_hadd_ps: 10482 case Intrinsic::x86_sse3_hadd_pd: 10483 case Intrinsic::x86_avx_hadd_ps_256: 10484 case Intrinsic::x86_avx_hadd_pd_256: 10485 Opcode = X86ISD::FHADD; 10486 break; 10487 case Intrinsic::x86_sse3_hsub_ps: 10488 case Intrinsic::x86_sse3_hsub_pd: 10489 case Intrinsic::x86_avx_hsub_ps_256: 10490 case Intrinsic::x86_avx_hsub_pd_256: 10491 Opcode = X86ISD::FHSUB; 10492 break; 10493 case Intrinsic::x86_ssse3_phadd_w_128: 10494 case Intrinsic::x86_ssse3_phadd_d_128: 10495 case Intrinsic::x86_avx2_phadd_w: 10496 case Intrinsic::x86_avx2_phadd_d: 10497 Opcode = X86ISD::HADD; 10498 break; 10499 case Intrinsic::x86_ssse3_phsub_w_128: 10500 case Intrinsic::x86_ssse3_phsub_d_128: 10501 case Intrinsic::x86_avx2_phsub_w: 10502 case Intrinsic::x86_avx2_phsub_d: 10503 Opcode = X86ISD::HSUB; 10504 break; 10505 } 10506 return DAG.getNode(Opcode, dl, Op.getValueType(), 10507 Op.getOperand(1), Op.getOperand(2)); 10508 } 10509 10510 // SSE2/SSE41/AVX2 integer max/min intrinsics. 10511 case Intrinsic::x86_sse2_pmaxu_b: 10512 case Intrinsic::x86_sse41_pmaxuw: 10513 case Intrinsic::x86_sse41_pmaxud: 10514 case Intrinsic::x86_avx2_pmaxu_b: 10515 case Intrinsic::x86_avx2_pmaxu_w: 10516 case Intrinsic::x86_avx2_pmaxu_d: 10517 case Intrinsic::x86_sse2_pminu_b: 10518 case Intrinsic::x86_sse41_pminuw: 10519 case Intrinsic::x86_sse41_pminud: 10520 case Intrinsic::x86_avx2_pminu_b: 10521 case Intrinsic::x86_avx2_pminu_w: 10522 case Intrinsic::x86_avx2_pminu_d: 10523 case Intrinsic::x86_sse41_pmaxsb: 10524 case Intrinsic::x86_sse2_pmaxs_w: 10525 case Intrinsic::x86_sse41_pmaxsd: 10526 case Intrinsic::x86_avx2_pmaxs_b: 10527 case Intrinsic::x86_avx2_pmaxs_w: 10528 case Intrinsic::x86_avx2_pmaxs_d: 10529 case Intrinsic::x86_sse41_pminsb: 10530 case Intrinsic::x86_sse2_pmins_w: 10531 case Intrinsic::x86_sse41_pminsd: 10532 case Intrinsic::x86_avx2_pmins_b: 10533 case Intrinsic::x86_avx2_pmins_w: 10534 case Intrinsic::x86_avx2_pmins_d: { 10535 unsigned Opcode; 10536 switch (IntNo) { 10537 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10538 case Intrinsic::x86_sse2_pmaxu_b: 10539 case Intrinsic::x86_sse41_pmaxuw: 10540 case Intrinsic::x86_sse41_pmaxud: 10541 case Intrinsic::x86_avx2_pmaxu_b: 10542 case Intrinsic::x86_avx2_pmaxu_w: 10543 case Intrinsic::x86_avx2_pmaxu_d: 10544 Opcode = X86ISD::UMAX; 10545 break; 10546 case Intrinsic::x86_sse2_pminu_b: 10547 case Intrinsic::x86_sse41_pminuw: 10548 case Intrinsic::x86_sse41_pminud: 10549 case Intrinsic::x86_avx2_pminu_b: 10550 case Intrinsic::x86_avx2_pminu_w: 10551 case Intrinsic::x86_avx2_pminu_d: 10552 Opcode = X86ISD::UMIN; 10553 break; 10554 case Intrinsic::x86_sse41_pmaxsb: 10555 case Intrinsic::x86_sse2_pmaxs_w: 10556 case Intrinsic::x86_sse41_pmaxsd: 10557 case Intrinsic::x86_avx2_pmaxs_b: 10558 case Intrinsic::x86_avx2_pmaxs_w: 10559 case Intrinsic::x86_avx2_pmaxs_d: 10560 Opcode = X86ISD::SMAX; 10561 break; 10562 case Intrinsic::x86_sse41_pminsb: 10563 case Intrinsic::x86_sse2_pmins_w: 10564 case Intrinsic::x86_sse41_pminsd: 10565 case Intrinsic::x86_avx2_pmins_b: 10566 case Intrinsic::x86_avx2_pmins_w: 10567 case Intrinsic::x86_avx2_pmins_d: 10568 Opcode = X86ISD::SMIN; 10569 break; 10570 } 10571 return DAG.getNode(Opcode, dl, Op.getValueType(), 10572 Op.getOperand(1), Op.getOperand(2)); 10573 } 10574 10575 // SSE/SSE2/AVX floating point max/min intrinsics. 10576 case Intrinsic::x86_sse_max_ps: 10577 case Intrinsic::x86_sse2_max_pd: 10578 case Intrinsic::x86_avx_max_ps_256: 10579 case Intrinsic::x86_avx_max_pd_256: 10580 case Intrinsic::x86_sse_min_ps: 10581 case Intrinsic::x86_sse2_min_pd: 10582 case Intrinsic::x86_avx_min_ps_256: 10583 case Intrinsic::x86_avx_min_pd_256: { 10584 unsigned Opcode; 10585 switch (IntNo) { 10586 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10587 case Intrinsic::x86_sse_max_ps: 10588 case Intrinsic::x86_sse2_max_pd: 10589 case Intrinsic::x86_avx_max_ps_256: 10590 case Intrinsic::x86_avx_max_pd_256: 10591 Opcode = X86ISD::FMAX; 10592 break; 10593 case Intrinsic::x86_sse_min_ps: 10594 case Intrinsic::x86_sse2_min_pd: 10595 case Intrinsic::x86_avx_min_ps_256: 10596 case Intrinsic::x86_avx_min_pd_256: 10597 Opcode = X86ISD::FMIN; 10598 break; 10599 } 10600 return DAG.getNode(Opcode, dl, Op.getValueType(), 10601 Op.getOperand(1), Op.getOperand(2)); 10602 } 10603 10604 // AVX2 variable shift intrinsics 10605 case Intrinsic::x86_avx2_psllv_d: 10606 case Intrinsic::x86_avx2_psllv_q: 10607 case Intrinsic::x86_avx2_psllv_d_256: 10608 case Intrinsic::x86_avx2_psllv_q_256: 10609 case Intrinsic::x86_avx2_psrlv_d: 10610 case Intrinsic::x86_avx2_psrlv_q: 10611 case Intrinsic::x86_avx2_psrlv_d_256: 10612 case Intrinsic::x86_avx2_psrlv_q_256: 10613 case Intrinsic::x86_avx2_psrav_d: 10614 case Intrinsic::x86_avx2_psrav_d_256: { 10615 unsigned Opcode; 10616 switch (IntNo) { 10617 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10618 case Intrinsic::x86_avx2_psllv_d: 10619 case Intrinsic::x86_avx2_psllv_q: 10620 case Intrinsic::x86_avx2_psllv_d_256: 10621 case Intrinsic::x86_avx2_psllv_q_256: 10622 Opcode = ISD::SHL; 10623 break; 10624 case Intrinsic::x86_avx2_psrlv_d: 10625 case Intrinsic::x86_avx2_psrlv_q: 10626 case Intrinsic::x86_avx2_psrlv_d_256: 10627 case Intrinsic::x86_avx2_psrlv_q_256: 10628 Opcode = ISD::SRL; 10629 break; 10630 case Intrinsic::x86_avx2_psrav_d: 10631 case Intrinsic::x86_avx2_psrav_d_256: 10632 Opcode = ISD::SRA; 10633 break; 10634 } 10635 return DAG.getNode(Opcode, dl, Op.getValueType(), 10636 Op.getOperand(1), Op.getOperand(2)); 10637 } 10638 10639 case Intrinsic::x86_ssse3_pshuf_b_128: 10640 case Intrinsic::x86_avx2_pshuf_b: 10641 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(), 10642 Op.getOperand(1), Op.getOperand(2)); 10643 10644 case Intrinsic::x86_ssse3_psign_b_128: 10645 case Intrinsic::x86_ssse3_psign_w_128: 10646 case Intrinsic::x86_ssse3_psign_d_128: 10647 case Intrinsic::x86_avx2_psign_b: 10648 case Intrinsic::x86_avx2_psign_w: 10649 case Intrinsic::x86_avx2_psign_d: 10650 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(), 10651 Op.getOperand(1), Op.getOperand(2)); 10652 10653 case Intrinsic::x86_sse41_insertps: 10654 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(), 10655 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 10656 10657 case Intrinsic::x86_avx_vperm2f128_ps_256: 10658 case Intrinsic::x86_avx_vperm2f128_pd_256: 10659 case Intrinsic::x86_avx_vperm2f128_si_256: 10660 case Intrinsic::x86_avx2_vperm2i128: 10661 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(), 10662 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 10663 10664 case Intrinsic::x86_avx2_permd: 10665 case Intrinsic::x86_avx2_permps: 10666 // Operands intentionally swapped. Mask is last operand to intrinsic, 10667 // but second operand for node/intruction. 10668 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(), 10669 Op.getOperand(2), Op.getOperand(1)); 10670 10671 case Intrinsic::x86_sse_sqrt_ps: 10672 case Intrinsic::x86_sse2_sqrt_pd: 10673 case Intrinsic::x86_avx_sqrt_ps_256: 10674 case Intrinsic::x86_avx_sqrt_pd_256: 10675 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1)); 10676 10677 // ptest and testp intrinsics. The intrinsic these come from are designed to 10678 // return an integer value, not just an instruction so lower it to the ptest 10679 // or testp pattern and a setcc for the result. 10680 case Intrinsic::x86_sse41_ptestz: 10681 case Intrinsic::x86_sse41_ptestc: 10682 case Intrinsic::x86_sse41_ptestnzc: 10683 case Intrinsic::x86_avx_ptestz_256: 10684 case Intrinsic::x86_avx_ptestc_256: 10685 case Intrinsic::x86_avx_ptestnzc_256: 10686 case Intrinsic::x86_avx_vtestz_ps: 10687 case Intrinsic::x86_avx_vtestc_ps: 10688 case Intrinsic::x86_avx_vtestnzc_ps: 10689 case Intrinsic::x86_avx_vtestz_pd: 10690 case Intrinsic::x86_avx_vtestc_pd: 10691 case Intrinsic::x86_avx_vtestnzc_pd: 10692 case Intrinsic::x86_avx_vtestz_ps_256: 10693 case Intrinsic::x86_avx_vtestc_ps_256: 10694 case Intrinsic::x86_avx_vtestnzc_ps_256: 10695 case Intrinsic::x86_avx_vtestz_pd_256: 10696 case Intrinsic::x86_avx_vtestc_pd_256: 10697 case Intrinsic::x86_avx_vtestnzc_pd_256: { 10698 bool IsTestPacked = false; 10699 unsigned X86CC; 10700 switch (IntNo) { 10701 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 10702 case Intrinsic::x86_avx_vtestz_ps: 10703 case Intrinsic::x86_avx_vtestz_pd: 10704 case Intrinsic::x86_avx_vtestz_ps_256: 10705 case Intrinsic::x86_avx_vtestz_pd_256: 10706 IsTestPacked = true; // Fallthrough 10707 case Intrinsic::x86_sse41_ptestz: 10708 case Intrinsic::x86_avx_ptestz_256: 10709 // ZF = 1 10710 X86CC = X86::COND_E; 10711 break; 10712 case Intrinsic::x86_avx_vtestc_ps: 10713 case Intrinsic::x86_avx_vtestc_pd: 10714 case Intrinsic::x86_avx_vtestc_ps_256: 10715 case Intrinsic::x86_avx_vtestc_pd_256: 10716 IsTestPacked = true; // Fallthrough 10717 case Intrinsic::x86_sse41_ptestc: 10718 case Intrinsic::x86_avx_ptestc_256: 10719 // CF = 1 10720 X86CC = X86::COND_B; 10721 break; 10722 case Intrinsic::x86_avx_vtestnzc_ps: 10723 case Intrinsic::x86_avx_vtestnzc_pd: 10724 case Intrinsic::x86_avx_vtestnzc_ps_256: 10725 case Intrinsic::x86_avx_vtestnzc_pd_256: 10726 IsTestPacked = true; // Fallthrough 10727 case Intrinsic::x86_sse41_ptestnzc: 10728 case Intrinsic::x86_avx_ptestnzc_256: 10729 // ZF and CF = 0 10730 X86CC = X86::COND_A; 10731 break; 10732 } 10733 10734 SDValue LHS = Op.getOperand(1); 10735 SDValue RHS = Op.getOperand(2); 10736 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 10737 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 10738 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 10739 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 10740 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10741 } 10742 10743 // SSE/AVX shift intrinsics 10744 case Intrinsic::x86_sse2_psll_w: 10745 case Intrinsic::x86_sse2_psll_d: 10746 case Intrinsic::x86_sse2_psll_q: 10747 case Intrinsic::x86_avx2_psll_w: 10748 case Intrinsic::x86_avx2_psll_d: 10749 case Intrinsic::x86_avx2_psll_q: 10750 case Intrinsic::x86_sse2_psrl_w: 10751 case Intrinsic::x86_sse2_psrl_d: 10752 case Intrinsic::x86_sse2_psrl_q: 10753 case Intrinsic::x86_avx2_psrl_w: 10754 case Intrinsic::x86_avx2_psrl_d: 10755 case Intrinsic::x86_avx2_psrl_q: 10756 case Intrinsic::x86_sse2_psra_w: 10757 case Intrinsic::x86_sse2_psra_d: 10758 case Intrinsic::x86_avx2_psra_w: 10759 case Intrinsic::x86_avx2_psra_d: { 10760 unsigned Opcode; 10761 switch (IntNo) { 10762 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10763 case Intrinsic::x86_sse2_psll_w: 10764 case Intrinsic::x86_sse2_psll_d: 10765 case Intrinsic::x86_sse2_psll_q: 10766 case Intrinsic::x86_avx2_psll_w: 10767 case Intrinsic::x86_avx2_psll_d: 10768 case Intrinsic::x86_avx2_psll_q: 10769 Opcode = X86ISD::VSHL; 10770 break; 10771 case Intrinsic::x86_sse2_psrl_w: 10772 case Intrinsic::x86_sse2_psrl_d: 10773 case Intrinsic::x86_sse2_psrl_q: 10774 case Intrinsic::x86_avx2_psrl_w: 10775 case Intrinsic::x86_avx2_psrl_d: 10776 case Intrinsic::x86_avx2_psrl_q: 10777 Opcode = X86ISD::VSRL; 10778 break; 10779 case Intrinsic::x86_sse2_psra_w: 10780 case Intrinsic::x86_sse2_psra_d: 10781 case Intrinsic::x86_avx2_psra_w: 10782 case Intrinsic::x86_avx2_psra_d: 10783 Opcode = X86ISD::VSRA; 10784 break; 10785 } 10786 return DAG.getNode(Opcode, dl, Op.getValueType(), 10787 Op.getOperand(1), Op.getOperand(2)); 10788 } 10789 10790 // SSE/AVX immediate shift intrinsics 10791 case Intrinsic::x86_sse2_pslli_w: 10792 case Intrinsic::x86_sse2_pslli_d: 10793 case Intrinsic::x86_sse2_pslli_q: 10794 case Intrinsic::x86_avx2_pslli_w: 10795 case Intrinsic::x86_avx2_pslli_d: 10796 case Intrinsic::x86_avx2_pslli_q: 10797 case Intrinsic::x86_sse2_psrli_w: 10798 case Intrinsic::x86_sse2_psrli_d: 10799 case Intrinsic::x86_sse2_psrli_q: 10800 case Intrinsic::x86_avx2_psrli_w: 10801 case Intrinsic::x86_avx2_psrli_d: 10802 case Intrinsic::x86_avx2_psrli_q: 10803 case Intrinsic::x86_sse2_psrai_w: 10804 case Intrinsic::x86_sse2_psrai_d: 10805 case Intrinsic::x86_avx2_psrai_w: 10806 case Intrinsic::x86_avx2_psrai_d: { 10807 unsigned Opcode; 10808 switch (IntNo) { 10809 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10810 case Intrinsic::x86_sse2_pslli_w: 10811 case Intrinsic::x86_sse2_pslli_d: 10812 case Intrinsic::x86_sse2_pslli_q: 10813 case Intrinsic::x86_avx2_pslli_w: 10814 case Intrinsic::x86_avx2_pslli_d: 10815 case Intrinsic::x86_avx2_pslli_q: 10816 Opcode = X86ISD::VSHLI; 10817 break; 10818 case Intrinsic::x86_sse2_psrli_w: 10819 case Intrinsic::x86_sse2_psrli_d: 10820 case Intrinsic::x86_sse2_psrli_q: 10821 case Intrinsic::x86_avx2_psrli_w: 10822 case Intrinsic::x86_avx2_psrli_d: 10823 case Intrinsic::x86_avx2_psrli_q: 10824 Opcode = X86ISD::VSRLI; 10825 break; 10826 case Intrinsic::x86_sse2_psrai_w: 10827 case Intrinsic::x86_sse2_psrai_d: 10828 case Intrinsic::x86_avx2_psrai_w: 10829 case Intrinsic::x86_avx2_psrai_d: 10830 Opcode = X86ISD::VSRAI; 10831 break; 10832 } 10833 return getTargetVShiftNode(Opcode, dl, Op.getValueType(), 10834 Op.getOperand(1), Op.getOperand(2), DAG); 10835 } 10836 10837 case Intrinsic::x86_sse42_pcmpistria128: 10838 case Intrinsic::x86_sse42_pcmpestria128: 10839 case Intrinsic::x86_sse42_pcmpistric128: 10840 case Intrinsic::x86_sse42_pcmpestric128: 10841 case Intrinsic::x86_sse42_pcmpistrio128: 10842 case Intrinsic::x86_sse42_pcmpestrio128: 10843 case Intrinsic::x86_sse42_pcmpistris128: 10844 case Intrinsic::x86_sse42_pcmpestris128: 10845 case Intrinsic::x86_sse42_pcmpistriz128: 10846 case Intrinsic::x86_sse42_pcmpestriz128: { 10847 unsigned Opcode; 10848 unsigned X86CC; 10849 switch (IntNo) { 10850 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10851 case Intrinsic::x86_sse42_pcmpistria128: 10852 Opcode = X86ISD::PCMPISTRI; 10853 X86CC = X86::COND_A; 10854 break; 10855 case Intrinsic::x86_sse42_pcmpestria128: 10856 Opcode = X86ISD::PCMPESTRI; 10857 X86CC = X86::COND_A; 10858 break; 10859 case Intrinsic::x86_sse42_pcmpistric128: 10860 Opcode = X86ISD::PCMPISTRI; 10861 X86CC = X86::COND_B; 10862 break; 10863 case Intrinsic::x86_sse42_pcmpestric128: 10864 Opcode = X86ISD::PCMPESTRI; 10865 X86CC = X86::COND_B; 10866 break; 10867 case Intrinsic::x86_sse42_pcmpistrio128: 10868 Opcode = X86ISD::PCMPISTRI; 10869 X86CC = X86::COND_O; 10870 break; 10871 case Intrinsic::x86_sse42_pcmpestrio128: 10872 Opcode = X86ISD::PCMPESTRI; 10873 X86CC = X86::COND_O; 10874 break; 10875 case Intrinsic::x86_sse42_pcmpistris128: 10876 Opcode = X86ISD::PCMPISTRI; 10877 X86CC = X86::COND_S; 10878 break; 10879 case Intrinsic::x86_sse42_pcmpestris128: 10880 Opcode = X86ISD::PCMPESTRI; 10881 X86CC = X86::COND_S; 10882 break; 10883 case Intrinsic::x86_sse42_pcmpistriz128: 10884 Opcode = X86ISD::PCMPISTRI; 10885 X86CC = X86::COND_E; 10886 break; 10887 case Intrinsic::x86_sse42_pcmpestriz128: 10888 Opcode = X86ISD::PCMPESTRI; 10889 X86CC = X86::COND_E; 10890 break; 10891 } 10892 SmallVector<SDValue, 5> NewOps; 10893 NewOps.append(Op->op_begin()+1, Op->op_end()); 10894 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 10895 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 10896 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 10897 DAG.getConstant(X86CC, MVT::i8), 10898 SDValue(PCMP.getNode(), 1)); 10899 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10900 } 10901 10902 case Intrinsic::x86_sse42_pcmpistri128: 10903 case Intrinsic::x86_sse42_pcmpestri128: { 10904 unsigned Opcode; 10905 if (IntNo == Intrinsic::x86_sse42_pcmpistri128) 10906 Opcode = X86ISD::PCMPISTRI; 10907 else 10908 Opcode = X86ISD::PCMPESTRI; 10909 10910 SmallVector<SDValue, 5> NewOps; 10911 NewOps.append(Op->op_begin()+1, Op->op_end()); 10912 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 10913 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 10914 } 10915 case Intrinsic::x86_fma_vfmadd_ps: 10916 case Intrinsic::x86_fma_vfmadd_pd: 10917 case Intrinsic::x86_fma_vfmsub_ps: 10918 case Intrinsic::x86_fma_vfmsub_pd: 10919 case Intrinsic::x86_fma_vfnmadd_ps: 10920 case Intrinsic::x86_fma_vfnmadd_pd: 10921 case Intrinsic::x86_fma_vfnmsub_ps: 10922 case Intrinsic::x86_fma_vfnmsub_pd: 10923 case Intrinsic::x86_fma_vfmaddsub_ps: 10924 case Intrinsic::x86_fma_vfmaddsub_pd: 10925 case Intrinsic::x86_fma_vfmsubadd_ps: 10926 case Intrinsic::x86_fma_vfmsubadd_pd: 10927 case Intrinsic::x86_fma_vfmadd_ps_256: 10928 case Intrinsic::x86_fma_vfmadd_pd_256: 10929 case Intrinsic::x86_fma_vfmsub_ps_256: 10930 case Intrinsic::x86_fma_vfmsub_pd_256: 10931 case Intrinsic::x86_fma_vfnmadd_ps_256: 10932 case Intrinsic::x86_fma_vfnmadd_pd_256: 10933 case Intrinsic::x86_fma_vfnmsub_ps_256: 10934 case Intrinsic::x86_fma_vfnmsub_pd_256: 10935 case Intrinsic::x86_fma_vfmaddsub_ps_256: 10936 case Intrinsic::x86_fma_vfmaddsub_pd_256: 10937 case Intrinsic::x86_fma_vfmsubadd_ps_256: 10938 case Intrinsic::x86_fma_vfmsubadd_pd_256: { 10939 unsigned Opc; 10940 switch (IntNo) { 10941 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10942 case Intrinsic::x86_fma_vfmadd_ps: 10943 case Intrinsic::x86_fma_vfmadd_pd: 10944 case Intrinsic::x86_fma_vfmadd_ps_256: 10945 case Intrinsic::x86_fma_vfmadd_pd_256: 10946 Opc = X86ISD::FMADD; 10947 break; 10948 case Intrinsic::x86_fma_vfmsub_ps: 10949 case Intrinsic::x86_fma_vfmsub_pd: 10950 case Intrinsic::x86_fma_vfmsub_ps_256: 10951 case Intrinsic::x86_fma_vfmsub_pd_256: 10952 Opc = X86ISD::FMSUB; 10953 break; 10954 case Intrinsic::x86_fma_vfnmadd_ps: 10955 case Intrinsic::x86_fma_vfnmadd_pd: 10956 case Intrinsic::x86_fma_vfnmadd_ps_256: 10957 case Intrinsic::x86_fma_vfnmadd_pd_256: 10958 Opc = X86ISD::FNMADD; 10959 break; 10960 case Intrinsic::x86_fma_vfnmsub_ps: 10961 case Intrinsic::x86_fma_vfnmsub_pd: 10962 case Intrinsic::x86_fma_vfnmsub_ps_256: 10963 case Intrinsic::x86_fma_vfnmsub_pd_256: 10964 Opc = X86ISD::FNMSUB; 10965 break; 10966 case Intrinsic::x86_fma_vfmaddsub_ps: 10967 case Intrinsic::x86_fma_vfmaddsub_pd: 10968 case Intrinsic::x86_fma_vfmaddsub_ps_256: 10969 case Intrinsic::x86_fma_vfmaddsub_pd_256: 10970 Opc = X86ISD::FMADDSUB; 10971 break; 10972 case Intrinsic::x86_fma_vfmsubadd_ps: 10973 case Intrinsic::x86_fma_vfmsubadd_pd: 10974 case Intrinsic::x86_fma_vfmsubadd_ps_256: 10975 case Intrinsic::x86_fma_vfmsubadd_pd_256: 10976 Opc = X86ISD::FMSUBADD; 10977 break; 10978 } 10979 10980 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1), 10981 Op.getOperand(2), Op.getOperand(3)); 10982 } 10983 } 10984 } 10985 10986 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) { 10987 SDLoc dl(Op); 10988 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10989 switch (IntNo) { 10990 default: return SDValue(); // Don't custom lower most intrinsics. 10991 10992 // RDRAND/RDSEED intrinsics. 10993 case Intrinsic::x86_rdrand_16: 10994 case Intrinsic::x86_rdrand_32: 10995 case Intrinsic::x86_rdrand_64: 10996 case Intrinsic::x86_rdseed_16: 10997 case Intrinsic::x86_rdseed_32: 10998 case Intrinsic::x86_rdseed_64: { 10999 unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 || 11000 IntNo == Intrinsic::x86_rdseed_32 || 11001 IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED : 11002 X86ISD::RDRAND; 11003 // Emit the node with the right value type. 11004 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other); 11005 SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0)); 11006 11007 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1. 11008 // Otherwise return the value from Rand, which is always 0, casted to i32. 11009 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)), 11010 DAG.getConstant(1, Op->getValueType(1)), 11011 DAG.getConstant(X86::COND_B, MVT::i32), 11012 SDValue(Result.getNode(), 1) }; 11013 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, 11014 DAG.getVTList(Op->getValueType(1), MVT::Glue), 11015 Ops, array_lengthof(Ops)); 11016 11017 // Return { result, isValid, chain }. 11018 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid, 11019 SDValue(Result.getNode(), 2)); 11020 } 11021 11022 // XTEST intrinsics. 11023 case Intrinsic::x86_xtest: { 11024 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other); 11025 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0)); 11026 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 11027 DAG.getConstant(X86::COND_NE, MVT::i8), 11028 InTrans); 11029 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC); 11030 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), 11031 Ret, SDValue(InTrans.getNode(), 1)); 11032 } 11033 } 11034 } 11035 11036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 11037 SelectionDAG &DAG) const { 11038 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11039 MFI->setReturnAddressIsTaken(true); 11040 11041 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11042 SDLoc dl(Op); 11043 EVT PtrVT = getPointerTy(); 11044 11045 if (Depth > 0) { 11046 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 11047 const X86RegisterInfo *RegInfo = 11048 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11049 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT); 11050 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 11051 DAG.getNode(ISD::ADD, dl, PtrVT, 11052 FrameAddr, Offset), 11053 MachinePointerInfo(), false, false, false, 0); 11054 } 11055 11056 // Just load the return address. 11057 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 11058 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 11059 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 11060 } 11061 11062 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 11063 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 11064 MFI->setFrameAddressIsTaken(true); 11065 11066 EVT VT = Op.getValueType(); 11067 SDLoc dl(Op); // FIXME probably not meaningful 11068 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 11069 const X86RegisterInfo *RegInfo = 11070 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11071 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction()); 11072 assert(((FrameReg == X86::RBP && VT == MVT::i64) || 11073 (FrameReg == X86::EBP && VT == MVT::i32)) && 11074 "Invalid Frame Register!"); 11075 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 11076 while (Depth--) 11077 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 11078 MachinePointerInfo(), 11079 false, false, false, 0); 11080 return FrameAddr; 11081 } 11082 11083 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 11084 SelectionDAG &DAG) const { 11085 const X86RegisterInfo *RegInfo = 11086 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11087 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize()); 11088 } 11089 11090 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 11091 SDValue Chain = Op.getOperand(0); 11092 SDValue Offset = Op.getOperand(1); 11093 SDValue Handler = Op.getOperand(2); 11094 SDLoc dl (Op); 11095 11096 EVT PtrVT = getPointerTy(); 11097 const X86RegisterInfo *RegInfo = 11098 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 11099 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction()); 11100 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) || 11101 (FrameReg == X86::EBP && PtrVT == MVT::i32)) && 11102 "Invalid Frame Register!"); 11103 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT); 11104 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX; 11105 11106 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame, 11107 DAG.getIntPtrConstant(RegInfo->getSlotSize())); 11108 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset); 11109 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 11110 false, false, 0); 11111 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 11112 11113 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain, 11114 DAG.getRegister(StoreAddrReg, PtrVT)); 11115 } 11116 11117 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 11118 SelectionDAG &DAG) const { 11119 SDLoc DL(Op); 11120 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL, 11121 DAG.getVTList(MVT::i32, MVT::Other), 11122 Op.getOperand(0), Op.getOperand(1)); 11123 } 11124 11125 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 11126 SelectionDAG &DAG) const { 11127 SDLoc DL(Op); 11128 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 11129 Op.getOperand(0), Op.getOperand(1)); 11130 } 11131 11132 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) { 11133 return Op.getOperand(0); 11134 } 11135 11136 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 11137 SelectionDAG &DAG) const { 11138 SDValue Root = Op.getOperand(0); 11139 SDValue Trmp = Op.getOperand(1); // trampoline 11140 SDValue FPtr = Op.getOperand(2); // nested function 11141 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 11142 SDLoc dl (Op); 11143 11144 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 11145 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 11146 11147 if (Subtarget->is64Bit()) { 11148 SDValue OutChains[6]; 11149 11150 // Large code-model. 11151 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 11152 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 11153 11154 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7; 11155 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7; 11156 11157 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 11158 11159 // Load the pointer to the nested function into R11. 11160 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 11161 SDValue Addr = Trmp; 11162 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11163 Addr, MachinePointerInfo(TrmpAddr), 11164 false, false, 0); 11165 11166 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11167 DAG.getConstant(2, MVT::i64)); 11168 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 11169 MachinePointerInfo(TrmpAddr, 2), 11170 false, false, 2); 11171 11172 // Load the 'nest' parameter value into R10. 11173 // R10 is specified in X86CallingConv.td 11174 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 11175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11176 DAG.getConstant(10, MVT::i64)); 11177 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11178 Addr, MachinePointerInfo(TrmpAddr, 10), 11179 false, false, 0); 11180 11181 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11182 DAG.getConstant(12, MVT::i64)); 11183 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 11184 MachinePointerInfo(TrmpAddr, 12), 11185 false, false, 2); 11186 11187 // Jump to the nested function. 11188 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 11189 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11190 DAG.getConstant(20, MVT::i64)); 11191 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11192 Addr, MachinePointerInfo(TrmpAddr, 20), 11193 false, false, 0); 11194 11195 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 11196 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11197 DAG.getConstant(22, MVT::i64)); 11198 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 11199 MachinePointerInfo(TrmpAddr, 22), 11200 false, false, 0); 11201 11202 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 11203 } else { 11204 const Function *Func = 11205 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 11206 CallingConv::ID CC = Func->getCallingConv(); 11207 unsigned NestReg; 11208 11209 switch (CC) { 11210 default: 11211 llvm_unreachable("Unsupported calling convention"); 11212 case CallingConv::C: 11213 case CallingConv::X86_StdCall: { 11214 // Pass 'nest' parameter in ECX. 11215 // Must be kept in sync with X86CallingConv.td 11216 NestReg = X86::ECX; 11217 11218 // Check that ECX wasn't needed by an 'inreg' parameter. 11219 FunctionType *FTy = Func->getFunctionType(); 11220 const AttributeSet &Attrs = Func->getAttributes(); 11221 11222 if (!Attrs.isEmpty() && !Func->isVarArg()) { 11223 unsigned InRegCount = 0; 11224 unsigned Idx = 1; 11225 11226 for (FunctionType::param_iterator I = FTy->param_begin(), 11227 E = FTy->param_end(); I != E; ++I, ++Idx) 11228 if (Attrs.hasAttribute(Idx, Attribute::InReg)) 11229 // FIXME: should only count parameters that are lowered to integers. 11230 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 11231 11232 if (InRegCount > 2) { 11233 report_fatal_error("Nest register in use - reduce number of inreg" 11234 " parameters!"); 11235 } 11236 } 11237 break; 11238 } 11239 case CallingConv::X86_FastCall: 11240 case CallingConv::X86_ThisCall: 11241 case CallingConv::Fast: 11242 // Pass 'nest' parameter in EAX. 11243 // Must be kept in sync with X86CallingConv.td 11244 NestReg = X86::EAX; 11245 break; 11246 } 11247 11248 SDValue OutChains[4]; 11249 SDValue Addr, Disp; 11250 11251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11252 DAG.getConstant(10, MVT::i32)); 11253 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 11254 11255 // This is storing the opcode for MOV32ri. 11256 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 11257 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7; 11258 OutChains[0] = DAG.getStore(Root, dl, 11259 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 11260 Trmp, MachinePointerInfo(TrmpAddr), 11261 false, false, 0); 11262 11263 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11264 DAG.getConstant(1, MVT::i32)); 11265 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 11266 MachinePointerInfo(TrmpAddr, 1), 11267 false, false, 1); 11268 11269 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 11270 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11271 DAG.getConstant(5, MVT::i32)); 11272 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 11273 MachinePointerInfo(TrmpAddr, 5), 11274 false, false, 1); 11275 11276 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11277 DAG.getConstant(6, MVT::i32)); 11278 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 11279 MachinePointerInfo(TrmpAddr, 6), 11280 false, false, 1); 11281 11282 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 11283 } 11284 } 11285 11286 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 11287 SelectionDAG &DAG) const { 11288 /* 11289 The rounding mode is in bits 11:10 of FPSR, and has the following 11290 settings: 11291 00 Round to nearest 11292 01 Round to -inf 11293 10 Round to +inf 11294 11 Round to 0 11295 11296 FLT_ROUNDS, on the other hand, expects the following: 11297 -1 Undefined 11298 0 Round to 0 11299 1 Round to nearest 11300 2 Round to +inf 11301 3 Round to -inf 11302 11303 To perform the conversion, we do: 11304 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 11305 */ 11306 11307 MachineFunction &MF = DAG.getMachineFunction(); 11308 const TargetMachine &TM = MF.getTarget(); 11309 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 11310 unsigned StackAlignment = TFI.getStackAlignment(); 11311 EVT VT = Op.getValueType(); 11312 SDLoc DL(Op); 11313 11314 // Save FP Control Word to stack slot 11315 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 11316 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 11317 11318 MachineMemOperand *MMO = 11319 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 11320 MachineMemOperand::MOStore, 2, 2); 11321 11322 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 11323 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 11324 DAG.getVTList(MVT::Other), 11325 Ops, array_lengthof(Ops), MVT::i16, 11326 MMO); 11327 11328 // Load FP Control Word from stack slot 11329 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 11330 MachinePointerInfo(), false, false, false, 0); 11331 11332 // Transform as necessary 11333 SDValue CWD1 = 11334 DAG.getNode(ISD::SRL, DL, MVT::i16, 11335 DAG.getNode(ISD::AND, DL, MVT::i16, 11336 CWD, DAG.getConstant(0x800, MVT::i16)), 11337 DAG.getConstant(11, MVT::i8)); 11338 SDValue CWD2 = 11339 DAG.getNode(ISD::SRL, DL, MVT::i16, 11340 DAG.getNode(ISD::AND, DL, MVT::i16, 11341 CWD, DAG.getConstant(0x400, MVT::i16)), 11342 DAG.getConstant(9, MVT::i8)); 11343 11344 SDValue RetVal = 11345 DAG.getNode(ISD::AND, DL, MVT::i16, 11346 DAG.getNode(ISD::ADD, DL, MVT::i16, 11347 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 11348 DAG.getConstant(1, MVT::i16)), 11349 DAG.getConstant(3, MVT::i16)); 11350 11351 return DAG.getNode((VT.getSizeInBits() < 16 ? 11352 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 11353 } 11354 11355 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) { 11356 EVT VT = Op.getValueType(); 11357 EVT OpVT = VT; 11358 unsigned NumBits = VT.getSizeInBits(); 11359 SDLoc dl(Op); 11360 11361 Op = Op.getOperand(0); 11362 if (VT == MVT::i8) { 11363 // Zero extend to i32 since there is not an i8 bsr. 11364 OpVT = MVT::i32; 11365 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11366 } 11367 11368 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 11369 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11370 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11371 11372 // If src is zero (i.e. bsr sets ZF), returns NumBits. 11373 SDValue Ops[] = { 11374 Op, 11375 DAG.getConstant(NumBits+NumBits-1, OpVT), 11376 DAG.getConstant(X86::COND_E, MVT::i8), 11377 Op.getValue(1) 11378 }; 11379 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 11380 11381 // Finally xor with NumBits-1. 11382 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11383 11384 if (VT == MVT::i8) 11385 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11386 return Op; 11387 } 11388 11389 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 11390 EVT VT = Op.getValueType(); 11391 EVT OpVT = VT; 11392 unsigned NumBits = VT.getSizeInBits(); 11393 SDLoc dl(Op); 11394 11395 Op = Op.getOperand(0); 11396 if (VT == MVT::i8) { 11397 // Zero extend to i32 since there is not an i8 bsr. 11398 OpVT = MVT::i32; 11399 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11400 } 11401 11402 // Issue a bsr (scan bits in reverse). 11403 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11404 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11405 11406 // And xor with NumBits-1. 11407 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11408 11409 if (VT == MVT::i8) 11410 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11411 return Op; 11412 } 11413 11414 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) { 11415 EVT VT = Op.getValueType(); 11416 unsigned NumBits = VT.getSizeInBits(); 11417 SDLoc dl(Op); 11418 Op = Op.getOperand(0); 11419 11420 // Issue a bsf (scan bits forward) which also sets EFLAGS. 11421 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 11422 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 11423 11424 // If src is zero (i.e. bsf sets ZF), returns NumBits. 11425 SDValue Ops[] = { 11426 Op, 11427 DAG.getConstant(NumBits, VT), 11428 DAG.getConstant(X86::COND_E, MVT::i8), 11429 Op.getValue(1) 11430 }; 11431 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops)); 11432 } 11433 11434 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 11435 // ones, and then concatenate the result back. 11436 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 11437 EVT VT = Op.getValueType(); 11438 11439 assert(VT.is256BitVector() && VT.isInteger() && 11440 "Unsupported value type for operation"); 11441 11442 unsigned NumElems = VT.getVectorNumElements(); 11443 SDLoc dl(Op); 11444 11445 // Extract the LHS vectors 11446 SDValue LHS = Op.getOperand(0); 11447 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 11448 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 11449 11450 // Extract the RHS vectors 11451 SDValue RHS = Op.getOperand(1); 11452 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 11453 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 11454 11455 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11456 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11457 11458 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 11459 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 11460 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 11461 } 11462 11463 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) { 11464 assert(Op.getValueType().is256BitVector() && 11465 Op.getValueType().isInteger() && 11466 "Only handle AVX 256-bit vector integer operation"); 11467 return Lower256IntArith(Op, DAG); 11468 } 11469 11470 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) { 11471 assert(Op.getValueType().is256BitVector() && 11472 Op.getValueType().isInteger() && 11473 "Only handle AVX 256-bit vector integer operation"); 11474 return Lower256IntArith(Op, DAG); 11475 } 11476 11477 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget, 11478 SelectionDAG &DAG) { 11479 SDLoc dl(Op); 11480 EVT VT = Op.getValueType(); 11481 11482 // Decompose 256-bit ops into smaller 128-bit ops. 11483 if (VT.is256BitVector() && !Subtarget->hasInt256()) 11484 return Lower256IntArith(Op, DAG); 11485 11486 SDValue A = Op.getOperand(0); 11487 SDValue B = Op.getOperand(1); 11488 11489 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle. 11490 if (VT == MVT::v4i32) { 11491 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() && 11492 "Should not custom lower when pmuldq is available!"); 11493 11494 // Extract the odd parts. 11495 const int UnpackMask[] = { 1, -1, 3, -1 }; 11496 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask); 11497 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask); 11498 11499 // Multiply the even parts. 11500 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B); 11501 // Now multiply odd parts. 11502 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds); 11503 11504 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens); 11505 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds); 11506 11507 // Merge the two vectors back together with a shuffle. This expands into 2 11508 // shuffles. 11509 const int ShufMask[] = { 0, 4, 2, 6 }; 11510 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask); 11511 } 11512 11513 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && 11514 "Only know how to lower V2I64/V4I64 multiply"); 11515 11516 // Ahi = psrlqi(a, 32); 11517 // Bhi = psrlqi(b, 32); 11518 // 11519 // AloBlo = pmuludq(a, b); 11520 // AloBhi = pmuludq(a, Bhi); 11521 // AhiBlo = pmuludq(Ahi, b); 11522 11523 // AloBhi = psllqi(AloBhi, 32); 11524 // AhiBlo = psllqi(AhiBlo, 32); 11525 // return AloBlo + AloBhi + AhiBlo; 11526 11527 SDValue ShAmt = DAG.getConstant(32, MVT::i32); 11528 11529 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt); 11530 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt); 11531 11532 // Bit cast to 32-bit vectors for MULUDQ 11533 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32; 11534 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A); 11535 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B); 11536 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi); 11537 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi); 11538 11539 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B); 11540 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi); 11541 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B); 11542 11543 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt); 11544 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt); 11545 11546 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 11547 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 11548 } 11549 11550 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const { 11551 EVT VT = Op.getValueType(); 11552 EVT EltTy = VT.getVectorElementType(); 11553 unsigned NumElts = VT.getVectorNumElements(); 11554 SDValue N0 = Op.getOperand(0); 11555 SDLoc dl(Op); 11556 11557 // Lower sdiv X, pow2-const. 11558 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1)); 11559 if (!C) 11560 return SDValue(); 11561 11562 APInt SplatValue, SplatUndef; 11563 unsigned MinSplatBits; 11564 bool HasAnyUndefs; 11565 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs)) 11566 return SDValue(); 11567 11568 if ((SplatValue != 0) && 11569 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) { 11570 unsigned lg2 = SplatValue.countTrailingZeros(); 11571 // Splat the sign bit. 11572 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32); 11573 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG); 11574 // Add (N0 < 0) ? abs2 - 1 : 0; 11575 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32); 11576 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG); 11577 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL); 11578 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32); 11579 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG); 11580 11581 // If we're dividing by a positive value, we're done. Otherwise, we must 11582 // negate the result. 11583 if (SplatValue.isNonNegative()) 11584 return SRA; 11585 11586 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy)); 11587 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts); 11588 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA); 11589 } 11590 return SDValue(); 11591 } 11592 11593 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG, 11594 const X86Subtarget *Subtarget) { 11595 EVT VT = Op.getValueType(); 11596 SDLoc dl(Op); 11597 SDValue R = Op.getOperand(0); 11598 SDValue Amt = Op.getOperand(1); 11599 11600 // Optimize shl/srl/sra with constant shift amount. 11601 if (isSplatVector(Amt.getNode())) { 11602 SDValue SclrAmt = Amt->getOperand(0); 11603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 11604 uint64_t ShiftAmt = C->getZExtValue(); 11605 11606 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 11607 (Subtarget->hasInt256() && 11608 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) { 11609 if (Op.getOpcode() == ISD::SHL) 11610 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 11611 DAG.getConstant(ShiftAmt, MVT::i32)); 11612 if (Op.getOpcode() == ISD::SRL) 11613 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 11614 DAG.getConstant(ShiftAmt, MVT::i32)); 11615 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64) 11616 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 11617 DAG.getConstant(ShiftAmt, MVT::i32)); 11618 } 11619 11620 if (VT == MVT::v16i8) { 11621 if (Op.getOpcode() == ISD::SHL) { 11622 // Make a large shift. 11623 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R, 11624 DAG.getConstant(ShiftAmt, MVT::i32)); 11625 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 11626 // Zero out the rightmost bits. 11627 SmallVector<SDValue, 16> V(16, 11628 DAG.getConstant(uint8_t(-1U << ShiftAmt), 11629 MVT::i8)); 11630 return DAG.getNode(ISD::AND, dl, VT, SHL, 11631 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 11632 } 11633 if (Op.getOpcode() == ISD::SRL) { 11634 // Make a large shift. 11635 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R, 11636 DAG.getConstant(ShiftAmt, MVT::i32)); 11637 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 11638 // Zero out the leftmost bits. 11639 SmallVector<SDValue, 16> V(16, 11640 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 11641 MVT::i8)); 11642 return DAG.getNode(ISD::AND, dl, VT, SRL, 11643 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 11644 } 11645 if (Op.getOpcode() == ISD::SRA) { 11646 if (ShiftAmt == 7) { 11647 // R s>> 7 === R s< 0 11648 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 11649 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 11650 } 11651 11652 // R s>> a === ((R u>> a) ^ m) - m 11653 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 11654 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 11655 MVT::i8)); 11656 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 11657 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 11658 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 11659 return Res; 11660 } 11661 llvm_unreachable("Unknown shift opcode."); 11662 } 11663 11664 if (Subtarget->hasInt256() && VT == MVT::v32i8) { 11665 if (Op.getOpcode() == ISD::SHL) { 11666 // Make a large shift. 11667 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R, 11668 DAG.getConstant(ShiftAmt, MVT::i32)); 11669 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 11670 // Zero out the rightmost bits. 11671 SmallVector<SDValue, 32> V(32, 11672 DAG.getConstant(uint8_t(-1U << ShiftAmt), 11673 MVT::i8)); 11674 return DAG.getNode(ISD::AND, dl, VT, SHL, 11675 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 11676 } 11677 if (Op.getOpcode() == ISD::SRL) { 11678 // Make a large shift. 11679 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R, 11680 DAG.getConstant(ShiftAmt, MVT::i32)); 11681 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 11682 // Zero out the leftmost bits. 11683 SmallVector<SDValue, 32> V(32, 11684 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 11685 MVT::i8)); 11686 return DAG.getNode(ISD::AND, dl, VT, SRL, 11687 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 11688 } 11689 if (Op.getOpcode() == ISD::SRA) { 11690 if (ShiftAmt == 7) { 11691 // R s>> 7 === R s< 0 11692 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 11693 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 11694 } 11695 11696 // R s>> a === ((R u>> a) ^ m) - m 11697 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 11698 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt, 11699 MVT::i8)); 11700 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32); 11701 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 11702 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 11703 return Res; 11704 } 11705 llvm_unreachable("Unknown shift opcode."); 11706 } 11707 } 11708 } 11709 11710 // Special case in 32-bit mode, where i64 is expanded into high and low parts. 11711 if (!Subtarget->is64Bit() && 11712 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) && 11713 Amt.getOpcode() == ISD::BITCAST && 11714 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) { 11715 Amt = Amt.getOperand(0); 11716 unsigned Ratio = Amt.getValueType().getVectorNumElements() / 11717 VT.getVectorNumElements(); 11718 unsigned RatioInLog2 = Log2_32_Ceil(Ratio); 11719 uint64_t ShiftAmt = 0; 11720 for (unsigned i = 0; i != Ratio; ++i) { 11721 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i)); 11722 if (C == 0) 11723 return SDValue(); 11724 // 6 == Log2(64) 11725 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2))); 11726 } 11727 // Check remaining shift amounts. 11728 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) { 11729 uint64_t ShAmt = 0; 11730 for (unsigned j = 0; j != Ratio; ++j) { 11731 ConstantSDNode *C = 11732 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j)); 11733 if (C == 0) 11734 return SDValue(); 11735 // 6 == Log2(64) 11736 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2))); 11737 } 11738 if (ShAmt != ShiftAmt) 11739 return SDValue(); 11740 } 11741 switch (Op.getOpcode()) { 11742 default: 11743 llvm_unreachable("Unknown shift opcode!"); 11744 case ISD::SHL: 11745 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 11746 DAG.getConstant(ShiftAmt, MVT::i32)); 11747 case ISD::SRL: 11748 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 11749 DAG.getConstant(ShiftAmt, MVT::i32)); 11750 case ISD::SRA: 11751 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 11752 DAG.getConstant(ShiftAmt, MVT::i32)); 11753 } 11754 } 11755 11756 return SDValue(); 11757 } 11758 11759 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG, 11760 const X86Subtarget* Subtarget) { 11761 EVT VT = Op.getValueType(); 11762 SDLoc dl(Op); 11763 SDValue R = Op.getOperand(0); 11764 SDValue Amt = Op.getOperand(1); 11765 11766 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) || 11767 VT == MVT::v4i32 || VT == MVT::v8i16 || 11768 (Subtarget->hasInt256() && 11769 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) || 11770 VT == MVT::v8i32 || VT == MVT::v16i16))) { 11771 SDValue BaseShAmt; 11772 EVT EltVT = VT.getVectorElementType(); 11773 11774 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 11775 unsigned NumElts = VT.getVectorNumElements(); 11776 unsigned i, j; 11777 for (i = 0; i != NumElts; ++i) { 11778 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF) 11779 continue; 11780 break; 11781 } 11782 for (j = i; j != NumElts; ++j) { 11783 SDValue Arg = Amt.getOperand(j); 11784 if (Arg.getOpcode() == ISD::UNDEF) continue; 11785 if (Arg != Amt.getOperand(i)) 11786 break; 11787 } 11788 if (i != NumElts && j == NumElts) 11789 BaseShAmt = Amt.getOperand(i); 11790 } else { 11791 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR) 11792 Amt = Amt.getOperand(0); 11793 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE && 11794 cast<ShuffleVectorSDNode>(Amt)->isSplat()) { 11795 SDValue InVec = Amt.getOperand(0); 11796 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 11797 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 11798 unsigned i = 0; 11799 for (; i != NumElts; ++i) { 11800 SDValue Arg = InVec.getOperand(i); 11801 if (Arg.getOpcode() == ISD::UNDEF) continue; 11802 BaseShAmt = Arg; 11803 break; 11804 } 11805 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 11806 if (ConstantSDNode *C = 11807 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 11808 unsigned SplatIdx = 11809 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex(); 11810 if (C->getZExtValue() == SplatIdx) 11811 BaseShAmt = InVec.getOperand(1); 11812 } 11813 } 11814 if (BaseShAmt.getNode() == 0) 11815 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt, 11816 DAG.getIntPtrConstant(0)); 11817 } 11818 } 11819 11820 if (BaseShAmt.getNode()) { 11821 if (EltVT.bitsGT(MVT::i32)) 11822 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt); 11823 else if (EltVT.bitsLT(MVT::i32)) 11824 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt); 11825 11826 switch (Op.getOpcode()) { 11827 default: 11828 llvm_unreachable("Unknown shift opcode!"); 11829 case ISD::SHL: 11830 switch (VT.getSimpleVT().SimpleTy) { 11831 default: return SDValue(); 11832 case MVT::v2i64: 11833 case MVT::v4i32: 11834 case MVT::v8i16: 11835 case MVT::v4i64: 11836 case MVT::v8i32: 11837 case MVT::v16i16: 11838 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG); 11839 } 11840 case ISD::SRA: 11841 switch (VT.getSimpleVT().SimpleTy) { 11842 default: return SDValue(); 11843 case MVT::v4i32: 11844 case MVT::v8i16: 11845 case MVT::v8i32: 11846 case MVT::v16i16: 11847 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG); 11848 } 11849 case ISD::SRL: 11850 switch (VT.getSimpleVT().SimpleTy) { 11851 default: return SDValue(); 11852 case MVT::v2i64: 11853 case MVT::v4i32: 11854 case MVT::v8i16: 11855 case MVT::v4i64: 11856 case MVT::v8i32: 11857 case MVT::v16i16: 11858 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG); 11859 } 11860 } 11861 } 11862 } 11863 11864 // Special case in 32-bit mode, where i64 is expanded into high and low parts. 11865 if (!Subtarget->is64Bit() && 11866 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) && 11867 Amt.getOpcode() == ISD::BITCAST && 11868 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) { 11869 Amt = Amt.getOperand(0); 11870 unsigned Ratio = Amt.getValueType().getVectorNumElements() / 11871 VT.getVectorNumElements(); 11872 std::vector<SDValue> Vals(Ratio); 11873 for (unsigned i = 0; i != Ratio; ++i) 11874 Vals[i] = Amt.getOperand(i); 11875 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) { 11876 for (unsigned j = 0; j != Ratio; ++j) 11877 if (Vals[j] != Amt.getOperand(i + j)) 11878 return SDValue(); 11879 } 11880 switch (Op.getOpcode()) { 11881 default: 11882 llvm_unreachable("Unknown shift opcode!"); 11883 case ISD::SHL: 11884 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1)); 11885 case ISD::SRL: 11886 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1)); 11887 case ISD::SRA: 11888 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1)); 11889 } 11890 } 11891 11892 return SDValue(); 11893 } 11894 11895 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 11896 11897 EVT VT = Op.getValueType(); 11898 SDLoc dl(Op); 11899 SDValue R = Op.getOperand(0); 11900 SDValue Amt = Op.getOperand(1); 11901 SDValue V; 11902 11903 if (!Subtarget->hasSSE2()) 11904 return SDValue(); 11905 11906 V = LowerScalarImmediateShift(Op, DAG, Subtarget); 11907 if (V.getNode()) 11908 return V; 11909 11910 V = LowerScalarVariableShift(Op, DAG, Subtarget); 11911 if (V.getNode()) 11912 return V; 11913 11914 // AVX2 has VPSLLV/VPSRAV/VPSRLV. 11915 if (Subtarget->hasInt256()) { 11916 if (Op.getOpcode() == ISD::SRL && 11917 (VT == MVT::v2i64 || VT == MVT::v4i32 || 11918 VT == MVT::v4i64 || VT == MVT::v8i32)) 11919 return Op; 11920 if (Op.getOpcode() == ISD::SHL && 11921 (VT == MVT::v2i64 || VT == MVT::v4i32 || 11922 VT == MVT::v4i64 || VT == MVT::v8i32)) 11923 return Op; 11924 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32)) 11925 return Op; 11926 } 11927 11928 // Lower SHL with variable shift amount. 11929 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 11930 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT)); 11931 11932 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT)); 11933 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 11934 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 11935 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 11936 } 11937 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 11938 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq."); 11939 11940 // a = a << 5; 11941 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT)); 11942 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op); 11943 11944 // Turn 'a' into a mask suitable for VSELECT 11945 SDValue VSelM = DAG.getConstant(0x80, VT); 11946 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11947 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11948 11949 SDValue CM1 = DAG.getConstant(0x0f, VT); 11950 SDValue CM2 = DAG.getConstant(0x3f, VT); 11951 11952 // r = VSELECT(r, psllw(r & (char16)15, 4), a); 11953 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1); 11954 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 11955 DAG.getConstant(4, MVT::i32), DAG); 11956 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 11957 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 11958 11959 // a += a 11960 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 11961 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11962 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11963 11964 // r = VSELECT(r, psllw(r & (char16)63, 2), a); 11965 M = DAG.getNode(ISD::AND, dl, VT, R, CM2); 11966 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 11967 DAG.getConstant(2, MVT::i32), DAG); 11968 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 11969 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 11970 11971 // a += a 11972 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 11973 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11974 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11975 11976 // return VSELECT(r, r+r, a); 11977 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, 11978 DAG.getNode(ISD::ADD, dl, VT, R, R), R); 11979 return R; 11980 } 11981 11982 // Decompose 256-bit shifts into smaller 128-bit shifts. 11983 if (VT.is256BitVector()) { 11984 unsigned NumElems = VT.getVectorNumElements(); 11985 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11986 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11987 11988 // Extract the two vectors 11989 SDValue V1 = Extract128BitVector(R, 0, DAG, dl); 11990 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl); 11991 11992 // Recreate the shift amount vectors 11993 SDValue Amt1, Amt2; 11994 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 11995 // Constant shift amount 11996 SmallVector<SDValue, 4> Amt1Csts; 11997 SmallVector<SDValue, 4> Amt2Csts; 11998 for (unsigned i = 0; i != NumElems/2; ++i) 11999 Amt1Csts.push_back(Amt->getOperand(i)); 12000 for (unsigned i = NumElems/2; i != NumElems; ++i) 12001 Amt2Csts.push_back(Amt->getOperand(i)); 12002 12003 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 12004 &Amt1Csts[0], NumElems/2); 12005 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 12006 &Amt2Csts[0], NumElems/2); 12007 } else { 12008 // Variable shift amount 12009 Amt1 = Extract128BitVector(Amt, 0, DAG, dl); 12010 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl); 12011 } 12012 12013 // Issue new vector shifts for the smaller types 12014 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 12015 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 12016 12017 // Concatenate the result back 12018 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 12019 } 12020 12021 return SDValue(); 12022 } 12023 12024 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 12025 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 12026 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 12027 // looks for this combo and may remove the "setcc" instruction if the "setcc" 12028 // has only one use. 12029 SDNode *N = Op.getNode(); 12030 SDValue LHS = N->getOperand(0); 12031 SDValue RHS = N->getOperand(1); 12032 unsigned BaseOp = 0; 12033 unsigned Cond = 0; 12034 SDLoc DL(Op); 12035 switch (Op.getOpcode()) { 12036 default: llvm_unreachable("Unknown ovf instruction!"); 12037 case ISD::SADDO: 12038 // A subtract of one will be selected as a INC. Note that INC doesn't 12039 // set CF, so we can't do this for UADDO. 12040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 12041 if (C->isOne()) { 12042 BaseOp = X86ISD::INC; 12043 Cond = X86::COND_O; 12044 break; 12045 } 12046 BaseOp = X86ISD::ADD; 12047 Cond = X86::COND_O; 12048 break; 12049 case ISD::UADDO: 12050 BaseOp = X86ISD::ADD; 12051 Cond = X86::COND_B; 12052 break; 12053 case ISD::SSUBO: 12054 // A subtract of one will be selected as a DEC. Note that DEC doesn't 12055 // set CF, so we can't do this for USUBO. 12056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 12057 if (C->isOne()) { 12058 BaseOp = X86ISD::DEC; 12059 Cond = X86::COND_O; 12060 break; 12061 } 12062 BaseOp = X86ISD::SUB; 12063 Cond = X86::COND_O; 12064 break; 12065 case ISD::USUBO: 12066 BaseOp = X86ISD::SUB; 12067 Cond = X86::COND_B; 12068 break; 12069 case ISD::SMULO: 12070 BaseOp = X86ISD::SMUL; 12071 Cond = X86::COND_O; 12072 break; 12073 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 12074 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 12075 MVT::i32); 12076 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 12077 12078 SDValue SetCC = 12079 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 12080 DAG.getConstant(X86::COND_O, MVT::i32), 12081 SDValue(Sum.getNode(), 2)); 12082 12083 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 12084 } 12085 } 12086 12087 // Also sets EFLAGS. 12088 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 12089 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 12090 12091 SDValue SetCC = 12092 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 12093 DAG.getConstant(Cond, MVT::i32), 12094 SDValue(Sum.getNode(), 1)); 12095 12096 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 12097 } 12098 12099 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 12100 SelectionDAG &DAG) const { 12101 SDLoc dl(Op); 12102 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 12103 EVT VT = Op.getValueType(); 12104 12105 if (!Subtarget->hasSSE2() || !VT.isVector()) 12106 return SDValue(); 12107 12108 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 12109 ExtraVT.getScalarType().getSizeInBits(); 12110 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 12111 12112 switch (VT.getSimpleVT().SimpleTy) { 12113 default: return SDValue(); 12114 case MVT::v8i32: 12115 case MVT::v16i16: 12116 if (!Subtarget->hasFp256()) 12117 return SDValue(); 12118 if (!Subtarget->hasInt256()) { 12119 // needs to be split 12120 unsigned NumElems = VT.getVectorNumElements(); 12121 12122 // Extract the LHS vectors 12123 SDValue LHS = Op.getOperand(0); 12124 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 12125 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 12126 12127 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 12128 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 12129 12130 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 12131 unsigned ExtraNumElems = ExtraVT.getVectorNumElements(); 12132 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT, 12133 ExtraNumElems/2); 12134 SDValue Extra = DAG.getValueType(ExtraVT); 12135 12136 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra); 12137 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra); 12138 12139 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2); 12140 } 12141 // fall through 12142 case MVT::v4i32: 12143 case MVT::v8i16: { 12144 // (sext (vzext x)) -> (vsext x) 12145 SDValue Op0 = Op.getOperand(0); 12146 SDValue Op00 = Op0.getOperand(0); 12147 SDValue Tmp1; 12148 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT. 12149 if (Op0.getOpcode() == ISD::BITCAST && 12150 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) 12151 Tmp1 = LowerVectorIntExtend(Op00, DAG); 12152 if (Tmp1.getNode()) { 12153 SDValue Tmp1Op0 = Tmp1.getOperand(0); 12154 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT && 12155 "This optimization is invalid without a VZEXT."); 12156 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0)); 12157 } 12158 12159 // If the above didn't work, then just use Shift-Left + Shift-Right. 12160 Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG); 12161 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG); 12162 } 12163 } 12164 } 12165 12166 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget, 12167 SelectionDAG &DAG) { 12168 SDLoc dl(Op); 12169 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 12170 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 12171 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 12172 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 12173 12174 // The only fence that needs an instruction is a sequentially-consistent 12175 // cross-thread fence. 12176 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 12177 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 12178 // no-sse2). There isn't any reason to disable it if the target processor 12179 // supports it. 12180 if (Subtarget->hasSSE2() || Subtarget->is64Bit()) 12181 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 12182 12183 SDValue Chain = Op.getOperand(0); 12184 SDValue Zero = DAG.getConstant(0, MVT::i32); 12185 SDValue Ops[] = { 12186 DAG.getRegister(X86::ESP, MVT::i32), // Base 12187 DAG.getTargetConstant(1, MVT::i8), // Scale 12188 DAG.getRegister(0, MVT::i32), // Index 12189 DAG.getTargetConstant(0, MVT::i32), // Disp 12190 DAG.getRegister(0, MVT::i32), // Segment. 12191 Zero, 12192 Chain 12193 }; 12194 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops); 12195 return SDValue(Res, 0); 12196 } 12197 12198 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 12199 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 12200 } 12201 12202 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget, 12203 SelectionDAG &DAG) { 12204 EVT T = Op.getValueType(); 12205 SDLoc DL(Op); 12206 unsigned Reg = 0; 12207 unsigned size = 0; 12208 switch(T.getSimpleVT().SimpleTy) { 12209 default: llvm_unreachable("Invalid value type!"); 12210 case MVT::i8: Reg = X86::AL; size = 1; break; 12211 case MVT::i16: Reg = X86::AX; size = 2; break; 12212 case MVT::i32: Reg = X86::EAX; size = 4; break; 12213 case MVT::i64: 12214 assert(Subtarget->is64Bit() && "Node not type legal!"); 12215 Reg = X86::RAX; size = 8; 12216 break; 12217 } 12218 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 12219 Op.getOperand(2), SDValue()); 12220 SDValue Ops[] = { cpIn.getValue(0), 12221 Op.getOperand(1), 12222 Op.getOperand(3), 12223 DAG.getTargetConstant(size, MVT::i8), 12224 cpIn.getValue(1) }; 12225 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12226 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 12227 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 12228 Ops, array_lengthof(Ops), T, MMO); 12229 SDValue cpOut = 12230 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 12231 return cpOut; 12232 } 12233 12234 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget, 12235 SelectionDAG &DAG) { 12236 assert(Subtarget->is64Bit() && "Result not type legalized?"); 12237 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12238 SDValue TheChain = Op.getOperand(0); 12239 SDLoc dl(Op); 12240 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 12241 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 12242 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 12243 rax.getValue(2)); 12244 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 12245 DAG.getConstant(32, MVT::i8)); 12246 SDValue Ops[] = { 12247 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 12248 rdx.getValue(1) 12249 }; 12250 return DAG.getMergeValues(Ops, array_lengthof(Ops), dl); 12251 } 12252 12253 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 12254 EVT SrcVT = Op.getOperand(0).getValueType(); 12255 EVT DstVT = Op.getValueType(); 12256 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 12257 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 12258 assert((DstVT == MVT::i64 || 12259 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 12260 "Unexpected custom BITCAST"); 12261 // i64 <=> MMX conversions are Legal. 12262 if (SrcVT==MVT::i64 && DstVT.isVector()) 12263 return Op; 12264 if (DstVT==MVT::i64 && SrcVT.isVector()) 12265 return Op; 12266 // MMX <=> MMX conversions are Legal. 12267 if (SrcVT.isVector() && DstVT.isVector()) 12268 return Op; 12269 // All other conversions need to be expanded. 12270 return SDValue(); 12271 } 12272 12273 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) { 12274 SDNode *Node = Op.getNode(); 12275 SDLoc dl(Node); 12276 EVT T = Node->getValueType(0); 12277 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 12278 DAG.getConstant(0, T), Node->getOperand(2)); 12279 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 12280 cast<AtomicSDNode>(Node)->getMemoryVT(), 12281 Node->getOperand(0), 12282 Node->getOperand(1), negOp, 12283 cast<AtomicSDNode>(Node)->getSrcValue(), 12284 cast<AtomicSDNode>(Node)->getAlignment(), 12285 cast<AtomicSDNode>(Node)->getOrdering(), 12286 cast<AtomicSDNode>(Node)->getSynchScope()); 12287 } 12288 12289 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 12290 SDNode *Node = Op.getNode(); 12291 SDLoc dl(Node); 12292 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 12293 12294 // Convert seq_cst store -> xchg 12295 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 12296 // FIXME: On 32-bit, store -> fist or movq would be more efficient 12297 // (The only way to get a 16-byte store is cmpxchg16b) 12298 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 12299 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 12300 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 12301 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 12302 cast<AtomicSDNode>(Node)->getMemoryVT(), 12303 Node->getOperand(0), 12304 Node->getOperand(1), Node->getOperand(2), 12305 cast<AtomicSDNode>(Node)->getMemOperand(), 12306 cast<AtomicSDNode>(Node)->getOrdering(), 12307 cast<AtomicSDNode>(Node)->getSynchScope()); 12308 return Swap.getValue(1); 12309 } 12310 // Other atomic stores have a simple pattern. 12311 return Op; 12312 } 12313 12314 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 12315 EVT VT = Op.getNode()->getValueType(0); 12316 12317 // Let legalize expand this if it isn't a legal type yet. 12318 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 12319 return SDValue(); 12320 12321 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 12322 12323 unsigned Opc; 12324 bool ExtraOp = false; 12325 switch (Op.getOpcode()) { 12326 default: llvm_unreachable("Invalid code"); 12327 case ISD::ADDC: Opc = X86ISD::ADD; break; 12328 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 12329 case ISD::SUBC: Opc = X86ISD::SUB; break; 12330 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 12331 } 12332 12333 if (!ExtraOp) 12334 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 12335 Op.getOperand(1)); 12336 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), 12337 Op.getOperand(1), Op.getOperand(2)); 12338 } 12339 12340 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { 12341 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit()); 12342 12343 // For MacOSX, we want to call an alternative entry point: __sincos_stret, 12344 // which returns the values as { float, float } (in XMM0) or 12345 // { double, double } (which is returned in XMM0, XMM1). 12346 SDLoc dl(Op); 12347 SDValue Arg = Op.getOperand(0); 12348 EVT ArgVT = Arg.getValueType(); 12349 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 12350 12351 ArgListTy Args; 12352 ArgListEntry Entry; 12353 12354 Entry.Node = Arg; 12355 Entry.Ty = ArgTy; 12356 Entry.isSExt = false; 12357 Entry.isZExt = false; 12358 Args.push_back(Entry); 12359 12360 bool isF64 = ArgVT == MVT::f64; 12361 // Only optimize x86_64 for now. i386 is a bit messy. For f32, 12362 // the small struct {f32, f32} is returned in (eax, edx). For f64, 12363 // the results are returned via SRet in memory. 12364 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret"; 12365 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy()); 12366 12367 Type *RetTy = isF64 12368 ? (Type*)StructType::get(ArgTy, ArgTy, NULL) 12369 : (Type*)VectorType::get(ArgTy, 4); 12370 TargetLowering:: 12371 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, 12372 false, false, false, false, 0, 12373 CallingConv::C, /*isTaillCall=*/false, 12374 /*doesNotRet=*/false, /*isReturnValueUsed*/true, 12375 Callee, Args, DAG, dl); 12376 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 12377 12378 if (isF64) 12379 // Returned in xmm0 and xmm1. 12380 return CallResult.first; 12381 12382 // Returned in bits 0:31 and 32:64 xmm0. 12383 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, 12384 CallResult.first, DAG.getIntPtrConstant(0)); 12385 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT, 12386 CallResult.first, DAG.getIntPtrConstant(1)); 12387 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT); 12388 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal); 12389 } 12390 12391 /// LowerOperation - Provide custom lowering hooks for some operations. 12392 /// 12393 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 12394 switch (Op.getOpcode()) { 12395 default: llvm_unreachable("Should not custom lower this!"); 12396 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 12397 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG); 12398 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG); 12399 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 12400 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 12401 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 12402 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 12403 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 12404 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 12405 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 12406 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG); 12407 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG); 12408 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 12409 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 12410 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 12411 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 12412 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 12413 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 12414 case ISD::SHL_PARTS: 12415 case ISD::SRA_PARTS: 12416 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 12417 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 12418 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 12419 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 12420 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG); 12421 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG); 12422 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG); 12423 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 12424 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 12425 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 12426 case ISD::FABS: return LowerFABS(Op, DAG); 12427 case ISD::FNEG: return LowerFNEG(Op, DAG); 12428 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 12429 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 12430 case ISD::SETCC: return LowerSETCC(Op, DAG); 12431 case ISD::SELECT: return LowerSELECT(Op, DAG); 12432 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 12433 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 12434 case ISD::VASTART: return LowerVASTART(Op, DAG); 12435 case ISD::VAARG: return LowerVAARG(Op, DAG); 12436 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG); 12437 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 12438 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 12439 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 12440 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 12441 case ISD::FRAME_TO_ARGS_OFFSET: 12442 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 12443 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 12444 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 12445 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 12446 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 12447 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 12448 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 12449 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 12450 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 12451 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG); 12452 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 12453 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG); 12454 case ISD::SRA: 12455 case ISD::SRL: 12456 case ISD::SHL: return LowerShift(Op, DAG); 12457 case ISD::SADDO: 12458 case ISD::UADDO: 12459 case ISD::SSUBO: 12460 case ISD::USUBO: 12461 case ISD::SMULO: 12462 case ISD::UMULO: return LowerXALUO(Op, DAG); 12463 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG); 12464 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 12465 case ISD::ADDC: 12466 case ISD::ADDE: 12467 case ISD::SUBC: 12468 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 12469 case ISD::ADD: return LowerADD(Op, DAG); 12470 case ISD::SUB: return LowerSUB(Op, DAG); 12471 case ISD::SDIV: return LowerSDIV(Op, DAG); 12472 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); 12473 } 12474 } 12475 12476 static void ReplaceATOMIC_LOAD(SDNode *Node, 12477 SmallVectorImpl<SDValue> &Results, 12478 SelectionDAG &DAG) { 12479 SDLoc dl(Node); 12480 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 12481 12482 // Convert wide load -> cmpxchg8b/cmpxchg16b 12483 // FIXME: On 32-bit, load -> fild or movq would be more efficient 12484 // (The only way to get a 16-byte load is cmpxchg16b) 12485 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 12486 SDValue Zero = DAG.getConstant(0, VT); 12487 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 12488 Node->getOperand(0), 12489 Node->getOperand(1), Zero, Zero, 12490 cast<AtomicSDNode>(Node)->getMemOperand(), 12491 cast<AtomicSDNode>(Node)->getOrdering(), 12492 cast<AtomicSDNode>(Node)->getSynchScope()); 12493 Results.push_back(Swap.getValue(0)); 12494 Results.push_back(Swap.getValue(1)); 12495 } 12496 12497 static void 12498 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 12499 SelectionDAG &DAG, unsigned NewOp) { 12500 SDLoc dl(Node); 12501 assert (Node->getValueType(0) == MVT::i64 && 12502 "Only know how to expand i64 atomics"); 12503 12504 SDValue Chain = Node->getOperand(0); 12505 SDValue In1 = Node->getOperand(1); 12506 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12507 Node->getOperand(2), DAG.getIntPtrConstant(0)); 12508 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12509 Node->getOperand(2), DAG.getIntPtrConstant(1)); 12510 SDValue Ops[] = { Chain, In1, In2L, In2H }; 12511 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 12512 SDValue Result = 12513 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64, 12514 cast<MemSDNode>(Node)->getMemOperand()); 12515 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 12516 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 12517 Results.push_back(Result.getValue(2)); 12518 } 12519 12520 /// ReplaceNodeResults - Replace a node with an illegal result type 12521 /// with a new node built out of custom code. 12522 void X86TargetLowering::ReplaceNodeResults(SDNode *N, 12523 SmallVectorImpl<SDValue>&Results, 12524 SelectionDAG &DAG) const { 12525 SDLoc dl(N); 12526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12527 switch (N->getOpcode()) { 12528 default: 12529 llvm_unreachable("Do not know how to custom type legalize this operation!"); 12530 case ISD::SIGN_EXTEND_INREG: 12531 case ISD::ADDC: 12532 case ISD::ADDE: 12533 case ISD::SUBC: 12534 case ISD::SUBE: 12535 // We don't want to expand or promote these. 12536 return; 12537 case ISD::FP_TO_SINT: 12538 case ISD::FP_TO_UINT: { 12539 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12540 12541 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType())) 12542 return; 12543 12544 std::pair<SDValue,SDValue> Vals = 12545 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true); 12546 SDValue FIST = Vals.first, StackSlot = Vals.second; 12547 if (FIST.getNode() != 0) { 12548 EVT VT = N->getValueType(0); 12549 // Return a load from the stack slot. 12550 if (StackSlot.getNode() != 0) 12551 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 12552 MachinePointerInfo(), 12553 false, false, false, 0)); 12554 else 12555 Results.push_back(FIST); 12556 } 12557 return; 12558 } 12559 case ISD::UINT_TO_FP: { 12560 assert(Subtarget->hasSSE2() && "Requires at least SSE2!"); 12561 if (N->getOperand(0).getValueType() != MVT::v2i32 || 12562 N->getValueType(0) != MVT::v2f32) 12563 return; 12564 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, 12565 N->getOperand(0)); 12566 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 12567 MVT::f64); 12568 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias); 12569 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn, 12570 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias)); 12571 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or); 12572 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias); 12573 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub)); 12574 return; 12575 } 12576 case ISD::FP_ROUND: { 12577 if (!TLI.isTypeLegal(N->getOperand(0).getValueType())) 12578 return; 12579 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0)); 12580 Results.push_back(V); 12581 return; 12582 } 12583 case ISD::READCYCLECOUNTER: { 12584 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12585 SDValue TheChain = N->getOperand(0); 12586 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 12587 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 12588 rd.getValue(1)); 12589 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 12590 eax.getValue(2)); 12591 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 12592 SDValue Ops[] = { eax, edx }; 12593 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 12594 array_lengthof(Ops))); 12595 Results.push_back(edx.getValue(1)); 12596 return; 12597 } 12598 case ISD::ATOMIC_CMP_SWAP: { 12599 EVT T = N->getValueType(0); 12600 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 12601 bool Regs64bit = T == MVT::i128; 12602 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 12603 SDValue cpInL, cpInH; 12604 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 12605 DAG.getConstant(0, HalfT)); 12606 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 12607 DAG.getConstant(1, HalfT)); 12608 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 12609 Regs64bit ? X86::RAX : X86::EAX, 12610 cpInL, SDValue()); 12611 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 12612 Regs64bit ? X86::RDX : X86::EDX, 12613 cpInH, cpInL.getValue(1)); 12614 SDValue swapInL, swapInH; 12615 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 12616 DAG.getConstant(0, HalfT)); 12617 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 12618 DAG.getConstant(1, HalfT)); 12619 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 12620 Regs64bit ? X86::RBX : X86::EBX, 12621 swapInL, cpInH.getValue(1)); 12622 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 12623 Regs64bit ? X86::RCX : X86::ECX, 12624 swapInH, swapInL.getValue(1)); 12625 SDValue Ops[] = { swapInH.getValue(0), 12626 N->getOperand(1), 12627 swapInH.getValue(1) }; 12628 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12629 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 12630 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 12631 X86ISD::LCMPXCHG8_DAG; 12632 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 12633 Ops, array_lengthof(Ops), T, MMO); 12634 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 12635 Regs64bit ? X86::RAX : X86::EAX, 12636 HalfT, Result.getValue(1)); 12637 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 12638 Regs64bit ? X86::RDX : X86::EDX, 12639 HalfT, cpOutL.getValue(2)); 12640 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 12641 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 12642 Results.push_back(cpOutH.getValue(1)); 12643 return; 12644 } 12645 case ISD::ATOMIC_LOAD_ADD: 12646 case ISD::ATOMIC_LOAD_AND: 12647 case ISD::ATOMIC_LOAD_NAND: 12648 case ISD::ATOMIC_LOAD_OR: 12649 case ISD::ATOMIC_LOAD_SUB: 12650 case ISD::ATOMIC_LOAD_XOR: 12651 case ISD::ATOMIC_LOAD_MAX: 12652 case ISD::ATOMIC_LOAD_MIN: 12653 case ISD::ATOMIC_LOAD_UMAX: 12654 case ISD::ATOMIC_LOAD_UMIN: 12655 case ISD::ATOMIC_SWAP: { 12656 unsigned Opc; 12657 switch (N->getOpcode()) { 12658 default: llvm_unreachable("Unexpected opcode"); 12659 case ISD::ATOMIC_LOAD_ADD: 12660 Opc = X86ISD::ATOMADD64_DAG; 12661 break; 12662 case ISD::ATOMIC_LOAD_AND: 12663 Opc = X86ISD::ATOMAND64_DAG; 12664 break; 12665 case ISD::ATOMIC_LOAD_NAND: 12666 Opc = X86ISD::ATOMNAND64_DAG; 12667 break; 12668 case ISD::ATOMIC_LOAD_OR: 12669 Opc = X86ISD::ATOMOR64_DAG; 12670 break; 12671 case ISD::ATOMIC_LOAD_SUB: 12672 Opc = X86ISD::ATOMSUB64_DAG; 12673 break; 12674 case ISD::ATOMIC_LOAD_XOR: 12675 Opc = X86ISD::ATOMXOR64_DAG; 12676 break; 12677 case ISD::ATOMIC_LOAD_MAX: 12678 Opc = X86ISD::ATOMMAX64_DAG; 12679 break; 12680 case ISD::ATOMIC_LOAD_MIN: 12681 Opc = X86ISD::ATOMMIN64_DAG; 12682 break; 12683 case ISD::ATOMIC_LOAD_UMAX: 12684 Opc = X86ISD::ATOMUMAX64_DAG; 12685 break; 12686 case ISD::ATOMIC_LOAD_UMIN: 12687 Opc = X86ISD::ATOMUMIN64_DAG; 12688 break; 12689 case ISD::ATOMIC_SWAP: 12690 Opc = X86ISD::ATOMSWAP64_DAG; 12691 break; 12692 } 12693 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc); 12694 return; 12695 } 12696 case ISD::ATOMIC_LOAD: 12697 ReplaceATOMIC_LOAD(N, Results, DAG); 12698 } 12699 } 12700 12701 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 12702 switch (Opcode) { 12703 default: return NULL; 12704 case X86ISD::BSF: return "X86ISD::BSF"; 12705 case X86ISD::BSR: return "X86ISD::BSR"; 12706 case X86ISD::SHLD: return "X86ISD::SHLD"; 12707 case X86ISD::SHRD: return "X86ISD::SHRD"; 12708 case X86ISD::FAND: return "X86ISD::FAND"; 12709 case X86ISD::FOR: return "X86ISD::FOR"; 12710 case X86ISD::FXOR: return "X86ISD::FXOR"; 12711 case X86ISD::FSRL: return "X86ISD::FSRL"; 12712 case X86ISD::FILD: return "X86ISD::FILD"; 12713 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 12714 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 12715 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 12716 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 12717 case X86ISD::FLD: return "X86ISD::FLD"; 12718 case X86ISD::FST: return "X86ISD::FST"; 12719 case X86ISD::CALL: return "X86ISD::CALL"; 12720 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 12721 case X86ISD::BT: return "X86ISD::BT"; 12722 case X86ISD::CMP: return "X86ISD::CMP"; 12723 case X86ISD::COMI: return "X86ISD::COMI"; 12724 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 12725 case X86ISD::SETCC: return "X86ISD::SETCC"; 12726 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 12727 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 12728 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 12729 case X86ISD::CMOV: return "X86ISD::CMOV"; 12730 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 12731 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 12732 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 12733 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 12734 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 12735 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 12736 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 12737 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 12738 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 12739 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 12740 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 12741 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 12742 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 12743 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 12744 case X86ISD::PSIGN: return "X86ISD::PSIGN"; 12745 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 12746 case X86ISD::BLENDI: return "X86ISD::BLENDI"; 12747 case X86ISD::SUBUS: return "X86ISD::SUBUS"; 12748 case X86ISD::HADD: return "X86ISD::HADD"; 12749 case X86ISD::HSUB: return "X86ISD::HSUB"; 12750 case X86ISD::FHADD: return "X86ISD::FHADD"; 12751 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 12752 case X86ISD::UMAX: return "X86ISD::UMAX"; 12753 case X86ISD::UMIN: return "X86ISD::UMIN"; 12754 case X86ISD::SMAX: return "X86ISD::SMAX"; 12755 case X86ISD::SMIN: return "X86ISD::SMIN"; 12756 case X86ISD::FMAX: return "X86ISD::FMAX"; 12757 case X86ISD::FMIN: return "X86ISD::FMIN"; 12758 case X86ISD::FMAXC: return "X86ISD::FMAXC"; 12759 case X86ISD::FMINC: return "X86ISD::FMINC"; 12760 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 12761 case X86ISD::FRCP: return "X86ISD::FRCP"; 12762 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 12763 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR"; 12764 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 12765 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP"; 12766 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP"; 12767 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 12768 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 12769 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 12770 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r"; 12771 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 12772 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 12773 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 12774 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 12775 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 12776 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 12777 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 12778 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 12779 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 12780 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL"; 12781 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 12782 case X86ISD::VZEXT: return "X86ISD::VZEXT"; 12783 case X86ISD::VSEXT: return "X86ISD::VSEXT"; 12784 case X86ISD::VFPEXT: return "X86ISD::VFPEXT"; 12785 case X86ISD::VFPROUND: return "X86ISD::VFPROUND"; 12786 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ"; 12787 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ"; 12788 case X86ISD::VSHL: return "X86ISD::VSHL"; 12789 case X86ISD::VSRL: return "X86ISD::VSRL"; 12790 case X86ISD::VSRA: return "X86ISD::VSRA"; 12791 case X86ISD::VSHLI: return "X86ISD::VSHLI"; 12792 case X86ISD::VSRLI: return "X86ISD::VSRLI"; 12793 case X86ISD::VSRAI: return "X86ISD::VSRAI"; 12794 case X86ISD::CMPP: return "X86ISD::CMPP"; 12795 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ"; 12796 case X86ISD::PCMPGT: return "X86ISD::PCMPGT"; 12797 case X86ISD::ADD: return "X86ISD::ADD"; 12798 case X86ISD::SUB: return "X86ISD::SUB"; 12799 case X86ISD::ADC: return "X86ISD::ADC"; 12800 case X86ISD::SBB: return "X86ISD::SBB"; 12801 case X86ISD::SMUL: return "X86ISD::SMUL"; 12802 case X86ISD::UMUL: return "X86ISD::UMUL"; 12803 case X86ISD::INC: return "X86ISD::INC"; 12804 case X86ISD::DEC: return "X86ISD::DEC"; 12805 case X86ISD::OR: return "X86ISD::OR"; 12806 case X86ISD::XOR: return "X86ISD::XOR"; 12807 case X86ISD::AND: return "X86ISD::AND"; 12808 case X86ISD::BLSI: return "X86ISD::BLSI"; 12809 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 12810 case X86ISD::BLSR: return "X86ISD::BLSR"; 12811 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 12812 case X86ISD::PTEST: return "X86ISD::PTEST"; 12813 case X86ISD::TESTP: return "X86ISD::TESTP"; 12814 case X86ISD::PALIGNR: return "X86ISD::PALIGNR"; 12815 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 12816 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 12817 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 12818 case X86ISD::SHUFP: return "X86ISD::SHUFP"; 12819 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 12820 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 12821 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 12822 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 12823 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 12824 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 12825 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 12826 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 12827 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 12828 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 12829 case X86ISD::UNPCKL: return "X86ISD::UNPCKL"; 12830 case X86ISD::UNPCKH: return "X86ISD::UNPCKH"; 12831 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 12832 case X86ISD::VPERMILP: return "X86ISD::VPERMILP"; 12833 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128"; 12834 case X86ISD::VPERMV: return "X86ISD::VPERMV"; 12835 case X86ISD::VPERMI: return "X86ISD::VPERMI"; 12836 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ"; 12837 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 12838 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 12839 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 12840 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 12841 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 12842 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL"; 12843 case X86ISD::SAHF: return "X86ISD::SAHF"; 12844 case X86ISD::RDRAND: return "X86ISD::RDRAND"; 12845 case X86ISD::RDSEED: return "X86ISD::RDSEED"; 12846 case X86ISD::FMADD: return "X86ISD::FMADD"; 12847 case X86ISD::FMSUB: return "X86ISD::FMSUB"; 12848 case X86ISD::FNMADD: return "X86ISD::FNMADD"; 12849 case X86ISD::FNMSUB: return "X86ISD::FNMSUB"; 12850 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB"; 12851 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD"; 12852 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI"; 12853 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI"; 12854 case X86ISD::XTEST: return "X86ISD::XTEST"; 12855 } 12856 } 12857 12858 // isLegalAddressingMode - Return true if the addressing mode represented 12859 // by AM is legal for this target, for a load/store of the specified type. 12860 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 12861 Type *Ty) const { 12862 // X86 supports extremely general addressing modes. 12863 CodeModel::Model M = getTargetMachine().getCodeModel(); 12864 Reloc::Model R = getTargetMachine().getRelocationModel(); 12865 12866 // X86 allows a sign-extended 32-bit immediate field as a displacement. 12867 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 12868 return false; 12869 12870 if (AM.BaseGV) { 12871 unsigned GVFlags = 12872 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 12873 12874 // If a reference to this global requires an extra load, we can't fold it. 12875 if (isGlobalStubReference(GVFlags)) 12876 return false; 12877 12878 // If BaseGV requires a register for the PIC base, we cannot also have a 12879 // BaseReg specified. 12880 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 12881 return false; 12882 12883 // If lower 4G is not available, then we must use rip-relative addressing. 12884 if ((M != CodeModel::Small || R != Reloc::Static) && 12885 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 12886 return false; 12887 } 12888 12889 switch (AM.Scale) { 12890 case 0: 12891 case 1: 12892 case 2: 12893 case 4: 12894 case 8: 12895 // These scales always work. 12896 break; 12897 case 3: 12898 case 5: 12899 case 9: 12900 // These scales are formed with basereg+scalereg. Only accept if there is 12901 // no basereg yet. 12902 if (AM.HasBaseReg) 12903 return false; 12904 break; 12905 default: // Other stuff never works. 12906 return false; 12907 } 12908 12909 return true; 12910 } 12911 12912 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 12913 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12914 return false; 12915 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 12916 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 12917 return NumBits1 > NumBits2; 12918 } 12919 12920 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12921 return isInt<32>(Imm); 12922 } 12923 12924 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const { 12925 // Can also use sub to handle negated immediates. 12926 return isInt<32>(Imm); 12927 } 12928 12929 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 12930 if (!VT1.isInteger() || !VT2.isInteger()) 12931 return false; 12932 unsigned NumBits1 = VT1.getSizeInBits(); 12933 unsigned NumBits2 = VT2.getSizeInBits(); 12934 return NumBits1 > NumBits2; 12935 } 12936 12937 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 12938 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 12939 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 12940 } 12941 12942 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 12943 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 12944 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 12945 } 12946 12947 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12948 EVT VT1 = Val.getValueType(); 12949 if (isZExtFree(VT1, VT2)) 12950 return true; 12951 12952 if (Val.getOpcode() != ISD::LOAD) 12953 return false; 12954 12955 if (!VT1.isSimple() || !VT1.isInteger() || 12956 !VT2.isSimple() || !VT2.isInteger()) 12957 return false; 12958 12959 switch (VT1.getSimpleVT().SimpleTy) { 12960 default: break; 12961 case MVT::i8: 12962 case MVT::i16: 12963 case MVT::i32: 12964 // X86 has 8, 16, and 32-bit zero-extending loads. 12965 return true; 12966 } 12967 12968 return false; 12969 } 12970 12971 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 12972 // i16 instructions are longer (0x66 prefix) and potentially slower. 12973 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 12974 } 12975 12976 /// isShuffleMaskLegal - Targets can use this to indicate that they only 12977 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 12978 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 12979 /// are assumed to be legal. 12980 bool 12981 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 12982 EVT VT) const { 12983 // Very little shuffling can be done for 64-bit vectors right now. 12984 if (VT.getSizeInBits() == 64) 12985 return false; 12986 12987 // FIXME: pshufb, blends, shifts. 12988 return (VT.getVectorNumElements() == 2 || 12989 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 12990 isMOVLMask(M, VT) || 12991 isSHUFPMask(M, VT, Subtarget->hasFp256()) || 12992 isPSHUFDMask(M, VT) || 12993 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) || 12994 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) || 12995 isPALIGNRMask(M, VT, Subtarget) || 12996 isUNPCKLMask(M, VT, Subtarget->hasInt256()) || 12997 isUNPCKHMask(M, VT, Subtarget->hasInt256()) || 12998 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) || 12999 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256())); 13000 } 13001 13002 bool 13003 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 13004 EVT VT) const { 13005 unsigned NumElts = VT.getVectorNumElements(); 13006 // FIXME: This collection of masks seems suspect. 13007 if (NumElts == 2) 13008 return true; 13009 if (NumElts == 4 && VT.is128BitVector()) { 13010 return (isMOVLMask(Mask, VT) || 13011 isCommutedMOVLMask(Mask, VT, true) || 13012 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) || 13013 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true)); 13014 } 13015 return false; 13016 } 13017 13018 //===----------------------------------------------------------------------===// 13019 // X86 Scheduler Hooks 13020 //===----------------------------------------------------------------------===// 13021 13022 /// Utility function to emit xbegin specifying the start of an RTM region. 13023 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB, 13024 const TargetInstrInfo *TII) { 13025 DebugLoc DL = MI->getDebugLoc(); 13026 13027 const BasicBlock *BB = MBB->getBasicBlock(); 13028 MachineFunction::iterator I = MBB; 13029 ++I; 13030 13031 // For the v = xbegin(), we generate 13032 // 13033 // thisMBB: 13034 // xbegin sinkMBB 13035 // 13036 // mainMBB: 13037 // eax = -1 13038 // 13039 // sinkMBB: 13040 // v = eax 13041 13042 MachineBasicBlock *thisMBB = MBB; 13043 MachineFunction *MF = MBB->getParent(); 13044 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13045 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13046 MF->insert(I, mainMBB); 13047 MF->insert(I, sinkMBB); 13048 13049 // Transfer the remainder of BB and its successor edges to sinkMBB. 13050 sinkMBB->splice(sinkMBB->begin(), MBB, 13051 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13052 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13053 13054 // thisMBB: 13055 // xbegin sinkMBB 13056 // # fallthrough to mainMBB 13057 // # abortion to sinkMBB 13058 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB); 13059 thisMBB->addSuccessor(mainMBB); 13060 thisMBB->addSuccessor(sinkMBB); 13061 13062 // mainMBB: 13063 // EAX = -1 13064 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1); 13065 mainMBB->addSuccessor(sinkMBB); 13066 13067 // sinkMBB: 13068 // EAX is live into the sinkMBB 13069 sinkMBB->addLiveIn(X86::EAX); 13070 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13071 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13072 .addReg(X86::EAX); 13073 13074 MI->eraseFromParent(); 13075 return sinkMBB; 13076 } 13077 13078 // Get CMPXCHG opcode for the specified data type. 13079 static unsigned getCmpXChgOpcode(EVT VT) { 13080 switch (VT.getSimpleVT().SimpleTy) { 13081 case MVT::i8: return X86::LCMPXCHG8; 13082 case MVT::i16: return X86::LCMPXCHG16; 13083 case MVT::i32: return X86::LCMPXCHG32; 13084 case MVT::i64: return X86::LCMPXCHG64; 13085 default: 13086 break; 13087 } 13088 llvm_unreachable("Invalid operand size!"); 13089 } 13090 13091 // Get LOAD opcode for the specified data type. 13092 static unsigned getLoadOpcode(EVT VT) { 13093 switch (VT.getSimpleVT().SimpleTy) { 13094 case MVT::i8: return X86::MOV8rm; 13095 case MVT::i16: return X86::MOV16rm; 13096 case MVT::i32: return X86::MOV32rm; 13097 case MVT::i64: return X86::MOV64rm; 13098 default: 13099 break; 13100 } 13101 llvm_unreachable("Invalid operand size!"); 13102 } 13103 13104 // Get opcode of the non-atomic one from the specified atomic instruction. 13105 static unsigned getNonAtomicOpcode(unsigned Opc) { 13106 switch (Opc) { 13107 case X86::ATOMAND8: return X86::AND8rr; 13108 case X86::ATOMAND16: return X86::AND16rr; 13109 case X86::ATOMAND32: return X86::AND32rr; 13110 case X86::ATOMAND64: return X86::AND64rr; 13111 case X86::ATOMOR8: return X86::OR8rr; 13112 case X86::ATOMOR16: return X86::OR16rr; 13113 case X86::ATOMOR32: return X86::OR32rr; 13114 case X86::ATOMOR64: return X86::OR64rr; 13115 case X86::ATOMXOR8: return X86::XOR8rr; 13116 case X86::ATOMXOR16: return X86::XOR16rr; 13117 case X86::ATOMXOR32: return X86::XOR32rr; 13118 case X86::ATOMXOR64: return X86::XOR64rr; 13119 } 13120 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13121 } 13122 13123 // Get opcode of the non-atomic one from the specified atomic instruction with 13124 // extra opcode. 13125 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc, 13126 unsigned &ExtraOpc) { 13127 switch (Opc) { 13128 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr; 13129 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr; 13130 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr; 13131 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr; 13132 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr; 13133 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr; 13134 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr; 13135 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr; 13136 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr; 13137 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr; 13138 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr; 13139 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr; 13140 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr; 13141 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr; 13142 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr; 13143 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr; 13144 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr; 13145 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr; 13146 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr; 13147 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr; 13148 } 13149 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13150 } 13151 13152 // Get opcode of the non-atomic one from the specified atomic instruction for 13153 // 64-bit data type on 32-bit target. 13154 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) { 13155 switch (Opc) { 13156 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr; 13157 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr; 13158 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr; 13159 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr; 13160 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr; 13161 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr; 13162 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr; 13163 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr; 13164 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr; 13165 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr; 13166 } 13167 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13168 } 13169 13170 // Get opcode of the non-atomic one from the specified atomic instruction for 13171 // 64-bit data type on 32-bit target with extra opcode. 13172 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc, 13173 unsigned &HiOpc, 13174 unsigned &ExtraOpc) { 13175 switch (Opc) { 13176 case X86::ATOMNAND6432: 13177 ExtraOpc = X86::NOT32r; 13178 HiOpc = X86::AND32rr; 13179 return X86::AND32rr; 13180 } 13181 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13182 } 13183 13184 // Get pseudo CMOV opcode from the specified data type. 13185 static unsigned getPseudoCMOVOpc(EVT VT) { 13186 switch (VT.getSimpleVT().SimpleTy) { 13187 case MVT::i8: return X86::CMOV_GR8; 13188 case MVT::i16: return X86::CMOV_GR16; 13189 case MVT::i32: return X86::CMOV_GR32; 13190 default: 13191 break; 13192 } 13193 llvm_unreachable("Unknown CMOV opcode!"); 13194 } 13195 13196 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions. 13197 // They will be translated into a spin-loop or compare-exchange loop from 13198 // 13199 // ... 13200 // dst = atomic-fetch-op MI.addr, MI.val 13201 // ... 13202 // 13203 // to 13204 // 13205 // ... 13206 // t1 = LOAD MI.addr 13207 // loop: 13208 // t4 = phi(t1, t3 / loop) 13209 // t2 = OP MI.val, t4 13210 // EAX = t4 13211 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined] 13212 // t3 = EAX 13213 // JNE loop 13214 // sink: 13215 // dst = t3 13216 // ... 13217 MachineBasicBlock * 13218 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI, 13219 MachineBasicBlock *MBB) const { 13220 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13221 DebugLoc DL = MI->getDebugLoc(); 13222 13223 MachineFunction *MF = MBB->getParent(); 13224 MachineRegisterInfo &MRI = MF->getRegInfo(); 13225 13226 const BasicBlock *BB = MBB->getBasicBlock(); 13227 MachineFunction::iterator I = MBB; 13228 ++I; 13229 13230 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 && 13231 "Unexpected number of operands"); 13232 13233 assert(MI->hasOneMemOperand() && 13234 "Expected atomic-load-op to have one memoperand"); 13235 13236 // Memory Reference 13237 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13238 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13239 13240 unsigned DstReg, SrcReg; 13241 unsigned MemOpndSlot; 13242 13243 unsigned CurOp = 0; 13244 13245 DstReg = MI->getOperand(CurOp++).getReg(); 13246 MemOpndSlot = CurOp; 13247 CurOp += X86::AddrNumOperands; 13248 SrcReg = MI->getOperand(CurOp++).getReg(); 13249 13250 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 13251 MVT::SimpleValueType VT = *RC->vt_begin(); 13252 unsigned t1 = MRI.createVirtualRegister(RC); 13253 unsigned t2 = MRI.createVirtualRegister(RC); 13254 unsigned t3 = MRI.createVirtualRegister(RC); 13255 unsigned t4 = MRI.createVirtualRegister(RC); 13256 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT); 13257 13258 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT); 13259 unsigned LOADOpc = getLoadOpcode(VT); 13260 13261 // For the atomic load-arith operator, we generate 13262 // 13263 // thisMBB: 13264 // t1 = LOAD [MI.addr] 13265 // mainMBB: 13266 // t4 = phi(t1 / thisMBB, t3 / mainMBB) 13267 // t1 = OP MI.val, EAX 13268 // EAX = t4 13269 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined] 13270 // t3 = EAX 13271 // JNE mainMBB 13272 // sinkMBB: 13273 // dst = t3 13274 13275 MachineBasicBlock *thisMBB = MBB; 13276 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13277 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13278 MF->insert(I, mainMBB); 13279 MF->insert(I, sinkMBB); 13280 13281 MachineInstrBuilder MIB; 13282 13283 // Transfer the remainder of BB and its successor edges to sinkMBB. 13284 sinkMBB->splice(sinkMBB->begin(), MBB, 13285 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13286 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13287 13288 // thisMBB: 13289 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1); 13290 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13291 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13292 if (NewMO.isReg()) 13293 NewMO.setIsKill(false); 13294 MIB.addOperand(NewMO); 13295 } 13296 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) { 13297 unsigned flags = (*MMOI)->getFlags(); 13298 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad; 13299 MachineMemOperand *MMO = 13300 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags, 13301 (*MMOI)->getSize(), 13302 (*MMOI)->getBaseAlignment(), 13303 (*MMOI)->getTBAAInfo(), 13304 (*MMOI)->getRanges()); 13305 MIB.addMemOperand(MMO); 13306 } 13307 13308 thisMBB->addSuccessor(mainMBB); 13309 13310 // mainMBB: 13311 MachineBasicBlock *origMainMBB = mainMBB; 13312 13313 // Add a PHI. 13314 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4) 13315 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB); 13316 13317 unsigned Opc = MI->getOpcode(); 13318 switch (Opc) { 13319 default: 13320 llvm_unreachable("Unhandled atomic-load-op opcode!"); 13321 case X86::ATOMAND8: 13322 case X86::ATOMAND16: 13323 case X86::ATOMAND32: 13324 case X86::ATOMAND64: 13325 case X86::ATOMOR8: 13326 case X86::ATOMOR16: 13327 case X86::ATOMOR32: 13328 case X86::ATOMOR64: 13329 case X86::ATOMXOR8: 13330 case X86::ATOMXOR16: 13331 case X86::ATOMXOR32: 13332 case X86::ATOMXOR64: { 13333 unsigned ARITHOpc = getNonAtomicOpcode(Opc); 13334 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg) 13335 .addReg(t4); 13336 break; 13337 } 13338 case X86::ATOMNAND8: 13339 case X86::ATOMNAND16: 13340 case X86::ATOMNAND32: 13341 case X86::ATOMNAND64: { 13342 unsigned Tmp = MRI.createVirtualRegister(RC); 13343 unsigned NOTOpc; 13344 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc); 13345 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg) 13346 .addReg(t4); 13347 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp); 13348 break; 13349 } 13350 case X86::ATOMMAX8: 13351 case X86::ATOMMAX16: 13352 case X86::ATOMMAX32: 13353 case X86::ATOMMAX64: 13354 case X86::ATOMMIN8: 13355 case X86::ATOMMIN16: 13356 case X86::ATOMMIN32: 13357 case X86::ATOMMIN64: 13358 case X86::ATOMUMAX8: 13359 case X86::ATOMUMAX16: 13360 case X86::ATOMUMAX32: 13361 case X86::ATOMUMAX64: 13362 case X86::ATOMUMIN8: 13363 case X86::ATOMUMIN16: 13364 case X86::ATOMUMIN32: 13365 case X86::ATOMUMIN64: { 13366 unsigned CMPOpc; 13367 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc); 13368 13369 BuildMI(mainMBB, DL, TII->get(CMPOpc)) 13370 .addReg(SrcReg) 13371 .addReg(t4); 13372 13373 if (Subtarget->hasCMov()) { 13374 if (VT != MVT::i8) { 13375 // Native support 13376 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2) 13377 .addReg(SrcReg) 13378 .addReg(t4); 13379 } else { 13380 // Promote i8 to i32 to use CMOV32 13381 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 13382 const TargetRegisterClass *RC32 = 13383 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit); 13384 unsigned SrcReg32 = MRI.createVirtualRegister(RC32); 13385 unsigned AccReg32 = MRI.createVirtualRegister(RC32); 13386 unsigned Tmp = MRI.createVirtualRegister(RC32); 13387 13388 unsigned Undef = MRI.createVirtualRegister(RC32); 13389 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef); 13390 13391 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32) 13392 .addReg(Undef) 13393 .addReg(SrcReg) 13394 .addImm(X86::sub_8bit); 13395 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32) 13396 .addReg(Undef) 13397 .addReg(t4) 13398 .addImm(X86::sub_8bit); 13399 13400 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp) 13401 .addReg(SrcReg32) 13402 .addReg(AccReg32); 13403 13404 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2) 13405 .addReg(Tmp, 0, X86::sub_8bit); 13406 } 13407 } else { 13408 // Use pseudo select and lower them. 13409 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 13410 "Invalid atomic-load-op transformation!"); 13411 unsigned SelOpc = getPseudoCMOVOpc(VT); 13412 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc); 13413 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!"); 13414 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2) 13415 .addReg(SrcReg).addReg(t4) 13416 .addImm(CC); 13417 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13418 // Replace the original PHI node as mainMBB is changed after CMOV 13419 // lowering. 13420 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4) 13421 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB); 13422 Phi->eraseFromParent(); 13423 } 13424 break; 13425 } 13426 } 13427 13428 // Copy PhyReg back from virtual register. 13429 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg) 13430 .addReg(t4); 13431 13432 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 13433 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13434 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13435 if (NewMO.isReg()) 13436 NewMO.setIsKill(false); 13437 MIB.addOperand(NewMO); 13438 } 13439 MIB.addReg(t2); 13440 MIB.setMemRefs(MMOBegin, MMOEnd); 13441 13442 // Copy PhyReg back to virtual register. 13443 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3) 13444 .addReg(PhyReg); 13445 13446 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 13447 13448 mainMBB->addSuccessor(origMainMBB); 13449 mainMBB->addSuccessor(sinkMBB); 13450 13451 // sinkMBB: 13452 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13453 TII->get(TargetOpcode::COPY), DstReg) 13454 .addReg(t3); 13455 13456 MI->eraseFromParent(); 13457 return sinkMBB; 13458 } 13459 13460 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic 13461 // instructions. They will be translated into a spin-loop or compare-exchange 13462 // loop from 13463 // 13464 // ... 13465 // dst = atomic-fetch-op MI.addr, MI.val 13466 // ... 13467 // 13468 // to 13469 // 13470 // ... 13471 // t1L = LOAD [MI.addr + 0] 13472 // t1H = LOAD [MI.addr + 4] 13473 // loop: 13474 // t4L = phi(t1L, t3L / loop) 13475 // t4H = phi(t1H, t3H / loop) 13476 // t2L = OP MI.val.lo, t4L 13477 // t2H = OP MI.val.hi, t4H 13478 // EAX = t4L 13479 // EDX = t4H 13480 // EBX = t2L 13481 // ECX = t2H 13482 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13483 // t3L = EAX 13484 // t3H = EDX 13485 // JNE loop 13486 // sink: 13487 // dstL = t3L 13488 // dstH = t3H 13489 // ... 13490 MachineBasicBlock * 13491 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI, 13492 MachineBasicBlock *MBB) const { 13493 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13494 DebugLoc DL = MI->getDebugLoc(); 13495 13496 MachineFunction *MF = MBB->getParent(); 13497 MachineRegisterInfo &MRI = MF->getRegInfo(); 13498 13499 const BasicBlock *BB = MBB->getBasicBlock(); 13500 MachineFunction::iterator I = MBB; 13501 ++I; 13502 13503 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 && 13504 "Unexpected number of operands"); 13505 13506 assert(MI->hasOneMemOperand() && 13507 "Expected atomic-load-op32 to have one memoperand"); 13508 13509 // Memory Reference 13510 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13511 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13512 13513 unsigned DstLoReg, DstHiReg; 13514 unsigned SrcLoReg, SrcHiReg; 13515 unsigned MemOpndSlot; 13516 13517 unsigned CurOp = 0; 13518 13519 DstLoReg = MI->getOperand(CurOp++).getReg(); 13520 DstHiReg = MI->getOperand(CurOp++).getReg(); 13521 MemOpndSlot = CurOp; 13522 CurOp += X86::AddrNumOperands; 13523 SrcLoReg = MI->getOperand(CurOp++).getReg(); 13524 SrcHiReg = MI->getOperand(CurOp++).getReg(); 13525 13526 const TargetRegisterClass *RC = &X86::GR32RegClass; 13527 const TargetRegisterClass *RC8 = &X86::GR8RegClass; 13528 13529 unsigned t1L = MRI.createVirtualRegister(RC); 13530 unsigned t1H = MRI.createVirtualRegister(RC); 13531 unsigned t2L = MRI.createVirtualRegister(RC); 13532 unsigned t2H = MRI.createVirtualRegister(RC); 13533 unsigned t3L = MRI.createVirtualRegister(RC); 13534 unsigned t3H = MRI.createVirtualRegister(RC); 13535 unsigned t4L = MRI.createVirtualRegister(RC); 13536 unsigned t4H = MRI.createVirtualRegister(RC); 13537 13538 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B; 13539 unsigned LOADOpc = X86::MOV32rm; 13540 13541 // For the atomic load-arith operator, we generate 13542 // 13543 // thisMBB: 13544 // t1L = LOAD [MI.addr + 0] 13545 // t1H = LOAD [MI.addr + 4] 13546 // mainMBB: 13547 // t4L = phi(t1L / thisMBB, t3L / mainMBB) 13548 // t4H = phi(t1H / thisMBB, t3H / mainMBB) 13549 // t2L = OP MI.val.lo, t4L 13550 // t2H = OP MI.val.hi, t4H 13551 // EBX = t2L 13552 // ECX = t2H 13553 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13554 // t3L = EAX 13555 // t3H = EDX 13556 // JNE loop 13557 // sinkMBB: 13558 // dstL = t3L 13559 // dstH = t3H 13560 13561 MachineBasicBlock *thisMBB = MBB; 13562 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13563 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13564 MF->insert(I, mainMBB); 13565 MF->insert(I, sinkMBB); 13566 13567 MachineInstrBuilder MIB; 13568 13569 // Transfer the remainder of BB and its successor edges to sinkMBB. 13570 sinkMBB->splice(sinkMBB->begin(), MBB, 13571 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13572 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13573 13574 // thisMBB: 13575 // Lo 13576 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L); 13577 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13578 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13579 if (NewMO.isReg()) 13580 NewMO.setIsKill(false); 13581 MIB.addOperand(NewMO); 13582 } 13583 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) { 13584 unsigned flags = (*MMOI)->getFlags(); 13585 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad; 13586 MachineMemOperand *MMO = 13587 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags, 13588 (*MMOI)->getSize(), 13589 (*MMOI)->getBaseAlignment(), 13590 (*MMOI)->getTBAAInfo(), 13591 (*MMOI)->getRanges()); 13592 MIB.addMemOperand(MMO); 13593 }; 13594 MachineInstr *LowMI = MIB; 13595 13596 // Hi 13597 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H); 13598 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13599 if (i == X86::AddrDisp) { 13600 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32) 13601 } else { 13602 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13603 if (NewMO.isReg()) 13604 NewMO.setIsKill(false); 13605 MIB.addOperand(NewMO); 13606 } 13607 } 13608 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end()); 13609 13610 thisMBB->addSuccessor(mainMBB); 13611 13612 // mainMBB: 13613 MachineBasicBlock *origMainMBB = mainMBB; 13614 13615 // Add PHIs. 13616 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L) 13617 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB); 13618 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H) 13619 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB); 13620 13621 unsigned Opc = MI->getOpcode(); 13622 switch (Opc) { 13623 default: 13624 llvm_unreachable("Unhandled atomic-load-op6432 opcode!"); 13625 case X86::ATOMAND6432: 13626 case X86::ATOMOR6432: 13627 case X86::ATOMXOR6432: 13628 case X86::ATOMADD6432: 13629 case X86::ATOMSUB6432: { 13630 unsigned HiOpc; 13631 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13632 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L) 13633 .addReg(SrcLoReg); 13634 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H) 13635 .addReg(SrcHiReg); 13636 break; 13637 } 13638 case X86::ATOMNAND6432: { 13639 unsigned HiOpc, NOTOpc; 13640 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc); 13641 unsigned TmpL = MRI.createVirtualRegister(RC); 13642 unsigned TmpH = MRI.createVirtualRegister(RC); 13643 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg) 13644 .addReg(t4L); 13645 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg) 13646 .addReg(t4H); 13647 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL); 13648 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH); 13649 break; 13650 } 13651 case X86::ATOMMAX6432: 13652 case X86::ATOMMIN6432: 13653 case X86::ATOMUMAX6432: 13654 case X86::ATOMUMIN6432: { 13655 unsigned HiOpc; 13656 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13657 unsigned cL = MRI.createVirtualRegister(RC8); 13658 unsigned cH = MRI.createVirtualRegister(RC8); 13659 unsigned cL32 = MRI.createVirtualRegister(RC); 13660 unsigned cH32 = MRI.createVirtualRegister(RC); 13661 unsigned cc = MRI.createVirtualRegister(RC); 13662 // cl := cmp src_lo, lo 13663 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 13664 .addReg(SrcLoReg).addReg(t4L); 13665 BuildMI(mainMBB, DL, TII->get(LoOpc), cL); 13666 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL); 13667 // ch := cmp src_hi, hi 13668 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 13669 .addReg(SrcHiReg).addReg(t4H); 13670 BuildMI(mainMBB, DL, TII->get(HiOpc), cH); 13671 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH); 13672 // cc := if (src_hi == hi) ? cl : ch; 13673 if (Subtarget->hasCMov()) { 13674 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc) 13675 .addReg(cH32).addReg(cL32); 13676 } else { 13677 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc) 13678 .addReg(cH32).addReg(cL32) 13679 .addImm(X86::COND_E); 13680 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13681 } 13682 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc); 13683 if (Subtarget->hasCMov()) { 13684 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L) 13685 .addReg(SrcLoReg).addReg(t4L); 13686 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H) 13687 .addReg(SrcHiReg).addReg(t4H); 13688 } else { 13689 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L) 13690 .addReg(SrcLoReg).addReg(t4L) 13691 .addImm(X86::COND_NE); 13692 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13693 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the 13694 // 2nd CMOV lowering. 13695 mainMBB->addLiveIn(X86::EFLAGS); 13696 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H) 13697 .addReg(SrcHiReg).addReg(t4H) 13698 .addImm(X86::COND_NE); 13699 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13700 // Replace the original PHI node as mainMBB is changed after CMOV 13701 // lowering. 13702 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L) 13703 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB); 13704 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H) 13705 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB); 13706 PhiL->eraseFromParent(); 13707 PhiH->eraseFromParent(); 13708 } 13709 break; 13710 } 13711 case X86::ATOMSWAP6432: { 13712 unsigned HiOpc; 13713 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13714 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg); 13715 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg); 13716 break; 13717 } 13718 } 13719 13720 // Copy EDX:EAX back from HiReg:LoReg 13721 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L); 13722 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H); 13723 // Copy ECX:EBX from t1H:t1L 13724 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L); 13725 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H); 13726 13727 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 13728 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13729 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i); 13730 if (NewMO.isReg()) 13731 NewMO.setIsKill(false); 13732 MIB.addOperand(NewMO); 13733 } 13734 MIB.setMemRefs(MMOBegin, MMOEnd); 13735 13736 // Copy EDX:EAX back to t3H:t3L 13737 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX); 13738 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX); 13739 13740 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 13741 13742 mainMBB->addSuccessor(origMainMBB); 13743 mainMBB->addSuccessor(sinkMBB); 13744 13745 // sinkMBB: 13746 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13747 TII->get(TargetOpcode::COPY), DstLoReg) 13748 .addReg(t3L); 13749 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13750 TII->get(TargetOpcode::COPY), DstHiReg) 13751 .addReg(t3H); 13752 13753 MI->eraseFromParent(); 13754 return sinkMBB; 13755 } 13756 13757 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 13758 // or XMM0_V32I8 in AVX all of this code can be replaced with that 13759 // in the .td file. 13760 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB, 13761 const TargetInstrInfo *TII) { 13762 unsigned Opc; 13763 switch (MI->getOpcode()) { 13764 default: llvm_unreachable("illegal opcode!"); 13765 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break; 13766 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break; 13767 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break; 13768 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break; 13769 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break; 13770 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break; 13771 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break; 13772 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break; 13773 } 13774 13775 DebugLoc dl = MI->getDebugLoc(); 13776 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 13777 13778 unsigned NumArgs = MI->getNumOperands(); 13779 for (unsigned i = 1; i < NumArgs; ++i) { 13780 MachineOperand &Op = MI->getOperand(i); 13781 if (!(Op.isReg() && Op.isImplicit())) 13782 MIB.addOperand(Op); 13783 } 13784 if (MI->hasOneMemOperand()) 13785 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 13786 13787 BuildMI(*BB, MI, dl, 13788 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13789 .addReg(X86::XMM0); 13790 13791 MI->eraseFromParent(); 13792 return BB; 13793 } 13794 13795 // FIXME: Custom handling because TableGen doesn't support multiple implicit 13796 // defs in an instruction pattern 13797 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB, 13798 const TargetInstrInfo *TII) { 13799 unsigned Opc; 13800 switch (MI->getOpcode()) { 13801 default: llvm_unreachable("illegal opcode!"); 13802 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break; 13803 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break; 13804 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break; 13805 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break; 13806 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break; 13807 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break; 13808 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break; 13809 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break; 13810 } 13811 13812 DebugLoc dl = MI->getDebugLoc(); 13813 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 13814 13815 unsigned NumArgs = MI->getNumOperands(); // remove the results 13816 for (unsigned i = 1; i < NumArgs; ++i) { 13817 MachineOperand &Op = MI->getOperand(i); 13818 if (!(Op.isReg() && Op.isImplicit())) 13819 MIB.addOperand(Op); 13820 } 13821 if (MI->hasOneMemOperand()) 13822 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 13823 13824 BuildMI(*BB, MI, dl, 13825 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13826 .addReg(X86::ECX); 13827 13828 MI->eraseFromParent(); 13829 return BB; 13830 } 13831 13832 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB, 13833 const TargetInstrInfo *TII, 13834 const X86Subtarget* Subtarget) { 13835 DebugLoc dl = MI->getDebugLoc(); 13836 13837 // Address into RAX/EAX, other two args into ECX, EDX. 13838 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 13839 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 13840 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 13841 for (int i = 0; i < X86::AddrNumOperands; ++i) 13842 MIB.addOperand(MI->getOperand(i)); 13843 13844 unsigned ValOps = X86::AddrNumOperands; 13845 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 13846 .addReg(MI->getOperand(ValOps).getReg()); 13847 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 13848 .addReg(MI->getOperand(ValOps+1).getReg()); 13849 13850 // The instruction doesn't actually take any operands though. 13851 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 13852 13853 MI->eraseFromParent(); // The pseudo is gone now. 13854 return BB; 13855 } 13856 13857 MachineBasicBlock * 13858 X86TargetLowering::EmitVAARG64WithCustomInserter( 13859 MachineInstr *MI, 13860 MachineBasicBlock *MBB) const { 13861 // Emit va_arg instruction on X86-64. 13862 13863 // Operands to this pseudo-instruction: 13864 // 0 ) Output : destination address (reg) 13865 // 1-5) Input : va_list address (addr, i64mem) 13866 // 6 ) ArgSize : Size (in bytes) of vararg type 13867 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 13868 // 8 ) Align : Alignment of type 13869 // 9 ) EFLAGS (implicit-def) 13870 13871 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 13872 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 13873 13874 unsigned DestReg = MI->getOperand(0).getReg(); 13875 MachineOperand &Base = MI->getOperand(1); 13876 MachineOperand &Scale = MI->getOperand(2); 13877 MachineOperand &Index = MI->getOperand(3); 13878 MachineOperand &Disp = MI->getOperand(4); 13879 MachineOperand &Segment = MI->getOperand(5); 13880 unsigned ArgSize = MI->getOperand(6).getImm(); 13881 unsigned ArgMode = MI->getOperand(7).getImm(); 13882 unsigned Align = MI->getOperand(8).getImm(); 13883 13884 // Memory Reference 13885 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 13886 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13887 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13888 13889 // Machine Information 13890 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13891 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 13892 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 13893 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 13894 DebugLoc DL = MI->getDebugLoc(); 13895 13896 // struct va_list { 13897 // i32 gp_offset 13898 // i32 fp_offset 13899 // i64 overflow_area (address) 13900 // i64 reg_save_area (address) 13901 // } 13902 // sizeof(va_list) = 24 13903 // alignment(va_list) = 8 13904 13905 unsigned TotalNumIntRegs = 6; 13906 unsigned TotalNumXMMRegs = 8; 13907 bool UseGPOffset = (ArgMode == 1); 13908 bool UseFPOffset = (ArgMode == 2); 13909 unsigned MaxOffset = TotalNumIntRegs * 8 + 13910 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 13911 13912 /* Align ArgSize to a multiple of 8 */ 13913 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 13914 bool NeedsAlign = (Align > 8); 13915 13916 MachineBasicBlock *thisMBB = MBB; 13917 MachineBasicBlock *overflowMBB; 13918 MachineBasicBlock *offsetMBB; 13919 MachineBasicBlock *endMBB; 13920 13921 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 13922 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 13923 unsigned OffsetReg = 0; 13924 13925 if (!UseGPOffset && !UseFPOffset) { 13926 // If we only pull from the overflow region, we don't create a branch. 13927 // We don't need to alter control flow. 13928 OffsetDestReg = 0; // unused 13929 OverflowDestReg = DestReg; 13930 13931 offsetMBB = NULL; 13932 overflowMBB = thisMBB; 13933 endMBB = thisMBB; 13934 } else { 13935 // First emit code to check if gp_offset (or fp_offset) is below the bound. 13936 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 13937 // If not, pull from overflow_area. (branch to overflowMBB) 13938 // 13939 // thisMBB 13940 // | . 13941 // | . 13942 // offsetMBB overflowMBB 13943 // | . 13944 // | . 13945 // endMBB 13946 13947 // Registers for the PHI in endMBB 13948 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 13949 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 13950 13951 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 13952 MachineFunction *MF = MBB->getParent(); 13953 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13954 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13955 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13956 13957 MachineFunction::iterator MBBIter = MBB; 13958 ++MBBIter; 13959 13960 // Insert the new basic blocks 13961 MF->insert(MBBIter, offsetMBB); 13962 MF->insert(MBBIter, overflowMBB); 13963 MF->insert(MBBIter, endMBB); 13964 13965 // Transfer the remainder of MBB and its successor edges to endMBB. 13966 endMBB->splice(endMBB->begin(), thisMBB, 13967 llvm::next(MachineBasicBlock::iterator(MI)), 13968 thisMBB->end()); 13969 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 13970 13971 // Make offsetMBB and overflowMBB successors of thisMBB 13972 thisMBB->addSuccessor(offsetMBB); 13973 thisMBB->addSuccessor(overflowMBB); 13974 13975 // endMBB is a successor of both offsetMBB and overflowMBB 13976 offsetMBB->addSuccessor(endMBB); 13977 overflowMBB->addSuccessor(endMBB); 13978 13979 // Load the offset value into a register 13980 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 13981 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 13982 .addOperand(Base) 13983 .addOperand(Scale) 13984 .addOperand(Index) 13985 .addDisp(Disp, UseFPOffset ? 4 : 0) 13986 .addOperand(Segment) 13987 .setMemRefs(MMOBegin, MMOEnd); 13988 13989 // Check if there is enough room left to pull this argument. 13990 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 13991 .addReg(OffsetReg) 13992 .addImm(MaxOffset + 8 - ArgSizeA8); 13993 13994 // Branch to "overflowMBB" if offset >= max 13995 // Fall through to "offsetMBB" otherwise 13996 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 13997 .addMBB(overflowMBB); 13998 } 13999 14000 // In offsetMBB, emit code to use the reg_save_area. 14001 if (offsetMBB) { 14002 assert(OffsetReg != 0); 14003 14004 // Read the reg_save_area address. 14005 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 14006 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 14007 .addOperand(Base) 14008 .addOperand(Scale) 14009 .addOperand(Index) 14010 .addDisp(Disp, 16) 14011 .addOperand(Segment) 14012 .setMemRefs(MMOBegin, MMOEnd); 14013 14014 // Zero-extend the offset 14015 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 14016 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 14017 .addImm(0) 14018 .addReg(OffsetReg) 14019 .addImm(X86::sub_32bit); 14020 14021 // Add the offset to the reg_save_area to get the final address. 14022 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 14023 .addReg(OffsetReg64) 14024 .addReg(RegSaveReg); 14025 14026 // Compute the offset for the next argument 14027 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 14028 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 14029 .addReg(OffsetReg) 14030 .addImm(UseFPOffset ? 16 : 8); 14031 14032 // Store it back into the va_list. 14033 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 14034 .addOperand(Base) 14035 .addOperand(Scale) 14036 .addOperand(Index) 14037 .addDisp(Disp, UseFPOffset ? 4 : 0) 14038 .addOperand(Segment) 14039 .addReg(NextOffsetReg) 14040 .setMemRefs(MMOBegin, MMOEnd); 14041 14042 // Jump to endMBB 14043 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 14044 .addMBB(endMBB); 14045 } 14046 14047 // 14048 // Emit code to use overflow area 14049 // 14050 14051 // Load the overflow_area address into a register. 14052 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 14053 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 14054 .addOperand(Base) 14055 .addOperand(Scale) 14056 .addOperand(Index) 14057 .addDisp(Disp, 8) 14058 .addOperand(Segment) 14059 .setMemRefs(MMOBegin, MMOEnd); 14060 14061 // If we need to align it, do so. Otherwise, just copy the address 14062 // to OverflowDestReg. 14063 if (NeedsAlign) { 14064 // Align the overflow address 14065 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 14066 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 14067 14068 // aligned_addr = (addr + (align-1)) & ~(align-1) 14069 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 14070 .addReg(OverflowAddrReg) 14071 .addImm(Align-1); 14072 14073 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 14074 .addReg(TmpReg) 14075 .addImm(~(uint64_t)(Align-1)); 14076 } else { 14077 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 14078 .addReg(OverflowAddrReg); 14079 } 14080 14081 // Compute the next overflow address after this argument. 14082 // (the overflow address should be kept 8-byte aligned) 14083 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 14084 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 14085 .addReg(OverflowDestReg) 14086 .addImm(ArgSizeA8); 14087 14088 // Store the new overflow address. 14089 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 14090 .addOperand(Base) 14091 .addOperand(Scale) 14092 .addOperand(Index) 14093 .addDisp(Disp, 8) 14094 .addOperand(Segment) 14095 .addReg(NextAddrReg) 14096 .setMemRefs(MMOBegin, MMOEnd); 14097 14098 // If we branched, emit the PHI to the front of endMBB. 14099 if (offsetMBB) { 14100 BuildMI(*endMBB, endMBB->begin(), DL, 14101 TII->get(X86::PHI), DestReg) 14102 .addReg(OffsetDestReg).addMBB(offsetMBB) 14103 .addReg(OverflowDestReg).addMBB(overflowMBB); 14104 } 14105 14106 // Erase the pseudo instruction 14107 MI->eraseFromParent(); 14108 14109 return endMBB; 14110 } 14111 14112 MachineBasicBlock * 14113 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 14114 MachineInstr *MI, 14115 MachineBasicBlock *MBB) const { 14116 // Emit code to save XMM registers to the stack. The ABI says that the 14117 // number of registers to save is given in %al, so it's theoretically 14118 // possible to do an indirect jump trick to avoid saving all of them, 14119 // however this code takes a simpler approach and just executes all 14120 // of the stores if %al is non-zero. It's less code, and it's probably 14121 // easier on the hardware branch predictor, and stores aren't all that 14122 // expensive anyway. 14123 14124 // Create the new basic blocks. One block contains all the XMM stores, 14125 // and one block is the final destination regardless of whether any 14126 // stores were performed. 14127 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 14128 MachineFunction *F = MBB->getParent(); 14129 MachineFunction::iterator MBBIter = MBB; 14130 ++MBBIter; 14131 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 14132 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 14133 F->insert(MBBIter, XMMSaveMBB); 14134 F->insert(MBBIter, EndMBB); 14135 14136 // Transfer the remainder of MBB and its successor edges to EndMBB. 14137 EndMBB->splice(EndMBB->begin(), MBB, 14138 llvm::next(MachineBasicBlock::iterator(MI)), 14139 MBB->end()); 14140 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 14141 14142 // The original block will now fall through to the XMM save block. 14143 MBB->addSuccessor(XMMSaveMBB); 14144 // The XMMSaveMBB will fall through to the end block. 14145 XMMSaveMBB->addSuccessor(EndMBB); 14146 14147 // Now add the instructions. 14148 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14149 DebugLoc DL = MI->getDebugLoc(); 14150 14151 unsigned CountReg = MI->getOperand(0).getReg(); 14152 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 14153 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 14154 14155 if (!Subtarget->isTargetWin64()) { 14156 // If %al is 0, branch around the XMM save block. 14157 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 14158 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 14159 MBB->addSuccessor(EndMBB); 14160 } 14161 14162 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr; 14163 // In the XMM save block, save all the XMM argument registers. 14164 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 14165 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 14166 MachineMemOperand *MMO = 14167 F->getMachineMemOperand( 14168 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 14169 MachineMemOperand::MOStore, 14170 /*Size=*/16, /*Align=*/16); 14171 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 14172 .addFrameIndex(RegSaveFrameIndex) 14173 .addImm(/*Scale=*/1) 14174 .addReg(/*IndexReg=*/0) 14175 .addImm(/*Disp=*/Offset) 14176 .addReg(/*Segment=*/0) 14177 .addReg(MI->getOperand(i).getReg()) 14178 .addMemOperand(MMO); 14179 } 14180 14181 MI->eraseFromParent(); // The pseudo instruction is gone now. 14182 14183 return EndMBB; 14184 } 14185 14186 // The EFLAGS operand of SelectItr might be missing a kill marker 14187 // because there were multiple uses of EFLAGS, and ISel didn't know 14188 // which to mark. Figure out whether SelectItr should have had a 14189 // kill marker, and set it if it should. Returns the correct kill 14190 // marker value. 14191 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr, 14192 MachineBasicBlock* BB, 14193 const TargetRegisterInfo* TRI) { 14194 // Scan forward through BB for a use/def of EFLAGS. 14195 MachineBasicBlock::iterator miI(llvm::next(SelectItr)); 14196 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 14197 const MachineInstr& mi = *miI; 14198 if (mi.readsRegister(X86::EFLAGS)) 14199 return false; 14200 if (mi.definesRegister(X86::EFLAGS)) 14201 break; // Should have kill-flag - update below. 14202 } 14203 14204 // If we hit the end of the block, check whether EFLAGS is live into a 14205 // successor. 14206 if (miI == BB->end()) { 14207 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 14208 sEnd = BB->succ_end(); 14209 sItr != sEnd; ++sItr) { 14210 MachineBasicBlock* succ = *sItr; 14211 if (succ->isLiveIn(X86::EFLAGS)) 14212 return false; 14213 } 14214 } 14215 14216 // We found a def, or hit the end of the basic block and EFLAGS wasn't live 14217 // out. SelectMI should have a kill flag on EFLAGS. 14218 SelectItr->addRegisterKilled(X86::EFLAGS, TRI); 14219 return true; 14220 } 14221 14222 MachineBasicBlock * 14223 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 14224 MachineBasicBlock *BB) const { 14225 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14226 DebugLoc DL = MI->getDebugLoc(); 14227 14228 // To "insert" a SELECT_CC instruction, we actually have to insert the 14229 // diamond control-flow pattern. The incoming instruction knows the 14230 // destination vreg to set, the condition code register to branch on, the 14231 // true/false values to select between, and a branch opcode to use. 14232 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 14233 MachineFunction::iterator It = BB; 14234 ++It; 14235 14236 // thisMBB: 14237 // ... 14238 // TrueVal = ... 14239 // cmpTY ccX, r1, r2 14240 // bCC copy1MBB 14241 // fallthrough --> copy0MBB 14242 MachineBasicBlock *thisMBB = BB; 14243 MachineFunction *F = BB->getParent(); 14244 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 14245 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 14246 F->insert(It, copy0MBB); 14247 F->insert(It, sinkMBB); 14248 14249 // If the EFLAGS register isn't dead in the terminator, then claim that it's 14250 // live into the sink and copy blocks. 14251 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 14252 if (!MI->killsRegister(X86::EFLAGS) && 14253 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) { 14254 copy0MBB->addLiveIn(X86::EFLAGS); 14255 sinkMBB->addLiveIn(X86::EFLAGS); 14256 } 14257 14258 // Transfer the remainder of BB and its successor edges to sinkMBB. 14259 sinkMBB->splice(sinkMBB->begin(), BB, 14260 llvm::next(MachineBasicBlock::iterator(MI)), 14261 BB->end()); 14262 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 14263 14264 // Add the true and fallthrough blocks as its successors. 14265 BB->addSuccessor(copy0MBB); 14266 BB->addSuccessor(sinkMBB); 14267 14268 // Create the conditional branch instruction. 14269 unsigned Opc = 14270 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 14271 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 14272 14273 // copy0MBB: 14274 // %FalseValue = ... 14275 // # fallthrough to sinkMBB 14276 copy0MBB->addSuccessor(sinkMBB); 14277 14278 // sinkMBB: 14279 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 14280 // ... 14281 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14282 TII->get(X86::PHI), MI->getOperand(0).getReg()) 14283 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 14284 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 14285 14286 MI->eraseFromParent(); // The pseudo instruction is gone now. 14287 return sinkMBB; 14288 } 14289 14290 MachineBasicBlock * 14291 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 14292 bool Is64Bit) const { 14293 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14294 DebugLoc DL = MI->getDebugLoc(); 14295 MachineFunction *MF = BB->getParent(); 14296 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 14297 14298 assert(getTargetMachine().Options.EnableSegmentedStacks); 14299 14300 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 14301 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 14302 14303 // BB: 14304 // ... [Till the alloca] 14305 // If stacklet is not large enough, jump to mallocMBB 14306 // 14307 // bumpMBB: 14308 // Allocate by subtracting from RSP 14309 // Jump to continueMBB 14310 // 14311 // mallocMBB: 14312 // Allocate by call to runtime 14313 // 14314 // continueMBB: 14315 // ... 14316 // [rest of original BB] 14317 // 14318 14319 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14320 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14321 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 14322 14323 MachineRegisterInfo &MRI = MF->getRegInfo(); 14324 const TargetRegisterClass *AddrRegClass = 14325 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 14326 14327 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 14328 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 14329 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 14330 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 14331 sizeVReg = MI->getOperand(1).getReg(), 14332 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 14333 14334 MachineFunction::iterator MBBIter = BB; 14335 ++MBBIter; 14336 14337 MF->insert(MBBIter, bumpMBB); 14338 MF->insert(MBBIter, mallocMBB); 14339 MF->insert(MBBIter, continueMBB); 14340 14341 continueMBB->splice(continueMBB->begin(), BB, llvm::next 14342 (MachineBasicBlock::iterator(MI)), BB->end()); 14343 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 14344 14345 // Add code to the main basic block to check if the stack limit has been hit, 14346 // and if so, jump to mallocMBB otherwise to bumpMBB. 14347 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 14348 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 14349 .addReg(tmpSPVReg).addReg(sizeVReg); 14350 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 14351 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg) 14352 .addReg(SPLimitVReg); 14353 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 14354 14355 // bumpMBB simply decreases the stack pointer, since we know the current 14356 // stacklet has enough space. 14357 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 14358 .addReg(SPLimitVReg); 14359 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 14360 .addReg(SPLimitVReg); 14361 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 14362 14363 // Calls into a routine in libgcc to allocate more space from the heap. 14364 const uint32_t *RegMask = 14365 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 14366 if (Is64Bit) { 14367 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 14368 .addReg(sizeVReg); 14369 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 14370 .addExternalSymbol("__morestack_allocate_stack_space") 14371 .addRegMask(RegMask) 14372 .addReg(X86::RDI, RegState::Implicit) 14373 .addReg(X86::RAX, RegState::ImplicitDefine); 14374 } else { 14375 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 14376 .addImm(12); 14377 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 14378 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 14379 .addExternalSymbol("__morestack_allocate_stack_space") 14380 .addRegMask(RegMask) 14381 .addReg(X86::EAX, RegState::ImplicitDefine); 14382 } 14383 14384 if (!Is64Bit) 14385 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 14386 .addImm(16); 14387 14388 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 14389 .addReg(Is64Bit ? X86::RAX : X86::EAX); 14390 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 14391 14392 // Set up the CFG correctly. 14393 BB->addSuccessor(bumpMBB); 14394 BB->addSuccessor(mallocMBB); 14395 mallocMBB->addSuccessor(continueMBB); 14396 bumpMBB->addSuccessor(continueMBB); 14397 14398 // Take care of the PHI nodes. 14399 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 14400 MI->getOperand(0).getReg()) 14401 .addReg(mallocPtrVReg).addMBB(mallocMBB) 14402 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 14403 14404 // Delete the original pseudo instruction. 14405 MI->eraseFromParent(); 14406 14407 // And we're done. 14408 return continueMBB; 14409 } 14410 14411 MachineBasicBlock * 14412 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 14413 MachineBasicBlock *BB) const { 14414 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14415 DebugLoc DL = MI->getDebugLoc(); 14416 14417 assert(!Subtarget->isTargetEnvMacho()); 14418 14419 // The lowering is pretty easy: we're just emitting the call to _alloca. The 14420 // non-trivial part is impdef of ESP. 14421 14422 if (Subtarget->isTargetWin64()) { 14423 if (Subtarget->isTargetCygMing()) { 14424 // ___chkstk(Mingw64): 14425 // Clobbers R10, R11, RAX and EFLAGS. 14426 // Updates RSP. 14427 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 14428 .addExternalSymbol("___chkstk") 14429 .addReg(X86::RAX, RegState::Implicit) 14430 .addReg(X86::RSP, RegState::Implicit) 14431 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 14432 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 14433 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14434 } else { 14435 // __chkstk(MSVCRT): does not update stack pointer. 14436 // Clobbers R10, R11 and EFLAGS. 14437 // FIXME: RAX(allocated size) might be reused and not killed. 14438 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 14439 .addExternalSymbol("__chkstk") 14440 .addReg(X86::RAX, RegState::Implicit) 14441 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14442 // RAX has the offset to subtracted from RSP. 14443 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 14444 .addReg(X86::RSP) 14445 .addReg(X86::RAX); 14446 } 14447 } else { 14448 const char *StackProbeSymbol = 14449 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 14450 14451 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 14452 .addExternalSymbol(StackProbeSymbol) 14453 .addReg(X86::EAX, RegState::Implicit) 14454 .addReg(X86::ESP, RegState::Implicit) 14455 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 14456 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 14457 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 14458 } 14459 14460 MI->eraseFromParent(); // The pseudo instruction is gone now. 14461 return BB; 14462 } 14463 14464 MachineBasicBlock * 14465 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 14466 MachineBasicBlock *BB) const { 14467 // This is pretty easy. We're taking the value that we received from 14468 // our load from the relocation, sticking it in either RDI (x86-64) 14469 // or EAX and doing an indirect call. The return value will then 14470 // be in the normal return register. 14471 const X86InstrInfo *TII 14472 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 14473 DebugLoc DL = MI->getDebugLoc(); 14474 MachineFunction *F = BB->getParent(); 14475 14476 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 14477 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 14478 14479 // Get a register mask for the lowered call. 14480 // FIXME: The 32-bit calls have non-standard calling conventions. Use a 14481 // proper register mask. 14482 const uint32_t *RegMask = 14483 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 14484 if (Subtarget->is64Bit()) { 14485 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14486 TII->get(X86::MOV64rm), X86::RDI) 14487 .addReg(X86::RIP) 14488 .addImm(0).addReg(0) 14489 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14490 MI->getOperand(3).getTargetFlags()) 14491 .addReg(0); 14492 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 14493 addDirectMem(MIB, X86::RDI); 14494 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask); 14495 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 14496 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14497 TII->get(X86::MOV32rm), X86::EAX) 14498 .addReg(0) 14499 .addImm(0).addReg(0) 14500 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14501 MI->getOperand(3).getTargetFlags()) 14502 .addReg(0); 14503 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14504 addDirectMem(MIB, X86::EAX); 14505 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14506 } else { 14507 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14508 TII->get(X86::MOV32rm), X86::EAX) 14509 .addReg(TII->getGlobalBaseReg(F)) 14510 .addImm(0).addReg(0) 14511 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14512 MI->getOperand(3).getTargetFlags()) 14513 .addReg(0); 14514 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14515 addDirectMem(MIB, X86::EAX); 14516 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14517 } 14518 14519 MI->eraseFromParent(); // The pseudo instruction is gone now. 14520 return BB; 14521 } 14522 14523 MachineBasicBlock * 14524 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 14525 MachineBasicBlock *MBB) const { 14526 DebugLoc DL = MI->getDebugLoc(); 14527 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14528 14529 MachineFunction *MF = MBB->getParent(); 14530 MachineRegisterInfo &MRI = MF->getRegInfo(); 14531 14532 const BasicBlock *BB = MBB->getBasicBlock(); 14533 MachineFunction::iterator I = MBB; 14534 ++I; 14535 14536 // Memory Reference 14537 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14538 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14539 14540 unsigned DstReg; 14541 unsigned MemOpndSlot = 0; 14542 14543 unsigned CurOp = 0; 14544 14545 DstReg = MI->getOperand(CurOp++).getReg(); 14546 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 14547 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 14548 unsigned mainDstReg = MRI.createVirtualRegister(RC); 14549 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 14550 14551 MemOpndSlot = CurOp; 14552 14553 MVT PVT = getPointerTy(); 14554 assert((PVT == MVT::i64 || PVT == MVT::i32) && 14555 "Invalid Pointer Size!"); 14556 14557 // For v = setjmp(buf), we generate 14558 // 14559 // thisMBB: 14560 // buf[LabelOffset] = restoreMBB 14561 // SjLjSetup restoreMBB 14562 // 14563 // mainMBB: 14564 // v_main = 0 14565 // 14566 // sinkMBB: 14567 // v = phi(main, restore) 14568 // 14569 // restoreMBB: 14570 // v_restore = 1 14571 14572 MachineBasicBlock *thisMBB = MBB; 14573 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 14574 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 14575 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB); 14576 MF->insert(I, mainMBB); 14577 MF->insert(I, sinkMBB); 14578 MF->push_back(restoreMBB); 14579 14580 MachineInstrBuilder MIB; 14581 14582 // Transfer the remainder of BB and its successor edges to sinkMBB. 14583 sinkMBB->splice(sinkMBB->begin(), MBB, 14584 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 14585 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 14586 14587 // thisMBB: 14588 unsigned PtrStoreOpc = 0; 14589 unsigned LabelReg = 0; 14590 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 14591 Reloc::Model RM = getTargetMachine().getRelocationModel(); 14592 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) && 14593 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC); 14594 14595 // Prepare IP either in reg or imm. 14596 if (!UseImmLabel) { 14597 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr; 14598 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 14599 LabelReg = MRI.createVirtualRegister(PtrRC); 14600 if (Subtarget->is64Bit()) { 14601 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg) 14602 .addReg(X86::RIP) 14603 .addImm(0) 14604 .addReg(0) 14605 .addMBB(restoreMBB) 14606 .addReg(0); 14607 } else { 14608 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII); 14609 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg) 14610 .addReg(XII->getGlobalBaseReg(MF)) 14611 .addImm(0) 14612 .addReg(0) 14613 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference()) 14614 .addReg(0); 14615 } 14616 } else 14617 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi; 14618 // Store IP 14619 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc)); 14620 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14621 if (i == X86::AddrDisp) 14622 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset); 14623 else 14624 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 14625 } 14626 if (!UseImmLabel) 14627 MIB.addReg(LabelReg); 14628 else 14629 MIB.addMBB(restoreMBB); 14630 MIB.setMemRefs(MMOBegin, MMOEnd); 14631 // Setup 14632 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup)) 14633 .addMBB(restoreMBB); 14634 14635 const X86RegisterInfo *RegInfo = 14636 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 14637 MIB.addRegMask(RegInfo->getNoPreservedMask()); 14638 thisMBB->addSuccessor(mainMBB); 14639 thisMBB->addSuccessor(restoreMBB); 14640 14641 // mainMBB: 14642 // EAX = 0 14643 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg); 14644 mainMBB->addSuccessor(sinkMBB); 14645 14646 // sinkMBB: 14647 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14648 TII->get(X86::PHI), DstReg) 14649 .addReg(mainDstReg).addMBB(mainMBB) 14650 .addReg(restoreDstReg).addMBB(restoreMBB); 14651 14652 // restoreMBB: 14653 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1); 14654 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB); 14655 restoreMBB->addSuccessor(sinkMBB); 14656 14657 MI->eraseFromParent(); 14658 return sinkMBB; 14659 } 14660 14661 MachineBasicBlock * 14662 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 14663 MachineBasicBlock *MBB) const { 14664 DebugLoc DL = MI->getDebugLoc(); 14665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14666 14667 MachineFunction *MF = MBB->getParent(); 14668 MachineRegisterInfo &MRI = MF->getRegInfo(); 14669 14670 // Memory Reference 14671 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14672 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14673 14674 MVT PVT = getPointerTy(); 14675 assert((PVT == MVT::i64 || PVT == MVT::i32) && 14676 "Invalid Pointer Size!"); 14677 14678 const TargetRegisterClass *RC = 14679 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass; 14680 unsigned Tmp = MRI.createVirtualRegister(RC); 14681 // Since FP is only updated here but NOT referenced, it's treated as GPR. 14682 const X86RegisterInfo *RegInfo = 14683 static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo()); 14684 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP; 14685 unsigned SP = RegInfo->getStackRegister(); 14686 14687 MachineInstrBuilder MIB; 14688 14689 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 14690 const int64_t SPOffset = 2 * PVT.getStoreSize(); 14691 14692 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm; 14693 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r; 14694 14695 // Reload FP 14696 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP); 14697 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 14698 MIB.addOperand(MI->getOperand(i)); 14699 MIB.setMemRefs(MMOBegin, MMOEnd); 14700 // Reload IP 14701 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp); 14702 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14703 if (i == X86::AddrDisp) 14704 MIB.addDisp(MI->getOperand(i), LabelOffset); 14705 else 14706 MIB.addOperand(MI->getOperand(i)); 14707 } 14708 MIB.setMemRefs(MMOBegin, MMOEnd); 14709 // Reload SP 14710 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP); 14711 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14712 if (i == X86::AddrDisp) 14713 MIB.addDisp(MI->getOperand(i), SPOffset); 14714 else 14715 MIB.addOperand(MI->getOperand(i)); 14716 } 14717 MIB.setMemRefs(MMOBegin, MMOEnd); 14718 // Jump 14719 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp); 14720 14721 MI->eraseFromParent(); 14722 return MBB; 14723 } 14724 14725 MachineBasicBlock * 14726 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 14727 MachineBasicBlock *BB) const { 14728 switch (MI->getOpcode()) { 14729 default: llvm_unreachable("Unexpected instr type to insert"); 14730 case X86::TAILJMPd64: 14731 case X86::TAILJMPr64: 14732 case X86::TAILJMPm64: 14733 llvm_unreachable("TAILJMP64 would not be touched here."); 14734 case X86::TCRETURNdi64: 14735 case X86::TCRETURNri64: 14736 case X86::TCRETURNmi64: 14737 return BB; 14738 case X86::WIN_ALLOCA: 14739 return EmitLoweredWinAlloca(MI, BB); 14740 case X86::SEG_ALLOCA_32: 14741 return EmitLoweredSegAlloca(MI, BB, false); 14742 case X86::SEG_ALLOCA_64: 14743 return EmitLoweredSegAlloca(MI, BB, true); 14744 case X86::TLSCall_32: 14745 case X86::TLSCall_64: 14746 return EmitLoweredTLSCall(MI, BB); 14747 case X86::CMOV_GR8: 14748 case X86::CMOV_FR32: 14749 case X86::CMOV_FR64: 14750 case X86::CMOV_V4F32: 14751 case X86::CMOV_V2F64: 14752 case X86::CMOV_V2I64: 14753 case X86::CMOV_V8F32: 14754 case X86::CMOV_V4F64: 14755 case X86::CMOV_V4I64: 14756 case X86::CMOV_GR16: 14757 case X86::CMOV_GR32: 14758 case X86::CMOV_RFP32: 14759 case X86::CMOV_RFP64: 14760 case X86::CMOV_RFP80: 14761 return EmitLoweredSelect(MI, BB); 14762 14763 case X86::FP32_TO_INT16_IN_MEM: 14764 case X86::FP32_TO_INT32_IN_MEM: 14765 case X86::FP32_TO_INT64_IN_MEM: 14766 case X86::FP64_TO_INT16_IN_MEM: 14767 case X86::FP64_TO_INT32_IN_MEM: 14768 case X86::FP64_TO_INT64_IN_MEM: 14769 case X86::FP80_TO_INT16_IN_MEM: 14770 case X86::FP80_TO_INT32_IN_MEM: 14771 case X86::FP80_TO_INT64_IN_MEM: { 14772 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14773 DebugLoc DL = MI->getDebugLoc(); 14774 14775 // Change the floating point control register to use "round towards zero" 14776 // mode when truncating to an integer value. 14777 MachineFunction *F = BB->getParent(); 14778 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 14779 addFrameReference(BuildMI(*BB, MI, DL, 14780 TII->get(X86::FNSTCW16m)), CWFrameIdx); 14781 14782 // Load the old value of the high byte of the control word... 14783 unsigned OldCW = 14784 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass); 14785 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 14786 CWFrameIdx); 14787 14788 // Set the high part to be round to zero... 14789 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 14790 .addImm(0xC7F); 14791 14792 // Reload the modified control word now... 14793 addFrameReference(BuildMI(*BB, MI, DL, 14794 TII->get(X86::FLDCW16m)), CWFrameIdx); 14795 14796 // Restore the memory image of control word to original value 14797 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 14798 .addReg(OldCW); 14799 14800 // Get the X86 opcode to use. 14801 unsigned Opc; 14802 switch (MI->getOpcode()) { 14803 default: llvm_unreachable("illegal opcode!"); 14804 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 14805 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 14806 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 14807 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 14808 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 14809 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 14810 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 14811 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 14812 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 14813 } 14814 14815 X86AddressMode AM; 14816 MachineOperand &Op = MI->getOperand(0); 14817 if (Op.isReg()) { 14818 AM.BaseType = X86AddressMode::RegBase; 14819 AM.Base.Reg = Op.getReg(); 14820 } else { 14821 AM.BaseType = X86AddressMode::FrameIndexBase; 14822 AM.Base.FrameIndex = Op.getIndex(); 14823 } 14824 Op = MI->getOperand(1); 14825 if (Op.isImm()) 14826 AM.Scale = Op.getImm(); 14827 Op = MI->getOperand(2); 14828 if (Op.isImm()) 14829 AM.IndexReg = Op.getImm(); 14830 Op = MI->getOperand(3); 14831 if (Op.isGlobal()) { 14832 AM.GV = Op.getGlobal(); 14833 } else { 14834 AM.Disp = Op.getImm(); 14835 } 14836 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 14837 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 14838 14839 // Reload the original control word now. 14840 addFrameReference(BuildMI(*BB, MI, DL, 14841 TII->get(X86::FLDCW16m)), CWFrameIdx); 14842 14843 MI->eraseFromParent(); // The pseudo instruction is gone now. 14844 return BB; 14845 } 14846 // String/text processing lowering. 14847 case X86::PCMPISTRM128REG: 14848 case X86::VPCMPISTRM128REG: 14849 case X86::PCMPISTRM128MEM: 14850 case X86::VPCMPISTRM128MEM: 14851 case X86::PCMPESTRM128REG: 14852 case X86::VPCMPESTRM128REG: 14853 case X86::PCMPESTRM128MEM: 14854 case X86::VPCMPESTRM128MEM: 14855 assert(Subtarget->hasSSE42() && 14856 "Target must have SSE4.2 or AVX features enabled"); 14857 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo()); 14858 14859 // String/text processing lowering. 14860 case X86::PCMPISTRIREG: 14861 case X86::VPCMPISTRIREG: 14862 case X86::PCMPISTRIMEM: 14863 case X86::VPCMPISTRIMEM: 14864 case X86::PCMPESTRIREG: 14865 case X86::VPCMPESTRIREG: 14866 case X86::PCMPESTRIMEM: 14867 case X86::VPCMPESTRIMEM: 14868 assert(Subtarget->hasSSE42() && 14869 "Target must have SSE4.2 or AVX features enabled"); 14870 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo()); 14871 14872 // Thread synchronization. 14873 case X86::MONITOR: 14874 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget); 14875 14876 // xbegin 14877 case X86::XBEGIN: 14878 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo()); 14879 14880 // Atomic Lowering. 14881 case X86::ATOMAND8: 14882 case X86::ATOMAND16: 14883 case X86::ATOMAND32: 14884 case X86::ATOMAND64: 14885 // Fall through 14886 case X86::ATOMOR8: 14887 case X86::ATOMOR16: 14888 case X86::ATOMOR32: 14889 case X86::ATOMOR64: 14890 // Fall through 14891 case X86::ATOMXOR16: 14892 case X86::ATOMXOR8: 14893 case X86::ATOMXOR32: 14894 case X86::ATOMXOR64: 14895 // Fall through 14896 case X86::ATOMNAND8: 14897 case X86::ATOMNAND16: 14898 case X86::ATOMNAND32: 14899 case X86::ATOMNAND64: 14900 // Fall through 14901 case X86::ATOMMAX8: 14902 case X86::ATOMMAX16: 14903 case X86::ATOMMAX32: 14904 case X86::ATOMMAX64: 14905 // Fall through 14906 case X86::ATOMMIN8: 14907 case X86::ATOMMIN16: 14908 case X86::ATOMMIN32: 14909 case X86::ATOMMIN64: 14910 // Fall through 14911 case X86::ATOMUMAX8: 14912 case X86::ATOMUMAX16: 14913 case X86::ATOMUMAX32: 14914 case X86::ATOMUMAX64: 14915 // Fall through 14916 case X86::ATOMUMIN8: 14917 case X86::ATOMUMIN16: 14918 case X86::ATOMUMIN32: 14919 case X86::ATOMUMIN64: 14920 return EmitAtomicLoadArith(MI, BB); 14921 14922 // This group does 64-bit operations on a 32-bit host. 14923 case X86::ATOMAND6432: 14924 case X86::ATOMOR6432: 14925 case X86::ATOMXOR6432: 14926 case X86::ATOMNAND6432: 14927 case X86::ATOMADD6432: 14928 case X86::ATOMSUB6432: 14929 case X86::ATOMMAX6432: 14930 case X86::ATOMMIN6432: 14931 case X86::ATOMUMAX6432: 14932 case X86::ATOMUMIN6432: 14933 case X86::ATOMSWAP6432: 14934 return EmitAtomicLoadArith6432(MI, BB); 14935 14936 case X86::VASTART_SAVE_XMM_REGS: 14937 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 14938 14939 case X86::VAARG_64: 14940 return EmitVAARG64WithCustomInserter(MI, BB); 14941 14942 case X86::EH_SjLj_SetJmp32: 14943 case X86::EH_SjLj_SetJmp64: 14944 return emitEHSjLjSetJmp(MI, BB); 14945 14946 case X86::EH_SjLj_LongJmp32: 14947 case X86::EH_SjLj_LongJmp64: 14948 return emitEHSjLjLongJmp(MI, BB); 14949 } 14950 } 14951 14952 //===----------------------------------------------------------------------===// 14953 // X86 Optimization Hooks 14954 //===----------------------------------------------------------------------===// 14955 14956 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 14957 APInt &KnownZero, 14958 APInt &KnownOne, 14959 const SelectionDAG &DAG, 14960 unsigned Depth) const { 14961 unsigned BitWidth = KnownZero.getBitWidth(); 14962 unsigned Opc = Op.getOpcode(); 14963 assert((Opc >= ISD::BUILTIN_OP_END || 14964 Opc == ISD::INTRINSIC_WO_CHAIN || 14965 Opc == ISD::INTRINSIC_W_CHAIN || 14966 Opc == ISD::INTRINSIC_VOID) && 14967 "Should use MaskedValueIsZero if you don't know whether Op" 14968 " is a target node!"); 14969 14970 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 14971 switch (Opc) { 14972 default: break; 14973 case X86ISD::ADD: 14974 case X86ISD::SUB: 14975 case X86ISD::ADC: 14976 case X86ISD::SBB: 14977 case X86ISD::SMUL: 14978 case X86ISD::UMUL: 14979 case X86ISD::INC: 14980 case X86ISD::DEC: 14981 case X86ISD::OR: 14982 case X86ISD::XOR: 14983 case X86ISD::AND: 14984 // These nodes' second result is a boolean. 14985 if (Op.getResNo() == 0) 14986 break; 14987 // Fallthrough 14988 case X86ISD::SETCC: 14989 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14990 break; 14991 case ISD::INTRINSIC_WO_CHAIN: { 14992 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14993 unsigned NumLoBits = 0; 14994 switch (IntId) { 14995 default: break; 14996 case Intrinsic::x86_sse_movmsk_ps: 14997 case Intrinsic::x86_avx_movmsk_ps_256: 14998 case Intrinsic::x86_sse2_movmsk_pd: 14999 case Intrinsic::x86_avx_movmsk_pd_256: 15000 case Intrinsic::x86_mmx_pmovmskb: 15001 case Intrinsic::x86_sse2_pmovmskb_128: 15002 case Intrinsic::x86_avx2_pmovmskb: { 15003 // High bits of movmskp{s|d}, pmovmskb are known zero. 15004 switch (IntId) { 15005 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 15006 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 15007 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 15008 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 15009 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 15010 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 15011 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 15012 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break; 15013 } 15014 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits); 15015 break; 15016 } 15017 } 15018 break; 15019 } 15020 } 15021 } 15022 15023 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 15024 unsigned Depth) const { 15025 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 15026 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 15027 return Op.getValueType().getScalarType().getSizeInBits(); 15028 15029 // Fallback case. 15030 return 1; 15031 } 15032 15033 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 15034 /// node is a GlobalAddress + offset. 15035 bool X86TargetLowering::isGAPlusOffset(SDNode *N, 15036 const GlobalValue* &GA, 15037 int64_t &Offset) const { 15038 if (N->getOpcode() == X86ISD::Wrapper) { 15039 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 15040 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 15041 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 15042 return true; 15043 } 15044 } 15045 return TargetLowering::isGAPlusOffset(N, GA, Offset); 15046 } 15047 15048 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 15049 /// same as extracting the high 128-bit part of 256-bit vector and then 15050 /// inserting the result into the low part of a new 256-bit vector 15051 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 15052 EVT VT = SVOp->getValueType(0); 15053 unsigned NumElems = VT.getVectorNumElements(); 15054 15055 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 15056 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j) 15057 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 15058 SVOp->getMaskElt(j) >= 0) 15059 return false; 15060 15061 return true; 15062 } 15063 15064 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 15065 /// same as extracting the low 128-bit part of 256-bit vector and then 15066 /// inserting the result into the high part of a new 256-bit vector 15067 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 15068 EVT VT = SVOp->getValueType(0); 15069 unsigned NumElems = VT.getVectorNumElements(); 15070 15071 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 15072 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j) 15073 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 15074 SVOp->getMaskElt(j) >= 0) 15075 return false; 15076 15077 return true; 15078 } 15079 15080 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 15081 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 15082 TargetLowering::DAGCombinerInfo &DCI, 15083 const X86Subtarget* Subtarget) { 15084 SDLoc dl(N); 15085 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 15086 SDValue V1 = SVOp->getOperand(0); 15087 SDValue V2 = SVOp->getOperand(1); 15088 EVT VT = SVOp->getValueType(0); 15089 unsigned NumElems = VT.getVectorNumElements(); 15090 15091 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 15092 V2.getOpcode() == ISD::CONCAT_VECTORS) { 15093 // 15094 // 0,0,0,... 15095 // | 15096 // V UNDEF BUILD_VECTOR UNDEF 15097 // \ / \ / 15098 // CONCAT_VECTOR CONCAT_VECTOR 15099 // \ / 15100 // \ / 15101 // RESULT: V + zero extended 15102 // 15103 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 15104 V2.getOperand(1).getOpcode() != ISD::UNDEF || 15105 V1.getOperand(1).getOpcode() != ISD::UNDEF) 15106 return SDValue(); 15107 15108 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 15109 return SDValue(); 15110 15111 // To match the shuffle mask, the first half of the mask should 15112 // be exactly the first vector, and all the rest a splat with the 15113 // first element of the second one. 15114 for (unsigned i = 0; i != NumElems/2; ++i) 15115 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 15116 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 15117 return SDValue(); 15118 15119 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD. 15120 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) { 15121 if (Ld->hasNUsesOfValue(1, 0)) { 15122 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other); 15123 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() }; 15124 SDValue ResNode = 15125 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 15126 array_lengthof(Ops), 15127 Ld->getMemoryVT(), 15128 Ld->getPointerInfo(), 15129 Ld->getAlignment(), 15130 false/*isVolatile*/, true/*ReadMem*/, 15131 false/*WriteMem*/); 15132 15133 // Make sure the newly-created LOAD is in the same position as Ld in 15134 // terms of dependency. We create a TokenFactor for Ld and ResNode, 15135 // and update uses of Ld's output chain to use the TokenFactor. 15136 if (Ld->hasAnyUseOfValue(1)) { 15137 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15138 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1)); 15139 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain); 15140 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1), 15141 SDValue(ResNode.getNode(), 1)); 15142 } 15143 15144 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode); 15145 } 15146 } 15147 15148 // Emit a zeroed vector and insert the desired subvector on its 15149 // first half. 15150 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 15151 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl); 15152 return DCI.CombineTo(N, InsV); 15153 } 15154 15155 //===--------------------------------------------------------------------===// 15156 // Combine some shuffles into subvector extracts and inserts: 15157 // 15158 15159 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 15160 if (isShuffleHigh128VectorInsertLow(SVOp)) { 15161 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl); 15162 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl); 15163 return DCI.CombineTo(N, InsV); 15164 } 15165 15166 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 15167 if (isShuffleLow128VectorInsertHigh(SVOp)) { 15168 SDValue V = Extract128BitVector(V1, 0, DAG, dl); 15169 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl); 15170 return DCI.CombineTo(N, InsV); 15171 } 15172 15173 return SDValue(); 15174 } 15175 15176 /// PerformShuffleCombine - Performs several different shuffle combines. 15177 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 15178 TargetLowering::DAGCombinerInfo &DCI, 15179 const X86Subtarget *Subtarget) { 15180 SDLoc dl(N); 15181 EVT VT = N->getValueType(0); 15182 15183 // Don't create instructions with illegal types after legalize types has run. 15184 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15185 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 15186 return SDValue(); 15187 15188 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 15189 if (Subtarget->hasFp256() && VT.is256BitVector() && 15190 N->getOpcode() == ISD::VECTOR_SHUFFLE) 15191 return PerformShuffleCombine256(N, DAG, DCI, Subtarget); 15192 15193 // Only handle 128 wide vector from here on. 15194 if (!VT.is128BitVector()) 15195 return SDValue(); 15196 15197 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 15198 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 15199 // consecutive, non-overlapping, and in the right order. 15200 SmallVector<SDValue, 16> Elts; 15201 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 15202 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 15203 15204 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 15205 } 15206 15207 /// PerformTruncateCombine - Converts truncate operation to 15208 /// a sequence of vector shuffle operations. 15209 /// It is possible when we truncate 256-bit vector to 128-bit vector 15210 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 15211 TargetLowering::DAGCombinerInfo &DCI, 15212 const X86Subtarget *Subtarget) { 15213 return SDValue(); 15214 } 15215 15216 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target 15217 /// specific shuffle of a load can be folded into a single element load. 15218 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but 15219 /// shuffles have been customed lowered so we need to handle those here. 15220 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG, 15221 TargetLowering::DAGCombinerInfo &DCI) { 15222 if (DCI.isBeforeLegalizeOps()) 15223 return SDValue(); 15224 15225 SDValue InVec = N->getOperand(0); 15226 SDValue EltNo = N->getOperand(1); 15227 15228 if (!isa<ConstantSDNode>(EltNo)) 15229 return SDValue(); 15230 15231 EVT VT = InVec.getValueType(); 15232 15233 bool HasShuffleIntoBitcast = false; 15234 if (InVec.getOpcode() == ISD::BITCAST) { 15235 // Don't duplicate a load with other uses. 15236 if (!InVec.hasOneUse()) 15237 return SDValue(); 15238 EVT BCVT = InVec.getOperand(0).getValueType(); 15239 if (BCVT.getVectorNumElements() != VT.getVectorNumElements()) 15240 return SDValue(); 15241 InVec = InVec.getOperand(0); 15242 HasShuffleIntoBitcast = true; 15243 } 15244 15245 if (!isTargetShuffle(InVec.getOpcode())) 15246 return SDValue(); 15247 15248 // Don't duplicate a load with other uses. 15249 if (!InVec.hasOneUse()) 15250 return SDValue(); 15251 15252 SmallVector<int, 16> ShuffleMask; 15253 bool UnaryShuffle; 15254 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask, 15255 UnaryShuffle)) 15256 return SDValue(); 15257 15258 // Select the input vector, guarding against out of range extract vector. 15259 unsigned NumElems = VT.getVectorNumElements(); 15260 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 15261 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt]; 15262 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0) 15263 : InVec.getOperand(1); 15264 15265 // If inputs to shuffle are the same for both ops, then allow 2 uses 15266 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1; 15267 15268 if (LdNode.getOpcode() == ISD::BITCAST) { 15269 // Don't duplicate a load with other uses. 15270 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0)) 15271 return SDValue(); 15272 15273 AllowedUses = 1; // only allow 1 load use if we have a bitcast 15274 LdNode = LdNode.getOperand(0); 15275 } 15276 15277 if (!ISD::isNormalLoad(LdNode.getNode())) 15278 return SDValue(); 15279 15280 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode); 15281 15282 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile()) 15283 return SDValue(); 15284 15285 if (HasShuffleIntoBitcast) { 15286 // If there's a bitcast before the shuffle, check if the load type and 15287 // alignment is valid. 15288 unsigned Align = LN0->getAlignment(); 15289 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15290 unsigned NewAlign = TLI.getDataLayout()-> 15291 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 15292 15293 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 15294 return SDValue(); 15295 } 15296 15297 // All checks match so transform back to vector_shuffle so that DAG combiner 15298 // can finish the job 15299 SDLoc dl(N); 15300 15301 // Create shuffle node taking into account the case that its a unary shuffle 15302 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1); 15303 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl, 15304 InVec.getOperand(0), Shuffle, 15305 &ShuffleMask[0]); 15306 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 15307 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle, 15308 EltNo); 15309 } 15310 15311 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 15312 /// generation and convert it from being a bunch of shuffles and extracts 15313 /// to a simple store and scalar loads to extract the elements. 15314 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 15315 TargetLowering::DAGCombinerInfo &DCI) { 15316 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI); 15317 if (NewOp.getNode()) 15318 return NewOp; 15319 15320 SDValue InputVector = N->getOperand(0); 15321 // Detect whether we are trying to convert from mmx to i32 and the bitcast 15322 // from mmx to v2i32 has a single usage. 15323 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST && 15324 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx && 15325 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32) 15326 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector), 15327 N->getValueType(0), 15328 InputVector.getNode()->getOperand(0)); 15329 15330 // Only operate on vectors of 4 elements, where the alternative shuffling 15331 // gets to be more expensive. 15332 if (InputVector.getValueType() != MVT::v4i32) 15333 return SDValue(); 15334 15335 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 15336 // single use which is a sign-extend or zero-extend, and all elements are 15337 // used. 15338 SmallVector<SDNode *, 4> Uses; 15339 unsigned ExtractedElements = 0; 15340 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 15341 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 15342 if (UI.getUse().getResNo() != InputVector.getResNo()) 15343 return SDValue(); 15344 15345 SDNode *Extract = *UI; 15346 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 15347 return SDValue(); 15348 15349 if (Extract->getValueType(0) != MVT::i32) 15350 return SDValue(); 15351 if (!Extract->hasOneUse()) 15352 return SDValue(); 15353 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 15354 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 15355 return SDValue(); 15356 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 15357 return SDValue(); 15358 15359 // Record which element was extracted. 15360 ExtractedElements |= 15361 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 15362 15363 Uses.push_back(Extract); 15364 } 15365 15366 // If not all the elements were used, this may not be worthwhile. 15367 if (ExtractedElements != 15) 15368 return SDValue(); 15369 15370 // Ok, we've now decided to do the transformation. 15371 SDLoc dl(InputVector); 15372 15373 // Store the value to a temporary stack slot. 15374 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 15375 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 15376 MachinePointerInfo(), false, false, 0); 15377 15378 // Replace each use (extract) with a load of the appropriate element. 15379 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 15380 UE = Uses.end(); UI != UE; ++UI) { 15381 SDNode *Extract = *UI; 15382 15383 // cOMpute the element's address. 15384 SDValue Idx = Extract->getOperand(1); 15385 unsigned EltSize = 15386 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 15387 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 15388 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15389 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 15390 15391 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 15392 StackPtr, OffsetVal); 15393 15394 // Load the scalar. 15395 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 15396 ScalarAddr, MachinePointerInfo(), 15397 false, false, false, 0); 15398 15399 // Replace the exact with the load. 15400 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 15401 } 15402 15403 // The replacement was made in place; don't return anything. 15404 return SDValue(); 15405 } 15406 15407 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match. 15408 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, 15409 SDValue RHS, SelectionDAG &DAG, 15410 const X86Subtarget *Subtarget) { 15411 if (!VT.isVector()) 15412 return 0; 15413 15414 switch (VT.getSimpleVT().SimpleTy) { 15415 default: return 0; 15416 case MVT::v32i8: 15417 case MVT::v16i16: 15418 case MVT::v8i32: 15419 if (!Subtarget->hasAVX2()) 15420 return 0; 15421 case MVT::v16i8: 15422 case MVT::v8i16: 15423 case MVT::v4i32: 15424 if (!Subtarget->hasSSE2()) 15425 return 0; 15426 } 15427 15428 // SSE2 has only a small subset of the operations. 15429 bool hasUnsigned = Subtarget->hasSSE41() || 15430 (Subtarget->hasSSE2() && VT == MVT::v16i8); 15431 bool hasSigned = Subtarget->hasSSE41() || 15432 (Subtarget->hasSSE2() && VT == MVT::v8i16); 15433 15434 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15435 15436 // Check for x CC y ? x : y. 15437 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15438 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15439 switch (CC) { 15440 default: break; 15441 case ISD::SETULT: 15442 case ISD::SETULE: 15443 return hasUnsigned ? X86ISD::UMIN : 0; 15444 case ISD::SETUGT: 15445 case ISD::SETUGE: 15446 return hasUnsigned ? X86ISD::UMAX : 0; 15447 case ISD::SETLT: 15448 case ISD::SETLE: 15449 return hasSigned ? X86ISD::SMIN : 0; 15450 case ISD::SETGT: 15451 case ISD::SETGE: 15452 return hasSigned ? X86ISD::SMAX : 0; 15453 } 15454 // Check for x CC y ? y : x -- a min/max with reversed arms. 15455 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 15456 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 15457 switch (CC) { 15458 default: break; 15459 case ISD::SETULT: 15460 case ISD::SETULE: 15461 return hasUnsigned ? X86ISD::UMAX : 0; 15462 case ISD::SETUGT: 15463 case ISD::SETUGE: 15464 return hasUnsigned ? X86ISD::UMIN : 0; 15465 case ISD::SETLT: 15466 case ISD::SETLE: 15467 return hasSigned ? X86ISD::SMAX : 0; 15468 case ISD::SETGT: 15469 case ISD::SETGE: 15470 return hasSigned ? X86ISD::SMIN : 0; 15471 } 15472 } 15473 15474 return 0; 15475 } 15476 15477 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 15478 /// nodes. 15479 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 15480 TargetLowering::DAGCombinerInfo &DCI, 15481 const X86Subtarget *Subtarget) { 15482 SDLoc DL(N); 15483 SDValue Cond = N->getOperand(0); 15484 // Get the LHS/RHS of the select. 15485 SDValue LHS = N->getOperand(1); 15486 SDValue RHS = N->getOperand(2); 15487 EVT VT = LHS.getValueType(); 15488 15489 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 15490 // instructions match the semantics of the common C idiom x<y?x:y but not 15491 // x<=y?x:y, because of how they handle negative zero (which can be 15492 // ignored in unsafe-math mode). 15493 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 15494 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 15495 (Subtarget->hasSSE2() || 15496 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 15497 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15498 15499 unsigned Opcode = 0; 15500 // Check for x CC y ? x : y. 15501 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15502 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15503 switch (CC) { 15504 default: break; 15505 case ISD::SETULT: 15506 // Converting this to a min would handle NaNs incorrectly, and swapping 15507 // the operands would cause it to handle comparisons between positive 15508 // and negative zero incorrectly. 15509 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15510 if (!DAG.getTarget().Options.UnsafeFPMath && 15511 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15512 break; 15513 std::swap(LHS, RHS); 15514 } 15515 Opcode = X86ISD::FMIN; 15516 break; 15517 case ISD::SETOLE: 15518 // Converting this to a min would handle comparisons between positive 15519 // and negative zero incorrectly. 15520 if (!DAG.getTarget().Options.UnsafeFPMath && 15521 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15522 break; 15523 Opcode = X86ISD::FMIN; 15524 break; 15525 case ISD::SETULE: 15526 // Converting this to a min would handle both negative zeros and NaNs 15527 // incorrectly, but we can swap the operands to fix both. 15528 std::swap(LHS, RHS); 15529 case ISD::SETOLT: 15530 case ISD::SETLT: 15531 case ISD::SETLE: 15532 Opcode = X86ISD::FMIN; 15533 break; 15534 15535 case ISD::SETOGE: 15536 // Converting this to a max would handle comparisons between positive 15537 // and negative zero incorrectly. 15538 if (!DAG.getTarget().Options.UnsafeFPMath && 15539 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15540 break; 15541 Opcode = X86ISD::FMAX; 15542 break; 15543 case ISD::SETUGT: 15544 // Converting this to a max would handle NaNs incorrectly, and swapping 15545 // the operands would cause it to handle comparisons between positive 15546 // and negative zero incorrectly. 15547 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15548 if (!DAG.getTarget().Options.UnsafeFPMath && 15549 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15550 break; 15551 std::swap(LHS, RHS); 15552 } 15553 Opcode = X86ISD::FMAX; 15554 break; 15555 case ISD::SETUGE: 15556 // Converting this to a max would handle both negative zeros and NaNs 15557 // incorrectly, but we can swap the operands to fix both. 15558 std::swap(LHS, RHS); 15559 case ISD::SETOGT: 15560 case ISD::SETGT: 15561 case ISD::SETGE: 15562 Opcode = X86ISD::FMAX; 15563 break; 15564 } 15565 // Check for x CC y ? y : x -- a min/max with reversed arms. 15566 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 15567 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 15568 switch (CC) { 15569 default: break; 15570 case ISD::SETOGE: 15571 // Converting this to a min would handle comparisons between positive 15572 // and negative zero incorrectly, and swapping the operands would 15573 // cause it to handle NaNs incorrectly. 15574 if (!DAG.getTarget().Options.UnsafeFPMath && 15575 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 15576 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15577 break; 15578 std::swap(LHS, RHS); 15579 } 15580 Opcode = X86ISD::FMIN; 15581 break; 15582 case ISD::SETUGT: 15583 // Converting this to a min would handle NaNs incorrectly. 15584 if (!DAG.getTarget().Options.UnsafeFPMath && 15585 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 15586 break; 15587 Opcode = X86ISD::FMIN; 15588 break; 15589 case ISD::SETUGE: 15590 // Converting this to a min would handle both negative zeros and NaNs 15591 // incorrectly, but we can swap the operands to fix both. 15592 std::swap(LHS, RHS); 15593 case ISD::SETOGT: 15594 case ISD::SETGT: 15595 case ISD::SETGE: 15596 Opcode = X86ISD::FMIN; 15597 break; 15598 15599 case ISD::SETULT: 15600 // Converting this to a max would handle NaNs incorrectly. 15601 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15602 break; 15603 Opcode = X86ISD::FMAX; 15604 break; 15605 case ISD::SETOLE: 15606 // Converting this to a max would handle comparisons between positive 15607 // and negative zero incorrectly, and swapping the operands would 15608 // cause it to handle NaNs incorrectly. 15609 if (!DAG.getTarget().Options.UnsafeFPMath && 15610 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 15611 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15612 break; 15613 std::swap(LHS, RHS); 15614 } 15615 Opcode = X86ISD::FMAX; 15616 break; 15617 case ISD::SETULE: 15618 // Converting this to a max would handle both negative zeros and NaNs 15619 // incorrectly, but we can swap the operands to fix both. 15620 std::swap(LHS, RHS); 15621 case ISD::SETOLT: 15622 case ISD::SETLT: 15623 case ISD::SETLE: 15624 Opcode = X86ISD::FMAX; 15625 break; 15626 } 15627 } 15628 15629 if (Opcode) 15630 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 15631 } 15632 15633 // If this is a select between two integer constants, try to do some 15634 // optimizations. 15635 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 15636 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 15637 // Don't do this for crazy integer types. 15638 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 15639 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 15640 // so that TrueC (the true value) is larger than FalseC. 15641 bool NeedsCondInvert = false; 15642 15643 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 15644 // Efficiently invertible. 15645 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 15646 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 15647 isa<ConstantSDNode>(Cond.getOperand(1))))) { 15648 NeedsCondInvert = true; 15649 std::swap(TrueC, FalseC); 15650 } 15651 15652 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 15653 if (FalseC->getAPIntValue() == 0 && 15654 TrueC->getAPIntValue().isPowerOf2()) { 15655 if (NeedsCondInvert) // Invert the condition if needed. 15656 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15657 DAG.getConstant(1, Cond.getValueType())); 15658 15659 // Zero extend the condition if needed. 15660 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 15661 15662 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 15663 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 15664 DAG.getConstant(ShAmt, MVT::i8)); 15665 } 15666 15667 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 15668 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 15669 if (NeedsCondInvert) // Invert the condition if needed. 15670 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15671 DAG.getConstant(1, Cond.getValueType())); 15672 15673 // Zero extend the condition if needed. 15674 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 15675 FalseC->getValueType(0), Cond); 15676 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15677 SDValue(FalseC, 0)); 15678 } 15679 15680 // Optimize cases that will turn into an LEA instruction. This requires 15681 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 15682 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 15683 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 15684 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 15685 15686 bool isFastMultiplier = false; 15687 if (Diff < 10) { 15688 switch ((unsigned char)Diff) { 15689 default: break; 15690 case 1: // result = add base, cond 15691 case 2: // result = lea base( , cond*2) 15692 case 3: // result = lea base(cond, cond*2) 15693 case 4: // result = lea base( , cond*4) 15694 case 5: // result = lea base(cond, cond*4) 15695 case 8: // result = lea base( , cond*8) 15696 case 9: // result = lea base(cond, cond*8) 15697 isFastMultiplier = true; 15698 break; 15699 } 15700 } 15701 15702 if (isFastMultiplier) { 15703 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 15704 if (NeedsCondInvert) // Invert the condition if needed. 15705 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15706 DAG.getConstant(1, Cond.getValueType())); 15707 15708 // Zero extend the condition if needed. 15709 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 15710 Cond); 15711 // Scale the condition by the difference. 15712 if (Diff != 1) 15713 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 15714 DAG.getConstant(Diff, Cond.getValueType())); 15715 15716 // Add the base if non-zero. 15717 if (FalseC->getAPIntValue() != 0) 15718 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15719 SDValue(FalseC, 0)); 15720 return Cond; 15721 } 15722 } 15723 } 15724 } 15725 15726 // Canonicalize max and min: 15727 // (x > y) ? x : y -> (x >= y) ? x : y 15728 // (x < y) ? x : y -> (x <= y) ? x : y 15729 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates 15730 // the need for an extra compare 15731 // against zero. e.g. 15732 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0 15733 // subl %esi, %edi 15734 // testl %edi, %edi 15735 // movl $0, %eax 15736 // cmovgl %edi, %eax 15737 // => 15738 // xorl %eax, %eax 15739 // subl %esi, $edi 15740 // cmovsl %eax, %edi 15741 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC && 15742 DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15743 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15744 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15745 switch (CC) { 15746 default: break; 15747 case ISD::SETLT: 15748 case ISD::SETGT: { 15749 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE; 15750 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), 15751 Cond.getOperand(0), Cond.getOperand(1), NewCC); 15752 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS); 15753 } 15754 } 15755 } 15756 15757 // Match VSELECTs into subs with unsigned saturation. 15758 if (!DCI.isBeforeLegalize() && 15759 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC && 15760 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors. 15761 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) || 15762 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) { 15763 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15764 15765 // Check if one of the arms of the VSELECT is a zero vector. If it's on the 15766 // left side invert the predicate to simplify logic below. 15767 SDValue Other; 15768 if (ISD::isBuildVectorAllZeros(LHS.getNode())) { 15769 Other = RHS; 15770 CC = ISD::getSetCCInverse(CC, true); 15771 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) { 15772 Other = LHS; 15773 } 15774 15775 if (Other.getNode() && Other->getNumOperands() == 2 && 15776 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) { 15777 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1); 15778 SDValue CondRHS = Cond->getOperand(1); 15779 15780 // Look for a general sub with unsigned saturation first. 15781 // x >= y ? x-y : 0 --> subus x, y 15782 // x > y ? x-y : 0 --> subus x, y 15783 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) && 15784 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS)) 15785 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 15786 15787 // If the RHS is a constant we have to reverse the const canonicalization. 15788 // x > C-1 ? x+-C : 0 --> subus x, C 15789 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD && 15790 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) { 15791 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 15792 if (CondRHS.getConstantOperandVal(0) == -A-1) 15793 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, 15794 DAG.getConstant(-A, VT)); 15795 } 15796 15797 // Another special case: If C was a sign bit, the sub has been 15798 // canonicalized into a xor. 15799 // FIXME: Would it be better to use ComputeMaskedBits to determine whether 15800 // it's safe to decanonicalize the xor? 15801 // x s< 0 ? x^C : 0 --> subus x, C 15802 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR && 15803 ISD::isBuildVectorAllZeros(CondRHS.getNode()) && 15804 isSplatVector(OpRHS.getNode())) { 15805 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 15806 if (A.isSignBit()) 15807 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 15808 } 15809 } 15810 } 15811 15812 // Try to match a min/max vector operation. 15813 if (!DCI.isBeforeLegalize() && 15814 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) 15815 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget)) 15816 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS); 15817 15818 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*. 15819 if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT && 15820 Cond.getOpcode() == ISD::SETCC) { 15821 15822 assert(Cond.getValueType().isVector() && 15823 "vector select expects a vector selector!"); 15824 15825 EVT IntVT = Cond.getValueType(); 15826 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode()); 15827 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 15828 15829 if (!TValIsAllOnes && !FValIsAllZeros) { 15830 // Try invert the condition if true value is not all 1s and false value 15831 // is not all 0s. 15832 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode()); 15833 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode()); 15834 15835 if (TValIsAllZeros || FValIsAllOnes) { 15836 SDValue CC = Cond.getOperand(2); 15837 ISD::CondCode NewCC = 15838 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 15839 Cond.getOperand(0).getValueType().isInteger()); 15840 Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC); 15841 std::swap(LHS, RHS); 15842 TValIsAllOnes = FValIsAllOnes; 15843 FValIsAllZeros = TValIsAllZeros; 15844 } 15845 } 15846 15847 if (TValIsAllOnes || FValIsAllZeros) { 15848 SDValue Ret; 15849 15850 if (TValIsAllOnes && FValIsAllZeros) 15851 Ret = Cond; 15852 else if (TValIsAllOnes) 15853 Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond, 15854 DAG.getNode(ISD::BITCAST, DL, IntVT, RHS)); 15855 else if (FValIsAllZeros) 15856 Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond, 15857 DAG.getNode(ISD::BITCAST, DL, IntVT, LHS)); 15858 15859 return DAG.getNode(ISD::BITCAST, DL, VT, Ret); 15860 } 15861 } 15862 15863 // If we know that this node is legal then we know that it is going to be 15864 // matched by one of the SSE/AVX BLEND instructions. These instructions only 15865 // depend on the highest bit in each word. Try to use SimplifyDemandedBits 15866 // to simplify previous instructions. 15867 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15868 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() && 15869 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) { 15870 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits(); 15871 15872 // Don't optimize vector selects that map to mask-registers. 15873 if (BitWidth == 1) 15874 return SDValue(); 15875 15876 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size"); 15877 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1); 15878 15879 APInt KnownZero, KnownOne; 15880 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 15881 DCI.isBeforeLegalizeOps()); 15882 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) || 15883 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO)) 15884 DCI.CommitTargetLoweringOpt(TLO); 15885 } 15886 15887 return SDValue(); 15888 } 15889 15890 // Check whether a boolean test is testing a boolean value generated by 15891 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition 15892 // code. 15893 // 15894 // Simplify the following patterns: 15895 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or 15896 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ) 15897 // to (Op EFLAGS Cond) 15898 // 15899 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or 15900 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ) 15901 // to (Op EFLAGS !Cond) 15902 // 15903 // where Op could be BRCOND or CMOV. 15904 // 15905 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) { 15906 // Quit if not CMP and SUB with its value result used. 15907 if (Cmp.getOpcode() != X86ISD::CMP && 15908 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0))) 15909 return SDValue(); 15910 15911 // Quit if not used as a boolean value. 15912 if (CC != X86::COND_E && CC != X86::COND_NE) 15913 return SDValue(); 15914 15915 // Check CMP operands. One of them should be 0 or 1 and the other should be 15916 // an SetCC or extended from it. 15917 SDValue Op1 = Cmp.getOperand(0); 15918 SDValue Op2 = Cmp.getOperand(1); 15919 15920 SDValue SetCC; 15921 const ConstantSDNode* C = 0; 15922 bool needOppositeCond = (CC == X86::COND_E); 15923 bool checkAgainstTrue = false; // Is it a comparison against 1? 15924 15925 if ((C = dyn_cast<ConstantSDNode>(Op1))) 15926 SetCC = Op2; 15927 else if ((C = dyn_cast<ConstantSDNode>(Op2))) 15928 SetCC = Op1; 15929 else // Quit if all operands are not constants. 15930 return SDValue(); 15931 15932 if (C->getZExtValue() == 1) { 15933 needOppositeCond = !needOppositeCond; 15934 checkAgainstTrue = true; 15935 } else if (C->getZExtValue() != 0) 15936 // Quit if the constant is neither 0 or 1. 15937 return SDValue(); 15938 15939 bool truncatedToBoolWithAnd = false; 15940 // Skip (zext $x), (trunc $x), or (and $x, 1) node. 15941 while (SetCC.getOpcode() == ISD::ZERO_EXTEND || 15942 SetCC.getOpcode() == ISD::TRUNCATE || 15943 SetCC.getOpcode() == ISD::AND) { 15944 if (SetCC.getOpcode() == ISD::AND) { 15945 int OpIdx = -1; 15946 ConstantSDNode *CS; 15947 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) && 15948 CS->getZExtValue() == 1) 15949 OpIdx = 1; 15950 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) && 15951 CS->getZExtValue() == 1) 15952 OpIdx = 0; 15953 if (OpIdx == -1) 15954 break; 15955 SetCC = SetCC.getOperand(OpIdx); 15956 truncatedToBoolWithAnd = true; 15957 } else 15958 SetCC = SetCC.getOperand(0); 15959 } 15960 15961 switch (SetCC.getOpcode()) { 15962 case X86ISD::SETCC_CARRY: 15963 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to 15964 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1, 15965 // i.e. it's a comparison against true but the result of SETCC_CARRY is not 15966 // truncated to i1 using 'and'. 15967 if (checkAgainstTrue && !truncatedToBoolWithAnd) 15968 break; 15969 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && 15970 "Invalid use of SETCC_CARRY!"); 15971 // FALL THROUGH 15972 case X86ISD::SETCC: 15973 // Set the condition code or opposite one if necessary. 15974 CC = X86::CondCode(SetCC.getConstantOperandVal(0)); 15975 if (needOppositeCond) 15976 CC = X86::GetOppositeBranchCondition(CC); 15977 return SetCC.getOperand(1); 15978 case X86ISD::CMOV: { 15979 // Check whether false/true value has canonical one, i.e. 0 or 1. 15980 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0)); 15981 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1)); 15982 // Quit if true value is not a constant. 15983 if (!TVal) 15984 return SDValue(); 15985 // Quit if false value is not a constant. 15986 if (!FVal) { 15987 SDValue Op = SetCC.getOperand(0); 15988 // Skip 'zext' or 'trunc' node. 15989 if (Op.getOpcode() == ISD::ZERO_EXTEND || 15990 Op.getOpcode() == ISD::TRUNCATE) 15991 Op = Op.getOperand(0); 15992 // A special case for rdrand/rdseed, where 0 is set if false cond is 15993 // found. 15994 if ((Op.getOpcode() != X86ISD::RDRAND && 15995 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0) 15996 return SDValue(); 15997 } 15998 // Quit if false value is not the constant 0 or 1. 15999 bool FValIsFalse = true; 16000 if (FVal && FVal->getZExtValue() != 0) { 16001 if (FVal->getZExtValue() != 1) 16002 return SDValue(); 16003 // If FVal is 1, opposite cond is needed. 16004 needOppositeCond = !needOppositeCond; 16005 FValIsFalse = false; 16006 } 16007 // Quit if TVal is not the constant opposite of FVal. 16008 if (FValIsFalse && TVal->getZExtValue() != 1) 16009 return SDValue(); 16010 if (!FValIsFalse && TVal->getZExtValue() != 0) 16011 return SDValue(); 16012 CC = X86::CondCode(SetCC.getConstantOperandVal(2)); 16013 if (needOppositeCond) 16014 CC = X86::GetOppositeBranchCondition(CC); 16015 return SetCC.getOperand(3); 16016 } 16017 } 16018 16019 return SDValue(); 16020 } 16021 16022 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 16023 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 16024 TargetLowering::DAGCombinerInfo &DCI, 16025 const X86Subtarget *Subtarget) { 16026 SDLoc DL(N); 16027 16028 // If the flag operand isn't dead, don't touch this CMOV. 16029 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 16030 return SDValue(); 16031 16032 SDValue FalseOp = N->getOperand(0); 16033 SDValue TrueOp = N->getOperand(1); 16034 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 16035 SDValue Cond = N->getOperand(3); 16036 16037 if (CC == X86::COND_E || CC == X86::COND_NE) { 16038 switch (Cond.getOpcode()) { 16039 default: break; 16040 case X86ISD::BSR: 16041 case X86ISD::BSF: 16042 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 16043 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 16044 return (CC == X86::COND_E) ? FalseOp : TrueOp; 16045 } 16046 } 16047 16048 SDValue Flags; 16049 16050 Flags = checkBoolTestSetCCCombine(Cond, CC); 16051 if (Flags.getNode() && 16052 // Extra check as FCMOV only supports a subset of X86 cond. 16053 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) { 16054 SDValue Ops[] = { FalseOp, TrueOp, 16055 DAG.getConstant(CC, MVT::i8), Flags }; 16056 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), 16057 Ops, array_lengthof(Ops)); 16058 } 16059 16060 // If this is a select between two integer constants, try to do some 16061 // optimizations. Note that the operands are ordered the opposite of SELECT 16062 // operands. 16063 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 16064 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 16065 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 16066 // larger than FalseC (the false value). 16067 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 16068 CC = X86::GetOppositeBranchCondition(CC); 16069 std::swap(TrueC, FalseC); 16070 std::swap(TrueOp, FalseOp); 16071 } 16072 16073 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 16074 // This is efficient for any integer data type (including i8/i16) and 16075 // shift amount. 16076 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 16077 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16078 DAG.getConstant(CC, MVT::i8), Cond); 16079 16080 // Zero extend the condition if needed. 16081 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 16082 16083 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 16084 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 16085 DAG.getConstant(ShAmt, MVT::i8)); 16086 if (N->getNumValues() == 2) // Dead flag value? 16087 return DCI.CombineTo(N, Cond, SDValue()); 16088 return Cond; 16089 } 16090 16091 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 16092 // for any integer data type, including i8/i16. 16093 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 16094 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16095 DAG.getConstant(CC, MVT::i8), Cond); 16096 16097 // Zero extend the condition if needed. 16098 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 16099 FalseC->getValueType(0), Cond); 16100 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16101 SDValue(FalseC, 0)); 16102 16103 if (N->getNumValues() == 2) // Dead flag value? 16104 return DCI.CombineTo(N, Cond, SDValue()); 16105 return Cond; 16106 } 16107 16108 // Optimize cases that will turn into an LEA instruction. This requires 16109 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 16110 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 16111 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 16112 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 16113 16114 bool isFastMultiplier = false; 16115 if (Diff < 10) { 16116 switch ((unsigned char)Diff) { 16117 default: break; 16118 case 1: // result = add base, cond 16119 case 2: // result = lea base( , cond*2) 16120 case 3: // result = lea base(cond, cond*2) 16121 case 4: // result = lea base( , cond*4) 16122 case 5: // result = lea base(cond, cond*4) 16123 case 8: // result = lea base( , cond*8) 16124 case 9: // result = lea base(cond, cond*8) 16125 isFastMultiplier = true; 16126 break; 16127 } 16128 } 16129 16130 if (isFastMultiplier) { 16131 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 16132 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 16133 DAG.getConstant(CC, MVT::i8), Cond); 16134 // Zero extend the condition if needed. 16135 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 16136 Cond); 16137 // Scale the condition by the difference. 16138 if (Diff != 1) 16139 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 16140 DAG.getConstant(Diff, Cond.getValueType())); 16141 16142 // Add the base if non-zero. 16143 if (FalseC->getAPIntValue() != 0) 16144 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 16145 SDValue(FalseC, 0)); 16146 if (N->getNumValues() == 2) // Dead flag value? 16147 return DCI.CombineTo(N, Cond, SDValue()); 16148 return Cond; 16149 } 16150 } 16151 } 16152 } 16153 16154 // Handle these cases: 16155 // (select (x != c), e, c) -> select (x != c), e, x), 16156 // (select (x == c), c, e) -> select (x == c), x, e) 16157 // where the c is an integer constant, and the "select" is the combination 16158 // of CMOV and CMP. 16159 // 16160 // The rationale for this change is that the conditional-move from a constant 16161 // needs two instructions, however, conditional-move from a register needs 16162 // only one instruction. 16163 // 16164 // CAVEAT: By replacing a constant with a symbolic value, it may obscure 16165 // some instruction-combining opportunities. This opt needs to be 16166 // postponed as late as possible. 16167 // 16168 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) { 16169 // the DCI.xxxx conditions are provided to postpone the optimization as 16170 // late as possible. 16171 16172 ConstantSDNode *CmpAgainst = 0; 16173 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) && 16174 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) && 16175 !isa<ConstantSDNode>(Cond.getOperand(0))) { 16176 16177 if (CC == X86::COND_NE && 16178 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) { 16179 CC = X86::GetOppositeBranchCondition(CC); 16180 std::swap(TrueOp, FalseOp); 16181 } 16182 16183 if (CC == X86::COND_E && 16184 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) { 16185 SDValue Ops[] = { FalseOp, Cond.getOperand(0), 16186 DAG.getConstant(CC, MVT::i8), Cond }; 16187 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops, 16188 array_lengthof(Ops)); 16189 } 16190 } 16191 } 16192 16193 return SDValue(); 16194 } 16195 16196 /// PerformMulCombine - Optimize a single multiply with constant into two 16197 /// in order to implement it with two cheaper instructions, e.g. 16198 /// LEA + SHL, LEA + LEA. 16199 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 16200 TargetLowering::DAGCombinerInfo &DCI) { 16201 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 16202 return SDValue(); 16203 16204 EVT VT = N->getValueType(0); 16205 if (VT != MVT::i64) 16206 return SDValue(); 16207 16208 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 16209 if (!C) 16210 return SDValue(); 16211 uint64_t MulAmt = C->getZExtValue(); 16212 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 16213 return SDValue(); 16214 16215 uint64_t MulAmt1 = 0; 16216 uint64_t MulAmt2 = 0; 16217 if ((MulAmt % 9) == 0) { 16218 MulAmt1 = 9; 16219 MulAmt2 = MulAmt / 9; 16220 } else if ((MulAmt % 5) == 0) { 16221 MulAmt1 = 5; 16222 MulAmt2 = MulAmt / 5; 16223 } else if ((MulAmt % 3) == 0) { 16224 MulAmt1 = 3; 16225 MulAmt2 = MulAmt / 3; 16226 } 16227 if (MulAmt2 && 16228 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 16229 SDLoc DL(N); 16230 16231 if (isPowerOf2_64(MulAmt2) && 16232 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 16233 // If second multiplifer is pow2, issue it first. We want the multiply by 16234 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 16235 // is an add. 16236 std::swap(MulAmt1, MulAmt2); 16237 16238 SDValue NewMul; 16239 if (isPowerOf2_64(MulAmt1)) 16240 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 16241 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 16242 else 16243 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 16244 DAG.getConstant(MulAmt1, VT)); 16245 16246 if (isPowerOf2_64(MulAmt2)) 16247 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 16248 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 16249 else 16250 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 16251 DAG.getConstant(MulAmt2, VT)); 16252 16253 // Do not add new nodes to DAG combiner worklist. 16254 DCI.CombineTo(N, NewMul, false); 16255 } 16256 return SDValue(); 16257 } 16258 16259 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 16260 SDValue N0 = N->getOperand(0); 16261 SDValue N1 = N->getOperand(1); 16262 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 16263 EVT VT = N0.getValueType(); 16264 16265 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 16266 // since the result of setcc_c is all zero's or all ones. 16267 if (VT.isInteger() && !VT.isVector() && 16268 N1C && N0.getOpcode() == ISD::AND && 16269 N0.getOperand(1).getOpcode() == ISD::Constant) { 16270 SDValue N00 = N0.getOperand(0); 16271 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 16272 ((N00.getOpcode() == ISD::ANY_EXTEND || 16273 N00.getOpcode() == ISD::ZERO_EXTEND) && 16274 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 16275 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 16276 APInt ShAmt = N1C->getAPIntValue(); 16277 Mask = Mask.shl(ShAmt); 16278 if (Mask != 0) 16279 return DAG.getNode(ISD::AND, SDLoc(N), VT, 16280 N00, DAG.getConstant(Mask, VT)); 16281 } 16282 } 16283 16284 // Hardware support for vector shifts is sparse which makes us scalarize the 16285 // vector operations in many cases. Also, on sandybridge ADD is faster than 16286 // shl. 16287 // (shl V, 1) -> add V,V 16288 if (isSplatVector(N1.getNode())) { 16289 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 16290 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 16291 // We shift all of the values by one. In many cases we do not have 16292 // hardware support for this operation. This is better expressed as an ADD 16293 // of two values. 16294 if (N1C && (1 == N1C->getZExtValue())) { 16295 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0); 16296 } 16297 } 16298 16299 return SDValue(); 16300 } 16301 16302 /// PerformShiftCombine - Combine shifts. 16303 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 16304 TargetLowering::DAGCombinerInfo &DCI, 16305 const X86Subtarget *Subtarget) { 16306 if (N->getOpcode() == ISD::SHL) { 16307 SDValue V = PerformSHLCombine(N, DAG); 16308 if (V.getNode()) return V; 16309 } 16310 16311 return SDValue(); 16312 } 16313 16314 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 16315 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS 16316 // and friends. Likewise for OR -> CMPNEQSS. 16317 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 16318 TargetLowering::DAGCombinerInfo &DCI, 16319 const X86Subtarget *Subtarget) { 16320 unsigned opcode; 16321 16322 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 16323 // we're requiring SSE2 for both. 16324 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 16325 SDValue N0 = N->getOperand(0); 16326 SDValue N1 = N->getOperand(1); 16327 SDValue CMP0 = N0->getOperand(1); 16328 SDValue CMP1 = N1->getOperand(1); 16329 SDLoc DL(N); 16330 16331 // The SETCCs should both refer to the same CMP. 16332 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 16333 return SDValue(); 16334 16335 SDValue CMP00 = CMP0->getOperand(0); 16336 SDValue CMP01 = CMP0->getOperand(1); 16337 EVT VT = CMP00.getValueType(); 16338 16339 if (VT == MVT::f32 || VT == MVT::f64) { 16340 bool ExpectingFlags = false; 16341 // Check for any users that want flags: 16342 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 16343 !ExpectingFlags && UI != UE; ++UI) 16344 switch (UI->getOpcode()) { 16345 default: 16346 case ISD::BR_CC: 16347 case ISD::BRCOND: 16348 case ISD::SELECT: 16349 ExpectingFlags = true; 16350 break; 16351 case ISD::CopyToReg: 16352 case ISD::SIGN_EXTEND: 16353 case ISD::ZERO_EXTEND: 16354 case ISD::ANY_EXTEND: 16355 break; 16356 } 16357 16358 if (!ExpectingFlags) { 16359 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 16360 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 16361 16362 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 16363 X86::CondCode tmp = cc0; 16364 cc0 = cc1; 16365 cc1 = tmp; 16366 } 16367 16368 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 16369 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 16370 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 16371 X86ISD::NodeType NTOperator = is64BitFP ? 16372 X86ISD::FSETCCsd : X86ISD::FSETCCss; 16373 // FIXME: need symbolic constants for these magic numbers. 16374 // See X86ATTInstPrinter.cpp:printSSECC(). 16375 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 16376 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 16377 DAG.getConstant(x86cc, MVT::i8)); 16378 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 16379 OnesOrZeroesF); 16380 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 16381 DAG.getConstant(1, MVT::i32)); 16382 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 16383 return OneBitOfTruth; 16384 } 16385 } 16386 } 16387 } 16388 return SDValue(); 16389 } 16390 16391 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 16392 /// so it can be folded inside ANDNP. 16393 static bool CanFoldXORWithAllOnes(const SDNode *N) { 16394 EVT VT = N->getValueType(0); 16395 16396 // Match direct AllOnes for 128 and 256-bit vectors 16397 if (ISD::isBuildVectorAllOnes(N)) 16398 return true; 16399 16400 // Look through a bit convert. 16401 if (N->getOpcode() == ISD::BITCAST) 16402 N = N->getOperand(0).getNode(); 16403 16404 // Sometimes the operand may come from a insert_subvector building a 256-bit 16405 // allones vector 16406 if (VT.is256BitVector() && 16407 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 16408 SDValue V1 = N->getOperand(0); 16409 SDValue V2 = N->getOperand(1); 16410 16411 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 16412 V1.getOperand(0).getOpcode() == ISD::UNDEF && 16413 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 16414 ISD::isBuildVectorAllOnes(V2.getNode())) 16415 return true; 16416 } 16417 16418 return false; 16419 } 16420 16421 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized 16422 // register. In most cases we actually compare or select YMM-sized registers 16423 // and mixing the two types creates horrible code. This method optimizes 16424 // some of the transition sequences. 16425 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG, 16426 TargetLowering::DAGCombinerInfo &DCI, 16427 const X86Subtarget *Subtarget) { 16428 EVT VT = N->getValueType(0); 16429 if (!VT.is256BitVector()) 16430 return SDValue(); 16431 16432 assert((N->getOpcode() == ISD::ANY_EXTEND || 16433 N->getOpcode() == ISD::ZERO_EXTEND || 16434 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node"); 16435 16436 SDValue Narrow = N->getOperand(0); 16437 EVT NarrowVT = Narrow->getValueType(0); 16438 if (!NarrowVT.is128BitVector()) 16439 return SDValue(); 16440 16441 if (Narrow->getOpcode() != ISD::XOR && 16442 Narrow->getOpcode() != ISD::AND && 16443 Narrow->getOpcode() != ISD::OR) 16444 return SDValue(); 16445 16446 SDValue N0 = Narrow->getOperand(0); 16447 SDValue N1 = Narrow->getOperand(1); 16448 SDLoc DL(Narrow); 16449 16450 // The Left side has to be a trunc. 16451 if (N0.getOpcode() != ISD::TRUNCATE) 16452 return SDValue(); 16453 16454 // The type of the truncated inputs. 16455 EVT WideVT = N0->getOperand(0)->getValueType(0); 16456 if (WideVT != VT) 16457 return SDValue(); 16458 16459 // The right side has to be a 'trunc' or a constant vector. 16460 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE; 16461 bool RHSConst = (isSplatVector(N1.getNode()) && 16462 isa<ConstantSDNode>(N1->getOperand(0))); 16463 if (!RHSTrunc && !RHSConst) 16464 return SDValue(); 16465 16466 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16467 16468 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT)) 16469 return SDValue(); 16470 16471 // Set N0 and N1 to hold the inputs to the new wide operation. 16472 N0 = N0->getOperand(0); 16473 if (RHSConst) { 16474 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(), 16475 N1->getOperand(0)); 16476 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1); 16477 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size()); 16478 } else if (RHSTrunc) { 16479 N1 = N1->getOperand(0); 16480 } 16481 16482 // Generate the wide operation. 16483 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1); 16484 unsigned Opcode = N->getOpcode(); 16485 switch (Opcode) { 16486 case ISD::ANY_EXTEND: 16487 return Op; 16488 case ISD::ZERO_EXTEND: { 16489 unsigned InBits = NarrowVT.getScalarType().getSizeInBits(); 16490 APInt Mask = APInt::getAllOnesValue(InBits); 16491 Mask = Mask.zext(VT.getScalarType().getSizeInBits()); 16492 return DAG.getNode(ISD::AND, DL, VT, 16493 Op, DAG.getConstant(Mask, VT)); 16494 } 16495 case ISD::SIGN_EXTEND: 16496 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, 16497 Op, DAG.getValueType(NarrowVT)); 16498 default: 16499 llvm_unreachable("Unexpected opcode"); 16500 } 16501 } 16502 16503 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 16504 TargetLowering::DAGCombinerInfo &DCI, 16505 const X86Subtarget *Subtarget) { 16506 EVT VT = N->getValueType(0); 16507 if (DCI.isBeforeLegalizeOps()) 16508 return SDValue(); 16509 16510 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 16511 if (R.getNode()) 16512 return R; 16513 16514 // Create BLSI, and BLSR instructions 16515 // BLSI is X & (-X) 16516 // BLSR is X & (X-1) 16517 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 16518 SDValue N0 = N->getOperand(0); 16519 SDValue N1 = N->getOperand(1); 16520 SDLoc DL(N); 16521 16522 // Check LHS for neg 16523 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 16524 isZero(N0.getOperand(0))) 16525 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 16526 16527 // Check RHS for neg 16528 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 16529 isZero(N1.getOperand(0))) 16530 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 16531 16532 // Check LHS for X-1 16533 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 16534 isAllOnes(N0.getOperand(1))) 16535 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 16536 16537 // Check RHS for X-1 16538 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 16539 isAllOnes(N1.getOperand(1))) 16540 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 16541 16542 return SDValue(); 16543 } 16544 16545 // Want to form ANDNP nodes: 16546 // 1) In the hopes of then easily combining them with OR and AND nodes 16547 // to form PBLEND/PSIGN. 16548 // 2) To match ANDN packed intrinsics 16549 if (VT != MVT::v2i64 && VT != MVT::v4i64) 16550 return SDValue(); 16551 16552 SDValue N0 = N->getOperand(0); 16553 SDValue N1 = N->getOperand(1); 16554 SDLoc DL(N); 16555 16556 // Check LHS for vnot 16557 if (N0.getOpcode() == ISD::XOR && 16558 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 16559 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 16560 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 16561 16562 // Check RHS for vnot 16563 if (N1.getOpcode() == ISD::XOR && 16564 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 16565 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 16566 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 16567 16568 return SDValue(); 16569 } 16570 16571 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 16572 TargetLowering::DAGCombinerInfo &DCI, 16573 const X86Subtarget *Subtarget) { 16574 EVT VT = N->getValueType(0); 16575 if (DCI.isBeforeLegalizeOps()) 16576 return SDValue(); 16577 16578 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 16579 if (R.getNode()) 16580 return R; 16581 16582 SDValue N0 = N->getOperand(0); 16583 SDValue N1 = N->getOperand(1); 16584 16585 // look for psign/blend 16586 if (VT == MVT::v2i64 || VT == MVT::v4i64) { 16587 if (!Subtarget->hasSSSE3() || 16588 (VT == MVT::v4i64 && !Subtarget->hasInt256())) 16589 return SDValue(); 16590 16591 // Canonicalize pandn to RHS 16592 if (N0.getOpcode() == X86ISD::ANDNP) 16593 std::swap(N0, N1); 16594 // or (and (m, y), (pandn m, x)) 16595 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 16596 SDValue Mask = N1.getOperand(0); 16597 SDValue X = N1.getOperand(1); 16598 SDValue Y; 16599 if (N0.getOperand(0) == Mask) 16600 Y = N0.getOperand(1); 16601 if (N0.getOperand(1) == Mask) 16602 Y = N0.getOperand(0); 16603 16604 // Check to see if the mask appeared in both the AND and ANDNP and 16605 if (!Y.getNode()) 16606 return SDValue(); 16607 16608 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 16609 // Look through mask bitcast. 16610 if (Mask.getOpcode() == ISD::BITCAST) 16611 Mask = Mask.getOperand(0); 16612 if (X.getOpcode() == ISD::BITCAST) 16613 X = X.getOperand(0); 16614 if (Y.getOpcode() == ISD::BITCAST) 16615 Y = Y.getOperand(0); 16616 16617 EVT MaskVT = Mask.getValueType(); 16618 16619 // Validate that the Mask operand is a vector sra node. 16620 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 16621 // there is no psrai.b 16622 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 16623 unsigned SraAmt = ~0; 16624 if (Mask.getOpcode() == ISD::SRA) { 16625 SDValue Amt = Mask.getOperand(1); 16626 if (isSplatVector(Amt.getNode())) { 16627 SDValue SclrAmt = Amt->getOperand(0); 16628 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) 16629 SraAmt = C->getZExtValue(); 16630 } 16631 } else if (Mask.getOpcode() == X86ISD::VSRAI) { 16632 SDValue SraC = Mask.getOperand(1); 16633 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 16634 } 16635 if ((SraAmt + 1) != EltBits) 16636 return SDValue(); 16637 16638 SDLoc DL(N); 16639 16640 // Now we know we at least have a plendvb with the mask val. See if 16641 // we can form a psignb/w/d. 16642 // psign = x.type == y.type == mask.type && y = sub(0, x); 16643 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 16644 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 16645 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) { 16646 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) && 16647 "Unsupported VT for PSIGN"); 16648 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0)); 16649 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 16650 } 16651 // PBLENDVB only available on SSE 4.1 16652 if (!Subtarget->hasSSE41()) 16653 return SDValue(); 16654 16655 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8; 16656 16657 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X); 16658 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y); 16659 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask); 16660 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); 16661 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 16662 } 16663 } 16664 16665 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 16666 return SDValue(); 16667 16668 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 16669 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 16670 std::swap(N0, N1); 16671 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 16672 return SDValue(); 16673 if (!N0.hasOneUse() || !N1.hasOneUse()) 16674 return SDValue(); 16675 16676 SDValue ShAmt0 = N0.getOperand(1); 16677 if (ShAmt0.getValueType() != MVT::i8) 16678 return SDValue(); 16679 SDValue ShAmt1 = N1.getOperand(1); 16680 if (ShAmt1.getValueType() != MVT::i8) 16681 return SDValue(); 16682 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 16683 ShAmt0 = ShAmt0.getOperand(0); 16684 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 16685 ShAmt1 = ShAmt1.getOperand(0); 16686 16687 SDLoc DL(N); 16688 unsigned Opc = X86ISD::SHLD; 16689 SDValue Op0 = N0.getOperand(0); 16690 SDValue Op1 = N1.getOperand(0); 16691 if (ShAmt0.getOpcode() == ISD::SUB) { 16692 Opc = X86ISD::SHRD; 16693 std::swap(Op0, Op1); 16694 std::swap(ShAmt0, ShAmt1); 16695 } 16696 16697 unsigned Bits = VT.getSizeInBits(); 16698 if (ShAmt1.getOpcode() == ISD::SUB) { 16699 SDValue Sum = ShAmt1.getOperand(0); 16700 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 16701 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 16702 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 16703 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 16704 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 16705 return DAG.getNode(Opc, DL, VT, 16706 Op0, Op1, 16707 DAG.getNode(ISD::TRUNCATE, DL, 16708 MVT::i8, ShAmt0)); 16709 } 16710 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 16711 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 16712 if (ShAmt0C && 16713 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 16714 return DAG.getNode(Opc, DL, VT, 16715 N0.getOperand(0), N1.getOperand(0), 16716 DAG.getNode(ISD::TRUNCATE, DL, 16717 MVT::i8, ShAmt0)); 16718 } 16719 16720 return SDValue(); 16721 } 16722 16723 // Generate NEG and CMOV for integer abs. 16724 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 16725 EVT VT = N->getValueType(0); 16726 16727 // Since X86 does not have CMOV for 8-bit integer, we don't convert 16728 // 8-bit integer abs to NEG and CMOV. 16729 if (VT.isInteger() && VT.getSizeInBits() == 8) 16730 return SDValue(); 16731 16732 SDValue N0 = N->getOperand(0); 16733 SDValue N1 = N->getOperand(1); 16734 SDLoc DL(N); 16735 16736 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 16737 // and change it to SUB and CMOV. 16738 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 16739 N0.getOpcode() == ISD::ADD && 16740 N0.getOperand(1) == N1 && 16741 N1.getOpcode() == ISD::SRA && 16742 N1.getOperand(0) == N0.getOperand(0)) 16743 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 16744 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) { 16745 // Generate SUB & CMOV. 16746 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32), 16747 DAG.getConstant(0, VT), N0.getOperand(0)); 16748 16749 SDValue Ops[] = { N0.getOperand(0), Neg, 16750 DAG.getConstant(X86::COND_GE, MVT::i8), 16751 SDValue(Neg.getNode(), 1) }; 16752 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), 16753 Ops, array_lengthof(Ops)); 16754 } 16755 return SDValue(); 16756 } 16757 16758 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes 16759 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 16760 TargetLowering::DAGCombinerInfo &DCI, 16761 const X86Subtarget *Subtarget) { 16762 EVT VT = N->getValueType(0); 16763 if (DCI.isBeforeLegalizeOps()) 16764 return SDValue(); 16765 16766 if (Subtarget->hasCMov()) { 16767 SDValue RV = performIntegerAbsCombine(N, DAG); 16768 if (RV.getNode()) 16769 return RV; 16770 } 16771 16772 // Try forming BMI if it is available. 16773 if (!Subtarget->hasBMI()) 16774 return SDValue(); 16775 16776 if (VT != MVT::i32 && VT != MVT::i64) 16777 return SDValue(); 16778 16779 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions"); 16780 16781 // Create BLSMSK instructions by finding X ^ (X-1) 16782 SDValue N0 = N->getOperand(0); 16783 SDValue N1 = N->getOperand(1); 16784 SDLoc DL(N); 16785 16786 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 16787 isAllOnes(N0.getOperand(1))) 16788 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 16789 16790 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 16791 isAllOnes(N1.getOperand(1))) 16792 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 16793 16794 return SDValue(); 16795 } 16796 16797 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 16798 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 16799 TargetLowering::DAGCombinerInfo &DCI, 16800 const X86Subtarget *Subtarget) { 16801 LoadSDNode *Ld = cast<LoadSDNode>(N); 16802 EVT RegVT = Ld->getValueType(0); 16803 EVT MemVT = Ld->getMemoryVT(); 16804 SDLoc dl(Ld); 16805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16806 unsigned RegSz = RegVT.getSizeInBits(); 16807 16808 // On Sandybridge unaligned 256bit loads are inefficient. 16809 ISD::LoadExtType Ext = Ld->getExtensionType(); 16810 unsigned Alignment = Ld->getAlignment(); 16811 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8; 16812 if (RegVT.is256BitVector() && !Subtarget->hasInt256() && 16813 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) { 16814 unsigned NumElems = RegVT.getVectorNumElements(); 16815 if (NumElems < 2) 16816 return SDValue(); 16817 16818 SDValue Ptr = Ld->getBasePtr(); 16819 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy()); 16820 16821 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 16822 NumElems/2); 16823 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, 16824 Ld->getPointerInfo(), Ld->isVolatile(), 16825 Ld->isNonTemporal(), Ld->isInvariant(), 16826 Alignment); 16827 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 16828 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, 16829 Ld->getPointerInfo(), Ld->isVolatile(), 16830 Ld->isNonTemporal(), Ld->isInvariant(), 16831 std::min(16U, Alignment)); 16832 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 16833 Load1.getValue(1), 16834 Load2.getValue(1)); 16835 16836 SDValue NewVec = DAG.getUNDEF(RegVT); 16837 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl); 16838 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl); 16839 return DCI.CombineTo(N, NewVec, TF, true); 16840 } 16841 16842 // If this is a vector EXT Load then attempt to optimize it using a 16843 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the 16844 // expansion is still better than scalar code. 16845 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll 16846 // emit a shuffle and a arithmetic shift. 16847 // TODO: It is possible to support ZExt by zeroing the undef values 16848 // during the shuffle phase or after the shuffle. 16849 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() && 16850 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) { 16851 assert(MemVT != RegVT && "Cannot extend to the same type"); 16852 assert(MemVT.isVector() && "Must load a vector from memory"); 16853 16854 unsigned NumElems = RegVT.getVectorNumElements(); 16855 unsigned MemSz = MemVT.getSizeInBits(); 16856 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 16857 16858 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) 16859 return SDValue(); 16860 16861 // All sizes must be a power of two. 16862 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) 16863 return SDValue(); 16864 16865 // Attempt to load the original value using scalar loads. 16866 // Find the largest scalar type that divides the total loaded size. 16867 MVT SclrLoadTy = MVT::i8; 16868 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 16869 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 16870 MVT Tp = (MVT::SimpleValueType)tp; 16871 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) { 16872 SclrLoadTy = Tp; 16873 } 16874 } 16875 16876 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 16877 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 && 16878 (64 <= MemSz)) 16879 SclrLoadTy = MVT::f64; 16880 16881 // Calculate the number of scalar loads that we need to perform 16882 // in order to load our vector from memory. 16883 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits(); 16884 if (Ext == ISD::SEXTLOAD && NumLoads > 1) 16885 return SDValue(); 16886 16887 unsigned loadRegZize = RegSz; 16888 if (Ext == ISD::SEXTLOAD && RegSz == 256) 16889 loadRegZize /= 2; 16890 16891 // Represent our vector as a sequence of elements which are the 16892 // largest scalar that we can load. 16893 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 16894 loadRegZize/SclrLoadTy.getSizeInBits()); 16895 16896 // Represent the data using the same element type that is stored in 16897 // memory. In practice, we ''widen'' MemVT. 16898 EVT WideVecVT = 16899 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 16900 loadRegZize/MemVT.getScalarType().getSizeInBits()); 16901 16902 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && 16903 "Invalid vector type"); 16904 16905 // We can't shuffle using an illegal type. 16906 if (!TLI.isTypeLegal(WideVecVT)) 16907 return SDValue(); 16908 16909 SmallVector<SDValue, 8> Chains; 16910 SDValue Ptr = Ld->getBasePtr(); 16911 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8, 16912 TLI.getPointerTy()); 16913 SDValue Res = DAG.getUNDEF(LoadUnitVecVT); 16914 16915 for (unsigned i = 0; i < NumLoads; ++i) { 16916 // Perform a single load. 16917 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 16918 Ptr, Ld->getPointerInfo(), 16919 Ld->isVolatile(), Ld->isNonTemporal(), 16920 Ld->isInvariant(), Ld->getAlignment()); 16921 Chains.push_back(ScalarLoad.getValue(1)); 16922 // Create the first element type using SCALAR_TO_VECTOR in order to avoid 16923 // another round of DAGCombining. 16924 if (i == 0) 16925 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad); 16926 else 16927 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res, 16928 ScalarLoad, DAG.getIntPtrConstant(i)); 16929 16930 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 16931 } 16932 16933 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 16934 Chains.size()); 16935 16936 // Bitcast the loaded value to a vector of the original element type, in 16937 // the size of the target vector type. 16938 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res); 16939 unsigned SizeRatio = RegSz/MemSz; 16940 16941 if (Ext == ISD::SEXTLOAD) { 16942 // If we have SSE4.1 we can directly emit a VSEXT node. 16943 if (Subtarget->hasSSE41()) { 16944 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec); 16945 return DCI.CombineTo(N, Sext, TF, true); 16946 } 16947 16948 // Otherwise we'll shuffle the small elements in the high bits of the 16949 // larger type and perform an arithmetic shift. If the shift is not legal 16950 // it's better to scalarize. 16951 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT)) 16952 return SDValue(); 16953 16954 // Redistribute the loaded elements into the different locations. 16955 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 16956 for (unsigned i = 0; i != NumElems; ++i) 16957 ShuffleVec[i*SizeRatio + SizeRatio-1] = i; 16958 16959 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 16960 DAG.getUNDEF(WideVecVT), 16961 &ShuffleVec[0]); 16962 16963 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 16964 16965 // Build the arithmetic shift. 16966 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() - 16967 MemVT.getVectorElementType().getSizeInBits(); 16968 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, 16969 DAG.getConstant(Amt, RegVT)); 16970 16971 return DCI.CombineTo(N, Shuff, TF, true); 16972 } 16973 16974 // Redistribute the loaded elements into the different locations. 16975 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 16976 for (unsigned i = 0; i != NumElems; ++i) 16977 ShuffleVec[i*SizeRatio] = i; 16978 16979 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 16980 DAG.getUNDEF(WideVecVT), 16981 &ShuffleVec[0]); 16982 16983 // Bitcast to the requested type. 16984 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 16985 // Replace the original load with the new sequence 16986 // and return the new chain. 16987 return DCI.CombineTo(N, Shuff, TF, true); 16988 } 16989 16990 return SDValue(); 16991 } 16992 16993 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 16994 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 16995 const X86Subtarget *Subtarget) { 16996 StoreSDNode *St = cast<StoreSDNode>(N); 16997 EVT VT = St->getValue().getValueType(); 16998 EVT StVT = St->getMemoryVT(); 16999 SDLoc dl(St); 17000 SDValue StoredVal = St->getOperand(1); 17001 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17002 17003 // If we are saving a concatenation of two XMM registers, perform two stores. 17004 // On Sandy Bridge, 256-bit memory operations are executed by two 17005 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit 17006 // memory operation. 17007 unsigned Alignment = St->getAlignment(); 17008 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8; 17009 if (VT.is256BitVector() && !Subtarget->hasInt256() && 17010 StVT == VT && !IsAligned) { 17011 unsigned NumElems = VT.getVectorNumElements(); 17012 if (NumElems < 2) 17013 return SDValue(); 17014 17015 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl); 17016 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl); 17017 17018 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 17019 SDValue Ptr0 = St->getBasePtr(); 17020 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 17021 17022 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 17023 St->getPointerInfo(), St->isVolatile(), 17024 St->isNonTemporal(), Alignment); 17025 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 17026 St->getPointerInfo(), St->isVolatile(), 17027 St->isNonTemporal(), 17028 std::min(16U, Alignment)); 17029 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 17030 } 17031 17032 // Optimize trunc store (of multiple scalars) to shuffle and store. 17033 // First, pack all of the elements in one place. Next, store to memory 17034 // in fewer chunks. 17035 if (St->isTruncatingStore() && VT.isVector()) { 17036 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17037 unsigned NumElems = VT.getVectorNumElements(); 17038 assert(StVT != VT && "Cannot truncate to the same type"); 17039 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 17040 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 17041 17042 // From, To sizes and ElemCount must be pow of two 17043 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 17044 // We are going to use the original vector elt for storing. 17045 // Accumulated smaller vector elements must be a multiple of the store size. 17046 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 17047 17048 unsigned SizeRatio = FromSz / ToSz; 17049 17050 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 17051 17052 // Create a type on which we perform the shuffle 17053 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 17054 StVT.getScalarType(), NumElems*SizeRatio); 17055 17056 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 17057 17058 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 17059 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 17060 for (unsigned i = 0; i != NumElems; ++i) 17061 ShuffleVec[i] = i * SizeRatio; 17062 17063 // Can't shuffle using an illegal type. 17064 if (!TLI.isTypeLegal(WideVecVT)) 17065 return SDValue(); 17066 17067 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 17068 DAG.getUNDEF(WideVecVT), 17069 &ShuffleVec[0]); 17070 // At this point all of the data is stored at the bottom of the 17071 // register. We now need to save it to mem. 17072 17073 // Find the largest store unit 17074 MVT StoreType = MVT::i8; 17075 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 17076 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 17077 MVT Tp = (MVT::SimpleValueType)tp; 17078 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz) 17079 StoreType = Tp; 17080 } 17081 17082 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 17083 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 && 17084 (64 <= NumElems * ToSz)) 17085 StoreType = MVT::f64; 17086 17087 // Bitcast the original vector into a vector of store-size units 17088 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 17089 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits()); 17090 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 17091 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 17092 SmallVector<SDValue, 8> Chains; 17093 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 17094 TLI.getPointerTy()); 17095 SDValue Ptr = St->getBasePtr(); 17096 17097 // Perform one or more big stores into memory. 17098 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) { 17099 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 17100 StoreType, ShuffWide, 17101 DAG.getIntPtrConstant(i)); 17102 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 17103 St->getPointerInfo(), St->isVolatile(), 17104 St->isNonTemporal(), St->getAlignment()); 17105 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 17106 Chains.push_back(Ch); 17107 } 17108 17109 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 17110 Chains.size()); 17111 } 17112 17113 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 17114 // the FP state in cases where an emms may be missing. 17115 // A preferable solution to the general problem is to figure out the right 17116 // places to insert EMMS. This qualifies as a quick hack. 17117 17118 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 17119 if (VT.getSizeInBits() != 64) 17120 return SDValue(); 17121 17122 const Function *F = DAG.getMachineFunction().getFunction(); 17123 bool NoImplicitFloatOps = F->getAttributes(). 17124 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 17125 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps 17126 && Subtarget->hasSSE2(); 17127 if ((VT.isVector() || 17128 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 17129 isa<LoadSDNode>(St->getValue()) && 17130 !cast<LoadSDNode>(St->getValue())->isVolatile() && 17131 St->getChain().hasOneUse() && !St->isVolatile()) { 17132 SDNode* LdVal = St->getValue().getNode(); 17133 LoadSDNode *Ld = 0; 17134 int TokenFactorIndex = -1; 17135 SmallVector<SDValue, 8> Ops; 17136 SDNode* ChainVal = St->getChain().getNode(); 17137 // Must be a store of a load. We currently handle two cases: the load 17138 // is a direct child, and it's under an intervening TokenFactor. It is 17139 // possible to dig deeper under nested TokenFactors. 17140 if (ChainVal == LdVal) 17141 Ld = cast<LoadSDNode>(St->getChain()); 17142 else if (St->getValue().hasOneUse() && 17143 ChainVal->getOpcode() == ISD::TokenFactor) { 17144 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) { 17145 if (ChainVal->getOperand(i).getNode() == LdVal) { 17146 TokenFactorIndex = i; 17147 Ld = cast<LoadSDNode>(St->getValue()); 17148 } else 17149 Ops.push_back(ChainVal->getOperand(i)); 17150 } 17151 } 17152 17153 if (!Ld || !ISD::isNormalLoad(Ld)) 17154 return SDValue(); 17155 17156 // If this is not the MMX case, i.e. we are just turning i64 load/store 17157 // into f64 load/store, avoid the transformation if there are multiple 17158 // uses of the loaded value. 17159 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 17160 return SDValue(); 17161 17162 SDLoc LdDL(Ld); 17163 SDLoc StDL(N); 17164 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 17165 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 17166 // pair instead. 17167 if (Subtarget->is64Bit() || F64IsLegal) { 17168 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 17169 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 17170 Ld->getPointerInfo(), Ld->isVolatile(), 17171 Ld->isNonTemporal(), Ld->isInvariant(), 17172 Ld->getAlignment()); 17173 SDValue NewChain = NewLd.getValue(1); 17174 if (TokenFactorIndex != -1) { 17175 Ops.push_back(NewChain); 17176 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 17177 Ops.size()); 17178 } 17179 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 17180 St->getPointerInfo(), 17181 St->isVolatile(), St->isNonTemporal(), 17182 St->getAlignment()); 17183 } 17184 17185 // Otherwise, lower to two pairs of 32-bit loads / stores. 17186 SDValue LoAddr = Ld->getBasePtr(); 17187 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 17188 DAG.getConstant(4, MVT::i32)); 17189 17190 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 17191 Ld->getPointerInfo(), 17192 Ld->isVolatile(), Ld->isNonTemporal(), 17193 Ld->isInvariant(), Ld->getAlignment()); 17194 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 17195 Ld->getPointerInfo().getWithOffset(4), 17196 Ld->isVolatile(), Ld->isNonTemporal(), 17197 Ld->isInvariant(), 17198 MinAlign(Ld->getAlignment(), 4)); 17199 17200 SDValue NewChain = LoLd.getValue(1); 17201 if (TokenFactorIndex != -1) { 17202 Ops.push_back(LoLd); 17203 Ops.push_back(HiLd); 17204 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 17205 Ops.size()); 17206 } 17207 17208 LoAddr = St->getBasePtr(); 17209 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 17210 DAG.getConstant(4, MVT::i32)); 17211 17212 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 17213 St->getPointerInfo(), 17214 St->isVolatile(), St->isNonTemporal(), 17215 St->getAlignment()); 17216 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 17217 St->getPointerInfo().getWithOffset(4), 17218 St->isVolatile(), 17219 St->isNonTemporal(), 17220 MinAlign(St->getAlignment(), 4)); 17221 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 17222 } 17223 return SDValue(); 17224 } 17225 17226 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 17227 /// and return the operands for the horizontal operation in LHS and RHS. A 17228 /// horizontal operation performs the binary operation on successive elements 17229 /// of its first operand, then on successive elements of its second operand, 17230 /// returning the resulting values in a vector. For example, if 17231 /// A = < float a0, float a1, float a2, float a3 > 17232 /// and 17233 /// B = < float b0, float b1, float b2, float b3 > 17234 /// then the result of doing a horizontal operation on A and B is 17235 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 17236 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 17237 /// A horizontal-op B, for some already available A and B, and if so then LHS is 17238 /// set to A, RHS to B, and the routine returns 'true'. 17239 /// Note that the binary operation should have the property that if one of the 17240 /// operands is UNDEF then the result is UNDEF. 17241 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) { 17242 // Look for the following pattern: if 17243 // A = < float a0, float a1, float a2, float a3 > 17244 // B = < float b0, float b1, float b2, float b3 > 17245 // and 17246 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 17247 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 17248 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 17249 // which is A horizontal-op B. 17250 17251 // At least one of the operands should be a vector shuffle. 17252 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 17253 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 17254 return false; 17255 17256 EVT VT = LHS.getValueType(); 17257 17258 assert((VT.is128BitVector() || VT.is256BitVector()) && 17259 "Unsupported vector type for horizontal add/sub"); 17260 17261 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to 17262 // operate independently on 128-bit lanes. 17263 unsigned NumElts = VT.getVectorNumElements(); 17264 unsigned NumLanes = VT.getSizeInBits()/128; 17265 unsigned NumLaneElts = NumElts / NumLanes; 17266 assert((NumLaneElts % 2 == 0) && 17267 "Vector type should have an even number of elements in each lane"); 17268 unsigned HalfLaneElts = NumLaneElts/2; 17269 17270 // View LHS in the form 17271 // LHS = VECTOR_SHUFFLE A, B, LMask 17272 // If LHS is not a shuffle then pretend it is the shuffle 17273 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 17274 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 17275 // type VT. 17276 SDValue A, B; 17277 SmallVector<int, 16> LMask(NumElts); 17278 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 17279 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 17280 A = LHS.getOperand(0); 17281 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 17282 B = LHS.getOperand(1); 17283 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(); 17284 std::copy(Mask.begin(), Mask.end(), LMask.begin()); 17285 } else { 17286 if (LHS.getOpcode() != ISD::UNDEF) 17287 A = LHS; 17288 for (unsigned i = 0; i != NumElts; ++i) 17289 LMask[i] = i; 17290 } 17291 17292 // Likewise, view RHS in the form 17293 // RHS = VECTOR_SHUFFLE C, D, RMask 17294 SDValue C, D; 17295 SmallVector<int, 16> RMask(NumElts); 17296 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 17297 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 17298 C = RHS.getOperand(0); 17299 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 17300 D = RHS.getOperand(1); 17301 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(); 17302 std::copy(Mask.begin(), Mask.end(), RMask.begin()); 17303 } else { 17304 if (RHS.getOpcode() != ISD::UNDEF) 17305 C = RHS; 17306 for (unsigned i = 0; i != NumElts; ++i) 17307 RMask[i] = i; 17308 } 17309 17310 // Check that the shuffles are both shuffling the same vectors. 17311 if (!(A == C && B == D) && !(A == D && B == C)) 17312 return false; 17313 17314 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 17315 if (!A.getNode() && !B.getNode()) 17316 return false; 17317 17318 // If A and B occur in reverse order in RHS, then "swap" them (which means 17319 // rewriting the mask). 17320 if (A != C) 17321 CommuteVectorShuffleMask(RMask, NumElts); 17322 17323 // At this point LHS and RHS are equivalent to 17324 // LHS = VECTOR_SHUFFLE A, B, LMask 17325 // RHS = VECTOR_SHUFFLE A, B, RMask 17326 // Check that the masks correspond to performing a horizontal operation. 17327 for (unsigned i = 0; i != NumElts; ++i) { 17328 int LIdx = LMask[i], RIdx = RMask[i]; 17329 17330 // Ignore any UNDEF components. 17331 if (LIdx < 0 || RIdx < 0 || 17332 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) || 17333 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts))) 17334 continue; 17335 17336 // Check that successive elements are being operated on. If not, this is 17337 // not a horizontal operation. 17338 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs 17339 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts; 17340 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart; 17341 if (!(LIdx == Index && RIdx == Index + 1) && 17342 !(IsCommutative && LIdx == Index + 1 && RIdx == Index)) 17343 return false; 17344 } 17345 17346 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 17347 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 17348 return true; 17349 } 17350 17351 /// PerformFADDCombine - Do target-specific dag combines on floating point adds. 17352 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 17353 const X86Subtarget *Subtarget) { 17354 EVT VT = N->getValueType(0); 17355 SDValue LHS = N->getOperand(0); 17356 SDValue RHS = N->getOperand(1); 17357 17358 // Try to synthesize horizontal adds from adds of shuffles. 17359 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 17360 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 17361 isHorizontalBinOp(LHS, RHS, true)) 17362 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS); 17363 return SDValue(); 17364 } 17365 17366 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 17367 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 17368 const X86Subtarget *Subtarget) { 17369 EVT VT = N->getValueType(0); 17370 SDValue LHS = N->getOperand(0); 17371 SDValue RHS = N->getOperand(1); 17372 17373 // Try to synthesize horizontal subs from subs of shuffles. 17374 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 17375 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 17376 isHorizontalBinOp(LHS, RHS, false)) 17377 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS); 17378 return SDValue(); 17379 } 17380 17381 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 17382 /// X86ISD::FXOR nodes. 17383 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 17384 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 17385 // F[X]OR(0.0, x) -> x 17386 // F[X]OR(x, 0.0) -> x 17387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 17388 if (C->getValueAPF().isPosZero()) 17389 return N->getOperand(1); 17390 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 17391 if (C->getValueAPF().isPosZero()) 17392 return N->getOperand(0); 17393 return SDValue(); 17394 } 17395 17396 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and 17397 /// X86ISD::FMAX nodes. 17398 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) { 17399 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX); 17400 17401 // Only perform optimizations if UnsafeMath is used. 17402 if (!DAG.getTarget().Options.UnsafeFPMath) 17403 return SDValue(); 17404 17405 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes 17406 // into FMINC and FMAXC, which are Commutative operations. 17407 unsigned NewOp = 0; 17408 switch (N->getOpcode()) { 17409 default: llvm_unreachable("unknown opcode"); 17410 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break; 17411 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break; 17412 } 17413 17414 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0), 17415 N->getOperand(0), N->getOperand(1)); 17416 } 17417 17418 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 17419 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 17420 // FAND(0.0, x) -> 0.0 17421 // FAND(x, 0.0) -> 0.0 17422 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 17423 if (C->getValueAPF().isPosZero()) 17424 return N->getOperand(0); 17425 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 17426 if (C->getValueAPF().isPosZero()) 17427 return N->getOperand(1); 17428 return SDValue(); 17429 } 17430 17431 static SDValue PerformBTCombine(SDNode *N, 17432 SelectionDAG &DAG, 17433 TargetLowering::DAGCombinerInfo &DCI) { 17434 // BT ignores high bits in the bit index operand. 17435 SDValue Op1 = N->getOperand(1); 17436 if (Op1.hasOneUse()) { 17437 unsigned BitWidth = Op1.getValueSizeInBits(); 17438 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 17439 APInt KnownZero, KnownOne; 17440 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 17441 !DCI.isBeforeLegalizeOps()); 17442 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17443 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 17444 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 17445 DCI.CommitTargetLoweringOpt(TLO); 17446 } 17447 return SDValue(); 17448 } 17449 17450 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 17451 SDValue Op = N->getOperand(0); 17452 if (Op.getOpcode() == ISD::BITCAST) 17453 Op = Op.getOperand(0); 17454 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 17455 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 17456 VT.getVectorElementType().getSizeInBits() == 17457 OpVT.getVectorElementType().getSizeInBits()) { 17458 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 17459 } 17460 return SDValue(); 17461 } 17462 17463 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 17464 const X86Subtarget *Subtarget) { 17465 EVT VT = N->getValueType(0); 17466 if (!VT.isVector()) 17467 return SDValue(); 17468 17469 SDValue N0 = N->getOperand(0); 17470 SDValue N1 = N->getOperand(1); 17471 EVT ExtraVT = cast<VTSDNode>(N1)->getVT(); 17472 SDLoc dl(N); 17473 17474 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the 17475 // both SSE and AVX2 since there is no sign-extended shift right 17476 // operation on a vector with 64-bit elements. 17477 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) -> 17478 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT))) 17479 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND || 17480 N0.getOpcode() == ISD::SIGN_EXTEND)) { 17481 SDValue N00 = N0.getOperand(0); 17482 17483 // EXTLOAD has a better solution on AVX2, 17484 // it may be replaced with X86ISD::VSEXT node. 17485 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256()) 17486 if (!ISD::isNormalLoad(N00.getNode())) 17487 return SDValue(); 17488 17489 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) { 17490 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 17491 N00, N1); 17492 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp); 17493 } 17494 } 17495 return SDValue(); 17496 } 17497 17498 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG, 17499 TargetLowering::DAGCombinerInfo &DCI, 17500 const X86Subtarget *Subtarget) { 17501 if (!DCI.isBeforeLegalizeOps()) 17502 return SDValue(); 17503 17504 if (!Subtarget->hasFp256()) 17505 return SDValue(); 17506 17507 EVT VT = N->getValueType(0); 17508 if (VT.isVector() && VT.getSizeInBits() == 256) { 17509 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 17510 if (R.getNode()) 17511 return R; 17512 } 17513 17514 return SDValue(); 17515 } 17516 17517 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG, 17518 const X86Subtarget* Subtarget) { 17519 SDLoc dl(N); 17520 EVT VT = N->getValueType(0); 17521 17522 // Let legalize expand this if it isn't a legal type yet. 17523 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 17524 return SDValue(); 17525 17526 EVT ScalarVT = VT.getScalarType(); 17527 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || 17528 (!Subtarget->hasFMA() && !Subtarget->hasFMA4())) 17529 return SDValue(); 17530 17531 SDValue A = N->getOperand(0); 17532 SDValue B = N->getOperand(1); 17533 SDValue C = N->getOperand(2); 17534 17535 bool NegA = (A.getOpcode() == ISD::FNEG); 17536 bool NegB = (B.getOpcode() == ISD::FNEG); 17537 bool NegC = (C.getOpcode() == ISD::FNEG); 17538 17539 // Negative multiplication when NegA xor NegB 17540 bool NegMul = (NegA != NegB); 17541 if (NegA) 17542 A = A.getOperand(0); 17543 if (NegB) 17544 B = B.getOperand(0); 17545 if (NegC) 17546 C = C.getOperand(0); 17547 17548 unsigned Opcode; 17549 if (!NegMul) 17550 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB; 17551 else 17552 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB; 17553 17554 return DAG.getNode(Opcode, dl, VT, A, B, C); 17555 } 17556 17557 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG, 17558 TargetLowering::DAGCombinerInfo &DCI, 17559 const X86Subtarget *Subtarget) { 17560 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 17561 // (and (i32 x86isd::setcc_carry), 1) 17562 // This eliminates the zext. This transformation is necessary because 17563 // ISD::SETCC is always legalized to i8. 17564 SDLoc dl(N); 17565 SDValue N0 = N->getOperand(0); 17566 EVT VT = N->getValueType(0); 17567 17568 if (N0.getOpcode() == ISD::AND && 17569 N0.hasOneUse() && 17570 N0.getOperand(0).hasOneUse()) { 17571 SDValue N00 = N0.getOperand(0); 17572 if (N00.getOpcode() == X86ISD::SETCC_CARRY) { 17573 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 17574 if (!C || C->getZExtValue() != 1) 17575 return SDValue(); 17576 return DAG.getNode(ISD::AND, dl, VT, 17577 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 17578 N00.getOperand(0), N00.getOperand(1)), 17579 DAG.getConstant(1, VT)); 17580 } 17581 } 17582 17583 if (VT.is256BitVector()) { 17584 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 17585 if (R.getNode()) 17586 return R; 17587 } 17588 17589 return SDValue(); 17590 } 17591 17592 // Optimize x == -y --> x+y == 0 17593 // x != -y --> x+y != 0 17594 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) { 17595 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 17596 SDValue LHS = N->getOperand(0); 17597 SDValue RHS = N->getOperand(1); 17598 17599 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB) 17600 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0))) 17601 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) { 17602 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), 17603 LHS.getValueType(), RHS, LHS.getOperand(1)); 17604 return DAG.getSetCC(SDLoc(N), N->getValueType(0), 17605 addV, DAG.getConstant(0, addV.getValueType()), CC); 17606 } 17607 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB) 17608 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0))) 17609 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) { 17610 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N), 17611 RHS.getValueType(), LHS, RHS.getOperand(1)); 17612 return DAG.getSetCC(SDLoc(N), N->getValueType(0), 17613 addV, DAG.getConstant(0, addV.getValueType()), CC); 17614 } 17615 return SDValue(); 17616 } 17617 17618 // Helper function of PerformSETCCCombine. It is to materialize "setb reg" 17619 // as "sbb reg,reg", since it can be extended without zext and produces 17620 // an all-ones bit which is more useful than 0/1 in some cases. 17621 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) { 17622 return DAG.getNode(ISD::AND, DL, MVT::i8, 17623 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 17624 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS), 17625 DAG.getConstant(1, MVT::i8)); 17626 } 17627 17628 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 17629 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG, 17630 TargetLowering::DAGCombinerInfo &DCI, 17631 const X86Subtarget *Subtarget) { 17632 SDLoc DL(N); 17633 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0)); 17634 SDValue EFLAGS = N->getOperand(1); 17635 17636 if (CC == X86::COND_A) { 17637 // Try to convert COND_A into COND_B in an attempt to facilitate 17638 // materializing "setb reg". 17639 // 17640 // Do not flip "e > c", where "c" is a constant, because Cmp instruction 17641 // cannot take an immediate as its first operand. 17642 // 17643 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 17644 EFLAGS.getValueType().isInteger() && 17645 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) { 17646 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), 17647 EFLAGS.getNode()->getVTList(), 17648 EFLAGS.getOperand(1), EFLAGS.getOperand(0)); 17649 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo()); 17650 return MaterializeSETB(DL, NewEFLAGS, DAG); 17651 } 17652 } 17653 17654 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 17655 // a zext and produces an all-ones bit which is more useful than 0/1 in some 17656 // cases. 17657 if (CC == X86::COND_B) 17658 return MaterializeSETB(DL, EFLAGS, DAG); 17659 17660 SDValue Flags; 17661 17662 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 17663 if (Flags.getNode()) { 17664 SDValue Cond = DAG.getConstant(CC, MVT::i8); 17665 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags); 17666 } 17667 17668 return SDValue(); 17669 } 17670 17671 // Optimize branch condition evaluation. 17672 // 17673 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG, 17674 TargetLowering::DAGCombinerInfo &DCI, 17675 const X86Subtarget *Subtarget) { 17676 SDLoc DL(N); 17677 SDValue Chain = N->getOperand(0); 17678 SDValue Dest = N->getOperand(1); 17679 SDValue EFLAGS = N->getOperand(3); 17680 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2)); 17681 17682 SDValue Flags; 17683 17684 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 17685 if (Flags.getNode()) { 17686 SDValue Cond = DAG.getConstant(CC, MVT::i8); 17687 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond, 17688 Flags); 17689 } 17690 17691 return SDValue(); 17692 } 17693 17694 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 17695 const X86TargetLowering *XTLI) { 17696 SDValue Op0 = N->getOperand(0); 17697 EVT InVT = Op0->getValueType(0); 17698 17699 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32)) 17700 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) { 17701 SDLoc dl(N); 17702 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 17703 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0); 17704 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P); 17705 } 17706 17707 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 17708 // a 32-bit target where SSE doesn't support i64->FP operations. 17709 if (Op0.getOpcode() == ISD::LOAD) { 17710 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 17711 EVT VT = Ld->getValueType(0); 17712 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 17713 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 17714 !XTLI->getSubtarget()->is64Bit() && 17715 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 17716 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 17717 Ld->getChain(), Op0, DAG); 17718 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 17719 return FILDChain; 17720 } 17721 } 17722 return SDValue(); 17723 } 17724 17725 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 17726 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 17727 X86TargetLowering::DAGCombinerInfo &DCI) { 17728 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 17729 // the result is either zero or one (depending on the input carry bit). 17730 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 17731 if (X86::isZeroNode(N->getOperand(0)) && 17732 X86::isZeroNode(N->getOperand(1)) && 17733 // We don't have a good way to replace an EFLAGS use, so only do this when 17734 // dead right now. 17735 SDValue(N, 1).use_empty()) { 17736 SDLoc DL(N); 17737 EVT VT = N->getValueType(0); 17738 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 17739 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 17740 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 17741 DAG.getConstant(X86::COND_B,MVT::i8), 17742 N->getOperand(2)), 17743 DAG.getConstant(1, VT)); 17744 return DCI.CombineTo(N, Res1, CarryOut); 17745 } 17746 17747 return SDValue(); 17748 } 17749 17750 // fold (add Y, (sete X, 0)) -> adc 0, Y 17751 // (add Y, (setne X, 0)) -> sbb -1, Y 17752 // (sub (sete X, 0), Y) -> sbb 0, Y 17753 // (sub (setne X, 0), Y) -> adc -1, Y 17754 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 17755 SDLoc DL(N); 17756 17757 // Look through ZExts. 17758 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 17759 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 17760 return SDValue(); 17761 17762 SDValue SetCC = Ext.getOperand(0); 17763 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 17764 return SDValue(); 17765 17766 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 17767 if (CC != X86::COND_E && CC != X86::COND_NE) 17768 return SDValue(); 17769 17770 SDValue Cmp = SetCC.getOperand(1); 17771 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 17772 !X86::isZeroNode(Cmp.getOperand(1)) || 17773 !Cmp.getOperand(0).getValueType().isInteger()) 17774 return SDValue(); 17775 17776 SDValue CmpOp0 = Cmp.getOperand(0); 17777 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 17778 DAG.getConstant(1, CmpOp0.getValueType())); 17779 17780 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 17781 if (CC == X86::COND_NE) 17782 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 17783 DL, OtherVal.getValueType(), OtherVal, 17784 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 17785 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 17786 DL, OtherVal.getValueType(), OtherVal, 17787 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 17788 } 17789 17790 /// PerformADDCombine - Do target-specific dag combines on integer adds. 17791 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG, 17792 const X86Subtarget *Subtarget) { 17793 EVT VT = N->getValueType(0); 17794 SDValue Op0 = N->getOperand(0); 17795 SDValue Op1 = N->getOperand(1); 17796 17797 // Try to synthesize horizontal adds from adds of shuffles. 17798 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 17799 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 17800 isHorizontalBinOp(Op0, Op1, true)) 17801 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1); 17802 17803 return OptimizeConditionalInDecrement(N, DAG); 17804 } 17805 17806 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG, 17807 const X86Subtarget *Subtarget) { 17808 SDValue Op0 = N->getOperand(0); 17809 SDValue Op1 = N->getOperand(1); 17810 17811 // X86 can't encode an immediate LHS of a sub. See if we can push the 17812 // negation into a preceding instruction. 17813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 17814 // If the RHS of the sub is a XOR with one use and a constant, invert the 17815 // immediate. Then add one to the LHS of the sub so we can turn 17816 // X-Y -> X+~Y+1, saving one register. 17817 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 17818 isa<ConstantSDNode>(Op1.getOperand(1))) { 17819 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 17820 EVT VT = Op0.getValueType(); 17821 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, 17822 Op1.getOperand(0), 17823 DAG.getConstant(~XorC, VT)); 17824 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor, 17825 DAG.getConstant(C->getAPIntValue()+1, VT)); 17826 } 17827 } 17828 17829 // Try to synthesize horizontal adds from adds of shuffles. 17830 EVT VT = N->getValueType(0); 17831 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 17832 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 17833 isHorizontalBinOp(Op0, Op1, true)) 17834 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1); 17835 17836 return OptimizeConditionalInDecrement(N, DAG); 17837 } 17838 17839 /// performVZEXTCombine - Performs build vector combines 17840 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG, 17841 TargetLowering::DAGCombinerInfo &DCI, 17842 const X86Subtarget *Subtarget) { 17843 // (vzext (bitcast (vzext (x)) -> (vzext x) 17844 SDValue In = N->getOperand(0); 17845 while (In.getOpcode() == ISD::BITCAST) 17846 In = In.getOperand(0); 17847 17848 if (In.getOpcode() != X86ISD::VZEXT) 17849 return SDValue(); 17850 17851 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0), 17852 In.getOperand(0)); 17853 } 17854 17855 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 17856 DAGCombinerInfo &DCI) const { 17857 SelectionDAG &DAG = DCI.DAG; 17858 switch (N->getOpcode()) { 17859 default: break; 17860 case ISD::EXTRACT_VECTOR_ELT: 17861 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI); 17862 case ISD::VSELECT: 17863 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget); 17864 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget); 17865 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget); 17866 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget); 17867 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 17868 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 17869 case ISD::SHL: 17870 case ISD::SRA: 17871 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget); 17872 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 17873 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 17874 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 17875 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget); 17876 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 17877 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 17878 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 17879 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 17880 case X86ISD::FXOR: 17881 case X86ISD::FOR: return PerformFORCombine(N, DAG); 17882 case X86ISD::FMIN: 17883 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG); 17884 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 17885 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 17886 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 17887 case ISD::ANY_EXTEND: 17888 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget); 17889 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget); 17890 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 17891 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget); 17892 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG); 17893 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget); 17894 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget); 17895 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget); 17896 case X86ISD::SHUFP: // Handle all target specific shuffles 17897 case X86ISD::PALIGNR: 17898 case X86ISD::UNPCKH: 17899 case X86ISD::UNPCKL: 17900 case X86ISD::MOVHLPS: 17901 case X86ISD::MOVLHPS: 17902 case X86ISD::PSHUFD: 17903 case X86ISD::PSHUFHW: 17904 case X86ISD::PSHUFLW: 17905 case X86ISD::MOVSS: 17906 case X86ISD::MOVSD: 17907 case X86ISD::VPERMILP: 17908 case X86ISD::VPERM2X128: 17909 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 17910 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget); 17911 } 17912 17913 return SDValue(); 17914 } 17915 17916 /// isTypeDesirableForOp - Return true if the target has native support for 17917 /// the specified value type and it is 'desirable' to use the type for the 17918 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16 17919 /// instruction encodings are longer and some i16 instructions are slow. 17920 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 17921 if (!isTypeLegal(VT)) 17922 return false; 17923 if (VT != MVT::i16) 17924 return true; 17925 17926 switch (Opc) { 17927 default: 17928 return true; 17929 case ISD::LOAD: 17930 case ISD::SIGN_EXTEND: 17931 case ISD::ZERO_EXTEND: 17932 case ISD::ANY_EXTEND: 17933 case ISD::SHL: 17934 case ISD::SRL: 17935 case ISD::SUB: 17936 case ISD::ADD: 17937 case ISD::MUL: 17938 case ISD::AND: 17939 case ISD::OR: 17940 case ISD::XOR: 17941 return false; 17942 } 17943 } 17944 17945 /// IsDesirableToPromoteOp - This method query the target whether it is 17946 /// beneficial for dag combiner to promote the specified node. If true, it 17947 /// should return the desired promotion type by reference. 17948 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 17949 EVT VT = Op.getValueType(); 17950 if (VT != MVT::i16) 17951 return false; 17952 17953 bool Promote = false; 17954 bool Commute = false; 17955 switch (Op.getOpcode()) { 17956 default: break; 17957 case ISD::LOAD: { 17958 LoadSDNode *LD = cast<LoadSDNode>(Op); 17959 // If the non-extending load has a single use and it's not live out, then it 17960 // might be folded. 17961 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 17962 Op.hasOneUse()*/) { 17963 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 17964 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 17965 // The only case where we'd want to promote LOAD (rather then it being 17966 // promoted as an operand is when it's only use is liveout. 17967 if (UI->getOpcode() != ISD::CopyToReg) 17968 return false; 17969 } 17970 } 17971 Promote = true; 17972 break; 17973 } 17974 case ISD::SIGN_EXTEND: 17975 case ISD::ZERO_EXTEND: 17976 case ISD::ANY_EXTEND: 17977 Promote = true; 17978 break; 17979 case ISD::SHL: 17980 case ISD::SRL: { 17981 SDValue N0 = Op.getOperand(0); 17982 // Look out for (store (shl (load), x)). 17983 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 17984 return false; 17985 Promote = true; 17986 break; 17987 } 17988 case ISD::ADD: 17989 case ISD::MUL: 17990 case ISD::AND: 17991 case ISD::OR: 17992 case ISD::XOR: 17993 Commute = true; 17994 // fallthrough 17995 case ISD::SUB: { 17996 SDValue N0 = Op.getOperand(0); 17997 SDValue N1 = Op.getOperand(1); 17998 if (!Commute && MayFoldLoad(N1)) 17999 return false; 18000 // Avoid disabling potential load folding opportunities. 18001 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 18002 return false; 18003 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 18004 return false; 18005 Promote = true; 18006 } 18007 } 18008 18009 PVT = MVT::i32; 18010 return Promote; 18011 } 18012 18013 //===----------------------------------------------------------------------===// 18014 // X86 Inline Assembly Support 18015 //===----------------------------------------------------------------------===// 18016 18017 namespace { 18018 // Helper to match a string separated by whitespace. 18019 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) { 18020 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace. 18021 18022 for (unsigned i = 0, e = args.size(); i != e; ++i) { 18023 StringRef piece(*args[i]); 18024 if (!s.startswith(piece)) // Check if the piece matches. 18025 return false; 18026 18027 s = s.substr(piece.size()); 18028 StringRef::size_type pos = s.find_first_not_of(" \t"); 18029 if (pos == 0) // We matched a prefix. 18030 return false; 18031 18032 s = s.substr(pos); 18033 } 18034 18035 return s.empty(); 18036 } 18037 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={}; 18038 } 18039 18040 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 18041 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 18042 18043 std::string AsmStr = IA->getAsmString(); 18044 18045 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 18046 if (!Ty || Ty->getBitWidth() % 16 != 0) 18047 return false; 18048 18049 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 18050 SmallVector<StringRef, 4> AsmPieces; 18051 SplitString(AsmStr, AsmPieces, ";\n"); 18052 18053 switch (AsmPieces.size()) { 18054 default: return false; 18055 case 1: 18056 // FIXME: this should verify that we are targeting a 486 or better. If not, 18057 // we will turn this bswap into something that will be lowered to logical 18058 // ops instead of emitting the bswap asm. For now, we don't support 486 or 18059 // lower so don't worry about this. 18060 // bswap $0 18061 if (matchAsm(AsmPieces[0], "bswap", "$0") || 18062 matchAsm(AsmPieces[0], "bswapl", "$0") || 18063 matchAsm(AsmPieces[0], "bswapq", "$0") || 18064 matchAsm(AsmPieces[0], "bswap", "${0:q}") || 18065 matchAsm(AsmPieces[0], "bswapl", "${0:q}") || 18066 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) { 18067 // No need to check constraints, nothing other than the equivalent of 18068 // "=r,0" would be valid here. 18069 return IntrinsicLowering::LowerToByteSwap(CI); 18070 } 18071 18072 // rorw $$8, ${0:w} --> llvm.bswap.i16 18073 if (CI->getType()->isIntegerTy(16) && 18074 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 18075 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") || 18076 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) { 18077 AsmPieces.clear(); 18078 const std::string &ConstraintsStr = IA->getConstraintString(); 18079 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 18080 array_pod_sort(AsmPieces.begin(), AsmPieces.end()); 18081 if (AsmPieces.size() == 4 && 18082 AsmPieces[0] == "~{cc}" && 18083 AsmPieces[1] == "~{dirflag}" && 18084 AsmPieces[2] == "~{flags}" && 18085 AsmPieces[3] == "~{fpsr}") 18086 return IntrinsicLowering::LowerToByteSwap(CI); 18087 } 18088 break; 18089 case 3: 18090 if (CI->getType()->isIntegerTy(32) && 18091 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 18092 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") && 18093 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") && 18094 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) { 18095 AsmPieces.clear(); 18096 const std::string &ConstraintsStr = IA->getConstraintString(); 18097 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 18098 array_pod_sort(AsmPieces.begin(), AsmPieces.end()); 18099 if (AsmPieces.size() == 4 && 18100 AsmPieces[0] == "~{cc}" && 18101 AsmPieces[1] == "~{dirflag}" && 18102 AsmPieces[2] == "~{flags}" && 18103 AsmPieces[3] == "~{fpsr}") 18104 return IntrinsicLowering::LowerToByteSwap(CI); 18105 } 18106 18107 if (CI->getType()->isIntegerTy(64)) { 18108 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 18109 if (Constraints.size() >= 2 && 18110 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 18111 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 18112 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 18113 if (matchAsm(AsmPieces[0], "bswap", "%eax") && 18114 matchAsm(AsmPieces[1], "bswap", "%edx") && 18115 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx")) 18116 return IntrinsicLowering::LowerToByteSwap(CI); 18117 } 18118 } 18119 break; 18120 } 18121 return false; 18122 } 18123 18124 /// getConstraintType - Given a constraint letter, return the type of 18125 /// constraint it is for this target. 18126 X86TargetLowering::ConstraintType 18127 X86TargetLowering::getConstraintType(const std::string &Constraint) const { 18128 if (Constraint.size() == 1) { 18129 switch (Constraint[0]) { 18130 case 'R': 18131 case 'q': 18132 case 'Q': 18133 case 'f': 18134 case 't': 18135 case 'u': 18136 case 'y': 18137 case 'x': 18138 case 'Y': 18139 case 'l': 18140 return C_RegisterClass; 18141 case 'a': 18142 case 'b': 18143 case 'c': 18144 case 'd': 18145 case 'S': 18146 case 'D': 18147 case 'A': 18148 return C_Register; 18149 case 'I': 18150 case 'J': 18151 case 'K': 18152 case 'L': 18153 case 'M': 18154 case 'N': 18155 case 'G': 18156 case 'C': 18157 case 'e': 18158 case 'Z': 18159 return C_Other; 18160 default: 18161 break; 18162 } 18163 } 18164 return TargetLowering::getConstraintType(Constraint); 18165 } 18166 18167 /// Examine constraint type and operand type and determine a weight value. 18168 /// This object must already have been set up with the operand type 18169 /// and the current alternative constraint selected. 18170 TargetLowering::ConstraintWeight 18171 X86TargetLowering::getSingleConstraintMatchWeight( 18172 AsmOperandInfo &info, const char *constraint) const { 18173 ConstraintWeight weight = CW_Invalid; 18174 Value *CallOperandVal = info.CallOperandVal; 18175 // If we don't have a value, we can't do a match, 18176 // but allow it at the lowest weight. 18177 if (CallOperandVal == NULL) 18178 return CW_Default; 18179 Type *type = CallOperandVal->getType(); 18180 // Look at the constraint type. 18181 switch (*constraint) { 18182 default: 18183 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 18184 case 'R': 18185 case 'q': 18186 case 'Q': 18187 case 'a': 18188 case 'b': 18189 case 'c': 18190 case 'd': 18191 case 'S': 18192 case 'D': 18193 case 'A': 18194 if (CallOperandVal->getType()->isIntegerTy()) 18195 weight = CW_SpecificReg; 18196 break; 18197 case 'f': 18198 case 't': 18199 case 'u': 18200 if (type->isFloatingPointTy()) 18201 weight = CW_SpecificReg; 18202 break; 18203 case 'y': 18204 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 18205 weight = CW_SpecificReg; 18206 break; 18207 case 'x': 18208 case 'Y': 18209 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) || 18210 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256())) 18211 weight = CW_Register; 18212 break; 18213 case 'I': 18214 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 18215 if (C->getZExtValue() <= 31) 18216 weight = CW_Constant; 18217 } 18218 break; 18219 case 'J': 18220 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18221 if (C->getZExtValue() <= 63) 18222 weight = CW_Constant; 18223 } 18224 break; 18225 case 'K': 18226 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18227 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 18228 weight = CW_Constant; 18229 } 18230 break; 18231 case 'L': 18232 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18233 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 18234 weight = CW_Constant; 18235 } 18236 break; 18237 case 'M': 18238 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18239 if (C->getZExtValue() <= 3) 18240 weight = CW_Constant; 18241 } 18242 break; 18243 case 'N': 18244 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18245 if (C->getZExtValue() <= 0xff) 18246 weight = CW_Constant; 18247 } 18248 break; 18249 case 'G': 18250 case 'C': 18251 if (dyn_cast<ConstantFP>(CallOperandVal)) { 18252 weight = CW_Constant; 18253 } 18254 break; 18255 case 'e': 18256 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18257 if ((C->getSExtValue() >= -0x80000000LL) && 18258 (C->getSExtValue() <= 0x7fffffffLL)) 18259 weight = CW_Constant; 18260 } 18261 break; 18262 case 'Z': 18263 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 18264 if (C->getZExtValue() <= 0xffffffff) 18265 weight = CW_Constant; 18266 } 18267 break; 18268 } 18269 return weight; 18270 } 18271 18272 /// LowerXConstraint - try to replace an X constraint, which matches anything, 18273 /// with another that has more specific requirements based on the type of the 18274 /// corresponding operand. 18275 const char *X86TargetLowering:: 18276 LowerXConstraint(EVT ConstraintVT) const { 18277 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 18278 // 'f' like normal targets. 18279 if (ConstraintVT.isFloatingPoint()) { 18280 if (Subtarget->hasSSE2()) 18281 return "Y"; 18282 if (Subtarget->hasSSE1()) 18283 return "x"; 18284 } 18285 18286 return TargetLowering::LowerXConstraint(ConstraintVT); 18287 } 18288 18289 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 18290 /// vector. If it is invalid, don't add anything to Ops. 18291 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 18292 std::string &Constraint, 18293 std::vector<SDValue>&Ops, 18294 SelectionDAG &DAG) const { 18295 SDValue Result(0, 0); 18296 18297 // Only support length 1 constraints for now. 18298 if (Constraint.length() > 1) return; 18299 18300 char ConstraintLetter = Constraint[0]; 18301 switch (ConstraintLetter) { 18302 default: break; 18303 case 'I': 18304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18305 if (C->getZExtValue() <= 31) { 18306 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18307 break; 18308 } 18309 } 18310 return; 18311 case 'J': 18312 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18313 if (C->getZExtValue() <= 63) { 18314 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18315 break; 18316 } 18317 } 18318 return; 18319 case 'K': 18320 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18321 if (isInt<8>(C->getSExtValue())) { 18322 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18323 break; 18324 } 18325 } 18326 return; 18327 case 'N': 18328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18329 if (C->getZExtValue() <= 255) { 18330 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18331 break; 18332 } 18333 } 18334 return; 18335 case 'e': { 18336 // 32-bit signed value 18337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18338 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 18339 C->getSExtValue())) { 18340 // Widen to 64 bits here to get it sign extended. 18341 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 18342 break; 18343 } 18344 // FIXME gcc accepts some relocatable values here too, but only in certain 18345 // memory models; it's complicated. 18346 } 18347 return; 18348 } 18349 case 'Z': { 18350 // 32-bit unsigned value 18351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 18352 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 18353 C->getZExtValue())) { 18354 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 18355 break; 18356 } 18357 } 18358 // FIXME gcc accepts some relocatable values here too, but only in certain 18359 // memory models; it's complicated. 18360 return; 18361 } 18362 case 'i': { 18363 // Literal immediates are always ok. 18364 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 18365 // Widen to 64 bits here to get it sign extended. 18366 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 18367 break; 18368 } 18369 18370 // In any sort of PIC mode addresses need to be computed at runtime by 18371 // adding in a register or some sort of table lookup. These can't 18372 // be used as immediates. 18373 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 18374 return; 18375 18376 // If we are in non-pic codegen mode, we allow the address of a global (with 18377 // an optional displacement) to be used with 'i'. 18378 GlobalAddressSDNode *GA = 0; 18379 int64_t Offset = 0; 18380 18381 // Match either (GA), (GA+C), (GA+C1+C2), etc. 18382 while (1) { 18383 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 18384 Offset += GA->getOffset(); 18385 break; 18386 } else if (Op.getOpcode() == ISD::ADD) { 18387 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 18388 Offset += C->getZExtValue(); 18389 Op = Op.getOperand(0); 18390 continue; 18391 } 18392 } else if (Op.getOpcode() == ISD::SUB) { 18393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 18394 Offset += -C->getZExtValue(); 18395 Op = Op.getOperand(0); 18396 continue; 18397 } 18398 } 18399 18400 // Otherwise, this isn't something we can handle, reject it. 18401 return; 18402 } 18403 18404 const GlobalValue *GV = GA->getGlobal(); 18405 // If we require an extra load to get this address, as in PIC mode, we 18406 // can't accept it. 18407 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 18408 getTargetMachine()))) 18409 return; 18410 18411 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), 18412 GA->getValueType(0), Offset); 18413 break; 18414 } 18415 } 18416 18417 if (Result.getNode()) { 18418 Ops.push_back(Result); 18419 return; 18420 } 18421 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 18422 } 18423 18424 std::pair<unsigned, const TargetRegisterClass*> 18425 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 18426 EVT VT) const { 18427 // First, see if this is a constraint that directly corresponds to an LLVM 18428 // register class. 18429 if (Constraint.size() == 1) { 18430 // GCC Constraint Letters 18431 switch (Constraint[0]) { 18432 default: break; 18433 // TODO: Slight differences here in allocation order and leaving 18434 // RIP in the class. Do they matter any more here than they do 18435 // in the normal allocation? 18436 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 18437 if (Subtarget->is64Bit()) { 18438 if (VT == MVT::i32 || VT == MVT::f32) 18439 return std::make_pair(0U, &X86::GR32RegClass); 18440 if (VT == MVT::i16) 18441 return std::make_pair(0U, &X86::GR16RegClass); 18442 if (VT == MVT::i8 || VT == MVT::i1) 18443 return std::make_pair(0U, &X86::GR8RegClass); 18444 if (VT == MVT::i64 || VT == MVT::f64) 18445 return std::make_pair(0U, &X86::GR64RegClass); 18446 break; 18447 } 18448 // 32-bit fallthrough 18449 case 'Q': // Q_REGS 18450 if (VT == MVT::i32 || VT == MVT::f32) 18451 return std::make_pair(0U, &X86::GR32_ABCDRegClass); 18452 if (VT == MVT::i16) 18453 return std::make_pair(0U, &X86::GR16_ABCDRegClass); 18454 if (VT == MVT::i8 || VT == MVT::i1) 18455 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass); 18456 if (VT == MVT::i64) 18457 return std::make_pair(0U, &X86::GR64_ABCDRegClass); 18458 break; 18459 case 'r': // GENERAL_REGS 18460 case 'l': // INDEX_REGS 18461 if (VT == MVT::i8 || VT == MVT::i1) 18462 return std::make_pair(0U, &X86::GR8RegClass); 18463 if (VT == MVT::i16) 18464 return std::make_pair(0U, &X86::GR16RegClass); 18465 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 18466 return std::make_pair(0U, &X86::GR32RegClass); 18467 return std::make_pair(0U, &X86::GR64RegClass); 18468 case 'R': // LEGACY_REGS 18469 if (VT == MVT::i8 || VT == MVT::i1) 18470 return std::make_pair(0U, &X86::GR8_NOREXRegClass); 18471 if (VT == MVT::i16) 18472 return std::make_pair(0U, &X86::GR16_NOREXRegClass); 18473 if (VT == MVT::i32 || !Subtarget->is64Bit()) 18474 return std::make_pair(0U, &X86::GR32_NOREXRegClass); 18475 return std::make_pair(0U, &X86::GR64_NOREXRegClass); 18476 case 'f': // FP Stack registers. 18477 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 18478 // value to the correct fpstack register class. 18479 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 18480 return std::make_pair(0U, &X86::RFP32RegClass); 18481 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 18482 return std::make_pair(0U, &X86::RFP64RegClass); 18483 return std::make_pair(0U, &X86::RFP80RegClass); 18484 case 'y': // MMX_REGS if MMX allowed. 18485 if (!Subtarget->hasMMX()) break; 18486 return std::make_pair(0U, &X86::VR64RegClass); 18487 case 'Y': // SSE_REGS if SSE2 allowed 18488 if (!Subtarget->hasSSE2()) break; 18489 // FALL THROUGH. 18490 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed 18491 if (!Subtarget->hasSSE1()) break; 18492 18493 switch (VT.getSimpleVT().SimpleTy) { 18494 default: break; 18495 // Scalar SSE types. 18496 case MVT::f32: 18497 case MVT::i32: 18498 return std::make_pair(0U, &X86::FR32RegClass); 18499 case MVT::f64: 18500 case MVT::i64: 18501 return std::make_pair(0U, &X86::FR64RegClass); 18502 // Vector types. 18503 case MVT::v16i8: 18504 case MVT::v8i16: 18505 case MVT::v4i32: 18506 case MVT::v2i64: 18507 case MVT::v4f32: 18508 case MVT::v2f64: 18509 return std::make_pair(0U, &X86::VR128RegClass); 18510 // AVX types. 18511 case MVT::v32i8: 18512 case MVT::v16i16: 18513 case MVT::v8i32: 18514 case MVT::v4i64: 18515 case MVT::v8f32: 18516 case MVT::v4f64: 18517 return std::make_pair(0U, &X86::VR256RegClass); 18518 } 18519 break; 18520 } 18521 } 18522 18523 // Use the default implementation in TargetLowering to convert the register 18524 // constraint into a member of a register class. 18525 std::pair<unsigned, const TargetRegisterClass*> Res; 18526 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 18527 18528 // Not found as a standard register? 18529 if (Res.second == 0) { 18530 // Map st(0) -> st(7) -> ST0 18531 if (Constraint.size() == 7 && Constraint[0] == '{' && 18532 tolower(Constraint[1]) == 's' && 18533 tolower(Constraint[2]) == 't' && 18534 Constraint[3] == '(' && 18535 (Constraint[4] >= '0' && Constraint[4] <= '7') && 18536 Constraint[5] == ')' && 18537 Constraint[6] == '}') { 18538 18539 Res.first = X86::ST0+Constraint[4]-'0'; 18540 Res.second = &X86::RFP80RegClass; 18541 return Res; 18542 } 18543 18544 // GCC allows "st(0)" to be called just plain "st". 18545 if (StringRef("{st}").equals_lower(Constraint)) { 18546 Res.first = X86::ST0; 18547 Res.second = &X86::RFP80RegClass; 18548 return Res; 18549 } 18550 18551 // flags -> EFLAGS 18552 if (StringRef("{flags}").equals_lower(Constraint)) { 18553 Res.first = X86::EFLAGS; 18554 Res.second = &X86::CCRRegClass; 18555 return Res; 18556 } 18557 18558 // 'A' means EAX + EDX. 18559 if (Constraint == "A") { 18560 Res.first = X86::EAX; 18561 Res.second = &X86::GR32_ADRegClass; 18562 return Res; 18563 } 18564 return Res; 18565 } 18566 18567 // Otherwise, check to see if this is a register class of the wrong value 18568 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 18569 // turn into {ax},{dx}. 18570 if (Res.second->hasType(VT)) 18571 return Res; // Correct type already, nothing to do. 18572 18573 // All of the single-register GCC register classes map their values onto 18574 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 18575 // really want an 8-bit or 32-bit register, map to the appropriate register 18576 // class and return the appropriate register. 18577 if (Res.second == &X86::GR16RegClass) { 18578 if (VT == MVT::i8 || VT == MVT::i1) { 18579 unsigned DestReg = 0; 18580 switch (Res.first) { 18581 default: break; 18582 case X86::AX: DestReg = X86::AL; break; 18583 case X86::DX: DestReg = X86::DL; break; 18584 case X86::CX: DestReg = X86::CL; break; 18585 case X86::BX: DestReg = X86::BL; break; 18586 } 18587 if (DestReg) { 18588 Res.first = DestReg; 18589 Res.second = &X86::GR8RegClass; 18590 } 18591 } else if (VT == MVT::i32 || VT == MVT::f32) { 18592 unsigned DestReg = 0; 18593 switch (Res.first) { 18594 default: break; 18595 case X86::AX: DestReg = X86::EAX; break; 18596 case X86::DX: DestReg = X86::EDX; break; 18597 case X86::CX: DestReg = X86::ECX; break; 18598 case X86::BX: DestReg = X86::EBX; break; 18599 case X86::SI: DestReg = X86::ESI; break; 18600 case X86::DI: DestReg = X86::EDI; break; 18601 case X86::BP: DestReg = X86::EBP; break; 18602 case X86::SP: DestReg = X86::ESP; break; 18603 } 18604 if (DestReg) { 18605 Res.first = DestReg; 18606 Res.second = &X86::GR32RegClass; 18607 } 18608 } else if (VT == MVT::i64 || VT == MVT::f64) { 18609 unsigned DestReg = 0; 18610 switch (Res.first) { 18611 default: break; 18612 case X86::AX: DestReg = X86::RAX; break; 18613 case X86::DX: DestReg = X86::RDX; break; 18614 case X86::CX: DestReg = X86::RCX; break; 18615 case X86::BX: DestReg = X86::RBX; break; 18616 case X86::SI: DestReg = X86::RSI; break; 18617 case X86::DI: DestReg = X86::RDI; break; 18618 case X86::BP: DestReg = X86::RBP; break; 18619 case X86::SP: DestReg = X86::RSP; break; 18620 } 18621 if (DestReg) { 18622 Res.first = DestReg; 18623 Res.second = &X86::GR64RegClass; 18624 } 18625 } 18626 } else if (Res.second == &X86::FR32RegClass || 18627 Res.second == &X86::FR64RegClass || 18628 Res.second == &X86::VR128RegClass) { 18629 // Handle references to XMM physical registers that got mapped into the 18630 // wrong class. This can happen with constraints like {xmm0} where the 18631 // target independent register mapper will just pick the first match it can 18632 // find, ignoring the required type. 18633 18634 if (VT == MVT::f32 || VT == MVT::i32) 18635 Res.second = &X86::FR32RegClass; 18636 else if (VT == MVT::f64 || VT == MVT::i64) 18637 Res.second = &X86::FR64RegClass; 18638 else if (X86::VR128RegClass.hasType(VT)) 18639 Res.second = &X86::VR128RegClass; 18640 else if (X86::VR256RegClass.hasType(VT)) 18641 Res.second = &X86::VR256RegClass; 18642 } 18643 18644 return Res; 18645 } 18646