X86ISelLowering.cpp revision e0ef509aeb47b396cf1bdc170ca4f468f799719f
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 "X86.h" 17#include "X86InstrBuilder.h" 18#include "X86ISelLowering.h" 19#include "X86TargetMachine.h" 20#include "X86TargetObjectFile.h" 21#include "Utils/X86ShuffleDecode.h" 22#include "llvm/CallingConv.h" 23#include "llvm/Constants.h" 24#include "llvm/DerivedTypes.h" 25#include "llvm/GlobalAlias.h" 26#include "llvm/GlobalVariable.h" 27#include "llvm/Function.h" 28#include "llvm/Instructions.h" 29#include "llvm/Intrinsics.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/CodeGen/IntrinsicLowering.h" 32#include "llvm/CodeGen/MachineFrameInfo.h" 33#include "llvm/CodeGen/MachineFunction.h" 34#include "llvm/CodeGen/MachineInstrBuilder.h" 35#include "llvm/CodeGen/MachineJumpTableInfo.h" 36#include "llvm/CodeGen/MachineModuleInfo.h" 37#include "llvm/CodeGen/MachineRegisterInfo.h" 38#include "llvm/CodeGen/PseudoSourceValue.h" 39#include "llvm/MC/MCAsmInfo.h" 40#include "llvm/MC/MCContext.h" 41#include "llvm/MC/MCExpr.h" 42#include "llvm/MC/MCSymbol.h" 43#include "llvm/ADT/BitVector.h" 44#include "llvm/ADT/SmallSet.h" 45#include "llvm/ADT/Statistic.h" 46#include "llvm/ADT/StringExtras.h" 47#include "llvm/ADT/VectorExtras.h" 48#include "llvm/Support/Debug.h" 49#include "llvm/Support/Dwarf.h" 50#include "llvm/Support/ErrorHandling.h" 51#include "llvm/Support/MathExtras.h" 52#include "llvm/Support/raw_ostream.h" 53using namespace llvm; 54using namespace dwarf; 55 56STATISTIC(NumTailCalls, "Number of tail calls"); 57 58// Forward declarations. 59static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 60 SDValue V2); 61 62static SDValue Insert128BitVector(SDValue Result, 63 SDValue Vec, 64 SDValue Idx, 65 SelectionDAG &DAG, 66 DebugLoc dl); 67 68static SDValue Extract128BitVector(SDValue Vec, 69 SDValue Idx, 70 SelectionDAG &DAG, 71 DebugLoc dl); 72 73static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG); 74 75 76/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 77/// sets things up to match to an AVX VEXTRACTF128 instruction or a 78/// simple subregister reference. Idx is an index in the 128 bits we 79/// want. It need not be aligned to a 128-bit bounday. That makes 80/// lowering EXTRACT_VECTOR_ELT operations easier. 81static SDValue Extract128BitVector(SDValue Vec, 82 SDValue Idx, 83 SelectionDAG &DAG, 84 DebugLoc dl) { 85 EVT VT = Vec.getValueType(); 86 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 87 88 EVT ElVT = VT.getVectorElementType(); 89 90 int Factor = VT.getSizeInBits() / 128; 91 92 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), 93 ElVT, 94 VT.getVectorNumElements() / Factor); 95 96 // Extract from UNDEF is UNDEF. 97 if (Vec.getOpcode() == ISD::UNDEF) 98 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 99 100 if (isa<ConstantSDNode>(Idx)) { 101 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 102 103 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 104 // we can match to VEXTRACTF128. 105 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 106 107 // This is the index of the first element of the 128-bit chunk 108 // we want. 109 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 110 * ElemsPerChunk); 111 112 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 113 114 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 115 VecIdx); 116 117 return Result; 118 } 119 120 return SDValue(); 121} 122 123/// Generate a DAG to put 128-bits into a vector > 128 bits. This 124/// sets things up to match to an AVX VINSERTF128 instruction or a 125/// simple superregister reference. Idx is an index in the 128 bits 126/// we want. It need not be aligned to a 128-bit bounday. That makes 127/// lowering INSERT_VECTOR_ELT operations easier. 128static SDValue Insert128BitVector(SDValue Result, 129 SDValue Vec, 130 SDValue Idx, 131 SelectionDAG &DAG, 132 DebugLoc dl) { 133 if (isa<ConstantSDNode>(Idx)) { 134 EVT VT = Vec.getValueType(); 135 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 136 137 EVT ElVT = VT.getVectorElementType(); 138 139 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 140 141 EVT ResultVT = Result.getValueType(); 142 143 // Insert the relevant 128 bits. 144 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 145 146 // This is the index of the first element of the 128-bit chunk 147 // we want. 148 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 149 * ElemsPerChunk); 150 151 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 152 153 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 154 VecIdx); 155 return Result; 156 } 157 158 return SDValue(); 159} 160 161/// Given two vectors, concat them. 162static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) { 163 DebugLoc dl = Lower.getDebugLoc(); 164 165 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!"); 166 167 EVT VT = EVT::getVectorVT(*DAG.getContext(), 168 Lower.getValueType().getVectorElementType(), 169 Lower.getValueType().getVectorNumElements() * 2); 170 171 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors). 172 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!"); 173 174 // Insert the upper subvector. 175 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper, 176 DAG.getConstant( 177 // This is half the length of the result 178 // vector. Start inserting the upper 128 179 // bits here. 180 Lower.getValueType().getVectorNumElements(), 181 MVT::i32), 182 DAG, dl); 183 184 // Insert the lower subvector. 185 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl); 186 return Vec; 187} 188 189static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 190 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 191 bool is64Bit = Subtarget->is64Bit(); 192 193 if (Subtarget->isTargetEnvMacho()) { 194 if (is64Bit) 195 return new X8664_MachoTargetObjectFile(); 196 return new TargetLoweringObjectFileMachO(); 197 } 198 199 if (Subtarget->isTargetELF()) { 200 if (is64Bit) 201 return new X8664_ELFTargetObjectFile(TM); 202 return new X8632_ELFTargetObjectFile(TM); 203 } 204 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 205 return new TargetLoweringObjectFileCOFF(); 206 llvm_unreachable("unknown subtarget type"); 207} 208 209X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 210 : TargetLowering(TM, createTLOF(TM)) { 211 Subtarget = &TM.getSubtarget<X86Subtarget>(); 212 X86ScalarSSEf64 = Subtarget->hasXMMInt(); 213 X86ScalarSSEf32 = Subtarget->hasXMM(); 214 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 215 216 RegInfo = TM.getRegisterInfo(); 217 TD = getTargetData(); 218 219 // Set up the TargetLowering object. 220 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 221 222 // X86 is weird, it always uses i8 for shift amounts and setcc results. 223 setBooleanContents(ZeroOrOneBooleanContent); 224 setSchedulingPreference(Sched::RegPressure); 225 setStackPointerRegisterToSaveRestore(X86StackPtr); 226 227 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 228 // Setup Windows compiler runtime calls. 229 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 231 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 232 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 233 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 234 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 235 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 236 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 237 } 238 239 if (Subtarget->isTargetDarwin()) { 240 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 241 setUseUnderscoreSetJmp(false); 242 setUseUnderscoreLongJmp(false); 243 } else if (Subtarget->isTargetMingw()) { 244 // MS runtime is weird: it exports _setjmp, but longjmp! 245 setUseUnderscoreSetJmp(true); 246 setUseUnderscoreLongJmp(false); 247 } else { 248 setUseUnderscoreSetJmp(true); 249 setUseUnderscoreLongJmp(true); 250 } 251 252 // Set up the register classes. 253 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 254 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 255 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 256 if (Subtarget->is64Bit()) 257 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 258 259 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 260 261 // We don't accept any truncstore of integer registers. 262 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 263 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 264 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 265 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 266 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 267 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 268 269 // SETOEQ and SETUNE require checking two conditions. 270 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 271 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 272 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 273 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 274 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 275 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 276 277 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 278 // operation. 279 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 280 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 281 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 282 283 if (Subtarget->is64Bit()) { 284 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 285 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 286 } else if (!UseSoftFloat) { 287 // We have an algorithm for SSE2->double, and we turn this into a 288 // 64-bit FILD followed by conditional FADD for other targets. 289 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 290 // We have an algorithm for SSE2, and we turn this into a 64-bit 291 // FILD for other targets. 292 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 293 } 294 295 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 296 // this operation. 297 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 298 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 299 300 if (!UseSoftFloat) { 301 // SSE has no i16 to fp conversion, only i32 302 if (X86ScalarSSEf32) { 303 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 304 // f32 and f64 cases are Legal, f80 case is not 305 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 306 } else { 307 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 308 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 309 } 310 } else { 311 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 313 } 314 315 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 316 // are Legal, f80 is custom lowered. 317 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 318 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 319 320 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 321 // this operation. 322 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 323 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 324 325 if (X86ScalarSSEf32) { 326 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 327 // f32 and f64 cases are Legal, f80 case is not 328 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 329 } else { 330 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 331 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 332 } 333 334 // Handle FP_TO_UINT by promoting the destination to a larger signed 335 // conversion. 336 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 337 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 338 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 339 340 if (Subtarget->is64Bit()) { 341 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 342 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 343 } else if (!UseSoftFloat) { 344 if (X86ScalarSSEf32 && !Subtarget->hasSSE3()) 345 // Expand FP_TO_UINT into a select. 346 // FIXME: We would like to use a Custom expander here eventually to do 347 // the optimal thing for SSE vs. the default expansion in the legalizer. 348 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 349 else 350 // With SSE3 we can use fisttpll to convert to a signed i64; without 351 // SSE, we're stuck with a fistpll. 352 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 353 } 354 355 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 356 if (!X86ScalarSSEf64) { 357 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 358 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 359 if (Subtarget->is64Bit()) { 360 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 361 // Without SSE, i64->f64 goes through memory. 362 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 363 } 364 } 365 366 // Scalar integer divide and remainder are lowered to use operations that 367 // produce two results, to match the available instructions. This exposes 368 // the two-result form to trivial CSE, which is able to combine x/y and x%y 369 // into a single instruction. 370 // 371 // Scalar integer multiply-high is also lowered to use two-result 372 // operations, to match the available instructions. However, plain multiply 373 // (low) operations are left as Legal, as there are single-result 374 // instructions for this in x86. Using the two-result multiply instructions 375 // when both high and low results are needed must be arranged by dagcombine. 376 for (unsigned i = 0, e = 4; i != e; ++i) { 377 MVT VT = IntVTs[i]; 378 setOperationAction(ISD::MULHS, VT, Expand); 379 setOperationAction(ISD::MULHU, VT, Expand); 380 setOperationAction(ISD::SDIV, VT, Expand); 381 setOperationAction(ISD::UDIV, VT, Expand); 382 setOperationAction(ISD::SREM, VT, Expand); 383 setOperationAction(ISD::UREM, VT, Expand); 384 385 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 386 setOperationAction(ISD::ADDC, VT, Custom); 387 setOperationAction(ISD::ADDE, VT, Custom); 388 setOperationAction(ISD::SUBC, VT, Custom); 389 setOperationAction(ISD::SUBE, VT, Custom); 390 } 391 392 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 393 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 394 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 395 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 396 if (Subtarget->is64Bit()) 397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 398 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 399 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 401 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 402 setOperationAction(ISD::FREM , MVT::f32 , Expand); 403 setOperationAction(ISD::FREM , MVT::f64 , Expand); 404 setOperationAction(ISD::FREM , MVT::f80 , Expand); 405 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 406 407 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 408 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 409 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 410 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 411 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 412 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 413 if (Subtarget->is64Bit()) { 414 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 415 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 416 } 417 418 if (Subtarget->hasPOPCNT()) { 419 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 420 } else { 421 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 422 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 423 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 424 if (Subtarget->is64Bit()) 425 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 426 } 427 428 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 429 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 430 431 // These should be promoted to a larger select which is supported. 432 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 433 // X86 wants to expand cmov itself. 434 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 435 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 436 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 437 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 438 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 439 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 440 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 441 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 442 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 443 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 444 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 445 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 446 if (Subtarget->is64Bit()) { 447 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 448 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 449 } 450 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 451 452 // Darwin ABI issue. 453 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 454 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 455 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 456 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 457 if (Subtarget->is64Bit()) 458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 459 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 460 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 461 if (Subtarget->is64Bit()) { 462 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 463 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 464 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 465 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 466 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 467 } 468 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 469 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 470 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 471 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 472 if (Subtarget->is64Bit()) { 473 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 474 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 475 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 476 } 477 478 if (Subtarget->hasXMM()) 479 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 480 481 // We may not have a libcall for MEMBARRIER so we should lower this. 482 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 483 484 // On X86 and X86-64, atomic operations are lowered to locked instructions. 485 // Locked instructions, in turn, have implicit fence semantics (all memory 486 // operations are flushed before issuing the locked instruction, and they 487 // are not buffered), so we can fold away the common pattern of 488 // fence-atomic-fence. 489 setShouldFoldAtomicFences(true); 490 491 // Expand certain atomics 492 for (unsigned i = 0, e = 4; i != e; ++i) { 493 MVT VT = IntVTs[i]; 494 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 495 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 496 } 497 498 if (!Subtarget->is64Bit()) { 499 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 500 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 501 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 502 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 503 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 504 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 505 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 506 } 507 508 // FIXME - use subtarget debug flags 509 if (!Subtarget->isTargetDarwin() && 510 !Subtarget->isTargetELF() && 511 !Subtarget->isTargetCygMing()) { 512 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 513 } 514 515 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 516 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 517 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 518 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 519 if (Subtarget->is64Bit()) { 520 setExceptionPointerRegister(X86::RAX); 521 setExceptionSelectorRegister(X86::RDX); 522 } else { 523 setExceptionPointerRegister(X86::EAX); 524 setExceptionSelectorRegister(X86::EDX); 525 } 526 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 527 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 528 529 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom); 530 531 setOperationAction(ISD::TRAP, MVT::Other, Legal); 532 533 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 534 setOperationAction(ISD::VASTART , MVT::Other, Custom); 535 setOperationAction(ISD::VAEND , MVT::Other, Expand); 536 if (Subtarget->is64Bit()) { 537 setOperationAction(ISD::VAARG , MVT::Other, Custom); 538 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 539 } else { 540 setOperationAction(ISD::VAARG , MVT::Other, Expand); 541 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 542 } 543 544 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 545 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 546 if (Subtarget->is64Bit()) 547 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 548 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) 549 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 550 else 551 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand); 552 553 if (!UseSoftFloat && X86ScalarSSEf64) { 554 // f32 and f64 use SSE. 555 // Set up the FP register classes. 556 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 557 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 558 559 // Use ANDPD to simulate FABS. 560 setOperationAction(ISD::FABS , MVT::f64, Custom); 561 setOperationAction(ISD::FABS , MVT::f32, Custom); 562 563 // Use XORP to simulate FNEG. 564 setOperationAction(ISD::FNEG , MVT::f64, Custom); 565 setOperationAction(ISD::FNEG , MVT::f32, Custom); 566 567 // Use ANDPD and ORPD to simulate FCOPYSIGN. 568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 570 571 // We don't support sin/cos/fmod 572 setOperationAction(ISD::FSIN , MVT::f64, Expand); 573 setOperationAction(ISD::FCOS , MVT::f64, Expand); 574 setOperationAction(ISD::FSIN , MVT::f32, Expand); 575 setOperationAction(ISD::FCOS , MVT::f32, Expand); 576 577 // Expand FP immediates into loads from the stack, except for the special 578 // cases we handle. 579 addLegalFPImmediate(APFloat(+0.0)); // xorpd 580 addLegalFPImmediate(APFloat(+0.0f)); // xorps 581 } else if (!UseSoftFloat && X86ScalarSSEf32) { 582 // Use SSE for f32, x87 for f64. 583 // Set up the FP register classes. 584 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 585 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 586 587 // Use ANDPS to simulate FABS. 588 setOperationAction(ISD::FABS , MVT::f32, Custom); 589 590 // Use XORP to simulate FNEG. 591 setOperationAction(ISD::FNEG , MVT::f32, Custom); 592 593 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 594 595 // Use ANDPS and ORPS to simulate FCOPYSIGN. 596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 598 599 // We don't support sin/cos/fmod 600 setOperationAction(ISD::FSIN , MVT::f32, Expand); 601 setOperationAction(ISD::FCOS , MVT::f32, Expand); 602 603 // Special cases we handle for FP constants. 604 addLegalFPImmediate(APFloat(+0.0f)); // xorps 605 addLegalFPImmediate(APFloat(+0.0)); // FLD0 606 addLegalFPImmediate(APFloat(+1.0)); // FLD1 607 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 608 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 609 610 if (!UnsafeFPMath) { 611 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 612 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 613 } 614 } else if (!UseSoftFloat) { 615 // f32 and f64 in x87. 616 // Set up the FP register classes. 617 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 618 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 619 620 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 621 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 622 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 623 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 624 625 if (!UnsafeFPMath) { 626 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 627 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 628 } 629 addLegalFPImmediate(APFloat(+0.0)); // FLD0 630 addLegalFPImmediate(APFloat(+1.0)); // FLD1 631 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 632 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 633 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 634 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 635 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 636 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 637 } 638 639 // Long double always uses X87. 640 if (!UseSoftFloat) { 641 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 642 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 643 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 644 { 645 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 646 addLegalFPImmediate(TmpFlt); // FLD0 647 TmpFlt.changeSign(); 648 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 649 650 bool ignored; 651 APFloat TmpFlt2(+1.0); 652 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 653 &ignored); 654 addLegalFPImmediate(TmpFlt2); // FLD1 655 TmpFlt2.changeSign(); 656 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 657 } 658 659 if (!UnsafeFPMath) { 660 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 661 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 662 } 663 } 664 665 // Always use a library call for pow. 666 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 667 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 668 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 669 670 setOperationAction(ISD::FLOG, MVT::f80, Expand); 671 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 672 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 673 setOperationAction(ISD::FEXP, MVT::f80, Expand); 674 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 675 676 // First set operation action for all vector types to either promote 677 // (for widening) or expand (for scalarization). Then we will selectively 678 // turn on ones that can be effectively codegen'd. 679 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 680 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 681 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 682 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 683 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 684 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 685 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 686 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 687 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 688 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 689 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 690 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 691 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 693 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 694 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 696 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 698 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 699 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 700 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 702 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 703 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 706 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 708 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 709 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 730 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 731 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 735 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 736 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 737 setTruncStoreAction((MVT::SimpleValueType)VT, 738 (MVT::SimpleValueType)InnerVT, Expand); 739 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 740 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 741 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 742 } 743 744 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 745 // with -msoft-float, disable use of MMX as well. 746 if (!UseSoftFloat && Subtarget->hasMMX()) { 747 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 748 // No operations on x86mmx supported, everything uses intrinsics. 749 } 750 751 // MMX-sized vectors (other than x86mmx) are expected to be expanded 752 // into smaller operations. 753 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 754 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 755 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 756 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 757 setOperationAction(ISD::AND, MVT::v8i8, Expand); 758 setOperationAction(ISD::AND, MVT::v4i16, Expand); 759 setOperationAction(ISD::AND, MVT::v2i32, Expand); 760 setOperationAction(ISD::AND, MVT::v1i64, Expand); 761 setOperationAction(ISD::OR, MVT::v8i8, Expand); 762 setOperationAction(ISD::OR, MVT::v4i16, Expand); 763 setOperationAction(ISD::OR, MVT::v2i32, Expand); 764 setOperationAction(ISD::OR, MVT::v1i64, Expand); 765 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 766 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 767 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 768 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 769 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 770 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 771 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 772 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 774 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 775 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 776 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 777 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 778 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 779 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 780 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 781 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 782 783 if (!UseSoftFloat && Subtarget->hasXMM()) { 784 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 785 786 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 787 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 788 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 789 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 790 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 791 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 792 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 793 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 794 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 796 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 797 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom); 798 } 799 800 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 801 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 802 803 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 804 // registers cannot be used even for integer operations. 805 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 806 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 807 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 808 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 809 810 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 811 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 812 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 813 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 814 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 815 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 816 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 817 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 818 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 819 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 820 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 826 827 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom); 828 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom); 829 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom); 830 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom); 831 832 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 833 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 837 838 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 839 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 840 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 841 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 842 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 843 844 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 845 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 846 EVT VT = (MVT::SimpleValueType)i; 847 // Do not attempt to custom lower non-power-of-2 vectors 848 if (!isPowerOf2_32(VT.getVectorNumElements())) 849 continue; 850 // Do not attempt to custom lower non-128-bit vectors 851 if (!VT.is128BitVector()) 852 continue; 853 setOperationAction(ISD::BUILD_VECTOR, 854 VT.getSimpleVT().SimpleTy, Custom); 855 setOperationAction(ISD::VECTOR_SHUFFLE, 856 VT.getSimpleVT().SimpleTy, Custom); 857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 858 VT.getSimpleVT().SimpleTy, Custom); 859 } 860 861 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 862 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 864 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 866 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 867 868 if (Subtarget->is64Bit()) { 869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 870 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 871 } 872 873 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 874 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 875 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 876 EVT VT = SVT; 877 878 // Do not attempt to promote non-128-bit vectors 879 if (!VT.is128BitVector()) 880 continue; 881 882 setOperationAction(ISD::AND, SVT, Promote); 883 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 884 setOperationAction(ISD::OR, SVT, Promote); 885 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 886 setOperationAction(ISD::XOR, SVT, Promote); 887 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 888 setOperationAction(ISD::LOAD, SVT, Promote); 889 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 890 setOperationAction(ISD::SELECT, SVT, Promote); 891 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 892 } 893 894 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 895 896 // Custom lower v2i64 and v2f64 selects. 897 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 898 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 899 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 900 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 901 902 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 903 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 904 } 905 906 if (Subtarget->hasSSE41()) { 907 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 908 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 910 setOperationAction(ISD::FRINT, MVT::f32, Legal); 911 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 912 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 913 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 914 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 915 setOperationAction(ISD::FRINT, MVT::f64, Legal); 916 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 917 918 // FIXME: Do we need to handle scalar-to-vector here? 919 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 920 921 // Can turn SHL into an integer multiply. 922 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 923 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 924 925 // i8 and i16 vectors are custom , because the source register and source 926 // source memory operand types are not the same width. f32 vectors are 927 // custom since the immediate controlling the insert encodes additional 928 // information. 929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 933 934 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 938 939 if (Subtarget->is64Bit()) { 940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 942 } 943 } 944 945 if (Subtarget->hasSSE42()) 946 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom); 947 948 if (!UseSoftFloat && Subtarget->hasAVX()) { 949 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 950 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 951 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 952 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 953 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 954 955 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 956 setOperationAction(ISD::LOAD, MVT::v8i32, Legal); 957 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 958 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 959 960 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 961 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 962 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 963 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 964 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 965 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 966 967 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 968 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 969 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 970 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 971 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 972 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 973 974 // Custom lower build_vector, vector_shuffle, scalar_to_vector, 975 // insert_vector_elt extract_subvector and extract_vector_elt for 976 // 256-bit types. 977 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 978 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 979 ++i) { 980 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 981 // Do not attempt to custom lower non-256-bit vectors 982 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()) 983 || (MVT(VT).getSizeInBits() < 256)) 984 continue; 985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 986 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 987 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 989 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 990 } 991 // Custom-lower insert_subvector and extract_subvector based on 992 // the result type. 993 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 994 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; 995 ++i) { 996 MVT::SimpleValueType VT = (MVT::SimpleValueType)i; 997 // Do not attempt to custom lower non-256-bit vectors 998 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())) 999 continue; 1000 1001 if (MVT(VT).getSizeInBits() == 128) { 1002 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1003 } 1004 else if (MVT(VT).getSizeInBits() == 256) { 1005 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1006 } 1007 } 1008 1009 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1010 // Don't promote loads because we need them for VPERM vector index versions. 1011 1012 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1013 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; 1014 VT++) { 1015 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements()) 1016 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256)) 1017 continue; 1018 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote); 1019 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64); 1020 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote); 1021 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64); 1022 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote); 1023 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64); 1024 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote); 1025 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64); 1026 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote); 1027 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64); 1028 } 1029 } 1030 1031 // We want to custom lower some of our intrinsics. 1032 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1033 1034 1035 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1036 // handle type legalization for these operations here. 1037 // 1038 // FIXME: We really should do custom legalization for addition and 1039 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1040 // than generic legalization for 64-bit multiplication-with-overflow, though. 1041 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1042 // Add/Sub/Mul with overflow operations are custom lowered. 1043 MVT VT = IntVTs[i]; 1044 setOperationAction(ISD::SADDO, VT, Custom); 1045 setOperationAction(ISD::UADDO, VT, Custom); 1046 setOperationAction(ISD::SSUBO, VT, Custom); 1047 setOperationAction(ISD::USUBO, VT, Custom); 1048 setOperationAction(ISD::SMULO, VT, Custom); 1049 setOperationAction(ISD::UMULO, VT, Custom); 1050 } 1051 1052 // There are no 8-bit 3-address imul/mul instructions 1053 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1054 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1055 1056 if (!Subtarget->is64Bit()) { 1057 // These libcalls are not available in 32-bit. 1058 setLibcallName(RTLIB::SHL_I128, 0); 1059 setLibcallName(RTLIB::SRL_I128, 0); 1060 setLibcallName(RTLIB::SRA_I128, 0); 1061 } 1062 1063 // We have target-specific dag combine patterns for the following nodes: 1064 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1065 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1066 setTargetDAGCombine(ISD::BUILD_VECTOR); 1067 setTargetDAGCombine(ISD::SELECT); 1068 setTargetDAGCombine(ISD::SHL); 1069 setTargetDAGCombine(ISD::SRA); 1070 setTargetDAGCombine(ISD::SRL); 1071 setTargetDAGCombine(ISD::OR); 1072 setTargetDAGCombine(ISD::AND); 1073 setTargetDAGCombine(ISD::ADD); 1074 setTargetDAGCombine(ISD::SUB); 1075 setTargetDAGCombine(ISD::STORE); 1076 setTargetDAGCombine(ISD::ZERO_EXTEND); 1077 if (Subtarget->is64Bit()) 1078 setTargetDAGCombine(ISD::MUL); 1079 1080 computeRegisterProperties(); 1081 1082 // On Darwin, -Os means optimize for size without hurting performance, 1083 // do not reduce the limit. 1084 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1085 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1086 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1087 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1088 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1089 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1090 setPrefLoopAlignment(16); 1091 benefitFromCodePlacementOpt = true; 1092} 1093 1094 1095MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const { 1096 return MVT::i8; 1097} 1098 1099 1100/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1101/// the desired ByVal argument alignment. 1102static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) { 1103 if (MaxAlign == 16) 1104 return; 1105 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1106 if (VTy->getBitWidth() == 128) 1107 MaxAlign = 16; 1108 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1109 unsigned EltAlign = 0; 1110 getMaxByValAlign(ATy->getElementType(), EltAlign); 1111 if (EltAlign > MaxAlign) 1112 MaxAlign = EltAlign; 1113 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) { 1114 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1115 unsigned EltAlign = 0; 1116 getMaxByValAlign(STy->getElementType(i), EltAlign); 1117 if (EltAlign > MaxAlign) 1118 MaxAlign = EltAlign; 1119 if (MaxAlign == 16) 1120 break; 1121 } 1122 } 1123 return; 1124} 1125 1126/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1127/// function arguments in the caller parameter area. For X86, aggregates 1128/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1129/// are at 4-byte boundaries. 1130unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const { 1131 if (Subtarget->is64Bit()) { 1132 // Max of 8 and alignment of type. 1133 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1134 if (TyAlign > 8) 1135 return TyAlign; 1136 return 8; 1137 } 1138 1139 unsigned Align = 4; 1140 if (Subtarget->hasXMM()) 1141 getMaxByValAlign(Ty, Align); 1142 return Align; 1143} 1144 1145/// getOptimalMemOpType - Returns the target specific optimal type for load 1146/// and store operations as a result of memset, memcpy, and memmove 1147/// lowering. If DstAlign is zero that means it's safe to destination 1148/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1149/// means there isn't a need to check it against alignment requirement, 1150/// probably because the source does not need to be loaded. If 1151/// 'NonScalarIntSafe' is true, that means it's safe to return a 1152/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1153/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1154/// constant so it does not need to be loaded. 1155/// It returns EVT::Other if the type should be determined using generic 1156/// target-independent logic. 1157EVT 1158X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1159 unsigned DstAlign, unsigned SrcAlign, 1160 bool NonScalarIntSafe, 1161 bool MemcpyStrSrc, 1162 MachineFunction &MF) const { 1163 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1164 // linux. This is because the stack realignment code can't handle certain 1165 // cases like PR2962. This should be removed when PR2962 is fixed. 1166 const Function *F = MF.getFunction(); 1167 if (NonScalarIntSafe && 1168 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1169 if (Size >= 16 && 1170 (Subtarget->isUnalignedMemAccessFast() || 1171 ((DstAlign == 0 || DstAlign >= 16) && 1172 (SrcAlign == 0 || SrcAlign >= 16))) && 1173 Subtarget->getStackAlignment() >= 16) { 1174 if (Subtarget->hasSSE2()) 1175 return MVT::v4i32; 1176 if (Subtarget->hasSSE1()) 1177 return MVT::v4f32; 1178 } else if (!MemcpyStrSrc && Size >= 8 && 1179 !Subtarget->is64Bit() && 1180 Subtarget->getStackAlignment() >= 8 && 1181 Subtarget->hasXMMInt()) { 1182 // Do not use f64 to lower memcpy if source is string constant. It's 1183 // better to use i32 to avoid the loads. 1184 return MVT::f64; 1185 } 1186 } 1187 if (Subtarget->is64Bit() && Size >= 8) 1188 return MVT::i64; 1189 return MVT::i32; 1190} 1191 1192/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1193/// current function. The returned value is a member of the 1194/// MachineJumpTableInfo::JTEntryKind enum. 1195unsigned X86TargetLowering::getJumpTableEncoding() const { 1196 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1197 // symbol. 1198 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1199 Subtarget->isPICStyleGOT()) 1200 return MachineJumpTableInfo::EK_Custom32; 1201 1202 // Otherwise, use the normal jump table encoding heuristics. 1203 return TargetLowering::getJumpTableEncoding(); 1204} 1205 1206const MCExpr * 1207X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1208 const MachineBasicBlock *MBB, 1209 unsigned uid,MCContext &Ctx) const{ 1210 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1211 Subtarget->isPICStyleGOT()); 1212 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1213 // entries. 1214 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1215 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1216} 1217 1218/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1219/// jumptable. 1220SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1221 SelectionDAG &DAG) const { 1222 if (!Subtarget->is64Bit()) 1223 // This doesn't have DebugLoc associated with it, but is not really the 1224 // same as a Register. 1225 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1226 return Table; 1227} 1228 1229/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1230/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1231/// MCExpr. 1232const MCExpr *X86TargetLowering:: 1233getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1234 MCContext &Ctx) const { 1235 // X86-64 uses RIP relative addressing based on the jump table label. 1236 if (Subtarget->isPICStyleRIPRel()) 1237 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1238 1239 // Otherwise, the reference is relative to the PIC base. 1240 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1241} 1242 1243/// getFunctionAlignment - Return the Log2 alignment of this function. 1244unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const { 1245 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4; 1246} 1247 1248// FIXME: Why this routine is here? Move to RegInfo! 1249std::pair<const TargetRegisterClass*, uint8_t> 1250X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1251 const TargetRegisterClass *RRC = 0; 1252 uint8_t Cost = 1; 1253 switch (VT.getSimpleVT().SimpleTy) { 1254 default: 1255 return TargetLowering::findRepresentativeClass(VT); 1256 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1257 RRC = (Subtarget->is64Bit() 1258 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1259 break; 1260 case MVT::x86mmx: 1261 RRC = X86::VR64RegisterClass; 1262 break; 1263 case MVT::f32: case MVT::f64: 1264 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1265 case MVT::v4f32: case MVT::v2f64: 1266 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1267 case MVT::v4f64: 1268 RRC = X86::VR128RegisterClass; 1269 break; 1270 } 1271 return std::make_pair(RRC, Cost); 1272} 1273 1274// FIXME: Why this routine is here? Move to RegInfo! 1275unsigned 1276X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC, 1277 MachineFunction &MF) const { 1278 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); 1279 1280 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0; 1281 switch (RC->getID()) { 1282 default: 1283 return 0; 1284 case X86::GR32RegClassID: 1285 return 4 - FPDiff; 1286 case X86::GR64RegClassID: 1287 return 12 - FPDiff; 1288 case X86::VR128RegClassID: 1289 return Subtarget->is64Bit() ? 10 : 4; 1290 case X86::VR64RegClassID: 1291 return 4; 1292 } 1293} 1294 1295bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1296 unsigned &Offset) const { 1297 if (!Subtarget->isTargetLinux()) 1298 return false; 1299 1300 if (Subtarget->is64Bit()) { 1301 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1302 Offset = 0x28; 1303 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1304 AddressSpace = 256; 1305 else 1306 AddressSpace = 257; 1307 } else { 1308 // %gs:0x14 on i386 1309 Offset = 0x14; 1310 AddressSpace = 256; 1311 } 1312 return true; 1313} 1314 1315 1316//===----------------------------------------------------------------------===// 1317// Return Value Calling Convention Implementation 1318//===----------------------------------------------------------------------===// 1319 1320#include "X86GenCallingConv.inc" 1321 1322bool 1323X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg, 1324 const SmallVectorImpl<ISD::OutputArg> &Outs, 1325 LLVMContext &Context) const { 1326 SmallVector<CCValAssign, 16> RVLocs; 1327 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1328 RVLocs, Context); 1329 return CCInfo.CheckReturn(Outs, RetCC_X86); 1330} 1331 1332SDValue 1333X86TargetLowering::LowerReturn(SDValue Chain, 1334 CallingConv::ID CallConv, bool isVarArg, 1335 const SmallVectorImpl<ISD::OutputArg> &Outs, 1336 const SmallVectorImpl<SDValue> &OutVals, 1337 DebugLoc dl, SelectionDAG &DAG) const { 1338 MachineFunction &MF = DAG.getMachineFunction(); 1339 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1340 1341 SmallVector<CCValAssign, 16> RVLocs; 1342 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1343 RVLocs, *DAG.getContext()); 1344 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1345 1346 // Add the regs to the liveout set for the function. 1347 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1348 for (unsigned i = 0; i != RVLocs.size(); ++i) 1349 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1350 MRI.addLiveOut(RVLocs[i].getLocReg()); 1351 1352 SDValue Flag; 1353 1354 SmallVector<SDValue, 6> RetOps; 1355 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1356 // Operand #1 = Bytes To Pop 1357 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1358 MVT::i16)); 1359 1360 // Copy the result values into the output registers. 1361 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1362 CCValAssign &VA = RVLocs[i]; 1363 assert(VA.isRegLoc() && "Can only return in registers!"); 1364 SDValue ValToCopy = OutVals[i]; 1365 EVT ValVT = ValToCopy.getValueType(); 1366 1367 // If this is x86-64, and we disabled SSE, we can't return FP values, 1368 // or SSE or MMX vectors. 1369 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1370 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1371 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1372 report_fatal_error("SSE register return with SSE disabled"); 1373 } 1374 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1375 // llvm-gcc has never done it right and no one has noticed, so this 1376 // should be OK for now. 1377 if (ValVT == MVT::f64 && 1378 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1379 report_fatal_error("SSE2 register return with SSE2 disabled"); 1380 1381 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1382 // the RET instruction and handled by the FP Stackifier. 1383 if (VA.getLocReg() == X86::ST0 || 1384 VA.getLocReg() == X86::ST1) { 1385 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1386 // change the value to the FP stack register class. 1387 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1388 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1389 RetOps.push_back(ValToCopy); 1390 // Don't emit a copytoreg. 1391 continue; 1392 } 1393 1394 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1395 // which is returned in RAX / RDX. 1396 if (Subtarget->is64Bit()) { 1397 if (ValVT == MVT::x86mmx) { 1398 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1399 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1400 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1401 ValToCopy); 1402 // If we don't have SSE2 available, convert to v4f32 so the generated 1403 // register is legal. 1404 if (!Subtarget->hasSSE2()) 1405 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1406 } 1407 } 1408 } 1409 1410 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1411 Flag = Chain.getValue(1); 1412 } 1413 1414 // The x86-64 ABI for returning structs by value requires that we copy 1415 // the sret argument into %rax for the return. We saved the argument into 1416 // a virtual register in the entry block, so now we copy the value out 1417 // and into %rax. 1418 if (Subtarget->is64Bit() && 1419 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1420 MachineFunction &MF = DAG.getMachineFunction(); 1421 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1422 unsigned Reg = FuncInfo->getSRetReturnReg(); 1423 assert(Reg && 1424 "SRetReturnReg should have been set in LowerFormalArguments()."); 1425 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1426 1427 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1428 Flag = Chain.getValue(1); 1429 1430 // RAX now acts like a return value. 1431 MRI.addLiveOut(X86::RAX); 1432 } 1433 1434 RetOps[0] = Chain; // Update chain. 1435 1436 // Add the flag if we have it. 1437 if (Flag.getNode()) 1438 RetOps.push_back(Flag); 1439 1440 return DAG.getNode(X86ISD::RET_FLAG, dl, 1441 MVT::Other, &RetOps[0], RetOps.size()); 1442} 1443 1444bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1445 if (N->getNumValues() != 1) 1446 return false; 1447 if (!N->hasNUsesOfValue(1, 0)) 1448 return false; 1449 1450 SDNode *Copy = *N->use_begin(); 1451 if (Copy->getOpcode() != ISD::CopyToReg && 1452 Copy->getOpcode() != ISD::FP_EXTEND) 1453 return false; 1454 1455 bool HasRet = false; 1456 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1457 UI != UE; ++UI) { 1458 if (UI->getOpcode() != X86ISD::RET_FLAG) 1459 return false; 1460 HasRet = true; 1461 } 1462 1463 return HasRet; 1464} 1465 1466/// LowerCallResult - Lower the result values of a call into the 1467/// appropriate copies out of appropriate physical registers. 1468/// 1469SDValue 1470X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1471 CallingConv::ID CallConv, bool isVarArg, 1472 const SmallVectorImpl<ISD::InputArg> &Ins, 1473 DebugLoc dl, SelectionDAG &DAG, 1474 SmallVectorImpl<SDValue> &InVals) const { 1475 1476 // Assign locations to each value returned by this call. 1477 SmallVector<CCValAssign, 16> RVLocs; 1478 bool Is64Bit = Subtarget->is64Bit(); 1479 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1480 RVLocs, *DAG.getContext()); 1481 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1482 1483 // Copy all of the result registers out of their specified physreg. 1484 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1485 CCValAssign &VA = RVLocs[i]; 1486 EVT CopyVT = VA.getValVT(); 1487 1488 // If this is x86-64, and we disabled SSE, we can't return FP values 1489 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1490 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1491 report_fatal_error("SSE register return with SSE disabled"); 1492 } 1493 1494 SDValue Val; 1495 1496 // If this is a call to a function that returns an fp value on the floating 1497 // point stack, we must guarantee the the value is popped from the stack, so 1498 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1499 // if the return value is not used. We use the FpGET_ST0 instructions 1500 // instead. 1501 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1502 // If we prefer to use the value in xmm registers, copy it out as f80 and 1503 // use a truncate to move it from fp stack reg to xmm reg. 1504 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1505 bool isST0 = VA.getLocReg() == X86::ST0; 1506 unsigned Opc = 0; 1507 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32; 1508 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64; 1509 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80; 1510 SDValue Ops[] = { Chain, InFlag }; 1511 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue, 1512 Ops, 2), 1); 1513 Val = Chain.getValue(0); 1514 1515 // Round the f80 to the right size, which also moves it to the appropriate 1516 // xmm register. 1517 if (CopyVT != VA.getValVT()) 1518 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1519 // This truncation won't change the value. 1520 DAG.getIntPtrConstant(1)); 1521 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) { 1522 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64. 1523 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1524 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1525 MVT::v2i64, InFlag).getValue(1); 1526 Val = Chain.getValue(0); 1527 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, 1528 Val, DAG.getConstant(0, MVT::i64)); 1529 } else { 1530 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1531 MVT::i64, InFlag).getValue(1); 1532 Val = Chain.getValue(0); 1533 } 1534 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val); 1535 } else { 1536 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1537 CopyVT, InFlag).getValue(1); 1538 Val = Chain.getValue(0); 1539 } 1540 InFlag = Chain.getValue(2); 1541 InVals.push_back(Val); 1542 } 1543 1544 return Chain; 1545} 1546 1547 1548//===----------------------------------------------------------------------===// 1549// C & StdCall & Fast Calling Convention implementation 1550//===----------------------------------------------------------------------===// 1551// StdCall calling convention seems to be standard for many Windows' API 1552// routines and around. It differs from C calling convention just a little: 1553// callee should clean up the stack, not caller. Symbols should be also 1554// decorated in some fancy way :) It doesn't support any vector arguments. 1555// For info on fast calling convention see Fast Calling Convention (tail call) 1556// implementation LowerX86_32FastCCCallTo. 1557 1558/// CallIsStructReturn - Determines whether a call uses struct return 1559/// semantics. 1560static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1561 if (Outs.empty()) 1562 return false; 1563 1564 return Outs[0].Flags.isSRet(); 1565} 1566 1567/// ArgsAreStructReturn - Determines whether a function uses struct 1568/// return semantics. 1569static bool 1570ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1571 if (Ins.empty()) 1572 return false; 1573 1574 return Ins[0].Flags.isSRet(); 1575} 1576 1577/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1578/// by "Src" to address "Dst" with size and alignment information specified by 1579/// the specific parameter attribute. The copy will be passed as a byval 1580/// function parameter. 1581static SDValue 1582CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1583 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1584 DebugLoc dl) { 1585 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1586 1587 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1588 /*isVolatile*/false, /*AlwaysInline=*/true, 1589 MachinePointerInfo(), MachinePointerInfo()); 1590} 1591 1592/// IsTailCallConvention - Return true if the calling convention is one that 1593/// supports tail call optimization. 1594static bool IsTailCallConvention(CallingConv::ID CC) { 1595 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1596} 1597 1598/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1599/// a tailcall target by changing its ABI. 1600static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1601 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1602} 1603 1604SDValue 1605X86TargetLowering::LowerMemArgument(SDValue Chain, 1606 CallingConv::ID CallConv, 1607 const SmallVectorImpl<ISD::InputArg> &Ins, 1608 DebugLoc dl, SelectionDAG &DAG, 1609 const CCValAssign &VA, 1610 MachineFrameInfo *MFI, 1611 unsigned i) const { 1612 // Create the nodes corresponding to a load from this parameter slot. 1613 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1614 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1615 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1616 EVT ValVT; 1617 1618 // If value is passed by pointer we have address passed instead of the value 1619 // itself. 1620 if (VA.getLocInfo() == CCValAssign::Indirect) 1621 ValVT = VA.getLocVT(); 1622 else 1623 ValVT = VA.getValVT(); 1624 1625 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1626 // changed with more analysis. 1627 // In case of tail call optimization mark all arguments mutable. Since they 1628 // could be overwritten by lowering of arguments in case of a tail call. 1629 if (Flags.isByVal()) { 1630 int FI = MFI->CreateFixedObject(Flags.getByValSize(), 1631 VA.getLocMemOffset(), isImmutable); 1632 return DAG.getFrameIndex(FI, getPointerTy()); 1633 } else { 1634 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1635 VA.getLocMemOffset(), isImmutable); 1636 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1637 return DAG.getLoad(ValVT, dl, Chain, FIN, 1638 MachinePointerInfo::getFixedStack(FI), 1639 false, false, 0); 1640 } 1641} 1642 1643SDValue 1644X86TargetLowering::LowerFormalArguments(SDValue Chain, 1645 CallingConv::ID CallConv, 1646 bool isVarArg, 1647 const SmallVectorImpl<ISD::InputArg> &Ins, 1648 DebugLoc dl, 1649 SelectionDAG &DAG, 1650 SmallVectorImpl<SDValue> &InVals) 1651 const { 1652 MachineFunction &MF = DAG.getMachineFunction(); 1653 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1654 1655 const Function* Fn = MF.getFunction(); 1656 if (Fn->hasExternalLinkage() && 1657 Subtarget->isTargetCygMing() && 1658 Fn->getName() == "main") 1659 FuncInfo->setForceFramePointer(true); 1660 1661 MachineFrameInfo *MFI = MF.getFrameInfo(); 1662 bool Is64Bit = Subtarget->is64Bit(); 1663 bool IsWin64 = Subtarget->isTargetWin64(); 1664 1665 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1666 "Var args not supported with calling convention fastcc or ghc"); 1667 1668 // Assign locations to all of the incoming arguments. 1669 SmallVector<CCValAssign, 16> ArgLocs; 1670 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1671 ArgLocs, *DAG.getContext()); 1672 1673 // Allocate shadow area for Win64 1674 if (IsWin64) { 1675 CCInfo.AllocateStack(32, 8); 1676 } 1677 1678 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1679 1680 unsigned LastVal = ~0U; 1681 SDValue ArgValue; 1682 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1683 CCValAssign &VA = ArgLocs[i]; 1684 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1685 // places. 1686 assert(VA.getValNo() != LastVal && 1687 "Don't support value assigned to multiple locs yet"); 1688 LastVal = VA.getValNo(); 1689 1690 if (VA.isRegLoc()) { 1691 EVT RegVT = VA.getLocVT(); 1692 TargetRegisterClass *RC = NULL; 1693 if (RegVT == MVT::i32) 1694 RC = X86::GR32RegisterClass; 1695 else if (Is64Bit && RegVT == MVT::i64) 1696 RC = X86::GR64RegisterClass; 1697 else if (RegVT == MVT::f32) 1698 RC = X86::FR32RegisterClass; 1699 else if (RegVT == MVT::f64) 1700 RC = X86::FR64RegisterClass; 1701 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1702 RC = X86::VR256RegisterClass; 1703 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1704 RC = X86::VR128RegisterClass; 1705 else if (RegVT == MVT::x86mmx) 1706 RC = X86::VR64RegisterClass; 1707 else 1708 llvm_unreachable("Unknown argument type!"); 1709 1710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1711 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1712 1713 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1714 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1715 // right size. 1716 if (VA.getLocInfo() == CCValAssign::SExt) 1717 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1718 DAG.getValueType(VA.getValVT())); 1719 else if (VA.getLocInfo() == CCValAssign::ZExt) 1720 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1721 DAG.getValueType(VA.getValVT())); 1722 else if (VA.getLocInfo() == CCValAssign::BCvt) 1723 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1724 1725 if (VA.isExtInLoc()) { 1726 // Handle MMX values passed in XMM regs. 1727 if (RegVT.isVector()) { 1728 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1729 ArgValue); 1730 } else 1731 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1732 } 1733 } else { 1734 assert(VA.isMemLoc()); 1735 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1736 } 1737 1738 // If value is passed via pointer - do a load. 1739 if (VA.getLocInfo() == CCValAssign::Indirect) 1740 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1741 MachinePointerInfo(), false, false, 0); 1742 1743 InVals.push_back(ArgValue); 1744 } 1745 1746 // The x86-64 ABI for returning structs by value requires that we copy 1747 // the sret argument into %rax for the return. Save the argument into 1748 // a virtual register so that we can access it from the return points. 1749 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1750 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1751 unsigned Reg = FuncInfo->getSRetReturnReg(); 1752 if (!Reg) { 1753 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1754 FuncInfo->setSRetReturnReg(Reg); 1755 } 1756 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1758 } 1759 1760 unsigned StackSize = CCInfo.getNextStackOffset(); 1761 // Align stack specially for tail calls. 1762 if (FuncIsMadeTailCallSafe(CallConv)) 1763 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1764 1765 // If the function takes variable number of arguments, make a frame index for 1766 // the start of the first vararg value... for expansion of llvm.va_start. 1767 if (isVarArg) { 1768 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1769 CallConv != CallingConv::X86_ThisCall))) { 1770 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1771 } 1772 if (Is64Bit) { 1773 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1774 1775 // FIXME: We should really autogenerate these arrays 1776 static const unsigned GPR64ArgRegsWin64[] = { 1777 X86::RCX, X86::RDX, X86::R8, X86::R9 1778 }; 1779 static const unsigned GPR64ArgRegs64Bit[] = { 1780 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1781 }; 1782 static const unsigned XMMArgRegs64Bit[] = { 1783 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1784 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1785 }; 1786 const unsigned *GPR64ArgRegs; 1787 unsigned NumXMMRegs = 0; 1788 1789 if (IsWin64) { 1790 // The XMM registers which might contain var arg parameters are shadowed 1791 // in their paired GPR. So we only need to save the GPR to their home 1792 // slots. 1793 TotalNumIntRegs = 4; 1794 GPR64ArgRegs = GPR64ArgRegsWin64; 1795 } else { 1796 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1797 GPR64ArgRegs = GPR64ArgRegs64Bit; 1798 1799 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1800 } 1801 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1802 TotalNumIntRegs); 1803 1804 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1805 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1806 "SSE register cannot be used when SSE is disabled!"); 1807 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1808 "SSE register cannot be used when SSE is disabled!"); 1809 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1810 // Kernel mode asks for SSE to be disabled, so don't push them 1811 // on the stack. 1812 TotalNumXMMRegs = 0; 1813 1814 if (IsWin64) { 1815 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1816 // Get to the caller-allocated home save location. Add 8 to account 1817 // for the return address. 1818 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1819 FuncInfo->setRegSaveFrameIndex( 1820 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1821 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1822 } else { 1823 // For X86-64, if there are vararg parameters that are passed via 1824 // registers, then we must store them to their spots on the stack so they 1825 // may be loaded by deferencing the result of va_next. 1826 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1827 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1828 FuncInfo->setRegSaveFrameIndex( 1829 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1830 false)); 1831 } 1832 1833 // Store the integer parameter registers. 1834 SmallVector<SDValue, 8> MemOps; 1835 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1836 getPointerTy()); 1837 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1838 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1839 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1840 DAG.getIntPtrConstant(Offset)); 1841 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1842 X86::GR64RegisterClass); 1843 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1844 SDValue Store = 1845 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1846 MachinePointerInfo::getFixedStack( 1847 FuncInfo->getRegSaveFrameIndex(), Offset), 1848 false, false, 0); 1849 MemOps.push_back(Store); 1850 Offset += 8; 1851 } 1852 1853 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1854 // Now store the XMM (fp + vector) parameter registers. 1855 SmallVector<SDValue, 11> SaveXMMOps; 1856 SaveXMMOps.push_back(Chain); 1857 1858 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1859 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1860 SaveXMMOps.push_back(ALVal); 1861 1862 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1863 FuncInfo->getRegSaveFrameIndex())); 1864 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1865 FuncInfo->getVarArgsFPOffset())); 1866 1867 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1868 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1869 X86::VR128RegisterClass); 1870 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1871 SaveXMMOps.push_back(Val); 1872 } 1873 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1874 MVT::Other, 1875 &SaveXMMOps[0], SaveXMMOps.size())); 1876 } 1877 1878 if (!MemOps.empty()) 1879 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1880 &MemOps[0], MemOps.size()); 1881 } 1882 } 1883 1884 // Some CCs need callee pop. 1885 if (Subtarget->IsCalleePop(isVarArg, CallConv)) { 1886 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 1887 } else { 1888 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 1889 // If this is an sret function, the return should pop the hidden pointer. 1890 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 1891 FuncInfo->setBytesToPopOnReturn(4); 1892 } 1893 1894 if (!Is64Bit) { 1895 // RegSaveFrameIndex is X86-64 only. 1896 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 1897 if (CallConv == CallingConv::X86_FastCall || 1898 CallConv == CallingConv::X86_ThisCall) 1899 // fastcc functions can't have varargs. 1900 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 1901 } 1902 1903 return Chain; 1904} 1905 1906SDValue 1907X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 1908 SDValue StackPtr, SDValue Arg, 1909 DebugLoc dl, SelectionDAG &DAG, 1910 const CCValAssign &VA, 1911 ISD::ArgFlagsTy Flags) const { 1912 unsigned LocMemOffset = VA.getLocMemOffset(); 1913 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 1914 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 1915 if (Flags.isByVal()) 1916 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 1917 1918 return DAG.getStore(Chain, dl, Arg, PtrOff, 1919 MachinePointerInfo::getStack(LocMemOffset), 1920 false, false, 0); 1921} 1922 1923/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 1924/// optimization is performed and it is required. 1925SDValue 1926X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 1927 SDValue &OutRetAddr, SDValue Chain, 1928 bool IsTailCall, bool Is64Bit, 1929 int FPDiff, DebugLoc dl) const { 1930 // Adjust the Return address stack slot. 1931 EVT VT = getPointerTy(); 1932 OutRetAddr = getReturnAddressFrameIndex(DAG); 1933 1934 // Load the "old" Return address. 1935 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 1936 false, false, 0); 1937 return SDValue(OutRetAddr.getNode(), 1); 1938} 1939 1940/// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call 1941/// optimization is performed and it is required (FPDiff!=0). 1942static SDValue 1943EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 1944 SDValue Chain, SDValue RetAddrFrIdx, 1945 bool Is64Bit, int FPDiff, DebugLoc dl) { 1946 // Store the return address to the appropriate stack slot. 1947 if (!FPDiff) return Chain; 1948 // Calculate the new stack slot for the return address. 1949 int SlotSize = Is64Bit ? 8 : 4; 1950 int NewReturnAddrFI = 1951 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 1952 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 1953 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 1954 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 1955 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 1956 false, false, 0); 1957 return Chain; 1958} 1959 1960SDValue 1961X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 1962 CallingConv::ID CallConv, bool isVarArg, 1963 bool &isTailCall, 1964 const SmallVectorImpl<ISD::OutputArg> &Outs, 1965 const SmallVectorImpl<SDValue> &OutVals, 1966 const SmallVectorImpl<ISD::InputArg> &Ins, 1967 DebugLoc dl, SelectionDAG &DAG, 1968 SmallVectorImpl<SDValue> &InVals) const { 1969 MachineFunction &MF = DAG.getMachineFunction(); 1970 bool Is64Bit = Subtarget->is64Bit(); 1971 bool IsWin64 = Subtarget->isTargetWin64(); 1972 bool IsStructRet = CallIsStructReturn(Outs); 1973 bool IsSibcall = false; 1974 1975 if (isTailCall) { 1976 // Check if it's really possible to do a tail call. 1977 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 1978 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 1979 Outs, OutVals, Ins, DAG); 1980 1981 // Sibcalls are automatically detected tailcalls which do not require 1982 // ABI changes. 1983 if (!GuaranteedTailCallOpt && isTailCall) 1984 IsSibcall = true; 1985 1986 if (isTailCall) 1987 ++NumTailCalls; 1988 } 1989 1990 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1991 "Var args not supported with calling convention fastcc or ghc"); 1992 1993 // Analyze operands of the call, assigning locations to each operand. 1994 SmallVector<CCValAssign, 16> ArgLocs; 1995 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), 1996 ArgLocs, *DAG.getContext()); 1997 1998 // Allocate shadow area for Win64 1999 if (IsWin64) { 2000 CCInfo.AllocateStack(32, 8); 2001 } 2002 2003 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2004 2005 // Get a count of how many bytes are to be pushed on the stack. 2006 unsigned NumBytes = CCInfo.getNextStackOffset(); 2007 if (IsSibcall) 2008 // This is a sibcall. The memory operands are available in caller's 2009 // own caller's stack. 2010 NumBytes = 0; 2011 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2012 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2013 2014 int FPDiff = 0; 2015 if (isTailCall && !IsSibcall) { 2016 // Lower arguments at fp - stackoffset + fpdiff. 2017 unsigned NumBytesCallerPushed = 2018 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2019 FPDiff = NumBytesCallerPushed - NumBytes; 2020 2021 // Set the delta of movement of the returnaddr stackslot. 2022 // But only set if delta is greater than previous delta. 2023 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2024 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2025 } 2026 2027 if (!IsSibcall) 2028 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2029 2030 SDValue RetAddrFrIdx; 2031 // Load return adress for tail calls. 2032 if (isTailCall && FPDiff) 2033 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2034 Is64Bit, FPDiff, dl); 2035 2036 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2037 SmallVector<SDValue, 8> MemOpChains; 2038 SDValue StackPtr; 2039 2040 // Walk the register/memloc assignments, inserting copies/loads. In the case 2041 // of tail call optimization arguments are handle later. 2042 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2043 CCValAssign &VA = ArgLocs[i]; 2044 EVT RegVT = VA.getLocVT(); 2045 SDValue Arg = OutVals[i]; 2046 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2047 bool isByVal = Flags.isByVal(); 2048 2049 // Promote the value if needed. 2050 switch (VA.getLocInfo()) { 2051 default: llvm_unreachable("Unknown loc info!"); 2052 case CCValAssign::Full: break; 2053 case CCValAssign::SExt: 2054 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2055 break; 2056 case CCValAssign::ZExt: 2057 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2058 break; 2059 case CCValAssign::AExt: 2060 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2061 // Special case: passing MMX values in XMM registers. 2062 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2063 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2064 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2065 } else 2066 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2067 break; 2068 case CCValAssign::BCvt: 2069 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2070 break; 2071 case CCValAssign::Indirect: { 2072 // Store the argument. 2073 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2074 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2075 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2076 MachinePointerInfo::getFixedStack(FI), 2077 false, false, 0); 2078 Arg = SpillSlot; 2079 break; 2080 } 2081 } 2082 2083 if (VA.isRegLoc()) { 2084 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2085 if (isVarArg && IsWin64) { 2086 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2087 // shadow reg if callee is a varargs function. 2088 unsigned ShadowReg = 0; 2089 switch (VA.getLocReg()) { 2090 case X86::XMM0: ShadowReg = X86::RCX; break; 2091 case X86::XMM1: ShadowReg = X86::RDX; break; 2092 case X86::XMM2: ShadowReg = X86::R8; break; 2093 case X86::XMM3: ShadowReg = X86::R9; break; 2094 } 2095 if (ShadowReg) 2096 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2097 } 2098 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2099 assert(VA.isMemLoc()); 2100 if (StackPtr.getNode() == 0) 2101 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2102 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2103 dl, DAG, VA, Flags)); 2104 } 2105 } 2106 2107 if (!MemOpChains.empty()) 2108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2109 &MemOpChains[0], MemOpChains.size()); 2110 2111 // Build a sequence of copy-to-reg nodes chained together with token chain 2112 // and flag operands which copy the outgoing args into registers. 2113 SDValue InFlag; 2114 // Tail call byval lowering might overwrite argument registers so in case of 2115 // tail call optimization the copies to registers are lowered later. 2116 if (!isTailCall) 2117 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2118 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2119 RegsToPass[i].second, InFlag); 2120 InFlag = Chain.getValue(1); 2121 } 2122 2123 if (Subtarget->isPICStyleGOT()) { 2124 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2125 // GOT pointer. 2126 if (!isTailCall) { 2127 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2128 DAG.getNode(X86ISD::GlobalBaseReg, 2129 DebugLoc(), getPointerTy()), 2130 InFlag); 2131 InFlag = Chain.getValue(1); 2132 } else { 2133 // If we are tail calling and generating PIC/GOT style code load the 2134 // address of the callee into ECX. The value in ecx is used as target of 2135 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2136 // for tail calls on PIC/GOT architectures. Normally we would just put the 2137 // address of GOT into ebx and then call target@PLT. But for tail calls 2138 // ebx would be restored (since ebx is callee saved) before jumping to the 2139 // target@PLT. 2140 2141 // Note: The actual moving to ECX is done further down. 2142 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2143 if (G && !G->getGlobal()->hasHiddenVisibility() && 2144 !G->getGlobal()->hasProtectedVisibility()) 2145 Callee = LowerGlobalAddress(Callee, DAG); 2146 else if (isa<ExternalSymbolSDNode>(Callee)) 2147 Callee = LowerExternalSymbol(Callee, DAG); 2148 } 2149 } 2150 2151 if (Is64Bit && isVarArg && !IsWin64) { 2152 // From AMD64 ABI document: 2153 // For calls that may call functions that use varargs or stdargs 2154 // (prototype-less calls or calls to functions containing ellipsis (...) in 2155 // the declaration) %al is used as hidden argument to specify the number 2156 // of SSE registers used. The contents of %al do not need to match exactly 2157 // the number of registers, but must be an ubound on the number of SSE 2158 // registers used and is in the range 0 - 8 inclusive. 2159 2160 // Count the number of XMM registers allocated. 2161 static const unsigned XMMArgRegs[] = { 2162 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2163 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2164 }; 2165 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2166 assert((Subtarget->hasXMM() || !NumXMMRegs) 2167 && "SSE registers cannot be used when SSE is disabled"); 2168 2169 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2170 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2171 InFlag = Chain.getValue(1); 2172 } 2173 2174 2175 // For tail calls lower the arguments to the 'real' stack slot. 2176 if (isTailCall) { 2177 // Force all the incoming stack arguments to be loaded from the stack 2178 // before any new outgoing arguments are stored to the stack, because the 2179 // outgoing stack slots may alias the incoming argument stack slots, and 2180 // the alias isn't otherwise explicit. This is slightly more conservative 2181 // than necessary, because it means that each store effectively depends 2182 // on every argument instead of just those arguments it would clobber. 2183 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2184 2185 SmallVector<SDValue, 8> MemOpChains2; 2186 SDValue FIN; 2187 int FI = 0; 2188 // Do not flag preceeding copytoreg stuff together with the following stuff. 2189 InFlag = SDValue(); 2190 if (GuaranteedTailCallOpt) { 2191 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2192 CCValAssign &VA = ArgLocs[i]; 2193 if (VA.isRegLoc()) 2194 continue; 2195 assert(VA.isMemLoc()); 2196 SDValue Arg = OutVals[i]; 2197 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2198 // Create frame index. 2199 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2200 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2201 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2202 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2203 2204 if (Flags.isByVal()) { 2205 // Copy relative to framepointer. 2206 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2207 if (StackPtr.getNode() == 0) 2208 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2209 getPointerTy()); 2210 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2211 2212 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2213 ArgChain, 2214 Flags, DAG, dl)); 2215 } else { 2216 // Store relative to framepointer. 2217 MemOpChains2.push_back( 2218 DAG.getStore(ArgChain, dl, Arg, FIN, 2219 MachinePointerInfo::getFixedStack(FI), 2220 false, false, 0)); 2221 } 2222 } 2223 } 2224 2225 if (!MemOpChains2.empty()) 2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2227 &MemOpChains2[0], MemOpChains2.size()); 2228 2229 // Copy arguments to their registers. 2230 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2231 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2232 RegsToPass[i].second, InFlag); 2233 InFlag = Chain.getValue(1); 2234 } 2235 InFlag =SDValue(); 2236 2237 // Store the return address to the appropriate stack slot. 2238 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2239 FPDiff, dl); 2240 } 2241 2242 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2243 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2244 // In the 64-bit large code model, we have to make all calls 2245 // through a register, since the call instruction's 32-bit 2246 // pc-relative offset may not be large enough to hold the whole 2247 // address. 2248 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2249 // If the callee is a GlobalAddress node (quite common, every direct call 2250 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2251 // it. 2252 2253 // We should use extra load for direct calls to dllimported functions in 2254 // non-JIT mode. 2255 const GlobalValue *GV = G->getGlobal(); 2256 if (!GV->hasDLLImportLinkage()) { 2257 unsigned char OpFlags = 0; 2258 2259 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2260 // external symbols most go through the PLT in PIC mode. If the symbol 2261 // has hidden or protected visibility, or if it is static or local, then 2262 // we don't need to use the PLT - we can directly call it. 2263 if (Subtarget->isTargetELF() && 2264 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2265 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2266 OpFlags = X86II::MO_PLT; 2267 } else if (Subtarget->isPICStyleStubAny() && 2268 (GV->isDeclaration() || GV->isWeakForLinker()) && 2269 Subtarget->getDarwinVers() < 9) { 2270 // PC-relative references to external symbols should go through $stub, 2271 // unless we're building with the leopard linker or later, which 2272 // automatically synthesizes these stubs. 2273 OpFlags = X86II::MO_DARWIN_STUB; 2274 } 2275 2276 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2277 G->getOffset(), OpFlags); 2278 } 2279 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2280 unsigned char OpFlags = 0; 2281 2282 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2283 // external symbols should go through the PLT. 2284 if (Subtarget->isTargetELF() && 2285 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2286 OpFlags = X86II::MO_PLT; 2287 } else if (Subtarget->isPICStyleStubAny() && 2288 Subtarget->getDarwinVers() < 9) { 2289 // PC-relative references to external symbols should go through $stub, 2290 // unless we're building with the leopard linker or later, which 2291 // automatically synthesizes these stubs. 2292 OpFlags = X86II::MO_DARWIN_STUB; 2293 } 2294 2295 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2296 OpFlags); 2297 } 2298 2299 // Returns a chain & a flag for retval copy to use. 2300 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2301 SmallVector<SDValue, 8> Ops; 2302 2303 if (!IsSibcall && isTailCall) { 2304 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2305 DAG.getIntPtrConstant(0, true), InFlag); 2306 InFlag = Chain.getValue(1); 2307 } 2308 2309 Ops.push_back(Chain); 2310 Ops.push_back(Callee); 2311 2312 if (isTailCall) 2313 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2314 2315 // Add argument registers to the end of the list so that they are known live 2316 // into the call. 2317 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2318 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2319 RegsToPass[i].second.getValueType())); 2320 2321 // Add an implicit use GOT pointer in EBX. 2322 if (!isTailCall && Subtarget->isPICStyleGOT()) 2323 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2324 2325 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2326 if (Is64Bit && isVarArg && !IsWin64) 2327 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2328 2329 if (InFlag.getNode()) 2330 Ops.push_back(InFlag); 2331 2332 if (isTailCall) { 2333 // We used to do: 2334 //// If this is the first return lowered for this function, add the regs 2335 //// to the liveout set for the function. 2336 // This isn't right, although it's probably harmless on x86; liveouts 2337 // should be computed from returns not tail calls. Consider a void 2338 // function making a tail call to a function returning int. 2339 return DAG.getNode(X86ISD::TC_RETURN, dl, 2340 NodeTys, &Ops[0], Ops.size()); 2341 } 2342 2343 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2344 InFlag = Chain.getValue(1); 2345 2346 // Create the CALLSEQ_END node. 2347 unsigned NumBytesForCalleeToPush; 2348 if (Subtarget->IsCalleePop(isVarArg, CallConv)) 2349 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2350 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2351 // If this is a call to a struct-return function, the callee 2352 // pops the hidden struct pointer, so we have to push it back. 2353 // This is common for Darwin/X86, Linux & Mingw32 targets. 2354 NumBytesForCalleeToPush = 4; 2355 else 2356 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2357 2358 // Returns a flag for retval copy to use. 2359 if (!IsSibcall) { 2360 Chain = DAG.getCALLSEQ_END(Chain, 2361 DAG.getIntPtrConstant(NumBytes, true), 2362 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2363 true), 2364 InFlag); 2365 InFlag = Chain.getValue(1); 2366 } 2367 2368 // Handle result values, copying them out of physregs into vregs that we 2369 // return. 2370 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2371 Ins, dl, DAG, InVals); 2372} 2373 2374 2375//===----------------------------------------------------------------------===// 2376// Fast Calling Convention (tail call) implementation 2377//===----------------------------------------------------------------------===// 2378 2379// Like std call, callee cleans arguments, convention except that ECX is 2380// reserved for storing the tail called function address. Only 2 registers are 2381// free for argument passing (inreg). Tail call optimization is performed 2382// provided: 2383// * tailcallopt is enabled 2384// * caller/callee are fastcc 2385// On X86_64 architecture with GOT-style position independent code only local 2386// (within module) calls are supported at the moment. 2387// To keep the stack aligned according to platform abi the function 2388// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2389// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2390// If a tail called function callee has more arguments than the caller the 2391// caller needs to make sure that there is room to move the RETADDR to. This is 2392// achieved by reserving an area the size of the argument delta right after the 2393// original REtADDR, but before the saved framepointer or the spilled registers 2394// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2395// stack layout: 2396// arg1 2397// arg2 2398// RETADDR 2399// [ new RETADDR 2400// move area ] 2401// (possible EBP) 2402// ESI 2403// EDI 2404// local1 .. 2405 2406/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2407/// for a 16 byte align requirement. 2408unsigned 2409X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2410 SelectionDAG& DAG) const { 2411 MachineFunction &MF = DAG.getMachineFunction(); 2412 const TargetMachine &TM = MF.getTarget(); 2413 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2414 unsigned StackAlignment = TFI.getStackAlignment(); 2415 uint64_t AlignMask = StackAlignment - 1; 2416 int64_t Offset = StackSize; 2417 uint64_t SlotSize = TD->getPointerSize(); 2418 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2419 // Number smaller than 12 so just add the difference. 2420 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2421 } else { 2422 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2423 Offset = ((~AlignMask) & Offset) + StackAlignment + 2424 (StackAlignment-SlotSize); 2425 } 2426 return Offset; 2427} 2428 2429/// MatchingStackOffset - Return true if the given stack call argument is 2430/// already available in the same position (relatively) of the caller's 2431/// incoming argument stack. 2432static 2433bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2434 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2435 const X86InstrInfo *TII) { 2436 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2437 int FI = INT_MAX; 2438 if (Arg.getOpcode() == ISD::CopyFromReg) { 2439 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2440 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2441 return false; 2442 MachineInstr *Def = MRI->getVRegDef(VR); 2443 if (!Def) 2444 return false; 2445 if (!Flags.isByVal()) { 2446 if (!TII->isLoadFromStackSlot(Def, FI)) 2447 return false; 2448 } else { 2449 unsigned Opcode = Def->getOpcode(); 2450 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2451 Def->getOperand(1).isFI()) { 2452 FI = Def->getOperand(1).getIndex(); 2453 Bytes = Flags.getByValSize(); 2454 } else 2455 return false; 2456 } 2457 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2458 if (Flags.isByVal()) 2459 // ByVal argument is passed in as a pointer but it's now being 2460 // dereferenced. e.g. 2461 // define @foo(%struct.X* %A) { 2462 // tail call @bar(%struct.X* byval %A) 2463 // } 2464 return false; 2465 SDValue Ptr = Ld->getBasePtr(); 2466 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2467 if (!FINode) 2468 return false; 2469 FI = FINode->getIndex(); 2470 } else 2471 return false; 2472 2473 assert(FI != INT_MAX); 2474 if (!MFI->isFixedObjectIndex(FI)) 2475 return false; 2476 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2477} 2478 2479/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2480/// for tail call optimization. Targets which want to do tail call 2481/// optimization should implement this function. 2482bool 2483X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2484 CallingConv::ID CalleeCC, 2485 bool isVarArg, 2486 bool isCalleeStructRet, 2487 bool isCallerStructRet, 2488 const SmallVectorImpl<ISD::OutputArg> &Outs, 2489 const SmallVectorImpl<SDValue> &OutVals, 2490 const SmallVectorImpl<ISD::InputArg> &Ins, 2491 SelectionDAG& DAG) const { 2492 if (!IsTailCallConvention(CalleeCC) && 2493 CalleeCC != CallingConv::C) 2494 return false; 2495 2496 // If -tailcallopt is specified, make fastcc functions tail-callable. 2497 const MachineFunction &MF = DAG.getMachineFunction(); 2498 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2499 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2500 bool CCMatch = CallerCC == CalleeCC; 2501 2502 if (GuaranteedTailCallOpt) { 2503 if (IsTailCallConvention(CalleeCC) && CCMatch) 2504 return true; 2505 return false; 2506 } 2507 2508 // Look for obvious safe cases to perform tail call optimization that do not 2509 // require ABI changes. This is what gcc calls sibcall. 2510 2511 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2512 // emit a special epilogue. 2513 if (RegInfo->needsStackRealignment(MF)) 2514 return false; 2515 2516 // Do not sibcall optimize vararg calls unless the call site is not passing 2517 // any arguments. 2518 if (isVarArg && !Outs.empty()) 2519 return false; 2520 2521 // Also avoid sibcall optimization if either caller or callee uses struct 2522 // return semantics. 2523 if (isCalleeStructRet || isCallerStructRet) 2524 return false; 2525 2526 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2527 // Therefore if it's not used by the call it is not safe to optimize this into 2528 // a sibcall. 2529 bool Unused = false; 2530 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2531 if (!Ins[i].Used) { 2532 Unused = true; 2533 break; 2534 } 2535 } 2536 if (Unused) { 2537 SmallVector<CCValAssign, 16> RVLocs; 2538 CCState CCInfo(CalleeCC, false, getTargetMachine(), 2539 RVLocs, *DAG.getContext()); 2540 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2541 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2542 CCValAssign &VA = RVLocs[i]; 2543 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2544 return false; 2545 } 2546 } 2547 2548 // If the calling conventions do not match, then we'd better make sure the 2549 // results are returned in the same way as what the caller expects. 2550 if (!CCMatch) { 2551 SmallVector<CCValAssign, 16> RVLocs1; 2552 CCState CCInfo1(CalleeCC, false, getTargetMachine(), 2553 RVLocs1, *DAG.getContext()); 2554 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2555 2556 SmallVector<CCValAssign, 16> RVLocs2; 2557 CCState CCInfo2(CallerCC, false, getTargetMachine(), 2558 RVLocs2, *DAG.getContext()); 2559 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2560 2561 if (RVLocs1.size() != RVLocs2.size()) 2562 return false; 2563 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2564 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2565 return false; 2566 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2567 return false; 2568 if (RVLocs1[i].isRegLoc()) { 2569 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2570 return false; 2571 } else { 2572 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2573 return false; 2574 } 2575 } 2576 } 2577 2578 // If the callee takes no arguments then go on to check the results of the 2579 // call. 2580 if (!Outs.empty()) { 2581 // Check if stack adjustment is needed. For now, do not do this if any 2582 // argument is passed on the stack. 2583 SmallVector<CCValAssign, 16> ArgLocs; 2584 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(), 2585 ArgLocs, *DAG.getContext()); 2586 2587 // Allocate shadow area for Win64 2588 if (Subtarget->isTargetWin64()) { 2589 CCInfo.AllocateStack(32, 8); 2590 } 2591 2592 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2593 if (CCInfo.getNextStackOffset()) { 2594 MachineFunction &MF = DAG.getMachineFunction(); 2595 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2596 return false; 2597 2598 // Check if the arguments are already laid out in the right way as 2599 // the caller's fixed stack objects. 2600 MachineFrameInfo *MFI = MF.getFrameInfo(); 2601 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2602 const X86InstrInfo *TII = 2603 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2604 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2605 CCValAssign &VA = ArgLocs[i]; 2606 SDValue Arg = OutVals[i]; 2607 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2608 if (VA.getLocInfo() == CCValAssign::Indirect) 2609 return false; 2610 if (!VA.isRegLoc()) { 2611 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2612 MFI, MRI, TII)) 2613 return false; 2614 } 2615 } 2616 } 2617 2618 // If the tailcall address may be in a register, then make sure it's 2619 // possible to register allocate for it. In 32-bit, the call address can 2620 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2621 // callee-saved registers are restored. These happen to be the same 2622 // registers used to pass 'inreg' arguments so watch out for those. 2623 if (!Subtarget->is64Bit() && 2624 !isa<GlobalAddressSDNode>(Callee) && 2625 !isa<ExternalSymbolSDNode>(Callee)) { 2626 unsigned NumInRegs = 0; 2627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2628 CCValAssign &VA = ArgLocs[i]; 2629 if (!VA.isRegLoc()) 2630 continue; 2631 unsigned Reg = VA.getLocReg(); 2632 switch (Reg) { 2633 default: break; 2634 case X86::EAX: case X86::EDX: case X86::ECX: 2635 if (++NumInRegs == 3) 2636 return false; 2637 break; 2638 } 2639 } 2640 } 2641 } 2642 2643 // An stdcall caller is expected to clean up its arguments; the callee 2644 // isn't going to do that. 2645 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2646 return false; 2647 2648 return true; 2649} 2650 2651FastISel * 2652X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2653 return X86::createFastISel(funcInfo); 2654} 2655 2656 2657//===----------------------------------------------------------------------===// 2658// Other Lowering Hooks 2659//===----------------------------------------------------------------------===// 2660 2661static bool MayFoldLoad(SDValue Op) { 2662 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2663} 2664 2665static bool MayFoldIntoStore(SDValue Op) { 2666 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2667} 2668 2669static bool isTargetShuffle(unsigned Opcode) { 2670 switch(Opcode) { 2671 default: return false; 2672 case X86ISD::PSHUFD: 2673 case X86ISD::PSHUFHW: 2674 case X86ISD::PSHUFLW: 2675 case X86ISD::SHUFPD: 2676 case X86ISD::PALIGN: 2677 case X86ISD::SHUFPS: 2678 case X86ISD::MOVLHPS: 2679 case X86ISD::MOVLHPD: 2680 case X86ISD::MOVHLPS: 2681 case X86ISD::MOVLPS: 2682 case X86ISD::MOVLPD: 2683 case X86ISD::MOVSHDUP: 2684 case X86ISD::MOVSLDUP: 2685 case X86ISD::MOVDDUP: 2686 case X86ISD::MOVSS: 2687 case X86ISD::MOVSD: 2688 case X86ISD::UNPCKLPS: 2689 case X86ISD::UNPCKLPD: 2690 case X86ISD::VUNPCKLPS: 2691 case X86ISD::VUNPCKLPD: 2692 case X86ISD::VUNPCKLPSY: 2693 case X86ISD::VUNPCKLPDY: 2694 case X86ISD::PUNPCKLWD: 2695 case X86ISD::PUNPCKLBW: 2696 case X86ISD::PUNPCKLDQ: 2697 case X86ISD::PUNPCKLQDQ: 2698 case X86ISD::UNPCKHPS: 2699 case X86ISD::UNPCKHPD: 2700 case X86ISD::PUNPCKHWD: 2701 case X86ISD::PUNPCKHBW: 2702 case X86ISD::PUNPCKHDQ: 2703 case X86ISD::PUNPCKHQDQ: 2704 return true; 2705 } 2706 return false; 2707} 2708 2709static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2710 SDValue V1, SelectionDAG &DAG) { 2711 switch(Opc) { 2712 default: llvm_unreachable("Unknown x86 shuffle node"); 2713 case X86ISD::MOVSHDUP: 2714 case X86ISD::MOVSLDUP: 2715 case X86ISD::MOVDDUP: 2716 return DAG.getNode(Opc, dl, VT, V1); 2717 } 2718 2719 return SDValue(); 2720} 2721 2722static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2723 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2724 switch(Opc) { 2725 default: llvm_unreachable("Unknown x86 shuffle node"); 2726 case X86ISD::PSHUFD: 2727 case X86ISD::PSHUFHW: 2728 case X86ISD::PSHUFLW: 2729 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2730 } 2731 2732 return SDValue(); 2733} 2734 2735static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2736 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2737 switch(Opc) { 2738 default: llvm_unreachable("Unknown x86 shuffle node"); 2739 case X86ISD::PALIGN: 2740 case X86ISD::SHUFPD: 2741 case X86ISD::SHUFPS: 2742 return DAG.getNode(Opc, dl, VT, V1, V2, 2743 DAG.getConstant(TargetMask, MVT::i8)); 2744 } 2745 return SDValue(); 2746} 2747 2748static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2749 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2750 switch(Opc) { 2751 default: llvm_unreachable("Unknown x86 shuffle node"); 2752 case X86ISD::MOVLHPS: 2753 case X86ISD::MOVLHPD: 2754 case X86ISD::MOVHLPS: 2755 case X86ISD::MOVLPS: 2756 case X86ISD::MOVLPD: 2757 case X86ISD::MOVSS: 2758 case X86ISD::MOVSD: 2759 case X86ISD::UNPCKLPS: 2760 case X86ISD::UNPCKLPD: 2761 case X86ISD::VUNPCKLPS: 2762 case X86ISD::VUNPCKLPD: 2763 case X86ISD::VUNPCKLPSY: 2764 case X86ISD::VUNPCKLPDY: 2765 case X86ISD::PUNPCKLWD: 2766 case X86ISD::PUNPCKLBW: 2767 case X86ISD::PUNPCKLDQ: 2768 case X86ISD::PUNPCKLQDQ: 2769 case X86ISD::UNPCKHPS: 2770 case X86ISD::UNPCKHPD: 2771 case X86ISD::PUNPCKHWD: 2772 case X86ISD::PUNPCKHBW: 2773 case X86ISD::PUNPCKHDQ: 2774 case X86ISD::PUNPCKHQDQ: 2775 return DAG.getNode(Opc, dl, VT, V1, V2); 2776 } 2777 return SDValue(); 2778} 2779 2780SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2781 MachineFunction &MF = DAG.getMachineFunction(); 2782 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2783 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2784 2785 if (ReturnAddrIndex == 0) { 2786 // Set up a frame object for the return address. 2787 uint64_t SlotSize = TD->getPointerSize(); 2788 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2789 false); 2790 FuncInfo->setRAIndex(ReturnAddrIndex); 2791 } 2792 2793 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2794} 2795 2796 2797bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2798 bool hasSymbolicDisplacement) { 2799 // Offset should fit into 32 bit immediate field. 2800 if (!isInt<32>(Offset)) 2801 return false; 2802 2803 // If we don't have a symbolic displacement - we don't have any extra 2804 // restrictions. 2805 if (!hasSymbolicDisplacement) 2806 return true; 2807 2808 // FIXME: Some tweaks might be needed for medium code model. 2809 if (M != CodeModel::Small && M != CodeModel::Kernel) 2810 return false; 2811 2812 // For small code model we assume that latest object is 16MB before end of 31 2813 // bits boundary. We may also accept pretty large negative constants knowing 2814 // that all objects are in the positive half of address space. 2815 if (M == CodeModel::Small && Offset < 16*1024*1024) 2816 return true; 2817 2818 // For kernel code model we know that all object resist in the negative half 2819 // of 32bits address space. We may not accept negative offsets, since they may 2820 // be just off and we may accept pretty large positive ones. 2821 if (M == CodeModel::Kernel && Offset > 0) 2822 return true; 2823 2824 return false; 2825} 2826 2827/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 2828/// specific condition code, returning the condition code and the LHS/RHS of the 2829/// comparison to make. 2830static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 2831 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 2832 if (!isFP) { 2833 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 2834 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 2835 // X > -1 -> X == 0, jump !sign. 2836 RHS = DAG.getConstant(0, RHS.getValueType()); 2837 return X86::COND_NS; 2838 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 2839 // X < 0 -> X == 0, jump on sign. 2840 return X86::COND_S; 2841 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 2842 // X < 1 -> X <= 0 2843 RHS = DAG.getConstant(0, RHS.getValueType()); 2844 return X86::COND_LE; 2845 } 2846 } 2847 2848 switch (SetCCOpcode) { 2849 default: llvm_unreachable("Invalid integer condition!"); 2850 case ISD::SETEQ: return X86::COND_E; 2851 case ISD::SETGT: return X86::COND_G; 2852 case ISD::SETGE: return X86::COND_GE; 2853 case ISD::SETLT: return X86::COND_L; 2854 case ISD::SETLE: return X86::COND_LE; 2855 case ISD::SETNE: return X86::COND_NE; 2856 case ISD::SETULT: return X86::COND_B; 2857 case ISD::SETUGT: return X86::COND_A; 2858 case ISD::SETULE: return X86::COND_BE; 2859 case ISD::SETUGE: return X86::COND_AE; 2860 } 2861 } 2862 2863 // First determine if it is required or is profitable to flip the operands. 2864 2865 // If LHS is a foldable load, but RHS is not, flip the condition. 2866 if (ISD::isNON_EXTLoad(LHS.getNode()) && 2867 !ISD::isNON_EXTLoad(RHS.getNode())) { 2868 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 2869 std::swap(LHS, RHS); 2870 } 2871 2872 switch (SetCCOpcode) { 2873 default: break; 2874 case ISD::SETOLT: 2875 case ISD::SETOLE: 2876 case ISD::SETUGT: 2877 case ISD::SETUGE: 2878 std::swap(LHS, RHS); 2879 break; 2880 } 2881 2882 // On a floating point condition, the flags are set as follows: 2883 // ZF PF CF op 2884 // 0 | 0 | 0 | X > Y 2885 // 0 | 0 | 1 | X < Y 2886 // 1 | 0 | 0 | X == Y 2887 // 1 | 1 | 1 | unordered 2888 switch (SetCCOpcode) { 2889 default: llvm_unreachable("Condcode should be pre-legalized away"); 2890 case ISD::SETUEQ: 2891 case ISD::SETEQ: return X86::COND_E; 2892 case ISD::SETOLT: // flipped 2893 case ISD::SETOGT: 2894 case ISD::SETGT: return X86::COND_A; 2895 case ISD::SETOLE: // flipped 2896 case ISD::SETOGE: 2897 case ISD::SETGE: return X86::COND_AE; 2898 case ISD::SETUGT: // flipped 2899 case ISD::SETULT: 2900 case ISD::SETLT: return X86::COND_B; 2901 case ISD::SETUGE: // flipped 2902 case ISD::SETULE: 2903 case ISD::SETLE: return X86::COND_BE; 2904 case ISD::SETONE: 2905 case ISD::SETNE: return X86::COND_NE; 2906 case ISD::SETUO: return X86::COND_P; 2907 case ISD::SETO: return X86::COND_NP; 2908 case ISD::SETOEQ: 2909 case ISD::SETUNE: return X86::COND_INVALID; 2910 } 2911} 2912 2913/// hasFPCMov - is there a floating point cmov for the specific X86 condition 2914/// code. Current x86 isa includes the following FP cmov instructions: 2915/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 2916static bool hasFPCMov(unsigned X86CC) { 2917 switch (X86CC) { 2918 default: 2919 return false; 2920 case X86::COND_B: 2921 case X86::COND_BE: 2922 case X86::COND_E: 2923 case X86::COND_P: 2924 case X86::COND_A: 2925 case X86::COND_AE: 2926 case X86::COND_NE: 2927 case X86::COND_NP: 2928 return true; 2929 } 2930} 2931 2932/// isFPImmLegal - Returns true if the target can instruction select the 2933/// specified FP immediate natively. If false, the legalizer will 2934/// materialize the FP immediate as a load from a constant pool. 2935bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 2936 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 2937 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 2938 return true; 2939 } 2940 return false; 2941} 2942 2943/// isUndefOrInRange - Return true if Val is undef or if its value falls within 2944/// the specified range (L, H]. 2945static bool isUndefOrInRange(int Val, int Low, int Hi) { 2946 return (Val < 0) || (Val >= Low && Val < Hi); 2947} 2948 2949/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 2950/// specified value. 2951static bool isUndefOrEqual(int Val, int CmpVal) { 2952 if (Val < 0 || Val == CmpVal) 2953 return true; 2954 return false; 2955} 2956 2957/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 2958/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 2959/// the second operand. 2960static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 2961 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 2962 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 2963 if (VT == MVT::v2f64 || VT == MVT::v2i64) 2964 return (Mask[0] < 2 && Mask[1] < 2); 2965 return false; 2966} 2967 2968bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 2969 SmallVector<int, 8> M; 2970 N->getMask(M); 2971 return ::isPSHUFDMask(M, N->getValueType(0)); 2972} 2973 2974/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 2975/// is suitable for input to PSHUFHW. 2976static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 2977 if (VT != MVT::v8i16) 2978 return false; 2979 2980 // Lower quadword copied in order or undef. 2981 for (int i = 0; i != 4; ++i) 2982 if (Mask[i] >= 0 && Mask[i] != i) 2983 return false; 2984 2985 // Upper quadword shuffled. 2986 for (int i = 4; i != 8; ++i) 2987 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 2988 return false; 2989 2990 return true; 2991} 2992 2993bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 2994 SmallVector<int, 8> M; 2995 N->getMask(M); 2996 return ::isPSHUFHWMask(M, N->getValueType(0)); 2997} 2998 2999/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3000/// is suitable for input to PSHUFLW. 3001static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3002 if (VT != MVT::v8i16) 3003 return false; 3004 3005 // Upper quadword copied in order. 3006 for (int i = 4; i != 8; ++i) 3007 if (Mask[i] >= 0 && Mask[i] != i) 3008 return false; 3009 3010 // Lower quadword shuffled. 3011 for (int i = 0; i != 4; ++i) 3012 if (Mask[i] >= 4) 3013 return false; 3014 3015 return true; 3016} 3017 3018bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3019 SmallVector<int, 8> M; 3020 N->getMask(M); 3021 return ::isPSHUFLWMask(M, N->getValueType(0)); 3022} 3023 3024/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3025/// is suitable for input to PALIGNR. 3026static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3027 bool hasSSSE3) { 3028 int i, e = VT.getVectorNumElements(); 3029 3030 // Do not handle v2i64 / v2f64 shuffles with palignr. 3031 if (e < 4 || !hasSSSE3) 3032 return false; 3033 3034 for (i = 0; i != e; ++i) 3035 if (Mask[i] >= 0) 3036 break; 3037 3038 // All undef, not a palignr. 3039 if (i == e) 3040 return false; 3041 3042 // Determine if it's ok to perform a palignr with only the LHS, since we 3043 // don't have access to the actual shuffle elements to see if RHS is undef. 3044 bool Unary = Mask[i] < (int)e; 3045 bool NeedsUnary = false; 3046 3047 int s = Mask[i] - i; 3048 3049 // Check the rest of the elements to see if they are consecutive. 3050 for (++i; i != e; ++i) { 3051 int m = Mask[i]; 3052 if (m < 0) 3053 continue; 3054 3055 Unary = Unary && (m < (int)e); 3056 NeedsUnary = NeedsUnary || (m < s); 3057 3058 if (NeedsUnary && !Unary) 3059 return false; 3060 if (Unary && m != ((s+i) & (e-1))) 3061 return false; 3062 if (!Unary && m != (s+i)) 3063 return false; 3064 } 3065 return true; 3066} 3067 3068bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) { 3069 SmallVector<int, 8> M; 3070 N->getMask(M); 3071 return ::isPALIGNRMask(M, N->getValueType(0), true); 3072} 3073 3074/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3075/// specifies a shuffle of elements that is suitable for input to SHUFP*. 3076static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3077 int NumElems = VT.getVectorNumElements(); 3078 if (NumElems != 2 && NumElems != 4) 3079 return false; 3080 3081 int Half = NumElems / 2; 3082 for (int i = 0; i < Half; ++i) 3083 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3084 return false; 3085 for (int i = Half; i < NumElems; ++i) 3086 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3087 return false; 3088 3089 return true; 3090} 3091 3092bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3093 SmallVector<int, 8> M; 3094 N->getMask(M); 3095 return ::isSHUFPMask(M, N->getValueType(0)); 3096} 3097 3098/// isCommutedSHUFP - Returns true if the shuffle mask is exactly 3099/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3100/// half elements to come from vector 1 (which would equal the dest.) and 3101/// the upper half to come from vector 2. 3102static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3103 int NumElems = VT.getVectorNumElements(); 3104 3105 if (NumElems != 2 && NumElems != 4) 3106 return false; 3107 3108 int Half = NumElems / 2; 3109 for (int i = 0; i < Half; ++i) 3110 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3111 return false; 3112 for (int i = Half; i < NumElems; ++i) 3113 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3114 return false; 3115 return true; 3116} 3117 3118static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3119 SmallVector<int, 8> M; 3120 N->getMask(M); 3121 return isCommutedSHUFPMask(M, N->getValueType(0)); 3122} 3123 3124/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3125/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3126bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3127 if (N->getValueType(0).getVectorNumElements() != 4) 3128 return false; 3129 3130 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3131 return isUndefOrEqual(N->getMaskElt(0), 6) && 3132 isUndefOrEqual(N->getMaskElt(1), 7) && 3133 isUndefOrEqual(N->getMaskElt(2), 2) && 3134 isUndefOrEqual(N->getMaskElt(3), 3); 3135} 3136 3137/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3138/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3139/// <2, 3, 2, 3> 3140bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3141 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3142 3143 if (NumElems != 4) 3144 return false; 3145 3146 return isUndefOrEqual(N->getMaskElt(0), 2) && 3147 isUndefOrEqual(N->getMaskElt(1), 3) && 3148 isUndefOrEqual(N->getMaskElt(2), 2) && 3149 isUndefOrEqual(N->getMaskElt(3), 3); 3150} 3151 3152/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3153/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3154bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3155 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3156 3157 if (NumElems != 2 && NumElems != 4) 3158 return false; 3159 3160 for (unsigned i = 0; i < NumElems/2; ++i) 3161 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3162 return false; 3163 3164 for (unsigned i = NumElems/2; i < NumElems; ++i) 3165 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3166 return false; 3167 3168 return true; 3169} 3170 3171/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3172/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3173bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3174 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3175 3176 if ((NumElems != 2 && NumElems != 4) 3177 || N->getValueType(0).getSizeInBits() > 128) 3178 return false; 3179 3180 for (unsigned i = 0; i < NumElems/2; ++i) 3181 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3182 return false; 3183 3184 for (unsigned i = 0; i < NumElems/2; ++i) 3185 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3186 return false; 3187 3188 return true; 3189} 3190 3191/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3192/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3193static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3194 bool V2IsSplat = false) { 3195 int NumElts = VT.getVectorNumElements(); 3196 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3197 return false; 3198 3199 // Handle vector lengths > 128 bits. Define a "section" as a set of 3200 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit 3201 // sections. 3202 unsigned NumSections = VT.getSizeInBits() / 128; 3203 if (NumSections == 0 ) NumSections = 1; // Handle MMX 3204 unsigned NumSectionElts = NumElts / NumSections; 3205 3206 unsigned Start = 0; 3207 unsigned End = NumSectionElts; 3208 for (unsigned s = 0; s < NumSections; ++s) { 3209 for (unsigned i = Start, j = s * NumSectionElts; 3210 i != End; 3211 i += 2, ++j) { 3212 int BitI = Mask[i]; 3213 int BitI1 = Mask[i+1]; 3214 if (!isUndefOrEqual(BitI, j)) 3215 return false; 3216 if (V2IsSplat) { 3217 if (!isUndefOrEqual(BitI1, NumElts)) 3218 return false; 3219 } else { 3220 if (!isUndefOrEqual(BitI1, j + NumElts)) 3221 return false; 3222 } 3223 } 3224 // Process the next 128 bits. 3225 Start += NumSectionElts; 3226 End += NumSectionElts; 3227 } 3228 3229 return true; 3230} 3231 3232bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3233 SmallVector<int, 8> M; 3234 N->getMask(M); 3235 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat); 3236} 3237 3238/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3239/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3240static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3241 bool V2IsSplat = false) { 3242 int NumElts = VT.getVectorNumElements(); 3243 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 3244 return false; 3245 3246 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) { 3247 int BitI = Mask[i]; 3248 int BitI1 = Mask[i+1]; 3249 if (!isUndefOrEqual(BitI, j + NumElts/2)) 3250 return false; 3251 if (V2IsSplat) { 3252 if (isUndefOrEqual(BitI1, NumElts)) 3253 return false; 3254 } else { 3255 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts)) 3256 return false; 3257 } 3258 } 3259 return true; 3260} 3261 3262bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) { 3263 SmallVector<int, 8> M; 3264 N->getMask(M); 3265 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat); 3266} 3267 3268/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3269/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3270/// <0, 0, 1, 1> 3271static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3272 int NumElems = VT.getVectorNumElements(); 3273 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3274 return false; 3275 3276 // Handle vector lengths > 128 bits. Define a "section" as a set of 3277 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit 3278 // sections. 3279 unsigned NumSections = VT.getSizeInBits() / 128; 3280 if (NumSections == 0 ) NumSections = 1; // Handle MMX 3281 unsigned NumSectionElts = NumElems / NumSections; 3282 3283 for (unsigned s = 0; s < NumSections; ++s) { 3284 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts; 3285 i != NumSectionElts * (s + 1); 3286 i += 2, ++j) { 3287 int BitI = Mask[i]; 3288 int BitI1 = Mask[i+1]; 3289 3290 if (!isUndefOrEqual(BitI, j)) 3291 return false; 3292 if (!isUndefOrEqual(BitI1, j)) 3293 return false; 3294 } 3295 } 3296 3297 return true; 3298} 3299 3300bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3301 SmallVector<int, 8> M; 3302 N->getMask(M); 3303 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3304} 3305 3306/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3307/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3308/// <2, 2, 3, 3> 3309static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3310 int NumElems = VT.getVectorNumElements(); 3311 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3312 return false; 3313 3314 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3315 int BitI = Mask[i]; 3316 int BitI1 = Mask[i+1]; 3317 if (!isUndefOrEqual(BitI, j)) 3318 return false; 3319 if (!isUndefOrEqual(BitI1, j)) 3320 return false; 3321 } 3322 return true; 3323} 3324 3325bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3326 SmallVector<int, 8> M; 3327 N->getMask(M); 3328 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3329} 3330 3331/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3332/// specifies a shuffle of elements that is suitable for input to MOVSS, 3333/// MOVSD, and MOVD, i.e. setting the lowest element. 3334static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3335 if (VT.getVectorElementType().getSizeInBits() < 32) 3336 return false; 3337 3338 int NumElts = VT.getVectorNumElements(); 3339 3340 if (!isUndefOrEqual(Mask[0], NumElts)) 3341 return false; 3342 3343 for (int i = 1; i < NumElts; ++i) 3344 if (!isUndefOrEqual(Mask[i], i)) 3345 return false; 3346 3347 return true; 3348} 3349 3350bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3351 SmallVector<int, 8> M; 3352 N->getMask(M); 3353 return ::isMOVLMask(M, N->getValueType(0)); 3354} 3355 3356/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3357/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3358/// element of vector 2 and the other elements to come from vector 1 in order. 3359static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3360 bool V2IsSplat = false, bool V2IsUndef = false) { 3361 int NumOps = VT.getVectorNumElements(); 3362 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3363 return false; 3364 3365 if (!isUndefOrEqual(Mask[0], 0)) 3366 return false; 3367 3368 for (int i = 1; i < NumOps; ++i) 3369 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3370 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3371 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3372 return false; 3373 3374 return true; 3375} 3376 3377static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3378 bool V2IsUndef = false) { 3379 SmallVector<int, 8> M; 3380 N->getMask(M); 3381 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3382} 3383 3384/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3385/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3386bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) { 3387 if (N->getValueType(0).getVectorNumElements() != 4) 3388 return false; 3389 3390 // Expect 1, 1, 3, 3 3391 for (unsigned i = 0; i < 2; ++i) { 3392 int Elt = N->getMaskElt(i); 3393 if (Elt >= 0 && Elt != 1) 3394 return false; 3395 } 3396 3397 bool HasHi = false; 3398 for (unsigned i = 2; i < 4; ++i) { 3399 int Elt = N->getMaskElt(i); 3400 if (Elt >= 0 && Elt != 3) 3401 return false; 3402 if (Elt == 3) 3403 HasHi = true; 3404 } 3405 // Don't use movshdup if it can be done with a shufps. 3406 // FIXME: verify that matching u, u, 3, 3 is what we want. 3407 return HasHi; 3408} 3409 3410/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3411/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3412bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) { 3413 if (N->getValueType(0).getVectorNumElements() != 4) 3414 return false; 3415 3416 // Expect 0, 0, 2, 2 3417 for (unsigned i = 0; i < 2; ++i) 3418 if (N->getMaskElt(i) > 0) 3419 return false; 3420 3421 bool HasHi = false; 3422 for (unsigned i = 2; i < 4; ++i) { 3423 int Elt = N->getMaskElt(i); 3424 if (Elt >= 0 && Elt != 2) 3425 return false; 3426 if (Elt == 2) 3427 HasHi = true; 3428 } 3429 // Don't use movsldup if it can be done with a shufps. 3430 return HasHi; 3431} 3432 3433/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3434/// specifies a shuffle of elements that is suitable for input to MOVDDUP. 3435bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 3436 int e = N->getValueType(0).getVectorNumElements() / 2; 3437 3438 for (int i = 0; i < e; ++i) 3439 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3440 return false; 3441 for (int i = 0; i < e; ++i) 3442 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 3443 return false; 3444 return true; 3445} 3446 3447/// isVEXTRACTF128Index - Return true if the specified 3448/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 3449/// suitable for input to VEXTRACTF128. 3450bool X86::isVEXTRACTF128Index(SDNode *N) { 3451 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3452 return false; 3453 3454 // The index should be aligned on a 128-bit boundary. 3455 uint64_t Index = 3456 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3457 3458 unsigned VL = N->getValueType(0).getVectorNumElements(); 3459 unsigned VBits = N->getValueType(0).getSizeInBits(); 3460 unsigned ElSize = VBits / VL; 3461 bool Result = (Index * ElSize) % 128 == 0; 3462 3463 return Result; 3464} 3465 3466/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 3467/// operand specifies a subvector insert that is suitable for input to 3468/// VINSERTF128. 3469bool X86::isVINSERTF128Index(SDNode *N) { 3470 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3471 return false; 3472 3473 // The index should be aligned on a 128-bit boundary. 3474 uint64_t Index = 3475 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3476 3477 unsigned VL = N->getValueType(0).getVectorNumElements(); 3478 unsigned VBits = N->getValueType(0).getSizeInBits(); 3479 unsigned ElSize = VBits / VL; 3480 bool Result = (Index * ElSize) % 128 == 0; 3481 3482 return Result; 3483} 3484 3485/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 3486/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 3487unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 3488 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3489 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 3490 3491 unsigned Shift = (NumOperands == 4) ? 2 : 1; 3492 unsigned Mask = 0; 3493 for (int i = 0; i < NumOperands; ++i) { 3494 int Val = SVOp->getMaskElt(NumOperands-i-1); 3495 if (Val < 0) Val = 0; 3496 if (Val >= NumOperands) Val -= NumOperands; 3497 Mask |= Val; 3498 if (i != NumOperands - 1) 3499 Mask <<= Shift; 3500 } 3501 return Mask; 3502} 3503 3504/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 3505/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 3506unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 3507 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3508 unsigned Mask = 0; 3509 // 8 nodes, but we only care about the last 4. 3510 for (unsigned i = 7; i >= 4; --i) { 3511 int Val = SVOp->getMaskElt(i); 3512 if (Val >= 0) 3513 Mask |= (Val - 4); 3514 if (i != 4) 3515 Mask <<= 2; 3516 } 3517 return Mask; 3518} 3519 3520/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 3521/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 3522unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 3523 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3524 unsigned Mask = 0; 3525 // 8 nodes, but we only care about the first 4. 3526 for (int i = 3; i >= 0; --i) { 3527 int Val = SVOp->getMaskElt(i); 3528 if (Val >= 0) 3529 Mask |= Val; 3530 if (i != 0) 3531 Mask <<= 2; 3532 } 3533 return Mask; 3534} 3535 3536/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 3537/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 3538unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 3539 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3540 EVT VVT = N->getValueType(0); 3541 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 3542 int Val = 0; 3543 3544 unsigned i, e; 3545 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 3546 Val = SVOp->getMaskElt(i); 3547 if (Val >= 0) 3548 break; 3549 } 3550 return (Val - i) * EltSize; 3551} 3552 3553/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 3554/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 3555/// instructions. 3556unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 3557 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 3558 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 3559 3560 uint64_t Index = 3561 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 3562 3563 EVT VecVT = N->getOperand(0).getValueType(); 3564 EVT ElVT = VecVT.getVectorElementType(); 3565 3566 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3567 3568 return Index / NumElemsPerChunk; 3569} 3570 3571/// getInsertVINSERTF128Immediate - Return the appropriate immediate 3572/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 3573/// instructions. 3574unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 3575 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 3576 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 3577 3578 uint64_t Index = 3579 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 3580 3581 EVT VecVT = N->getValueType(0); 3582 EVT ElVT = VecVT.getVectorElementType(); 3583 3584 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 3585 3586 return Index / NumElemsPerChunk; 3587} 3588 3589/// isZeroNode - Returns true if Elt is a constant zero or a floating point 3590/// constant +0.0. 3591bool X86::isZeroNode(SDValue Elt) { 3592 return ((isa<ConstantSDNode>(Elt) && 3593 cast<ConstantSDNode>(Elt)->isNullValue()) || 3594 (isa<ConstantFPSDNode>(Elt) && 3595 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 3596} 3597 3598/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 3599/// their permute mask. 3600static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 3601 SelectionDAG &DAG) { 3602 EVT VT = SVOp->getValueType(0); 3603 unsigned NumElems = VT.getVectorNumElements(); 3604 SmallVector<int, 8> MaskVec; 3605 3606 for (unsigned i = 0; i != NumElems; ++i) { 3607 int idx = SVOp->getMaskElt(i); 3608 if (idx < 0) 3609 MaskVec.push_back(idx); 3610 else if (idx < (int)NumElems) 3611 MaskVec.push_back(idx + NumElems); 3612 else 3613 MaskVec.push_back(idx - NumElems); 3614 } 3615 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 3616 SVOp->getOperand(0), &MaskVec[0]); 3617} 3618 3619/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3620/// the two vector operands have swapped position. 3621static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 3622 unsigned NumElems = VT.getVectorNumElements(); 3623 for (unsigned i = 0; i != NumElems; ++i) { 3624 int idx = Mask[i]; 3625 if (idx < 0) 3626 continue; 3627 else if (idx < (int)NumElems) 3628 Mask[i] = idx + NumElems; 3629 else 3630 Mask[i] = idx - NumElems; 3631 } 3632} 3633 3634/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 3635/// match movhlps. The lower half elements should come from upper half of 3636/// V1 (and in order), and the upper half elements should come from the upper 3637/// half of V2 (and in order). 3638static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 3639 if (Op->getValueType(0).getVectorNumElements() != 4) 3640 return false; 3641 for (unsigned i = 0, e = 2; i != e; ++i) 3642 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 3643 return false; 3644 for (unsigned i = 2; i != 4; ++i) 3645 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 3646 return false; 3647 return true; 3648} 3649 3650/// isScalarLoadToVector - Returns true if the node is a scalar load that 3651/// is promoted to a vector. It also returns the LoadSDNode by reference if 3652/// required. 3653static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 3654 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 3655 return false; 3656 N = N->getOperand(0).getNode(); 3657 if (!ISD::isNON_EXTLoad(N)) 3658 return false; 3659 if (LD) 3660 *LD = cast<LoadSDNode>(N); 3661 return true; 3662} 3663 3664/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 3665/// match movlp{s|d}. The lower half elements should come from lower half of 3666/// V1 (and in order), and the upper half elements should come from the upper 3667/// half of V2 (and in order). And since V1 will become the source of the 3668/// MOVLP, it must be either a vector load or a scalar load to vector. 3669static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 3670 ShuffleVectorSDNode *Op) { 3671 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 3672 return false; 3673 // Is V2 is a vector load, don't do this transformation. We will try to use 3674 // load folding shufps op. 3675 if (ISD::isNON_EXTLoad(V2)) 3676 return false; 3677 3678 unsigned NumElems = Op->getValueType(0).getVectorNumElements(); 3679 3680 if (NumElems != 2 && NumElems != 4) 3681 return false; 3682 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3683 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 3684 return false; 3685 for (unsigned i = NumElems/2; i != NumElems; ++i) 3686 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 3687 return false; 3688 return true; 3689} 3690 3691/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 3692/// all the same. 3693static bool isSplatVector(SDNode *N) { 3694 if (N->getOpcode() != ISD::BUILD_VECTOR) 3695 return false; 3696 3697 SDValue SplatValue = N->getOperand(0); 3698 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 3699 if (N->getOperand(i) != SplatValue) 3700 return false; 3701 return true; 3702} 3703 3704/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 3705/// to an zero vector. 3706/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 3707static bool isZeroShuffle(ShuffleVectorSDNode *N) { 3708 SDValue V1 = N->getOperand(0); 3709 SDValue V2 = N->getOperand(1); 3710 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3711 for (unsigned i = 0; i != NumElems; ++i) { 3712 int Idx = N->getMaskElt(i); 3713 if (Idx >= (int)NumElems) { 3714 unsigned Opc = V2.getOpcode(); 3715 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 3716 continue; 3717 if (Opc != ISD::BUILD_VECTOR || 3718 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 3719 return false; 3720 } else if (Idx >= 0) { 3721 unsigned Opc = V1.getOpcode(); 3722 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 3723 continue; 3724 if (Opc != ISD::BUILD_VECTOR || 3725 !X86::isZeroNode(V1.getOperand(Idx))) 3726 return false; 3727 } 3728 } 3729 return true; 3730} 3731 3732/// getZeroVector - Returns a vector of specified type with all zero elements. 3733/// 3734static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG, 3735 DebugLoc dl) { 3736 assert(VT.isVector() && "Expected a vector type"); 3737 3738 // Always build SSE zero vectors as <4 x i32> bitcasted 3739 // to their dest type. This ensures they get CSE'd. 3740 SDValue Vec; 3741 if (VT.getSizeInBits() == 128) { // SSE 3742 if (HasSSE2) { // SSE2 3743 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 3744 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3745 } else { // SSE1 3746 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3747 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 3748 } 3749 } else if (VT.getSizeInBits() == 256) { // AVX 3750 // 256-bit logic and arithmetic instructions in AVX are 3751 // all floating-point, no support for integer ops. Default 3752 // to emitting fp zeroed vectors then. 3753 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 3754 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 3755 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 3756 } 3757 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3758} 3759 3760/// getOnesVector - Returns a vector of specified type with all bits set. 3761/// 3762static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) { 3763 assert(VT.isVector() && "Expected a vector type"); 3764 3765 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest 3766 // type. This ensures they get CSE'd. 3767 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 3768 SDValue Vec; 3769 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 3770 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 3771} 3772 3773 3774/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 3775/// that point to V2 points to its first element. 3776static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 3777 EVT VT = SVOp->getValueType(0); 3778 unsigned NumElems = VT.getVectorNumElements(); 3779 3780 bool Changed = false; 3781 SmallVector<int, 8> MaskVec; 3782 SVOp->getMask(MaskVec); 3783 3784 for (unsigned i = 0; i != NumElems; ++i) { 3785 if (MaskVec[i] > (int)NumElems) { 3786 MaskVec[i] = NumElems; 3787 Changed = true; 3788 } 3789 } 3790 if (Changed) 3791 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 3792 SVOp->getOperand(1), &MaskVec[0]); 3793 return SDValue(SVOp, 0); 3794} 3795 3796/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 3797/// operation of specified width. 3798static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3799 SDValue V2) { 3800 unsigned NumElems = VT.getVectorNumElements(); 3801 SmallVector<int, 8> Mask; 3802 Mask.push_back(NumElems); 3803 for (unsigned i = 1; i != NumElems; ++i) 3804 Mask.push_back(i); 3805 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3806} 3807 3808/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 3809static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3810 SDValue V2) { 3811 unsigned NumElems = VT.getVectorNumElements(); 3812 SmallVector<int, 8> Mask; 3813 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 3814 Mask.push_back(i); 3815 Mask.push_back(i + NumElems); 3816 } 3817 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3818} 3819 3820/// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation. 3821static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 3822 SDValue V2) { 3823 unsigned NumElems = VT.getVectorNumElements(); 3824 unsigned Half = NumElems/2; 3825 SmallVector<int, 8> Mask; 3826 for (unsigned i = 0; i != Half; ++i) { 3827 Mask.push_back(i + Half); 3828 Mask.push_back(i + NumElems + Half); 3829 } 3830 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 3831} 3832 3833/// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32. 3834static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 3835 EVT PVT = MVT::v4f32; 3836 EVT VT = SV->getValueType(0); 3837 DebugLoc dl = SV->getDebugLoc(); 3838 SDValue V1 = SV->getOperand(0); 3839 int NumElems = VT.getVectorNumElements(); 3840 int EltNo = SV->getSplatIndex(); 3841 3842 // unpack elements to the correct location 3843 while (NumElems > 4) { 3844 if (EltNo < NumElems/2) { 3845 V1 = getUnpackl(DAG, dl, VT, V1, V1); 3846 } else { 3847 V1 = getUnpackh(DAG, dl, VT, V1, V1); 3848 EltNo -= NumElems/2; 3849 } 3850 NumElems >>= 1; 3851 } 3852 3853 // Perform the splat. 3854 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 3855 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1); 3856 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]); 3857 return DAG.getNode(ISD::BITCAST, dl, VT, V1); 3858} 3859 3860/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 3861/// vector of zero or undef vector. This produces a shuffle where the low 3862/// element of V2 is swizzled into the zero/undef vector, landing at element 3863/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 3864static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 3865 bool isZero, bool HasSSE2, 3866 SelectionDAG &DAG) { 3867 EVT VT = V2.getValueType(); 3868 SDValue V1 = isZero 3869 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 3870 unsigned NumElems = VT.getVectorNumElements(); 3871 SmallVector<int, 16> MaskVec; 3872 for (unsigned i = 0; i != NumElems; ++i) 3873 // If this is the insertion idx, put the low elt of V2 here. 3874 MaskVec.push_back(i == Idx ? NumElems : i); 3875 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 3876} 3877 3878/// getShuffleScalarElt - Returns the scalar element that will make up the ith 3879/// element of the result of the vector shuffle. 3880SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 3881 unsigned Depth) { 3882 if (Depth == 6) 3883 return SDValue(); // Limit search depth. 3884 3885 SDValue V = SDValue(N, 0); 3886 EVT VT = V.getValueType(); 3887 unsigned Opcode = V.getOpcode(); 3888 3889 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 3890 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 3891 Index = SV->getMaskElt(Index); 3892 3893 if (Index < 0) 3894 return DAG.getUNDEF(VT.getVectorElementType()); 3895 3896 int NumElems = VT.getVectorNumElements(); 3897 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 3898 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 3899 } 3900 3901 // Recurse into target specific vector shuffles to find scalars. 3902 if (isTargetShuffle(Opcode)) { 3903 int NumElems = VT.getVectorNumElements(); 3904 SmallVector<unsigned, 16> ShuffleMask; 3905 SDValue ImmN; 3906 3907 switch(Opcode) { 3908 case X86ISD::SHUFPS: 3909 case X86ISD::SHUFPD: 3910 ImmN = N->getOperand(N->getNumOperands()-1); 3911 DecodeSHUFPSMask(NumElems, 3912 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3913 ShuffleMask); 3914 break; 3915 case X86ISD::PUNPCKHBW: 3916 case X86ISD::PUNPCKHWD: 3917 case X86ISD::PUNPCKHDQ: 3918 case X86ISD::PUNPCKHQDQ: 3919 DecodePUNPCKHMask(NumElems, ShuffleMask); 3920 break; 3921 case X86ISD::UNPCKHPS: 3922 case X86ISD::UNPCKHPD: 3923 DecodeUNPCKHPMask(NumElems, ShuffleMask); 3924 break; 3925 case X86ISD::PUNPCKLBW: 3926 case X86ISD::PUNPCKLWD: 3927 case X86ISD::PUNPCKLDQ: 3928 case X86ISD::PUNPCKLQDQ: 3929 DecodePUNPCKLMask(VT, ShuffleMask); 3930 break; 3931 case X86ISD::UNPCKLPS: 3932 case X86ISD::UNPCKLPD: 3933 case X86ISD::VUNPCKLPS: 3934 case X86ISD::VUNPCKLPD: 3935 case X86ISD::VUNPCKLPSY: 3936 case X86ISD::VUNPCKLPDY: 3937 DecodeUNPCKLPMask(VT, ShuffleMask); 3938 break; 3939 case X86ISD::MOVHLPS: 3940 DecodeMOVHLPSMask(NumElems, ShuffleMask); 3941 break; 3942 case X86ISD::MOVLHPS: 3943 DecodeMOVLHPSMask(NumElems, ShuffleMask); 3944 break; 3945 case X86ISD::PSHUFD: 3946 ImmN = N->getOperand(N->getNumOperands()-1); 3947 DecodePSHUFMask(NumElems, 3948 cast<ConstantSDNode>(ImmN)->getZExtValue(), 3949 ShuffleMask); 3950 break; 3951 case X86ISD::PSHUFHW: 3952 ImmN = N->getOperand(N->getNumOperands()-1); 3953 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3954 ShuffleMask); 3955 break; 3956 case X86ISD::PSHUFLW: 3957 ImmN = N->getOperand(N->getNumOperands()-1); 3958 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 3959 ShuffleMask); 3960 break; 3961 case X86ISD::MOVSS: 3962 case X86ISD::MOVSD: { 3963 // The index 0 always comes from the first element of the second source, 3964 // this is why MOVSS and MOVSD are used in the first place. The other 3965 // elements come from the other positions of the first source vector. 3966 unsigned OpNum = (Index == 0) ? 1 : 0; 3967 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 3968 Depth+1); 3969 } 3970 default: 3971 assert("not implemented for target shuffle node"); 3972 return SDValue(); 3973 } 3974 3975 Index = ShuffleMask[Index]; 3976 if (Index < 0) 3977 return DAG.getUNDEF(VT.getVectorElementType()); 3978 3979 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 3980 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 3981 Depth+1); 3982 } 3983 3984 // Actual nodes that may contain scalar elements 3985 if (Opcode == ISD::BITCAST) { 3986 V = V.getOperand(0); 3987 EVT SrcVT = V.getValueType(); 3988 unsigned NumElems = VT.getVectorNumElements(); 3989 3990 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 3991 return SDValue(); 3992 } 3993 3994 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 3995 return (Index == 0) ? V.getOperand(0) 3996 : DAG.getUNDEF(VT.getVectorElementType()); 3997 3998 if (V.getOpcode() == ISD::BUILD_VECTOR) 3999 return V.getOperand(Index); 4000 4001 return SDValue(); 4002} 4003 4004/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4005/// shuffle operation which come from a consecutively from a zero. The 4006/// search can start in two diferent directions, from left or right. 4007static 4008unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 4009 bool ZerosFromLeft, SelectionDAG &DAG) { 4010 int i = 0; 4011 4012 while (i < NumElems) { 4013 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4014 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 4015 if (!(Elt.getNode() && 4016 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4017 break; 4018 ++i; 4019 } 4020 4021 return i; 4022} 4023 4024/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 4025/// MaskE correspond consecutively to elements from one of the vector operands, 4026/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4027static 4028bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 4029 int OpIdx, int NumElems, unsigned &OpNum) { 4030 bool SeenV1 = false; 4031 bool SeenV2 = false; 4032 4033 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4034 int Idx = SVOp->getMaskElt(i); 4035 // Ignore undef indicies 4036 if (Idx < 0) 4037 continue; 4038 4039 if (Idx < NumElems) 4040 SeenV1 = true; 4041 else 4042 SeenV2 = true; 4043 4044 // Only accept consecutive elements from the same vector 4045 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4046 return false; 4047 } 4048 4049 OpNum = SeenV1 ? 0 : 1; 4050 return true; 4051} 4052 4053/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4054/// logical left shift of a vector. 4055static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4056 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4057 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4058 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4059 false /* check zeros from right */, DAG); 4060 unsigned OpSrc; 4061 4062 if (!NumZeros) 4063 return false; 4064 4065 // Considering the elements in the mask that are not consecutive zeros, 4066 // check if they consecutively come from only one of the source vectors. 4067 // 4068 // V1 = {X, A, B, C} 0 4069 // \ \ \ / 4070 // vector_shuffle V1, V2 <1, 2, 3, X> 4071 // 4072 if (!isShuffleMaskConsecutive(SVOp, 4073 0, // Mask Start Index 4074 NumElems-NumZeros-1, // Mask End Index 4075 NumZeros, // Where to start looking in the src vector 4076 NumElems, // Number of elements in vector 4077 OpSrc)) // Which source operand ? 4078 return false; 4079 4080 isLeft = false; 4081 ShAmt = NumZeros; 4082 ShVal = SVOp->getOperand(OpSrc); 4083 return true; 4084} 4085 4086/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4087/// logical left shift of a vector. 4088static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4089 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4090 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4091 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4092 true /* check zeros from left */, DAG); 4093 unsigned OpSrc; 4094 4095 if (!NumZeros) 4096 return false; 4097 4098 // Considering the elements in the mask that are not consecutive zeros, 4099 // check if they consecutively come from only one of the source vectors. 4100 // 4101 // 0 { A, B, X, X } = V2 4102 // / \ / / 4103 // vector_shuffle V1, V2 <X, X, 4, 5> 4104 // 4105 if (!isShuffleMaskConsecutive(SVOp, 4106 NumZeros, // Mask Start Index 4107 NumElems-1, // Mask End Index 4108 0, // Where to start looking in the src vector 4109 NumElems, // Number of elements in vector 4110 OpSrc)) // Which source operand ? 4111 return false; 4112 4113 isLeft = true; 4114 ShAmt = NumZeros; 4115 ShVal = SVOp->getOperand(OpSrc); 4116 return true; 4117} 4118 4119/// isVectorShift - Returns true if the shuffle can be implemented as a 4120/// logical left or right shift of a vector. 4121static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4122 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4123 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4124 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4125 return true; 4126 4127 return false; 4128} 4129 4130/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4131/// 4132static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4133 unsigned NumNonZero, unsigned NumZero, 4134 SelectionDAG &DAG, 4135 const TargetLowering &TLI) { 4136 if (NumNonZero > 8) 4137 return SDValue(); 4138 4139 DebugLoc dl = Op.getDebugLoc(); 4140 SDValue V(0, 0); 4141 bool First = true; 4142 for (unsigned i = 0; i < 16; ++i) { 4143 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4144 if (ThisIsNonZero && First) { 4145 if (NumZero) 4146 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4147 else 4148 V = DAG.getUNDEF(MVT::v8i16); 4149 First = false; 4150 } 4151 4152 if ((i & 1) != 0) { 4153 SDValue ThisElt(0, 0), LastElt(0, 0); 4154 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4155 if (LastIsNonZero) { 4156 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4157 MVT::i16, Op.getOperand(i-1)); 4158 } 4159 if (ThisIsNonZero) { 4160 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4161 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4162 ThisElt, DAG.getConstant(8, MVT::i8)); 4163 if (LastIsNonZero) 4164 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4165 } else 4166 ThisElt = LastElt; 4167 4168 if (ThisElt.getNode()) 4169 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4170 DAG.getIntPtrConstant(i/2)); 4171 } 4172 } 4173 4174 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4175} 4176 4177/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4178/// 4179static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4180 unsigned NumNonZero, unsigned NumZero, 4181 SelectionDAG &DAG, 4182 const TargetLowering &TLI) { 4183 if (NumNonZero > 4) 4184 return SDValue(); 4185 4186 DebugLoc dl = Op.getDebugLoc(); 4187 SDValue V(0, 0); 4188 bool First = true; 4189 for (unsigned i = 0; i < 8; ++i) { 4190 bool isNonZero = (NonZeros & (1 << i)) != 0; 4191 if (isNonZero) { 4192 if (First) { 4193 if (NumZero) 4194 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4195 else 4196 V = DAG.getUNDEF(MVT::v8i16); 4197 First = false; 4198 } 4199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4200 MVT::v8i16, V, Op.getOperand(i), 4201 DAG.getIntPtrConstant(i)); 4202 } 4203 } 4204 4205 return V; 4206} 4207 4208/// getVShift - Return a vector logical shift node. 4209/// 4210static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4211 unsigned NumBits, SelectionDAG &DAG, 4212 const TargetLowering &TLI, DebugLoc dl) { 4213 EVT ShVT = MVT::v2i64; 4214 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4215 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4216 return DAG.getNode(ISD::BITCAST, dl, VT, 4217 DAG.getNode(Opc, dl, ShVT, SrcOp, 4218 DAG.getConstant(NumBits, 4219 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4220} 4221 4222SDValue 4223X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4224 SelectionDAG &DAG) const { 4225 4226 // Check if the scalar load can be widened into a vector load. And if 4227 // the address is "base + cst" see if the cst can be "absorbed" into 4228 // the shuffle mask. 4229 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4230 SDValue Ptr = LD->getBasePtr(); 4231 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4232 return SDValue(); 4233 EVT PVT = LD->getValueType(0); 4234 if (PVT != MVT::i32 && PVT != MVT::f32) 4235 return SDValue(); 4236 4237 int FI = -1; 4238 int64_t Offset = 0; 4239 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4240 FI = FINode->getIndex(); 4241 Offset = 0; 4242 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4243 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4244 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4245 Offset = Ptr.getConstantOperandVal(1); 4246 Ptr = Ptr.getOperand(0); 4247 } else { 4248 return SDValue(); 4249 } 4250 4251 SDValue Chain = LD->getChain(); 4252 // Make sure the stack object alignment is at least 16. 4253 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4254 if (DAG.InferPtrAlignment(Ptr) < 16) { 4255 if (MFI->isFixedObjectIndex(FI)) { 4256 // Can't change the alignment. FIXME: It's possible to compute 4257 // the exact stack offset and reference FI + adjust offset instead. 4258 // If someone *really* cares about this. That's the way to implement it. 4259 return SDValue(); 4260 } else { 4261 MFI->setObjectAlignment(FI, 16); 4262 } 4263 } 4264 4265 // (Offset % 16) must be multiple of 4. Then address is then 4266 // Ptr + (Offset & ~15). 4267 if (Offset < 0) 4268 return SDValue(); 4269 if ((Offset % 16) & 3) 4270 return SDValue(); 4271 int64_t StartOffset = Offset & ~15; 4272 if (StartOffset) 4273 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4274 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4275 4276 int EltNo = (Offset - StartOffset) >> 2; 4277 int Mask[4] = { EltNo, EltNo, EltNo, EltNo }; 4278 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32; 4279 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr, 4280 LD->getPointerInfo().getWithOffset(StartOffset), 4281 false, false, 0); 4282 // Canonicalize it to a v4i32 shuffle. 4283 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 4284 return DAG.getNode(ISD::BITCAST, dl, VT, 4285 DAG.getVectorShuffle(MVT::v4i32, dl, V1, 4286 DAG.getUNDEF(MVT::v4i32),&Mask[0])); 4287 } 4288 4289 return SDValue(); 4290} 4291 4292/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4293/// vector of type 'VT', see if the elements can be replaced by a single large 4294/// load which has the same value as a build_vector whose operands are 'elts'. 4295/// 4296/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4297/// 4298/// FIXME: we'd also like to handle the case where the last elements are zero 4299/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4300/// There's even a handy isZeroNode for that purpose. 4301static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4302 DebugLoc &DL, SelectionDAG &DAG) { 4303 EVT EltVT = VT.getVectorElementType(); 4304 unsigned NumElems = Elts.size(); 4305 4306 LoadSDNode *LDBase = NULL; 4307 unsigned LastLoadedElt = -1U; 4308 4309 // For each element in the initializer, see if we've found a load or an undef. 4310 // If we don't find an initial load element, or later load elements are 4311 // non-consecutive, bail out. 4312 for (unsigned i = 0; i < NumElems; ++i) { 4313 SDValue Elt = Elts[i]; 4314 4315 if (!Elt.getNode() || 4316 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4317 return SDValue(); 4318 if (!LDBase) { 4319 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4320 return SDValue(); 4321 LDBase = cast<LoadSDNode>(Elt.getNode()); 4322 LastLoadedElt = i; 4323 continue; 4324 } 4325 if (Elt.getOpcode() == ISD::UNDEF) 4326 continue; 4327 4328 LoadSDNode *LD = cast<LoadSDNode>(Elt); 4329 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 4330 return SDValue(); 4331 LastLoadedElt = i; 4332 } 4333 4334 // If we have found an entire vector of loads and undefs, then return a large 4335 // load of the entire vector width starting at the base pointer. If we found 4336 // consecutive loads for the low half, generate a vzext_load node. 4337 if (LastLoadedElt == NumElems - 1) { 4338 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 4339 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4340 LDBase->getPointerInfo(), 4341 LDBase->isVolatile(), LDBase->isNonTemporal(), 0); 4342 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 4343 LDBase->getPointerInfo(), 4344 LDBase->isVolatile(), LDBase->isNonTemporal(), 4345 LDBase->getAlignment()); 4346 } else if (NumElems == 4 && LastLoadedElt == 1) { 4347 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 4348 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 4349 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, 4350 Ops, 2, MVT::i32, 4351 LDBase->getMemOperand()); 4352 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 4353 } 4354 return SDValue(); 4355} 4356 4357SDValue 4358X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 4359 DebugLoc dl = Op.getDebugLoc(); 4360 4361 EVT VT = Op.getValueType(); 4362 EVT ExtVT = VT.getVectorElementType(); 4363 4364 unsigned NumElems = Op.getNumOperands(); 4365 4366 // For AVX-length vectors, build the individual 128-bit pieces and 4367 // use shuffles to put them in place. 4368 if (VT.getSizeInBits() > 256 && 4369 Subtarget->hasAVX() && 4370 !ISD::isBuildVectorAllZeros(Op.getNode())) { 4371 SmallVector<SDValue, 8> V; 4372 V.resize(NumElems); 4373 for (unsigned i = 0; i < NumElems; ++i) { 4374 V[i] = Op.getOperand(i); 4375 } 4376 4377 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 4378 4379 // Build the lower subvector. 4380 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 4381 // Build the upper subvector. 4382 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 4383 NumElems/2); 4384 4385 return ConcatVectors(Lower, Upper, DAG); 4386 } 4387 4388 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1. 4389 // All one's are handled with pcmpeqd. In AVX, zero's are handled with 4390 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd 4391 // is present, so AllOnes is ignored. 4392 if (ISD::isBuildVectorAllZeros(Op.getNode()) || 4393 (Op.getValueType().getSizeInBits() != 256 && 4394 ISD::isBuildVectorAllOnes(Op.getNode()))) { 4395 // Canonicalize this to <4 x i32> (SSE) to 4396 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are 4397 // eliminated on x86-32 hosts. 4398 if (Op.getValueType() == MVT::v4i32) 4399 return Op; 4400 4401 if (ISD::isBuildVectorAllOnes(Op.getNode())) 4402 return getOnesVector(Op.getValueType(), DAG, dl); 4403 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl); 4404 } 4405 4406 unsigned EVTBits = ExtVT.getSizeInBits(); 4407 4408 unsigned NumZero = 0; 4409 unsigned NumNonZero = 0; 4410 unsigned NonZeros = 0; 4411 bool IsAllConstants = true; 4412 SmallSet<SDValue, 8> Values; 4413 for (unsigned i = 0; i < NumElems; ++i) { 4414 SDValue Elt = Op.getOperand(i); 4415 if (Elt.getOpcode() == ISD::UNDEF) 4416 continue; 4417 Values.insert(Elt); 4418 if (Elt.getOpcode() != ISD::Constant && 4419 Elt.getOpcode() != ISD::ConstantFP) 4420 IsAllConstants = false; 4421 if (X86::isZeroNode(Elt)) 4422 NumZero++; 4423 else { 4424 NonZeros |= (1 << i); 4425 NumNonZero++; 4426 } 4427 } 4428 4429 // All undef vector. Return an UNDEF. All zero vectors were handled above. 4430 if (NumNonZero == 0) 4431 return DAG.getUNDEF(VT); 4432 4433 // Special case for single non-zero, non-undef, element. 4434 if (NumNonZero == 1) { 4435 unsigned Idx = CountTrailingZeros_32(NonZeros); 4436 SDValue Item = Op.getOperand(Idx); 4437 4438 // If this is an insertion of an i64 value on x86-32, and if the top bits of 4439 // the value are obviously zero, truncate the value to i32 and do the 4440 // insertion that way. Only do this if the value is non-constant or if the 4441 // value is a constant being inserted into element 0. It is cheaper to do 4442 // a constant pool load than it is to do a movd + shuffle. 4443 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 4444 (!IsAllConstants || Idx == 0)) { 4445 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 4446 // Handle SSE only. 4447 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 4448 EVT VecVT = MVT::v4i32; 4449 unsigned VecElts = 4; 4450 4451 // Truncate the value (which may itself be a constant) to i32, and 4452 // convert it to a vector with movd (S2V+shuffle to zero extend). 4453 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 4454 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 4455 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4456 Subtarget->hasSSE2(), DAG); 4457 4458 // Now we have our 32-bit value zero extended in the low element of 4459 // a vector. If Idx != 0, swizzle it into place. 4460 if (Idx != 0) { 4461 SmallVector<int, 4> Mask; 4462 Mask.push_back(Idx); 4463 for (unsigned i = 1; i != VecElts; ++i) 4464 Mask.push_back(i); 4465 Item = DAG.getVectorShuffle(VecVT, dl, Item, 4466 DAG.getUNDEF(Item.getValueType()), 4467 &Mask[0]); 4468 } 4469 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 4470 } 4471 } 4472 4473 // If we have a constant or non-constant insertion into the low element of 4474 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 4475 // the rest of the elements. This will be matched as movd/movq/movss/movsd 4476 // depending on what the source datatype is. 4477 if (Idx == 0) { 4478 if (NumZero == 0) { 4479 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4480 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 4481 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 4482 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4483 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 4484 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(), 4485 DAG); 4486 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 4487 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 4488 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 4489 EVT MiddleVT = MVT::v4i32; 4490 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 4491 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 4492 Subtarget->hasSSE2(), DAG); 4493 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 4494 } 4495 } 4496 4497 // Is it a vector logical left shift? 4498 if (NumElems == 2 && Idx == 1 && 4499 X86::isZeroNode(Op.getOperand(0)) && 4500 !X86::isZeroNode(Op.getOperand(1))) { 4501 unsigned NumBits = VT.getSizeInBits(); 4502 return getVShift(true, VT, 4503 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 4504 VT, Op.getOperand(1)), 4505 NumBits/2, DAG, *this, dl); 4506 } 4507 4508 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 4509 return SDValue(); 4510 4511 // Otherwise, if this is a vector with i32 or f32 elements, and the element 4512 // is a non-constant being inserted into an element other than the low one, 4513 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 4514 // movd/movss) to move this into the low element, then shuffle it into 4515 // place. 4516 if (EVTBits == 32) { 4517 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 4518 4519 // Turn it into a shuffle of zero and zero-extended scalar to vector. 4520 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 4521 Subtarget->hasSSE2(), DAG); 4522 SmallVector<int, 8> MaskVec; 4523 for (unsigned i = 0; i < NumElems; i++) 4524 MaskVec.push_back(i == Idx ? 0 : 1); 4525 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 4526 } 4527 } 4528 4529 // Splat is obviously ok. Let legalizer expand it to a shuffle. 4530 if (Values.size() == 1) { 4531 if (EVTBits == 32) { 4532 // Instead of a shuffle like this: 4533 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 4534 // Check if it's possible to issue this instead. 4535 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 4536 unsigned Idx = CountTrailingZeros_32(NonZeros); 4537 SDValue Item = Op.getOperand(Idx); 4538 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 4539 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 4540 } 4541 return SDValue(); 4542 } 4543 4544 // A vector full of immediates; various special cases are already 4545 // handled, so this is best done with a single constant-pool load. 4546 if (IsAllConstants) 4547 return SDValue(); 4548 4549 // Let legalizer expand 2-wide build_vectors. 4550 if (EVTBits == 64) { 4551 if (NumNonZero == 1) { 4552 // One half is zero or undef. 4553 unsigned Idx = CountTrailingZeros_32(NonZeros); 4554 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 4555 Op.getOperand(Idx)); 4556 return getShuffleVectorZeroOrUndef(V2, Idx, true, 4557 Subtarget->hasSSE2(), DAG); 4558 } 4559 return SDValue(); 4560 } 4561 4562 // If element VT is < 32 bits, convert it to inserts into a zero vector. 4563 if (EVTBits == 8 && NumElems == 16) { 4564 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 4565 *this); 4566 if (V.getNode()) return V; 4567 } 4568 4569 if (EVTBits == 16 && NumElems == 8) { 4570 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 4571 *this); 4572 if (V.getNode()) return V; 4573 } 4574 4575 // If element VT is == 32 bits, turn it into a number of shuffles. 4576 SmallVector<SDValue, 8> V; 4577 V.resize(NumElems); 4578 if (NumElems == 4 && NumZero > 0) { 4579 for (unsigned i = 0; i < 4; ++i) { 4580 bool isZero = !(NonZeros & (1 << i)); 4581 if (isZero) 4582 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 4583 else 4584 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4585 } 4586 4587 for (unsigned i = 0; i < 2; ++i) { 4588 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 4589 default: break; 4590 case 0: 4591 V[i] = V[i*2]; // Must be a zero vector. 4592 break; 4593 case 1: 4594 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 4595 break; 4596 case 2: 4597 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 4598 break; 4599 case 3: 4600 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 4601 break; 4602 } 4603 } 4604 4605 SmallVector<int, 8> MaskVec; 4606 bool Reverse = (NonZeros & 0x3) == 2; 4607 for (unsigned i = 0; i < 2; ++i) 4608 MaskVec.push_back(Reverse ? 1-i : i); 4609 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 4610 for (unsigned i = 0; i < 2; ++i) 4611 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 4612 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 4613 } 4614 4615 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 4616 // Check for a build vector of consecutive loads. 4617 for (unsigned i = 0; i < NumElems; ++i) 4618 V[i] = Op.getOperand(i); 4619 4620 // Check for elements which are consecutive loads. 4621 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 4622 if (LD.getNode()) 4623 return LD; 4624 4625 // For SSE 4.1, use insertps to put the high elements into the low element. 4626 if (getSubtarget()->hasSSE41()) { 4627 SDValue Result; 4628 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 4629 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 4630 else 4631 Result = DAG.getUNDEF(VT); 4632 4633 for (unsigned i = 1; i < NumElems; ++i) { 4634 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 4635 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 4636 Op.getOperand(i), DAG.getIntPtrConstant(i)); 4637 } 4638 return Result; 4639 } 4640 4641 // Otherwise, expand into a number of unpckl*, start by extending each of 4642 // our (non-undef) elements to the full vector width with the element in the 4643 // bottom slot of the vector (which generates no code for SSE). 4644 for (unsigned i = 0; i < NumElems; ++i) { 4645 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 4646 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 4647 else 4648 V[i] = DAG.getUNDEF(VT); 4649 } 4650 4651 // Next, we iteratively mix elements, e.g. for v4f32: 4652 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 4653 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 4654 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 4655 unsigned EltStride = NumElems >> 1; 4656 while (EltStride != 0) { 4657 for (unsigned i = 0; i < EltStride; ++i) { 4658 // If V[i+EltStride] is undef and this is the first round of mixing, 4659 // then it is safe to just drop this shuffle: V[i] is already in the 4660 // right place, the one element (since it's the first round) being 4661 // inserted as undef can be dropped. This isn't safe for successive 4662 // rounds because they will permute elements within both vectors. 4663 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 4664 EltStride == NumElems/2) 4665 continue; 4666 4667 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 4668 } 4669 EltStride >>= 1; 4670 } 4671 return V[0]; 4672 } 4673 return SDValue(); 4674} 4675 4676SDValue 4677X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 4678 // We support concatenate two MMX registers and place them in a MMX 4679 // register. This is better than doing a stack convert. 4680 DebugLoc dl = Op.getDebugLoc(); 4681 EVT ResVT = Op.getValueType(); 4682 assert(Op.getNumOperands() == 2); 4683 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 4684 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 4685 int Mask[2]; 4686 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 4687 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4688 InVec = Op.getOperand(1); 4689 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 4690 unsigned NumElts = ResVT.getVectorNumElements(); 4691 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4692 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 4693 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 4694 } else { 4695 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 4696 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 4697 Mask[0] = 0; Mask[1] = 2; 4698 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 4699 } 4700 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 4701} 4702 4703// v8i16 shuffles - Prefer shuffles in the following order: 4704// 1. [all] pshuflw, pshufhw, optional move 4705// 2. [ssse3] 1 x pshufb 4706// 3. [ssse3] 2 x pshufb + 1 x por 4707// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 4708SDValue 4709X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 4710 SelectionDAG &DAG) const { 4711 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 4712 SDValue V1 = SVOp->getOperand(0); 4713 SDValue V2 = SVOp->getOperand(1); 4714 DebugLoc dl = SVOp->getDebugLoc(); 4715 SmallVector<int, 8> MaskVals; 4716 4717 // Determine if more than 1 of the words in each of the low and high quadwords 4718 // of the result come from the same quadword of one of the two inputs. Undef 4719 // mask values count as coming from any quadword, for better codegen. 4720 SmallVector<unsigned, 4> LoQuad(4); 4721 SmallVector<unsigned, 4> HiQuad(4); 4722 BitVector InputQuads(4); 4723 for (unsigned i = 0; i < 8; ++i) { 4724 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad; 4725 int EltIdx = SVOp->getMaskElt(i); 4726 MaskVals.push_back(EltIdx); 4727 if (EltIdx < 0) { 4728 ++Quad[0]; 4729 ++Quad[1]; 4730 ++Quad[2]; 4731 ++Quad[3]; 4732 continue; 4733 } 4734 ++Quad[EltIdx / 4]; 4735 InputQuads.set(EltIdx / 4); 4736 } 4737 4738 int BestLoQuad = -1; 4739 unsigned MaxQuad = 1; 4740 for (unsigned i = 0; i < 4; ++i) { 4741 if (LoQuad[i] > MaxQuad) { 4742 BestLoQuad = i; 4743 MaxQuad = LoQuad[i]; 4744 } 4745 } 4746 4747 int BestHiQuad = -1; 4748 MaxQuad = 1; 4749 for (unsigned i = 0; i < 4; ++i) { 4750 if (HiQuad[i] > MaxQuad) { 4751 BestHiQuad = i; 4752 MaxQuad = HiQuad[i]; 4753 } 4754 } 4755 4756 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 4757 // of the two input vectors, shuffle them into one input vector so only a 4758 // single pshufb instruction is necessary. If There are more than 2 input 4759 // quads, disable the next transformation since it does not help SSSE3. 4760 bool V1Used = InputQuads[0] || InputQuads[1]; 4761 bool V2Used = InputQuads[2] || InputQuads[3]; 4762 if (Subtarget->hasSSSE3()) { 4763 if (InputQuads.count() == 2 && V1Used && V2Used) { 4764 BestLoQuad = InputQuads.find_first(); 4765 BestHiQuad = InputQuads.find_next(BestLoQuad); 4766 } 4767 if (InputQuads.count() > 2) { 4768 BestLoQuad = -1; 4769 BestHiQuad = -1; 4770 } 4771 } 4772 4773 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 4774 // the shuffle mask. If a quad is scored as -1, that means that it contains 4775 // words from all 4 input quadwords. 4776 SDValue NewV; 4777 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 4778 SmallVector<int, 8> MaskV; 4779 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 4780 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 4781 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 4782 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 4783 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 4784 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 4785 4786 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 4787 // source words for the shuffle, to aid later transformations. 4788 bool AllWordsInNewV = true; 4789 bool InOrder[2] = { true, true }; 4790 for (unsigned i = 0; i != 8; ++i) { 4791 int idx = MaskVals[i]; 4792 if (idx != (int)i) 4793 InOrder[i/4] = false; 4794 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 4795 continue; 4796 AllWordsInNewV = false; 4797 break; 4798 } 4799 4800 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 4801 if (AllWordsInNewV) { 4802 for (int i = 0; i != 8; ++i) { 4803 int idx = MaskVals[i]; 4804 if (idx < 0) 4805 continue; 4806 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 4807 if ((idx != i) && idx < 4) 4808 pshufhw = false; 4809 if ((idx != i) && idx > 3) 4810 pshuflw = false; 4811 } 4812 V1 = NewV; 4813 V2Used = false; 4814 BestLoQuad = 0; 4815 BestHiQuad = 1; 4816 } 4817 4818 // If we've eliminated the use of V2, and the new mask is a pshuflw or 4819 // pshufhw, that's as cheap as it gets. Return the new shuffle. 4820 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 4821 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 4822 unsigned TargetMask = 0; 4823 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 4824 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 4825 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 4826 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 4827 V1 = NewV.getOperand(0); 4828 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 4829 } 4830 } 4831 4832 // If we have SSSE3, and all words of the result are from 1 input vector, 4833 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 4834 // is present, fall back to case 4. 4835 if (Subtarget->hasSSSE3()) { 4836 SmallVector<SDValue,16> pshufbMask; 4837 4838 // If we have elements from both input vectors, set the high bit of the 4839 // shuffle mask element to zero out elements that come from V2 in the V1 4840 // mask, and elements that come from V1 in the V2 mask, so that the two 4841 // results can be OR'd together. 4842 bool TwoInputs = V1Used && V2Used; 4843 for (unsigned i = 0; i != 8; ++i) { 4844 int EltIdx = MaskVals[i] * 2; 4845 if (TwoInputs && (EltIdx >= 16)) { 4846 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4847 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4848 continue; 4849 } 4850 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 4851 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 4852 } 4853 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 4854 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 4855 DAG.getNode(ISD::BUILD_VECTOR, dl, 4856 MVT::v16i8, &pshufbMask[0], 16)); 4857 if (!TwoInputs) 4858 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4859 4860 // Calculate the shuffle mask for the second input, shuffle it, and 4861 // OR it with the first shuffled input. 4862 pshufbMask.clear(); 4863 for (unsigned i = 0; i != 8; ++i) { 4864 int EltIdx = MaskVals[i] * 2; 4865 if (EltIdx < 16) { 4866 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4867 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 4868 continue; 4869 } 4870 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 4871 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 4872 } 4873 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 4874 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 4875 DAG.getNode(ISD::BUILD_VECTOR, dl, 4876 MVT::v16i8, &pshufbMask[0], 16)); 4877 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 4878 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 4879 } 4880 4881 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 4882 // and update MaskVals with new element order. 4883 BitVector InOrder(8); 4884 if (BestLoQuad >= 0) { 4885 SmallVector<int, 8> MaskV; 4886 for (int i = 0; i != 4; ++i) { 4887 int idx = MaskVals[i]; 4888 if (idx < 0) { 4889 MaskV.push_back(-1); 4890 InOrder.set(i); 4891 } else if ((idx / 4) == BestLoQuad) { 4892 MaskV.push_back(idx & 3); 4893 InOrder.set(i); 4894 } else { 4895 MaskV.push_back(-1); 4896 } 4897 } 4898 for (unsigned i = 4; i != 8; ++i) 4899 MaskV.push_back(i); 4900 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4901 &MaskV[0]); 4902 4903 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4904 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 4905 NewV.getOperand(0), 4906 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 4907 DAG); 4908 } 4909 4910 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 4911 // and update MaskVals with the new element order. 4912 if (BestHiQuad >= 0) { 4913 SmallVector<int, 8> MaskV; 4914 for (unsigned i = 0; i != 4; ++i) 4915 MaskV.push_back(i); 4916 for (unsigned i = 4; i != 8; ++i) { 4917 int idx = MaskVals[i]; 4918 if (idx < 0) { 4919 MaskV.push_back(-1); 4920 InOrder.set(i); 4921 } else if ((idx / 4) == BestHiQuad) { 4922 MaskV.push_back((idx & 3) + 4); 4923 InOrder.set(i); 4924 } else { 4925 MaskV.push_back(-1); 4926 } 4927 } 4928 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 4929 &MaskV[0]); 4930 4931 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) 4932 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 4933 NewV.getOperand(0), 4934 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 4935 DAG); 4936 } 4937 4938 // In case BestHi & BestLo were both -1, which means each quadword has a word 4939 // from each of the four input quadwords, calculate the InOrder bitvector now 4940 // before falling through to the insert/extract cleanup. 4941 if (BestLoQuad == -1 && BestHiQuad == -1) { 4942 NewV = V1; 4943 for (int i = 0; i != 8; ++i) 4944 if (MaskVals[i] < 0 || MaskVals[i] == i) 4945 InOrder.set(i); 4946 } 4947 4948 // The other elements are put in the right place using pextrw and pinsrw. 4949 for (unsigned i = 0; i != 8; ++i) { 4950 if (InOrder[i]) 4951 continue; 4952 int EltIdx = MaskVals[i]; 4953 if (EltIdx < 0) 4954 continue; 4955 SDValue ExtOp = (EltIdx < 8) 4956 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 4957 DAG.getIntPtrConstant(EltIdx)) 4958 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 4959 DAG.getIntPtrConstant(EltIdx - 8)); 4960 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 4961 DAG.getIntPtrConstant(i)); 4962 } 4963 return NewV; 4964} 4965 4966// v16i8 shuffles - Prefer shuffles in the following order: 4967// 1. [ssse3] 1 x pshufb 4968// 2. [ssse3] 2 x pshufb + 1 x por 4969// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 4970static 4971SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 4972 SelectionDAG &DAG, 4973 const X86TargetLowering &TLI) { 4974 SDValue V1 = SVOp->getOperand(0); 4975 SDValue V2 = SVOp->getOperand(1); 4976 DebugLoc dl = SVOp->getDebugLoc(); 4977 SmallVector<int, 16> MaskVals; 4978 SVOp->getMask(MaskVals); 4979 4980 // If we have SSSE3, case 1 is generated when all result bytes come from 4981 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 4982 // present, fall back to case 3. 4983 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 4984 bool V1Only = true; 4985 bool V2Only = true; 4986 for (unsigned i = 0; i < 16; ++i) { 4987 int EltIdx = MaskVals[i]; 4988 if (EltIdx < 0) 4989 continue; 4990 if (EltIdx < 16) 4991 V2Only = false; 4992 else 4993 V1Only = false; 4994 } 4995 4996 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 4997 if (TLI.getSubtarget()->hasSSSE3()) { 4998 SmallVector<SDValue,16> pshufbMask; 4999 5000 // If all result elements are from one input vector, then only translate 5001 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5002 // 5003 // Otherwise, we have elements from both input vectors, and must zero out 5004 // elements that come from V2 in the first mask, and V1 in the second mask 5005 // so that we can OR them together. 5006 bool TwoInputs = !(V1Only || V2Only); 5007 for (unsigned i = 0; i != 16; ++i) { 5008 int EltIdx = MaskVals[i]; 5009 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 5010 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5011 continue; 5012 } 5013 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5014 } 5015 // If all the elements are from V2, assign it to V1 and return after 5016 // building the first pshufb. 5017 if (V2Only) 5018 V1 = V2; 5019 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5020 DAG.getNode(ISD::BUILD_VECTOR, dl, 5021 MVT::v16i8, &pshufbMask[0], 16)); 5022 if (!TwoInputs) 5023 return V1; 5024 5025 // Calculate the shuffle mask for the second input, shuffle it, and 5026 // OR it with the first shuffled input. 5027 pshufbMask.clear(); 5028 for (unsigned i = 0; i != 16; ++i) { 5029 int EltIdx = MaskVals[i]; 5030 if (EltIdx < 16) { 5031 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5032 continue; 5033 } 5034 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5035 } 5036 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5037 DAG.getNode(ISD::BUILD_VECTOR, dl, 5038 MVT::v16i8, &pshufbMask[0], 16)); 5039 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5040 } 5041 5042 // No SSSE3 - Calculate in place words and then fix all out of place words 5043 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5044 // the 16 different words that comprise the two doublequadword input vectors. 5045 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5046 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5047 SDValue NewV = V2Only ? V2 : V1; 5048 for (int i = 0; i != 8; ++i) { 5049 int Elt0 = MaskVals[i*2]; 5050 int Elt1 = MaskVals[i*2+1]; 5051 5052 // This word of the result is all undef, skip it. 5053 if (Elt0 < 0 && Elt1 < 0) 5054 continue; 5055 5056 // This word of the result is already in the correct place, skip it. 5057 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5058 continue; 5059 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5060 continue; 5061 5062 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5063 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5064 SDValue InsElt; 5065 5066 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5067 // using a single extract together, load it and store it. 5068 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5069 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5070 DAG.getIntPtrConstant(Elt1 / 2)); 5071 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5072 DAG.getIntPtrConstant(i)); 5073 continue; 5074 } 5075 5076 // If Elt1 is defined, extract it from the appropriate source. If the 5077 // source byte is not also odd, shift the extracted word left 8 bits 5078 // otherwise clear the bottom 8 bits if we need to do an or. 5079 if (Elt1 >= 0) { 5080 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5081 DAG.getIntPtrConstant(Elt1 / 2)); 5082 if ((Elt1 & 1) == 0) 5083 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5084 DAG.getConstant(8, 5085 TLI.getShiftAmountTy(InsElt.getValueType()))); 5086 else if (Elt0 >= 0) 5087 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5088 DAG.getConstant(0xFF00, MVT::i16)); 5089 } 5090 // If Elt0 is defined, extract it from the appropriate source. If the 5091 // source byte is not also even, shift the extracted word right 8 bits. If 5092 // Elt1 was also defined, OR the extracted values together before 5093 // inserting them in the result. 5094 if (Elt0 >= 0) { 5095 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5096 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5097 if ((Elt0 & 1) != 0) 5098 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5099 DAG.getConstant(8, 5100 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5101 else if (Elt1 >= 0) 5102 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5103 DAG.getConstant(0x00FF, MVT::i16)); 5104 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5105 : InsElt0; 5106 } 5107 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5108 DAG.getIntPtrConstant(i)); 5109 } 5110 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5111} 5112 5113/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5114/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5115/// done when every pair / quad of shuffle mask elements point to elements in 5116/// the right sequence. e.g. 5117/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5118static 5119SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5120 SelectionDAG &DAG, DebugLoc dl) { 5121 EVT VT = SVOp->getValueType(0); 5122 SDValue V1 = SVOp->getOperand(0); 5123 SDValue V2 = SVOp->getOperand(1); 5124 unsigned NumElems = VT.getVectorNumElements(); 5125 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 5126 EVT NewVT; 5127 switch (VT.getSimpleVT().SimpleTy) { 5128 default: assert(false && "Unexpected!"); 5129 case MVT::v4f32: NewVT = MVT::v2f64; break; 5130 case MVT::v4i32: NewVT = MVT::v2i64; break; 5131 case MVT::v8i16: NewVT = MVT::v4i32; break; 5132 case MVT::v16i8: NewVT = MVT::v4i32; break; 5133 } 5134 5135 int Scale = NumElems / NewWidth; 5136 SmallVector<int, 8> MaskVec; 5137 for (unsigned i = 0; i < NumElems; i += Scale) { 5138 int StartIdx = -1; 5139 for (int j = 0; j < Scale; ++j) { 5140 int EltIdx = SVOp->getMaskElt(i+j); 5141 if (EltIdx < 0) 5142 continue; 5143 if (StartIdx == -1) 5144 StartIdx = EltIdx - (EltIdx % Scale); 5145 if (EltIdx != StartIdx + j) 5146 return SDValue(); 5147 } 5148 if (StartIdx == -1) 5149 MaskVec.push_back(-1); 5150 else 5151 MaskVec.push_back(StartIdx / Scale); 5152 } 5153 5154 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 5155 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 5156 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5157} 5158 5159/// getVZextMovL - Return a zero-extending vector move low node. 5160/// 5161static SDValue getVZextMovL(EVT VT, EVT OpVT, 5162 SDValue SrcOp, SelectionDAG &DAG, 5163 const X86Subtarget *Subtarget, DebugLoc dl) { 5164 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 5165 LoadSDNode *LD = NULL; 5166 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 5167 LD = dyn_cast<LoadSDNode>(SrcOp); 5168 if (!LD) { 5169 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 5170 // instead. 5171 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 5172 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 5173 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 5174 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 5175 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 5176 // PR2108 5177 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 5178 return DAG.getNode(ISD::BITCAST, dl, VT, 5179 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5180 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5181 OpVT, 5182 SrcOp.getOperand(0) 5183 .getOperand(0)))); 5184 } 5185 } 5186 } 5187 5188 return DAG.getNode(ISD::BITCAST, dl, VT, 5189 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5190 DAG.getNode(ISD::BITCAST, dl, 5191 OpVT, SrcOp))); 5192} 5193 5194/// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of 5195/// shuffles. 5196static SDValue 5197LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 5198 SDValue V1 = SVOp->getOperand(0); 5199 SDValue V2 = SVOp->getOperand(1); 5200 DebugLoc dl = SVOp->getDebugLoc(); 5201 EVT VT = SVOp->getValueType(0); 5202 5203 SmallVector<std::pair<int, int>, 8> Locs; 5204 Locs.resize(4); 5205 SmallVector<int, 8> Mask1(4U, -1); 5206 SmallVector<int, 8> PermMask; 5207 SVOp->getMask(PermMask); 5208 5209 unsigned NumHi = 0; 5210 unsigned NumLo = 0; 5211 for (unsigned i = 0; i != 4; ++i) { 5212 int Idx = PermMask[i]; 5213 if (Idx < 0) { 5214 Locs[i] = std::make_pair(-1, -1); 5215 } else { 5216 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 5217 if (Idx < 4) { 5218 Locs[i] = std::make_pair(0, NumLo); 5219 Mask1[NumLo] = Idx; 5220 NumLo++; 5221 } else { 5222 Locs[i] = std::make_pair(1, NumHi); 5223 if (2+NumHi < 4) 5224 Mask1[2+NumHi] = Idx; 5225 NumHi++; 5226 } 5227 } 5228 } 5229 5230 if (NumLo <= 2 && NumHi <= 2) { 5231 // If no more than two elements come from either vector. This can be 5232 // implemented with two shuffles. First shuffle gather the elements. 5233 // The second shuffle, which takes the first shuffle as both of its 5234 // vector operands, put the elements into the right order. 5235 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5236 5237 SmallVector<int, 8> Mask2(4U, -1); 5238 5239 for (unsigned i = 0; i != 4; ++i) { 5240 if (Locs[i].first == -1) 5241 continue; 5242 else { 5243 unsigned Idx = (i < 2) ? 0 : 4; 5244 Idx += Locs[i].first * 2 + Locs[i].second; 5245 Mask2[i] = Idx; 5246 } 5247 } 5248 5249 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 5250 } else if (NumLo == 3 || NumHi == 3) { 5251 // Otherwise, we must have three elements from one vector, call it X, and 5252 // one element from the other, call it Y. First, use a shufps to build an 5253 // intermediate vector with the one element from Y and the element from X 5254 // that will be in the same half in the final destination (the indexes don't 5255 // matter). Then, use a shufps to build the final vector, taking the half 5256 // containing the element from Y from the intermediate, and the other half 5257 // from X. 5258 if (NumHi == 3) { 5259 // Normalize it so the 3 elements come from V1. 5260 CommuteVectorShuffleMask(PermMask, VT); 5261 std::swap(V1, V2); 5262 } 5263 5264 // Find the element from V2. 5265 unsigned HiIndex; 5266 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 5267 int Val = PermMask[HiIndex]; 5268 if (Val < 0) 5269 continue; 5270 if (Val >= 4) 5271 break; 5272 } 5273 5274 Mask1[0] = PermMask[HiIndex]; 5275 Mask1[1] = -1; 5276 Mask1[2] = PermMask[HiIndex^1]; 5277 Mask1[3] = -1; 5278 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5279 5280 if (HiIndex >= 2) { 5281 Mask1[0] = PermMask[0]; 5282 Mask1[1] = PermMask[1]; 5283 Mask1[2] = HiIndex & 1 ? 6 : 4; 5284 Mask1[3] = HiIndex & 1 ? 4 : 6; 5285 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 5286 } else { 5287 Mask1[0] = HiIndex & 1 ? 2 : 0; 5288 Mask1[1] = HiIndex & 1 ? 0 : 2; 5289 Mask1[2] = PermMask[2]; 5290 Mask1[3] = PermMask[3]; 5291 if (Mask1[2] >= 0) 5292 Mask1[2] += 4; 5293 if (Mask1[3] >= 0) 5294 Mask1[3] += 4; 5295 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 5296 } 5297 } 5298 5299 // Break it into (shuffle shuffle_hi, shuffle_lo). 5300 Locs.clear(); 5301 Locs.resize(4); 5302 SmallVector<int,8> LoMask(4U, -1); 5303 SmallVector<int,8> HiMask(4U, -1); 5304 5305 SmallVector<int,8> *MaskPtr = &LoMask; 5306 unsigned MaskIdx = 0; 5307 unsigned LoIdx = 0; 5308 unsigned HiIdx = 2; 5309 for (unsigned i = 0; i != 4; ++i) { 5310 if (i == 2) { 5311 MaskPtr = &HiMask; 5312 MaskIdx = 1; 5313 LoIdx = 0; 5314 HiIdx = 2; 5315 } 5316 int Idx = PermMask[i]; 5317 if (Idx < 0) { 5318 Locs[i] = std::make_pair(-1, -1); 5319 } else if (Idx < 4) { 5320 Locs[i] = std::make_pair(MaskIdx, LoIdx); 5321 (*MaskPtr)[LoIdx] = Idx; 5322 LoIdx++; 5323 } else { 5324 Locs[i] = std::make_pair(MaskIdx, HiIdx); 5325 (*MaskPtr)[HiIdx] = Idx; 5326 HiIdx++; 5327 } 5328 } 5329 5330 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 5331 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 5332 SmallVector<int, 8> MaskOps; 5333 for (unsigned i = 0; i != 4; ++i) { 5334 if (Locs[i].first == -1) { 5335 MaskOps.push_back(-1); 5336 } else { 5337 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 5338 MaskOps.push_back(Idx); 5339 } 5340 } 5341 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 5342} 5343 5344static bool MayFoldVectorLoad(SDValue V) { 5345 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5346 V = V.getOperand(0); 5347 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5348 V = V.getOperand(0); 5349 if (MayFoldLoad(V)) 5350 return true; 5351 return false; 5352} 5353 5354// FIXME: the version above should always be used. Since there's 5355// a bug where several vector shuffles can't be folded because the 5356// DAG is not updated during lowering and a node claims to have two 5357// uses while it only has one, use this version, and let isel match 5358// another instruction if the load really happens to have more than 5359// one use. Remove this version after this bug get fixed. 5360// rdar://8434668, PR8156 5361static bool RelaxedMayFoldVectorLoad(SDValue V) { 5362 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5363 V = V.getOperand(0); 5364 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 5365 V = V.getOperand(0); 5366 if (ISD::isNormalLoad(V.getNode())) 5367 return true; 5368 return false; 5369} 5370 5371/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 5372/// a vector extract, and if both can be later optimized into a single load. 5373/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 5374/// here because otherwise a target specific shuffle node is going to be 5375/// emitted for this shuffle, and the optimization not done. 5376/// FIXME: This is probably not the best approach, but fix the problem 5377/// until the right path is decided. 5378static 5379bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 5380 const TargetLowering &TLI) { 5381 EVT VT = V.getValueType(); 5382 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 5383 5384 // Be sure that the vector shuffle is present in a pattern like this: 5385 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 5386 if (!V.hasOneUse()) 5387 return false; 5388 5389 SDNode *N = *V.getNode()->use_begin(); 5390 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 5391 return false; 5392 5393 SDValue EltNo = N->getOperand(1); 5394 if (!isa<ConstantSDNode>(EltNo)) 5395 return false; 5396 5397 // If the bit convert changed the number of elements, it is unsafe 5398 // to examine the mask. 5399 bool HasShuffleIntoBitcast = false; 5400 if (V.getOpcode() == ISD::BITCAST) { 5401 EVT SrcVT = V.getOperand(0).getValueType(); 5402 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 5403 return false; 5404 V = V.getOperand(0); 5405 HasShuffleIntoBitcast = true; 5406 } 5407 5408 // Select the input vector, guarding against out of range extract vector. 5409 unsigned NumElems = VT.getVectorNumElements(); 5410 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 5411 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 5412 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 5413 5414 // Skip one more bit_convert if necessary 5415 if (V.getOpcode() == ISD::BITCAST) 5416 V = V.getOperand(0); 5417 5418 if (ISD::isNormalLoad(V.getNode())) { 5419 // Is the original load suitable? 5420 LoadSDNode *LN0 = cast<LoadSDNode>(V); 5421 5422 // FIXME: avoid the multi-use bug that is preventing lots of 5423 // of foldings to be detected, this is still wrong of course, but 5424 // give the temporary desired behavior, and if it happens that 5425 // the load has real more uses, during isel it will not fold, and 5426 // will generate poor code. 5427 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 5428 return false; 5429 5430 if (!HasShuffleIntoBitcast) 5431 return true; 5432 5433 // If there's a bitcast before the shuffle, check if the load type and 5434 // alignment is valid. 5435 unsigned Align = LN0->getAlignment(); 5436 unsigned NewAlign = 5437 TLI.getTargetData()->getABITypeAlignment( 5438 VT.getTypeForEVT(*DAG.getContext())); 5439 5440 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 5441 return false; 5442 } 5443 5444 return true; 5445} 5446 5447static 5448SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 5449 EVT VT = Op.getValueType(); 5450 5451 // Canonizalize to v2f64. 5452 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 5453 return DAG.getNode(ISD::BITCAST, dl, VT, 5454 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 5455 V1, DAG)); 5456} 5457 5458static 5459SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 5460 bool HasSSE2) { 5461 SDValue V1 = Op.getOperand(0); 5462 SDValue V2 = Op.getOperand(1); 5463 EVT VT = Op.getValueType(); 5464 5465 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 5466 5467 if (HasSSE2 && VT == MVT::v2f64) 5468 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 5469 5470 // v4f32 or v4i32 5471 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG); 5472} 5473 5474static 5475SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 5476 SDValue V1 = Op.getOperand(0); 5477 SDValue V2 = Op.getOperand(1); 5478 EVT VT = Op.getValueType(); 5479 5480 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 5481 "unsupported shuffle type"); 5482 5483 if (V2.getOpcode() == ISD::UNDEF) 5484 V2 = V1; 5485 5486 // v4i32 or v4f32 5487 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 5488} 5489 5490static 5491SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 5492 SDValue V1 = Op.getOperand(0); 5493 SDValue V2 = Op.getOperand(1); 5494 EVT VT = Op.getValueType(); 5495 unsigned NumElems = VT.getVectorNumElements(); 5496 5497 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 5498 // operand of these instructions is only memory, so check if there's a 5499 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 5500 // same masks. 5501 bool CanFoldLoad = false; 5502 5503 // Trivial case, when V2 comes from a load. 5504 if (MayFoldVectorLoad(V2)) 5505 CanFoldLoad = true; 5506 5507 // When V1 is a load, it can be folded later into a store in isel, example: 5508 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 5509 // turns into: 5510 // (MOVLPSmr addr:$src1, VR128:$src2) 5511 // So, recognize this potential and also use MOVLPS or MOVLPD 5512 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 5513 CanFoldLoad = true; 5514 5515 // Both of them can't be memory operations though. 5516 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2)) 5517 CanFoldLoad = false; 5518 5519 if (CanFoldLoad) { 5520 if (HasSSE2 && NumElems == 2) 5521 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 5522 5523 if (NumElems == 4) 5524 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 5525 } 5526 5527 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5528 // movl and movlp will both match v2i64, but v2i64 is never matched by 5529 // movl earlier because we make it strict to avoid messing with the movlp load 5530 // folding logic (see the code above getMOVLP call). Match it here then, 5531 // this is horrible, but will stay like this until we move all shuffle 5532 // matching to x86 specific nodes. Note that for the 1st condition all 5533 // types are matched with movsd. 5534 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp)) 5535 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5536 else if (HasSSE2) 5537 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5538 5539 5540 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 5541 5542 // Invert the operand order and use SHUFPS to match it. 5543 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1, 5544 X86::getShuffleSHUFImmediate(SVOp), DAG); 5545} 5546 5547static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) { 5548 switch(VT.getSimpleVT().SimpleTy) { 5549 case MVT::v4i32: return X86ISD::PUNPCKLDQ; 5550 case MVT::v2i64: return X86ISD::PUNPCKLQDQ; 5551 case MVT::v4f32: 5552 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS; 5553 case MVT::v2f64: 5554 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5555 case MVT::v8f32: return X86ISD::VUNPCKLPSY; 5556 case MVT::v4f64: return X86ISD::VUNPCKLPDY; 5557 case MVT::v16i8: return X86ISD::PUNPCKLBW; 5558 case MVT::v8i16: return X86ISD::PUNPCKLWD; 5559 default: 5560 llvm_unreachable("Unknown type for unpckl"); 5561 } 5562 return 0; 5563} 5564 5565static inline unsigned getUNPCKHOpcode(EVT VT) { 5566 switch(VT.getSimpleVT().SimpleTy) { 5567 case MVT::v4i32: return X86ISD::PUNPCKHDQ; 5568 case MVT::v2i64: return X86ISD::PUNPCKHQDQ; 5569 case MVT::v4f32: return X86ISD::UNPCKHPS; 5570 case MVT::v2f64: return X86ISD::UNPCKHPD; 5571 case MVT::v16i8: return X86ISD::PUNPCKHBW; 5572 case MVT::v8i16: return X86ISD::PUNPCKHWD; 5573 default: 5574 llvm_unreachable("Unknown type for unpckh"); 5575 } 5576 return 0; 5577} 5578 5579static 5580SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 5581 const TargetLowering &TLI, 5582 const X86Subtarget *Subtarget) { 5583 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5584 EVT VT = Op.getValueType(); 5585 DebugLoc dl = Op.getDebugLoc(); 5586 SDValue V1 = Op.getOperand(0); 5587 SDValue V2 = Op.getOperand(1); 5588 5589 if (isZeroShuffle(SVOp)) 5590 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl); 5591 5592 // Handle splat operations 5593 if (SVOp->isSplat()) { 5594 // Special case, this is the only place now where it's 5595 // allowed to return a vector_shuffle operation without 5596 // using a target specific node, because *hopefully* it 5597 // will be optimized away by the dag combiner. 5598 if (VT.getVectorNumElements() <= 4 && 5599 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 5600 return Op; 5601 5602 // Handle splats by matching through known masks 5603 if (VT.getVectorNumElements() <= 4) 5604 return SDValue(); 5605 5606 // Canonicalize all of the remaining to v4f32. 5607 return PromoteSplat(SVOp, DAG); 5608 } 5609 5610 // If the shuffle can be profitably rewritten as a narrower shuffle, then 5611 // do it! 5612 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 5613 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5614 if (NewOp.getNode()) 5615 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 5616 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 5617 // FIXME: Figure out a cleaner way to do this. 5618 // Try to make use of movq to zero out the top part. 5619 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 5620 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5621 if (NewOp.getNode()) { 5622 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 5623 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 5624 DAG, Subtarget, dl); 5625 } 5626 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 5627 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 5628 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 5629 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 5630 DAG, Subtarget, dl); 5631 } 5632 } 5633 return SDValue(); 5634} 5635 5636SDValue 5637X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 5638 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5639 SDValue V1 = Op.getOperand(0); 5640 SDValue V2 = Op.getOperand(1); 5641 EVT VT = Op.getValueType(); 5642 DebugLoc dl = Op.getDebugLoc(); 5643 unsigned NumElems = VT.getVectorNumElements(); 5644 bool isMMX = VT.getSizeInBits() == 64; 5645 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 5646 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 5647 bool V1IsSplat = false; 5648 bool V2IsSplat = false; 5649 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX(); 5650 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX(); 5651 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX(); 5652 MachineFunction &MF = DAG.getMachineFunction(); 5653 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 5654 5655 // Shuffle operations on MMX not supported. 5656 if (isMMX) 5657 return Op; 5658 5659 // Vector shuffle lowering takes 3 steps: 5660 // 5661 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 5662 // narrowing and commutation of operands should be handled. 5663 // 2) Matching of shuffles with known shuffle masks to x86 target specific 5664 // shuffle nodes. 5665 // 3) Rewriting of unmatched masks into new generic shuffle operations, 5666 // so the shuffle can be broken into other shuffles and the legalizer can 5667 // try the lowering again. 5668 // 5669 // The general ideia is that no vector_shuffle operation should be left to 5670 // be matched during isel, all of them must be converted to a target specific 5671 // node here. 5672 5673 // Normalize the input vectors. Here splats, zeroed vectors, profitable 5674 // narrowing and commutation of operands should be handled. The actual code 5675 // doesn't include all of those, work in progress... 5676 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 5677 if (NewOp.getNode()) 5678 return NewOp; 5679 5680 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 5681 // unpckh_undef). Only use pshufd if speed is more important than size. 5682 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 5683 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5684 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG); 5685 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 5686 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5687 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5688 5689 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef && 5690 RelaxedMayFoldVectorLoad(V1)) 5691 return getMOVDDup(Op, dl, V1, DAG); 5692 5693 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 5694 return getMOVHighToLow(Op, dl, DAG); 5695 5696 // Use to match splats 5697 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef && 5698 (VT == MVT::v2f64 || VT == MVT::v2i64)) 5699 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5700 5701 if (X86::isPSHUFDMask(SVOp)) { 5702 // The actual implementation will match the mask in the if above and then 5703 // during isel it can match several different instructions, not only pshufd 5704 // as its name says, sad but true, emulate the behavior for now... 5705 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 5706 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 5707 5708 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5709 5710 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 5711 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 5712 5713 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5714 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1, 5715 TargetMask, DAG); 5716 5717 if (VT == MVT::v4f32) 5718 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1, 5719 TargetMask, DAG); 5720 } 5721 5722 // Check if this can be converted into a logical shift. 5723 bool isLeft = false; 5724 unsigned ShAmt = 0; 5725 SDValue ShVal; 5726 bool isShift = getSubtarget()->hasSSE2() && 5727 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 5728 if (isShift && ShVal.hasOneUse()) { 5729 // If the shifted value has multiple uses, it may be cheaper to use 5730 // v_set0 + movlhps or movhlps, etc. 5731 EVT EltVT = VT.getVectorElementType(); 5732 ShAmt *= EltVT.getSizeInBits(); 5733 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5734 } 5735 5736 if (X86::isMOVLMask(SVOp)) { 5737 if (V1IsUndef) 5738 return V2; 5739 if (ISD::isBuildVectorAllZeros(V1.getNode())) 5740 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 5741 if (!X86::isMOVLPMask(SVOp)) { 5742 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 5743 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 5744 5745 if (VT == MVT::v4i32 || VT == MVT::v4f32) 5746 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 5747 } 5748 } 5749 5750 // FIXME: fold these into legal mask. 5751 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp)) 5752 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 5753 5754 if (X86::isMOVHLPSMask(SVOp)) 5755 return getMOVHighToLow(Op, dl, DAG); 5756 5757 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5758 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 5759 5760 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4) 5761 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 5762 5763 if (X86::isMOVLPMask(SVOp)) 5764 return getMOVLP(Op, dl, DAG, HasSSE2); 5765 5766 if (ShouldXformToMOVHLPS(SVOp) || 5767 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 5768 return CommuteVectorShuffle(SVOp, DAG); 5769 5770 if (isShift) { 5771 // No better options. Use a vshl / vsrl. 5772 EVT EltVT = VT.getVectorElementType(); 5773 ShAmt *= EltVT.getSizeInBits(); 5774 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 5775 } 5776 5777 bool Commuted = false; 5778 // FIXME: This should also accept a bitcast of a splat? Be careful, not 5779 // 1,1,1,1 -> v8i16 though. 5780 V1IsSplat = isSplatVector(V1.getNode()); 5781 V2IsSplat = isSplatVector(V2.getNode()); 5782 5783 // Canonicalize the splat or undef, if present, to be on the RHS. 5784 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) { 5785 Op = CommuteVectorShuffle(SVOp, DAG); 5786 SVOp = cast<ShuffleVectorSDNode>(Op); 5787 V1 = SVOp->getOperand(0); 5788 V2 = SVOp->getOperand(1); 5789 std::swap(V1IsSplat, V2IsSplat); 5790 std::swap(V1IsUndef, V2IsUndef); 5791 Commuted = true; 5792 } 5793 5794 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 5795 // Shuffling low element of v1 into undef, just return v1. 5796 if (V2IsUndef) 5797 return V1; 5798 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 5799 // the instruction selector will not match, so get a canonical MOVL with 5800 // swapped operands to undo the commute. 5801 return getMOVL(DAG, dl, VT, V2, V1); 5802 } 5803 5804 if (X86::isUNPCKLMask(SVOp)) 5805 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5806 dl, VT, V1, V2, DAG); 5807 5808 if (X86::isUNPCKHMask(SVOp)) 5809 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG); 5810 5811 if (V2IsSplat) { 5812 // Normalize mask so all entries that point to V2 points to its first 5813 // element then try to match unpck{h|l} again. If match, return a 5814 // new vector_shuffle with the corrected mask. 5815 SDValue NewMask = NormalizeMask(SVOp, DAG); 5816 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 5817 if (NSVOp != SVOp) { 5818 if (X86::isUNPCKLMask(NSVOp, true)) { 5819 return NewMask; 5820 } else if (X86::isUNPCKHMask(NSVOp, true)) { 5821 return NewMask; 5822 } 5823 } 5824 } 5825 5826 if (Commuted) { 5827 // Commute is back and try unpck* again. 5828 // FIXME: this seems wrong. 5829 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 5830 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 5831 5832 if (X86::isUNPCKLMask(NewSVOp)) 5833 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5834 dl, VT, V2, V1, DAG); 5835 5836 if (X86::isUNPCKHMask(NewSVOp)) 5837 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG); 5838 } 5839 5840 // Normalize the node to match x86 shuffle ops if needed 5841 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp)) 5842 return CommuteVectorShuffle(SVOp, DAG); 5843 5844 // The checks below are all present in isShuffleMaskLegal, but they are 5845 // inlined here right now to enable us to directly emit target specific 5846 // nodes, and remove one by one until they don't return Op anymore. 5847 SmallVector<int, 16> M; 5848 SVOp->getMask(M); 5849 5850 if (isPALIGNRMask(M, VT, HasSSSE3)) 5851 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 5852 X86::getShufflePALIGNRImmediate(SVOp), 5853 DAG); 5854 5855 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 5856 SVOp->getSplatIndex() == 0 && V2IsUndef) { 5857 if (VT == MVT::v2f64) { 5858 X86ISD::NodeType Opcode = 5859 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD; 5860 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG); 5861 } 5862 if (VT == MVT::v2i64) 5863 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG); 5864 } 5865 5866 if (isPSHUFHWMask(M, VT)) 5867 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 5868 X86::getShufflePSHUFHWImmediate(SVOp), 5869 DAG); 5870 5871 if (isPSHUFLWMask(M, VT)) 5872 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 5873 X86::getShufflePSHUFLWImmediate(SVOp), 5874 DAG); 5875 5876 if (isSHUFPMask(M, VT)) { 5877 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 5878 if (VT == MVT::v4f32 || VT == MVT::v4i32) 5879 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2, 5880 TargetMask, DAG); 5881 if (VT == MVT::v2f64 || VT == MVT::v2i64) 5882 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2, 5883 TargetMask, DAG); 5884 } 5885 5886 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 5887 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5888 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), 5889 dl, VT, V1, V1, DAG); 5890 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 5891 if (VT != MVT::v2i64 && VT != MVT::v2f64) 5892 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG); 5893 5894 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 5895 if (VT == MVT::v8i16) { 5896 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 5897 if (NewOp.getNode()) 5898 return NewOp; 5899 } 5900 5901 if (VT == MVT::v16i8) { 5902 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 5903 if (NewOp.getNode()) 5904 return NewOp; 5905 } 5906 5907 // Handle all 4 wide cases with a number of shuffles. 5908 if (NumElems == 4) 5909 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG); 5910 5911 return SDValue(); 5912} 5913 5914SDValue 5915X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 5916 SelectionDAG &DAG) const { 5917 EVT VT = Op.getValueType(); 5918 DebugLoc dl = Op.getDebugLoc(); 5919 if (VT.getSizeInBits() == 8) { 5920 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 5921 Op.getOperand(0), Op.getOperand(1)); 5922 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5923 DAG.getValueType(VT)); 5924 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5925 } else if (VT.getSizeInBits() == 16) { 5926 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5927 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 5928 if (Idx == 0) 5929 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 5930 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5931 DAG.getNode(ISD::BITCAST, dl, 5932 MVT::v4i32, 5933 Op.getOperand(0)), 5934 Op.getOperand(1))); 5935 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 5936 Op.getOperand(0), Op.getOperand(1)); 5937 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 5938 DAG.getValueType(VT)); 5939 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 5940 } else if (VT == MVT::f32) { 5941 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 5942 // the result back to FR32 register. It's only worth matching if the 5943 // result has a single use which is a store or a bitcast to i32. And in 5944 // the case of a store, it's not worth it if the index is a constant 0, 5945 // because a MOVSSmr can be used instead, which is smaller and faster. 5946 if (!Op.hasOneUse()) 5947 return SDValue(); 5948 SDNode *User = *Op.getNode()->use_begin(); 5949 if ((User->getOpcode() != ISD::STORE || 5950 (isa<ConstantSDNode>(Op.getOperand(1)) && 5951 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 5952 (User->getOpcode() != ISD::BITCAST || 5953 User->getValueType(0) != MVT::i32)) 5954 return SDValue(); 5955 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 5956 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 5957 Op.getOperand(0)), 5958 Op.getOperand(1)); 5959 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 5960 } else if (VT == MVT::i32) { 5961 // ExtractPS works with constant index. 5962 if (isa<ConstantSDNode>(Op.getOperand(1))) 5963 return Op; 5964 } 5965 return SDValue(); 5966} 5967 5968 5969SDValue 5970X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 5971 SelectionDAG &DAG) const { 5972 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5973 return SDValue(); 5974 5975 SDValue Vec = Op.getOperand(0); 5976 EVT VecVT = Vec.getValueType(); 5977 5978 // If this is a 256-bit vector result, first extract the 128-bit 5979 // vector and then extract from the 128-bit vector. 5980 if (VecVT.getSizeInBits() > 128) { 5981 DebugLoc dl = Op.getNode()->getDebugLoc(); 5982 unsigned NumElems = VecVT.getVectorNumElements(); 5983 SDValue Idx = Op.getOperand(1); 5984 5985 if (!isa<ConstantSDNode>(Idx)) 5986 return SDValue(); 5987 5988 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128); 5989 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5990 5991 // Get the 128-bit vector. 5992 bool Upper = IdxVal >= ExtractNumElems; 5993 Vec = Extract128BitVector(Vec, Idx, DAG, dl); 5994 5995 // Extract from it. 5996 SDValue ScaledIdx = Idx; 5997 if (Upper) 5998 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx, 5999 DAG.getConstant(ExtractNumElems, 6000 Idx.getValueType())); 6001 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 6002 ScaledIdx); 6003 } 6004 6005 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 6006 6007 if (Subtarget->hasSSE41()) { 6008 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 6009 if (Res.getNode()) 6010 return Res; 6011 } 6012 6013 EVT VT = Op.getValueType(); 6014 DebugLoc dl = Op.getDebugLoc(); 6015 // TODO: handle v16i8. 6016 if (VT.getSizeInBits() == 16) { 6017 SDValue Vec = Op.getOperand(0); 6018 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6019 if (Idx == 0) 6020 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6021 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6022 DAG.getNode(ISD::BITCAST, dl, 6023 MVT::v4i32, Vec), 6024 Op.getOperand(1))); 6025 // Transform it so it match pextrw which produces a 32-bit result. 6026 EVT EltVT = MVT::i32; 6027 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 6028 Op.getOperand(0), Op.getOperand(1)); 6029 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 6030 DAG.getValueType(VT)); 6031 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6032 } else if (VT.getSizeInBits() == 32) { 6033 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6034 if (Idx == 0) 6035 return Op; 6036 6037 // SHUFPS the element to the lowest double word, then movss. 6038 int Mask[4] = { Idx, -1, -1, -1 }; 6039 EVT VVT = Op.getOperand(0).getValueType(); 6040 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6041 DAG.getUNDEF(VVT), Mask); 6042 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6043 DAG.getIntPtrConstant(0)); 6044 } else if (VT.getSizeInBits() == 64) { 6045 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 6046 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 6047 // to match extract_elt for f64. 6048 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6049 if (Idx == 0) 6050 return Op; 6051 6052 // UNPCKHPD the element to the lowest double word, then movsd. 6053 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 6054 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 6055 int Mask[2] = { 1, -1 }; 6056 EVT VVT = Op.getOperand(0).getValueType(); 6057 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 6058 DAG.getUNDEF(VVT), Mask); 6059 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 6060 DAG.getIntPtrConstant(0)); 6061 } 6062 6063 return SDValue(); 6064} 6065 6066SDValue 6067X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 6068 SelectionDAG &DAG) const { 6069 EVT VT = Op.getValueType(); 6070 EVT EltVT = VT.getVectorElementType(); 6071 DebugLoc dl = Op.getDebugLoc(); 6072 6073 SDValue N0 = Op.getOperand(0); 6074 SDValue N1 = Op.getOperand(1); 6075 SDValue N2 = Op.getOperand(2); 6076 6077 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 6078 isa<ConstantSDNode>(N2)) { 6079 unsigned Opc; 6080 if (VT == MVT::v8i16) 6081 Opc = X86ISD::PINSRW; 6082 else if (VT == MVT::v16i8) 6083 Opc = X86ISD::PINSRB; 6084 else 6085 Opc = X86ISD::PINSRB; 6086 6087 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 6088 // argument. 6089 if (N1.getValueType() != MVT::i32) 6090 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6091 if (N2.getValueType() != MVT::i32) 6092 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6093 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 6094 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 6095 // Bits [7:6] of the constant are the source select. This will always be 6096 // zero here. The DAG Combiner may combine an extract_elt index into these 6097 // bits. For example (insert (extract, 3), 2) could be matched by putting 6098 // the '3' into bits [7:6] of X86ISD::INSERTPS. 6099 // Bits [5:4] of the constant are the destination select. This is the 6100 // value of the incoming immediate. 6101 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 6102 // combine either bitwise AND or insert of float 0.0 to set these bits. 6103 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 6104 // Create this as a scalar to vector.. 6105 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 6106 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 6107 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) { 6108 // PINSR* works with constant index. 6109 return Op; 6110 } 6111 return SDValue(); 6112} 6113 6114SDValue 6115X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 6116 EVT VT = Op.getValueType(); 6117 EVT EltVT = VT.getVectorElementType(); 6118 6119 DebugLoc dl = Op.getDebugLoc(); 6120 SDValue N0 = Op.getOperand(0); 6121 SDValue N1 = Op.getOperand(1); 6122 SDValue N2 = Op.getOperand(2); 6123 6124 // If this is a 256-bit vector result, first insert into a 128-bit 6125 // vector and then insert into the 256-bit vector. 6126 if (VT.getSizeInBits() > 128) { 6127 if (!isa<ConstantSDNode>(N2)) 6128 return SDValue(); 6129 6130 // Get the 128-bit vector. 6131 unsigned NumElems = VT.getVectorNumElements(); 6132 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 6133 bool Upper = IdxVal >= NumElems / 2; 6134 6135 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl); 6136 6137 // Insert into it. 6138 SDValue ScaledN2 = N2; 6139 if (Upper) 6140 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2, 6141 DAG.getConstant(NumElems / 6142 (VT.getSizeInBits() / 128), 6143 N2.getValueType())); 6144 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0, 6145 N1, ScaledN2); 6146 6147 // Insert the 128-bit vector 6148 // FIXME: Why UNDEF? 6149 return Insert128BitVector(N0, Op, N2, DAG, dl); 6150 } 6151 6152 if (Subtarget->hasSSE41()) 6153 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 6154 6155 if (EltVT == MVT::i8) 6156 return SDValue(); 6157 6158 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 6159 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 6160 // as its second argument. 6161 if (N1.getValueType() != MVT::i32) 6162 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 6163 if (N2.getValueType() != MVT::i32) 6164 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 6165 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 6166 } 6167 return SDValue(); 6168} 6169 6170SDValue 6171X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 6172 LLVMContext *Context = DAG.getContext(); 6173 DebugLoc dl = Op.getDebugLoc(); 6174 EVT OpVT = Op.getValueType(); 6175 6176 // If this is a 256-bit vector result, first insert into a 128-bit 6177 // vector and then insert into the 256-bit vector. 6178 if (OpVT.getSizeInBits() > 128) { 6179 // Insert into a 128-bit vector. 6180 EVT VT128 = EVT::getVectorVT(*Context, 6181 OpVT.getVectorElementType(), 6182 OpVT.getVectorNumElements() / 2); 6183 6184 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 6185 6186 // Insert the 128-bit vector. 6187 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 6188 DAG.getConstant(0, MVT::i32), 6189 DAG, dl); 6190 } 6191 6192 if (Op.getValueType() == MVT::v1i64 && 6193 Op.getOperand(0).getValueType() == MVT::i64) 6194 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 6195 6196 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 6197 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 6198 "Expected an SSE type!"); 6199 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 6200 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 6201} 6202 6203// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 6204// a simple subregister reference or explicit instructions to grab 6205// upper bits of a vector. 6206SDValue 6207X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6208 if (Subtarget->hasAVX()) { 6209 DebugLoc dl = Op.getNode()->getDebugLoc(); 6210 SDValue Vec = Op.getNode()->getOperand(0); 6211 SDValue Idx = Op.getNode()->getOperand(1); 6212 6213 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 6214 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 6215 return Extract128BitVector(Vec, Idx, DAG, dl); 6216 } 6217 } 6218 return SDValue(); 6219} 6220 6221// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 6222// simple superregister reference or explicit instructions to insert 6223// the upper bits of a vector. 6224SDValue 6225X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 6226 if (Subtarget->hasAVX()) { 6227 DebugLoc dl = Op.getNode()->getDebugLoc(); 6228 SDValue Vec = Op.getNode()->getOperand(0); 6229 SDValue SubVec = Op.getNode()->getOperand(1); 6230 SDValue Idx = Op.getNode()->getOperand(2); 6231 6232 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 6233 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 6234 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 6235 } 6236 } 6237 return SDValue(); 6238} 6239 6240// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 6241// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 6242// one of the above mentioned nodes. It has to be wrapped because otherwise 6243// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 6244// be used to form addressing mode. These wrapped nodes will be selected 6245// into MOV32ri. 6246SDValue 6247X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 6248 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 6249 6250 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6251 // global base reg. 6252 unsigned char OpFlag = 0; 6253 unsigned WrapperKind = X86ISD::Wrapper; 6254 CodeModel::Model M = getTargetMachine().getCodeModel(); 6255 6256 if (Subtarget->isPICStyleRIPRel() && 6257 (M == CodeModel::Small || M == CodeModel::Kernel)) 6258 WrapperKind = X86ISD::WrapperRIP; 6259 else if (Subtarget->isPICStyleGOT()) 6260 OpFlag = X86II::MO_GOTOFF; 6261 else if (Subtarget->isPICStyleStubPIC()) 6262 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6263 6264 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 6265 CP->getAlignment(), 6266 CP->getOffset(), OpFlag); 6267 DebugLoc DL = CP->getDebugLoc(); 6268 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6269 // With PIC, the address is actually $g + Offset. 6270 if (OpFlag) { 6271 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6272 DAG.getNode(X86ISD::GlobalBaseReg, 6273 DebugLoc(), getPointerTy()), 6274 Result); 6275 } 6276 6277 return Result; 6278} 6279 6280SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 6281 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 6282 6283 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6284 // global base reg. 6285 unsigned char OpFlag = 0; 6286 unsigned WrapperKind = X86ISD::Wrapper; 6287 CodeModel::Model M = getTargetMachine().getCodeModel(); 6288 6289 if (Subtarget->isPICStyleRIPRel() && 6290 (M == CodeModel::Small || M == CodeModel::Kernel)) 6291 WrapperKind = X86ISD::WrapperRIP; 6292 else if (Subtarget->isPICStyleGOT()) 6293 OpFlag = X86II::MO_GOTOFF; 6294 else if (Subtarget->isPICStyleStubPIC()) 6295 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6296 6297 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 6298 OpFlag); 6299 DebugLoc DL = JT->getDebugLoc(); 6300 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6301 6302 // With PIC, the address is actually $g + Offset. 6303 if (OpFlag) 6304 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6305 DAG.getNode(X86ISD::GlobalBaseReg, 6306 DebugLoc(), getPointerTy()), 6307 Result); 6308 6309 return Result; 6310} 6311 6312SDValue 6313X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 6314 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 6315 6316 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6317 // global base reg. 6318 unsigned char OpFlag = 0; 6319 unsigned WrapperKind = X86ISD::Wrapper; 6320 CodeModel::Model M = getTargetMachine().getCodeModel(); 6321 6322 if (Subtarget->isPICStyleRIPRel() && 6323 (M == CodeModel::Small || M == CodeModel::Kernel)) 6324 WrapperKind = X86ISD::WrapperRIP; 6325 else if (Subtarget->isPICStyleGOT()) 6326 OpFlag = X86II::MO_GOTOFF; 6327 else if (Subtarget->isPICStyleStubPIC()) 6328 OpFlag = X86II::MO_PIC_BASE_OFFSET; 6329 6330 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 6331 6332 DebugLoc DL = Op.getDebugLoc(); 6333 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6334 6335 6336 // With PIC, the address is actually $g + Offset. 6337 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 6338 !Subtarget->is64Bit()) { 6339 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6340 DAG.getNode(X86ISD::GlobalBaseReg, 6341 DebugLoc(), getPointerTy()), 6342 Result); 6343 } 6344 6345 return Result; 6346} 6347 6348SDValue 6349X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 6350 // Create the TargetBlockAddressAddress node. 6351 unsigned char OpFlags = 6352 Subtarget->ClassifyBlockAddressReference(); 6353 CodeModel::Model M = getTargetMachine().getCodeModel(); 6354 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 6355 DebugLoc dl = Op.getDebugLoc(); 6356 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 6357 /*isTarget=*/true, OpFlags); 6358 6359 if (Subtarget->isPICStyleRIPRel() && 6360 (M == CodeModel::Small || M == CodeModel::Kernel)) 6361 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6362 else 6363 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6364 6365 // With PIC, the address is actually $g + Offset. 6366 if (isGlobalRelativeToPICBase(OpFlags)) { 6367 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6368 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6369 Result); 6370 } 6371 6372 return Result; 6373} 6374 6375SDValue 6376X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 6377 int64_t Offset, 6378 SelectionDAG &DAG) const { 6379 // Create the TargetGlobalAddress node, folding in the constant 6380 // offset if it is legal. 6381 unsigned char OpFlags = 6382 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 6383 CodeModel::Model M = getTargetMachine().getCodeModel(); 6384 SDValue Result; 6385 if (OpFlags == X86II::MO_NO_FLAG && 6386 X86::isOffsetSuitableForCodeModel(Offset, M)) { 6387 // A direct static reference to a global. 6388 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 6389 Offset = 0; 6390 } else { 6391 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 6392 } 6393 6394 if (Subtarget->isPICStyleRIPRel() && 6395 (M == CodeModel::Small || M == CodeModel::Kernel)) 6396 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 6397 else 6398 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 6399 6400 // With PIC, the address is actually $g + Offset. 6401 if (isGlobalRelativeToPICBase(OpFlags)) { 6402 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 6403 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 6404 Result); 6405 } 6406 6407 // For globals that require a load from a stub to get the address, emit the 6408 // load. 6409 if (isGlobalStubReference(OpFlags)) 6410 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 6411 MachinePointerInfo::getGOT(), false, false, 0); 6412 6413 // If there was a non-zero offset that we didn't fold, create an explicit 6414 // addition for it. 6415 if (Offset != 0) 6416 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 6417 DAG.getConstant(Offset, getPointerTy())); 6418 6419 return Result; 6420} 6421 6422SDValue 6423X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 6424 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 6425 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 6426 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 6427} 6428 6429static SDValue 6430GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 6431 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 6432 unsigned char OperandFlags) { 6433 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6434 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6435 DebugLoc dl = GA->getDebugLoc(); 6436 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6437 GA->getValueType(0), 6438 GA->getOffset(), 6439 OperandFlags); 6440 if (InFlag) { 6441 SDValue Ops[] = { Chain, TGA, *InFlag }; 6442 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 6443 } else { 6444 SDValue Ops[] = { Chain, TGA }; 6445 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 6446 } 6447 6448 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 6449 MFI->setAdjustsStack(true); 6450 6451 SDValue Flag = Chain.getValue(1); 6452 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 6453} 6454 6455// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 6456static SDValue 6457LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6458 const EVT PtrVT) { 6459 SDValue InFlag; 6460 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 6461 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 6462 DAG.getNode(X86ISD::GlobalBaseReg, 6463 DebugLoc(), PtrVT), InFlag); 6464 InFlag = Chain.getValue(1); 6465 6466 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 6467} 6468 6469// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 6470static SDValue 6471LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6472 const EVT PtrVT) { 6473 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 6474 X86::RAX, X86II::MO_TLSGD); 6475} 6476 6477// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 6478// "local exec" model. 6479static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 6480 const EVT PtrVT, TLSModel::Model model, 6481 bool is64Bit) { 6482 DebugLoc dl = GA->getDebugLoc(); 6483 6484 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 6485 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 6486 is64Bit ? 257 : 256)); 6487 6488 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 6489 DAG.getIntPtrConstant(0), 6490 MachinePointerInfo(Ptr), false, false, 0); 6491 6492 unsigned char OperandFlags = 0; 6493 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 6494 // initialexec. 6495 unsigned WrapperKind = X86ISD::Wrapper; 6496 if (model == TLSModel::LocalExec) { 6497 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 6498 } else if (is64Bit) { 6499 assert(model == TLSModel::InitialExec); 6500 OperandFlags = X86II::MO_GOTTPOFF; 6501 WrapperKind = X86ISD::WrapperRIP; 6502 } else { 6503 assert(model == TLSModel::InitialExec); 6504 OperandFlags = X86II::MO_INDNTPOFF; 6505 } 6506 6507 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 6508 // exec) 6509 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 6510 GA->getValueType(0), 6511 GA->getOffset(), OperandFlags); 6512 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 6513 6514 if (model == TLSModel::InitialExec) 6515 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 6516 MachinePointerInfo::getGOT(), false, false, 0); 6517 6518 // The address of the thread local variable is the add of the thread 6519 // pointer with the offset of the variable. 6520 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 6521} 6522 6523SDValue 6524X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 6525 6526 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 6527 const GlobalValue *GV = GA->getGlobal(); 6528 6529 if (Subtarget->isTargetELF()) { 6530 // TODO: implement the "local dynamic" model 6531 // TODO: implement the "initial exec"model for pic executables 6532 6533 // If GV is an alias then use the aliasee for determining 6534 // thread-localness. 6535 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 6536 GV = GA->resolveAliasedGlobal(false); 6537 6538 TLSModel::Model model 6539 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 6540 6541 switch (model) { 6542 case TLSModel::GeneralDynamic: 6543 case TLSModel::LocalDynamic: // not implemented 6544 if (Subtarget->is64Bit()) 6545 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 6546 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 6547 6548 case TLSModel::InitialExec: 6549 case TLSModel::LocalExec: 6550 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 6551 Subtarget->is64Bit()); 6552 } 6553 } else if (Subtarget->isTargetDarwin()) { 6554 // Darwin only has one model of TLS. Lower to that. 6555 unsigned char OpFlag = 0; 6556 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 6557 X86ISD::WrapperRIP : X86ISD::Wrapper; 6558 6559 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 6560 // global base reg. 6561 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 6562 !Subtarget->is64Bit(); 6563 if (PIC32) 6564 OpFlag = X86II::MO_TLVP_PIC_BASE; 6565 else 6566 OpFlag = X86II::MO_TLVP; 6567 DebugLoc DL = Op.getDebugLoc(); 6568 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 6569 GA->getValueType(0), 6570 GA->getOffset(), OpFlag); 6571 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 6572 6573 // With PIC32, the address is actually $g + Offset. 6574 if (PIC32) 6575 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 6576 DAG.getNode(X86ISD::GlobalBaseReg, 6577 DebugLoc(), getPointerTy()), 6578 Offset); 6579 6580 // Lowering the machine isd will make sure everything is in the right 6581 // location. 6582 SDValue Chain = DAG.getEntryNode(); 6583 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6584 SDValue Args[] = { Chain, Offset }; 6585 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 6586 6587 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 6588 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 6589 MFI->setAdjustsStack(true); 6590 6591 // And our return value (tls address) is in the standard call return value 6592 // location. 6593 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 6594 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy()); 6595 } 6596 6597 assert(false && 6598 "TLS not implemented for this target."); 6599 6600 llvm_unreachable("Unreachable"); 6601 return SDValue(); 6602} 6603 6604 6605/// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and 6606/// take a 2 x i32 value to shift plus a shift amount. 6607SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 6608 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6609 EVT VT = Op.getValueType(); 6610 unsigned VTBits = VT.getSizeInBits(); 6611 DebugLoc dl = Op.getDebugLoc(); 6612 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 6613 SDValue ShOpLo = Op.getOperand(0); 6614 SDValue ShOpHi = Op.getOperand(1); 6615 SDValue ShAmt = Op.getOperand(2); 6616 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 6617 DAG.getConstant(VTBits - 1, MVT::i8)) 6618 : DAG.getConstant(0, VT); 6619 6620 SDValue Tmp2, Tmp3; 6621 if (Op.getOpcode() == ISD::SHL_PARTS) { 6622 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 6623 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6624 } else { 6625 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 6626 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 6627 } 6628 6629 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 6630 DAG.getConstant(VTBits, MVT::i8)); 6631 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 6632 AndNode, DAG.getConstant(0, MVT::i8)); 6633 6634 SDValue Hi, Lo; 6635 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 6636 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 6637 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 6638 6639 if (Op.getOpcode() == ISD::SHL_PARTS) { 6640 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6641 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6642 } else { 6643 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 6644 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 6645 } 6646 6647 SDValue Ops[2] = { Lo, Hi }; 6648 return DAG.getMergeValues(Ops, 2, dl); 6649} 6650 6651SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 6652 SelectionDAG &DAG) const { 6653 EVT SrcVT = Op.getOperand(0).getValueType(); 6654 6655 if (SrcVT.isVector()) 6656 return SDValue(); 6657 6658 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 6659 "Unknown SINT_TO_FP to lower!"); 6660 6661 // These are really Legal; return the operand so the caller accepts it as 6662 // Legal. 6663 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 6664 return Op; 6665 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 6666 Subtarget->is64Bit()) { 6667 return Op; 6668 } 6669 6670 DebugLoc dl = Op.getDebugLoc(); 6671 unsigned Size = SrcVT.getSizeInBits()/8; 6672 MachineFunction &MF = DAG.getMachineFunction(); 6673 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 6674 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6675 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6676 StackSlot, 6677 MachinePointerInfo::getFixedStack(SSFI), 6678 false, false, 0); 6679 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 6680} 6681 6682SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 6683 SDValue StackSlot, 6684 SelectionDAG &DAG) const { 6685 // Build the FILD 6686 DebugLoc DL = Op.getDebugLoc(); 6687 SDVTList Tys; 6688 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 6689 if (useSSE) 6690 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 6691 else 6692 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 6693 6694 unsigned ByteSize = SrcVT.getSizeInBits()/8; 6695 6696 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 6697 MachineMemOperand *MMO = 6698 DAG.getMachineFunction() 6699 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6700 MachineMemOperand::MOLoad, ByteSize, ByteSize); 6701 6702 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 6703 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 6704 X86ISD::FILD, DL, 6705 Tys, Ops, array_lengthof(Ops), 6706 SrcVT, MMO); 6707 6708 if (useSSE) { 6709 Chain = Result.getValue(1); 6710 SDValue InFlag = Result.getValue(2); 6711 6712 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 6713 // shouldn't be necessary except that RFP cannot be live across 6714 // multiple blocks. When stackifier is fixed, they can be uncoupled. 6715 MachineFunction &MF = DAG.getMachineFunction(); 6716 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 6717 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 6718 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6719 Tys = DAG.getVTList(MVT::Other); 6720 SDValue Ops[] = { 6721 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 6722 }; 6723 MachineMemOperand *MMO = 6724 DAG.getMachineFunction() 6725 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6726 MachineMemOperand::MOStore, SSFISize, SSFISize); 6727 6728 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 6729 Ops, array_lengthof(Ops), 6730 Op.getValueType(), MMO); 6731 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 6732 MachinePointerInfo::getFixedStack(SSFI), 6733 false, false, 0); 6734 } 6735 6736 return Result; 6737} 6738 6739// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 6740SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 6741 SelectionDAG &DAG) const { 6742 // This algorithm is not obvious. Here it is in C code, more or less: 6743 /* 6744 double uint64_to_double( uint32_t hi, uint32_t lo ) { 6745 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 6746 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 6747 6748 // Copy ints to xmm registers. 6749 __m128i xh = _mm_cvtsi32_si128( hi ); 6750 __m128i xl = _mm_cvtsi32_si128( lo ); 6751 6752 // Combine into low half of a single xmm register. 6753 __m128i x = _mm_unpacklo_epi32( xh, xl ); 6754 __m128d d; 6755 double sd; 6756 6757 // Merge in appropriate exponents to give the integer bits the right 6758 // magnitude. 6759 x = _mm_unpacklo_epi32( x, exp ); 6760 6761 // Subtract away the biases to deal with the IEEE-754 double precision 6762 // implicit 1. 6763 d = _mm_sub_pd( (__m128d) x, bias ); 6764 6765 // All conversions up to here are exact. The correctly rounded result is 6766 // calculated using the current rounding mode using the following 6767 // horizontal add. 6768 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 6769 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 6770 // store doesn't really need to be here (except 6771 // maybe to zero the other double) 6772 return sd; 6773 } 6774 */ 6775 6776 DebugLoc dl = Op.getDebugLoc(); 6777 LLVMContext *Context = DAG.getContext(); 6778 6779 // Build some magic constants. 6780 std::vector<Constant*> CV0; 6781 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 6782 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 6783 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6784 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 6785 Constant *C0 = ConstantVector::get(CV0); 6786 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 6787 6788 std::vector<Constant*> CV1; 6789 CV1.push_back( 6790 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 6791 CV1.push_back( 6792 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 6793 Constant *C1 = ConstantVector::get(CV1); 6794 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 6795 6796 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6797 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6798 Op.getOperand(0), 6799 DAG.getIntPtrConstant(1))); 6800 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6801 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6802 Op.getOperand(0), 6803 DAG.getIntPtrConstant(0))); 6804 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 6805 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 6806 MachinePointerInfo::getConstantPool(), 6807 false, false, 16); 6808 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 6809 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 6810 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 6811 MachinePointerInfo::getConstantPool(), 6812 false, false, 16); 6813 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 6814 6815 // Add the halves; easiest way is to swap them into another reg first. 6816 int ShufMask[2] = { 1, -1 }; 6817 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 6818 DAG.getUNDEF(MVT::v2f64), ShufMask); 6819 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 6820 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 6821 DAG.getIntPtrConstant(0)); 6822} 6823 6824// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 6825SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 6826 SelectionDAG &DAG) const { 6827 DebugLoc dl = Op.getDebugLoc(); 6828 // FP constant to bias correct the final result. 6829 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 6830 MVT::f64); 6831 6832 // Load the 32-bit value into an XMM register. 6833 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 6834 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 6835 Op.getOperand(0), 6836 DAG.getIntPtrConstant(0))); 6837 6838 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6839 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 6840 DAG.getIntPtrConstant(0)); 6841 6842 // Or the load with the bias. 6843 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 6844 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6845 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6846 MVT::v2f64, Load)), 6847 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 6848 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6849 MVT::v2f64, Bias))); 6850 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 6851 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 6852 DAG.getIntPtrConstant(0)); 6853 6854 // Subtract the bias. 6855 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 6856 6857 // Handle final rounding. 6858 EVT DestVT = Op.getValueType(); 6859 6860 if (DestVT.bitsLT(MVT::f64)) { 6861 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 6862 DAG.getIntPtrConstant(0)); 6863 } else if (DestVT.bitsGT(MVT::f64)) { 6864 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 6865 } 6866 6867 // Handle final rounding. 6868 return Sub; 6869} 6870 6871SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 6872 SelectionDAG &DAG) const { 6873 SDValue N0 = Op.getOperand(0); 6874 DebugLoc dl = Op.getDebugLoc(); 6875 6876 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 6877 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 6878 // the optimization here. 6879 if (DAG.SignBitIsZero(N0)) 6880 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 6881 6882 EVT SrcVT = N0.getValueType(); 6883 EVT DstVT = Op.getValueType(); 6884 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 6885 return LowerUINT_TO_FP_i64(Op, DAG); 6886 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 6887 return LowerUINT_TO_FP_i32(Op, DAG); 6888 6889 // Make a 64-bit buffer, and use it to build an FILD. 6890 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 6891 if (SrcVT == MVT::i32) { 6892 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 6893 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 6894 getPointerTy(), StackSlot, WordOff); 6895 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6896 StackSlot, MachinePointerInfo(), 6897 false, false, 0); 6898 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 6899 OffsetSlot, MachinePointerInfo(), 6900 false, false, 0); 6901 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 6902 return Fild; 6903 } 6904 6905 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 6906 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 6907 StackSlot, MachinePointerInfo(), 6908 false, false, 0); 6909 // For i64 source, we need to add the appropriate power of 2 if the input 6910 // was negative. This is the same as the optimization in 6911 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 6912 // we must be careful to do the computation in x87 extended precision, not 6913 // in SSE. (The generic code can't know it's OK to do this, or how to.) 6914 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 6915 MachineMemOperand *MMO = 6916 DAG.getMachineFunction() 6917 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 6918 MachineMemOperand::MOLoad, 8, 8); 6919 6920 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 6921 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 6922 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 6923 MVT::i64, MMO); 6924 6925 APInt FF(32, 0x5F800000ULL); 6926 6927 // Check whether the sign bit is set. 6928 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 6929 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 6930 ISD::SETLT); 6931 6932 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 6933 SDValue FudgePtr = DAG.getConstantPool( 6934 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 6935 getPointerTy()); 6936 6937 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 6938 SDValue Zero = DAG.getIntPtrConstant(0); 6939 SDValue Four = DAG.getIntPtrConstant(4); 6940 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 6941 Zero, Four); 6942 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 6943 6944 // Load the value out, extending it from f32 to f80. 6945 // FIXME: Avoid the extend by constructing the right constant pool? 6946 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 6947 FudgePtr, MachinePointerInfo::getConstantPool(), 6948 MVT::f32, false, false, 4); 6949 // Extend everything to 80 bits to force it to be done on x87. 6950 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 6951 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 6952} 6953 6954std::pair<SDValue,SDValue> X86TargetLowering:: 6955FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 6956 DebugLoc DL = Op.getDebugLoc(); 6957 6958 EVT DstTy = Op.getValueType(); 6959 6960 if (!IsSigned) { 6961 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 6962 DstTy = MVT::i64; 6963 } 6964 6965 assert(DstTy.getSimpleVT() <= MVT::i64 && 6966 DstTy.getSimpleVT() >= MVT::i16 && 6967 "Unknown FP_TO_SINT to lower!"); 6968 6969 // These are really Legal. 6970 if (DstTy == MVT::i32 && 6971 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 6972 return std::make_pair(SDValue(), SDValue()); 6973 if (Subtarget->is64Bit() && 6974 DstTy == MVT::i64 && 6975 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 6976 return std::make_pair(SDValue(), SDValue()); 6977 6978 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 6979 // stack slot. 6980 MachineFunction &MF = DAG.getMachineFunction(); 6981 unsigned MemSize = DstTy.getSizeInBits()/8; 6982 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 6983 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 6984 6985 6986 6987 unsigned Opc; 6988 switch (DstTy.getSimpleVT().SimpleTy) { 6989 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 6990 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 6991 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 6992 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 6993 } 6994 6995 SDValue Chain = DAG.getEntryNode(); 6996 SDValue Value = Op.getOperand(0); 6997 EVT TheVT = Op.getOperand(0).getValueType(); 6998 if (isScalarFPTypeInSSEReg(TheVT)) { 6999 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 7000 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 7001 MachinePointerInfo::getFixedStack(SSFI), 7002 false, false, 0); 7003 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 7004 SDValue Ops[] = { 7005 Chain, StackSlot, DAG.getValueType(TheVT) 7006 }; 7007 7008 MachineMemOperand *MMO = 7009 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7010 MachineMemOperand::MOLoad, MemSize, MemSize); 7011 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 7012 DstTy, MMO); 7013 Chain = Value.getValue(1); 7014 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7015 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7016 } 7017 7018 MachineMemOperand *MMO = 7019 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7020 MachineMemOperand::MOStore, MemSize, MemSize); 7021 7022 // Build the FP_TO_INT*_IN_MEM 7023 SDValue Ops[] = { Chain, Value, StackSlot }; 7024 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 7025 Ops, 3, DstTy, MMO); 7026 7027 return std::make_pair(FIST, StackSlot); 7028} 7029 7030SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 7031 SelectionDAG &DAG) const { 7032 if (Op.getValueType().isVector()) 7033 return SDValue(); 7034 7035 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 7036 SDValue FIST = Vals.first, StackSlot = Vals.second; 7037 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 7038 if (FIST.getNode() == 0) return Op; 7039 7040 // Load the result. 7041 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7042 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7043} 7044 7045SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 7046 SelectionDAG &DAG) const { 7047 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 7048 SDValue FIST = Vals.first, StackSlot = Vals.second; 7049 assert(FIST.getNode() && "Unexpected failure"); 7050 7051 // Load the result. 7052 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 7053 FIST, StackSlot, MachinePointerInfo(), false, false, 0); 7054} 7055 7056SDValue X86TargetLowering::LowerFABS(SDValue Op, 7057 SelectionDAG &DAG) const { 7058 LLVMContext *Context = DAG.getContext(); 7059 DebugLoc dl = Op.getDebugLoc(); 7060 EVT VT = Op.getValueType(); 7061 EVT EltVT = VT; 7062 if (VT.isVector()) 7063 EltVT = VT.getVectorElementType(); 7064 std::vector<Constant*> CV; 7065 if (EltVT == MVT::f64) { 7066 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 7067 CV.push_back(C); 7068 CV.push_back(C); 7069 } else { 7070 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 7071 CV.push_back(C); 7072 CV.push_back(C); 7073 CV.push_back(C); 7074 CV.push_back(C); 7075 } 7076 Constant *C = ConstantVector::get(CV); 7077 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7078 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7079 MachinePointerInfo::getConstantPool(), 7080 false, false, 16); 7081 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 7082} 7083 7084SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 7085 LLVMContext *Context = DAG.getContext(); 7086 DebugLoc dl = Op.getDebugLoc(); 7087 EVT VT = Op.getValueType(); 7088 EVT EltVT = VT; 7089 if (VT.isVector()) 7090 EltVT = VT.getVectorElementType(); 7091 std::vector<Constant*> CV; 7092 if (EltVT == MVT::f64) { 7093 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 7094 CV.push_back(C); 7095 CV.push_back(C); 7096 } else { 7097 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 7098 CV.push_back(C); 7099 CV.push_back(C); 7100 CV.push_back(C); 7101 CV.push_back(C); 7102 } 7103 Constant *C = ConstantVector::get(CV); 7104 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7105 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7106 MachinePointerInfo::getConstantPool(), 7107 false, false, 16); 7108 if (VT.isVector()) { 7109 return DAG.getNode(ISD::BITCAST, dl, VT, 7110 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 7111 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7112 Op.getOperand(0)), 7113 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 7114 } else { 7115 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 7116 } 7117} 7118 7119SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 7120 LLVMContext *Context = DAG.getContext(); 7121 SDValue Op0 = Op.getOperand(0); 7122 SDValue Op1 = Op.getOperand(1); 7123 DebugLoc dl = Op.getDebugLoc(); 7124 EVT VT = Op.getValueType(); 7125 EVT SrcVT = Op1.getValueType(); 7126 7127 // If second operand is smaller, extend it first. 7128 if (SrcVT.bitsLT(VT)) { 7129 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 7130 SrcVT = VT; 7131 } 7132 // And if it is bigger, shrink it first. 7133 if (SrcVT.bitsGT(VT)) { 7134 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 7135 SrcVT = VT; 7136 } 7137 7138 // At this point the operands and the result should have the same 7139 // type, and that won't be f80 since that is not custom lowered. 7140 7141 // First get the sign bit of second operand. 7142 std::vector<Constant*> CV; 7143 if (SrcVT == MVT::f64) { 7144 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 7145 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7146 } else { 7147 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 7148 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7149 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7150 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7151 } 7152 Constant *C = ConstantVector::get(CV); 7153 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7154 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 7155 MachinePointerInfo::getConstantPool(), 7156 false, false, 16); 7157 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 7158 7159 // Shift sign bit right or left if the two operands have different types. 7160 if (SrcVT.bitsGT(VT)) { 7161 // Op0 is MVT::f32, Op1 is MVT::f64. 7162 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 7163 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 7164 DAG.getConstant(32, MVT::i32)); 7165 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 7166 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 7167 DAG.getIntPtrConstant(0)); 7168 } 7169 7170 // Clear first operand sign bit. 7171 CV.clear(); 7172 if (VT == MVT::f64) { 7173 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 7174 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 7175 } else { 7176 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 7177 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7178 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7179 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 7180 } 7181 C = ConstantVector::get(CV); 7182 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 7183 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 7184 MachinePointerInfo::getConstantPool(), 7185 false, false, 16); 7186 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 7187 7188 // Or the value with the sign bit. 7189 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 7190} 7191 7192/// Emit nodes that will be selected as "test Op0,Op0", or something 7193/// equivalent. 7194SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 7195 SelectionDAG &DAG) const { 7196 DebugLoc dl = Op.getDebugLoc(); 7197 7198 // CF and OF aren't always set the way we want. Determine which 7199 // of these we need. 7200 bool NeedCF = false; 7201 bool NeedOF = false; 7202 switch (X86CC) { 7203 default: break; 7204 case X86::COND_A: case X86::COND_AE: 7205 case X86::COND_B: case X86::COND_BE: 7206 NeedCF = true; 7207 break; 7208 case X86::COND_G: case X86::COND_GE: 7209 case X86::COND_L: case X86::COND_LE: 7210 case X86::COND_O: case X86::COND_NO: 7211 NeedOF = true; 7212 break; 7213 } 7214 7215 // See if we can use the EFLAGS value from the operand instead of 7216 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 7217 // we prove that the arithmetic won't overflow, we can't use OF or CF. 7218 if (Op.getResNo() != 0 || NeedOF || NeedCF) 7219 // Emit a CMP with 0, which is the TEST pattern. 7220 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7221 DAG.getConstant(0, Op.getValueType())); 7222 7223 unsigned Opcode = 0; 7224 unsigned NumOperands = 0; 7225 switch (Op.getNode()->getOpcode()) { 7226 case ISD::ADD: 7227 // Due to an isel shortcoming, be conservative if this add is likely to be 7228 // selected as part of a load-modify-store instruction. When the root node 7229 // in a match is a store, isel doesn't know how to remap non-chain non-flag 7230 // uses of other nodes in the match, such as the ADD in this case. This 7231 // leads to the ADD being left around and reselected, with the result being 7232 // two adds in the output. Alas, even if none our users are stores, that 7233 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 7234 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 7235 // climbing the DAG back to the root, and it doesn't seem to be worth the 7236 // effort. 7237 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7238 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7239 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC) 7240 goto default_case; 7241 7242 if (ConstantSDNode *C = 7243 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 7244 // An add of one will be selected as an INC. 7245 if (C->getAPIntValue() == 1) { 7246 Opcode = X86ISD::INC; 7247 NumOperands = 1; 7248 break; 7249 } 7250 7251 // An add of negative one (subtract of one) will be selected as a DEC. 7252 if (C->getAPIntValue().isAllOnesValue()) { 7253 Opcode = X86ISD::DEC; 7254 NumOperands = 1; 7255 break; 7256 } 7257 } 7258 7259 // Otherwise use a regular EFLAGS-setting add. 7260 Opcode = X86ISD::ADD; 7261 NumOperands = 2; 7262 break; 7263 case ISD::AND: { 7264 // If the primary and result isn't used, don't bother using X86ISD::AND, 7265 // because a TEST instruction will be better. 7266 bool NonFlagUse = false; 7267 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7268 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 7269 SDNode *User = *UI; 7270 unsigned UOpNo = UI.getOperandNo(); 7271 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 7272 // Look pass truncate. 7273 UOpNo = User->use_begin().getOperandNo(); 7274 User = *User->use_begin(); 7275 } 7276 7277 if (User->getOpcode() != ISD::BRCOND && 7278 User->getOpcode() != ISD::SETCC && 7279 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 7280 NonFlagUse = true; 7281 break; 7282 } 7283 } 7284 7285 if (!NonFlagUse) 7286 break; 7287 } 7288 // FALL THROUGH 7289 case ISD::SUB: 7290 case ISD::OR: 7291 case ISD::XOR: 7292 // Due to the ISEL shortcoming noted above, be conservative if this op is 7293 // likely to be selected as part of a load-modify-store instruction. 7294 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 7295 UE = Op.getNode()->use_end(); UI != UE; ++UI) 7296 if (UI->getOpcode() == ISD::STORE) 7297 goto default_case; 7298 7299 // Otherwise use a regular EFLAGS-setting instruction. 7300 switch (Op.getNode()->getOpcode()) { 7301 default: llvm_unreachable("unexpected operator!"); 7302 case ISD::SUB: Opcode = X86ISD::SUB; break; 7303 case ISD::OR: Opcode = X86ISD::OR; break; 7304 case ISD::XOR: Opcode = X86ISD::XOR; break; 7305 case ISD::AND: Opcode = X86ISD::AND; break; 7306 } 7307 7308 NumOperands = 2; 7309 break; 7310 case X86ISD::ADD: 7311 case X86ISD::SUB: 7312 case X86ISD::INC: 7313 case X86ISD::DEC: 7314 case X86ISD::OR: 7315 case X86ISD::XOR: 7316 case X86ISD::AND: 7317 return SDValue(Op.getNode(), 1); 7318 default: 7319 default_case: 7320 break; 7321 } 7322 7323 if (Opcode == 0) 7324 // Emit a CMP with 0, which is the TEST pattern. 7325 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 7326 DAG.getConstant(0, Op.getValueType())); 7327 7328 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 7329 SmallVector<SDValue, 4> Ops; 7330 for (unsigned i = 0; i != NumOperands; ++i) 7331 Ops.push_back(Op.getOperand(i)); 7332 7333 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 7334 DAG.ReplaceAllUsesWith(Op, New); 7335 return SDValue(New.getNode(), 1); 7336} 7337 7338/// Emit nodes that will be selected as "cmp Op0,Op1", or something 7339/// equivalent. 7340SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 7341 SelectionDAG &DAG) const { 7342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 7343 if (C->getAPIntValue() == 0) 7344 return EmitTest(Op0, X86CC, DAG); 7345 7346 DebugLoc dl = Op0.getDebugLoc(); 7347 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 7348} 7349 7350/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 7351/// if it's possible. 7352SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 7353 DebugLoc dl, SelectionDAG &DAG) const { 7354 SDValue Op0 = And.getOperand(0); 7355 SDValue Op1 = And.getOperand(1); 7356 if (Op0.getOpcode() == ISD::TRUNCATE) 7357 Op0 = Op0.getOperand(0); 7358 if (Op1.getOpcode() == ISD::TRUNCATE) 7359 Op1 = Op1.getOperand(0); 7360 7361 SDValue LHS, RHS; 7362 if (Op1.getOpcode() == ISD::SHL) 7363 std::swap(Op0, Op1); 7364 if (Op0.getOpcode() == ISD::SHL) { 7365 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 7366 if (And00C->getZExtValue() == 1) { 7367 // If we looked past a truncate, check that it's only truncating away 7368 // known zeros. 7369 unsigned BitWidth = Op0.getValueSizeInBits(); 7370 unsigned AndBitWidth = And.getValueSizeInBits(); 7371 if (BitWidth > AndBitWidth) { 7372 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 7373 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 7374 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 7375 return SDValue(); 7376 } 7377 LHS = Op1; 7378 RHS = Op0.getOperand(1); 7379 } 7380 } else if (Op1.getOpcode() == ISD::Constant) { 7381 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 7382 SDValue AndLHS = Op0; 7383 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) { 7384 LHS = AndLHS.getOperand(0); 7385 RHS = AndLHS.getOperand(1); 7386 } 7387 } 7388 7389 if (LHS.getNode()) { 7390 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 7391 // instruction. Since the shift amount is in-range-or-undefined, we know 7392 // that doing a bittest on the i32 value is ok. We extend to i32 because 7393 // the encoding for the i16 version is larger than the i32 version. 7394 // Also promote i16 to i32 for performance / code size reason. 7395 if (LHS.getValueType() == MVT::i8 || 7396 LHS.getValueType() == MVT::i16) 7397 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 7398 7399 // If the operand types disagree, extend the shift amount to match. Since 7400 // BT ignores high bits (like shifts) we can use anyextend. 7401 if (LHS.getValueType() != RHS.getValueType()) 7402 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 7403 7404 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 7405 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 7406 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7407 DAG.getConstant(Cond, MVT::i8), BT); 7408 } 7409 7410 return SDValue(); 7411} 7412 7413SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 7414 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 7415 SDValue Op0 = Op.getOperand(0); 7416 SDValue Op1 = Op.getOperand(1); 7417 DebugLoc dl = Op.getDebugLoc(); 7418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7419 7420 // Optimize to BT if possible. 7421 // Lower (X & (1 << N)) == 0 to BT(X, N). 7422 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 7423 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 7424 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 7425 Op1.getOpcode() == ISD::Constant && 7426 cast<ConstantSDNode>(Op1)->isNullValue() && 7427 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7428 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 7429 if (NewSetCC.getNode()) 7430 return NewSetCC; 7431 } 7432 7433 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 7434 // these. 7435 if (Op1.getOpcode() == ISD::Constant && 7436 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 7437 cast<ConstantSDNode>(Op1)->isNullValue()) && 7438 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 7439 7440 // If the input is a setcc, then reuse the input setcc or use a new one with 7441 // the inverted condition. 7442 if (Op0.getOpcode() == X86ISD::SETCC) { 7443 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 7444 bool Invert = (CC == ISD::SETNE) ^ 7445 cast<ConstantSDNode>(Op1)->isNullValue(); 7446 if (!Invert) return Op0; 7447 7448 CCode = X86::GetOppositeBranchCondition(CCode); 7449 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7450 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 7451 } 7452 } 7453 7454 bool isFP = Op1.getValueType().isFloatingPoint(); 7455 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 7456 if (X86CC == X86::COND_INVALID) 7457 return SDValue(); 7458 7459 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 7460 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 7461 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 7462} 7463 7464SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 7465 SDValue Cond; 7466 SDValue Op0 = Op.getOperand(0); 7467 SDValue Op1 = Op.getOperand(1); 7468 SDValue CC = Op.getOperand(2); 7469 EVT VT = Op.getValueType(); 7470 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 7471 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 7472 DebugLoc dl = Op.getDebugLoc(); 7473 7474 if (isFP) { 7475 unsigned SSECC = 8; 7476 EVT VT0 = Op0.getValueType(); 7477 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64); 7478 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 7479 bool Swap = false; 7480 7481 switch (SetCCOpcode) { 7482 default: break; 7483 case ISD::SETOEQ: 7484 case ISD::SETEQ: SSECC = 0; break; 7485 case ISD::SETOGT: 7486 case ISD::SETGT: Swap = true; // Fallthrough 7487 case ISD::SETLT: 7488 case ISD::SETOLT: SSECC = 1; break; 7489 case ISD::SETOGE: 7490 case ISD::SETGE: Swap = true; // Fallthrough 7491 case ISD::SETLE: 7492 case ISD::SETOLE: SSECC = 2; break; 7493 case ISD::SETUO: SSECC = 3; break; 7494 case ISD::SETUNE: 7495 case ISD::SETNE: SSECC = 4; break; 7496 case ISD::SETULE: Swap = true; 7497 case ISD::SETUGE: SSECC = 5; break; 7498 case ISD::SETULT: Swap = true; 7499 case ISD::SETUGT: SSECC = 6; break; 7500 case ISD::SETO: SSECC = 7; break; 7501 } 7502 if (Swap) 7503 std::swap(Op0, Op1); 7504 7505 // In the two special cases we can't handle, emit two comparisons. 7506 if (SSECC == 8) { 7507 if (SetCCOpcode == ISD::SETUEQ) { 7508 SDValue UNORD, EQ; 7509 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 7510 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 7511 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 7512 } 7513 else if (SetCCOpcode == ISD::SETONE) { 7514 SDValue ORD, NEQ; 7515 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 7516 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 7517 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 7518 } 7519 llvm_unreachable("Illegal FP comparison"); 7520 } 7521 // Handle all other FP comparisons here. 7522 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 7523 } 7524 7525 // We are handling one of the integer comparisons here. Since SSE only has 7526 // GT and EQ comparisons for integer, swapping operands and multiple 7527 // operations may be required for some comparisons. 7528 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 7529 bool Swap = false, Invert = false, FlipSigns = false; 7530 7531 switch (VT.getSimpleVT().SimpleTy) { 7532 default: break; 7533 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 7534 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 7535 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 7536 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 7537 } 7538 7539 switch (SetCCOpcode) { 7540 default: break; 7541 case ISD::SETNE: Invert = true; 7542 case ISD::SETEQ: Opc = EQOpc; break; 7543 case ISD::SETLT: Swap = true; 7544 case ISD::SETGT: Opc = GTOpc; break; 7545 case ISD::SETGE: Swap = true; 7546 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 7547 case ISD::SETULT: Swap = true; 7548 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 7549 case ISD::SETUGE: Swap = true; 7550 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 7551 } 7552 if (Swap) 7553 std::swap(Op0, Op1); 7554 7555 // Since SSE has no unsigned integer comparisons, we need to flip the sign 7556 // bits of the inputs before performing those operations. 7557 if (FlipSigns) { 7558 EVT EltVT = VT.getVectorElementType(); 7559 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 7560 EltVT); 7561 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 7562 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 7563 SignBits.size()); 7564 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 7565 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 7566 } 7567 7568 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 7569 7570 // If the logical-not of the result is required, perform that now. 7571 if (Invert) 7572 Result = DAG.getNOT(dl, Result, VT); 7573 7574 return Result; 7575} 7576 7577// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 7578static bool isX86LogicalCmp(SDValue Op) { 7579 unsigned Opc = Op.getNode()->getOpcode(); 7580 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 7581 return true; 7582 if (Op.getResNo() == 1 && 7583 (Opc == X86ISD::ADD || 7584 Opc == X86ISD::SUB || 7585 Opc == X86ISD::ADC || 7586 Opc == X86ISD::SBB || 7587 Opc == X86ISD::SMUL || 7588 Opc == X86ISD::UMUL || 7589 Opc == X86ISD::INC || 7590 Opc == X86ISD::DEC || 7591 Opc == X86ISD::OR || 7592 Opc == X86ISD::XOR || 7593 Opc == X86ISD::AND)) 7594 return true; 7595 7596 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 7597 return true; 7598 7599 return false; 7600} 7601 7602static bool isZero(SDValue V) { 7603 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7604 return C && C->isNullValue(); 7605} 7606 7607static bool isAllOnes(SDValue V) { 7608 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 7609 return C && C->isAllOnesValue(); 7610} 7611 7612SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7613 bool addTest = true; 7614 SDValue Cond = Op.getOperand(0); 7615 SDValue Op1 = Op.getOperand(1); 7616 SDValue Op2 = Op.getOperand(2); 7617 DebugLoc DL = Op.getDebugLoc(); 7618 SDValue CC; 7619 7620 if (Cond.getOpcode() == ISD::SETCC) { 7621 SDValue NewCond = LowerSETCC(Cond, DAG); 7622 if (NewCond.getNode()) 7623 Cond = NewCond; 7624 } 7625 7626 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 7627 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 7628 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 7629 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 7630 if (Cond.getOpcode() == X86ISD::SETCC && 7631 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 7632 isZero(Cond.getOperand(1).getOperand(1))) { 7633 SDValue Cmp = Cond.getOperand(1); 7634 7635 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 7636 7637 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 7638 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 7639 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 7640 7641 SDValue CmpOp0 = Cmp.getOperand(0); 7642 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 7643 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 7644 7645 SDValue Res = // Res = 0 or -1. 7646 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7647 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 7648 7649 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 7650 Res = DAG.getNOT(DL, Res, Res.getValueType()); 7651 7652 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 7653 if (N2C == 0 || !N2C->isNullValue()) 7654 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 7655 return Res; 7656 } 7657 } 7658 7659 // Look past (and (setcc_carry (cmp ...)), 1). 7660 if (Cond.getOpcode() == ISD::AND && 7661 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7662 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7663 if (C && C->getAPIntValue() == 1) 7664 Cond = Cond.getOperand(0); 7665 } 7666 7667 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7668 // setting operand in place of the X86ISD::SETCC. 7669 if (Cond.getOpcode() == X86ISD::SETCC || 7670 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7671 CC = Cond.getOperand(0); 7672 7673 SDValue Cmp = Cond.getOperand(1); 7674 unsigned Opc = Cmp.getOpcode(); 7675 EVT VT = Op.getValueType(); 7676 7677 bool IllegalFPCMov = false; 7678 if (VT.isFloatingPoint() && !VT.isVector() && 7679 !isScalarFPTypeInSSEReg(VT)) // FPStack? 7680 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 7681 7682 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 7683 Opc == X86ISD::BT) { // FIXME 7684 Cond = Cmp; 7685 addTest = false; 7686 } 7687 } 7688 7689 if (addTest) { 7690 // Look pass the truncate. 7691 if (Cond.getOpcode() == ISD::TRUNCATE) 7692 Cond = Cond.getOperand(0); 7693 7694 // We know the result of AND is compared against zero. Try to match 7695 // it to BT. 7696 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7697 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 7698 if (NewSetCC.getNode()) { 7699 CC = NewSetCC.getOperand(0); 7700 Cond = NewSetCC.getOperand(1); 7701 addTest = false; 7702 } 7703 } 7704 } 7705 7706 if (addTest) { 7707 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7708 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7709 } 7710 7711 // a < b ? -1 : 0 -> RES = ~setcc_carry 7712 // a < b ? 0 : -1 -> RES = setcc_carry 7713 // a >= b ? -1 : 0 -> RES = setcc_carry 7714 // a >= b ? 0 : -1 -> RES = ~setcc_carry 7715 if (Cond.getOpcode() == X86ISD::CMP) { 7716 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 7717 7718 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 7719 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 7720 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 7721 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 7722 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 7723 return DAG.getNOT(DL, Res, Res.getValueType()); 7724 return Res; 7725 } 7726 } 7727 7728 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 7729 // condition is true. 7730 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 7731 SDValue Ops[] = { Op2, Op1, CC, Cond }; 7732 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 7733} 7734 7735// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 7736// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 7737// from the AND / OR. 7738static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 7739 Opc = Op.getOpcode(); 7740 if (Opc != ISD::OR && Opc != ISD::AND) 7741 return false; 7742 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7743 Op.getOperand(0).hasOneUse() && 7744 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 7745 Op.getOperand(1).hasOneUse()); 7746} 7747 7748// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 7749// 1 and that the SETCC node has a single use. 7750static bool isXor1OfSetCC(SDValue Op) { 7751 if (Op.getOpcode() != ISD::XOR) 7752 return false; 7753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7754 if (N1C && N1C->getAPIntValue() == 1) { 7755 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 7756 Op.getOperand(0).hasOneUse(); 7757 } 7758 return false; 7759} 7760 7761SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 7762 bool addTest = true; 7763 SDValue Chain = Op.getOperand(0); 7764 SDValue Cond = Op.getOperand(1); 7765 SDValue Dest = Op.getOperand(2); 7766 DebugLoc dl = Op.getDebugLoc(); 7767 SDValue CC; 7768 7769 if (Cond.getOpcode() == ISD::SETCC) { 7770 SDValue NewCond = LowerSETCC(Cond, DAG); 7771 if (NewCond.getNode()) 7772 Cond = NewCond; 7773 } 7774#if 0 7775 // FIXME: LowerXALUO doesn't handle these!! 7776 else if (Cond.getOpcode() == X86ISD::ADD || 7777 Cond.getOpcode() == X86ISD::SUB || 7778 Cond.getOpcode() == X86ISD::SMUL || 7779 Cond.getOpcode() == X86ISD::UMUL) 7780 Cond = LowerXALUO(Cond, DAG); 7781#endif 7782 7783 // Look pass (and (setcc_carry (cmp ...)), 1). 7784 if (Cond.getOpcode() == ISD::AND && 7785 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 7786 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 7787 if (C && C->getAPIntValue() == 1) 7788 Cond = Cond.getOperand(0); 7789 } 7790 7791 // If condition flag is set by a X86ISD::CMP, then use it as the condition 7792 // setting operand in place of the X86ISD::SETCC. 7793 if (Cond.getOpcode() == X86ISD::SETCC || 7794 Cond.getOpcode() == X86ISD::SETCC_CARRY) { 7795 CC = Cond.getOperand(0); 7796 7797 SDValue Cmp = Cond.getOperand(1); 7798 unsigned Opc = Cmp.getOpcode(); 7799 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 7800 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 7801 Cond = Cmp; 7802 addTest = false; 7803 } else { 7804 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 7805 default: break; 7806 case X86::COND_O: 7807 case X86::COND_B: 7808 // These can only come from an arithmetic instruction with overflow, 7809 // e.g. SADDO, UADDO. 7810 Cond = Cond.getNode()->getOperand(1); 7811 addTest = false; 7812 break; 7813 } 7814 } 7815 } else { 7816 unsigned CondOpc; 7817 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 7818 SDValue Cmp = Cond.getOperand(0).getOperand(1); 7819 if (CondOpc == ISD::OR) { 7820 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 7821 // two branches instead of an explicit OR instruction with a 7822 // separate test. 7823 if (Cmp == Cond.getOperand(1).getOperand(1) && 7824 isX86LogicalCmp(Cmp)) { 7825 CC = Cond.getOperand(0).getOperand(0); 7826 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7827 Chain, Dest, CC, Cmp); 7828 CC = Cond.getOperand(1).getOperand(0); 7829 Cond = Cmp; 7830 addTest = false; 7831 } 7832 } else { // ISD::AND 7833 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 7834 // two branches instead of an explicit AND instruction with a 7835 // separate test. However, we only do this if this block doesn't 7836 // have a fall-through edge, because this requires an explicit 7837 // jmp when the condition is false. 7838 if (Cmp == Cond.getOperand(1).getOperand(1) && 7839 isX86LogicalCmp(Cmp) && 7840 Op.getNode()->hasOneUse()) { 7841 X86::CondCode CCode = 7842 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7843 CCode = X86::GetOppositeBranchCondition(CCode); 7844 CC = DAG.getConstant(CCode, MVT::i8); 7845 SDNode *User = *Op.getNode()->use_begin(); 7846 // Look for an unconditional branch following this conditional branch. 7847 // We need this because we need to reverse the successors in order 7848 // to implement FCMP_OEQ. 7849 if (User->getOpcode() == ISD::BR) { 7850 SDValue FalseBB = User->getOperand(1); 7851 SDNode *NewBR = 7852 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 7853 assert(NewBR == User); 7854 (void)NewBR; 7855 Dest = FalseBB; 7856 7857 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7858 Chain, Dest, CC, Cmp); 7859 X86::CondCode CCode = 7860 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 7861 CCode = X86::GetOppositeBranchCondition(CCode); 7862 CC = DAG.getConstant(CCode, MVT::i8); 7863 Cond = Cmp; 7864 addTest = false; 7865 } 7866 } 7867 } 7868 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 7869 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 7870 // It should be transformed during dag combiner except when the condition 7871 // is set by a arithmetics with overflow node. 7872 X86::CondCode CCode = 7873 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 7874 CCode = X86::GetOppositeBranchCondition(CCode); 7875 CC = DAG.getConstant(CCode, MVT::i8); 7876 Cond = Cond.getOperand(0).getOperand(1); 7877 addTest = false; 7878 } 7879 } 7880 7881 if (addTest) { 7882 // Look pass the truncate. 7883 if (Cond.getOpcode() == ISD::TRUNCATE) 7884 Cond = Cond.getOperand(0); 7885 7886 // We know the result of AND is compared against zero. Try to match 7887 // it to BT. 7888 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 7889 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 7890 if (NewSetCC.getNode()) { 7891 CC = NewSetCC.getOperand(0); 7892 Cond = NewSetCC.getOperand(1); 7893 addTest = false; 7894 } 7895 } 7896 } 7897 7898 if (addTest) { 7899 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7900 Cond = EmitTest(Cond, X86::COND_NE, DAG); 7901 } 7902 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 7903 Chain, Dest, CC, Cond); 7904} 7905 7906 7907// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 7908// Calls to _alloca is needed to probe the stack when allocating more than 4k 7909// bytes in one go. Touching the stack at 4K increments is necessary to ensure 7910// that the guard pages used by the OS virtual memory manager are allocated in 7911// correct sequence. 7912SDValue 7913X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7914 SelectionDAG &DAG) const { 7915 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) && 7916 "This should be used only on Windows targets"); 7917 DebugLoc dl = Op.getDebugLoc(); 7918 7919 // Get the inputs. 7920 SDValue Chain = Op.getOperand(0); 7921 SDValue Size = Op.getOperand(1); 7922 // FIXME: Ensure alignment here 7923 7924 SDValue Flag; 7925 7926 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32; 7927 7928 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag); 7929 Flag = Chain.getValue(1); 7930 7931 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7932 7933 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 7934 Flag = Chain.getValue(1); 7935 7936 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 7937 7938 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 7939 return DAG.getMergeValues(Ops1, 2, dl); 7940} 7941 7942SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 7943 MachineFunction &MF = DAG.getMachineFunction(); 7944 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 7945 7946 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 7947 DebugLoc DL = Op.getDebugLoc(); 7948 7949 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 7950 // vastart just stores the address of the VarArgsFrameIndex slot into the 7951 // memory location argument. 7952 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 7953 getPointerTy()); 7954 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 7955 MachinePointerInfo(SV), false, false, 0); 7956 } 7957 7958 // __va_list_tag: 7959 // gp_offset (0 - 6 * 8) 7960 // fp_offset (48 - 48 + 8 * 16) 7961 // overflow_arg_area (point to parameters coming in memory). 7962 // reg_save_area 7963 SmallVector<SDValue, 8> MemOps; 7964 SDValue FIN = Op.getOperand(1); 7965 // Store gp_offset 7966 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 7967 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 7968 MVT::i32), 7969 FIN, MachinePointerInfo(SV), false, false, 0); 7970 MemOps.push_back(Store); 7971 7972 // Store fp_offset 7973 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7974 FIN, DAG.getIntPtrConstant(4)); 7975 Store = DAG.getStore(Op.getOperand(0), DL, 7976 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 7977 MVT::i32), 7978 FIN, MachinePointerInfo(SV, 4), false, false, 0); 7979 MemOps.push_back(Store); 7980 7981 // Store ptr to overflow_arg_area 7982 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7983 FIN, DAG.getIntPtrConstant(4)); 7984 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 7985 getPointerTy()); 7986 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 7987 MachinePointerInfo(SV, 8), 7988 false, false, 0); 7989 MemOps.push_back(Store); 7990 7991 // Store ptr to reg_save_area. 7992 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7993 FIN, DAG.getIntPtrConstant(8)); 7994 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 7995 getPointerTy()); 7996 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 7997 MachinePointerInfo(SV, 16), false, false, 0); 7998 MemOps.push_back(Store); 7999 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 8000 &MemOps[0], MemOps.size()); 8001} 8002 8003SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 8004 assert(Subtarget->is64Bit() && 8005 "LowerVAARG only handles 64-bit va_arg!"); 8006 assert((Subtarget->isTargetLinux() || 8007 Subtarget->isTargetDarwin()) && 8008 "Unhandled target in LowerVAARG"); 8009 assert(Op.getNode()->getNumOperands() == 4); 8010 SDValue Chain = Op.getOperand(0); 8011 SDValue SrcPtr = Op.getOperand(1); 8012 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 8013 unsigned Align = Op.getConstantOperandVal(3); 8014 DebugLoc dl = Op.getDebugLoc(); 8015 8016 EVT ArgVT = Op.getNode()->getValueType(0); 8017 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 8018 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 8019 uint8_t ArgMode; 8020 8021 // Decide which area this value should be read from. 8022 // TODO: Implement the AMD64 ABI in its entirety. This simple 8023 // selection mechanism works only for the basic types. 8024 if (ArgVT == MVT::f80) { 8025 llvm_unreachable("va_arg for f80 not yet implemented"); 8026 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 8027 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 8028 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 8029 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 8030 } else { 8031 llvm_unreachable("Unhandled argument type in LowerVAARG"); 8032 } 8033 8034 if (ArgMode == 2) { 8035 // Sanity Check: Make sure using fp_offset makes sense. 8036 assert(!UseSoftFloat && 8037 !(DAG.getMachineFunction() 8038 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 8039 Subtarget->hasXMM()); 8040 } 8041 8042 // Insert VAARG_64 node into the DAG 8043 // VAARG_64 returns two values: Variable Argument Address, Chain 8044 SmallVector<SDValue, 11> InstOps; 8045 InstOps.push_back(Chain); 8046 InstOps.push_back(SrcPtr); 8047 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 8048 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 8049 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 8050 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 8051 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 8052 VTs, &InstOps[0], InstOps.size(), 8053 MVT::i64, 8054 MachinePointerInfo(SV), 8055 /*Align=*/0, 8056 /*Volatile=*/false, 8057 /*ReadMem=*/true, 8058 /*WriteMem=*/true); 8059 Chain = VAARG.getValue(1); 8060 8061 // Load the next argument and return it 8062 return DAG.getLoad(ArgVT, dl, 8063 Chain, 8064 VAARG, 8065 MachinePointerInfo(), 8066 false, false, 0); 8067} 8068 8069SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 8070 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 8071 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 8072 SDValue Chain = Op.getOperand(0); 8073 SDValue DstPtr = Op.getOperand(1); 8074 SDValue SrcPtr = Op.getOperand(2); 8075 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 8076 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8077 DebugLoc DL = Op.getDebugLoc(); 8078 8079 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 8080 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 8081 false, 8082 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 8083} 8084 8085SDValue 8086X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 8087 DebugLoc dl = Op.getDebugLoc(); 8088 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8089 switch (IntNo) { 8090 default: return SDValue(); // Don't custom lower most intrinsics. 8091 // Comparison intrinsics. 8092 case Intrinsic::x86_sse_comieq_ss: 8093 case Intrinsic::x86_sse_comilt_ss: 8094 case Intrinsic::x86_sse_comile_ss: 8095 case Intrinsic::x86_sse_comigt_ss: 8096 case Intrinsic::x86_sse_comige_ss: 8097 case Intrinsic::x86_sse_comineq_ss: 8098 case Intrinsic::x86_sse_ucomieq_ss: 8099 case Intrinsic::x86_sse_ucomilt_ss: 8100 case Intrinsic::x86_sse_ucomile_ss: 8101 case Intrinsic::x86_sse_ucomigt_ss: 8102 case Intrinsic::x86_sse_ucomige_ss: 8103 case Intrinsic::x86_sse_ucomineq_ss: 8104 case Intrinsic::x86_sse2_comieq_sd: 8105 case Intrinsic::x86_sse2_comilt_sd: 8106 case Intrinsic::x86_sse2_comile_sd: 8107 case Intrinsic::x86_sse2_comigt_sd: 8108 case Intrinsic::x86_sse2_comige_sd: 8109 case Intrinsic::x86_sse2_comineq_sd: 8110 case Intrinsic::x86_sse2_ucomieq_sd: 8111 case Intrinsic::x86_sse2_ucomilt_sd: 8112 case Intrinsic::x86_sse2_ucomile_sd: 8113 case Intrinsic::x86_sse2_ucomigt_sd: 8114 case Intrinsic::x86_sse2_ucomige_sd: 8115 case Intrinsic::x86_sse2_ucomineq_sd: { 8116 unsigned Opc = 0; 8117 ISD::CondCode CC = ISD::SETCC_INVALID; 8118 switch (IntNo) { 8119 default: break; 8120 case Intrinsic::x86_sse_comieq_ss: 8121 case Intrinsic::x86_sse2_comieq_sd: 8122 Opc = X86ISD::COMI; 8123 CC = ISD::SETEQ; 8124 break; 8125 case Intrinsic::x86_sse_comilt_ss: 8126 case Intrinsic::x86_sse2_comilt_sd: 8127 Opc = X86ISD::COMI; 8128 CC = ISD::SETLT; 8129 break; 8130 case Intrinsic::x86_sse_comile_ss: 8131 case Intrinsic::x86_sse2_comile_sd: 8132 Opc = X86ISD::COMI; 8133 CC = ISD::SETLE; 8134 break; 8135 case Intrinsic::x86_sse_comigt_ss: 8136 case Intrinsic::x86_sse2_comigt_sd: 8137 Opc = X86ISD::COMI; 8138 CC = ISD::SETGT; 8139 break; 8140 case Intrinsic::x86_sse_comige_ss: 8141 case Intrinsic::x86_sse2_comige_sd: 8142 Opc = X86ISD::COMI; 8143 CC = ISD::SETGE; 8144 break; 8145 case Intrinsic::x86_sse_comineq_ss: 8146 case Intrinsic::x86_sse2_comineq_sd: 8147 Opc = X86ISD::COMI; 8148 CC = ISD::SETNE; 8149 break; 8150 case Intrinsic::x86_sse_ucomieq_ss: 8151 case Intrinsic::x86_sse2_ucomieq_sd: 8152 Opc = X86ISD::UCOMI; 8153 CC = ISD::SETEQ; 8154 break; 8155 case Intrinsic::x86_sse_ucomilt_ss: 8156 case Intrinsic::x86_sse2_ucomilt_sd: 8157 Opc = X86ISD::UCOMI; 8158 CC = ISD::SETLT; 8159 break; 8160 case Intrinsic::x86_sse_ucomile_ss: 8161 case Intrinsic::x86_sse2_ucomile_sd: 8162 Opc = X86ISD::UCOMI; 8163 CC = ISD::SETLE; 8164 break; 8165 case Intrinsic::x86_sse_ucomigt_ss: 8166 case Intrinsic::x86_sse2_ucomigt_sd: 8167 Opc = X86ISD::UCOMI; 8168 CC = ISD::SETGT; 8169 break; 8170 case Intrinsic::x86_sse_ucomige_ss: 8171 case Intrinsic::x86_sse2_ucomige_sd: 8172 Opc = X86ISD::UCOMI; 8173 CC = ISD::SETGE; 8174 break; 8175 case Intrinsic::x86_sse_ucomineq_ss: 8176 case Intrinsic::x86_sse2_ucomineq_sd: 8177 Opc = X86ISD::UCOMI; 8178 CC = ISD::SETNE; 8179 break; 8180 } 8181 8182 SDValue LHS = Op.getOperand(1); 8183 SDValue RHS = Op.getOperand(2); 8184 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 8185 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 8186 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 8187 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8188 DAG.getConstant(X86CC, MVT::i8), Cond); 8189 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8190 } 8191 // ptest and testp intrinsics. The intrinsic these come from are designed to 8192 // return an integer value, not just an instruction so lower it to the ptest 8193 // or testp pattern and a setcc for the result. 8194 case Intrinsic::x86_sse41_ptestz: 8195 case Intrinsic::x86_sse41_ptestc: 8196 case Intrinsic::x86_sse41_ptestnzc: 8197 case Intrinsic::x86_avx_ptestz_256: 8198 case Intrinsic::x86_avx_ptestc_256: 8199 case Intrinsic::x86_avx_ptestnzc_256: 8200 case Intrinsic::x86_avx_vtestz_ps: 8201 case Intrinsic::x86_avx_vtestc_ps: 8202 case Intrinsic::x86_avx_vtestnzc_ps: 8203 case Intrinsic::x86_avx_vtestz_pd: 8204 case Intrinsic::x86_avx_vtestc_pd: 8205 case Intrinsic::x86_avx_vtestnzc_pd: 8206 case Intrinsic::x86_avx_vtestz_ps_256: 8207 case Intrinsic::x86_avx_vtestc_ps_256: 8208 case Intrinsic::x86_avx_vtestnzc_ps_256: 8209 case Intrinsic::x86_avx_vtestz_pd_256: 8210 case Intrinsic::x86_avx_vtestc_pd_256: 8211 case Intrinsic::x86_avx_vtestnzc_pd_256: { 8212 bool IsTestPacked = false; 8213 unsigned X86CC = 0; 8214 switch (IntNo) { 8215 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 8216 case Intrinsic::x86_avx_vtestz_ps: 8217 case Intrinsic::x86_avx_vtestz_pd: 8218 case Intrinsic::x86_avx_vtestz_ps_256: 8219 case Intrinsic::x86_avx_vtestz_pd_256: 8220 IsTestPacked = true; // Fallthrough 8221 case Intrinsic::x86_sse41_ptestz: 8222 case Intrinsic::x86_avx_ptestz_256: 8223 // ZF = 1 8224 X86CC = X86::COND_E; 8225 break; 8226 case Intrinsic::x86_avx_vtestc_ps: 8227 case Intrinsic::x86_avx_vtestc_pd: 8228 case Intrinsic::x86_avx_vtestc_ps_256: 8229 case Intrinsic::x86_avx_vtestc_pd_256: 8230 IsTestPacked = true; // Fallthrough 8231 case Intrinsic::x86_sse41_ptestc: 8232 case Intrinsic::x86_avx_ptestc_256: 8233 // CF = 1 8234 X86CC = X86::COND_B; 8235 break; 8236 case Intrinsic::x86_avx_vtestnzc_ps: 8237 case Intrinsic::x86_avx_vtestnzc_pd: 8238 case Intrinsic::x86_avx_vtestnzc_ps_256: 8239 case Intrinsic::x86_avx_vtestnzc_pd_256: 8240 IsTestPacked = true; // Fallthrough 8241 case Intrinsic::x86_sse41_ptestnzc: 8242 case Intrinsic::x86_avx_ptestnzc_256: 8243 // ZF and CF = 0 8244 X86CC = X86::COND_A; 8245 break; 8246 } 8247 8248 SDValue LHS = Op.getOperand(1); 8249 SDValue RHS = Op.getOperand(2); 8250 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 8251 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 8252 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 8253 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 8254 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 8255 } 8256 8257 // Fix vector shift instructions where the last operand is a non-immediate 8258 // i32 value. 8259 case Intrinsic::x86_sse2_pslli_w: 8260 case Intrinsic::x86_sse2_pslli_d: 8261 case Intrinsic::x86_sse2_pslli_q: 8262 case Intrinsic::x86_sse2_psrli_w: 8263 case Intrinsic::x86_sse2_psrli_d: 8264 case Intrinsic::x86_sse2_psrli_q: 8265 case Intrinsic::x86_sse2_psrai_w: 8266 case Intrinsic::x86_sse2_psrai_d: 8267 case Intrinsic::x86_mmx_pslli_w: 8268 case Intrinsic::x86_mmx_pslli_d: 8269 case Intrinsic::x86_mmx_pslli_q: 8270 case Intrinsic::x86_mmx_psrli_w: 8271 case Intrinsic::x86_mmx_psrli_d: 8272 case Intrinsic::x86_mmx_psrli_q: 8273 case Intrinsic::x86_mmx_psrai_w: 8274 case Intrinsic::x86_mmx_psrai_d: { 8275 SDValue ShAmt = Op.getOperand(2); 8276 if (isa<ConstantSDNode>(ShAmt)) 8277 return SDValue(); 8278 8279 unsigned NewIntNo = 0; 8280 EVT ShAmtVT = MVT::v4i32; 8281 switch (IntNo) { 8282 case Intrinsic::x86_sse2_pslli_w: 8283 NewIntNo = Intrinsic::x86_sse2_psll_w; 8284 break; 8285 case Intrinsic::x86_sse2_pslli_d: 8286 NewIntNo = Intrinsic::x86_sse2_psll_d; 8287 break; 8288 case Intrinsic::x86_sse2_pslli_q: 8289 NewIntNo = Intrinsic::x86_sse2_psll_q; 8290 break; 8291 case Intrinsic::x86_sse2_psrli_w: 8292 NewIntNo = Intrinsic::x86_sse2_psrl_w; 8293 break; 8294 case Intrinsic::x86_sse2_psrli_d: 8295 NewIntNo = Intrinsic::x86_sse2_psrl_d; 8296 break; 8297 case Intrinsic::x86_sse2_psrli_q: 8298 NewIntNo = Intrinsic::x86_sse2_psrl_q; 8299 break; 8300 case Intrinsic::x86_sse2_psrai_w: 8301 NewIntNo = Intrinsic::x86_sse2_psra_w; 8302 break; 8303 case Intrinsic::x86_sse2_psrai_d: 8304 NewIntNo = Intrinsic::x86_sse2_psra_d; 8305 break; 8306 default: { 8307 ShAmtVT = MVT::v2i32; 8308 switch (IntNo) { 8309 case Intrinsic::x86_mmx_pslli_w: 8310 NewIntNo = Intrinsic::x86_mmx_psll_w; 8311 break; 8312 case Intrinsic::x86_mmx_pslli_d: 8313 NewIntNo = Intrinsic::x86_mmx_psll_d; 8314 break; 8315 case Intrinsic::x86_mmx_pslli_q: 8316 NewIntNo = Intrinsic::x86_mmx_psll_q; 8317 break; 8318 case Intrinsic::x86_mmx_psrli_w: 8319 NewIntNo = Intrinsic::x86_mmx_psrl_w; 8320 break; 8321 case Intrinsic::x86_mmx_psrli_d: 8322 NewIntNo = Intrinsic::x86_mmx_psrl_d; 8323 break; 8324 case Intrinsic::x86_mmx_psrli_q: 8325 NewIntNo = Intrinsic::x86_mmx_psrl_q; 8326 break; 8327 case Intrinsic::x86_mmx_psrai_w: 8328 NewIntNo = Intrinsic::x86_mmx_psra_w; 8329 break; 8330 case Intrinsic::x86_mmx_psrai_d: 8331 NewIntNo = Intrinsic::x86_mmx_psra_d; 8332 break; 8333 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 8334 } 8335 break; 8336 } 8337 } 8338 8339 // The vector shift intrinsics with scalars uses 32b shift amounts but 8340 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 8341 // to be zero. 8342 SDValue ShOps[4]; 8343 ShOps[0] = ShAmt; 8344 ShOps[1] = DAG.getConstant(0, MVT::i32); 8345 if (ShAmtVT == MVT::v4i32) { 8346 ShOps[2] = DAG.getUNDEF(MVT::i32); 8347 ShOps[3] = DAG.getUNDEF(MVT::i32); 8348 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 8349 } else { 8350 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 8351// FIXME this must be lowered to get rid of the invalid type. 8352 } 8353 8354 EVT VT = Op.getValueType(); 8355 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 8356 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8357 DAG.getConstant(NewIntNo, MVT::i32), 8358 Op.getOperand(1), ShAmt); 8359 } 8360 } 8361} 8362 8363SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 8364 SelectionDAG &DAG) const { 8365 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8366 MFI->setReturnAddressIsTaken(true); 8367 8368 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8369 DebugLoc dl = Op.getDebugLoc(); 8370 8371 if (Depth > 0) { 8372 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 8373 SDValue Offset = 8374 DAG.getConstant(TD->getPointerSize(), 8375 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 8376 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8377 DAG.getNode(ISD::ADD, dl, getPointerTy(), 8378 FrameAddr, Offset), 8379 MachinePointerInfo(), false, false, 0); 8380 } 8381 8382 // Just load the return address. 8383 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 8384 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 8385 RetAddrFI, MachinePointerInfo(), false, false, 0); 8386} 8387 8388SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 8389 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 8390 MFI->setFrameAddressIsTaken(true); 8391 8392 EVT VT = Op.getValueType(); 8393 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 8394 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8395 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 8396 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 8397 while (Depth--) 8398 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 8399 MachinePointerInfo(), 8400 false, false, 0); 8401 return FrameAddr; 8402} 8403 8404SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 8405 SelectionDAG &DAG) const { 8406 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 8407} 8408 8409SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 8410 MachineFunction &MF = DAG.getMachineFunction(); 8411 SDValue Chain = Op.getOperand(0); 8412 SDValue Offset = Op.getOperand(1); 8413 SDValue Handler = Op.getOperand(2); 8414 DebugLoc dl = Op.getDebugLoc(); 8415 8416 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 8417 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 8418 getPointerTy()); 8419 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 8420 8421 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 8422 DAG.getIntPtrConstant(TD->getPointerSize())); 8423 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 8424 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 8425 false, false, 0); 8426 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 8427 MF.getRegInfo().addLiveOut(StoreAddrReg); 8428 8429 return DAG.getNode(X86ISD::EH_RETURN, dl, 8430 MVT::Other, 8431 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 8432} 8433 8434SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op, 8435 SelectionDAG &DAG) const { 8436 SDValue Root = Op.getOperand(0); 8437 SDValue Trmp = Op.getOperand(1); // trampoline 8438 SDValue FPtr = Op.getOperand(2); // nested function 8439 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 8440 DebugLoc dl = Op.getDebugLoc(); 8441 8442 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 8443 8444 if (Subtarget->is64Bit()) { 8445 SDValue OutChains[6]; 8446 8447 // Large code-model. 8448 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 8449 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 8450 8451 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10); 8452 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11); 8453 8454 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 8455 8456 // Load the pointer to the nested function into R11. 8457 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 8458 SDValue Addr = Trmp; 8459 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8460 Addr, MachinePointerInfo(TrmpAddr), 8461 false, false, 0); 8462 8463 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8464 DAG.getConstant(2, MVT::i64)); 8465 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 8466 MachinePointerInfo(TrmpAddr, 2), 8467 false, false, 2); 8468 8469 // Load the 'nest' parameter value into R10. 8470 // R10 is specified in X86CallingConv.td 8471 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 8472 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8473 DAG.getConstant(10, MVT::i64)); 8474 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8475 Addr, MachinePointerInfo(TrmpAddr, 10), 8476 false, false, 0); 8477 8478 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8479 DAG.getConstant(12, MVT::i64)); 8480 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 8481 MachinePointerInfo(TrmpAddr, 12), 8482 false, false, 2); 8483 8484 // Jump to the nested function. 8485 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 8486 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8487 DAG.getConstant(20, MVT::i64)); 8488 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 8489 Addr, MachinePointerInfo(TrmpAddr, 20), 8490 false, false, 0); 8491 8492 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 8493 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 8494 DAG.getConstant(22, MVT::i64)); 8495 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 8496 MachinePointerInfo(TrmpAddr, 22), 8497 false, false, 0); 8498 8499 SDValue Ops[] = 8500 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) }; 8501 return DAG.getMergeValues(Ops, 2, dl); 8502 } else { 8503 const Function *Func = 8504 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 8505 CallingConv::ID CC = Func->getCallingConv(); 8506 unsigned NestReg; 8507 8508 switch (CC) { 8509 default: 8510 llvm_unreachable("Unsupported calling convention"); 8511 case CallingConv::C: 8512 case CallingConv::X86_StdCall: { 8513 // Pass 'nest' parameter in ECX. 8514 // Must be kept in sync with X86CallingConv.td 8515 NestReg = X86::ECX; 8516 8517 // Check that ECX wasn't needed by an 'inreg' parameter. 8518 const FunctionType *FTy = Func->getFunctionType(); 8519 const AttrListPtr &Attrs = Func->getAttributes(); 8520 8521 if (!Attrs.isEmpty() && !Func->isVarArg()) { 8522 unsigned InRegCount = 0; 8523 unsigned Idx = 1; 8524 8525 for (FunctionType::param_iterator I = FTy->param_begin(), 8526 E = FTy->param_end(); I != E; ++I, ++Idx) 8527 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 8528 // FIXME: should only count parameters that are lowered to integers. 8529 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 8530 8531 if (InRegCount > 2) { 8532 report_fatal_error("Nest register in use - reduce number of inreg" 8533 " parameters!"); 8534 } 8535 } 8536 break; 8537 } 8538 case CallingConv::X86_FastCall: 8539 case CallingConv::X86_ThisCall: 8540 case CallingConv::Fast: 8541 // Pass 'nest' parameter in EAX. 8542 // Must be kept in sync with X86CallingConv.td 8543 NestReg = X86::EAX; 8544 break; 8545 } 8546 8547 SDValue OutChains[4]; 8548 SDValue Addr, Disp; 8549 8550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8551 DAG.getConstant(10, MVT::i32)); 8552 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 8553 8554 // This is storing the opcode for MOV32ri. 8555 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 8556 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg); 8557 OutChains[0] = DAG.getStore(Root, dl, 8558 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 8559 Trmp, MachinePointerInfo(TrmpAddr), 8560 false, false, 0); 8561 8562 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8563 DAG.getConstant(1, MVT::i32)); 8564 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 8565 MachinePointerInfo(TrmpAddr, 1), 8566 false, false, 1); 8567 8568 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 8569 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8570 DAG.getConstant(5, MVT::i32)); 8571 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 8572 MachinePointerInfo(TrmpAddr, 5), 8573 false, false, 1); 8574 8575 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 8576 DAG.getConstant(6, MVT::i32)); 8577 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 8578 MachinePointerInfo(TrmpAddr, 6), 8579 false, false, 1); 8580 8581 SDValue Ops[] = 8582 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) }; 8583 return DAG.getMergeValues(Ops, 2, dl); 8584 } 8585} 8586 8587SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8588 SelectionDAG &DAG) const { 8589 /* 8590 The rounding mode is in bits 11:10 of FPSR, and has the following 8591 settings: 8592 00 Round to nearest 8593 01 Round to -inf 8594 10 Round to +inf 8595 11 Round to 0 8596 8597 FLT_ROUNDS, on the other hand, expects the following: 8598 -1 Undefined 8599 0 Round to 0 8600 1 Round to nearest 8601 2 Round to +inf 8602 3 Round to -inf 8603 8604 To perform the conversion, we do: 8605 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 8606 */ 8607 8608 MachineFunction &MF = DAG.getMachineFunction(); 8609 const TargetMachine &TM = MF.getTarget(); 8610 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 8611 unsigned StackAlignment = TFI.getStackAlignment(); 8612 EVT VT = Op.getValueType(); 8613 DebugLoc DL = Op.getDebugLoc(); 8614 8615 // Save FP Control Word to stack slot 8616 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 8617 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8618 8619 8620 MachineMemOperand *MMO = 8621 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8622 MachineMemOperand::MOStore, 2, 2); 8623 8624 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 8625 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 8626 DAG.getVTList(MVT::Other), 8627 Ops, 2, MVT::i16, MMO); 8628 8629 // Load FP Control Word from stack slot 8630 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 8631 MachinePointerInfo(), false, false, 0); 8632 8633 // Transform as necessary 8634 SDValue CWD1 = 8635 DAG.getNode(ISD::SRL, DL, MVT::i16, 8636 DAG.getNode(ISD::AND, DL, MVT::i16, 8637 CWD, DAG.getConstant(0x800, MVT::i16)), 8638 DAG.getConstant(11, MVT::i8)); 8639 SDValue CWD2 = 8640 DAG.getNode(ISD::SRL, DL, MVT::i16, 8641 DAG.getNode(ISD::AND, DL, MVT::i16, 8642 CWD, DAG.getConstant(0x400, MVT::i16)), 8643 DAG.getConstant(9, MVT::i8)); 8644 8645 SDValue RetVal = 8646 DAG.getNode(ISD::AND, DL, MVT::i16, 8647 DAG.getNode(ISD::ADD, DL, MVT::i16, 8648 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 8649 DAG.getConstant(1, MVT::i16)), 8650 DAG.getConstant(3, MVT::i16)); 8651 8652 8653 return DAG.getNode((VT.getSizeInBits() < 16 ? 8654 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 8655} 8656 8657SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 8658 EVT VT = Op.getValueType(); 8659 EVT OpVT = VT; 8660 unsigned NumBits = VT.getSizeInBits(); 8661 DebugLoc dl = Op.getDebugLoc(); 8662 8663 Op = Op.getOperand(0); 8664 if (VT == MVT::i8) { 8665 // Zero extend to i32 since there is not an i8 bsr. 8666 OpVT = MVT::i32; 8667 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8668 } 8669 8670 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 8671 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8672 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 8673 8674 // If src is zero (i.e. bsr sets ZF), returns NumBits. 8675 SDValue Ops[] = { 8676 Op, 8677 DAG.getConstant(NumBits+NumBits-1, OpVT), 8678 DAG.getConstant(X86::COND_E, MVT::i8), 8679 Op.getValue(1) 8680 }; 8681 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8682 8683 // Finally xor with NumBits-1. 8684 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 8685 8686 if (VT == MVT::i8) 8687 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8688 return Op; 8689} 8690 8691SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 8692 EVT VT = Op.getValueType(); 8693 EVT OpVT = VT; 8694 unsigned NumBits = VT.getSizeInBits(); 8695 DebugLoc dl = Op.getDebugLoc(); 8696 8697 Op = Op.getOperand(0); 8698 if (VT == MVT::i8) { 8699 OpVT = MVT::i32; 8700 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 8701 } 8702 8703 // Issue a bsf (scan bits forward) which also sets EFLAGS. 8704 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 8705 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 8706 8707 // If src is zero (i.e. bsf sets ZF), returns NumBits. 8708 SDValue Ops[] = { 8709 Op, 8710 DAG.getConstant(NumBits, OpVT), 8711 DAG.getConstant(X86::COND_E, MVT::i8), 8712 Op.getValue(1) 8713 }; 8714 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 8715 8716 if (VT == MVT::i8) 8717 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 8718 return Op; 8719} 8720 8721SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const { 8722 EVT VT = Op.getValueType(); 8723 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 8724 DebugLoc dl = Op.getDebugLoc(); 8725 8726 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 8727 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 8728 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 8729 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 8730 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 8731 // 8732 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 8733 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 8734 // return AloBlo + AloBhi + AhiBlo; 8735 8736 SDValue A = Op.getOperand(0); 8737 SDValue B = Op.getOperand(1); 8738 8739 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8740 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8741 A, DAG.getConstant(32, MVT::i32)); 8742 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8743 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 8744 B, DAG.getConstant(32, MVT::i32)); 8745 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8746 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8747 A, B); 8748 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8749 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8750 A, Bhi); 8751 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8752 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 8753 Ahi, B); 8754 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8755 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8756 AloBhi, DAG.getConstant(32, MVT::i32)); 8757 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8758 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 8759 AhiBlo, DAG.getConstant(32, MVT::i32)); 8760 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 8761 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 8762 return Res; 8763} 8764 8765SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const { 8766 EVT VT = Op.getValueType(); 8767 DebugLoc dl = Op.getDebugLoc(); 8768 SDValue R = Op.getOperand(0); 8769 8770 LLVMContext *Context = DAG.getContext(); 8771 8772 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later"); 8773 8774 if (VT == MVT::v4i32) { 8775 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8776 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 8777 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 8778 8779 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 8780 8781 std::vector<Constant*> CV(4, CI); 8782 Constant *C = ConstantVector::get(CV); 8783 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8784 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8785 MachinePointerInfo::getConstantPool(), 8786 false, false, 16); 8787 8788 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 8789 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 8790 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 8791 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 8792 } 8793 if (VT == MVT::v16i8) { 8794 // a = a << 5; 8795 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8796 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 8797 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 8798 8799 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 8800 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 8801 8802 std::vector<Constant*> CVM1(16, CM1); 8803 std::vector<Constant*> CVM2(16, CM2); 8804 Constant *C = ConstantVector::get(CVM1); 8805 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8806 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8807 MachinePointerInfo::getConstantPool(), 8808 false, false, 16); 8809 8810 // r = pblendv(r, psllw(r & (char16)15, 4), a); 8811 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8812 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8813 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8814 DAG.getConstant(4, MVT::i32)); 8815 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8816 // a += a 8817 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8818 8819 C = ConstantVector::get(CVM2); 8820 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8821 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8822 MachinePointerInfo::getConstantPool(), 8823 false, false, 16); 8824 8825 // r = pblendv(r, psllw(r & (char16)63, 2), a); 8826 M = DAG.getNode(ISD::AND, dl, VT, R, M); 8827 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 8828 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 8829 DAG.getConstant(2, MVT::i32)); 8830 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op); 8831 // a += a 8832 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 8833 8834 // return pblendv(r, r+r, a); 8835 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 8836 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op); 8837 return R; 8838 } 8839 return SDValue(); 8840} 8841 8842SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 8843 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 8844 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 8845 // looks for this combo and may remove the "setcc" instruction if the "setcc" 8846 // has only one use. 8847 SDNode *N = Op.getNode(); 8848 SDValue LHS = N->getOperand(0); 8849 SDValue RHS = N->getOperand(1); 8850 unsigned BaseOp = 0; 8851 unsigned Cond = 0; 8852 DebugLoc DL = Op.getDebugLoc(); 8853 switch (Op.getOpcode()) { 8854 default: llvm_unreachable("Unknown ovf instruction!"); 8855 case ISD::SADDO: 8856 // A subtract of one will be selected as a INC. Note that INC doesn't 8857 // set CF, so we can't do this for UADDO. 8858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 8859 if (C->getAPIntValue() == 1) { 8860 BaseOp = X86ISD::INC; 8861 Cond = X86::COND_O; 8862 break; 8863 } 8864 BaseOp = X86ISD::ADD; 8865 Cond = X86::COND_O; 8866 break; 8867 case ISD::UADDO: 8868 BaseOp = X86ISD::ADD; 8869 Cond = X86::COND_B; 8870 break; 8871 case ISD::SSUBO: 8872 // A subtract of one will be selected as a DEC. Note that DEC doesn't 8873 // set CF, so we can't do this for USUBO. 8874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 8875 if (C->getAPIntValue() == 1) { 8876 BaseOp = X86ISD::DEC; 8877 Cond = X86::COND_O; 8878 break; 8879 } 8880 BaseOp = X86ISD::SUB; 8881 Cond = X86::COND_O; 8882 break; 8883 case ISD::USUBO: 8884 BaseOp = X86ISD::SUB; 8885 Cond = X86::COND_B; 8886 break; 8887 case ISD::SMULO: 8888 BaseOp = X86ISD::SMUL; 8889 Cond = X86::COND_O; 8890 break; 8891 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 8892 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 8893 MVT::i32); 8894 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 8895 8896 SDValue SetCC = 8897 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 8898 DAG.getConstant(X86::COND_O, MVT::i32), 8899 SDValue(Sum.getNode(), 2)); 8900 8901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 8902 return Sum; 8903 } 8904 } 8905 8906 // Also sets EFLAGS. 8907 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 8908 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 8909 8910 SDValue SetCC = 8911 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 8912 DAG.getConstant(Cond, MVT::i32), 8913 SDValue(Sum.getNode(), 1)); 8914 8915 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC); 8916 return Sum; 8917} 8918 8919SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 8920 DebugLoc dl = Op.getDebugLoc(); 8921 8922 if (!Subtarget->hasSSE2()) { 8923 SDValue Chain = Op.getOperand(0); 8924 SDValue Zero = DAG.getConstant(0, 8925 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 8926 SDValue Ops[] = { 8927 DAG.getRegister(X86::ESP, MVT::i32), // Base 8928 DAG.getTargetConstant(1, MVT::i8), // Scale 8929 DAG.getRegister(0, MVT::i32), // Index 8930 DAG.getTargetConstant(0, MVT::i32), // Disp 8931 DAG.getRegister(0, MVT::i32), // Segment. 8932 Zero, 8933 Chain 8934 }; 8935 SDNode *Res = 8936 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 8937 array_lengthof(Ops)); 8938 return SDValue(Res, 0); 8939 } 8940 8941 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 8942 if (!isDev) 8943 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 8944 8945 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 8946 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8947 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 8948 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 8949 8950 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 8951 if (!Op1 && !Op2 && !Op3 && Op4) 8952 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 8953 8954 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 8955 if (Op1 && !Op2 && !Op3 && !Op4) 8956 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 8957 8958 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 8959 // (MFENCE)>; 8960 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 8961} 8962 8963SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8964 EVT T = Op.getValueType(); 8965 DebugLoc DL = Op.getDebugLoc(); 8966 unsigned Reg = 0; 8967 unsigned size = 0; 8968 switch(T.getSimpleVT().SimpleTy) { 8969 default: 8970 assert(false && "Invalid value type!"); 8971 case MVT::i8: Reg = X86::AL; size = 1; break; 8972 case MVT::i16: Reg = X86::AX; size = 2; break; 8973 case MVT::i32: Reg = X86::EAX; size = 4; break; 8974 case MVT::i64: 8975 assert(Subtarget->is64Bit() && "Node not type legal!"); 8976 Reg = X86::RAX; size = 8; 8977 break; 8978 } 8979 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 8980 Op.getOperand(2), SDValue()); 8981 SDValue Ops[] = { cpIn.getValue(0), 8982 Op.getOperand(1), 8983 Op.getOperand(3), 8984 DAG.getTargetConstant(size, MVT::i8), 8985 cpIn.getValue(1) }; 8986 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 8987 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 8988 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 8989 Ops, 5, T, MMO); 8990 SDValue cpOut = 8991 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 8992 return cpOut; 8993} 8994 8995SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 8996 SelectionDAG &DAG) const { 8997 assert(Subtarget->is64Bit() && "Result not type legalized?"); 8998 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 8999 SDValue TheChain = Op.getOperand(0); 9000 DebugLoc dl = Op.getDebugLoc(); 9001 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 9002 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 9003 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 9004 rax.getValue(2)); 9005 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 9006 DAG.getConstant(32, MVT::i8)); 9007 SDValue Ops[] = { 9008 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 9009 rdx.getValue(1) 9010 }; 9011 return DAG.getMergeValues(Ops, 2, dl); 9012} 9013 9014SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 9015 SelectionDAG &DAG) const { 9016 EVT SrcVT = Op.getOperand(0).getValueType(); 9017 EVT DstVT = Op.getValueType(); 9018 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 9019 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 9020 assert((DstVT == MVT::i64 || 9021 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 9022 "Unexpected custom BITCAST"); 9023 // i64 <=> MMX conversions are Legal. 9024 if (SrcVT==MVT::i64 && DstVT.isVector()) 9025 return Op; 9026 if (DstVT==MVT::i64 && SrcVT.isVector()) 9027 return Op; 9028 // MMX <=> MMX conversions are Legal. 9029 if (SrcVT.isVector() && DstVT.isVector()) 9030 return Op; 9031 // All other conversions need to be expanded. 9032 return SDValue(); 9033} 9034 9035SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 9036 SDNode *Node = Op.getNode(); 9037 DebugLoc dl = Node->getDebugLoc(); 9038 EVT T = Node->getValueType(0); 9039 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 9040 DAG.getConstant(0, T), Node->getOperand(2)); 9041 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 9042 cast<AtomicSDNode>(Node)->getMemoryVT(), 9043 Node->getOperand(0), 9044 Node->getOperand(1), negOp, 9045 cast<AtomicSDNode>(Node)->getSrcValue(), 9046 cast<AtomicSDNode>(Node)->getAlignment()); 9047} 9048 9049static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 9050 EVT VT = Op.getNode()->getValueType(0); 9051 9052 // Let legalize expand this if it isn't a legal type yet. 9053 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9054 return SDValue(); 9055 9056 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 9057 9058 unsigned Opc; 9059 bool ExtraOp = false; 9060 switch (Op.getOpcode()) { 9061 default: assert(0 && "Invalid code"); 9062 case ISD::ADDC: Opc = X86ISD::ADD; break; 9063 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 9064 case ISD::SUBC: Opc = X86ISD::SUB; break; 9065 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 9066 } 9067 9068 if (!ExtraOp) 9069 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9070 Op.getOperand(1)); 9071 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 9072 Op.getOperand(1), Op.getOperand(2)); 9073} 9074 9075/// LowerOperation - Provide custom lowering hooks for some operations. 9076/// 9077SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9078 switch (Op.getOpcode()) { 9079 default: llvm_unreachable("Should not custom lower this!"); 9080 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 9081 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 9082 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 9083 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9084 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 9085 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9086 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9087 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9088 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 9089 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 9090 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9091 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9092 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9093 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9094 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 9095 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9096 case ISD::SHL_PARTS: 9097 case ISD::SRA_PARTS: 9098 case ISD::SRL_PARTS: return LowerShift(Op, DAG); 9099 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 9100 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 9101 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 9102 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 9103 case ISD::FABS: return LowerFABS(Op, DAG); 9104 case ISD::FNEG: return LowerFNEG(Op, DAG); 9105 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 9106 case ISD::SETCC: return LowerSETCC(Op, DAG); 9107 case ISD::VSETCC: return LowerVSETCC(Op, DAG); 9108 case ISD::SELECT: return LowerSELECT(Op, DAG); 9109 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 9110 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9111 case ISD::VASTART: return LowerVASTART(Op, DAG); 9112 case ISD::VAARG: return LowerVAARG(Op, DAG); 9113 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9114 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9115 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9116 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9117 case ISD::FRAME_TO_ARGS_OFFSET: 9118 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 9119 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9120 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 9121 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG); 9122 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9123 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 9124 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 9125 case ISD::MUL: return LowerMUL_V2I64(Op, DAG); 9126 case ISD::SHL: return LowerSHL(Op, DAG); 9127 case ISD::SADDO: 9128 case ISD::UADDO: 9129 case ISD::SSUBO: 9130 case ISD::USUBO: 9131 case ISD::SMULO: 9132 case ISD::UMULO: return LowerXALUO(Op, DAG); 9133 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 9134 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9135 case ISD::ADDC: 9136 case ISD::ADDE: 9137 case ISD::SUBC: 9138 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 9139 } 9140} 9141 9142void X86TargetLowering:: 9143ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 9144 SelectionDAG &DAG, unsigned NewOp) const { 9145 EVT T = Node->getValueType(0); 9146 DebugLoc dl = Node->getDebugLoc(); 9147 assert (T == MVT::i64 && "Only know how to expand i64 atomics"); 9148 9149 SDValue Chain = Node->getOperand(0); 9150 SDValue In1 = Node->getOperand(1); 9151 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9152 Node->getOperand(2), DAG.getIntPtrConstant(0)); 9153 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 9154 Node->getOperand(2), DAG.getIntPtrConstant(1)); 9155 SDValue Ops[] = { Chain, In1, In2L, In2H }; 9156 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9157 SDValue Result = 9158 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 9159 cast<MemSDNode>(Node)->getMemOperand()); 9160 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 9161 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9162 Results.push_back(Result.getValue(2)); 9163} 9164 9165/// ReplaceNodeResults - Replace a node with an illegal result type 9166/// with a new node built out of custom code. 9167void X86TargetLowering::ReplaceNodeResults(SDNode *N, 9168 SmallVectorImpl<SDValue>&Results, 9169 SelectionDAG &DAG) const { 9170 DebugLoc dl = N->getDebugLoc(); 9171 switch (N->getOpcode()) { 9172 default: 9173 assert(false && "Do not know how to custom type legalize this operation!"); 9174 return; 9175 case ISD::ADDC: 9176 case ISD::ADDE: 9177 case ISD::SUBC: 9178 case ISD::SUBE: 9179 // We don't want to expand or promote these. 9180 return; 9181 case ISD::FP_TO_SINT: { 9182 std::pair<SDValue,SDValue> Vals = 9183 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 9184 SDValue FIST = Vals.first, StackSlot = Vals.second; 9185 if (FIST.getNode() != 0) { 9186 EVT VT = N->getValueType(0); 9187 // Return a load from the stack slot. 9188 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 9189 MachinePointerInfo(), false, false, 0)); 9190 } 9191 return; 9192 } 9193 case ISD::READCYCLECOUNTER: { 9194 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9195 SDValue TheChain = N->getOperand(0); 9196 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 9197 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 9198 rd.getValue(1)); 9199 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 9200 eax.getValue(2)); 9201 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 9202 SDValue Ops[] = { eax, edx }; 9203 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 9204 Results.push_back(edx.getValue(1)); 9205 return; 9206 } 9207 case ISD::ATOMIC_CMP_SWAP: { 9208 EVT T = N->getValueType(0); 9209 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap"); 9210 SDValue cpInL, cpInH; 9211 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9212 DAG.getConstant(0, MVT::i32)); 9213 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2), 9214 DAG.getConstant(1, MVT::i32)); 9215 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue()); 9216 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH, 9217 cpInL.getValue(1)); 9218 SDValue swapInL, swapInH; 9219 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9220 DAG.getConstant(0, MVT::i32)); 9221 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3), 9222 DAG.getConstant(1, MVT::i32)); 9223 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL, 9224 cpInH.getValue(1)); 9225 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH, 9226 swapInL.getValue(1)); 9227 SDValue Ops[] = { swapInH.getValue(0), 9228 N->getOperand(1), 9229 swapInH.getValue(1) }; 9230 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 9231 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 9232 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, 9233 Ops, 3, T, MMO); 9234 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX, 9235 MVT::i32, Result.getValue(1)); 9236 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX, 9237 MVT::i32, cpOutL.getValue(2)); 9238 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 9239 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 9240 Results.push_back(cpOutH.getValue(1)); 9241 return; 9242 } 9243 case ISD::ATOMIC_LOAD_ADD: 9244 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 9245 return; 9246 case ISD::ATOMIC_LOAD_AND: 9247 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 9248 return; 9249 case ISD::ATOMIC_LOAD_NAND: 9250 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 9251 return; 9252 case ISD::ATOMIC_LOAD_OR: 9253 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 9254 return; 9255 case ISD::ATOMIC_LOAD_SUB: 9256 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 9257 return; 9258 case ISD::ATOMIC_LOAD_XOR: 9259 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 9260 return; 9261 case ISD::ATOMIC_SWAP: 9262 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 9263 return; 9264 } 9265} 9266 9267const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 9268 switch (Opcode) { 9269 default: return NULL; 9270 case X86ISD::BSF: return "X86ISD::BSF"; 9271 case X86ISD::BSR: return "X86ISD::BSR"; 9272 case X86ISD::SHLD: return "X86ISD::SHLD"; 9273 case X86ISD::SHRD: return "X86ISD::SHRD"; 9274 case X86ISD::FAND: return "X86ISD::FAND"; 9275 case X86ISD::FOR: return "X86ISD::FOR"; 9276 case X86ISD::FXOR: return "X86ISD::FXOR"; 9277 case X86ISD::FSRL: return "X86ISD::FSRL"; 9278 case X86ISD::FILD: return "X86ISD::FILD"; 9279 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 9280 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 9281 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 9282 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 9283 case X86ISD::FLD: return "X86ISD::FLD"; 9284 case X86ISD::FST: return "X86ISD::FST"; 9285 case X86ISD::CALL: return "X86ISD::CALL"; 9286 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 9287 case X86ISD::BT: return "X86ISD::BT"; 9288 case X86ISD::CMP: return "X86ISD::CMP"; 9289 case X86ISD::COMI: return "X86ISD::COMI"; 9290 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 9291 case X86ISD::SETCC: return "X86ISD::SETCC"; 9292 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 9293 case X86ISD::CMOV: return "X86ISD::CMOV"; 9294 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 9295 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 9296 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 9297 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 9298 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 9299 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 9300 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 9301 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 9302 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 9303 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 9304 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 9305 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 9306 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 9307 case X86ISD::PANDN: return "X86ISD::PANDN"; 9308 case X86ISD::PSIGNB: return "X86ISD::PSIGNB"; 9309 case X86ISD::PSIGNW: return "X86ISD::PSIGNW"; 9310 case X86ISD::PSIGND: return "X86ISD::PSIGND"; 9311 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB"; 9312 case X86ISD::FMAX: return "X86ISD::FMAX"; 9313 case X86ISD::FMIN: return "X86ISD::FMIN"; 9314 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 9315 case X86ISD::FRCP: return "X86ISD::FRCP"; 9316 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 9317 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 9318 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 9319 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 9320 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 9321 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 9322 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 9323 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 9324 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 9325 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 9326 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 9327 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 9328 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 9329 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 9330 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 9331 case X86ISD::VSHL: return "X86ISD::VSHL"; 9332 case X86ISD::VSRL: return "X86ISD::VSRL"; 9333 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 9334 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 9335 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 9336 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 9337 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 9338 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 9339 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 9340 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 9341 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 9342 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 9343 case X86ISD::ADD: return "X86ISD::ADD"; 9344 case X86ISD::SUB: return "X86ISD::SUB"; 9345 case X86ISD::ADC: return "X86ISD::ADC"; 9346 case X86ISD::SBB: return "X86ISD::SBB"; 9347 case X86ISD::SMUL: return "X86ISD::SMUL"; 9348 case X86ISD::UMUL: return "X86ISD::UMUL"; 9349 case X86ISD::INC: return "X86ISD::INC"; 9350 case X86ISD::DEC: return "X86ISD::DEC"; 9351 case X86ISD::OR: return "X86ISD::OR"; 9352 case X86ISD::XOR: return "X86ISD::XOR"; 9353 case X86ISD::AND: return "X86ISD::AND"; 9354 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 9355 case X86ISD::PTEST: return "X86ISD::PTEST"; 9356 case X86ISD::TESTP: return "X86ISD::TESTP"; 9357 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 9358 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 9359 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 9360 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 9361 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 9362 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 9363 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 9364 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 9365 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 9366 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 9367 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 9368 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 9369 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 9370 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 9371 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 9372 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 9373 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 9374 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 9375 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 9376 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 9377 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 9378 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS"; 9379 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD"; 9380 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS"; 9381 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD"; 9382 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY"; 9383 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY"; 9384 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS"; 9385 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD"; 9386 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW"; 9387 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD"; 9388 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ"; 9389 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ"; 9390 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW"; 9391 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD"; 9392 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ"; 9393 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ"; 9394 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 9395 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 9396 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 9397 } 9398} 9399 9400// isLegalAddressingMode - Return true if the addressing mode represented 9401// by AM is legal for this target, for a load/store of the specified type. 9402bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 9403 const Type *Ty) const { 9404 // X86 supports extremely general addressing modes. 9405 CodeModel::Model M = getTargetMachine().getCodeModel(); 9406 Reloc::Model R = getTargetMachine().getRelocationModel(); 9407 9408 // X86 allows a sign-extended 32-bit immediate field as a displacement. 9409 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 9410 return false; 9411 9412 if (AM.BaseGV) { 9413 unsigned GVFlags = 9414 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 9415 9416 // If a reference to this global requires an extra load, we can't fold it. 9417 if (isGlobalStubReference(GVFlags)) 9418 return false; 9419 9420 // If BaseGV requires a register for the PIC base, we cannot also have a 9421 // BaseReg specified. 9422 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 9423 return false; 9424 9425 // If lower 4G is not available, then we must use rip-relative addressing. 9426 if ((M != CodeModel::Small || R != Reloc::Static) && 9427 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 9428 return false; 9429 } 9430 9431 switch (AM.Scale) { 9432 case 0: 9433 case 1: 9434 case 2: 9435 case 4: 9436 case 8: 9437 // These scales always work. 9438 break; 9439 case 3: 9440 case 5: 9441 case 9: 9442 // These scales are formed with basereg+scalereg. Only accept if there is 9443 // no basereg yet. 9444 if (AM.HasBaseReg) 9445 return false; 9446 break; 9447 default: // Other stuff never works. 9448 return false; 9449 } 9450 9451 return true; 9452} 9453 9454 9455bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const { 9456 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9457 return false; 9458 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9459 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9460 if (NumBits1 <= NumBits2) 9461 return false; 9462 return true; 9463} 9464 9465bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9466 if (!VT1.isInteger() || !VT2.isInteger()) 9467 return false; 9468 unsigned NumBits1 = VT1.getSizeInBits(); 9469 unsigned NumBits2 = VT2.getSizeInBits(); 9470 if (NumBits1 <= NumBits2) 9471 return false; 9472 return true; 9473} 9474 9475bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const { 9476 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9477 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 9478} 9479 9480bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 9481 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 9482 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 9483} 9484 9485bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 9486 // i16 instructions are longer (0x66 prefix) and potentially slower. 9487 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 9488} 9489 9490/// isShuffleMaskLegal - Targets can use this to indicate that they only 9491/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 9492/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 9493/// are assumed to be legal. 9494bool 9495X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 9496 EVT VT) const { 9497 // Very little shuffling can be done for 64-bit vectors right now. 9498 if (VT.getSizeInBits() == 64) 9499 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3()); 9500 9501 // FIXME: pshufb, blends, shifts. 9502 return (VT.getVectorNumElements() == 2 || 9503 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 9504 isMOVLMask(M, VT) || 9505 isSHUFPMask(M, VT) || 9506 isPSHUFDMask(M, VT) || 9507 isPSHUFHWMask(M, VT) || 9508 isPSHUFLWMask(M, VT) || 9509 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) || 9510 isUNPCKLMask(M, VT) || 9511 isUNPCKHMask(M, VT) || 9512 isUNPCKL_v_undef_Mask(M, VT) || 9513 isUNPCKH_v_undef_Mask(M, VT)); 9514} 9515 9516bool 9517X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 9518 EVT VT) const { 9519 unsigned NumElts = VT.getVectorNumElements(); 9520 // FIXME: This collection of masks seems suspect. 9521 if (NumElts == 2) 9522 return true; 9523 if (NumElts == 4 && VT.getSizeInBits() == 128) { 9524 return (isMOVLMask(Mask, VT) || 9525 isCommutedMOVLMask(Mask, VT, true) || 9526 isSHUFPMask(Mask, VT) || 9527 isCommutedSHUFPMask(Mask, VT)); 9528 } 9529 return false; 9530} 9531 9532//===----------------------------------------------------------------------===// 9533// X86 Scheduler Hooks 9534//===----------------------------------------------------------------------===// 9535 9536// private utility function 9537MachineBasicBlock * 9538X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 9539 MachineBasicBlock *MBB, 9540 unsigned regOpc, 9541 unsigned immOpc, 9542 unsigned LoadOpc, 9543 unsigned CXchgOpc, 9544 unsigned notOpc, 9545 unsigned EAXreg, 9546 TargetRegisterClass *RC, 9547 bool invSrc) const { 9548 // For the atomic bitwise operator, we generate 9549 // thisMBB: 9550 // newMBB: 9551 // ld t1 = [bitinstr.addr] 9552 // op t2 = t1, [bitinstr.val] 9553 // mov EAX = t1 9554 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9555 // bz newMBB 9556 // fallthrough -->nextMBB 9557 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9558 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9559 MachineFunction::iterator MBBIter = MBB; 9560 ++MBBIter; 9561 9562 /// First build the CFG 9563 MachineFunction *F = MBB->getParent(); 9564 MachineBasicBlock *thisMBB = MBB; 9565 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9566 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9567 F->insert(MBBIter, newMBB); 9568 F->insert(MBBIter, nextMBB); 9569 9570 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9571 nextMBB->splice(nextMBB->begin(), thisMBB, 9572 llvm::next(MachineBasicBlock::iterator(bInstr)), 9573 thisMBB->end()); 9574 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9575 9576 // Update thisMBB to fall through to newMBB 9577 thisMBB->addSuccessor(newMBB); 9578 9579 // newMBB jumps to itself and fall through to nextMBB 9580 newMBB->addSuccessor(nextMBB); 9581 newMBB->addSuccessor(newMBB); 9582 9583 // Insert instructions into newMBB based on incoming instruction 9584 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9585 "unexpected number of operands"); 9586 DebugLoc dl = bInstr->getDebugLoc(); 9587 MachineOperand& destOper = bInstr->getOperand(0); 9588 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9589 int numArgs = bInstr->getNumOperands() - 1; 9590 for (int i=0; i < numArgs; ++i) 9591 argOpers[i] = &bInstr->getOperand(i+1); 9592 9593 // x86 address has 4 operands: base, index, scale, and displacement 9594 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9595 int valArgIndx = lastAddrIndx + 1; 9596 9597 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9598 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 9599 for (int i=0; i <= lastAddrIndx; ++i) 9600 (*MIB).addOperand(*argOpers[i]); 9601 9602 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 9603 if (invSrc) { 9604 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 9605 } 9606 else 9607 tt = t1; 9608 9609 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9610 assert((argOpers[valArgIndx]->isReg() || 9611 argOpers[valArgIndx]->isImm()) && 9612 "invalid operand"); 9613 if (argOpers[valArgIndx]->isReg()) 9614 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 9615 else 9616 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 9617 MIB.addReg(tt); 9618 (*MIB).addOperand(*argOpers[valArgIndx]); 9619 9620 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 9621 MIB.addReg(t1); 9622 9623 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 9624 for (int i=0; i <= lastAddrIndx; ++i) 9625 (*MIB).addOperand(*argOpers[i]); 9626 MIB.addReg(t2); 9627 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9628 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9629 bInstr->memoperands_end()); 9630 9631 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 9632 MIB.addReg(EAXreg); 9633 9634 // insert branch 9635 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9636 9637 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9638 return nextMBB; 9639} 9640 9641// private utility function: 64 bit atomics on 32 bit host. 9642MachineBasicBlock * 9643X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 9644 MachineBasicBlock *MBB, 9645 unsigned regOpcL, 9646 unsigned regOpcH, 9647 unsigned immOpcL, 9648 unsigned immOpcH, 9649 bool invSrc) const { 9650 // For the atomic bitwise operator, we generate 9651 // thisMBB (instructions are in pairs, except cmpxchg8b) 9652 // ld t1,t2 = [bitinstr.addr] 9653 // newMBB: 9654 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 9655 // op t5, t6 <- out1, out2, [bitinstr.val] 9656 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 9657 // mov ECX, EBX <- t5, t6 9658 // mov EAX, EDX <- t1, t2 9659 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 9660 // mov t3, t4 <- EAX, EDX 9661 // bz newMBB 9662 // result in out1, out2 9663 // fallthrough -->nextMBB 9664 9665 const TargetRegisterClass *RC = X86::GR32RegisterClass; 9666 const unsigned LoadOpc = X86::MOV32rm; 9667 const unsigned NotOpc = X86::NOT32r; 9668 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9669 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9670 MachineFunction::iterator MBBIter = MBB; 9671 ++MBBIter; 9672 9673 /// First build the CFG 9674 MachineFunction *F = MBB->getParent(); 9675 MachineBasicBlock *thisMBB = MBB; 9676 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9677 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9678 F->insert(MBBIter, newMBB); 9679 F->insert(MBBIter, nextMBB); 9680 9681 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9682 nextMBB->splice(nextMBB->begin(), thisMBB, 9683 llvm::next(MachineBasicBlock::iterator(bInstr)), 9684 thisMBB->end()); 9685 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9686 9687 // Update thisMBB to fall through to newMBB 9688 thisMBB->addSuccessor(newMBB); 9689 9690 // newMBB jumps to itself and fall through to nextMBB 9691 newMBB->addSuccessor(nextMBB); 9692 newMBB->addSuccessor(newMBB); 9693 9694 DebugLoc dl = bInstr->getDebugLoc(); 9695 // Insert instructions into newMBB based on incoming instruction 9696 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 9697 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 9698 "unexpected number of operands"); 9699 MachineOperand& dest1Oper = bInstr->getOperand(0); 9700 MachineOperand& dest2Oper = bInstr->getOperand(1); 9701 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9702 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 9703 argOpers[i] = &bInstr->getOperand(i+2); 9704 9705 // We use some of the operands multiple times, so conservatively just 9706 // clear any kill flags that might be present. 9707 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 9708 argOpers[i]->setIsKill(false); 9709 } 9710 9711 // x86 address has 5 operands: base, index, scale, displacement, and segment. 9712 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9713 9714 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 9715 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 9716 for (int i=0; i <= lastAddrIndx; ++i) 9717 (*MIB).addOperand(*argOpers[i]); 9718 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 9719 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 9720 // add 4 to displacement. 9721 for (int i=0; i <= lastAddrIndx-2; ++i) 9722 (*MIB).addOperand(*argOpers[i]); 9723 MachineOperand newOp3 = *(argOpers[3]); 9724 if (newOp3.isImm()) 9725 newOp3.setImm(newOp3.getImm()+4); 9726 else 9727 newOp3.setOffset(newOp3.getOffset()+4); 9728 (*MIB).addOperand(newOp3); 9729 (*MIB).addOperand(*argOpers[lastAddrIndx]); 9730 9731 // t3/4 are defined later, at the bottom of the loop 9732 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 9733 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 9734 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 9735 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 9736 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 9737 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 9738 9739 // The subsequent operations should be using the destination registers of 9740 //the PHI instructions. 9741 if (invSrc) { 9742 t1 = F->getRegInfo().createVirtualRegister(RC); 9743 t2 = F->getRegInfo().createVirtualRegister(RC); 9744 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 9745 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 9746 } else { 9747 t1 = dest1Oper.getReg(); 9748 t2 = dest2Oper.getReg(); 9749 } 9750 9751 int valArgIndx = lastAddrIndx + 1; 9752 assert((argOpers[valArgIndx]->isReg() || 9753 argOpers[valArgIndx]->isImm()) && 9754 "invalid operand"); 9755 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 9756 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 9757 if (argOpers[valArgIndx]->isReg()) 9758 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 9759 else 9760 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 9761 if (regOpcL != X86::MOV32rr) 9762 MIB.addReg(t1); 9763 (*MIB).addOperand(*argOpers[valArgIndx]); 9764 assert(argOpers[valArgIndx + 1]->isReg() == 9765 argOpers[valArgIndx]->isReg()); 9766 assert(argOpers[valArgIndx + 1]->isImm() == 9767 argOpers[valArgIndx]->isImm()); 9768 if (argOpers[valArgIndx + 1]->isReg()) 9769 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 9770 else 9771 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 9772 if (regOpcH != X86::MOV32rr) 9773 MIB.addReg(t2); 9774 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 9775 9776 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9777 MIB.addReg(t1); 9778 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 9779 MIB.addReg(t2); 9780 9781 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 9782 MIB.addReg(t5); 9783 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 9784 MIB.addReg(t6); 9785 9786 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 9787 for (int i=0; i <= lastAddrIndx; ++i) 9788 (*MIB).addOperand(*argOpers[i]); 9789 9790 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9791 (*MIB).setMemRefs(bInstr->memoperands_begin(), 9792 bInstr->memoperands_end()); 9793 9794 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 9795 MIB.addReg(X86::EAX); 9796 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 9797 MIB.addReg(X86::EDX); 9798 9799 // insert branch 9800 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9801 9802 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 9803 return nextMBB; 9804} 9805 9806// private utility function 9807MachineBasicBlock * 9808X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 9809 MachineBasicBlock *MBB, 9810 unsigned cmovOpc) const { 9811 // For the atomic min/max operator, we generate 9812 // thisMBB: 9813 // newMBB: 9814 // ld t1 = [min/max.addr] 9815 // mov t2 = [min/max.val] 9816 // cmp t1, t2 9817 // cmov[cond] t2 = t1 9818 // mov EAX = t1 9819 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 9820 // bz newMBB 9821 // fallthrough -->nextMBB 9822 // 9823 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9824 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 9825 MachineFunction::iterator MBBIter = MBB; 9826 ++MBBIter; 9827 9828 /// First build the CFG 9829 MachineFunction *F = MBB->getParent(); 9830 MachineBasicBlock *thisMBB = MBB; 9831 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 9832 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 9833 F->insert(MBBIter, newMBB); 9834 F->insert(MBBIter, nextMBB); 9835 9836 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 9837 nextMBB->splice(nextMBB->begin(), thisMBB, 9838 llvm::next(MachineBasicBlock::iterator(mInstr)), 9839 thisMBB->end()); 9840 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 9841 9842 // Update thisMBB to fall through to newMBB 9843 thisMBB->addSuccessor(newMBB); 9844 9845 // newMBB jumps to newMBB and fall through to nextMBB 9846 newMBB->addSuccessor(nextMBB); 9847 newMBB->addSuccessor(newMBB); 9848 9849 DebugLoc dl = mInstr->getDebugLoc(); 9850 // Insert instructions into newMBB based on incoming instruction 9851 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 9852 "unexpected number of operands"); 9853 MachineOperand& destOper = mInstr->getOperand(0); 9854 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 9855 int numArgs = mInstr->getNumOperands() - 1; 9856 for (int i=0; i < numArgs; ++i) 9857 argOpers[i] = &mInstr->getOperand(i+1); 9858 9859 // x86 address has 4 operands: base, index, scale, and displacement 9860 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 9861 int valArgIndx = lastAddrIndx + 1; 9862 9863 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9864 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 9865 for (int i=0; i <= lastAddrIndx; ++i) 9866 (*MIB).addOperand(*argOpers[i]); 9867 9868 // We only support register and immediate values 9869 assert((argOpers[valArgIndx]->isReg() || 9870 argOpers[valArgIndx]->isImm()) && 9871 "invalid operand"); 9872 9873 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9874 if (argOpers[valArgIndx]->isReg()) 9875 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 9876 else 9877 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 9878 (*MIB).addOperand(*argOpers[valArgIndx]); 9879 9880 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 9881 MIB.addReg(t1); 9882 9883 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 9884 MIB.addReg(t1); 9885 MIB.addReg(t2); 9886 9887 // Generate movc 9888 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 9889 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 9890 MIB.addReg(t2); 9891 MIB.addReg(t1); 9892 9893 // Cmp and exchange if none has modified the memory location 9894 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 9895 for (int i=0; i <= lastAddrIndx; ++i) 9896 (*MIB).addOperand(*argOpers[i]); 9897 MIB.addReg(t3); 9898 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 9899 (*MIB).setMemRefs(mInstr->memoperands_begin(), 9900 mInstr->memoperands_end()); 9901 9902 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 9903 MIB.addReg(X86::EAX); 9904 9905 // insert branch 9906 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 9907 9908 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 9909 return nextMBB; 9910} 9911 9912// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 9913// or XMM0_V32I8 in AVX all of this code can be replaced with that 9914// in the .td file. 9915MachineBasicBlock * 9916X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 9917 unsigned numArgs, bool memArg) const { 9918 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) && 9919 "Target must have SSE4.2 or AVX features enabled"); 9920 9921 DebugLoc dl = MI->getDebugLoc(); 9922 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9923 unsigned Opc; 9924 if (!Subtarget->hasAVX()) { 9925 if (memArg) 9926 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 9927 else 9928 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 9929 } else { 9930 if (memArg) 9931 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 9932 else 9933 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 9934 } 9935 9936 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 9937 for (unsigned i = 0; i < numArgs; ++i) { 9938 MachineOperand &Op = MI->getOperand(i+1); 9939 if (!(Op.isReg() && Op.isImplicit())) 9940 MIB.addOperand(Op); 9941 } 9942 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg()) 9943 .addReg(X86::XMM0); 9944 9945 MI->eraseFromParent(); 9946 return BB; 9947} 9948 9949MachineBasicBlock * 9950X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 9951 DebugLoc dl = MI->getDebugLoc(); 9952 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9953 9954 // Address into RAX/EAX, other two args into ECX, EDX. 9955 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 9956 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 9957 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 9958 for (int i = 0; i < X86::AddrNumOperands; ++i) 9959 MIB.addOperand(MI->getOperand(i)); 9960 9961 unsigned ValOps = X86::AddrNumOperands; 9962 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 9963 .addReg(MI->getOperand(ValOps).getReg()); 9964 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 9965 .addReg(MI->getOperand(ValOps+1).getReg()); 9966 9967 // The instruction doesn't actually take any operands though. 9968 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 9969 9970 MI->eraseFromParent(); // The pseudo is gone now. 9971 return BB; 9972} 9973 9974MachineBasicBlock * 9975X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 9976 DebugLoc dl = MI->getDebugLoc(); 9977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 9978 9979 // First arg in ECX, the second in EAX. 9980 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 9981 .addReg(MI->getOperand(0).getReg()); 9982 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 9983 .addReg(MI->getOperand(1).getReg()); 9984 9985 // The instruction doesn't actually take any operands though. 9986 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 9987 9988 MI->eraseFromParent(); // The pseudo is gone now. 9989 return BB; 9990} 9991 9992MachineBasicBlock * 9993X86TargetLowering::EmitVAARG64WithCustomInserter( 9994 MachineInstr *MI, 9995 MachineBasicBlock *MBB) const { 9996 // Emit va_arg instruction on X86-64. 9997 9998 // Operands to this pseudo-instruction: 9999 // 0 ) Output : destination address (reg) 10000 // 1-5) Input : va_list address (addr, i64mem) 10001 // 6 ) ArgSize : Size (in bytes) of vararg type 10002 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 10003 // 8 ) Align : Alignment of type 10004 // 9 ) EFLAGS (implicit-def) 10005 10006 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 10007 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 10008 10009 unsigned DestReg = MI->getOperand(0).getReg(); 10010 MachineOperand &Base = MI->getOperand(1); 10011 MachineOperand &Scale = MI->getOperand(2); 10012 MachineOperand &Index = MI->getOperand(3); 10013 MachineOperand &Disp = MI->getOperand(4); 10014 MachineOperand &Segment = MI->getOperand(5); 10015 unsigned ArgSize = MI->getOperand(6).getImm(); 10016 unsigned ArgMode = MI->getOperand(7).getImm(); 10017 unsigned Align = MI->getOperand(8).getImm(); 10018 10019 // Memory Reference 10020 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 10021 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 10022 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 10023 10024 // Machine Information 10025 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10026 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 10027 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 10028 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 10029 DebugLoc DL = MI->getDebugLoc(); 10030 10031 // struct va_list { 10032 // i32 gp_offset 10033 // i32 fp_offset 10034 // i64 overflow_area (address) 10035 // i64 reg_save_area (address) 10036 // } 10037 // sizeof(va_list) = 24 10038 // alignment(va_list) = 8 10039 10040 unsigned TotalNumIntRegs = 6; 10041 unsigned TotalNumXMMRegs = 8; 10042 bool UseGPOffset = (ArgMode == 1); 10043 bool UseFPOffset = (ArgMode == 2); 10044 unsigned MaxOffset = TotalNumIntRegs * 8 + 10045 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 10046 10047 /* Align ArgSize to a multiple of 8 */ 10048 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 10049 bool NeedsAlign = (Align > 8); 10050 10051 MachineBasicBlock *thisMBB = MBB; 10052 MachineBasicBlock *overflowMBB; 10053 MachineBasicBlock *offsetMBB; 10054 MachineBasicBlock *endMBB; 10055 10056 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 10057 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 10058 unsigned OffsetReg = 0; 10059 10060 if (!UseGPOffset && !UseFPOffset) { 10061 // If we only pull from the overflow region, we don't create a branch. 10062 // We don't need to alter control flow. 10063 OffsetDestReg = 0; // unused 10064 OverflowDestReg = DestReg; 10065 10066 offsetMBB = NULL; 10067 overflowMBB = thisMBB; 10068 endMBB = thisMBB; 10069 } else { 10070 // First emit code to check if gp_offset (or fp_offset) is below the bound. 10071 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 10072 // If not, pull from overflow_area. (branch to overflowMBB) 10073 // 10074 // thisMBB 10075 // | . 10076 // | . 10077 // offsetMBB overflowMBB 10078 // | . 10079 // | . 10080 // endMBB 10081 10082 // Registers for the PHI in endMBB 10083 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 10084 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 10085 10086 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10087 MachineFunction *MF = MBB->getParent(); 10088 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10089 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10090 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 10091 10092 MachineFunction::iterator MBBIter = MBB; 10093 ++MBBIter; 10094 10095 // Insert the new basic blocks 10096 MF->insert(MBBIter, offsetMBB); 10097 MF->insert(MBBIter, overflowMBB); 10098 MF->insert(MBBIter, endMBB); 10099 10100 // Transfer the remainder of MBB and its successor edges to endMBB. 10101 endMBB->splice(endMBB->begin(), thisMBB, 10102 llvm::next(MachineBasicBlock::iterator(MI)), 10103 thisMBB->end()); 10104 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 10105 10106 // Make offsetMBB and overflowMBB successors of thisMBB 10107 thisMBB->addSuccessor(offsetMBB); 10108 thisMBB->addSuccessor(overflowMBB); 10109 10110 // endMBB is a successor of both offsetMBB and overflowMBB 10111 offsetMBB->addSuccessor(endMBB); 10112 overflowMBB->addSuccessor(endMBB); 10113 10114 // Load the offset value into a register 10115 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10116 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 10117 .addOperand(Base) 10118 .addOperand(Scale) 10119 .addOperand(Index) 10120 .addDisp(Disp, UseFPOffset ? 4 : 0) 10121 .addOperand(Segment) 10122 .setMemRefs(MMOBegin, MMOEnd); 10123 10124 // Check if there is enough room left to pull this argument. 10125 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 10126 .addReg(OffsetReg) 10127 .addImm(MaxOffset + 8 - ArgSizeA8); 10128 10129 // Branch to "overflowMBB" if offset >= max 10130 // Fall through to "offsetMBB" otherwise 10131 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 10132 .addMBB(overflowMBB); 10133 } 10134 10135 // In offsetMBB, emit code to use the reg_save_area. 10136 if (offsetMBB) { 10137 assert(OffsetReg != 0); 10138 10139 // Read the reg_save_area address. 10140 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 10141 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 10142 .addOperand(Base) 10143 .addOperand(Scale) 10144 .addOperand(Index) 10145 .addDisp(Disp, 16) 10146 .addOperand(Segment) 10147 .setMemRefs(MMOBegin, MMOEnd); 10148 10149 // Zero-extend the offset 10150 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 10151 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 10152 .addImm(0) 10153 .addReg(OffsetReg) 10154 .addImm(X86::sub_32bit); 10155 10156 // Add the offset to the reg_save_area to get the final address. 10157 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 10158 .addReg(OffsetReg64) 10159 .addReg(RegSaveReg); 10160 10161 // Compute the offset for the next argument 10162 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 10163 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 10164 .addReg(OffsetReg) 10165 .addImm(UseFPOffset ? 16 : 8); 10166 10167 // Store it back into the va_list. 10168 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 10169 .addOperand(Base) 10170 .addOperand(Scale) 10171 .addOperand(Index) 10172 .addDisp(Disp, UseFPOffset ? 4 : 0) 10173 .addOperand(Segment) 10174 .addReg(NextOffsetReg) 10175 .setMemRefs(MMOBegin, MMOEnd); 10176 10177 // Jump to endMBB 10178 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 10179 .addMBB(endMBB); 10180 } 10181 10182 // 10183 // Emit code to use overflow area 10184 // 10185 10186 // Load the overflow_area address into a register. 10187 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 10188 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 10189 .addOperand(Base) 10190 .addOperand(Scale) 10191 .addOperand(Index) 10192 .addDisp(Disp, 8) 10193 .addOperand(Segment) 10194 .setMemRefs(MMOBegin, MMOEnd); 10195 10196 // If we need to align it, do so. Otherwise, just copy the address 10197 // to OverflowDestReg. 10198 if (NeedsAlign) { 10199 // Align the overflow address 10200 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 10201 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 10202 10203 // aligned_addr = (addr + (align-1)) & ~(align-1) 10204 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 10205 .addReg(OverflowAddrReg) 10206 .addImm(Align-1); 10207 10208 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 10209 .addReg(TmpReg) 10210 .addImm(~(uint64_t)(Align-1)); 10211 } else { 10212 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 10213 .addReg(OverflowAddrReg); 10214 } 10215 10216 // Compute the next overflow address after this argument. 10217 // (the overflow address should be kept 8-byte aligned) 10218 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 10219 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 10220 .addReg(OverflowDestReg) 10221 .addImm(ArgSizeA8); 10222 10223 // Store the new overflow address. 10224 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 10225 .addOperand(Base) 10226 .addOperand(Scale) 10227 .addOperand(Index) 10228 .addDisp(Disp, 8) 10229 .addOperand(Segment) 10230 .addReg(NextAddrReg) 10231 .setMemRefs(MMOBegin, MMOEnd); 10232 10233 // If we branched, emit the PHI to the front of endMBB. 10234 if (offsetMBB) { 10235 BuildMI(*endMBB, endMBB->begin(), DL, 10236 TII->get(X86::PHI), DestReg) 10237 .addReg(OffsetDestReg).addMBB(offsetMBB) 10238 .addReg(OverflowDestReg).addMBB(overflowMBB); 10239 } 10240 10241 // Erase the pseudo instruction 10242 MI->eraseFromParent(); 10243 10244 return endMBB; 10245} 10246 10247MachineBasicBlock * 10248X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 10249 MachineInstr *MI, 10250 MachineBasicBlock *MBB) const { 10251 // Emit code to save XMM registers to the stack. The ABI says that the 10252 // number of registers to save is given in %al, so it's theoretically 10253 // possible to do an indirect jump trick to avoid saving all of them, 10254 // however this code takes a simpler approach and just executes all 10255 // of the stores if %al is non-zero. It's less code, and it's probably 10256 // easier on the hardware branch predictor, and stores aren't all that 10257 // expensive anyway. 10258 10259 // Create the new basic blocks. One block contains all the XMM stores, 10260 // and one block is the final destination regardless of whether any 10261 // stores were performed. 10262 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 10263 MachineFunction *F = MBB->getParent(); 10264 MachineFunction::iterator MBBIter = MBB; 10265 ++MBBIter; 10266 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 10267 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 10268 F->insert(MBBIter, XMMSaveMBB); 10269 F->insert(MBBIter, EndMBB); 10270 10271 // Transfer the remainder of MBB and its successor edges to EndMBB. 10272 EndMBB->splice(EndMBB->begin(), MBB, 10273 llvm::next(MachineBasicBlock::iterator(MI)), 10274 MBB->end()); 10275 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 10276 10277 // The original block will now fall through to the XMM save block. 10278 MBB->addSuccessor(XMMSaveMBB); 10279 // The XMMSaveMBB will fall through to the end block. 10280 XMMSaveMBB->addSuccessor(EndMBB); 10281 10282 // Now add the instructions. 10283 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10284 DebugLoc DL = MI->getDebugLoc(); 10285 10286 unsigned CountReg = MI->getOperand(0).getReg(); 10287 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 10288 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 10289 10290 if (!Subtarget->isTargetWin64()) { 10291 // If %al is 0, branch around the XMM save block. 10292 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 10293 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 10294 MBB->addSuccessor(EndMBB); 10295 } 10296 10297 // In the XMM save block, save all the XMM argument registers. 10298 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 10299 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 10300 MachineMemOperand *MMO = 10301 F->getMachineMemOperand( 10302 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 10303 MachineMemOperand::MOStore, 10304 /*Size=*/16, /*Align=*/16); 10305 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr)) 10306 .addFrameIndex(RegSaveFrameIndex) 10307 .addImm(/*Scale=*/1) 10308 .addReg(/*IndexReg=*/0) 10309 .addImm(/*Disp=*/Offset) 10310 .addReg(/*Segment=*/0) 10311 .addReg(MI->getOperand(i).getReg()) 10312 .addMemOperand(MMO); 10313 } 10314 10315 MI->eraseFromParent(); // The pseudo instruction is gone now. 10316 10317 return EndMBB; 10318} 10319 10320MachineBasicBlock * 10321X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 10322 MachineBasicBlock *BB) const { 10323 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10324 DebugLoc DL = MI->getDebugLoc(); 10325 10326 // To "insert" a SELECT_CC instruction, we actually have to insert the 10327 // diamond control-flow pattern. The incoming instruction knows the 10328 // destination vreg to set, the condition code register to branch on, the 10329 // true/false values to select between, and a branch opcode to use. 10330 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10331 MachineFunction::iterator It = BB; 10332 ++It; 10333 10334 // thisMBB: 10335 // ... 10336 // TrueVal = ... 10337 // cmpTY ccX, r1, r2 10338 // bCC copy1MBB 10339 // fallthrough --> copy0MBB 10340 MachineBasicBlock *thisMBB = BB; 10341 MachineFunction *F = BB->getParent(); 10342 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10343 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10344 F->insert(It, copy0MBB); 10345 F->insert(It, sinkMBB); 10346 10347 // If the EFLAGS register isn't dead in the terminator, then claim that it's 10348 // live into the sink and copy blocks. 10349 const MachineFunction *MF = BB->getParent(); 10350 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo(); 10351 BitVector ReservedRegs = TRI->getReservedRegs(*MF); 10352 10353 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { 10354 const MachineOperand &MO = MI->getOperand(I); 10355 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue; 10356 unsigned Reg = MO.getReg(); 10357 if (Reg != X86::EFLAGS) continue; 10358 copy0MBB->addLiveIn(Reg); 10359 sinkMBB->addLiveIn(Reg); 10360 } 10361 10362 // Transfer the remainder of BB and its successor edges to sinkMBB. 10363 sinkMBB->splice(sinkMBB->begin(), BB, 10364 llvm::next(MachineBasicBlock::iterator(MI)), 10365 BB->end()); 10366 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10367 10368 // Add the true and fallthrough blocks as its successors. 10369 BB->addSuccessor(copy0MBB); 10370 BB->addSuccessor(sinkMBB); 10371 10372 // Create the conditional branch instruction. 10373 unsigned Opc = 10374 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 10375 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 10376 10377 // copy0MBB: 10378 // %FalseValue = ... 10379 // # fallthrough to sinkMBB 10380 copy0MBB->addSuccessor(sinkMBB); 10381 10382 // sinkMBB: 10383 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10384 // ... 10385 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10386 TII->get(X86::PHI), MI->getOperand(0).getReg()) 10387 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 10388 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 10389 10390 MI->eraseFromParent(); // The pseudo instruction is gone now. 10391 return sinkMBB; 10392} 10393 10394MachineBasicBlock * 10395X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 10396 MachineBasicBlock *BB) const { 10397 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10398 DebugLoc DL = MI->getDebugLoc(); 10399 10400 // The lowering is pretty easy: we're just emitting the call to _alloca. The 10401 // non-trivial part is impdef of ESP. 10402 // FIXME: The code should be tweaked as soon as we'll try to do codegen for 10403 // mingw-w64. 10404 10405 const char *StackProbeSymbol = 10406 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 10407 10408 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 10409 .addExternalSymbol(StackProbeSymbol) 10410 .addReg(X86::EAX, RegState::Implicit) 10411 .addReg(X86::ESP, RegState::Implicit) 10412 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 10413 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 10414 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 10415 10416 MI->eraseFromParent(); // The pseudo instruction is gone now. 10417 return BB; 10418} 10419 10420MachineBasicBlock * 10421X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 10422 MachineBasicBlock *BB) const { 10423 // This is pretty easy. We're taking the value that we received from 10424 // our load from the relocation, sticking it in either RDI (x86-64) 10425 // or EAX and doing an indirect call. The return value will then 10426 // be in the normal return register. 10427 const X86InstrInfo *TII 10428 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 10429 DebugLoc DL = MI->getDebugLoc(); 10430 MachineFunction *F = BB->getParent(); 10431 10432 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 10433 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 10434 10435 if (Subtarget->is64Bit()) { 10436 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10437 TII->get(X86::MOV64rm), X86::RDI) 10438 .addReg(X86::RIP) 10439 .addImm(0).addReg(0) 10440 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10441 MI->getOperand(3).getTargetFlags()) 10442 .addReg(0); 10443 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 10444 addDirectMem(MIB, X86::RDI); 10445 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 10446 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10447 TII->get(X86::MOV32rm), X86::EAX) 10448 .addReg(0) 10449 .addImm(0).addReg(0) 10450 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10451 MI->getOperand(3).getTargetFlags()) 10452 .addReg(0); 10453 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10454 addDirectMem(MIB, X86::EAX); 10455 } else { 10456 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 10457 TII->get(X86::MOV32rm), X86::EAX) 10458 .addReg(TII->getGlobalBaseReg(F)) 10459 .addImm(0).addReg(0) 10460 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 10461 MI->getOperand(3).getTargetFlags()) 10462 .addReg(0); 10463 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 10464 addDirectMem(MIB, X86::EAX); 10465 } 10466 10467 MI->eraseFromParent(); // The pseudo instruction is gone now. 10468 return BB; 10469} 10470 10471MachineBasicBlock * 10472X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 10473 MachineBasicBlock *BB) const { 10474 switch (MI->getOpcode()) { 10475 default: assert(false && "Unexpected instr type to insert"); 10476 case X86::TAILJMPd64: 10477 case X86::TAILJMPr64: 10478 case X86::TAILJMPm64: 10479 assert(!"TAILJMP64 would not be touched here."); 10480 case X86::TCRETURNdi64: 10481 case X86::TCRETURNri64: 10482 case X86::TCRETURNmi64: 10483 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 10484 // On AMD64, additional defs should be added before register allocation. 10485 if (!Subtarget->isTargetWin64()) { 10486 MI->addRegisterDefined(X86::RSI); 10487 MI->addRegisterDefined(X86::RDI); 10488 MI->addRegisterDefined(X86::XMM6); 10489 MI->addRegisterDefined(X86::XMM7); 10490 MI->addRegisterDefined(X86::XMM8); 10491 MI->addRegisterDefined(X86::XMM9); 10492 MI->addRegisterDefined(X86::XMM10); 10493 MI->addRegisterDefined(X86::XMM11); 10494 MI->addRegisterDefined(X86::XMM12); 10495 MI->addRegisterDefined(X86::XMM13); 10496 MI->addRegisterDefined(X86::XMM14); 10497 MI->addRegisterDefined(X86::XMM15); 10498 } 10499 return BB; 10500 case X86::WIN_ALLOCA: 10501 return EmitLoweredWinAlloca(MI, BB); 10502 case X86::TLSCall_32: 10503 case X86::TLSCall_64: 10504 return EmitLoweredTLSCall(MI, BB); 10505 case X86::CMOV_GR8: 10506 case X86::CMOV_FR32: 10507 case X86::CMOV_FR64: 10508 case X86::CMOV_V4F32: 10509 case X86::CMOV_V2F64: 10510 case X86::CMOV_V2I64: 10511 case X86::CMOV_GR16: 10512 case X86::CMOV_GR32: 10513 case X86::CMOV_RFP32: 10514 case X86::CMOV_RFP64: 10515 case X86::CMOV_RFP80: 10516 return EmitLoweredSelect(MI, BB); 10517 10518 case X86::FP32_TO_INT16_IN_MEM: 10519 case X86::FP32_TO_INT32_IN_MEM: 10520 case X86::FP32_TO_INT64_IN_MEM: 10521 case X86::FP64_TO_INT16_IN_MEM: 10522 case X86::FP64_TO_INT32_IN_MEM: 10523 case X86::FP64_TO_INT64_IN_MEM: 10524 case X86::FP80_TO_INT16_IN_MEM: 10525 case X86::FP80_TO_INT32_IN_MEM: 10526 case X86::FP80_TO_INT64_IN_MEM: { 10527 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 10528 DebugLoc DL = MI->getDebugLoc(); 10529 10530 // Change the floating point control register to use "round towards zero" 10531 // mode when truncating to an integer value. 10532 MachineFunction *F = BB->getParent(); 10533 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 10534 addFrameReference(BuildMI(*BB, MI, DL, 10535 TII->get(X86::FNSTCW16m)), CWFrameIdx); 10536 10537 // Load the old value of the high byte of the control word... 10538 unsigned OldCW = 10539 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 10540 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 10541 CWFrameIdx); 10542 10543 // Set the high part to be round to zero... 10544 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 10545 .addImm(0xC7F); 10546 10547 // Reload the modified control word now... 10548 addFrameReference(BuildMI(*BB, MI, DL, 10549 TII->get(X86::FLDCW16m)), CWFrameIdx); 10550 10551 // Restore the memory image of control word to original value 10552 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 10553 .addReg(OldCW); 10554 10555 // Get the X86 opcode to use. 10556 unsigned Opc; 10557 switch (MI->getOpcode()) { 10558 default: llvm_unreachable("illegal opcode!"); 10559 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 10560 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 10561 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 10562 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 10563 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 10564 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 10565 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 10566 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 10567 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 10568 } 10569 10570 X86AddressMode AM; 10571 MachineOperand &Op = MI->getOperand(0); 10572 if (Op.isReg()) { 10573 AM.BaseType = X86AddressMode::RegBase; 10574 AM.Base.Reg = Op.getReg(); 10575 } else { 10576 AM.BaseType = X86AddressMode::FrameIndexBase; 10577 AM.Base.FrameIndex = Op.getIndex(); 10578 } 10579 Op = MI->getOperand(1); 10580 if (Op.isImm()) 10581 AM.Scale = Op.getImm(); 10582 Op = MI->getOperand(2); 10583 if (Op.isImm()) 10584 AM.IndexReg = Op.getImm(); 10585 Op = MI->getOperand(3); 10586 if (Op.isGlobal()) { 10587 AM.GV = Op.getGlobal(); 10588 } else { 10589 AM.Disp = Op.getImm(); 10590 } 10591 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 10592 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 10593 10594 // Reload the original control word now. 10595 addFrameReference(BuildMI(*BB, MI, DL, 10596 TII->get(X86::FLDCW16m)), CWFrameIdx); 10597 10598 MI->eraseFromParent(); // The pseudo instruction is gone now. 10599 return BB; 10600 } 10601 // String/text processing lowering. 10602 case X86::PCMPISTRM128REG: 10603 case X86::VPCMPISTRM128REG: 10604 return EmitPCMP(MI, BB, 3, false /* in-mem */); 10605 case X86::PCMPISTRM128MEM: 10606 case X86::VPCMPISTRM128MEM: 10607 return EmitPCMP(MI, BB, 3, true /* in-mem */); 10608 case X86::PCMPESTRM128REG: 10609 case X86::VPCMPESTRM128REG: 10610 return EmitPCMP(MI, BB, 5, false /* in mem */); 10611 case X86::PCMPESTRM128MEM: 10612 case X86::VPCMPESTRM128MEM: 10613 return EmitPCMP(MI, BB, 5, true /* in mem */); 10614 10615 // Thread synchronization. 10616 case X86::MONITOR: 10617 return EmitMonitor(MI, BB); 10618 case X86::MWAIT: 10619 return EmitMwait(MI, BB); 10620 10621 // Atomic Lowering. 10622 case X86::ATOMAND32: 10623 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10624 X86::AND32ri, X86::MOV32rm, 10625 X86::LCMPXCHG32, 10626 X86::NOT32r, X86::EAX, 10627 X86::GR32RegisterClass); 10628 case X86::ATOMOR32: 10629 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 10630 X86::OR32ri, X86::MOV32rm, 10631 X86::LCMPXCHG32, 10632 X86::NOT32r, X86::EAX, 10633 X86::GR32RegisterClass); 10634 case X86::ATOMXOR32: 10635 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 10636 X86::XOR32ri, X86::MOV32rm, 10637 X86::LCMPXCHG32, 10638 X86::NOT32r, X86::EAX, 10639 X86::GR32RegisterClass); 10640 case X86::ATOMNAND32: 10641 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 10642 X86::AND32ri, X86::MOV32rm, 10643 X86::LCMPXCHG32, 10644 X86::NOT32r, X86::EAX, 10645 X86::GR32RegisterClass, true); 10646 case X86::ATOMMIN32: 10647 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 10648 case X86::ATOMMAX32: 10649 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 10650 case X86::ATOMUMIN32: 10651 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 10652 case X86::ATOMUMAX32: 10653 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 10654 10655 case X86::ATOMAND16: 10656 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10657 X86::AND16ri, X86::MOV16rm, 10658 X86::LCMPXCHG16, 10659 X86::NOT16r, X86::AX, 10660 X86::GR16RegisterClass); 10661 case X86::ATOMOR16: 10662 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 10663 X86::OR16ri, X86::MOV16rm, 10664 X86::LCMPXCHG16, 10665 X86::NOT16r, X86::AX, 10666 X86::GR16RegisterClass); 10667 case X86::ATOMXOR16: 10668 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 10669 X86::XOR16ri, X86::MOV16rm, 10670 X86::LCMPXCHG16, 10671 X86::NOT16r, X86::AX, 10672 X86::GR16RegisterClass); 10673 case X86::ATOMNAND16: 10674 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 10675 X86::AND16ri, X86::MOV16rm, 10676 X86::LCMPXCHG16, 10677 X86::NOT16r, X86::AX, 10678 X86::GR16RegisterClass, true); 10679 case X86::ATOMMIN16: 10680 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 10681 case X86::ATOMMAX16: 10682 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 10683 case X86::ATOMUMIN16: 10684 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 10685 case X86::ATOMUMAX16: 10686 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 10687 10688 case X86::ATOMAND8: 10689 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10690 X86::AND8ri, X86::MOV8rm, 10691 X86::LCMPXCHG8, 10692 X86::NOT8r, X86::AL, 10693 X86::GR8RegisterClass); 10694 case X86::ATOMOR8: 10695 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 10696 X86::OR8ri, X86::MOV8rm, 10697 X86::LCMPXCHG8, 10698 X86::NOT8r, X86::AL, 10699 X86::GR8RegisterClass); 10700 case X86::ATOMXOR8: 10701 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 10702 X86::XOR8ri, X86::MOV8rm, 10703 X86::LCMPXCHG8, 10704 X86::NOT8r, X86::AL, 10705 X86::GR8RegisterClass); 10706 case X86::ATOMNAND8: 10707 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 10708 X86::AND8ri, X86::MOV8rm, 10709 X86::LCMPXCHG8, 10710 X86::NOT8r, X86::AL, 10711 X86::GR8RegisterClass, true); 10712 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 10713 // This group is for 64-bit host. 10714 case X86::ATOMAND64: 10715 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10716 X86::AND64ri32, X86::MOV64rm, 10717 X86::LCMPXCHG64, 10718 X86::NOT64r, X86::RAX, 10719 X86::GR64RegisterClass); 10720 case X86::ATOMOR64: 10721 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 10722 X86::OR64ri32, X86::MOV64rm, 10723 X86::LCMPXCHG64, 10724 X86::NOT64r, X86::RAX, 10725 X86::GR64RegisterClass); 10726 case X86::ATOMXOR64: 10727 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 10728 X86::XOR64ri32, X86::MOV64rm, 10729 X86::LCMPXCHG64, 10730 X86::NOT64r, X86::RAX, 10731 X86::GR64RegisterClass); 10732 case X86::ATOMNAND64: 10733 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 10734 X86::AND64ri32, X86::MOV64rm, 10735 X86::LCMPXCHG64, 10736 X86::NOT64r, X86::RAX, 10737 X86::GR64RegisterClass, true); 10738 case X86::ATOMMIN64: 10739 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 10740 case X86::ATOMMAX64: 10741 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 10742 case X86::ATOMUMIN64: 10743 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 10744 case X86::ATOMUMAX64: 10745 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 10746 10747 // This group does 64-bit operations on a 32-bit host. 10748 case X86::ATOMAND6432: 10749 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10750 X86::AND32rr, X86::AND32rr, 10751 X86::AND32ri, X86::AND32ri, 10752 false); 10753 case X86::ATOMOR6432: 10754 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10755 X86::OR32rr, X86::OR32rr, 10756 X86::OR32ri, X86::OR32ri, 10757 false); 10758 case X86::ATOMXOR6432: 10759 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10760 X86::XOR32rr, X86::XOR32rr, 10761 X86::XOR32ri, X86::XOR32ri, 10762 false); 10763 case X86::ATOMNAND6432: 10764 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10765 X86::AND32rr, X86::AND32rr, 10766 X86::AND32ri, X86::AND32ri, 10767 true); 10768 case X86::ATOMADD6432: 10769 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10770 X86::ADD32rr, X86::ADC32rr, 10771 X86::ADD32ri, X86::ADC32ri, 10772 false); 10773 case X86::ATOMSUB6432: 10774 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10775 X86::SUB32rr, X86::SBB32rr, 10776 X86::SUB32ri, X86::SBB32ri, 10777 false); 10778 case X86::ATOMSWAP6432: 10779 return EmitAtomicBit6432WithCustomInserter(MI, BB, 10780 X86::MOV32rr, X86::MOV32rr, 10781 X86::MOV32ri, X86::MOV32ri, 10782 false); 10783 case X86::VASTART_SAVE_XMM_REGS: 10784 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 10785 10786 case X86::VAARG_64: 10787 return EmitVAARG64WithCustomInserter(MI, BB); 10788 } 10789} 10790 10791//===----------------------------------------------------------------------===// 10792// X86 Optimization Hooks 10793//===----------------------------------------------------------------------===// 10794 10795void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 10796 const APInt &Mask, 10797 APInt &KnownZero, 10798 APInt &KnownOne, 10799 const SelectionDAG &DAG, 10800 unsigned Depth) const { 10801 unsigned Opc = Op.getOpcode(); 10802 assert((Opc >= ISD::BUILTIN_OP_END || 10803 Opc == ISD::INTRINSIC_WO_CHAIN || 10804 Opc == ISD::INTRINSIC_W_CHAIN || 10805 Opc == ISD::INTRINSIC_VOID) && 10806 "Should use MaskedValueIsZero if you don't know whether Op" 10807 " is a target node!"); 10808 10809 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 10810 switch (Opc) { 10811 default: break; 10812 case X86ISD::ADD: 10813 case X86ISD::SUB: 10814 case X86ISD::ADC: 10815 case X86ISD::SBB: 10816 case X86ISD::SMUL: 10817 case X86ISD::UMUL: 10818 case X86ISD::INC: 10819 case X86ISD::DEC: 10820 case X86ISD::OR: 10821 case X86ISD::XOR: 10822 case X86ISD::AND: 10823 // These nodes' second result is a boolean. 10824 if (Op.getResNo() == 0) 10825 break; 10826 // Fallthrough 10827 case X86ISD::SETCC: 10828 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 10829 Mask.getBitWidth() - 1); 10830 break; 10831 } 10832} 10833 10834unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 10835 unsigned Depth) const { 10836 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 10837 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 10838 return Op.getValueType().getScalarType().getSizeInBits(); 10839 10840 // Fallback case. 10841 return 1; 10842} 10843 10844/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 10845/// node is a GlobalAddress + offset. 10846bool X86TargetLowering::isGAPlusOffset(SDNode *N, 10847 const GlobalValue* &GA, 10848 int64_t &Offset) const { 10849 if (N->getOpcode() == X86ISD::Wrapper) { 10850 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 10851 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 10852 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 10853 return true; 10854 } 10855 } 10856 return TargetLowering::isGAPlusOffset(N, GA, Offset); 10857} 10858 10859/// PerformShuffleCombine - Combine a vector_shuffle that is equal to 10860/// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load 10861/// if the load addresses are consecutive, non-overlapping, and in the right 10862/// order. 10863static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 10864 TargetLowering::DAGCombinerInfo &DCI) { 10865 DebugLoc dl = N->getDebugLoc(); 10866 EVT VT = N->getValueType(0); 10867 10868 if (VT.getSizeInBits() != 128) 10869 return SDValue(); 10870 10871 // Don't create instructions with illegal types after legalize types has run. 10872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10873 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 10874 return SDValue(); 10875 10876 SmallVector<SDValue, 16> Elts; 10877 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 10878 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 10879 10880 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 10881} 10882 10883/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 10884/// generation and convert it from being a bunch of shuffles and extracts 10885/// to a simple store and scalar loads to extract the elements. 10886static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 10887 const TargetLowering &TLI) { 10888 SDValue InputVector = N->getOperand(0); 10889 10890 // Only operate on vectors of 4 elements, where the alternative shuffling 10891 // gets to be more expensive. 10892 if (InputVector.getValueType() != MVT::v4i32) 10893 return SDValue(); 10894 10895 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 10896 // single use which is a sign-extend or zero-extend, and all elements are 10897 // used. 10898 SmallVector<SDNode *, 4> Uses; 10899 unsigned ExtractedElements = 0; 10900 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 10901 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 10902 if (UI.getUse().getResNo() != InputVector.getResNo()) 10903 return SDValue(); 10904 10905 SDNode *Extract = *UI; 10906 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10907 return SDValue(); 10908 10909 if (Extract->getValueType(0) != MVT::i32) 10910 return SDValue(); 10911 if (!Extract->hasOneUse()) 10912 return SDValue(); 10913 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 10914 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 10915 return SDValue(); 10916 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 10917 return SDValue(); 10918 10919 // Record which element was extracted. 10920 ExtractedElements |= 10921 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 10922 10923 Uses.push_back(Extract); 10924 } 10925 10926 // If not all the elements were used, this may not be worthwhile. 10927 if (ExtractedElements != 15) 10928 return SDValue(); 10929 10930 // Ok, we've now decided to do the transformation. 10931 DebugLoc dl = InputVector.getDebugLoc(); 10932 10933 // Store the value to a temporary stack slot. 10934 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 10935 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 10936 MachinePointerInfo(), false, false, 0); 10937 10938 // Replace each use (extract) with a load of the appropriate element. 10939 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 10940 UE = Uses.end(); UI != UE; ++UI) { 10941 SDNode *Extract = *UI; 10942 10943 // Compute the element's address. 10944 SDValue Idx = Extract->getOperand(1); 10945 unsigned EltSize = 10946 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 10947 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 10948 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 10949 10950 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), 10951 StackPtr, OffsetVal); 10952 10953 // Load the scalar. 10954 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 10955 ScalarAddr, MachinePointerInfo(), 10956 false, false, 0); 10957 10958 // Replace the exact with the load. 10959 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 10960 } 10961 10962 // The replacement was made in place; don't return anything. 10963 return SDValue(); 10964} 10965 10966/// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes. 10967static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 10968 const X86Subtarget *Subtarget) { 10969 DebugLoc DL = N->getDebugLoc(); 10970 SDValue Cond = N->getOperand(0); 10971 // Get the LHS/RHS of the select. 10972 SDValue LHS = N->getOperand(1); 10973 SDValue RHS = N->getOperand(2); 10974 10975 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 10976 // instructions match the semantics of the common C idiom x<y?x:y but not 10977 // x<=y?x:y, because of how they handle negative zero (which can be 10978 // ignored in unsafe-math mode). 10979 if (Subtarget->hasSSE2() && 10980 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) && 10981 Cond.getOpcode() == ISD::SETCC) { 10982 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 10983 10984 unsigned Opcode = 0; 10985 // Check for x CC y ? x : y. 10986 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 10987 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 10988 switch (CC) { 10989 default: break; 10990 case ISD::SETULT: 10991 // Converting this to a min would handle NaNs incorrectly, and swapping 10992 // the operands would cause it to handle comparisons between positive 10993 // and negative zero incorrectly. 10994 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 10995 if (!UnsafeFPMath && 10996 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 10997 break; 10998 std::swap(LHS, RHS); 10999 } 11000 Opcode = X86ISD::FMIN; 11001 break; 11002 case ISD::SETOLE: 11003 // Converting this to a min would handle comparisons between positive 11004 // and negative zero incorrectly. 11005 if (!UnsafeFPMath && 11006 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 11007 break; 11008 Opcode = X86ISD::FMIN; 11009 break; 11010 case ISD::SETULE: 11011 // Converting this to a min would handle both negative zeros and NaNs 11012 // incorrectly, but we can swap the operands to fix both. 11013 std::swap(LHS, RHS); 11014 case ISD::SETOLT: 11015 case ISD::SETLT: 11016 case ISD::SETLE: 11017 Opcode = X86ISD::FMIN; 11018 break; 11019 11020 case ISD::SETOGE: 11021 // Converting this to a max would handle comparisons between positive 11022 // and negative zero incorrectly. 11023 if (!UnsafeFPMath && 11024 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS)) 11025 break; 11026 Opcode = X86ISD::FMAX; 11027 break; 11028 case ISD::SETUGT: 11029 // Converting this to a max would handle NaNs incorrectly, and swapping 11030 // the operands would cause it to handle comparisons between positive 11031 // and negative zero incorrectly. 11032 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 11033 if (!UnsafeFPMath && 11034 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 11035 break; 11036 std::swap(LHS, RHS); 11037 } 11038 Opcode = X86ISD::FMAX; 11039 break; 11040 case ISD::SETUGE: 11041 // Converting this to a max would handle both negative zeros and NaNs 11042 // incorrectly, but we can swap the operands to fix both. 11043 std::swap(LHS, RHS); 11044 case ISD::SETOGT: 11045 case ISD::SETGT: 11046 case ISD::SETGE: 11047 Opcode = X86ISD::FMAX; 11048 break; 11049 } 11050 // Check for x CC y ? y : x -- a min/max with reversed arms. 11051 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 11052 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 11053 switch (CC) { 11054 default: break; 11055 case ISD::SETOGE: 11056 // Converting this to a min would handle comparisons between positive 11057 // and negative zero incorrectly, and swapping the operands would 11058 // cause it to handle NaNs incorrectly. 11059 if (!UnsafeFPMath && 11060 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 11061 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11062 break; 11063 std::swap(LHS, RHS); 11064 } 11065 Opcode = X86ISD::FMIN; 11066 break; 11067 case ISD::SETUGT: 11068 // Converting this to a min would handle NaNs incorrectly. 11069 if (!UnsafeFPMath && 11070 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 11071 break; 11072 Opcode = X86ISD::FMIN; 11073 break; 11074 case ISD::SETUGE: 11075 // Converting this to a min would handle both negative zeros and NaNs 11076 // incorrectly, but we can swap the operands to fix both. 11077 std::swap(LHS, RHS); 11078 case ISD::SETOGT: 11079 case ISD::SETGT: 11080 case ISD::SETGE: 11081 Opcode = X86ISD::FMIN; 11082 break; 11083 11084 case ISD::SETULT: 11085 // Converting this to a max would handle NaNs incorrectly. 11086 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11087 break; 11088 Opcode = X86ISD::FMAX; 11089 break; 11090 case ISD::SETOLE: 11091 // Converting this to a max would handle comparisons between positive 11092 // and negative zero incorrectly, and swapping the operands would 11093 // cause it to handle NaNs incorrectly. 11094 if (!UnsafeFPMath && 11095 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 11096 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 11097 break; 11098 std::swap(LHS, RHS); 11099 } 11100 Opcode = X86ISD::FMAX; 11101 break; 11102 case ISD::SETULE: 11103 // Converting this to a max would handle both negative zeros and NaNs 11104 // incorrectly, but we can swap the operands to fix both. 11105 std::swap(LHS, RHS); 11106 case ISD::SETOLT: 11107 case ISD::SETLT: 11108 case ISD::SETLE: 11109 Opcode = X86ISD::FMAX; 11110 break; 11111 } 11112 } 11113 11114 if (Opcode) 11115 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 11116 } 11117 11118 // If this is a select between two integer constants, try to do some 11119 // optimizations. 11120 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 11121 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 11122 // Don't do this for crazy integer types. 11123 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 11124 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 11125 // so that TrueC (the true value) is larger than FalseC. 11126 bool NeedsCondInvert = false; 11127 11128 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 11129 // Efficiently invertible. 11130 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 11131 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 11132 isa<ConstantSDNode>(Cond.getOperand(1))))) { 11133 NeedsCondInvert = true; 11134 std::swap(TrueC, FalseC); 11135 } 11136 11137 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 11138 if (FalseC->getAPIntValue() == 0 && 11139 TrueC->getAPIntValue().isPowerOf2()) { 11140 if (NeedsCondInvert) // Invert the condition if needed. 11141 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11142 DAG.getConstant(1, Cond.getValueType())); 11143 11144 // Zero extend the condition if needed. 11145 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 11146 11147 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11148 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 11149 DAG.getConstant(ShAmt, MVT::i8)); 11150 } 11151 11152 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 11153 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11154 if (NeedsCondInvert) // Invert the condition if needed. 11155 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11156 DAG.getConstant(1, Cond.getValueType())); 11157 11158 // Zero extend the condition if needed. 11159 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11160 FalseC->getValueType(0), Cond); 11161 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11162 SDValue(FalseC, 0)); 11163 } 11164 11165 // Optimize cases that will turn into an LEA instruction. This requires 11166 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11167 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11168 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11169 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11170 11171 bool isFastMultiplier = false; 11172 if (Diff < 10) { 11173 switch ((unsigned char)Diff) { 11174 default: break; 11175 case 1: // result = add base, cond 11176 case 2: // result = lea base( , cond*2) 11177 case 3: // result = lea base(cond, cond*2) 11178 case 4: // result = lea base( , cond*4) 11179 case 5: // result = lea base(cond, cond*4) 11180 case 8: // result = lea base( , cond*8) 11181 case 9: // result = lea base(cond, cond*8) 11182 isFastMultiplier = true; 11183 break; 11184 } 11185 } 11186 11187 if (isFastMultiplier) { 11188 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11189 if (NeedsCondInvert) // Invert the condition if needed. 11190 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 11191 DAG.getConstant(1, Cond.getValueType())); 11192 11193 // Zero extend the condition if needed. 11194 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11195 Cond); 11196 // Scale the condition by the difference. 11197 if (Diff != 1) 11198 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11199 DAG.getConstant(Diff, Cond.getValueType())); 11200 11201 // Add the base if non-zero. 11202 if (FalseC->getAPIntValue() != 0) 11203 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11204 SDValue(FalseC, 0)); 11205 return Cond; 11206 } 11207 } 11208 } 11209 } 11210 11211 return SDValue(); 11212} 11213 11214/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 11215static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 11216 TargetLowering::DAGCombinerInfo &DCI) { 11217 DebugLoc DL = N->getDebugLoc(); 11218 11219 // If the flag operand isn't dead, don't touch this CMOV. 11220 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 11221 return SDValue(); 11222 11223 // If this is a select between two integer constants, try to do some 11224 // optimizations. Note that the operands are ordered the opposite of SELECT 11225 // operands. 11226 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 11227 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11228 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 11229 // larger than FalseC (the false value). 11230 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 11231 11232 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 11233 CC = X86::GetOppositeBranchCondition(CC); 11234 std::swap(TrueC, FalseC); 11235 } 11236 11237 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 11238 // This is efficient for any integer data type (including i8/i16) and 11239 // shift amount. 11240 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 11241 SDValue Cond = N->getOperand(3); 11242 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11243 DAG.getConstant(CC, MVT::i8), Cond); 11244 11245 // Zero extend the condition if needed. 11246 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 11247 11248 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 11249 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 11250 DAG.getConstant(ShAmt, MVT::i8)); 11251 if (N->getNumValues() == 2) // Dead flag value? 11252 return DCI.CombineTo(N, Cond, SDValue()); 11253 return Cond; 11254 } 11255 11256 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 11257 // for any integer data type, including i8/i16. 11258 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 11259 SDValue Cond = N->getOperand(3); 11260 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11261 DAG.getConstant(CC, MVT::i8), Cond); 11262 11263 // Zero extend the condition if needed. 11264 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 11265 FalseC->getValueType(0), Cond); 11266 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11267 SDValue(FalseC, 0)); 11268 11269 if (N->getNumValues() == 2) // Dead flag value? 11270 return DCI.CombineTo(N, Cond, SDValue()); 11271 return Cond; 11272 } 11273 11274 // Optimize cases that will turn into an LEA instruction. This requires 11275 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 11276 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 11277 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 11278 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 11279 11280 bool isFastMultiplier = false; 11281 if (Diff < 10) { 11282 switch ((unsigned char)Diff) { 11283 default: break; 11284 case 1: // result = add base, cond 11285 case 2: // result = lea base( , cond*2) 11286 case 3: // result = lea base(cond, cond*2) 11287 case 4: // result = lea base( , cond*4) 11288 case 5: // result = lea base(cond, cond*4) 11289 case 8: // result = lea base( , cond*8) 11290 case 9: // result = lea base(cond, cond*8) 11291 isFastMultiplier = true; 11292 break; 11293 } 11294 } 11295 11296 if (isFastMultiplier) { 11297 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 11298 SDValue Cond = N->getOperand(3); 11299 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11300 DAG.getConstant(CC, MVT::i8), Cond); 11301 // Zero extend the condition if needed. 11302 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 11303 Cond); 11304 // Scale the condition by the difference. 11305 if (Diff != 1) 11306 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 11307 DAG.getConstant(Diff, Cond.getValueType())); 11308 11309 // Add the base if non-zero. 11310 if (FalseC->getAPIntValue() != 0) 11311 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 11312 SDValue(FalseC, 0)); 11313 if (N->getNumValues() == 2) // Dead flag value? 11314 return DCI.CombineTo(N, Cond, SDValue()); 11315 return Cond; 11316 } 11317 } 11318 } 11319 } 11320 return SDValue(); 11321} 11322 11323 11324/// PerformMulCombine - Optimize a single multiply with constant into two 11325/// in order to implement it with two cheaper instructions, e.g. 11326/// LEA + SHL, LEA + LEA. 11327static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 11328 TargetLowering::DAGCombinerInfo &DCI) { 11329 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11330 return SDValue(); 11331 11332 EVT VT = N->getValueType(0); 11333 if (VT != MVT::i64) 11334 return SDValue(); 11335 11336 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11337 if (!C) 11338 return SDValue(); 11339 uint64_t MulAmt = C->getZExtValue(); 11340 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 11341 return SDValue(); 11342 11343 uint64_t MulAmt1 = 0; 11344 uint64_t MulAmt2 = 0; 11345 if ((MulAmt % 9) == 0) { 11346 MulAmt1 = 9; 11347 MulAmt2 = MulAmt / 9; 11348 } else if ((MulAmt % 5) == 0) { 11349 MulAmt1 = 5; 11350 MulAmt2 = MulAmt / 5; 11351 } else if ((MulAmt % 3) == 0) { 11352 MulAmt1 = 3; 11353 MulAmt2 = MulAmt / 3; 11354 } 11355 if (MulAmt2 && 11356 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 11357 DebugLoc DL = N->getDebugLoc(); 11358 11359 if (isPowerOf2_64(MulAmt2) && 11360 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 11361 // If second multiplifer is pow2, issue it first. We want the multiply by 11362 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 11363 // is an add. 11364 std::swap(MulAmt1, MulAmt2); 11365 11366 SDValue NewMul; 11367 if (isPowerOf2_64(MulAmt1)) 11368 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 11369 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 11370 else 11371 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 11372 DAG.getConstant(MulAmt1, VT)); 11373 11374 if (isPowerOf2_64(MulAmt2)) 11375 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 11376 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 11377 else 11378 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 11379 DAG.getConstant(MulAmt2, VT)); 11380 11381 // Do not add new nodes to DAG combiner worklist. 11382 DCI.CombineTo(N, NewMul, false); 11383 } 11384 return SDValue(); 11385} 11386 11387static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 11388 SDValue N0 = N->getOperand(0); 11389 SDValue N1 = N->getOperand(1); 11390 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 11391 EVT VT = N0.getValueType(); 11392 11393 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 11394 // since the result of setcc_c is all zero's or all ones. 11395 if (N1C && N0.getOpcode() == ISD::AND && 11396 N0.getOperand(1).getOpcode() == ISD::Constant) { 11397 SDValue N00 = N0.getOperand(0); 11398 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 11399 ((N00.getOpcode() == ISD::ANY_EXTEND || 11400 N00.getOpcode() == ISD::ZERO_EXTEND) && 11401 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 11402 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 11403 APInt ShAmt = N1C->getAPIntValue(); 11404 Mask = Mask.shl(ShAmt); 11405 if (Mask != 0) 11406 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 11407 N00, DAG.getConstant(Mask, VT)); 11408 } 11409 } 11410 11411 return SDValue(); 11412} 11413 11414/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 11415/// when possible. 11416static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 11417 const X86Subtarget *Subtarget) { 11418 EVT VT = N->getValueType(0); 11419 if (!VT.isVector() && VT.isInteger() && 11420 N->getOpcode() == ISD::SHL) 11421 return PerformSHLCombine(N, DAG); 11422 11423 // On X86 with SSE2 support, we can transform this to a vector shift if 11424 // all elements are shifted by the same amount. We can't do this in legalize 11425 // because the a constant vector is typically transformed to a constant pool 11426 // so we have no knowledge of the shift amount. 11427 if (!Subtarget->hasSSE2()) 11428 return SDValue(); 11429 11430 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16) 11431 return SDValue(); 11432 11433 SDValue ShAmtOp = N->getOperand(1); 11434 EVT EltVT = VT.getVectorElementType(); 11435 DebugLoc DL = N->getDebugLoc(); 11436 SDValue BaseShAmt = SDValue(); 11437 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 11438 unsigned NumElts = VT.getVectorNumElements(); 11439 unsigned i = 0; 11440 for (; i != NumElts; ++i) { 11441 SDValue Arg = ShAmtOp.getOperand(i); 11442 if (Arg.getOpcode() == ISD::UNDEF) continue; 11443 BaseShAmt = Arg; 11444 break; 11445 } 11446 for (; i != NumElts; ++i) { 11447 SDValue Arg = ShAmtOp.getOperand(i); 11448 if (Arg.getOpcode() == ISD::UNDEF) continue; 11449 if (Arg != BaseShAmt) { 11450 return SDValue(); 11451 } 11452 } 11453 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 11454 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 11455 SDValue InVec = ShAmtOp.getOperand(0); 11456 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 11457 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 11458 unsigned i = 0; 11459 for (; i != NumElts; ++i) { 11460 SDValue Arg = InVec.getOperand(i); 11461 if (Arg.getOpcode() == ISD::UNDEF) continue; 11462 BaseShAmt = Arg; 11463 break; 11464 } 11465 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 11466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 11467 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 11468 if (C->getZExtValue() == SplatIdx) 11469 BaseShAmt = InVec.getOperand(1); 11470 } 11471 } 11472 if (BaseShAmt.getNode() == 0) 11473 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 11474 DAG.getIntPtrConstant(0)); 11475 } else 11476 return SDValue(); 11477 11478 // The shift amount is an i32. 11479 if (EltVT.bitsGT(MVT::i32)) 11480 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 11481 else if (EltVT.bitsLT(MVT::i32)) 11482 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 11483 11484 // The shift amount is identical so we can do a vector shift. 11485 SDValue ValOp = N->getOperand(0); 11486 switch (N->getOpcode()) { 11487 default: 11488 llvm_unreachable("Unknown shift opcode!"); 11489 break; 11490 case ISD::SHL: 11491 if (VT == MVT::v2i64) 11492 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11493 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 11494 ValOp, BaseShAmt); 11495 if (VT == MVT::v4i32) 11496 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11497 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 11498 ValOp, BaseShAmt); 11499 if (VT == MVT::v8i16) 11500 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11501 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 11502 ValOp, BaseShAmt); 11503 break; 11504 case ISD::SRA: 11505 if (VT == MVT::v4i32) 11506 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11507 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 11508 ValOp, BaseShAmt); 11509 if (VT == MVT::v8i16) 11510 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11511 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 11512 ValOp, BaseShAmt); 11513 break; 11514 case ISD::SRL: 11515 if (VT == MVT::v2i64) 11516 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11517 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 11518 ValOp, BaseShAmt); 11519 if (VT == MVT::v4i32) 11520 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11521 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 11522 ValOp, BaseShAmt); 11523 if (VT == MVT::v8i16) 11524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11525 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 11526 ValOp, BaseShAmt); 11527 break; 11528 } 11529 return SDValue(); 11530} 11531 11532 11533static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 11534 TargetLowering::DAGCombinerInfo &DCI, 11535 const X86Subtarget *Subtarget) { 11536 if (DCI.isBeforeLegalizeOps()) 11537 return SDValue(); 11538 11539 // Want to form PANDN nodes, in the hopes of then easily combining them with 11540 // OR and AND nodes to form PBLEND/PSIGN. 11541 EVT VT = N->getValueType(0); 11542 if (VT != MVT::v2i64) 11543 return SDValue(); 11544 11545 SDValue N0 = N->getOperand(0); 11546 SDValue N1 = N->getOperand(1); 11547 DebugLoc DL = N->getDebugLoc(); 11548 11549 // Check LHS for vnot 11550 if (N0.getOpcode() == ISD::XOR && 11551 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 11552 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1); 11553 11554 // Check RHS for vnot 11555 if (N1.getOpcode() == ISD::XOR && 11556 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 11557 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0); 11558 11559 return SDValue(); 11560} 11561 11562static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 11563 TargetLowering::DAGCombinerInfo &DCI, 11564 const X86Subtarget *Subtarget) { 11565 if (DCI.isBeforeLegalizeOps()) 11566 return SDValue(); 11567 11568 EVT VT = N->getValueType(0); 11569 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64) 11570 return SDValue(); 11571 11572 SDValue N0 = N->getOperand(0); 11573 SDValue N1 = N->getOperand(1); 11574 11575 // look for psign/blend 11576 if (Subtarget->hasSSSE3()) { 11577 if (VT == MVT::v2i64) { 11578 // Canonicalize pandn to RHS 11579 if (N0.getOpcode() == X86ISD::PANDN) 11580 std::swap(N0, N1); 11581 // or (and (m, x), (pandn m, y)) 11582 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) { 11583 SDValue Mask = N1.getOperand(0); 11584 SDValue X = N1.getOperand(1); 11585 SDValue Y; 11586 if (N0.getOperand(0) == Mask) 11587 Y = N0.getOperand(1); 11588 if (N0.getOperand(1) == Mask) 11589 Y = N0.getOperand(0); 11590 11591 // Check to see if the mask appeared in both the AND and PANDN and 11592 if (!Y.getNode()) 11593 return SDValue(); 11594 11595 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 11596 if (Mask.getOpcode() != ISD::BITCAST || 11597 X.getOpcode() != ISD::BITCAST || 11598 Y.getOpcode() != ISD::BITCAST) 11599 return SDValue(); 11600 11601 // Look through mask bitcast. 11602 Mask = Mask.getOperand(0); 11603 EVT MaskVT = Mask.getValueType(); 11604 11605 // Validate that the Mask operand is a vector sra node. The sra node 11606 // will be an intrinsic. 11607 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 11608 return SDValue(); 11609 11610 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 11611 // there is no psrai.b 11612 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 11613 case Intrinsic::x86_sse2_psrai_w: 11614 case Intrinsic::x86_sse2_psrai_d: 11615 break; 11616 default: return SDValue(); 11617 } 11618 11619 // Check that the SRA is all signbits. 11620 SDValue SraC = Mask.getOperand(2); 11621 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 11622 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 11623 if ((SraAmt + 1) != EltBits) 11624 return SDValue(); 11625 11626 DebugLoc DL = N->getDebugLoc(); 11627 11628 // Now we know we at least have a plendvb with the mask val. See if 11629 // we can form a psignb/w/d. 11630 // psign = x.type == y.type == mask.type && y = sub(0, x); 11631 X = X.getOperand(0); 11632 Y = Y.getOperand(0); 11633 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 11634 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 11635 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){ 11636 unsigned Opc = 0; 11637 switch (EltBits) { 11638 case 8: Opc = X86ISD::PSIGNB; break; 11639 case 16: Opc = X86ISD::PSIGNW; break; 11640 case 32: Opc = X86ISD::PSIGND; break; 11641 default: break; 11642 } 11643 if (Opc) { 11644 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1)); 11645 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign); 11646 } 11647 } 11648 // PBLENDVB only available on SSE 4.1 11649 if (!Subtarget->hasSSE41()) 11650 return SDValue(); 11651 11652 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X); 11653 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y); 11654 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask); 11655 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask); 11656 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask); 11657 } 11658 } 11659 } 11660 11661 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 11662 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 11663 std::swap(N0, N1); 11664 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 11665 return SDValue(); 11666 if (!N0.hasOneUse() || !N1.hasOneUse()) 11667 return SDValue(); 11668 11669 SDValue ShAmt0 = N0.getOperand(1); 11670 if (ShAmt0.getValueType() != MVT::i8) 11671 return SDValue(); 11672 SDValue ShAmt1 = N1.getOperand(1); 11673 if (ShAmt1.getValueType() != MVT::i8) 11674 return SDValue(); 11675 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 11676 ShAmt0 = ShAmt0.getOperand(0); 11677 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 11678 ShAmt1 = ShAmt1.getOperand(0); 11679 11680 DebugLoc DL = N->getDebugLoc(); 11681 unsigned Opc = X86ISD::SHLD; 11682 SDValue Op0 = N0.getOperand(0); 11683 SDValue Op1 = N1.getOperand(0); 11684 if (ShAmt0.getOpcode() == ISD::SUB) { 11685 Opc = X86ISD::SHRD; 11686 std::swap(Op0, Op1); 11687 std::swap(ShAmt0, ShAmt1); 11688 } 11689 11690 unsigned Bits = VT.getSizeInBits(); 11691 if (ShAmt1.getOpcode() == ISD::SUB) { 11692 SDValue Sum = ShAmt1.getOperand(0); 11693 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 11694 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 11695 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 11696 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 11697 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 11698 return DAG.getNode(Opc, DL, VT, 11699 Op0, Op1, 11700 DAG.getNode(ISD::TRUNCATE, DL, 11701 MVT::i8, ShAmt0)); 11702 } 11703 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 11704 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 11705 if (ShAmt0C && 11706 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 11707 return DAG.getNode(Opc, DL, VT, 11708 N0.getOperand(0), N1.getOperand(0), 11709 DAG.getNode(ISD::TRUNCATE, DL, 11710 MVT::i8, ShAmt0)); 11711 } 11712 11713 return SDValue(); 11714} 11715 11716/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 11717static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 11718 const X86Subtarget *Subtarget) { 11719 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 11720 // the FP state in cases where an emms may be missing. 11721 // A preferable solution to the general problem is to figure out the right 11722 // places to insert EMMS. This qualifies as a quick hack. 11723 11724 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 11725 StoreSDNode *St = cast<StoreSDNode>(N); 11726 EVT VT = St->getValue().getValueType(); 11727 if (VT.getSizeInBits() != 64) 11728 return SDValue(); 11729 11730 const Function *F = DAG.getMachineFunction().getFunction(); 11731 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 11732 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 11733 && Subtarget->hasSSE2(); 11734 if ((VT.isVector() || 11735 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 11736 isa<LoadSDNode>(St->getValue()) && 11737 !cast<LoadSDNode>(St->getValue())->isVolatile() && 11738 St->getChain().hasOneUse() && !St->isVolatile()) { 11739 SDNode* LdVal = St->getValue().getNode(); 11740 LoadSDNode *Ld = 0; 11741 int TokenFactorIndex = -1; 11742 SmallVector<SDValue, 8> Ops; 11743 SDNode* ChainVal = St->getChain().getNode(); 11744 // Must be a store of a load. We currently handle two cases: the load 11745 // is a direct child, and it's under an intervening TokenFactor. It is 11746 // possible to dig deeper under nested TokenFactors. 11747 if (ChainVal == LdVal) 11748 Ld = cast<LoadSDNode>(St->getChain()); 11749 else if (St->getValue().hasOneUse() && 11750 ChainVal->getOpcode() == ISD::TokenFactor) { 11751 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 11752 if (ChainVal->getOperand(i).getNode() == LdVal) { 11753 TokenFactorIndex = i; 11754 Ld = cast<LoadSDNode>(St->getValue()); 11755 } else 11756 Ops.push_back(ChainVal->getOperand(i)); 11757 } 11758 } 11759 11760 if (!Ld || !ISD::isNormalLoad(Ld)) 11761 return SDValue(); 11762 11763 // If this is not the MMX case, i.e. we are just turning i64 load/store 11764 // into f64 load/store, avoid the transformation if there are multiple 11765 // uses of the loaded value. 11766 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 11767 return SDValue(); 11768 11769 DebugLoc LdDL = Ld->getDebugLoc(); 11770 DebugLoc StDL = N->getDebugLoc(); 11771 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 11772 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 11773 // pair instead. 11774 if (Subtarget->is64Bit() || F64IsLegal) { 11775 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 11776 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 11777 Ld->getPointerInfo(), Ld->isVolatile(), 11778 Ld->isNonTemporal(), Ld->getAlignment()); 11779 SDValue NewChain = NewLd.getValue(1); 11780 if (TokenFactorIndex != -1) { 11781 Ops.push_back(NewChain); 11782 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 11783 Ops.size()); 11784 } 11785 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 11786 St->getPointerInfo(), 11787 St->isVolatile(), St->isNonTemporal(), 11788 St->getAlignment()); 11789 } 11790 11791 // Otherwise, lower to two pairs of 32-bit loads / stores. 11792 SDValue LoAddr = Ld->getBasePtr(); 11793 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 11794 DAG.getConstant(4, MVT::i32)); 11795 11796 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 11797 Ld->getPointerInfo(), 11798 Ld->isVolatile(), Ld->isNonTemporal(), 11799 Ld->getAlignment()); 11800 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 11801 Ld->getPointerInfo().getWithOffset(4), 11802 Ld->isVolatile(), Ld->isNonTemporal(), 11803 MinAlign(Ld->getAlignment(), 4)); 11804 11805 SDValue NewChain = LoLd.getValue(1); 11806 if (TokenFactorIndex != -1) { 11807 Ops.push_back(LoLd); 11808 Ops.push_back(HiLd); 11809 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 11810 Ops.size()); 11811 } 11812 11813 LoAddr = St->getBasePtr(); 11814 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 11815 DAG.getConstant(4, MVT::i32)); 11816 11817 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 11818 St->getPointerInfo(), 11819 St->isVolatile(), St->isNonTemporal(), 11820 St->getAlignment()); 11821 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 11822 St->getPointerInfo().getWithOffset(4), 11823 St->isVolatile(), 11824 St->isNonTemporal(), 11825 MinAlign(St->getAlignment(), 4)); 11826 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 11827 } 11828 return SDValue(); 11829} 11830 11831/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 11832/// X86ISD::FXOR nodes. 11833static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 11834 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 11835 // F[X]OR(0.0, x) -> x 11836 // F[X]OR(x, 0.0) -> x 11837 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 11838 if (C->getValueAPF().isPosZero()) 11839 return N->getOperand(1); 11840 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 11841 if (C->getValueAPF().isPosZero()) 11842 return N->getOperand(0); 11843 return SDValue(); 11844} 11845 11846/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 11847static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 11848 // FAND(0.0, x) -> 0.0 11849 // FAND(x, 0.0) -> 0.0 11850 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 11851 if (C->getValueAPF().isPosZero()) 11852 return N->getOperand(0); 11853 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 11854 if (C->getValueAPF().isPosZero()) 11855 return N->getOperand(1); 11856 return SDValue(); 11857} 11858 11859static SDValue PerformBTCombine(SDNode *N, 11860 SelectionDAG &DAG, 11861 TargetLowering::DAGCombinerInfo &DCI) { 11862 // BT ignores high bits in the bit index operand. 11863 SDValue Op1 = N->getOperand(1); 11864 if (Op1.hasOneUse()) { 11865 unsigned BitWidth = Op1.getValueSizeInBits(); 11866 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 11867 APInt KnownZero, KnownOne; 11868 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 11869 !DCI.isBeforeLegalizeOps()); 11870 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11871 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 11872 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 11873 DCI.CommitTargetLoweringOpt(TLO); 11874 } 11875 return SDValue(); 11876} 11877 11878static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 11879 SDValue Op = N->getOperand(0); 11880 if (Op.getOpcode() == ISD::BITCAST) 11881 Op = Op.getOperand(0); 11882 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 11883 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 11884 VT.getVectorElementType().getSizeInBits() == 11885 OpVT.getVectorElementType().getSizeInBits()) { 11886 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 11887 } 11888 return SDValue(); 11889} 11890 11891static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 11892 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 11893 // (and (i32 x86isd::setcc_carry), 1) 11894 // This eliminates the zext. This transformation is necessary because 11895 // ISD::SETCC is always legalized to i8. 11896 DebugLoc dl = N->getDebugLoc(); 11897 SDValue N0 = N->getOperand(0); 11898 EVT VT = N->getValueType(0); 11899 if (N0.getOpcode() == ISD::AND && 11900 N0.hasOneUse() && 11901 N0.getOperand(0).hasOneUse()) { 11902 SDValue N00 = N0.getOperand(0); 11903 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 11904 return SDValue(); 11905 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 11906 if (!C || C->getZExtValue() != 1) 11907 return SDValue(); 11908 return DAG.getNode(ISD::AND, dl, VT, 11909 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 11910 N00.getOperand(0), N00.getOperand(1)), 11911 DAG.getConstant(1, VT)); 11912 } 11913 11914 return SDValue(); 11915} 11916 11917// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 11918static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 11919 unsigned X86CC = N->getConstantOperandVal(0); 11920 SDValue EFLAG = N->getOperand(1); 11921 DebugLoc DL = N->getDebugLoc(); 11922 11923 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 11924 // a zext and produces an all-ones bit which is more useful than 0/1 in some 11925 // cases. 11926 if (X86CC == X86::COND_B) 11927 return DAG.getNode(ISD::AND, DL, MVT::i8, 11928 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 11929 DAG.getConstant(X86CC, MVT::i8), EFLAG), 11930 DAG.getConstant(1, MVT::i8)); 11931 11932 return SDValue(); 11933} 11934 11935// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 11936static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 11937 X86TargetLowering::DAGCombinerInfo &DCI) { 11938 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 11939 // the result is either zero or one (depending on the input carry bit). 11940 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 11941 if (X86::isZeroNode(N->getOperand(0)) && 11942 X86::isZeroNode(N->getOperand(1)) && 11943 // We don't have a good way to replace an EFLAGS use, so only do this when 11944 // dead right now. 11945 SDValue(N, 1).use_empty()) { 11946 DebugLoc DL = N->getDebugLoc(); 11947 EVT VT = N->getValueType(0); 11948 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 11949 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 11950 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 11951 DAG.getConstant(X86::COND_B,MVT::i8), 11952 N->getOperand(2)), 11953 DAG.getConstant(1, VT)); 11954 return DCI.CombineTo(N, Res1, CarryOut); 11955 } 11956 11957 return SDValue(); 11958} 11959 11960// fold (add Y, (sete X, 0)) -> adc 0, Y 11961// (add Y, (setne X, 0)) -> sbb -1, Y 11962// (sub (sete X, 0), Y) -> sbb 0, Y 11963// (sub (setne X, 0), Y) -> adc -1, Y 11964static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) { 11965 DebugLoc DL = N->getDebugLoc(); 11966 11967 // Look through ZExts. 11968 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 11969 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 11970 return SDValue(); 11971 11972 SDValue SetCC = Ext.getOperand(0); 11973 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 11974 return SDValue(); 11975 11976 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 11977 if (CC != X86::COND_E && CC != X86::COND_NE) 11978 return SDValue(); 11979 11980 SDValue Cmp = SetCC.getOperand(1); 11981 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 11982 !X86::isZeroNode(Cmp.getOperand(1)) || 11983 !Cmp.getOperand(0).getValueType().isInteger()) 11984 return SDValue(); 11985 11986 SDValue CmpOp0 = Cmp.getOperand(0); 11987 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 11988 DAG.getConstant(1, CmpOp0.getValueType())); 11989 11990 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 11991 if (CC == X86::COND_NE) 11992 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 11993 DL, OtherVal.getValueType(), OtherVal, 11994 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 11995 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 11996 DL, OtherVal.getValueType(), OtherVal, 11997 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 11998} 11999 12000SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 12001 DAGCombinerInfo &DCI) const { 12002 SelectionDAG &DAG = DCI.DAG; 12003 switch (N->getOpcode()) { 12004 default: break; 12005 case ISD::EXTRACT_VECTOR_ELT: 12006 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 12007 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 12008 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 12009 case ISD::ADD: 12010 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG); 12011 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 12012 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 12013 case ISD::SHL: 12014 case ISD::SRA: 12015 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 12016 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 12017 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 12018 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 12019 case X86ISD::FXOR: 12020 case X86ISD::FOR: return PerformFORCombine(N, DAG); 12021 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 12022 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 12023 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 12024 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 12025 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 12026 case X86ISD::SHUFPS: // Handle all target specific shuffles 12027 case X86ISD::SHUFPD: 12028 case X86ISD::PALIGN: 12029 case X86ISD::PUNPCKHBW: 12030 case X86ISD::PUNPCKHWD: 12031 case X86ISD::PUNPCKHDQ: 12032 case X86ISD::PUNPCKHQDQ: 12033 case X86ISD::UNPCKHPS: 12034 case X86ISD::UNPCKHPD: 12035 case X86ISD::PUNPCKLBW: 12036 case X86ISD::PUNPCKLWD: 12037 case X86ISD::PUNPCKLDQ: 12038 case X86ISD::PUNPCKLQDQ: 12039 case X86ISD::UNPCKLPS: 12040 case X86ISD::UNPCKLPD: 12041 case X86ISD::VUNPCKLPS: 12042 case X86ISD::VUNPCKLPD: 12043 case X86ISD::VUNPCKLPSY: 12044 case X86ISD::VUNPCKLPDY: 12045 case X86ISD::MOVHLPS: 12046 case X86ISD::MOVLHPS: 12047 case X86ISD::PSHUFD: 12048 case X86ISD::PSHUFHW: 12049 case X86ISD::PSHUFLW: 12050 case X86ISD::MOVSS: 12051 case X86ISD::MOVSD: 12052 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI); 12053 } 12054 12055 return SDValue(); 12056} 12057 12058/// isTypeDesirableForOp - Return true if the target has native support for 12059/// the specified value type and it is 'desirable' to use the type for the 12060/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 12061/// instruction encodings are longer and some i16 instructions are slow. 12062bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 12063 if (!isTypeLegal(VT)) 12064 return false; 12065 if (VT != MVT::i16) 12066 return true; 12067 12068 switch (Opc) { 12069 default: 12070 return true; 12071 case ISD::LOAD: 12072 case ISD::SIGN_EXTEND: 12073 case ISD::ZERO_EXTEND: 12074 case ISD::ANY_EXTEND: 12075 case ISD::SHL: 12076 case ISD::SRL: 12077 case ISD::SUB: 12078 case ISD::ADD: 12079 case ISD::MUL: 12080 case ISD::AND: 12081 case ISD::OR: 12082 case ISD::XOR: 12083 return false; 12084 } 12085} 12086 12087/// IsDesirableToPromoteOp - This method query the target whether it is 12088/// beneficial for dag combiner to promote the specified node. If true, it 12089/// should return the desired promotion type by reference. 12090bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 12091 EVT VT = Op.getValueType(); 12092 if (VT != MVT::i16) 12093 return false; 12094 12095 bool Promote = false; 12096 bool Commute = false; 12097 switch (Op.getOpcode()) { 12098 default: break; 12099 case ISD::LOAD: { 12100 LoadSDNode *LD = cast<LoadSDNode>(Op); 12101 // If the non-extending load has a single use and it's not live out, then it 12102 // might be folded. 12103 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 12104 Op.hasOneUse()*/) { 12105 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 12106 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 12107 // The only case where we'd want to promote LOAD (rather then it being 12108 // promoted as an operand is when it's only use is liveout. 12109 if (UI->getOpcode() != ISD::CopyToReg) 12110 return false; 12111 } 12112 } 12113 Promote = true; 12114 break; 12115 } 12116 case ISD::SIGN_EXTEND: 12117 case ISD::ZERO_EXTEND: 12118 case ISD::ANY_EXTEND: 12119 Promote = true; 12120 break; 12121 case ISD::SHL: 12122 case ISD::SRL: { 12123 SDValue N0 = Op.getOperand(0); 12124 // Look out for (store (shl (load), x)). 12125 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 12126 return false; 12127 Promote = true; 12128 break; 12129 } 12130 case ISD::ADD: 12131 case ISD::MUL: 12132 case ISD::AND: 12133 case ISD::OR: 12134 case ISD::XOR: 12135 Commute = true; 12136 // fallthrough 12137 case ISD::SUB: { 12138 SDValue N0 = Op.getOperand(0); 12139 SDValue N1 = Op.getOperand(1); 12140 if (!Commute && MayFoldLoad(N1)) 12141 return false; 12142 // Avoid disabling potential load folding opportunities. 12143 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 12144 return false; 12145 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 12146 return false; 12147 Promote = true; 12148 } 12149 } 12150 12151 PVT = MVT::i32; 12152 return Promote; 12153} 12154 12155//===----------------------------------------------------------------------===// 12156// X86 Inline Assembly Support 12157//===----------------------------------------------------------------------===// 12158 12159bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 12160 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 12161 12162 std::string AsmStr = IA->getAsmString(); 12163 12164 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 12165 SmallVector<StringRef, 4> AsmPieces; 12166 SplitString(AsmStr, AsmPieces, ";\n"); 12167 12168 switch (AsmPieces.size()) { 12169 default: return false; 12170 case 1: 12171 AsmStr = AsmPieces[0]; 12172 AsmPieces.clear(); 12173 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 12174 12175 // FIXME: this should verify that we are targetting a 486 or better. If not, 12176 // we will turn this bswap into something that will be lowered to logical ops 12177 // instead of emitting the bswap asm. For now, we don't support 486 or lower 12178 // so don't worry about this. 12179 // bswap $0 12180 if (AsmPieces.size() == 2 && 12181 (AsmPieces[0] == "bswap" || 12182 AsmPieces[0] == "bswapq" || 12183 AsmPieces[0] == "bswapl") && 12184 (AsmPieces[1] == "$0" || 12185 AsmPieces[1] == "${0:q}")) { 12186 // No need to check constraints, nothing other than the equivalent of 12187 // "=r,0" would be valid here. 12188 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12189 if (!Ty || Ty->getBitWidth() % 16 != 0) 12190 return false; 12191 return IntrinsicLowering::LowerToByteSwap(CI); 12192 } 12193 // rorw $$8, ${0:w} --> llvm.bswap.i16 12194 if (CI->getType()->isIntegerTy(16) && 12195 AsmPieces.size() == 3 && 12196 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 12197 AsmPieces[1] == "$$8," && 12198 AsmPieces[2] == "${0:w}" && 12199 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12200 AsmPieces.clear(); 12201 const std::string &ConstraintsStr = IA->getConstraintString(); 12202 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12203 std::sort(AsmPieces.begin(), AsmPieces.end()); 12204 if (AsmPieces.size() == 4 && 12205 AsmPieces[0] == "~{cc}" && 12206 AsmPieces[1] == "~{dirflag}" && 12207 AsmPieces[2] == "~{flags}" && 12208 AsmPieces[3] == "~{fpsr}") { 12209 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12210 if (!Ty || Ty->getBitWidth() % 16 != 0) 12211 return false; 12212 return IntrinsicLowering::LowerToByteSwap(CI); 12213 } 12214 } 12215 break; 12216 case 3: 12217 if (CI->getType()->isIntegerTy(32) && 12218 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 12219 SmallVector<StringRef, 4> Words; 12220 SplitString(AsmPieces[0], Words, " \t,"); 12221 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12222 Words[2] == "${0:w}") { 12223 Words.clear(); 12224 SplitString(AsmPieces[1], Words, " \t,"); 12225 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 12226 Words[2] == "$0") { 12227 Words.clear(); 12228 SplitString(AsmPieces[2], Words, " \t,"); 12229 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 12230 Words[2] == "${0:w}") { 12231 AsmPieces.clear(); 12232 const std::string &ConstraintsStr = IA->getConstraintString(); 12233 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 12234 std::sort(AsmPieces.begin(), AsmPieces.end()); 12235 if (AsmPieces.size() == 4 && 12236 AsmPieces[0] == "~{cc}" && 12237 AsmPieces[1] == "~{dirflag}" && 12238 AsmPieces[2] == "~{flags}" && 12239 AsmPieces[3] == "~{fpsr}") { 12240 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12241 if (!Ty || Ty->getBitWidth() % 16 != 0) 12242 return false; 12243 return IntrinsicLowering::LowerToByteSwap(CI); 12244 } 12245 } 12246 } 12247 } 12248 } 12249 12250 if (CI->getType()->isIntegerTy(64)) { 12251 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 12252 if (Constraints.size() >= 2 && 12253 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 12254 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 12255 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 12256 SmallVector<StringRef, 4> Words; 12257 SplitString(AsmPieces[0], Words, " \t"); 12258 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 12259 Words.clear(); 12260 SplitString(AsmPieces[1], Words, " \t"); 12261 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 12262 Words.clear(); 12263 SplitString(AsmPieces[2], Words, " \t,"); 12264 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 12265 Words[2] == "%edx") { 12266 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 12267 if (!Ty || Ty->getBitWidth() % 16 != 0) 12268 return false; 12269 return IntrinsicLowering::LowerToByteSwap(CI); 12270 } 12271 } 12272 } 12273 } 12274 } 12275 break; 12276 } 12277 return false; 12278} 12279 12280 12281 12282/// getConstraintType - Given a constraint letter, return the type of 12283/// constraint it is for this target. 12284X86TargetLowering::ConstraintType 12285X86TargetLowering::getConstraintType(const std::string &Constraint) const { 12286 if (Constraint.size() == 1) { 12287 switch (Constraint[0]) { 12288 case 'R': 12289 case 'q': 12290 case 'Q': 12291 case 'f': 12292 case 't': 12293 case 'u': 12294 case 'y': 12295 case 'x': 12296 case 'Y': 12297 return C_RegisterClass; 12298 case 'a': 12299 case 'b': 12300 case 'c': 12301 case 'd': 12302 case 'S': 12303 case 'D': 12304 case 'A': 12305 return C_Register; 12306 case 'I': 12307 case 'J': 12308 case 'K': 12309 case 'L': 12310 case 'M': 12311 case 'N': 12312 case 'G': 12313 case 'C': 12314 case 'e': 12315 case 'Z': 12316 return C_Other; 12317 default: 12318 break; 12319 } 12320 } 12321 return TargetLowering::getConstraintType(Constraint); 12322} 12323 12324/// Examine constraint type and operand type and determine a weight value. 12325/// This object must already have been set up with the operand type 12326/// and the current alternative constraint selected. 12327TargetLowering::ConstraintWeight 12328 X86TargetLowering::getSingleConstraintMatchWeight( 12329 AsmOperandInfo &info, const char *constraint) const { 12330 ConstraintWeight weight = CW_Invalid; 12331 Value *CallOperandVal = info.CallOperandVal; 12332 // If we don't have a value, we can't do a match, 12333 // but allow it at the lowest weight. 12334 if (CallOperandVal == NULL) 12335 return CW_Default; 12336 const Type *type = CallOperandVal->getType(); 12337 // Look at the constraint type. 12338 switch (*constraint) { 12339 default: 12340 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12341 case 'R': 12342 case 'q': 12343 case 'Q': 12344 case 'a': 12345 case 'b': 12346 case 'c': 12347 case 'd': 12348 case 'S': 12349 case 'D': 12350 case 'A': 12351 if (CallOperandVal->getType()->isIntegerTy()) 12352 weight = CW_SpecificReg; 12353 break; 12354 case 'f': 12355 case 't': 12356 case 'u': 12357 if (type->isFloatingPointTy()) 12358 weight = CW_SpecificReg; 12359 break; 12360 case 'y': 12361 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 12362 weight = CW_SpecificReg; 12363 break; 12364 case 'x': 12365 case 'Y': 12366 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 12367 weight = CW_Register; 12368 break; 12369 case 'I': 12370 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 12371 if (C->getZExtValue() <= 31) 12372 weight = CW_Constant; 12373 } 12374 break; 12375 case 'J': 12376 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12377 if (C->getZExtValue() <= 63) 12378 weight = CW_Constant; 12379 } 12380 break; 12381 case 'K': 12382 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12383 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 12384 weight = CW_Constant; 12385 } 12386 break; 12387 case 'L': 12388 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12389 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 12390 weight = CW_Constant; 12391 } 12392 break; 12393 case 'M': 12394 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12395 if (C->getZExtValue() <= 3) 12396 weight = CW_Constant; 12397 } 12398 break; 12399 case 'N': 12400 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12401 if (C->getZExtValue() <= 0xff) 12402 weight = CW_Constant; 12403 } 12404 break; 12405 case 'G': 12406 case 'C': 12407 if (dyn_cast<ConstantFP>(CallOperandVal)) { 12408 weight = CW_Constant; 12409 } 12410 break; 12411 case 'e': 12412 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12413 if ((C->getSExtValue() >= -0x80000000LL) && 12414 (C->getSExtValue() <= 0x7fffffffLL)) 12415 weight = CW_Constant; 12416 } 12417 break; 12418 case 'Z': 12419 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 12420 if (C->getZExtValue() <= 0xffffffff) 12421 weight = CW_Constant; 12422 } 12423 break; 12424 } 12425 return weight; 12426} 12427 12428/// LowerXConstraint - try to replace an X constraint, which matches anything, 12429/// with another that has more specific requirements based on the type of the 12430/// corresponding operand. 12431const char *X86TargetLowering:: 12432LowerXConstraint(EVT ConstraintVT) const { 12433 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 12434 // 'f' like normal targets. 12435 if (ConstraintVT.isFloatingPoint()) { 12436 if (Subtarget->hasXMMInt()) 12437 return "Y"; 12438 if (Subtarget->hasXMM()) 12439 return "x"; 12440 } 12441 12442 return TargetLowering::LowerXConstraint(ConstraintVT); 12443} 12444 12445/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 12446/// vector. If it is invalid, don't add anything to Ops. 12447void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12448 char Constraint, 12449 std::vector<SDValue>&Ops, 12450 SelectionDAG &DAG) const { 12451 SDValue Result(0, 0); 12452 12453 switch (Constraint) { 12454 default: break; 12455 case 'I': 12456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12457 if (C->getZExtValue() <= 31) { 12458 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12459 break; 12460 } 12461 } 12462 return; 12463 case 'J': 12464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12465 if (C->getZExtValue() <= 63) { 12466 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12467 break; 12468 } 12469 } 12470 return; 12471 case 'K': 12472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12473 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 12474 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12475 break; 12476 } 12477 } 12478 return; 12479 case 'N': 12480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12481 if (C->getZExtValue() <= 255) { 12482 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12483 break; 12484 } 12485 } 12486 return; 12487 case 'e': { 12488 // 32-bit signed value 12489 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12490 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12491 C->getSExtValue())) { 12492 // Widen to 64 bits here to get it sign extended. 12493 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 12494 break; 12495 } 12496 // FIXME gcc accepts some relocatable values here too, but only in certain 12497 // memory models; it's complicated. 12498 } 12499 return; 12500 } 12501 case 'Z': { 12502 // 32-bit unsigned value 12503 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12504 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 12505 C->getZExtValue())) { 12506 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 12507 break; 12508 } 12509 } 12510 // FIXME gcc accepts some relocatable values here too, but only in certain 12511 // memory models; it's complicated. 12512 return; 12513 } 12514 case 'i': { 12515 // Literal immediates are always ok. 12516 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 12517 // Widen to 64 bits here to get it sign extended. 12518 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 12519 break; 12520 } 12521 12522 // In any sort of PIC mode addresses need to be computed at runtime by 12523 // adding in a register or some sort of table lookup. These can't 12524 // be used as immediates. 12525 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 12526 return; 12527 12528 // If we are in non-pic codegen mode, we allow the address of a global (with 12529 // an optional displacement) to be used with 'i'. 12530 GlobalAddressSDNode *GA = 0; 12531 int64_t Offset = 0; 12532 12533 // Match either (GA), (GA+C), (GA+C1+C2), etc. 12534 while (1) { 12535 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 12536 Offset += GA->getOffset(); 12537 break; 12538 } else if (Op.getOpcode() == ISD::ADD) { 12539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12540 Offset += C->getZExtValue(); 12541 Op = Op.getOperand(0); 12542 continue; 12543 } 12544 } else if (Op.getOpcode() == ISD::SUB) { 12545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 12546 Offset += -C->getZExtValue(); 12547 Op = Op.getOperand(0); 12548 continue; 12549 } 12550 } 12551 12552 // Otherwise, this isn't something we can handle, reject it. 12553 return; 12554 } 12555 12556 const GlobalValue *GV = GA->getGlobal(); 12557 // If we require an extra load to get this address, as in PIC mode, we 12558 // can't accept it. 12559 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 12560 getTargetMachine()))) 12561 return; 12562 12563 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 12564 GA->getValueType(0), Offset); 12565 break; 12566 } 12567 } 12568 12569 if (Result.getNode()) { 12570 Ops.push_back(Result); 12571 return; 12572 } 12573 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12574} 12575 12576std::vector<unsigned> X86TargetLowering:: 12577getRegClassForInlineAsmConstraint(const std::string &Constraint, 12578 EVT VT) const { 12579 if (Constraint.size() == 1) { 12580 // FIXME: not handling fp-stack yet! 12581 switch (Constraint[0]) { // GCC X86 Constraint Letters 12582 default: break; // Unknown constraint letter 12583 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 12584 if (Subtarget->is64Bit()) { 12585 if (VT == MVT::i32) 12586 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 12587 X86::ESI, X86::EDI, X86::R8D, X86::R9D, 12588 X86::R10D,X86::R11D,X86::R12D, 12589 X86::R13D,X86::R14D,X86::R15D, 12590 X86::EBP, X86::ESP, 0); 12591 else if (VT == MVT::i16) 12592 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 12593 X86::SI, X86::DI, X86::R8W,X86::R9W, 12594 X86::R10W,X86::R11W,X86::R12W, 12595 X86::R13W,X86::R14W,X86::R15W, 12596 X86::BP, X86::SP, 0); 12597 else if (VT == MVT::i8) 12598 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 12599 X86::SIL, X86::DIL, X86::R8B,X86::R9B, 12600 X86::R10B,X86::R11B,X86::R12B, 12601 X86::R13B,X86::R14B,X86::R15B, 12602 X86::BPL, X86::SPL, 0); 12603 12604 else if (VT == MVT::i64) 12605 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 12606 X86::RSI, X86::RDI, X86::R8, X86::R9, 12607 X86::R10, X86::R11, X86::R12, 12608 X86::R13, X86::R14, X86::R15, 12609 X86::RBP, X86::RSP, 0); 12610 12611 break; 12612 } 12613 // 32-bit fallthrough 12614 case 'Q': // Q_REGS 12615 if (VT == MVT::i32) 12616 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0); 12617 else if (VT == MVT::i16) 12618 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0); 12619 else if (VT == MVT::i8) 12620 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0); 12621 else if (VT == MVT::i64) 12622 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0); 12623 break; 12624 } 12625 } 12626 12627 return std::vector<unsigned>(); 12628} 12629 12630std::pair<unsigned, const TargetRegisterClass*> 12631X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 12632 EVT VT) const { 12633 // First, see if this is a constraint that directly corresponds to an LLVM 12634 // register class. 12635 if (Constraint.size() == 1) { 12636 // GCC Constraint Letters 12637 switch (Constraint[0]) { 12638 default: break; 12639 case 'r': // GENERAL_REGS 12640 case 'l': // INDEX_REGS 12641 if (VT == MVT::i8) 12642 return std::make_pair(0U, X86::GR8RegisterClass); 12643 if (VT == MVT::i16) 12644 return std::make_pair(0U, X86::GR16RegisterClass); 12645 if (VT == MVT::i32 || !Subtarget->is64Bit()) 12646 return std::make_pair(0U, X86::GR32RegisterClass); 12647 return std::make_pair(0U, X86::GR64RegisterClass); 12648 case 'R': // LEGACY_REGS 12649 if (VT == MVT::i8) 12650 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 12651 if (VT == MVT::i16) 12652 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 12653 if (VT == MVT::i32 || !Subtarget->is64Bit()) 12654 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 12655 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 12656 case 'f': // FP Stack registers. 12657 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 12658 // value to the correct fpstack register class. 12659 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 12660 return std::make_pair(0U, X86::RFP32RegisterClass); 12661 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 12662 return std::make_pair(0U, X86::RFP64RegisterClass); 12663 return std::make_pair(0U, X86::RFP80RegisterClass); 12664 case 'y': // MMX_REGS if MMX allowed. 12665 if (!Subtarget->hasMMX()) break; 12666 return std::make_pair(0U, X86::VR64RegisterClass); 12667 case 'Y': // SSE_REGS if SSE2 allowed 12668 if (!Subtarget->hasXMMInt()) break; 12669 // FALL THROUGH. 12670 case 'x': // SSE_REGS if SSE1 allowed 12671 if (!Subtarget->hasXMM()) break; 12672 12673 switch (VT.getSimpleVT().SimpleTy) { 12674 default: break; 12675 // Scalar SSE types. 12676 case MVT::f32: 12677 case MVT::i32: 12678 return std::make_pair(0U, X86::FR32RegisterClass); 12679 case MVT::f64: 12680 case MVT::i64: 12681 return std::make_pair(0U, X86::FR64RegisterClass); 12682 // Vector types. 12683 case MVT::v16i8: 12684 case MVT::v8i16: 12685 case MVT::v4i32: 12686 case MVT::v2i64: 12687 case MVT::v4f32: 12688 case MVT::v2f64: 12689 return std::make_pair(0U, X86::VR128RegisterClass); 12690 } 12691 break; 12692 } 12693 } 12694 12695 // Use the default implementation in TargetLowering to convert the register 12696 // constraint into a member of a register class. 12697 std::pair<unsigned, const TargetRegisterClass*> Res; 12698 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 12699 12700 // Not found as a standard register? 12701 if (Res.second == 0) { 12702 // Map st(0) -> st(7) -> ST0 12703 if (Constraint.size() == 7 && Constraint[0] == '{' && 12704 tolower(Constraint[1]) == 's' && 12705 tolower(Constraint[2]) == 't' && 12706 Constraint[3] == '(' && 12707 (Constraint[4] >= '0' && Constraint[4] <= '7') && 12708 Constraint[5] == ')' && 12709 Constraint[6] == '}') { 12710 12711 Res.first = X86::ST0+Constraint[4]-'0'; 12712 Res.second = X86::RFP80RegisterClass; 12713 return Res; 12714 } 12715 12716 // GCC allows "st(0)" to be called just plain "st". 12717 if (StringRef("{st}").equals_lower(Constraint)) { 12718 Res.first = X86::ST0; 12719 Res.second = X86::RFP80RegisterClass; 12720 return Res; 12721 } 12722 12723 // flags -> EFLAGS 12724 if (StringRef("{flags}").equals_lower(Constraint)) { 12725 Res.first = X86::EFLAGS; 12726 Res.second = X86::CCRRegisterClass; 12727 return Res; 12728 } 12729 12730 // 'A' means EAX + EDX. 12731 if (Constraint == "A") { 12732 Res.first = X86::EAX; 12733 Res.second = X86::GR32_ADRegisterClass; 12734 return Res; 12735 } 12736 return Res; 12737 } 12738 12739 // Otherwise, check to see if this is a register class of the wrong value 12740 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 12741 // turn into {ax},{dx}. 12742 if (Res.second->hasType(VT)) 12743 return Res; // Correct type already, nothing to do. 12744 12745 // All of the single-register GCC register classes map their values onto 12746 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 12747 // really want an 8-bit or 32-bit register, map to the appropriate register 12748 // class and return the appropriate register. 12749 if (Res.second == X86::GR16RegisterClass) { 12750 if (VT == MVT::i8) { 12751 unsigned DestReg = 0; 12752 switch (Res.first) { 12753 default: break; 12754 case X86::AX: DestReg = X86::AL; break; 12755 case X86::DX: DestReg = X86::DL; break; 12756 case X86::CX: DestReg = X86::CL; break; 12757 case X86::BX: DestReg = X86::BL; break; 12758 } 12759 if (DestReg) { 12760 Res.first = DestReg; 12761 Res.second = X86::GR8RegisterClass; 12762 } 12763 } else if (VT == MVT::i32) { 12764 unsigned DestReg = 0; 12765 switch (Res.first) { 12766 default: break; 12767 case X86::AX: DestReg = X86::EAX; break; 12768 case X86::DX: DestReg = X86::EDX; break; 12769 case X86::CX: DestReg = X86::ECX; break; 12770 case X86::BX: DestReg = X86::EBX; break; 12771 case X86::SI: DestReg = X86::ESI; break; 12772 case X86::DI: DestReg = X86::EDI; break; 12773 case X86::BP: DestReg = X86::EBP; break; 12774 case X86::SP: DestReg = X86::ESP; break; 12775 } 12776 if (DestReg) { 12777 Res.first = DestReg; 12778 Res.second = X86::GR32RegisterClass; 12779 } 12780 } else if (VT == MVT::i64) { 12781 unsigned DestReg = 0; 12782 switch (Res.first) { 12783 default: break; 12784 case X86::AX: DestReg = X86::RAX; break; 12785 case X86::DX: DestReg = X86::RDX; break; 12786 case X86::CX: DestReg = X86::RCX; break; 12787 case X86::BX: DestReg = X86::RBX; break; 12788 case X86::SI: DestReg = X86::RSI; break; 12789 case X86::DI: DestReg = X86::RDI; break; 12790 case X86::BP: DestReg = X86::RBP; break; 12791 case X86::SP: DestReg = X86::RSP; break; 12792 } 12793 if (DestReg) { 12794 Res.first = DestReg; 12795 Res.second = X86::GR64RegisterClass; 12796 } 12797 } 12798 } else if (Res.second == X86::FR32RegisterClass || 12799 Res.second == X86::FR64RegisterClass || 12800 Res.second == X86::VR128RegisterClass) { 12801 // Handle references to XMM physical registers that got mapped into the 12802 // wrong class. This can happen with constraints like {xmm0} where the 12803 // target independent register mapper will just pick the first match it can 12804 // find, ignoring the required type. 12805 if (VT == MVT::f32) 12806 Res.second = X86::FR32RegisterClass; 12807 else if (VT == MVT::f64) 12808 Res.second = X86::FR64RegisterClass; 12809 else if (X86::VR128RegisterClass->hasType(VT)) 12810 Res.second = X86::VR128RegisterClass; 12811 } 12812 12813 return Res; 12814} 12815