X86ISelLowering.cpp revision 138a5c66b9ccaded2ee5d63b96f69349c098e49a
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/MC/MCAsmInfo.h" 39#include "llvm/MC/MCContext.h" 40#include "llvm/MC/MCExpr.h" 41#include "llvm/MC/MCSymbol.h" 42#include "llvm/ADT/BitVector.h" 43#include "llvm/ADT/SmallSet.h" 44#include "llvm/ADT/Statistic.h" 45#include "llvm/ADT/StringExtras.h" 46#include "llvm/ADT/VectorExtras.h" 47#include "llvm/Support/CallSite.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" 53#include "llvm/Target/TargetOptions.h" 54using namespace llvm; 55using namespace dwarf; 56 57STATISTIC(NumTailCalls, "Number of tail calls"); 58 59// Forward declarations. 60static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 61 SDValue V2); 62 63static SDValue Insert128BitVector(SDValue Result, 64 SDValue Vec, 65 SDValue Idx, 66 SelectionDAG &DAG, 67 DebugLoc dl); 68 69static SDValue Extract128BitVector(SDValue Vec, 70 SDValue Idx, 71 SelectionDAG &DAG, 72 DebugLoc dl); 73 74/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 75/// sets things up to match to an AVX VEXTRACTF128 instruction or a 76/// simple subregister reference. Idx is an index in the 128 bits we 77/// want. It need not be aligned to a 128-bit bounday. That makes 78/// lowering EXTRACT_VECTOR_ELT operations easier. 79static SDValue Extract128BitVector(SDValue Vec, 80 SDValue Idx, 81 SelectionDAG &DAG, 82 DebugLoc dl) { 83 EVT VT = Vec.getValueType(); 84 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!"); 85 EVT ElVT = VT.getVectorElementType(); 86 int Factor = VT.getSizeInBits()/128; 87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 88 VT.getVectorNumElements()/Factor); 89 90 // Extract from UNDEF is UNDEF. 91 if (Vec.getOpcode() == ISD::UNDEF) 92 return DAG.getNode(ISD::UNDEF, dl, ResultVT); 93 94 if (isa<ConstantSDNode>(Idx)) { 95 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 96 97 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 98 // we can match to VEXTRACTF128. 99 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 100 101 // This is the index of the first element of the 128-bit chunk 102 // we want. 103 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 104 * ElemsPerChunk); 105 106 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 108 VecIdx); 109 110 return Result; 111 } 112 113 return SDValue(); 114} 115 116/// Generate a DAG to put 128-bits into a vector > 128 bits. This 117/// sets things up to match to an AVX VINSERTF128 instruction or a 118/// simple superregister reference. Idx is an index in the 128 bits 119/// we want. It need not be aligned to a 128-bit bounday. That makes 120/// lowering INSERT_VECTOR_ELT operations easier. 121static SDValue Insert128BitVector(SDValue Result, 122 SDValue Vec, 123 SDValue Idx, 124 SelectionDAG &DAG, 125 DebugLoc dl) { 126 if (isa<ConstantSDNode>(Idx)) { 127 EVT VT = Vec.getValueType(); 128 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!"); 129 130 EVT ElVT = VT.getVectorElementType(); 131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 132 EVT ResultVT = Result.getValueType(); 133 134 // Insert the relevant 128 bits. 135 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 136 137 // This is the index of the first element of the 128-bit chunk 138 // we want. 139 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 140 * ElemsPerChunk); 141 142 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32); 143 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 144 VecIdx); 145 return Result; 146 } 147 148 return SDValue(); 149} 150 151static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 152 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 153 bool is64Bit = Subtarget->is64Bit(); 154 155 if (Subtarget->isTargetEnvMacho()) { 156 if (is64Bit) 157 return new X8664_MachoTargetObjectFile(); 158 return new TargetLoweringObjectFileMachO(); 159 } 160 161 if (Subtarget->isTargetELF()) 162 return new TargetLoweringObjectFileELF(); 163 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 164 return new TargetLoweringObjectFileCOFF(); 165 llvm_unreachable("unknown subtarget type"); 166} 167 168X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 169 : TargetLowering(TM, createTLOF(TM)) { 170 Subtarget = &TM.getSubtarget<X86Subtarget>(); 171 X86ScalarSSEf64 = Subtarget->hasXMMInt(); 172 X86ScalarSSEf32 = Subtarget->hasXMM(); 173 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP; 174 175 RegInfo = TM.getRegisterInfo(); 176 TD = getTargetData(); 177 178 // Set up the TargetLowering object. 179 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 180 181 // X86 is weird, it always uses i8 for shift amounts and setcc results. 182 setBooleanContents(ZeroOrOneBooleanContent); 183 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 184 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 185 186 // For 64-bit since we have so many registers use the ILP scheduler, for 187 // 32-bit code use the register pressure specific scheduling. 188 if (Subtarget->is64Bit()) 189 setSchedulingPreference(Sched::ILP); 190 else 191 setSchedulingPreference(Sched::RegPressure); 192 setStackPointerRegisterToSaveRestore(X86StackPtr); 193 194 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 195 // Setup Windows compiler runtime calls. 196 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 197 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 198 setLibcallName(RTLIB::SREM_I64, "_allrem"); 199 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 200 setLibcallName(RTLIB::MUL_I64, "_allmul"); 201 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2"); 202 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2"); 203 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 204 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 205 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 206 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 207 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 208 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C); 209 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C); 210 } 211 212 if (Subtarget->isTargetDarwin()) { 213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 214 setUseUnderscoreSetJmp(false); 215 setUseUnderscoreLongJmp(false); 216 } else if (Subtarget->isTargetMingw()) { 217 // MS runtime is weird: it exports _setjmp, but longjmp! 218 setUseUnderscoreSetJmp(true); 219 setUseUnderscoreLongJmp(false); 220 } else { 221 setUseUnderscoreSetJmp(true); 222 setUseUnderscoreLongJmp(true); 223 } 224 225 // Set up the register classes. 226 addRegisterClass(MVT::i8, X86::GR8RegisterClass); 227 addRegisterClass(MVT::i16, X86::GR16RegisterClass); 228 addRegisterClass(MVT::i32, X86::GR32RegisterClass); 229 if (Subtarget->is64Bit()) 230 addRegisterClass(MVT::i64, X86::GR64RegisterClass); 231 232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 233 234 // We don't accept any truncstore of integer registers. 235 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 236 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 238 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 240 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 241 242 // SETOEQ and SETUNE require checking two conditions. 243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 249 250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 251 // operation. 252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 255 256 if (Subtarget->is64Bit()) { 257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand); 259 } else if (!UseSoftFloat) { 260 // We have an algorithm for SSE2->double, and we turn this into a 261 // 64-bit FILD followed by conditional FADD for other targets. 262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 263 // We have an algorithm for SSE2, and we turn this into a 64-bit 264 // FILD for other targets. 265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 266 } 267 268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 269 // this operation. 270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 272 273 if (!UseSoftFloat) { 274 // SSE has no i16 to fp conversion, only i32 275 if (X86ScalarSSEf32) { 276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 277 // f32 and f64 cases are Legal, f80 case is not 278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 279 } else { 280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 282 } 283 } else { 284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 286 } 287 288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 289 // are Legal, f80 is custom lowered. 290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 292 293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 294 // this operation. 295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 297 298 if (X86ScalarSSEf32) { 299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 300 // f32 and f64 cases are Legal, f80 case is not 301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 302 } else { 303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 305 } 306 307 // Handle FP_TO_UINT by promoting the destination to a larger signed 308 // conversion. 309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 312 313 if (Subtarget->is64Bit()) { 314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 316 } else if (!UseSoftFloat) { 317 // Since AVX is a superset of SSE3, only check for SSE here. 318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 319 // Expand FP_TO_UINT into a select. 320 // FIXME: We would like to use a Custom expander here eventually to do 321 // the optimal thing for SSE vs. the default expansion in the legalizer. 322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 323 else 324 // With SSE3 we can use fisttpll to convert to a signed i64; without 325 // SSE, we're stuck with a fistpll. 326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 327 } 328 329 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 330 if (!X86ScalarSSEf64) { 331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 333 if (Subtarget->is64Bit()) { 334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 335 // Without SSE, i64->f64 goes through memory. 336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 337 } 338 } 339 340 // Scalar integer divide and remainder are lowered to use operations that 341 // produce two results, to match the available instructions. This exposes 342 // the two-result form to trivial CSE, which is able to combine x/y and x%y 343 // into a single instruction. 344 // 345 // Scalar integer multiply-high is also lowered to use two-result 346 // operations, to match the available instructions. However, plain multiply 347 // (low) operations are left as Legal, as there are single-result 348 // instructions for this in x86. Using the two-result multiply instructions 349 // when both high and low results are needed must be arranged by dagcombine. 350 for (unsigned i = 0, e = 4; i != e; ++i) { 351 MVT VT = IntVTs[i]; 352 setOperationAction(ISD::MULHS, VT, Expand); 353 setOperationAction(ISD::MULHU, VT, Expand); 354 setOperationAction(ISD::SDIV, VT, Expand); 355 setOperationAction(ISD::UDIV, VT, Expand); 356 setOperationAction(ISD::SREM, VT, Expand); 357 setOperationAction(ISD::UREM, VT, Expand); 358 359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 360 setOperationAction(ISD::ADDC, VT, Custom); 361 setOperationAction(ISD::ADDE, VT, Custom); 362 setOperationAction(ISD::SUBC, VT, Custom); 363 setOperationAction(ISD::SUBE, VT, Custom); 364 } 365 366 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 367 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 368 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 370 if (Subtarget->is64Bit()) 371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 376 setOperationAction(ISD::FREM , MVT::f32 , Expand); 377 setOperationAction(ISD::FREM , MVT::f64 , Expand); 378 setOperationAction(ISD::FREM , MVT::f80 , Expand); 379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 380 381 if (Subtarget->hasBMI()) { 382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 383 } else { 384 setOperationAction(ISD::CTTZ , MVT::i8 , Custom); 385 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 387 if (Subtarget->is64Bit()) 388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 389 } 390 391 if (Subtarget->hasLZCNT()) { 392 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 393 } else { 394 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 395 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 396 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 397 if (Subtarget->is64Bit()) 398 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 399 } 400 401 if (Subtarget->hasPOPCNT()) { 402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 403 } else { 404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 407 if (Subtarget->is64Bit()) 408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 409 } 410 411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 412 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 413 414 // These should be promoted to a larger select which is supported. 415 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 416 // X86 wants to expand cmov itself. 417 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 418 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 419 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 420 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 421 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 422 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 423 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 424 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 425 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 426 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 427 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 428 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 429 if (Subtarget->is64Bit()) { 430 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 431 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 432 } 433 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 434 435 // Darwin ABI issue. 436 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 437 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 438 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 439 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 440 if (Subtarget->is64Bit()) 441 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 442 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 443 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 444 if (Subtarget->is64Bit()) { 445 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 446 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 447 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 448 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 449 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 450 } 451 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 452 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 453 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 454 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 455 if (Subtarget->is64Bit()) { 456 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 457 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 458 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 459 } 460 461 if (Subtarget->hasXMM()) 462 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 463 464 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 465 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 466 467 // On X86 and X86-64, atomic operations are lowered to locked instructions. 468 // Locked instructions, in turn, have implicit fence semantics (all memory 469 // operations are flushed before issuing the locked instruction, and they 470 // are not buffered), so we can fold away the common pattern of 471 // fence-atomic-fence. 472 setShouldFoldAtomicFences(true); 473 474 // Expand certain atomics 475 for (unsigned i = 0, e = 4; i != e; ++i) { 476 MVT VT = IntVTs[i]; 477 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 478 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 480 } 481 482 if (!Subtarget->is64Bit()) { 483 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 484 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 487 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 488 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 489 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 490 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 491 } 492 493 if (Subtarget->hasCmpxchg16b()) { 494 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 495 } 496 497 // FIXME - use subtarget debug flags 498 if (!Subtarget->isTargetDarwin() && 499 !Subtarget->isTargetELF() && 500 !Subtarget->isTargetCygMing()) { 501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 502 } 503 504 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 505 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 506 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 507 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 508 if (Subtarget->is64Bit()) { 509 setExceptionPointerRegister(X86::RAX); 510 setExceptionSelectorRegister(X86::RDX); 511 } else { 512 setExceptionPointerRegister(X86::EAX); 513 setExceptionSelectorRegister(X86::EDX); 514 } 515 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 517 518 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 519 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 520 521 setOperationAction(ISD::TRAP, MVT::Other, Legal); 522 523 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 524 setOperationAction(ISD::VASTART , MVT::Other, Custom); 525 setOperationAction(ISD::VAEND , MVT::Other, Expand); 526 if (Subtarget->is64Bit()) { 527 setOperationAction(ISD::VAARG , MVT::Other, Custom); 528 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 529 } else { 530 setOperationAction(ISD::VAARG , MVT::Other, Expand); 531 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 532 } 533 534 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 535 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 536 537 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 538 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 539 MVT::i64 : MVT::i32, Custom); 540 else if (EnableSegmentedStacks) 541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 542 MVT::i64 : MVT::i32, Custom); 543 else 544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 545 MVT::i64 : MVT::i32, Expand); 546 547 if (!UseSoftFloat && X86ScalarSSEf64) { 548 // f32 and f64 use SSE. 549 // Set up the FP register classes. 550 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 551 addRegisterClass(MVT::f64, X86::FR64RegisterClass); 552 553 // Use ANDPD to simulate FABS. 554 setOperationAction(ISD::FABS , MVT::f64, Custom); 555 setOperationAction(ISD::FABS , MVT::f32, Custom); 556 557 // Use XORP to simulate FNEG. 558 setOperationAction(ISD::FNEG , MVT::f64, Custom); 559 setOperationAction(ISD::FNEG , MVT::f32, Custom); 560 561 // Use ANDPD and ORPD to simulate FCOPYSIGN. 562 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 563 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 564 565 // Lower this to FGETSIGNx86 plus an AND. 566 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 567 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 568 569 // We don't support sin/cos/fmod 570 setOperationAction(ISD::FSIN , MVT::f64, Expand); 571 setOperationAction(ISD::FCOS , MVT::f64, Expand); 572 setOperationAction(ISD::FSIN , MVT::f32, Expand); 573 setOperationAction(ISD::FCOS , MVT::f32, Expand); 574 575 // Expand FP immediates into loads from the stack, except for the special 576 // cases we handle. 577 addLegalFPImmediate(APFloat(+0.0)); // xorpd 578 addLegalFPImmediate(APFloat(+0.0f)); // xorps 579 } else if (!UseSoftFloat && X86ScalarSSEf32) { 580 // Use SSE for f32, x87 for f64. 581 // Set up the FP register classes. 582 addRegisterClass(MVT::f32, X86::FR32RegisterClass); 583 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 584 585 // Use ANDPS to simulate FABS. 586 setOperationAction(ISD::FABS , MVT::f32, Custom); 587 588 // Use XORP to simulate FNEG. 589 setOperationAction(ISD::FNEG , MVT::f32, Custom); 590 591 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 592 593 // Use ANDPS and ORPS to simulate FCOPYSIGN. 594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 596 597 // We don't support sin/cos/fmod 598 setOperationAction(ISD::FSIN , MVT::f32, Expand); 599 setOperationAction(ISD::FCOS , MVT::f32, Expand); 600 601 // Special cases we handle for FP constants. 602 addLegalFPImmediate(APFloat(+0.0f)); // xorps 603 addLegalFPImmediate(APFloat(+0.0)); // FLD0 604 addLegalFPImmediate(APFloat(+1.0)); // FLD1 605 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 606 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 607 608 if (!UnsafeFPMath) { 609 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 610 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 611 } 612 } else if (!UseSoftFloat) { 613 // f32 and f64 in x87. 614 // Set up the FP register classes. 615 addRegisterClass(MVT::f64, X86::RFP64RegisterClass); 616 addRegisterClass(MVT::f32, X86::RFP32RegisterClass); 617 618 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 619 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 622 623 if (!UnsafeFPMath) { 624 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 625 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 626 } 627 addLegalFPImmediate(APFloat(+0.0)); // FLD0 628 addLegalFPImmediate(APFloat(+1.0)); // FLD1 629 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 630 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 631 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 632 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 633 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 634 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 635 } 636 637 // We don't support FMA. 638 setOperationAction(ISD::FMA, MVT::f64, Expand); 639 setOperationAction(ISD::FMA, MVT::f32, Expand); 640 641 // Long double always uses X87. 642 if (!UseSoftFloat) { 643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass); 644 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 646 { 647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 648 addLegalFPImmediate(TmpFlt); // FLD0 649 TmpFlt.changeSign(); 650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 651 652 bool ignored; 653 APFloat TmpFlt2(+1.0); 654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 655 &ignored); 656 addLegalFPImmediate(TmpFlt2); // FLD1 657 TmpFlt2.changeSign(); 658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 659 } 660 661 if (!UnsafeFPMath) { 662 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 663 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 664 } 665 666 setOperationAction(ISD::FMA, MVT::f80, Expand); 667 } 668 669 // Always use a library call for pow. 670 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 671 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 672 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 673 674 setOperationAction(ISD::FLOG, MVT::f80, Expand); 675 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 676 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 677 setOperationAction(ISD::FEXP, MVT::f80, Expand); 678 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 679 680 // First set operation action for all vector types to either promote 681 // (for widening) or expand (for scalarization). Then we will selectively 682 // turn on ones that can be effectively codegen'd. 683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) { 685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand); 686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand); 687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand); 688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand); 689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand); 690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand); 691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand); 692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand); 693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand); 694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand); 695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand); 696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand); 697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand); 698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand); 699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand); 700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand); 701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand); 703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand); 704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand); 705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand); 706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand); 707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand); 708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand); 709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand); 710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand); 712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand); 713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand); 714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand); 715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand); 716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand); 717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand); 718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand); 719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand); 720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand); 721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand); 722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand); 723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand); 724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand); 725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand); 726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand); 727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand); 728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand); 729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand); 730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand); 731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand); 732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand); 734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand); 735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand); 736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand); 737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand); 738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand); 739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand); 740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 742 setTruncStoreAction((MVT::SimpleValueType)VT, 743 (MVT::SimpleValueType)InnerVT, Expand); 744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand); 745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand); 746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand); 747 } 748 749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 750 // with -msoft-float, disable use of MMX as well. 751 if (!UseSoftFloat && Subtarget->hasMMX()) { 752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass); 753 // No operations on x86mmx supported, everything uses intrinsics. 754 } 755 756 // MMX-sized vectors (other than x86mmx) are expected to be expanded 757 // into smaller operations. 758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 762 setOperationAction(ISD::AND, MVT::v8i8, Expand); 763 setOperationAction(ISD::AND, MVT::v4i16, Expand); 764 setOperationAction(ISD::AND, MVT::v2i32, Expand); 765 setOperationAction(ISD::AND, MVT::v1i64, Expand); 766 setOperationAction(ISD::OR, MVT::v8i8, Expand); 767 setOperationAction(ISD::OR, MVT::v4i16, Expand); 768 setOperationAction(ISD::OR, MVT::v2i32, Expand); 769 setOperationAction(ISD::OR, MVT::v1i64, Expand); 770 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 771 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 772 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 773 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 787 788 if (!UseSoftFloat && Subtarget->hasXMM()) { 789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass); 790 791 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom); 803 } 804 805 if (!UseSoftFloat && Subtarget->hasXMMInt()) { 806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass); 807 808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 809 // registers cannot be used even for integer operations. 810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass); 811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass); 812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass); 813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass); 814 815 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 816 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 817 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 818 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 819 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 820 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 821 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 822 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 823 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 824 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 825 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 831 832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 836 837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 842 843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom); 844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom); 845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom); 846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom); 847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom); 848 849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) { 851 EVT VT = (MVT::SimpleValueType)i; 852 // Do not attempt to custom lower non-power-of-2 vectors 853 if (!isPowerOf2_32(VT.getVectorNumElements())) 854 continue; 855 // Do not attempt to custom lower non-128-bit vectors 856 if (!VT.is128BitVector()) 857 continue; 858 setOperationAction(ISD::BUILD_VECTOR, 859 VT.getSimpleVT().SimpleTy, Custom); 860 setOperationAction(ISD::VECTOR_SHUFFLE, 861 VT.getSimpleVT().SimpleTy, Custom); 862 setOperationAction(ISD::EXTRACT_VECTOR_ELT, 863 VT.getSimpleVT().SimpleTy, Custom); 864 } 865 866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 872 873 if (Subtarget->is64Bit()) { 874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 876 } 877 878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) { 880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 881 EVT VT = SVT; 882 883 // Do not attempt to promote non-128-bit vectors 884 if (!VT.is128BitVector()) 885 continue; 886 887 setOperationAction(ISD::AND, SVT, Promote); 888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64); 889 setOperationAction(ISD::OR, SVT, Promote); 890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64); 891 setOperationAction(ISD::XOR, SVT, Promote); 892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64); 893 setOperationAction(ISD::LOAD, SVT, Promote); 894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64); 895 setOperationAction(ISD::SELECT, SVT, Promote); 896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64); 897 } 898 899 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 900 901 // Custom lower v2i64 and v2f64 selects. 902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 906 907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 909 } 910 911 if (Subtarget->hasSSE41orAVX()) { 912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 913 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 915 setOperationAction(ISD::FRINT, MVT::f32, Legal); 916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 918 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 920 setOperationAction(ISD::FRINT, MVT::f64, Legal); 921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 922 923 // FIXME: Do we need to handle scalar-to-vector here? 924 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 925 926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 931 932 // i8 and i16 vectors are custom , because the source register and source 933 // source memory operand types are not the same width. f32 vectors are 934 // custom since the immediate controlling the insert encodes additional 935 // information. 936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 940 941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 945 946 // FIXME: these should be Legal but thats only for the case where 947 // the index is constant. For now custom expand to deal with that 948 if (Subtarget->is64Bit()) { 949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 951 } 952 } 953 954 if (Subtarget->hasXMMInt()) { 955 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 956 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 957 958 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 959 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 960 961 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 962 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 963 964 if (Subtarget->hasAVX2()) { 965 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 966 setOperationAction(ISD::SRL, MVT::v4i32, Legal); 967 968 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 969 setOperationAction(ISD::SHL, MVT::v4i32, Legal); 970 971 setOperationAction(ISD::SRA, MVT::v4i32, Legal); 972 } else { 973 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 974 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 975 976 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 977 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 978 979 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 980 } 981 } 982 983 if (Subtarget->hasSSE42orAVX()) 984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 985 986 if (!UseSoftFloat && Subtarget->hasAVX()) { 987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass); 988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass); 989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass); 990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass); 991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass); 992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass); 993 994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 997 998 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1004 1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1011 1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1015 1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom); 1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom); 1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom); 1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom); 1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom); 1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom); 1022 1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1025 1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1028 1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1031 1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1036 1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1040 1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1045 1046 if (Subtarget->hasAVX2()) { 1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1051 1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1056 1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1060 // Don't lower v32i8 because there is no 128-bit byte mul 1061 1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1063 1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal); 1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal); 1066 1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal); 1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal); 1069 1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal); 1071 } else { 1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1076 1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1081 1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1085 // Don't lower v32i8 because there is no 128-bit byte mul 1086 1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1089 1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1092 1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1094 } 1095 1096 // Custom lower several nodes for 256-bit types. 1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) { 1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1100 EVT VT = SVT; 1101 1102 // Extract subvector is special because the value type 1103 // (result) is 128-bit but the source is 256-bit wide. 1104 if (VT.is128BitVector()) 1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom); 1106 1107 // Do not attempt to custom lower other non-256-bit vectors 1108 if (!VT.is256BitVector()) 1109 continue; 1110 1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom); 1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom); 1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom); 1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom); 1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom); 1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom); 1117 } 1118 1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) { 1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i; 1122 EVT VT = SVT; 1123 1124 // Do not attempt to promote non-256-bit vectors 1125 if (!VT.is256BitVector()) 1126 continue; 1127 1128 setOperationAction(ISD::AND, SVT, Promote); 1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64); 1130 setOperationAction(ISD::OR, SVT, Promote); 1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64); 1132 setOperationAction(ISD::XOR, SVT, Promote); 1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64); 1134 setOperationAction(ISD::LOAD, SVT, Promote); 1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64); 1136 setOperationAction(ISD::SELECT, SVT, Promote); 1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64); 1138 } 1139 } 1140 1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1142 // of this type with custom code. 1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE; 1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) { 1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom); 1146 } 1147 1148 // We want to custom lower some of our intrinsics. 1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1150 1151 1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1153 // handle type legalization for these operations here. 1154 // 1155 // FIXME: We really should do custom legalization for addition and 1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1157 // than generic legalization for 64-bit multiplication-with-overflow, though. 1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1159 // Add/Sub/Mul with overflow operations are custom lowered. 1160 MVT VT = IntVTs[i]; 1161 setOperationAction(ISD::SADDO, VT, Custom); 1162 setOperationAction(ISD::UADDO, VT, Custom); 1163 setOperationAction(ISD::SSUBO, VT, Custom); 1164 setOperationAction(ISD::USUBO, VT, Custom); 1165 setOperationAction(ISD::SMULO, VT, Custom); 1166 setOperationAction(ISD::UMULO, VT, Custom); 1167 } 1168 1169 // There are no 8-bit 3-address imul/mul instructions 1170 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1171 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1172 1173 if (!Subtarget->is64Bit()) { 1174 // These libcalls are not available in 32-bit. 1175 setLibcallName(RTLIB::SHL_I128, 0); 1176 setLibcallName(RTLIB::SRL_I128, 0); 1177 setLibcallName(RTLIB::SRA_I128, 0); 1178 } 1179 1180 // We have target-specific dag combine patterns for the following nodes: 1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1183 setTargetDAGCombine(ISD::BUILD_VECTOR); 1184 setTargetDAGCombine(ISD::VSELECT); 1185 setTargetDAGCombine(ISD::SELECT); 1186 setTargetDAGCombine(ISD::SHL); 1187 setTargetDAGCombine(ISD::SRA); 1188 setTargetDAGCombine(ISD::SRL); 1189 setTargetDAGCombine(ISD::OR); 1190 setTargetDAGCombine(ISD::AND); 1191 setTargetDAGCombine(ISD::ADD); 1192 setTargetDAGCombine(ISD::FADD); 1193 setTargetDAGCombine(ISD::FSUB); 1194 setTargetDAGCombine(ISD::SUB); 1195 setTargetDAGCombine(ISD::LOAD); 1196 setTargetDAGCombine(ISD::STORE); 1197 setTargetDAGCombine(ISD::ZERO_EXTEND); 1198 setTargetDAGCombine(ISD::SINT_TO_FP); 1199 if (Subtarget->is64Bit()) 1200 setTargetDAGCombine(ISD::MUL); 1201 if (Subtarget->hasBMI()) 1202 setTargetDAGCombine(ISD::XOR); 1203 1204 computeRegisterProperties(); 1205 1206 // On Darwin, -Os means optimize for size without hurting performance, 1207 // do not reduce the limit. 1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1214 setPrefLoopAlignment(16); 1215 benefitFromCodePlacementOpt = true; 1216 1217 setPrefFunctionAlignment(4); 1218} 1219 1220 1221EVT X86TargetLowering::getSetCCResultType(EVT VT) const { 1222 if (!VT.isVector()) return MVT::i8; 1223 return VT.changeVectorElementTypeToInteger(); 1224} 1225 1226 1227/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1228/// the desired ByVal argument alignment. 1229static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1230 if (MaxAlign == 16) 1231 return; 1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1233 if (VTy->getBitWidth() == 128) 1234 MaxAlign = 16; 1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1236 unsigned EltAlign = 0; 1237 getMaxByValAlign(ATy->getElementType(), EltAlign); 1238 if (EltAlign > MaxAlign) 1239 MaxAlign = EltAlign; 1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1242 unsigned EltAlign = 0; 1243 getMaxByValAlign(STy->getElementType(i), EltAlign); 1244 if (EltAlign > MaxAlign) 1245 MaxAlign = EltAlign; 1246 if (MaxAlign == 16) 1247 break; 1248 } 1249 } 1250 return; 1251} 1252 1253/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1254/// function arguments in the caller parameter area. For X86, aggregates 1255/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1256/// are at 4-byte boundaries. 1257unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1258 if (Subtarget->is64Bit()) { 1259 // Max of 8 and alignment of type. 1260 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1261 if (TyAlign > 8) 1262 return TyAlign; 1263 return 8; 1264 } 1265 1266 unsigned Align = 4; 1267 if (Subtarget->hasXMM()) 1268 getMaxByValAlign(Ty, Align); 1269 return Align; 1270} 1271 1272/// getOptimalMemOpType - Returns the target specific optimal type for load 1273/// and store operations as a result of memset, memcpy, and memmove 1274/// lowering. If DstAlign is zero that means it's safe to destination 1275/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1276/// means there isn't a need to check it against alignment requirement, 1277/// probably because the source does not need to be loaded. If 1278/// 'IsZeroVal' is true, that means it's safe to return a 1279/// non-scalar-integer type, e.g. empty string source, constant, or loaded 1280/// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 1281/// constant so it does not need to be loaded. 1282/// It returns EVT::Other if the type should be determined using generic 1283/// target-independent logic. 1284EVT 1285X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1286 unsigned DstAlign, unsigned SrcAlign, 1287 bool IsZeroVal, 1288 bool MemcpyStrSrc, 1289 MachineFunction &MF) const { 1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like 1291 // linux. This is because the stack realignment code can't handle certain 1292 // cases like PR2962. This should be removed when PR2962 is fixed. 1293 const Function *F = MF.getFunction(); 1294 if (IsZeroVal && 1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) { 1296 if (Size >= 16 && 1297 (Subtarget->isUnalignedMemAccessFast() || 1298 ((DstAlign == 0 || DstAlign >= 16) && 1299 (SrcAlign == 0 || SrcAlign >= 16))) && 1300 Subtarget->getStackAlignment() >= 16) { 1301 if (Subtarget->hasAVX() && 1302 Subtarget->getStackAlignment() >= 32) 1303 return MVT::v8f32; 1304 if (Subtarget->hasXMMInt()) 1305 return MVT::v4i32; 1306 if (Subtarget->hasXMM()) 1307 return MVT::v4f32; 1308 } else if (!MemcpyStrSrc && Size >= 8 && 1309 !Subtarget->is64Bit() && 1310 Subtarget->getStackAlignment() >= 8 && 1311 Subtarget->hasXMMInt()) { 1312 // Do not use f64 to lower memcpy if source is string constant. It's 1313 // better to use i32 to avoid the loads. 1314 return MVT::f64; 1315 } 1316 } 1317 if (Subtarget->is64Bit() && Size >= 8) 1318 return MVT::i64; 1319 return MVT::i32; 1320} 1321 1322/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1323/// current function. The returned value is a member of the 1324/// MachineJumpTableInfo::JTEntryKind enum. 1325unsigned X86TargetLowering::getJumpTableEncoding() const { 1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1327 // symbol. 1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1329 Subtarget->isPICStyleGOT()) 1330 return MachineJumpTableInfo::EK_Custom32; 1331 1332 // Otherwise, use the normal jump table encoding heuristics. 1333 return TargetLowering::getJumpTableEncoding(); 1334} 1335 1336const MCExpr * 1337X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1338 const MachineBasicBlock *MBB, 1339 unsigned uid,MCContext &Ctx) const{ 1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1341 Subtarget->isPICStyleGOT()); 1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1343 // entries. 1344 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1345 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1346} 1347 1348/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1349/// jumptable. 1350SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1351 SelectionDAG &DAG) const { 1352 if (!Subtarget->is64Bit()) 1353 // This doesn't have DebugLoc associated with it, but is not really the 1354 // same as a Register. 1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1356 return Table; 1357} 1358 1359/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1360/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1361/// MCExpr. 1362const MCExpr *X86TargetLowering:: 1363getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1364 MCContext &Ctx) const { 1365 // X86-64 uses RIP relative addressing based on the jump table label. 1366 if (Subtarget->isPICStyleRIPRel()) 1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1368 1369 // Otherwise, the reference is relative to the PIC base. 1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1371} 1372 1373// FIXME: Why this routine is here? Move to RegInfo! 1374std::pair<const TargetRegisterClass*, uint8_t> 1375X86TargetLowering::findRepresentativeClass(EVT VT) const{ 1376 const TargetRegisterClass *RRC = 0; 1377 uint8_t Cost = 1; 1378 switch (VT.getSimpleVT().SimpleTy) { 1379 default: 1380 return TargetLowering::findRepresentativeClass(VT); 1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1382 RRC = (Subtarget->is64Bit() 1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass); 1384 break; 1385 case MVT::x86mmx: 1386 RRC = X86::VR64RegisterClass; 1387 break; 1388 case MVT::f32: case MVT::f64: 1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1390 case MVT::v4f32: case MVT::v2f64: 1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1392 case MVT::v4f64: 1393 RRC = X86::VR128RegisterClass; 1394 break; 1395 } 1396 return std::make_pair(RRC, Cost); 1397} 1398 1399bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1400 unsigned &Offset) const { 1401 if (!Subtarget->isTargetLinux()) 1402 return false; 1403 1404 if (Subtarget->is64Bit()) { 1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1406 Offset = 0x28; 1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1408 AddressSpace = 256; 1409 else 1410 AddressSpace = 257; 1411 } else { 1412 // %gs:0x14 on i386 1413 Offset = 0x14; 1414 AddressSpace = 256; 1415 } 1416 return true; 1417} 1418 1419 1420//===----------------------------------------------------------------------===// 1421// Return Value Calling Convention Implementation 1422//===----------------------------------------------------------------------===// 1423 1424#include "X86GenCallingConv.inc" 1425 1426bool 1427X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1428 MachineFunction &MF, bool isVarArg, 1429 const SmallVectorImpl<ISD::OutputArg> &Outs, 1430 LLVMContext &Context) const { 1431 SmallVector<CCValAssign, 16> RVLocs; 1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1433 RVLocs, Context); 1434 return CCInfo.CheckReturn(Outs, RetCC_X86); 1435} 1436 1437SDValue 1438X86TargetLowering::LowerReturn(SDValue Chain, 1439 CallingConv::ID CallConv, bool isVarArg, 1440 const SmallVectorImpl<ISD::OutputArg> &Outs, 1441 const SmallVectorImpl<SDValue> &OutVals, 1442 DebugLoc dl, SelectionDAG &DAG) const { 1443 MachineFunction &MF = DAG.getMachineFunction(); 1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1445 1446 SmallVector<CCValAssign, 16> RVLocs; 1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1448 RVLocs, *DAG.getContext()); 1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1450 1451 // Add the regs to the liveout set for the function. 1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1453 for (unsigned i = 0; i != RVLocs.size(); ++i) 1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1455 MRI.addLiveOut(RVLocs[i].getLocReg()); 1456 1457 SDValue Flag; 1458 1459 SmallVector<SDValue, 6> RetOps; 1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1461 // Operand #1 = Bytes To Pop 1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1463 MVT::i16)); 1464 1465 // Copy the result values into the output registers. 1466 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1467 CCValAssign &VA = RVLocs[i]; 1468 assert(VA.isRegLoc() && "Can only return in registers!"); 1469 SDValue ValToCopy = OutVals[i]; 1470 EVT ValVT = ValToCopy.getValueType(); 1471 1472 // If this is x86-64, and we disabled SSE, we can't return FP values, 1473 // or SSE or MMX vectors. 1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) { 1477 report_fatal_error("SSE register return with SSE disabled"); 1478 } 1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1480 // llvm-gcc has never done it right and no one has noticed, so this 1481 // should be OK for now. 1482 if (ValVT == MVT::f64 && 1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt())) 1484 report_fatal_error("SSE2 register return with SSE2 disabled"); 1485 1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1487 // the RET instruction and handled by the FP Stackifier. 1488 if (VA.getLocReg() == X86::ST0 || 1489 VA.getLocReg() == X86::ST1) { 1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1491 // change the value to the FP stack register class. 1492 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1494 RetOps.push_back(ValToCopy); 1495 // Don't emit a copytoreg. 1496 continue; 1497 } 1498 1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1500 // which is returned in RAX / RDX. 1501 if (Subtarget->is64Bit()) { 1502 if (ValVT == MVT::x86mmx) { 1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1506 ValToCopy); 1507 // If we don't have SSE2 available, convert to v4f32 so the generated 1508 // register is legal. 1509 if (!Subtarget->hasXMMInt()) 1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1511 } 1512 } 1513 } 1514 1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1516 Flag = Chain.getValue(1); 1517 } 1518 1519 // The x86-64 ABI for returning structs by value requires that we copy 1520 // the sret argument into %rax for the return. We saved the argument into 1521 // a virtual register in the entry block, so now we copy the value out 1522 // and into %rax. 1523 if (Subtarget->is64Bit() && 1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1525 MachineFunction &MF = DAG.getMachineFunction(); 1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1527 unsigned Reg = FuncInfo->getSRetReturnReg(); 1528 assert(Reg && 1529 "SRetReturnReg should have been set in LowerFormalArguments()."); 1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1531 1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1533 Flag = Chain.getValue(1); 1534 1535 // RAX now acts like a return value. 1536 MRI.addLiveOut(X86::RAX); 1537 } 1538 1539 RetOps[0] = Chain; // Update chain. 1540 1541 // Add the flag if we have it. 1542 if (Flag.getNode()) 1543 RetOps.push_back(Flag); 1544 1545 return DAG.getNode(X86ISD::RET_FLAG, dl, 1546 MVT::Other, &RetOps[0], RetOps.size()); 1547} 1548 1549bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const { 1550 if (N->getNumValues() != 1) 1551 return false; 1552 if (!N->hasNUsesOfValue(1, 0)) 1553 return false; 1554 1555 SDNode *Copy = *N->use_begin(); 1556 if (Copy->getOpcode() != ISD::CopyToReg && 1557 Copy->getOpcode() != ISD::FP_EXTEND) 1558 return false; 1559 1560 bool HasRet = false; 1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1562 UI != UE; ++UI) { 1563 if (UI->getOpcode() != X86ISD::RET_FLAG) 1564 return false; 1565 HasRet = true; 1566 } 1567 1568 return HasRet; 1569} 1570 1571EVT 1572X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1573 ISD::NodeType ExtendKind) const { 1574 MVT ReturnMVT; 1575 // TODO: Is this also valid on 32-bit? 1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1577 ReturnMVT = MVT::i8; 1578 else 1579 ReturnMVT = MVT::i32; 1580 1581 EVT MinVT = getRegisterType(Context, ReturnMVT); 1582 return VT.bitsLT(MinVT) ? MinVT : VT; 1583} 1584 1585/// LowerCallResult - Lower the result values of a call into the 1586/// appropriate copies out of appropriate physical registers. 1587/// 1588SDValue 1589X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1590 CallingConv::ID CallConv, bool isVarArg, 1591 const SmallVectorImpl<ISD::InputArg> &Ins, 1592 DebugLoc dl, SelectionDAG &DAG, 1593 SmallVectorImpl<SDValue> &InVals) const { 1594 1595 // Assign locations to each value returned by this call. 1596 SmallVector<CCValAssign, 16> RVLocs; 1597 bool Is64Bit = Subtarget->is64Bit(); 1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1599 getTargetMachine(), RVLocs, *DAG.getContext()); 1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1601 1602 // Copy all of the result registers out of their specified physreg. 1603 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1604 CCValAssign &VA = RVLocs[i]; 1605 EVT CopyVT = VA.getValVT(); 1606 1607 // If this is x86-64, and we disabled SSE, we can't return FP values 1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) { 1610 report_fatal_error("SSE register return with SSE disabled"); 1611 } 1612 1613 SDValue Val; 1614 1615 // If this is a call to a function that returns an fp value on the floating 1616 // point stack, we must guarantee the the value is popped from the stack, so 1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1618 // if the return value is not used. We use the FpPOP_RETVAL instruction 1619 // instead. 1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1621 // If we prefer to use the value in xmm registers, copy it out as f80 and 1622 // use a truncate to move it from fp stack reg to xmm reg. 1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1624 SDValue Ops[] = { Chain, InFlag }; 1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1626 MVT::Other, MVT::Glue, Ops, 2), 1); 1627 Val = Chain.getValue(0); 1628 1629 // Round the f80 to the right size, which also moves it to the appropriate 1630 // xmm register. 1631 if (CopyVT != VA.getValVT()) 1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1633 // This truncation won't change the value. 1634 DAG.getIntPtrConstant(1)); 1635 } else { 1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1637 CopyVT, InFlag).getValue(1); 1638 Val = Chain.getValue(0); 1639 } 1640 InFlag = Chain.getValue(2); 1641 InVals.push_back(Val); 1642 } 1643 1644 return Chain; 1645} 1646 1647 1648//===----------------------------------------------------------------------===// 1649// C & StdCall & Fast Calling Convention implementation 1650//===----------------------------------------------------------------------===// 1651// StdCall calling convention seems to be standard for many Windows' API 1652// routines and around. It differs from C calling convention just a little: 1653// callee should clean up the stack, not caller. Symbols should be also 1654// decorated in some fancy way :) It doesn't support any vector arguments. 1655// For info on fast calling convention see Fast Calling Convention (tail call) 1656// implementation LowerX86_32FastCCCallTo. 1657 1658/// CallIsStructReturn - Determines whether a call uses struct return 1659/// semantics. 1660static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1661 if (Outs.empty()) 1662 return false; 1663 1664 return Outs[0].Flags.isSRet(); 1665} 1666 1667/// ArgsAreStructReturn - Determines whether a function uses struct 1668/// return semantics. 1669static bool 1670ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1671 if (Ins.empty()) 1672 return false; 1673 1674 return Ins[0].Flags.isSRet(); 1675} 1676 1677/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1678/// by "Src" to address "Dst" with size and alignment information specified by 1679/// the specific parameter attribute. The copy will be passed as a byval 1680/// function parameter. 1681static SDValue 1682CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1684 DebugLoc dl) { 1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1686 1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1688 /*isVolatile*/false, /*AlwaysInline=*/true, 1689 MachinePointerInfo(), MachinePointerInfo()); 1690} 1691 1692/// IsTailCallConvention - Return true if the calling convention is one that 1693/// supports tail call optimization. 1694static bool IsTailCallConvention(CallingConv::ID CC) { 1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC); 1696} 1697 1698bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1699 if (!CI->isTailCall()) 1700 return false; 1701 1702 CallSite CS(CI); 1703 CallingConv::ID CalleeCC = CS.getCallingConv(); 1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1705 return false; 1706 1707 return true; 1708} 1709 1710/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1711/// a tailcall target by changing its ABI. 1712static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) { 1713 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1714} 1715 1716SDValue 1717X86TargetLowering::LowerMemArgument(SDValue Chain, 1718 CallingConv::ID CallConv, 1719 const SmallVectorImpl<ISD::InputArg> &Ins, 1720 DebugLoc dl, SelectionDAG &DAG, 1721 const CCValAssign &VA, 1722 MachineFrameInfo *MFI, 1723 unsigned i) const { 1724 // Create the nodes corresponding to a load from this parameter slot. 1725 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1726 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv); 1727 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1728 EVT ValVT; 1729 1730 // If value is passed by pointer we have address passed instead of the value 1731 // itself. 1732 if (VA.getLocInfo() == CCValAssign::Indirect) 1733 ValVT = VA.getLocVT(); 1734 else 1735 ValVT = VA.getValVT(); 1736 1737 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1738 // changed with more analysis. 1739 // In case of tail call optimization mark all arguments mutable. Since they 1740 // could be overwritten by lowering of arguments in case of a tail call. 1741 if (Flags.isByVal()) { 1742 unsigned Bytes = Flags.getByValSize(); 1743 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1744 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1745 return DAG.getFrameIndex(FI, getPointerTy()); 1746 } else { 1747 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1748 VA.getLocMemOffset(), isImmutable); 1749 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1750 return DAG.getLoad(ValVT, dl, Chain, FIN, 1751 MachinePointerInfo::getFixedStack(FI), 1752 false, false, false, 0); 1753 } 1754} 1755 1756SDValue 1757X86TargetLowering::LowerFormalArguments(SDValue Chain, 1758 CallingConv::ID CallConv, 1759 bool isVarArg, 1760 const SmallVectorImpl<ISD::InputArg> &Ins, 1761 DebugLoc dl, 1762 SelectionDAG &DAG, 1763 SmallVectorImpl<SDValue> &InVals) 1764 const { 1765 MachineFunction &MF = DAG.getMachineFunction(); 1766 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1767 1768 const Function* Fn = MF.getFunction(); 1769 if (Fn->hasExternalLinkage() && 1770 Subtarget->isTargetCygMing() && 1771 Fn->getName() == "main") 1772 FuncInfo->setForceFramePointer(true); 1773 1774 MachineFrameInfo *MFI = MF.getFrameInfo(); 1775 bool Is64Bit = Subtarget->is64Bit(); 1776 bool IsWin64 = Subtarget->isTargetWin64(); 1777 1778 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1779 "Var args not supported with calling convention fastcc or ghc"); 1780 1781 // Assign locations to all of the incoming arguments. 1782 SmallVector<CCValAssign, 16> ArgLocs; 1783 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1784 ArgLocs, *DAG.getContext()); 1785 1786 // Allocate shadow area for Win64 1787 if (IsWin64) { 1788 CCInfo.AllocateStack(32, 8); 1789 } 1790 1791 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1792 1793 unsigned LastVal = ~0U; 1794 SDValue ArgValue; 1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1796 CCValAssign &VA = ArgLocs[i]; 1797 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1798 // places. 1799 assert(VA.getValNo() != LastVal && 1800 "Don't support value assigned to multiple locs yet"); 1801 (void)LastVal; 1802 LastVal = VA.getValNo(); 1803 1804 if (VA.isRegLoc()) { 1805 EVT RegVT = VA.getLocVT(); 1806 TargetRegisterClass *RC = NULL; 1807 if (RegVT == MVT::i32) 1808 RC = X86::GR32RegisterClass; 1809 else if (Is64Bit && RegVT == MVT::i64) 1810 RC = X86::GR64RegisterClass; 1811 else if (RegVT == MVT::f32) 1812 RC = X86::FR32RegisterClass; 1813 else if (RegVT == MVT::f64) 1814 RC = X86::FR64RegisterClass; 1815 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256) 1816 RC = X86::VR256RegisterClass; 1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128) 1818 RC = X86::VR128RegisterClass; 1819 else if (RegVT == MVT::x86mmx) 1820 RC = X86::VR64RegisterClass; 1821 else 1822 llvm_unreachable("Unknown argument type!"); 1823 1824 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1825 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1826 1827 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1828 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1829 // right size. 1830 if (VA.getLocInfo() == CCValAssign::SExt) 1831 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1832 DAG.getValueType(VA.getValVT())); 1833 else if (VA.getLocInfo() == CCValAssign::ZExt) 1834 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1835 DAG.getValueType(VA.getValVT())); 1836 else if (VA.getLocInfo() == CCValAssign::BCvt) 1837 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1838 1839 if (VA.isExtInLoc()) { 1840 // Handle MMX values passed in XMM regs. 1841 if (RegVT.isVector()) { 1842 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), 1843 ArgValue); 1844 } else 1845 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 1846 } 1847 } else { 1848 assert(VA.isMemLoc()); 1849 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 1850 } 1851 1852 // If value is passed via pointer - do a load. 1853 if (VA.getLocInfo() == CCValAssign::Indirect) 1854 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 1855 MachinePointerInfo(), false, false, false, 0); 1856 1857 InVals.push_back(ArgValue); 1858 } 1859 1860 // The x86-64 ABI for returning structs by value requires that we copy 1861 // the sret argument into %rax for the return. Save the argument into 1862 // a virtual register so that we can access it from the return points. 1863 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1865 unsigned Reg = FuncInfo->getSRetReturnReg(); 1866 if (!Reg) { 1867 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 1868 FuncInfo->setSRetReturnReg(Reg); 1869 } 1870 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 1871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 1872 } 1873 1874 unsigned StackSize = CCInfo.getNextStackOffset(); 1875 // Align stack specially for tail calls. 1876 if (FuncIsMadeTailCallSafe(CallConv)) 1877 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 1878 1879 // If the function takes variable number of arguments, make a frame index for 1880 // the start of the first vararg value... for expansion of llvm.va_start. 1881 if (isVarArg) { 1882 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 1883 CallConv != CallingConv::X86_ThisCall)) { 1884 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 1885 } 1886 if (Is64Bit) { 1887 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 1888 1889 // FIXME: We should really autogenerate these arrays 1890 static const unsigned GPR64ArgRegsWin64[] = { 1891 X86::RCX, X86::RDX, X86::R8, X86::R9 1892 }; 1893 static const unsigned GPR64ArgRegs64Bit[] = { 1894 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 1895 }; 1896 static const unsigned XMMArgRegs64Bit[] = { 1897 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 1898 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 1899 }; 1900 const unsigned *GPR64ArgRegs; 1901 unsigned NumXMMRegs = 0; 1902 1903 if (IsWin64) { 1904 // The XMM registers which might contain var arg parameters are shadowed 1905 // in their paired GPR. So we only need to save the GPR to their home 1906 // slots. 1907 TotalNumIntRegs = 4; 1908 GPR64ArgRegs = GPR64ArgRegsWin64; 1909 } else { 1910 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 1911 GPR64ArgRegs = GPR64ArgRegs64Bit; 1912 1913 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs); 1914 } 1915 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 1916 TotalNumIntRegs); 1917 1918 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat); 1919 assert(!(NumXMMRegs && !Subtarget->hasXMM()) && 1920 "SSE register cannot be used when SSE is disabled!"); 1921 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) && 1922 "SSE register cannot be used when SSE is disabled!"); 1923 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM()) 1924 // Kernel mode asks for SSE to be disabled, so don't push them 1925 // on the stack. 1926 TotalNumXMMRegs = 0; 1927 1928 if (IsWin64) { 1929 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 1930 // Get to the caller-allocated home save location. Add 8 to account 1931 // for the return address. 1932 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 1933 FuncInfo->setRegSaveFrameIndex( 1934 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 1935 // Fixup to set vararg frame on shadow area (4 x i64). 1936 if (NumIntRegs < 4) 1937 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 1938 } else { 1939 // For X86-64, if there are vararg parameters that are passed via 1940 // registers, then we must store them to their spots on the stack so they 1941 // may be loaded by deferencing the result of va_next. 1942 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 1943 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 1944 FuncInfo->setRegSaveFrameIndex( 1945 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 1946 false)); 1947 } 1948 1949 // Store the integer parameter registers. 1950 SmallVector<SDValue, 8> MemOps; 1951 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 1952 getPointerTy()); 1953 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 1954 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 1955 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 1956 DAG.getIntPtrConstant(Offset)); 1957 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 1958 X86::GR64RegisterClass); 1959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 1960 SDValue Store = 1961 DAG.getStore(Val.getValue(1), dl, Val, FIN, 1962 MachinePointerInfo::getFixedStack( 1963 FuncInfo->getRegSaveFrameIndex(), Offset), 1964 false, false, 0); 1965 MemOps.push_back(Store); 1966 Offset += 8; 1967 } 1968 1969 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 1970 // Now store the XMM (fp + vector) parameter registers. 1971 SmallVector<SDValue, 11> SaveXMMOps; 1972 SaveXMMOps.push_back(Chain); 1973 1974 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass); 1975 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 1976 SaveXMMOps.push_back(ALVal); 1977 1978 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1979 FuncInfo->getRegSaveFrameIndex())); 1980 SaveXMMOps.push_back(DAG.getIntPtrConstant( 1981 FuncInfo->getVarArgsFPOffset())); 1982 1983 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 1984 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 1985 X86::VR128RegisterClass); 1986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 1987 SaveXMMOps.push_back(Val); 1988 } 1989 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 1990 MVT::Other, 1991 &SaveXMMOps[0], SaveXMMOps.size())); 1992 } 1993 1994 if (!MemOps.empty()) 1995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 1996 &MemOps[0], MemOps.size()); 1997 } 1998 } 1999 2000 // Some CCs need callee pop. 2001 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) { 2002 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2003 } else { 2004 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2005 // If this is an sret function, the return should pop the hidden pointer. 2006 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins)) 2007 FuncInfo->setBytesToPopOnReturn(4); 2008 } 2009 2010 if (!Is64Bit) { 2011 // RegSaveFrameIndex is X86-64 only. 2012 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2013 if (CallConv == CallingConv::X86_FastCall || 2014 CallConv == CallingConv::X86_ThisCall) 2015 // fastcc functions can't have varargs. 2016 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2017 } 2018 2019 FuncInfo->setArgumentStackSize(StackSize); 2020 2021 return Chain; 2022} 2023 2024SDValue 2025X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2026 SDValue StackPtr, SDValue Arg, 2027 DebugLoc dl, SelectionDAG &DAG, 2028 const CCValAssign &VA, 2029 ISD::ArgFlagsTy Flags) const { 2030 unsigned LocMemOffset = VA.getLocMemOffset(); 2031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2033 if (Flags.isByVal()) 2034 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2035 2036 return DAG.getStore(Chain, dl, Arg, PtrOff, 2037 MachinePointerInfo::getStack(LocMemOffset), 2038 false, false, 0); 2039} 2040 2041/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2042/// optimization is performed and it is required. 2043SDValue 2044X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2045 SDValue &OutRetAddr, SDValue Chain, 2046 bool IsTailCall, bool Is64Bit, 2047 int FPDiff, DebugLoc dl) const { 2048 // Adjust the Return address stack slot. 2049 EVT VT = getPointerTy(); 2050 OutRetAddr = getReturnAddressFrameIndex(DAG); 2051 2052 // Load the "old" Return address. 2053 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2054 false, false, false, 0); 2055 return SDValue(OutRetAddr.getNode(), 1); 2056} 2057 2058/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2059/// optimization is performed and it is required (FPDiff!=0). 2060static SDValue 2061EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2062 SDValue Chain, SDValue RetAddrFrIdx, 2063 bool Is64Bit, int FPDiff, DebugLoc dl) { 2064 // Store the return address to the appropriate stack slot. 2065 if (!FPDiff) return Chain; 2066 // Calculate the new stack slot for the return address. 2067 int SlotSize = Is64Bit ? 8 : 4; 2068 int NewReturnAddrFI = 2069 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2070 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2071 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT); 2072 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2073 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2074 false, false, 0); 2075 return Chain; 2076} 2077 2078SDValue 2079X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, 2080 CallingConv::ID CallConv, bool isVarArg, 2081 bool &isTailCall, 2082 const SmallVectorImpl<ISD::OutputArg> &Outs, 2083 const SmallVectorImpl<SDValue> &OutVals, 2084 const SmallVectorImpl<ISD::InputArg> &Ins, 2085 DebugLoc dl, SelectionDAG &DAG, 2086 SmallVectorImpl<SDValue> &InVals) const { 2087 MachineFunction &MF = DAG.getMachineFunction(); 2088 bool Is64Bit = Subtarget->is64Bit(); 2089 bool IsWin64 = Subtarget->isTargetWin64(); 2090 bool IsStructRet = CallIsStructReturn(Outs); 2091 bool IsSibcall = false; 2092 2093 if (isTailCall) { 2094 // Check if it's really possible to do a tail call. 2095 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2096 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(), 2097 Outs, OutVals, Ins, DAG); 2098 2099 // Sibcalls are automatically detected tailcalls which do not require 2100 // ABI changes. 2101 if (!GuaranteedTailCallOpt && isTailCall) 2102 IsSibcall = true; 2103 2104 if (isTailCall) 2105 ++NumTailCalls; 2106 } 2107 2108 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2109 "Var args not supported with calling convention fastcc or ghc"); 2110 2111 // Analyze operands of the call, assigning locations to each operand. 2112 SmallVector<CCValAssign, 16> ArgLocs; 2113 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2114 ArgLocs, *DAG.getContext()); 2115 2116 // Allocate shadow area for Win64 2117 if (IsWin64) { 2118 CCInfo.AllocateStack(32, 8); 2119 } 2120 2121 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2122 2123 // Get a count of how many bytes are to be pushed on the stack. 2124 unsigned NumBytes = CCInfo.getNextStackOffset(); 2125 if (IsSibcall) 2126 // This is a sibcall. The memory operands are available in caller's 2127 // own caller's stack. 2128 NumBytes = 0; 2129 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv)) 2130 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2131 2132 int FPDiff = 0; 2133 if (isTailCall && !IsSibcall) { 2134 // Lower arguments at fp - stackoffset + fpdiff. 2135 unsigned NumBytesCallerPushed = 2136 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn(); 2137 FPDiff = NumBytesCallerPushed - NumBytes; 2138 2139 // Set the delta of movement of the returnaddr stackslot. 2140 // But only set if delta is greater than previous delta. 2141 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta())) 2142 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff); 2143 } 2144 2145 if (!IsSibcall) 2146 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2147 2148 SDValue RetAddrFrIdx; 2149 // Load return address for tail calls. 2150 if (isTailCall && FPDiff) 2151 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2152 Is64Bit, FPDiff, dl); 2153 2154 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2155 SmallVector<SDValue, 8> MemOpChains; 2156 SDValue StackPtr; 2157 2158 // Walk the register/memloc assignments, inserting copies/loads. In the case 2159 // of tail call optimization arguments are handle later. 2160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2161 CCValAssign &VA = ArgLocs[i]; 2162 EVT RegVT = VA.getLocVT(); 2163 SDValue Arg = OutVals[i]; 2164 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2165 bool isByVal = Flags.isByVal(); 2166 2167 // Promote the value if needed. 2168 switch (VA.getLocInfo()) { 2169 default: llvm_unreachable("Unknown loc info!"); 2170 case CCValAssign::Full: break; 2171 case CCValAssign::SExt: 2172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2173 break; 2174 case CCValAssign::ZExt: 2175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2176 break; 2177 case CCValAssign::AExt: 2178 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) { 2179 // Special case: passing MMX values in XMM registers. 2180 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2181 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2182 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2183 } else 2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2185 break; 2186 case CCValAssign::BCvt: 2187 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2188 break; 2189 case CCValAssign::Indirect: { 2190 // Store the argument. 2191 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2192 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2193 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2194 MachinePointerInfo::getFixedStack(FI), 2195 false, false, 0); 2196 Arg = SpillSlot; 2197 break; 2198 } 2199 } 2200 2201 if (VA.isRegLoc()) { 2202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2203 if (isVarArg && IsWin64) { 2204 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2205 // shadow reg if callee is a varargs function. 2206 unsigned ShadowReg = 0; 2207 switch (VA.getLocReg()) { 2208 case X86::XMM0: ShadowReg = X86::RCX; break; 2209 case X86::XMM1: ShadowReg = X86::RDX; break; 2210 case X86::XMM2: ShadowReg = X86::R8; break; 2211 case X86::XMM3: ShadowReg = X86::R9; break; 2212 } 2213 if (ShadowReg) 2214 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2215 } 2216 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2217 assert(VA.isMemLoc()); 2218 if (StackPtr.getNode() == 0) 2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy()); 2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2221 dl, DAG, VA, Flags)); 2222 } 2223 } 2224 2225 if (!MemOpChains.empty()) 2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2227 &MemOpChains[0], MemOpChains.size()); 2228 2229 // Build a sequence of copy-to-reg nodes chained together with token chain 2230 // and flag operands which copy the outgoing args into registers. 2231 SDValue InFlag; 2232 // Tail call byval lowering might overwrite argument registers so in case of 2233 // tail call optimization the copies to registers are lowered later. 2234 if (!isTailCall) 2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2237 RegsToPass[i].second, InFlag); 2238 InFlag = Chain.getValue(1); 2239 } 2240 2241 if (Subtarget->isPICStyleGOT()) { 2242 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2243 // GOT pointer. 2244 if (!isTailCall) { 2245 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX, 2246 DAG.getNode(X86ISD::GlobalBaseReg, 2247 DebugLoc(), getPointerTy()), 2248 InFlag); 2249 InFlag = Chain.getValue(1); 2250 } else { 2251 // If we are tail calling and generating PIC/GOT style code load the 2252 // address of the callee into ECX. The value in ecx is used as target of 2253 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2254 // for tail calls on PIC/GOT architectures. Normally we would just put the 2255 // address of GOT into ebx and then call target@PLT. But for tail calls 2256 // ebx would be restored (since ebx is callee saved) before jumping to the 2257 // target@PLT. 2258 2259 // Note: The actual moving to ECX is done further down. 2260 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2261 if (G && !G->getGlobal()->hasHiddenVisibility() && 2262 !G->getGlobal()->hasProtectedVisibility()) 2263 Callee = LowerGlobalAddress(Callee, DAG); 2264 else if (isa<ExternalSymbolSDNode>(Callee)) 2265 Callee = LowerExternalSymbol(Callee, DAG); 2266 } 2267 } 2268 2269 if (Is64Bit && isVarArg && !IsWin64) { 2270 // From AMD64 ABI document: 2271 // For calls that may call functions that use varargs or stdargs 2272 // (prototype-less calls or calls to functions containing ellipsis (...) in 2273 // the declaration) %al is used as hidden argument to specify the number 2274 // of SSE registers used. The contents of %al do not need to match exactly 2275 // the number of registers, but must be an ubound on the number of SSE 2276 // registers used and is in the range 0 - 8 inclusive. 2277 2278 // Count the number of XMM registers allocated. 2279 static const unsigned XMMArgRegs[] = { 2280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2282 }; 2283 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2284 assert((Subtarget->hasXMM() || !NumXMMRegs) 2285 && "SSE registers cannot be used when SSE is disabled"); 2286 2287 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, 2288 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag); 2289 InFlag = Chain.getValue(1); 2290 } 2291 2292 2293 // For tail calls lower the arguments to the 'real' stack slot. 2294 if (isTailCall) { 2295 // Force all the incoming stack arguments to be loaded from the stack 2296 // before any new outgoing arguments are stored to the stack, because the 2297 // outgoing stack slots may alias the incoming argument stack slots, and 2298 // the alias isn't otherwise explicit. This is slightly more conservative 2299 // than necessary, because it means that each store effectively depends 2300 // on every argument instead of just those arguments it would clobber. 2301 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2302 2303 SmallVector<SDValue, 8> MemOpChains2; 2304 SDValue FIN; 2305 int FI = 0; 2306 // Do not flag preceding copytoreg stuff together with the following stuff. 2307 InFlag = SDValue(); 2308 if (GuaranteedTailCallOpt) { 2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2310 CCValAssign &VA = ArgLocs[i]; 2311 if (VA.isRegLoc()) 2312 continue; 2313 assert(VA.isMemLoc()); 2314 SDValue Arg = OutVals[i]; 2315 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2316 // Create frame index. 2317 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2318 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2319 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2320 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2321 2322 if (Flags.isByVal()) { 2323 // Copy relative to framepointer. 2324 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2325 if (StackPtr.getNode() == 0) 2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, 2327 getPointerTy()); 2328 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2329 2330 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2331 ArgChain, 2332 Flags, DAG, dl)); 2333 } else { 2334 // Store relative to framepointer. 2335 MemOpChains2.push_back( 2336 DAG.getStore(ArgChain, dl, Arg, FIN, 2337 MachinePointerInfo::getFixedStack(FI), 2338 false, false, 0)); 2339 } 2340 } 2341 } 2342 2343 if (!MemOpChains2.empty()) 2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2345 &MemOpChains2[0], MemOpChains2.size()); 2346 2347 // Copy arguments to their registers. 2348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2349 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2350 RegsToPass[i].second, InFlag); 2351 InFlag = Chain.getValue(1); 2352 } 2353 InFlag =SDValue(); 2354 2355 // Store the return address to the appropriate stack slot. 2356 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit, 2357 FPDiff, dl); 2358 } 2359 2360 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2361 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2362 // In the 64-bit large code model, we have to make all calls 2363 // through a register, since the call instruction's 32-bit 2364 // pc-relative offset may not be large enough to hold the whole 2365 // address. 2366 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2367 // If the callee is a GlobalAddress node (quite common, every direct call 2368 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2369 // it. 2370 2371 // We should use extra load for direct calls to dllimported functions in 2372 // non-JIT mode. 2373 const GlobalValue *GV = G->getGlobal(); 2374 if (!GV->hasDLLImportLinkage()) { 2375 unsigned char OpFlags = 0; 2376 bool ExtraLoad = false; 2377 unsigned WrapperKind = ISD::DELETED_NODE; 2378 2379 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2380 // external symbols most go through the PLT in PIC mode. If the symbol 2381 // has hidden or protected visibility, or if it is static or local, then 2382 // we don't need to use the PLT - we can directly call it. 2383 if (Subtarget->isTargetELF() && 2384 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2385 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2386 OpFlags = X86II::MO_PLT; 2387 } else if (Subtarget->isPICStyleStubAny() && 2388 (GV->isDeclaration() || GV->isWeakForLinker()) && 2389 (!Subtarget->getTargetTriple().isMacOSX() || 2390 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2391 // PC-relative references to external symbols should go through $stub, 2392 // unless we're building with the leopard linker or later, which 2393 // automatically synthesizes these stubs. 2394 OpFlags = X86II::MO_DARWIN_STUB; 2395 } else if (Subtarget->isPICStyleRIPRel() && 2396 isa<Function>(GV) && 2397 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) { 2398 // If the function is marked as non-lazy, generate an indirect call 2399 // which loads from the GOT directly. This avoids runtime overhead 2400 // at the cost of eager binding (and one extra byte of encoding). 2401 OpFlags = X86II::MO_GOTPCREL; 2402 WrapperKind = X86ISD::WrapperRIP; 2403 ExtraLoad = true; 2404 } 2405 2406 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2407 G->getOffset(), OpFlags); 2408 2409 // Add a wrapper if needed. 2410 if (WrapperKind != ISD::DELETED_NODE) 2411 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2412 // Add extra indirection if needed. 2413 if (ExtraLoad) 2414 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2415 MachinePointerInfo::getGOT(), 2416 false, false, false, 0); 2417 } 2418 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2419 unsigned char OpFlags = 0; 2420 2421 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2422 // external symbols should go through the PLT. 2423 if (Subtarget->isTargetELF() && 2424 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2425 OpFlags = X86II::MO_PLT; 2426 } else if (Subtarget->isPICStyleStubAny() && 2427 (!Subtarget->getTargetTriple().isMacOSX() || 2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2429 // PC-relative references to external symbols should go through $stub, 2430 // unless we're building with the leopard linker or later, which 2431 // automatically synthesizes these stubs. 2432 OpFlags = X86II::MO_DARWIN_STUB; 2433 } 2434 2435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2436 OpFlags); 2437 } 2438 2439 // Returns a chain & a flag for retval copy to use. 2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2441 SmallVector<SDValue, 8> Ops; 2442 2443 if (!IsSibcall && isTailCall) { 2444 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2445 DAG.getIntPtrConstant(0, true), InFlag); 2446 InFlag = Chain.getValue(1); 2447 } 2448 2449 Ops.push_back(Chain); 2450 Ops.push_back(Callee); 2451 2452 if (isTailCall) 2453 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2454 2455 // Add argument registers to the end of the list so that they are known live 2456 // into the call. 2457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2458 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2459 RegsToPass[i].second.getValueType())); 2460 2461 // Add an implicit use GOT pointer in EBX. 2462 if (!isTailCall && Subtarget->isPICStyleGOT()) 2463 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy())); 2464 2465 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions. 2466 if (Is64Bit && isVarArg && !IsWin64) 2467 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8)); 2468 2469 if (InFlag.getNode()) 2470 Ops.push_back(InFlag); 2471 2472 if (isTailCall) { 2473 // We used to do: 2474 //// If this is the first return lowered for this function, add the regs 2475 //// to the liveout set for the function. 2476 // This isn't right, although it's probably harmless on x86; liveouts 2477 // should be computed from returns not tail calls. Consider a void 2478 // function making a tail call to a function returning int. 2479 return DAG.getNode(X86ISD::TC_RETURN, dl, 2480 NodeTys, &Ops[0], Ops.size()); 2481 } 2482 2483 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2484 InFlag = Chain.getValue(1); 2485 2486 // Create the CALLSEQ_END node. 2487 unsigned NumBytesForCalleeToPush; 2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) 2489 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2490 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet) 2491 // If this is a call to a struct-return function, the callee 2492 // pops the hidden struct pointer, so we have to push it back. 2493 // This is common for Darwin/X86, Linux & Mingw32 targets. 2494 NumBytesForCalleeToPush = 4; 2495 else 2496 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2497 2498 // Returns a flag for retval copy to use. 2499 if (!IsSibcall) { 2500 Chain = DAG.getCALLSEQ_END(Chain, 2501 DAG.getIntPtrConstant(NumBytes, true), 2502 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2503 true), 2504 InFlag); 2505 InFlag = Chain.getValue(1); 2506 } 2507 2508 // Handle result values, copying them out of physregs into vregs that we 2509 // return. 2510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2511 Ins, dl, DAG, InVals); 2512} 2513 2514 2515//===----------------------------------------------------------------------===// 2516// Fast Calling Convention (tail call) implementation 2517//===----------------------------------------------------------------------===// 2518 2519// Like std call, callee cleans arguments, convention except that ECX is 2520// reserved for storing the tail called function address. Only 2 registers are 2521// free for argument passing (inreg). Tail call optimization is performed 2522// provided: 2523// * tailcallopt is enabled 2524// * caller/callee are fastcc 2525// On X86_64 architecture with GOT-style position independent code only local 2526// (within module) calls are supported at the moment. 2527// To keep the stack aligned according to platform abi the function 2528// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2529// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2530// If a tail called function callee has more arguments than the caller the 2531// caller needs to make sure that there is room to move the RETADDR to. This is 2532// achieved by reserving an area the size of the argument delta right after the 2533// original REtADDR, but before the saved framepointer or the spilled registers 2534// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2535// stack layout: 2536// arg1 2537// arg2 2538// RETADDR 2539// [ new RETADDR 2540// move area ] 2541// (possible EBP) 2542// ESI 2543// EDI 2544// local1 .. 2545 2546/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2547/// for a 16 byte align requirement. 2548unsigned 2549X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2550 SelectionDAG& DAG) const { 2551 MachineFunction &MF = DAG.getMachineFunction(); 2552 const TargetMachine &TM = MF.getTarget(); 2553 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2554 unsigned StackAlignment = TFI.getStackAlignment(); 2555 uint64_t AlignMask = StackAlignment - 1; 2556 int64_t Offset = StackSize; 2557 uint64_t SlotSize = TD->getPointerSize(); 2558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2559 // Number smaller than 12 so just add the difference. 2560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2561 } else { 2562 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2563 Offset = ((~AlignMask) & Offset) + StackAlignment + 2564 (StackAlignment-SlotSize); 2565 } 2566 return Offset; 2567} 2568 2569/// MatchingStackOffset - Return true if the given stack call argument is 2570/// already available in the same position (relatively) of the caller's 2571/// incoming argument stack. 2572static 2573bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2574 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2575 const X86InstrInfo *TII) { 2576 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2577 int FI = INT_MAX; 2578 if (Arg.getOpcode() == ISD::CopyFromReg) { 2579 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2580 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2581 return false; 2582 MachineInstr *Def = MRI->getVRegDef(VR); 2583 if (!Def) 2584 return false; 2585 if (!Flags.isByVal()) { 2586 if (!TII->isLoadFromStackSlot(Def, FI)) 2587 return false; 2588 } else { 2589 unsigned Opcode = Def->getOpcode(); 2590 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2591 Def->getOperand(1).isFI()) { 2592 FI = Def->getOperand(1).getIndex(); 2593 Bytes = Flags.getByValSize(); 2594 } else 2595 return false; 2596 } 2597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2598 if (Flags.isByVal()) 2599 // ByVal argument is passed in as a pointer but it's now being 2600 // dereferenced. e.g. 2601 // define @foo(%struct.X* %A) { 2602 // tail call @bar(%struct.X* byval %A) 2603 // } 2604 return false; 2605 SDValue Ptr = Ld->getBasePtr(); 2606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2607 if (!FINode) 2608 return false; 2609 FI = FINode->getIndex(); 2610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2612 FI = FINode->getIndex(); 2613 Bytes = Flags.getByValSize(); 2614 } else 2615 return false; 2616 2617 assert(FI != INT_MAX); 2618 if (!MFI->isFixedObjectIndex(FI)) 2619 return false; 2620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2621} 2622 2623/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2624/// for tail call optimization. Targets which want to do tail call 2625/// optimization should implement this function. 2626bool 2627X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2628 CallingConv::ID CalleeCC, 2629 bool isVarArg, 2630 bool isCalleeStructRet, 2631 bool isCallerStructRet, 2632 const SmallVectorImpl<ISD::OutputArg> &Outs, 2633 const SmallVectorImpl<SDValue> &OutVals, 2634 const SmallVectorImpl<ISD::InputArg> &Ins, 2635 SelectionDAG& DAG) const { 2636 if (!IsTailCallConvention(CalleeCC) && 2637 CalleeCC != CallingConv::C) 2638 return false; 2639 2640 // If -tailcallopt is specified, make fastcc functions tail-callable. 2641 const MachineFunction &MF = DAG.getMachineFunction(); 2642 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2643 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2644 bool CCMatch = CallerCC == CalleeCC; 2645 2646 if (GuaranteedTailCallOpt) { 2647 if (IsTailCallConvention(CalleeCC) && CCMatch) 2648 return true; 2649 return false; 2650 } 2651 2652 // Look for obvious safe cases to perform tail call optimization that do not 2653 // require ABI changes. This is what gcc calls sibcall. 2654 2655 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2656 // emit a special epilogue. 2657 if (RegInfo->needsStackRealignment(MF)) 2658 return false; 2659 2660 // Also avoid sibcall optimization if either caller or callee uses struct 2661 // return semantics. 2662 if (isCalleeStructRet || isCallerStructRet) 2663 return false; 2664 2665 // An stdcall caller is expected to clean up its arguments; the callee 2666 // isn't going to do that. 2667 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2668 return false; 2669 2670 // Do not sibcall optimize vararg calls unless all arguments are passed via 2671 // registers. 2672 if (isVarArg && !Outs.empty()) { 2673 2674 // Optimizing for varargs on Win64 is unlikely to be safe without 2675 // additional testing. 2676 if (Subtarget->isTargetWin64()) 2677 return false; 2678 2679 SmallVector<CCValAssign, 16> ArgLocs; 2680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2681 getTargetMachine(), ArgLocs, *DAG.getContext()); 2682 2683 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2685 if (!ArgLocs[i].isRegLoc()) 2686 return false; 2687 } 2688 2689 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack. 2690 // Therefore if it's not used by the call it is not safe to optimize this into 2691 // a sibcall. 2692 bool Unused = false; 2693 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2694 if (!Ins[i].Used) { 2695 Unused = true; 2696 break; 2697 } 2698 } 2699 if (Unused) { 2700 SmallVector<CCValAssign, 16> RVLocs; 2701 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2702 getTargetMachine(), RVLocs, *DAG.getContext()); 2703 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2704 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2705 CCValAssign &VA = RVLocs[i]; 2706 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2707 return false; 2708 } 2709 } 2710 2711 // If the calling conventions do not match, then we'd better make sure the 2712 // results are returned in the same way as what the caller expects. 2713 if (!CCMatch) { 2714 SmallVector<CCValAssign, 16> RVLocs1; 2715 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2716 getTargetMachine(), RVLocs1, *DAG.getContext()); 2717 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2718 2719 SmallVector<CCValAssign, 16> RVLocs2; 2720 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2721 getTargetMachine(), RVLocs2, *DAG.getContext()); 2722 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2723 2724 if (RVLocs1.size() != RVLocs2.size()) 2725 return false; 2726 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2727 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2728 return false; 2729 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2730 return false; 2731 if (RVLocs1[i].isRegLoc()) { 2732 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2733 return false; 2734 } else { 2735 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2736 return false; 2737 } 2738 } 2739 } 2740 2741 // If the callee takes no arguments then go on to check the results of the 2742 // call. 2743 if (!Outs.empty()) { 2744 // Check if stack adjustment is needed. For now, do not do this if any 2745 // argument is passed on the stack. 2746 SmallVector<CCValAssign, 16> ArgLocs; 2747 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2748 getTargetMachine(), ArgLocs, *DAG.getContext()); 2749 2750 // Allocate shadow area for Win64 2751 if (Subtarget->isTargetWin64()) { 2752 CCInfo.AllocateStack(32, 8); 2753 } 2754 2755 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2756 if (CCInfo.getNextStackOffset()) { 2757 MachineFunction &MF = DAG.getMachineFunction(); 2758 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2759 return false; 2760 2761 // Check if the arguments are already laid out in the right way as 2762 // the caller's fixed stack objects. 2763 MachineFrameInfo *MFI = MF.getFrameInfo(); 2764 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2765 const X86InstrInfo *TII = 2766 ((X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2768 CCValAssign &VA = ArgLocs[i]; 2769 SDValue Arg = OutVals[i]; 2770 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2771 if (VA.getLocInfo() == CCValAssign::Indirect) 2772 return false; 2773 if (!VA.isRegLoc()) { 2774 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2775 MFI, MRI, TII)) 2776 return false; 2777 } 2778 } 2779 } 2780 2781 // If the tailcall address may be in a register, then make sure it's 2782 // possible to register allocate for it. In 32-bit, the call address can 2783 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2784 // callee-saved registers are restored. These happen to be the same 2785 // registers used to pass 'inreg' arguments so watch out for those. 2786 if (!Subtarget->is64Bit() && 2787 !isa<GlobalAddressSDNode>(Callee) && 2788 !isa<ExternalSymbolSDNode>(Callee)) { 2789 unsigned NumInRegs = 0; 2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2791 CCValAssign &VA = ArgLocs[i]; 2792 if (!VA.isRegLoc()) 2793 continue; 2794 unsigned Reg = VA.getLocReg(); 2795 switch (Reg) { 2796 default: break; 2797 case X86::EAX: case X86::EDX: case X86::ECX: 2798 if (++NumInRegs == 3) 2799 return false; 2800 break; 2801 } 2802 } 2803 } 2804 } 2805 2806 return true; 2807} 2808 2809FastISel * 2810X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const { 2811 return X86::createFastISel(funcInfo); 2812} 2813 2814 2815//===----------------------------------------------------------------------===// 2816// Other Lowering Hooks 2817//===----------------------------------------------------------------------===// 2818 2819static bool MayFoldLoad(SDValue Op) { 2820 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2821} 2822 2823static bool MayFoldIntoStore(SDValue Op) { 2824 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2825} 2826 2827static bool isTargetShuffle(unsigned Opcode) { 2828 switch(Opcode) { 2829 default: return false; 2830 case X86ISD::PSHUFD: 2831 case X86ISD::PSHUFHW: 2832 case X86ISD::PSHUFLW: 2833 case X86ISD::SHUFPD: 2834 case X86ISD::PALIGN: 2835 case X86ISD::SHUFPS: 2836 case X86ISD::MOVLHPS: 2837 case X86ISD::MOVLHPD: 2838 case X86ISD::MOVHLPS: 2839 case X86ISD::MOVLPS: 2840 case X86ISD::MOVLPD: 2841 case X86ISD::MOVSHDUP: 2842 case X86ISD::MOVSLDUP: 2843 case X86ISD::MOVDDUP: 2844 case X86ISD::MOVSS: 2845 case X86ISD::MOVSD: 2846 case X86ISD::UNPCKLP: 2847 case X86ISD::PUNPCKL: 2848 case X86ISD::UNPCKHP: 2849 case X86ISD::PUNPCKH: 2850 case X86ISD::VPERMILP: 2851 case X86ISD::VPERM2X128: 2852 return true; 2853 } 2854 return false; 2855} 2856 2857static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2858 SDValue V1, SelectionDAG &DAG) { 2859 switch(Opc) { 2860 default: llvm_unreachable("Unknown x86 shuffle node"); 2861 case X86ISD::MOVSHDUP: 2862 case X86ISD::MOVSLDUP: 2863 case X86ISD::MOVDDUP: 2864 return DAG.getNode(Opc, dl, VT, V1); 2865 } 2866 2867 return SDValue(); 2868} 2869 2870static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2871 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) { 2872 switch(Opc) { 2873 default: llvm_unreachable("Unknown x86 shuffle node"); 2874 case X86ISD::PSHUFD: 2875 case X86ISD::PSHUFHW: 2876 case X86ISD::PSHUFLW: 2877 case X86ISD::VPERMILP: 2878 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 2879 } 2880 2881 return SDValue(); 2882} 2883 2884static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2885 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) { 2886 switch(Opc) { 2887 default: llvm_unreachable("Unknown x86 shuffle node"); 2888 case X86ISD::PALIGN: 2889 case X86ISD::SHUFPD: 2890 case X86ISD::SHUFPS: 2891 case X86ISD::VPERM2X128: 2892 return DAG.getNode(Opc, dl, VT, V1, V2, 2893 DAG.getConstant(TargetMask, MVT::i8)); 2894 } 2895 return SDValue(); 2896} 2897 2898static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 2899 SDValue V1, SDValue V2, SelectionDAG &DAG) { 2900 switch(Opc) { 2901 default: llvm_unreachable("Unknown x86 shuffle node"); 2902 case X86ISD::MOVLHPS: 2903 case X86ISD::MOVLHPD: 2904 case X86ISD::MOVHLPS: 2905 case X86ISD::MOVLPS: 2906 case X86ISD::MOVLPD: 2907 case X86ISD::MOVSS: 2908 case X86ISD::MOVSD: 2909 case X86ISD::UNPCKLP: 2910 case X86ISD::PUNPCKL: 2911 case X86ISD::UNPCKHP: 2912 case X86ISD::PUNPCKH: 2913 return DAG.getNode(Opc, dl, VT, V1, V2); 2914 } 2915 return SDValue(); 2916} 2917 2918SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 2919 MachineFunction &MF = DAG.getMachineFunction(); 2920 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2921 int ReturnAddrIndex = FuncInfo->getRAIndex(); 2922 2923 if (ReturnAddrIndex == 0) { 2924 // Set up a frame object for the return address. 2925 uint64_t SlotSize = TD->getPointerSize(); 2926 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 2927 false); 2928 FuncInfo->setRAIndex(ReturnAddrIndex); 2929 } 2930 2931 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 2932} 2933 2934 2935bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 2936 bool hasSymbolicDisplacement) { 2937 // Offset should fit into 32 bit immediate field. 2938 if (!isInt<32>(Offset)) 2939 return false; 2940 2941 // If we don't have a symbolic displacement - we don't have any extra 2942 // restrictions. 2943 if (!hasSymbolicDisplacement) 2944 return true; 2945 2946 // FIXME: Some tweaks might be needed for medium code model. 2947 if (M != CodeModel::Small && M != CodeModel::Kernel) 2948 return false; 2949 2950 // For small code model we assume that latest object is 16MB before end of 31 2951 // bits boundary. We may also accept pretty large negative constants knowing 2952 // that all objects are in the positive half of address space. 2953 if (M == CodeModel::Small && Offset < 16*1024*1024) 2954 return true; 2955 2956 // For kernel code model we know that all object resist in the negative half 2957 // of 32bits address space. We may not accept negative offsets, since they may 2958 // be just off and we may accept pretty large positive ones. 2959 if (M == CodeModel::Kernel && Offset > 0) 2960 return true; 2961 2962 return false; 2963} 2964 2965/// isCalleePop - Determines whether the callee is required to pop its 2966/// own arguments. Callee pop is necessary to support tail calls. 2967bool X86::isCalleePop(CallingConv::ID CallingConv, 2968 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 2969 if (IsVarArg) 2970 return false; 2971 2972 switch (CallingConv) { 2973 default: 2974 return false; 2975 case CallingConv::X86_StdCall: 2976 return !is64Bit; 2977 case CallingConv::X86_FastCall: 2978 return !is64Bit; 2979 case CallingConv::X86_ThisCall: 2980 return !is64Bit; 2981 case CallingConv::Fast: 2982 return TailCallOpt; 2983 case CallingConv::GHC: 2984 return TailCallOpt; 2985 } 2986} 2987 2988/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 2989/// specific condition code, returning the condition code and the LHS/RHS of the 2990/// comparison to make. 2991static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 2992 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 2993 if (!isFP) { 2994 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 2995 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 2996 // X > -1 -> X == 0, jump !sign. 2997 RHS = DAG.getConstant(0, RHS.getValueType()); 2998 return X86::COND_NS; 2999 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3000 // X < 0 -> X == 0, jump on sign. 3001 return X86::COND_S; 3002 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3003 // X < 1 -> X <= 0 3004 RHS = DAG.getConstant(0, RHS.getValueType()); 3005 return X86::COND_LE; 3006 } 3007 } 3008 3009 switch (SetCCOpcode) { 3010 default: llvm_unreachable("Invalid integer condition!"); 3011 case ISD::SETEQ: return X86::COND_E; 3012 case ISD::SETGT: return X86::COND_G; 3013 case ISD::SETGE: return X86::COND_GE; 3014 case ISD::SETLT: return X86::COND_L; 3015 case ISD::SETLE: return X86::COND_LE; 3016 case ISD::SETNE: return X86::COND_NE; 3017 case ISD::SETULT: return X86::COND_B; 3018 case ISD::SETUGT: return X86::COND_A; 3019 case ISD::SETULE: return X86::COND_BE; 3020 case ISD::SETUGE: return X86::COND_AE; 3021 } 3022 } 3023 3024 // First determine if it is required or is profitable to flip the operands. 3025 3026 // If LHS is a foldable load, but RHS is not, flip the condition. 3027 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3028 !ISD::isNON_EXTLoad(RHS.getNode())) { 3029 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3030 std::swap(LHS, RHS); 3031 } 3032 3033 switch (SetCCOpcode) { 3034 default: break; 3035 case ISD::SETOLT: 3036 case ISD::SETOLE: 3037 case ISD::SETUGT: 3038 case ISD::SETUGE: 3039 std::swap(LHS, RHS); 3040 break; 3041 } 3042 3043 // On a floating point condition, the flags are set as follows: 3044 // ZF PF CF op 3045 // 0 | 0 | 0 | X > Y 3046 // 0 | 0 | 1 | X < Y 3047 // 1 | 0 | 0 | X == Y 3048 // 1 | 1 | 1 | unordered 3049 switch (SetCCOpcode) { 3050 default: llvm_unreachable("Condcode should be pre-legalized away"); 3051 case ISD::SETUEQ: 3052 case ISD::SETEQ: return X86::COND_E; 3053 case ISD::SETOLT: // flipped 3054 case ISD::SETOGT: 3055 case ISD::SETGT: return X86::COND_A; 3056 case ISD::SETOLE: // flipped 3057 case ISD::SETOGE: 3058 case ISD::SETGE: return X86::COND_AE; 3059 case ISD::SETUGT: // flipped 3060 case ISD::SETULT: 3061 case ISD::SETLT: return X86::COND_B; 3062 case ISD::SETUGE: // flipped 3063 case ISD::SETULE: 3064 case ISD::SETLE: return X86::COND_BE; 3065 case ISD::SETONE: 3066 case ISD::SETNE: return X86::COND_NE; 3067 case ISD::SETUO: return X86::COND_P; 3068 case ISD::SETO: return X86::COND_NP; 3069 case ISD::SETOEQ: 3070 case ISD::SETUNE: return X86::COND_INVALID; 3071 } 3072} 3073 3074/// hasFPCMov - is there a floating point cmov for the specific X86 condition 3075/// code. Current x86 isa includes the following FP cmov instructions: 3076/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3077static bool hasFPCMov(unsigned X86CC) { 3078 switch (X86CC) { 3079 default: 3080 return false; 3081 case X86::COND_B: 3082 case X86::COND_BE: 3083 case X86::COND_E: 3084 case X86::COND_P: 3085 case X86::COND_A: 3086 case X86::COND_AE: 3087 case X86::COND_NE: 3088 case X86::COND_NP: 3089 return true; 3090 } 3091} 3092 3093/// isFPImmLegal - Returns true if the target can instruction select the 3094/// specified FP immediate natively. If false, the legalizer will 3095/// materialize the FP immediate as a load from a constant pool. 3096bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3097 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3098 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3099 return true; 3100 } 3101 return false; 3102} 3103 3104/// isUndefOrInRange - Return true if Val is undef or if its value falls within 3105/// the specified range (L, H]. 3106static bool isUndefOrInRange(int Val, int Low, int Hi) { 3107 return (Val < 0) || (Val >= Low && Val < Hi); 3108} 3109 3110/// isUndefOrInRange - Return true if every element in Mask, begining 3111/// from position Pos and ending in Pos+Size, falls within the specified 3112/// range (L, L+Pos]. or is undef. 3113static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask, 3114 int Pos, int Size, int Low, int Hi) { 3115 for (int i = Pos, e = Pos+Size; i != e; ++i) 3116 if (!isUndefOrInRange(Mask[i], Low, Hi)) 3117 return false; 3118 return true; 3119} 3120 3121/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3122/// specified value. 3123static bool isUndefOrEqual(int Val, int CmpVal) { 3124 if (Val < 0 || Val == CmpVal) 3125 return true; 3126 return false; 3127} 3128 3129/// isSequentialOrUndefInRange - Return true if every element in Mask, begining 3130/// from position Pos and ending in Pos+Size, falls within the specified 3131/// sequential range (L, L+Pos]. or is undef. 3132static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask, 3133 int Pos, int Size, int Low) { 3134 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3135 if (!isUndefOrEqual(Mask[i], Low)) 3136 return false; 3137 return true; 3138} 3139 3140/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3141/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3142/// the second operand. 3143static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3144 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3145 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3146 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3147 return (Mask[0] < 2 && Mask[1] < 2); 3148 return false; 3149} 3150 3151bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) { 3152 SmallVector<int, 8> M; 3153 N->getMask(M); 3154 return ::isPSHUFDMask(M, N->getValueType(0)); 3155} 3156 3157/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3158/// is suitable for input to PSHUFHW. 3159static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3160 if (VT != MVT::v8i16) 3161 return false; 3162 3163 // Lower quadword copied in order or undef. 3164 for (int i = 0; i != 4; ++i) 3165 if (Mask[i] >= 0 && Mask[i] != i) 3166 return false; 3167 3168 // Upper quadword shuffled. 3169 for (int i = 4; i != 8; ++i) 3170 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7)) 3171 return false; 3172 3173 return true; 3174} 3175 3176bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) { 3177 SmallVector<int, 8> M; 3178 N->getMask(M); 3179 return ::isPSHUFHWMask(M, N->getValueType(0)); 3180} 3181 3182/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3183/// is suitable for input to PSHUFLW. 3184static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3185 if (VT != MVT::v8i16) 3186 return false; 3187 3188 // Upper quadword copied in order. 3189 for (int i = 4; i != 8; ++i) 3190 if (Mask[i] >= 0 && Mask[i] != i) 3191 return false; 3192 3193 // Lower quadword shuffled. 3194 for (int i = 0; i != 4; ++i) 3195 if (Mask[i] >= 4) 3196 return false; 3197 3198 return true; 3199} 3200 3201bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) { 3202 SmallVector<int, 8> M; 3203 N->getMask(M); 3204 return ::isPSHUFLWMask(M, N->getValueType(0)); 3205} 3206 3207/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3208/// is suitable for input to PALIGNR. 3209static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT, 3210 bool hasSSSE3OrAVX) { 3211 int i, e = VT.getVectorNumElements(); 3212 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64) 3213 return false; 3214 3215 // Do not handle v2i64 / v2f64 shuffles with palignr. 3216 if (e < 4 || !hasSSSE3OrAVX) 3217 return false; 3218 3219 for (i = 0; i != e; ++i) 3220 if (Mask[i] >= 0) 3221 break; 3222 3223 // All undef, not a palignr. 3224 if (i == e) 3225 return false; 3226 3227 // Make sure we're shifting in the right direction. 3228 if (Mask[i] <= i) 3229 return false; 3230 3231 int s = Mask[i] - i; 3232 3233 // Check the rest of the elements to see if they are consecutive. 3234 for (++i; i != e; ++i) { 3235 int m = Mask[i]; 3236 if (m >= 0 && m != s+i) 3237 return false; 3238 } 3239 return true; 3240} 3241 3242/// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand 3243/// specifies a shuffle of elements that is suitable for input to 256-bit 3244/// VSHUFPSY. 3245static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT, 3246 bool HasAVX) { 3247 int NumElems = VT.getVectorNumElements(); 3248 3249 if (!HasAVX || VT.getSizeInBits() != 256) 3250 return false; 3251 3252 if (NumElems != 4 && NumElems != 8) 3253 return false; 3254 3255 // VSHUFPSY divides the resulting vector into 4 chunks. 3256 // The sources are also splitted into 4 chunks, and each destination 3257 // chunk must come from a different source chunk. 3258 // 3259 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3260 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3261 // 3262 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3263 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3264 // 3265 // VSHUFPDY divides the resulting vector into 4 chunks. 3266 // The sources are also splitted into 4 chunks, and each destination 3267 // chunk must come from a different source chunk. 3268 // 3269 // SRC1 => X3 X2 X1 X0 3270 // SRC2 => Y3 Y2 Y1 Y0 3271 // 3272 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3273 // 3274 int QuarterSize = NumElems/4; 3275 int HalfSize = QuarterSize*2; 3276 for (int i = 0; i < QuarterSize; ++i) 3277 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3278 return false; 3279 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3280 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3281 return false; 3282 3283 // For VSHUFPSY, the mask of the second half must be the same as the first 3284 // but with the appropriate offsets. This works in the same way as 3285 // VPERMILPS works with masks. 3286 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) { 3287 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3288 return false; 3289 if (NumElems == 4) 3290 continue; 3291 // VSHUFPSY handling 3292 int FstHalfIdx = i-HalfSize; 3293 if (Mask[FstHalfIdx] < 0) 3294 continue; 3295 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3296 return false; 3297 } 3298 for (int i = QuarterSize*3; i < NumElems; ++i) { 3299 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3300 return false; 3301 int FstHalfIdx = i-HalfSize; 3302 if (NumElems == 4) 3303 continue; 3304 // VSHUFPSY handling 3305 if (Mask[FstHalfIdx] < 0) 3306 continue; 3307 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3308 return false; 3309 } 3310 3311 return true; 3312} 3313 3314/// isCommutedVSHUFP() - Returns true if the shuffle mask is exactly 3315/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3316/// half elements to come from vector 1 (which would equal the dest.) and 3317/// the upper half to come from vector 2. 3318static bool isCommutedVSHUFPY(ShuffleVectorSDNode *N, bool HasAVX) { 3319 EVT VT = N->getValueType(0); 3320 int NumElems = VT.getVectorNumElements(); 3321 SmallVector<int, 8> Mask; 3322 N->getMask(Mask); 3323 3324 if (!HasAVX || VT.getSizeInBits() != 256) 3325 return false; 3326 3327 if (NumElems != 4 && NumElems != 8) 3328 return false; 3329 3330 // VSHUFPSY divides the resulting vector into 4 chunks. 3331 // The sources are also splitted into 4 chunks, and each destination 3332 // chunk must come from a different source chunk. 3333 // 3334 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3335 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3336 // 3337 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3338 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3339 // 3340 // VSHUFPDY divides the resulting vector into 4 chunks. 3341 // The sources are also splitted into 4 chunks, and each destination 3342 // chunk must come from a different source chunk. 3343 // 3344 // SRC1 => X3 X2 X1 X0 3345 // SRC2 => Y3 Y2 Y1 Y0 3346 // 3347 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3348 // 3349 int QuarterSize = NumElems/4; 3350 int HalfSize = QuarterSize*2; 3351 for (int i = 0; i < QuarterSize; ++i) 3352 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize)) 3353 return false; 3354 for (int i = QuarterSize; i < QuarterSize*2; ++i) 3355 if (!isUndefOrInRange(Mask[i], 0, HalfSize)) 3356 return false; 3357 3358 // For VSHUFPSY, the mask of the second half must be the same as the first 3359 // but with the appropriate offsets. This works in the same way as 3360 // VPERMILPS works with masks. 3361 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) { 3362 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2)) 3363 return false; 3364 if (NumElems == 4) 3365 continue; 3366 // VSHUFPSY handling 3367 int FstHalfIdx = i-HalfSize; 3368 if (Mask[FstHalfIdx] < 0) 3369 continue; 3370 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3371 return false; 3372 } 3373 for (int i = QuarterSize*3; i < NumElems; ++i) { 3374 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems)) 3375 return false; 3376 if (NumElems == 4) 3377 continue; 3378 // VSHUFPSY handling 3379 int FstHalfIdx = i-HalfSize; 3380 if (Mask[FstHalfIdx] < 0) 3381 continue; 3382 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize)) 3383 return false; 3384 } 3385 3386 return true; 3387} 3388 3389/// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle 3390/// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions. 3391static unsigned getShuffleVSHUFPYImmediate(SDNode *N) { 3392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3393 EVT VT = SVOp->getValueType(0); 3394 int NumElems = VT.getVectorNumElements(); 3395 3396 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types"); 3397 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types"); 3398 3399 int HalfSize = NumElems/2; 3400 unsigned Mul = (NumElems == 8) ? 2 : 1; 3401 unsigned Mask = 0; 3402 for (int i = 0; i != NumElems; ++i) { 3403 int Elt = SVOp->getMaskElt(i); 3404 if (Elt < 0) 3405 continue; 3406 Elt %= HalfSize; 3407 unsigned Shamt = i; 3408 // For VSHUFPSY, the mask of the first half must be equal to the second one. 3409 if (NumElems == 8) Shamt %= HalfSize; 3410 Mask |= Elt << (Shamt*Mul); 3411 } 3412 3413 return Mask; 3414} 3415 3416/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3417/// the two vector operands have swapped position. 3418static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) { 3419 unsigned NumElems = VT.getVectorNumElements(); 3420 for (unsigned i = 0; i != NumElems; ++i) { 3421 int idx = Mask[i]; 3422 if (idx < 0) 3423 continue; 3424 else if (idx < (int)NumElems) 3425 Mask[i] = idx + NumElems; 3426 else 3427 Mask[i] = idx - NumElems; 3428 } 3429} 3430 3431/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3432/// specifies a shuffle of elements that is suitable for input to 128-bit 3433/// SHUFPS and SHUFPD. 3434static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3435 int NumElems = VT.getVectorNumElements(); 3436 3437 if (VT.getSizeInBits() != 128) 3438 return false; 3439 3440 if (NumElems != 2 && NumElems != 4) 3441 return false; 3442 3443 int Half = NumElems / 2; 3444 for (int i = 0; i < Half; ++i) 3445 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3446 return false; 3447 for (int i = Half; i < NumElems; ++i) 3448 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3449 return false; 3450 3451 return true; 3452} 3453 3454bool X86::isSHUFPMask(ShuffleVectorSDNode *N) { 3455 SmallVector<int, 8> M; 3456 N->getMask(M); 3457 return ::isSHUFPMask(M, N->getValueType(0)); 3458} 3459 3460/// isCommutedSHUFPMask - Returns true if the shuffle mask is exactly 3461/// the reverse of what x86 shuffles want. x86 shuffles requires the lower 3462/// half elements to come from vector 1 (which would equal the dest.) and 3463/// the upper half to come from vector 2. 3464static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3465 int NumElems = VT.getVectorNumElements(); 3466 3467 if (NumElems != 2 && NumElems != 4) 3468 return false; 3469 3470 int Half = NumElems / 2; 3471 for (int i = 0; i < Half; ++i) 3472 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2)) 3473 return false; 3474 for (int i = Half; i < NumElems; ++i) 3475 if (!isUndefOrInRange(Mask[i], 0, NumElems)) 3476 return false; 3477 return true; 3478} 3479 3480static bool isCommutedSHUFP(ShuffleVectorSDNode *N) { 3481 SmallVector<int, 8> M; 3482 N->getMask(M); 3483 return isCommutedSHUFPMask(M, N->getValueType(0)); 3484} 3485 3486/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3487/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3488bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) { 3489 EVT VT = N->getValueType(0); 3490 unsigned NumElems = VT.getVectorNumElements(); 3491 3492 if (VT.getSizeInBits() != 128) 3493 return false; 3494 3495 if (NumElems != 4) 3496 return false; 3497 3498 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3499 return isUndefOrEqual(N->getMaskElt(0), 6) && 3500 isUndefOrEqual(N->getMaskElt(1), 7) && 3501 isUndefOrEqual(N->getMaskElt(2), 2) && 3502 isUndefOrEqual(N->getMaskElt(3), 3); 3503} 3504 3505/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3506/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3507/// <2, 3, 2, 3> 3508bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) { 3509 EVT VT = N->getValueType(0); 3510 unsigned NumElems = VT.getVectorNumElements(); 3511 3512 if (VT.getSizeInBits() != 128) 3513 return false; 3514 3515 if (NumElems != 4) 3516 return false; 3517 3518 return isUndefOrEqual(N->getMaskElt(0), 2) && 3519 isUndefOrEqual(N->getMaskElt(1), 3) && 3520 isUndefOrEqual(N->getMaskElt(2), 2) && 3521 isUndefOrEqual(N->getMaskElt(3), 3); 3522} 3523 3524/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3525/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3526bool X86::isMOVLPMask(ShuffleVectorSDNode *N) { 3527 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3528 3529 if (NumElems != 2 && NumElems != 4) 3530 return false; 3531 3532 for (unsigned i = 0; i < NumElems/2; ++i) 3533 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems)) 3534 return false; 3535 3536 for (unsigned i = NumElems/2; i < NumElems; ++i) 3537 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3538 return false; 3539 3540 return true; 3541} 3542 3543/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3544/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3545bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) { 3546 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 3547 3548 if ((NumElems != 2 && NumElems != 4) 3549 || N->getValueType(0).getSizeInBits() > 128) 3550 return false; 3551 3552 for (unsigned i = 0; i < NumElems/2; ++i) 3553 if (!isUndefOrEqual(N->getMaskElt(i), i)) 3554 return false; 3555 3556 for (unsigned i = 0; i < NumElems/2; ++i) 3557 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems)) 3558 return false; 3559 3560 return true; 3561} 3562 3563/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3564/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3565static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3566 bool HasAVX2, bool V2IsSplat = false) { 3567 int NumElts = VT.getVectorNumElements(); 3568 3569 assert((VT.is128BitVector() || VT.is256BitVector()) && 3570 "Unsupported vector type for unpckh"); 3571 3572 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3573 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3574 return false; 3575 3576 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3577 // independently on 128-bit lanes. 3578 unsigned NumLanes = VT.getSizeInBits()/128; 3579 unsigned NumLaneElts = NumElts/NumLanes; 3580 3581 unsigned Start = 0; 3582 unsigned End = NumLaneElts; 3583 for (unsigned s = 0; s < NumLanes; ++s) { 3584 for (unsigned i = Start, j = s * NumLaneElts; 3585 i != End; 3586 i += 2, ++j) { 3587 int BitI = Mask[i]; 3588 int BitI1 = Mask[i+1]; 3589 if (!isUndefOrEqual(BitI, j)) 3590 return false; 3591 if (V2IsSplat) { 3592 if (!isUndefOrEqual(BitI1, NumElts)) 3593 return false; 3594 } else { 3595 if (!isUndefOrEqual(BitI1, j + NumElts)) 3596 return false; 3597 } 3598 } 3599 // Process the next 128 bits. 3600 Start += NumLaneElts; 3601 End += NumLaneElts; 3602 } 3603 3604 return true; 3605} 3606 3607bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) { 3608 SmallVector<int, 8> M; 3609 N->getMask(M); 3610 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat); 3611} 3612 3613/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3614/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3615static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT, 3616 bool HasAVX2, bool V2IsSplat = false) { 3617 int NumElts = VT.getVectorNumElements(); 3618 3619 assert((VT.is128BitVector() || VT.is256BitVector()) && 3620 "Unsupported vector type for unpckh"); 3621 3622 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 && 3623 (!HasAVX2 || (NumElts != 16 && NumElts != 32))) 3624 return false; 3625 3626 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3627 // independently on 128-bit lanes. 3628 unsigned NumLanes = VT.getSizeInBits()/128; 3629 unsigned NumLaneElts = NumElts/NumLanes; 3630 3631 unsigned Start = 0; 3632 unsigned End = NumLaneElts; 3633 for (unsigned l = 0; l != NumLanes; ++l) { 3634 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2; 3635 i != End; i += 2, ++j) { 3636 int BitI = Mask[i]; 3637 int BitI1 = Mask[i+1]; 3638 if (!isUndefOrEqual(BitI, j)) 3639 return false; 3640 if (V2IsSplat) { 3641 if (isUndefOrEqual(BitI1, NumElts)) 3642 return false; 3643 } else { 3644 if (!isUndefOrEqual(BitI1, j+NumElts)) 3645 return false; 3646 } 3647 } 3648 // Process the next 128 bits. 3649 Start += NumLaneElts; 3650 End += NumLaneElts; 3651 } 3652 return true; 3653} 3654 3655bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) { 3656 SmallVector<int, 8> M; 3657 N->getMask(M); 3658 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat); 3659} 3660 3661/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3662/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3663/// <0, 0, 1, 1> 3664static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3665 int NumElems = VT.getVectorNumElements(); 3666 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3667 return false; 3668 3669 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3670 // FIXME: Need a better way to get rid of this, there's no latency difference 3671 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3672 // the former later. We should also remove the "_undef" special mask. 3673 if (NumElems == 4 && VT.getSizeInBits() == 256) 3674 return false; 3675 3676 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3677 // independently on 128-bit lanes. 3678 unsigned NumLanes = VT.getSizeInBits() / 128; 3679 unsigned NumLaneElts = NumElems / NumLanes; 3680 3681 for (unsigned s = 0; s < NumLanes; ++s) { 3682 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts; 3683 i != NumLaneElts * (s + 1); 3684 i += 2, ++j) { 3685 int BitI = Mask[i]; 3686 int BitI1 = Mask[i+1]; 3687 3688 if (!isUndefOrEqual(BitI, j)) 3689 return false; 3690 if (!isUndefOrEqual(BitI1, j)) 3691 return false; 3692 } 3693 } 3694 3695 return true; 3696} 3697 3698bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) { 3699 SmallVector<int, 8> M; 3700 N->getMask(M); 3701 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0)); 3702} 3703 3704/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3705/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3706/// <2, 2, 3, 3> 3707static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) { 3708 int NumElems = VT.getVectorNumElements(); 3709 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16) 3710 return false; 3711 3712 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) { 3713 int BitI = Mask[i]; 3714 int BitI1 = Mask[i+1]; 3715 if (!isUndefOrEqual(BitI, j)) 3716 return false; 3717 if (!isUndefOrEqual(BitI1, j)) 3718 return false; 3719 } 3720 return true; 3721} 3722 3723bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) { 3724 SmallVector<int, 8> M; 3725 N->getMask(M); 3726 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0)); 3727} 3728 3729/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3730/// specifies a shuffle of elements that is suitable for input to MOVSS, 3731/// MOVSD, and MOVD, i.e. setting the lowest element. 3732static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) { 3733 if (VT.getVectorElementType().getSizeInBits() < 32) 3734 return false; 3735 3736 int NumElts = VT.getVectorNumElements(); 3737 3738 if (!isUndefOrEqual(Mask[0], NumElts)) 3739 return false; 3740 3741 for (int i = 1; i < NumElts; ++i) 3742 if (!isUndefOrEqual(Mask[i], i)) 3743 return false; 3744 3745 return true; 3746} 3747 3748bool X86::isMOVLMask(ShuffleVectorSDNode *N) { 3749 SmallVector<int, 8> M; 3750 N->getMask(M); 3751 return ::isMOVLMask(M, N->getValueType(0)); 3752} 3753 3754/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered 3755/// as permutations between 128-bit chunks or halves. As an example: this 3756/// shuffle bellow: 3757/// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3758/// The first half comes from the second half of V1 and the second half from the 3759/// the second half of V2. 3760static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT, 3761 bool HasAVX) { 3762 if (!HasAVX || VT.getSizeInBits() != 256) 3763 return false; 3764 3765 // The shuffle result is divided into half A and half B. In total the two 3766 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3767 // B must come from C, D, E or F. 3768 int HalfSize = VT.getVectorNumElements()/2; 3769 bool MatchA = false, MatchB = false; 3770 3771 // Check if A comes from one of C, D, E, F. 3772 for (int Half = 0; Half < 4; ++Half) { 3773 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3774 MatchA = true; 3775 break; 3776 } 3777 } 3778 3779 // Check if B comes from one of C, D, E, F. 3780 for (int Half = 0; Half < 4; ++Half) { 3781 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3782 MatchB = true; 3783 break; 3784 } 3785 } 3786 3787 return MatchA && MatchB; 3788} 3789 3790/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle 3791/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions. 3792static unsigned getShuffleVPERM2X128Immediate(SDNode *N) { 3793 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3794 EVT VT = SVOp->getValueType(0); 3795 3796 int HalfSize = VT.getVectorNumElements()/2; 3797 3798 int FstHalf = 0, SndHalf = 0; 3799 for (int i = 0; i < HalfSize; ++i) { 3800 if (SVOp->getMaskElt(i) > 0) { 3801 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3802 break; 3803 } 3804 } 3805 for (int i = HalfSize; i < HalfSize*2; ++i) { 3806 if (SVOp->getMaskElt(i) > 0) { 3807 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3808 break; 3809 } 3810 } 3811 3812 return (FstHalf | (SndHalf << 4)); 3813} 3814 3815/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand 3816/// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3817/// Note that VPERMIL mask matching is different depending whether theunderlying 3818/// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3819/// to the same elements of the low, but to the higher half of the source. 3820/// In VPERMILPD the two lanes could be shuffled independently of each other 3821/// with the same restriction that lanes can't be crossed. 3822static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT, 3823 bool HasAVX) { 3824 int NumElts = VT.getVectorNumElements(); 3825 int NumLanes = VT.getSizeInBits()/128; 3826 3827 if (!HasAVX) 3828 return false; 3829 3830 // Only match 256-bit with 32/64-bit types 3831 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8)) 3832 return false; 3833 3834 int LaneSize = NumElts/NumLanes; 3835 for (int l = 0; l != NumLanes; ++l) { 3836 int LaneStart = l*LaneSize; 3837 for (int i = 0; i != LaneSize; ++i) { 3838 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize)) 3839 return false; 3840 if (NumElts == 4 || l == 0) 3841 continue; 3842 // VPERMILPS handling 3843 if (Mask[i] < 0) 3844 continue; 3845 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize)) 3846 return false; 3847 } 3848 } 3849 3850 return true; 3851} 3852 3853/// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle 3854/// the specified VECTOR_MASK mask with VPERMILPS/D* instructions. 3855static unsigned getShuffleVPERMILPImmediate(SDNode *N) { 3856 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 3857 EVT VT = SVOp->getValueType(0); 3858 3859 int NumElts = VT.getVectorNumElements(); 3860 int NumLanes = VT.getSizeInBits()/128; 3861 int LaneSize = NumElts/NumLanes; 3862 3863 // Although the mask is equal for both lanes do it twice to get the cases 3864 // where a mask will match because the same mask element is undef on the 3865 // first half but valid on the second. This would get pathological cases 3866 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid. 3867 unsigned Shift = (LaneSize == 4) ? 2 : 1; 3868 unsigned Mask = 0; 3869 for (int i = 0; i != NumElts; ++i) { 3870 int MaskElt = SVOp->getMaskElt(i); 3871 if (MaskElt < 0) 3872 continue; 3873 MaskElt %= LaneSize; 3874 unsigned Shamt = i; 3875 // VPERMILPSY, the mask of the first half must be equal to the second one 3876 if (NumElts == 8) Shamt %= LaneSize; 3877 Mask |= MaskElt << (Shamt*Shift); 3878 } 3879 3880 return Mask; 3881} 3882 3883/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse 3884/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3885/// element of vector 2 and the other elements to come from vector 1 in order. 3886static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT, 3887 bool V2IsSplat = false, bool V2IsUndef = false) { 3888 int NumOps = VT.getVectorNumElements(); 3889 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3890 return false; 3891 3892 if (!isUndefOrEqual(Mask[0], 0)) 3893 return false; 3894 3895 for (int i = 1; i < NumOps; ++i) 3896 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3897 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3898 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3899 return false; 3900 3901 return true; 3902} 3903 3904static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false, 3905 bool V2IsUndef = false) { 3906 SmallVector<int, 8> M; 3907 N->getMask(M); 3908 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef); 3909} 3910 3911/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3912/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3913/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3914bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N, 3915 const X86Subtarget *Subtarget) { 3916 if (!Subtarget->hasSSE3orAVX()) 3917 return false; 3918 3919 // The second vector must be undef 3920 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3921 return false; 3922 3923 EVT VT = N->getValueType(0); 3924 unsigned NumElems = VT.getVectorNumElements(); 3925 3926 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3927 (VT.getSizeInBits() == 256 && NumElems != 8)) 3928 return false; 3929 3930 // "i+1" is the value the indexed mask element must have 3931 for (unsigned i = 0; i < NumElems; i += 2) 3932 if (!isUndefOrEqual(N->getMaskElt(i), i+1) || 3933 !isUndefOrEqual(N->getMaskElt(i+1), i+1)) 3934 return false; 3935 3936 return true; 3937} 3938 3939/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3940/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3941/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3942bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N, 3943 const X86Subtarget *Subtarget) { 3944 if (!Subtarget->hasSSE3orAVX()) 3945 return false; 3946 3947 // The second vector must be undef 3948 if (N->getOperand(1).getOpcode() != ISD::UNDEF) 3949 return false; 3950 3951 EVT VT = N->getValueType(0); 3952 unsigned NumElems = VT.getVectorNumElements(); 3953 3954 if ((VT.getSizeInBits() == 128 && NumElems != 4) || 3955 (VT.getSizeInBits() == 256 && NumElems != 8)) 3956 return false; 3957 3958 // "i" is the value the indexed mask element must have 3959 for (unsigned i = 0; i < NumElems; i += 2) 3960 if (!isUndefOrEqual(N->getMaskElt(i), i) || 3961 !isUndefOrEqual(N->getMaskElt(i+1), i)) 3962 return false; 3963 3964 return true; 3965} 3966 3967/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 3968/// specifies a shuffle of elements that is suitable for input to 256-bit 3969/// version of MOVDDUP. 3970static bool isMOVDDUPYMask(ShuffleVectorSDNode *N, 3971 const X86Subtarget *Subtarget) { 3972 EVT VT = N->getValueType(0); 3973 int NumElts = VT.getVectorNumElements(); 3974 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF; 3975 3976 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 || 3977 !V2IsUndef || NumElts != 4) 3978 return false; 3979 3980 for (int i = 0; i != NumElts/2; ++i) 3981 if (!isUndefOrEqual(N->getMaskElt(i), 0)) 3982 return false; 3983 for (int i = NumElts/2; i != NumElts; ++i) 3984 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2)) 3985 return false; 3986 return true; 3987} 3988 3989/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3990/// specifies a shuffle of elements that is suitable for input to 128-bit 3991/// version of MOVDDUP. 3992bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) { 3993 EVT VT = N->getValueType(0); 3994 3995 if (VT.getSizeInBits() != 128) 3996 return false; 3997 3998 int e = VT.getVectorNumElements() / 2; 3999 for (int i = 0; i < e; ++i) 4000 if (!isUndefOrEqual(N->getMaskElt(i), i)) 4001 return false; 4002 for (int i = 0; i < e; ++i) 4003 if (!isUndefOrEqual(N->getMaskElt(e+i), i)) 4004 return false; 4005 return true; 4006} 4007 4008/// isVEXTRACTF128Index - Return true if the specified 4009/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 4010/// suitable for input to VEXTRACTF128. 4011bool X86::isVEXTRACTF128Index(SDNode *N) { 4012 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4013 return false; 4014 4015 // The index should be aligned on a 128-bit boundary. 4016 uint64_t Index = 4017 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4018 4019 unsigned VL = N->getValueType(0).getVectorNumElements(); 4020 unsigned VBits = N->getValueType(0).getSizeInBits(); 4021 unsigned ElSize = VBits / VL; 4022 bool Result = (Index * ElSize) % 128 == 0; 4023 4024 return Result; 4025} 4026 4027/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 4028/// operand specifies a subvector insert that is suitable for input to 4029/// VINSERTF128. 4030bool X86::isVINSERTF128Index(SDNode *N) { 4031 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4032 return false; 4033 4034 // The index should be aligned on a 128-bit boundary. 4035 uint64_t Index = 4036 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4037 4038 unsigned VL = N->getValueType(0).getVectorNumElements(); 4039 unsigned VBits = N->getValueType(0).getSizeInBits(); 4040 unsigned ElSize = VBits / VL; 4041 bool Result = (Index * ElSize) % 128 == 0; 4042 4043 return Result; 4044} 4045 4046/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4047/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4048unsigned X86::getShuffleSHUFImmediate(SDNode *N) { 4049 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4050 int NumOperands = SVOp->getValueType(0).getVectorNumElements(); 4051 4052 unsigned Shift = (NumOperands == 4) ? 2 : 1; 4053 unsigned Mask = 0; 4054 for (int i = 0; i < NumOperands; ++i) { 4055 int Val = SVOp->getMaskElt(NumOperands-i-1); 4056 if (Val < 0) Val = 0; 4057 if (Val >= NumOperands) Val -= NumOperands; 4058 Mask |= Val; 4059 if (i != NumOperands - 1) 4060 Mask <<= Shift; 4061 } 4062 return Mask; 4063} 4064 4065/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4066/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4067unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) { 4068 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4069 unsigned Mask = 0; 4070 // 8 nodes, but we only care about the last 4. 4071 for (unsigned i = 7; i >= 4; --i) { 4072 int Val = SVOp->getMaskElt(i); 4073 if (Val >= 0) 4074 Mask |= (Val - 4); 4075 if (i != 4) 4076 Mask <<= 2; 4077 } 4078 return Mask; 4079} 4080 4081/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4082/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4083unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) { 4084 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4085 unsigned Mask = 0; 4086 // 8 nodes, but we only care about the first 4. 4087 for (int i = 3; i >= 0; --i) { 4088 int Val = SVOp->getMaskElt(i); 4089 if (Val >= 0) 4090 Mask |= Val; 4091 if (i != 0) 4092 Mask <<= 2; 4093 } 4094 return Mask; 4095} 4096 4097/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4098/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4099unsigned X86::getShufflePALIGNRImmediate(SDNode *N) { 4100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 4101 EVT VVT = N->getValueType(0); 4102 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3; 4103 int Val = 0; 4104 4105 unsigned i, e; 4106 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) { 4107 Val = SVOp->getMaskElt(i); 4108 if (Val >= 0) 4109 break; 4110 } 4111 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4112 return (Val - i) * EltSize; 4113} 4114 4115/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4116/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4117/// instructions. 4118unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4119 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4120 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4121 4122 uint64_t Index = 4123 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4124 4125 EVT VecVT = N->getOperand(0).getValueType(); 4126 EVT ElVT = VecVT.getVectorElementType(); 4127 4128 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4129 return Index / NumElemsPerChunk; 4130} 4131 4132/// getInsertVINSERTF128Immediate - Return the appropriate immediate 4133/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4134/// instructions. 4135unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4136 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4137 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4138 4139 uint64_t Index = 4140 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4141 4142 EVT VecVT = N->getValueType(0); 4143 EVT ElVT = VecVT.getVectorElementType(); 4144 4145 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4146 return Index / NumElemsPerChunk; 4147} 4148 4149/// isZeroNode - Returns true if Elt is a constant zero or a floating point 4150/// constant +0.0. 4151bool X86::isZeroNode(SDValue Elt) { 4152 return ((isa<ConstantSDNode>(Elt) && 4153 cast<ConstantSDNode>(Elt)->isNullValue()) || 4154 (isa<ConstantFPSDNode>(Elt) && 4155 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 4156} 4157 4158/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4159/// their permute mask. 4160static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4161 SelectionDAG &DAG) { 4162 EVT VT = SVOp->getValueType(0); 4163 unsigned NumElems = VT.getVectorNumElements(); 4164 SmallVector<int, 8> MaskVec; 4165 4166 for (unsigned i = 0; i != NumElems; ++i) { 4167 int idx = SVOp->getMaskElt(i); 4168 if (idx < 0) 4169 MaskVec.push_back(idx); 4170 else if (idx < (int)NumElems) 4171 MaskVec.push_back(idx + NumElems); 4172 else 4173 MaskVec.push_back(idx - NumElems); 4174 } 4175 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 4176 SVOp->getOperand(0), &MaskVec[0]); 4177} 4178 4179/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4180/// match movhlps. The lower half elements should come from upper half of 4181/// V1 (and in order), and the upper half elements should come from the upper 4182/// half of V2 (and in order). 4183static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) { 4184 EVT VT = Op->getValueType(0); 4185 if (VT.getSizeInBits() != 128) 4186 return false; 4187 if (VT.getVectorNumElements() != 4) 4188 return false; 4189 for (unsigned i = 0, e = 2; i != e; ++i) 4190 if (!isUndefOrEqual(Op->getMaskElt(i), i+2)) 4191 return false; 4192 for (unsigned i = 2; i != 4; ++i) 4193 if (!isUndefOrEqual(Op->getMaskElt(i), i+4)) 4194 return false; 4195 return true; 4196} 4197 4198/// isScalarLoadToVector - Returns true if the node is a scalar load that 4199/// is promoted to a vector. It also returns the LoadSDNode by reference if 4200/// required. 4201static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4202 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4203 return false; 4204 N = N->getOperand(0).getNode(); 4205 if (!ISD::isNON_EXTLoad(N)) 4206 return false; 4207 if (LD) 4208 *LD = cast<LoadSDNode>(N); 4209 return true; 4210} 4211 4212// Test whether the given value is a vector value which will be legalized 4213// into a load. 4214static bool WillBeConstantPoolLoad(SDNode *N) { 4215 if (N->getOpcode() != ISD::BUILD_VECTOR) 4216 return false; 4217 4218 // Check for any non-constant elements. 4219 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4220 switch (N->getOperand(i).getNode()->getOpcode()) { 4221 case ISD::UNDEF: 4222 case ISD::ConstantFP: 4223 case ISD::Constant: 4224 break; 4225 default: 4226 return false; 4227 } 4228 4229 // Vectors of all-zeros and all-ones are materialized with special 4230 // instructions rather than being loaded. 4231 return !ISD::isBuildVectorAllZeros(N) && 4232 !ISD::isBuildVectorAllOnes(N); 4233} 4234 4235/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4236/// match movlp{s|d}. The lower half elements should come from lower half of 4237/// V1 (and in order), and the upper half elements should come from the upper 4238/// half of V2 (and in order). And since V1 will become the source of the 4239/// MOVLP, it must be either a vector load or a scalar load to vector. 4240static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4241 ShuffleVectorSDNode *Op) { 4242 EVT VT = Op->getValueType(0); 4243 if (VT.getSizeInBits() != 128) 4244 return false; 4245 4246 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4247 return false; 4248 // Is V2 is a vector load, don't do this transformation. We will try to use 4249 // load folding shufps op. 4250 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4251 return false; 4252 4253 unsigned NumElems = VT.getVectorNumElements(); 4254 4255 if (NumElems != 2 && NumElems != 4) 4256 return false; 4257 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4258 if (!isUndefOrEqual(Op->getMaskElt(i), i)) 4259 return false; 4260 for (unsigned i = NumElems/2; i != NumElems; ++i) 4261 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems)) 4262 return false; 4263 return true; 4264} 4265 4266/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4267/// all the same. 4268static bool isSplatVector(SDNode *N) { 4269 if (N->getOpcode() != ISD::BUILD_VECTOR) 4270 return false; 4271 4272 SDValue SplatValue = N->getOperand(0); 4273 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4274 if (N->getOperand(i) != SplatValue) 4275 return false; 4276 return true; 4277} 4278 4279/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4280/// to an zero vector. 4281/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4282static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4283 SDValue V1 = N->getOperand(0); 4284 SDValue V2 = N->getOperand(1); 4285 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4286 for (unsigned i = 0; i != NumElems; ++i) { 4287 int Idx = N->getMaskElt(i); 4288 if (Idx >= (int)NumElems) { 4289 unsigned Opc = V2.getOpcode(); 4290 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4291 continue; 4292 if (Opc != ISD::BUILD_VECTOR || 4293 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4294 return false; 4295 } else if (Idx >= 0) { 4296 unsigned Opc = V1.getOpcode(); 4297 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4298 continue; 4299 if (Opc != ISD::BUILD_VECTOR || 4300 !X86::isZeroNode(V1.getOperand(Idx))) 4301 return false; 4302 } 4303 } 4304 return true; 4305} 4306 4307/// getZeroVector - Returns a vector of specified type with all zero elements. 4308/// 4309static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG, 4310 DebugLoc dl) { 4311 assert(VT.isVector() && "Expected a vector type"); 4312 4313 // Always build SSE zero vectors as <4 x i32> bitcasted 4314 // to their dest type. This ensures they get CSE'd. 4315 SDValue Vec; 4316 if (VT.getSizeInBits() == 128) { // SSE 4317 if (HasXMMInt) { // SSE2 4318 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4320 } else { // SSE1 4321 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4322 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4323 } 4324 } else if (VT.getSizeInBits() == 256) { // AVX 4325 // 256-bit logic and arithmetic instructions in AVX are 4326 // all floating-point, no support for integer ops. Default 4327 // to emitting fp zeroed vectors then. 4328 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4329 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4330 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 4331 } 4332 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4333} 4334 4335/// getOnesVector - Returns a vector of specified type with all bits set. 4336/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with 4337/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately. 4338/// Then bitcast to their original type, ensuring they get CSE'd. 4339static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG, 4340 DebugLoc dl) { 4341 assert(VT.isVector() && "Expected a vector type"); 4342 assert((VT.is128BitVector() || VT.is256BitVector()) 4343 && "Expected a 128-bit or 256-bit vector type"); 4344 4345 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4346 SDValue Vec; 4347 if (VT.getSizeInBits() == 256) { 4348 if (HasAVX2) { // AVX2 4349 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4350 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8); 4351 } else { // AVX 4352 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4353 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32), 4354 Vec, DAG.getConstant(0, MVT::i32), DAG, dl); 4355 Vec = Insert128BitVector(InsV, Vec, 4356 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl); 4357 } 4358 } else { 4359 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4360 } 4361 4362 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4363} 4364 4365/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4366/// that point to V2 points to its first element. 4367static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 4368 EVT VT = SVOp->getValueType(0); 4369 unsigned NumElems = VT.getVectorNumElements(); 4370 4371 bool Changed = false; 4372 SmallVector<int, 8> MaskVec; 4373 SVOp->getMask(MaskVec); 4374 4375 for (unsigned i = 0; i != NumElems; ++i) { 4376 if (MaskVec[i] > (int)NumElems) { 4377 MaskVec[i] = NumElems; 4378 Changed = true; 4379 } 4380 } 4381 if (Changed) 4382 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0), 4383 SVOp->getOperand(1), &MaskVec[0]); 4384 return SDValue(SVOp, 0); 4385} 4386 4387/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4388/// operation of specified width. 4389static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4390 SDValue V2) { 4391 unsigned NumElems = VT.getVectorNumElements(); 4392 SmallVector<int, 8> Mask; 4393 Mask.push_back(NumElems); 4394 for (unsigned i = 1; i != NumElems; ++i) 4395 Mask.push_back(i); 4396 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4397} 4398 4399/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4400static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4401 SDValue V2) { 4402 unsigned NumElems = VT.getVectorNumElements(); 4403 SmallVector<int, 8> Mask; 4404 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4405 Mask.push_back(i); 4406 Mask.push_back(i + NumElems); 4407 } 4408 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4409} 4410 4411/// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4412static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4413 SDValue V2) { 4414 unsigned NumElems = VT.getVectorNumElements(); 4415 unsigned Half = NumElems/2; 4416 SmallVector<int, 8> Mask; 4417 for (unsigned i = 0; i != Half; ++i) { 4418 Mask.push_back(i + Half); 4419 Mask.push_back(i + NumElems + Half); 4420 } 4421 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4422} 4423 4424// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4425// a generic shuffle instruction because the target has no such instructions. 4426// Generate shuffles which repeat i16 and i8 several times until they can be 4427// represented by v4f32 and then be manipulated by target suported shuffles. 4428static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4429 EVT VT = V.getValueType(); 4430 int NumElems = VT.getVectorNumElements(); 4431 DebugLoc dl = V.getDebugLoc(); 4432 4433 while (NumElems > 4) { 4434 if (EltNo < NumElems/2) { 4435 V = getUnpackl(DAG, dl, VT, V, V); 4436 } else { 4437 V = getUnpackh(DAG, dl, VT, V, V); 4438 EltNo -= NumElems/2; 4439 } 4440 NumElems >>= 1; 4441 } 4442 return V; 4443} 4444 4445/// getLegalSplat - Generate a legal splat with supported x86 shuffles 4446static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4447 EVT VT = V.getValueType(); 4448 DebugLoc dl = V.getDebugLoc(); 4449 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256) 4450 && "Vector size not supported"); 4451 4452 if (VT.getSizeInBits() == 128) { 4453 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4454 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4455 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4456 &SplatMask[0]); 4457 } else { 4458 // To use VPERMILPS to splat scalars, the second half of indicies must 4459 // refer to the higher part, which is a duplication of the lower one, 4460 // because VPERMILPS can only handle in-lane permutations. 4461 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4462 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4463 4464 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4465 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4466 &SplatMask[0]); 4467 } 4468 4469 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4470} 4471 4472/// PromoteSplat - Splat is promoted to target supported vector shuffles. 4473static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4474 EVT SrcVT = SV->getValueType(0); 4475 SDValue V1 = SV->getOperand(0); 4476 DebugLoc dl = SV->getDebugLoc(); 4477 4478 int EltNo = SV->getSplatIndex(); 4479 int NumElems = SrcVT.getVectorNumElements(); 4480 unsigned Size = SrcVT.getSizeInBits(); 4481 4482 assert(((Size == 128 && NumElems > 4) || Size == 256) && 4483 "Unknown how to promote splat for type"); 4484 4485 // Extract the 128-bit part containing the splat element and update 4486 // the splat element index when it refers to the higher register. 4487 if (Size == 256) { 4488 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0; 4489 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl); 4490 if (Idx > 0) 4491 EltNo -= NumElems/2; 4492 } 4493 4494 // All i16 and i8 vector types can't be used directly by a generic shuffle 4495 // instruction because the target has no such instruction. Generate shuffles 4496 // which repeat i16 and i8 several times until they fit in i32, and then can 4497 // be manipulated by target suported shuffles. 4498 EVT EltVT = SrcVT.getVectorElementType(); 4499 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4500 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4501 4502 // Recreate the 256-bit vector and place the same 128-bit vector 4503 // into the low and high part. This is necessary because we want 4504 // to use VPERM* to shuffle the vectors 4505 if (Size == 256) { 4506 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1, 4507 DAG.getConstant(0, MVT::i32), DAG, dl); 4508 V1 = Insert128BitVector(InsV, V1, 4509 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 4510 } 4511 4512 return getLegalSplat(DAG, V1, EltNo); 4513} 4514 4515/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4516/// vector of zero or undef vector. This produces a shuffle where the low 4517/// element of V2 is swizzled into the zero/undef vector, landing at element 4518/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4519static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4520 bool isZero, bool HasXMMInt, 4521 SelectionDAG &DAG) { 4522 EVT VT = V2.getValueType(); 4523 SDValue V1 = isZero 4524 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 4525 unsigned NumElems = VT.getVectorNumElements(); 4526 SmallVector<int, 16> MaskVec; 4527 for (unsigned i = 0; i != NumElems; ++i) 4528 // If this is the insertion idx, put the low elt of V2 here. 4529 MaskVec.push_back(i == Idx ? NumElems : i); 4530 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 4531} 4532 4533/// getShuffleScalarElt - Returns the scalar element that will make up the ith 4534/// element of the result of the vector shuffle. 4535static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG, 4536 unsigned Depth) { 4537 if (Depth == 6) 4538 return SDValue(); // Limit search depth. 4539 4540 SDValue V = SDValue(N, 0); 4541 EVT VT = V.getValueType(); 4542 unsigned Opcode = V.getOpcode(); 4543 4544 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4545 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4546 Index = SV->getMaskElt(Index); 4547 4548 if (Index < 0) 4549 return DAG.getUNDEF(VT.getVectorElementType()); 4550 4551 int NumElems = VT.getVectorNumElements(); 4552 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1); 4553 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1); 4554 } 4555 4556 // Recurse into target specific vector shuffles to find scalars. 4557 if (isTargetShuffle(Opcode)) { 4558 int NumElems = VT.getVectorNumElements(); 4559 SmallVector<unsigned, 16> ShuffleMask; 4560 SDValue ImmN; 4561 4562 switch(Opcode) { 4563 case X86ISD::SHUFPS: 4564 case X86ISD::SHUFPD: 4565 ImmN = N->getOperand(N->getNumOperands()-1); 4566 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4567 ShuffleMask); 4568 break; 4569 case X86ISD::PUNPCKH: 4570 DecodePUNPCKHMask(NumElems, ShuffleMask); 4571 break; 4572 case X86ISD::UNPCKHP: 4573 DecodeUNPCKHPMask(VT, ShuffleMask); 4574 break; 4575 case X86ISD::PUNPCKL: 4576 DecodePUNPCKLMask(VT, ShuffleMask); 4577 break; 4578 case X86ISD::UNPCKLP: 4579 DecodeUNPCKLPMask(VT, ShuffleMask); 4580 break; 4581 case X86ISD::MOVHLPS: 4582 DecodeMOVHLPSMask(NumElems, ShuffleMask); 4583 break; 4584 case X86ISD::MOVLHPS: 4585 DecodeMOVLHPSMask(NumElems, ShuffleMask); 4586 break; 4587 case X86ISD::PSHUFD: 4588 ImmN = N->getOperand(N->getNumOperands()-1); 4589 DecodePSHUFMask(NumElems, 4590 cast<ConstantSDNode>(ImmN)->getZExtValue(), 4591 ShuffleMask); 4592 break; 4593 case X86ISD::PSHUFHW: 4594 ImmN = N->getOperand(N->getNumOperands()-1); 4595 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4596 ShuffleMask); 4597 break; 4598 case X86ISD::PSHUFLW: 4599 ImmN = N->getOperand(N->getNumOperands()-1); 4600 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), 4601 ShuffleMask); 4602 break; 4603 case X86ISD::MOVSS: 4604 case X86ISD::MOVSD: { 4605 // The index 0 always comes from the first element of the second source, 4606 // this is why MOVSS and MOVSD are used in the first place. The other 4607 // elements come from the other positions of the first source vector. 4608 unsigned OpNum = (Index == 0) ? 1 : 0; 4609 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG, 4610 Depth+1); 4611 } 4612 case X86ISD::VPERMILP: 4613 ImmN = N->getOperand(N->getNumOperands()-1); 4614 DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4615 ShuffleMask); 4616 break; 4617 case X86ISD::VPERM2X128: 4618 ImmN = N->getOperand(N->getNumOperands()-1); 4619 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), 4620 ShuffleMask); 4621 break; 4622 case X86ISD::MOVDDUP: 4623 case X86ISD::MOVLHPD: 4624 case X86ISD::MOVLPD: 4625 case X86ISD::MOVLPS: 4626 case X86ISD::MOVSHDUP: 4627 case X86ISD::MOVSLDUP: 4628 case X86ISD::PALIGN: 4629 return SDValue(); // Not yet implemented. 4630 default: 4631 assert(0 && "unknown target shuffle node"); 4632 return SDValue(); 4633 } 4634 4635 Index = ShuffleMask[Index]; 4636 if (Index < 0) 4637 return DAG.getUNDEF(VT.getVectorElementType()); 4638 4639 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 4640 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, 4641 Depth+1); 4642 } 4643 4644 // Actual nodes that may contain scalar elements 4645 if (Opcode == ISD::BITCAST) { 4646 V = V.getOperand(0); 4647 EVT SrcVT = V.getValueType(); 4648 unsigned NumElems = VT.getVectorNumElements(); 4649 4650 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4651 return SDValue(); 4652 } 4653 4654 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4655 return (Index == 0) ? V.getOperand(0) 4656 : DAG.getUNDEF(VT.getVectorElementType()); 4657 4658 if (V.getOpcode() == ISD::BUILD_VECTOR) 4659 return V.getOperand(Index); 4660 4661 return SDValue(); 4662} 4663 4664/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4665/// shuffle operation which come from a consecutively from a zero. The 4666/// search can start in two different directions, from left or right. 4667static 4668unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems, 4669 bool ZerosFromLeft, SelectionDAG &DAG) { 4670 int i = 0; 4671 4672 while (i < NumElems) { 4673 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4674 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0); 4675 if (!(Elt.getNode() && 4676 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4677 break; 4678 ++i; 4679 } 4680 4681 return i; 4682} 4683 4684/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to 4685/// MaskE correspond consecutively to elements from one of the vector operands, 4686/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4687static 4688bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE, 4689 int OpIdx, int NumElems, unsigned &OpNum) { 4690 bool SeenV1 = false; 4691 bool SeenV2 = false; 4692 4693 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) { 4694 int Idx = SVOp->getMaskElt(i); 4695 // Ignore undef indicies 4696 if (Idx < 0) 4697 continue; 4698 4699 if (Idx < NumElems) 4700 SeenV1 = true; 4701 else 4702 SeenV2 = true; 4703 4704 // Only accept consecutive elements from the same vector 4705 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4706 return false; 4707 } 4708 4709 OpNum = SeenV1 ? 0 : 1; 4710 return true; 4711} 4712 4713/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4714/// logical left shift of a vector. 4715static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4716 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4717 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4718 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4719 false /* check zeros from right */, DAG); 4720 unsigned OpSrc; 4721 4722 if (!NumZeros) 4723 return false; 4724 4725 // Considering the elements in the mask that are not consecutive zeros, 4726 // check if they consecutively come from only one of the source vectors. 4727 // 4728 // V1 = {X, A, B, C} 0 4729 // \ \ \ / 4730 // vector_shuffle V1, V2 <1, 2, 3, X> 4731 // 4732 if (!isShuffleMaskConsecutive(SVOp, 4733 0, // Mask Start Index 4734 NumElems-NumZeros-1, // Mask End Index 4735 NumZeros, // Where to start looking in the src vector 4736 NumElems, // Number of elements in vector 4737 OpSrc)) // Which source operand ? 4738 return false; 4739 4740 isLeft = false; 4741 ShAmt = NumZeros; 4742 ShVal = SVOp->getOperand(OpSrc); 4743 return true; 4744} 4745 4746/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4747/// logical left shift of a vector. 4748static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4749 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4750 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4751 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4752 true /* check zeros from left */, DAG); 4753 unsigned OpSrc; 4754 4755 if (!NumZeros) 4756 return false; 4757 4758 // Considering the elements in the mask that are not consecutive zeros, 4759 // check if they consecutively come from only one of the source vectors. 4760 // 4761 // 0 { A, B, X, X } = V2 4762 // / \ / / 4763 // vector_shuffle V1, V2 <X, X, 4, 5> 4764 // 4765 if (!isShuffleMaskConsecutive(SVOp, 4766 NumZeros, // Mask Start Index 4767 NumElems-1, // Mask End Index 4768 0, // Where to start looking in the src vector 4769 NumElems, // Number of elements in vector 4770 OpSrc)) // Which source operand ? 4771 return false; 4772 4773 isLeft = true; 4774 ShAmt = NumZeros; 4775 ShVal = SVOp->getOperand(OpSrc); 4776 return true; 4777} 4778 4779/// isVectorShift - Returns true if the shuffle can be implemented as a 4780/// logical left or right shift of a vector. 4781static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4782 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4783 // Although the logic below support any bitwidth size, there are no 4784 // shift instructions which handle more than 128-bit vectors. 4785 if (SVOp->getValueType(0).getSizeInBits() > 128) 4786 return false; 4787 4788 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4789 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4790 return true; 4791 4792 return false; 4793} 4794 4795/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4796/// 4797static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4798 unsigned NumNonZero, unsigned NumZero, 4799 SelectionDAG &DAG, 4800 const TargetLowering &TLI) { 4801 if (NumNonZero > 8) 4802 return SDValue(); 4803 4804 DebugLoc dl = Op.getDebugLoc(); 4805 SDValue V(0, 0); 4806 bool First = true; 4807 for (unsigned i = 0; i < 16; ++i) { 4808 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4809 if (ThisIsNonZero && First) { 4810 if (NumZero) 4811 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4812 else 4813 V = DAG.getUNDEF(MVT::v8i16); 4814 First = false; 4815 } 4816 4817 if ((i & 1) != 0) { 4818 SDValue ThisElt(0, 0), LastElt(0, 0); 4819 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4820 if (LastIsNonZero) { 4821 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4822 MVT::i16, Op.getOperand(i-1)); 4823 } 4824 if (ThisIsNonZero) { 4825 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4826 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4827 ThisElt, DAG.getConstant(8, MVT::i8)); 4828 if (LastIsNonZero) 4829 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4830 } else 4831 ThisElt = LastElt; 4832 4833 if (ThisElt.getNode()) 4834 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4835 DAG.getIntPtrConstant(i/2)); 4836 } 4837 } 4838 4839 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4840} 4841 4842/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4843/// 4844static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4845 unsigned NumNonZero, unsigned NumZero, 4846 SelectionDAG &DAG, 4847 const TargetLowering &TLI) { 4848 if (NumNonZero > 4) 4849 return SDValue(); 4850 4851 DebugLoc dl = Op.getDebugLoc(); 4852 SDValue V(0, 0); 4853 bool First = true; 4854 for (unsigned i = 0; i < 8; ++i) { 4855 bool isNonZero = (NonZeros & (1 << i)) != 0; 4856 if (isNonZero) { 4857 if (First) { 4858 if (NumZero) 4859 V = getZeroVector(MVT::v8i16, true, DAG, dl); 4860 else 4861 V = DAG.getUNDEF(MVT::v8i16); 4862 First = false; 4863 } 4864 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4865 MVT::v8i16, V, Op.getOperand(i), 4866 DAG.getIntPtrConstant(i)); 4867 } 4868 } 4869 4870 return V; 4871} 4872 4873/// getVShift - Return a vector logical shift node. 4874/// 4875static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4876 unsigned NumBits, SelectionDAG &DAG, 4877 const TargetLowering &TLI, DebugLoc dl) { 4878 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift"); 4879 EVT ShVT = MVT::v2i64; 4880 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL; 4881 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4882 return DAG.getNode(ISD::BITCAST, dl, VT, 4883 DAG.getNode(Opc, dl, ShVT, SrcOp, 4884 DAG.getConstant(NumBits, 4885 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4886} 4887 4888SDValue 4889X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4890 SelectionDAG &DAG) const { 4891 4892 // Check if the scalar load can be widened into a vector load. And if 4893 // the address is "base + cst" see if the cst can be "absorbed" into 4894 // the shuffle mask. 4895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4896 SDValue Ptr = LD->getBasePtr(); 4897 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4898 return SDValue(); 4899 EVT PVT = LD->getValueType(0); 4900 if (PVT != MVT::i32 && PVT != MVT::f32) 4901 return SDValue(); 4902 4903 int FI = -1; 4904 int64_t Offset = 0; 4905 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4906 FI = FINode->getIndex(); 4907 Offset = 0; 4908 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4909 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4910 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4911 Offset = Ptr.getConstantOperandVal(1); 4912 Ptr = Ptr.getOperand(0); 4913 } else { 4914 return SDValue(); 4915 } 4916 4917 // FIXME: 256-bit vector instructions don't require a strict alignment, 4918 // improve this code to support it better. 4919 unsigned RequiredAlign = VT.getSizeInBits()/8; 4920 SDValue Chain = LD->getChain(); 4921 // Make sure the stack object alignment is at least 16 or 32. 4922 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4923 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 4924 if (MFI->isFixedObjectIndex(FI)) { 4925 // Can't change the alignment. FIXME: It's possible to compute 4926 // the exact stack offset and reference FI + adjust offset instead. 4927 // If someone *really* cares about this. That's the way to implement it. 4928 return SDValue(); 4929 } else { 4930 MFI->setObjectAlignment(FI, RequiredAlign); 4931 } 4932 } 4933 4934 // (Offset % 16 or 32) must be multiple of 4. Then address is then 4935 // Ptr + (Offset & ~15). 4936 if (Offset < 0) 4937 return SDValue(); 4938 if ((Offset % RequiredAlign) & 3) 4939 return SDValue(); 4940 int64_t StartOffset = Offset & ~(RequiredAlign-1); 4941 if (StartOffset) 4942 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4943 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4944 4945 int EltNo = (Offset - StartOffset) >> 2; 4946 int NumElems = VT.getVectorNumElements(); 4947 4948 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32; 4949 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 4950 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 4951 LD->getPointerInfo().getWithOffset(StartOffset), 4952 false, false, false, 0); 4953 4954 // Canonicalize it to a v4i32 or v8i32 shuffle. 4955 SmallVector<int, 8> Mask; 4956 for (int i = 0; i < NumElems; ++i) 4957 Mask.push_back(EltNo); 4958 4959 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1); 4960 return DAG.getNode(ISD::BITCAST, dl, NVT, 4961 DAG.getVectorShuffle(CanonVT, dl, V1, 4962 DAG.getUNDEF(CanonVT),&Mask[0])); 4963 } 4964 4965 return SDValue(); 4966} 4967 4968/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 4969/// vector of type 'VT', see if the elements can be replaced by a single large 4970/// load which has the same value as a build_vector whose operands are 'elts'. 4971/// 4972/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 4973/// 4974/// FIXME: we'd also like to handle the case where the last elements are zero 4975/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 4976/// There's even a handy isZeroNode for that purpose. 4977static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 4978 DebugLoc &DL, SelectionDAG &DAG) { 4979 EVT EltVT = VT.getVectorElementType(); 4980 unsigned NumElems = Elts.size(); 4981 4982 LoadSDNode *LDBase = NULL; 4983 unsigned LastLoadedElt = -1U; 4984 4985 // For each element in the initializer, see if we've found a load or an undef. 4986 // If we don't find an initial load element, or later load elements are 4987 // non-consecutive, bail out. 4988 for (unsigned i = 0; i < NumElems; ++i) { 4989 SDValue Elt = Elts[i]; 4990 4991 if (!Elt.getNode() || 4992 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 4993 return SDValue(); 4994 if (!LDBase) { 4995 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 4996 return SDValue(); 4997 LDBase = cast<LoadSDNode>(Elt.getNode()); 4998 LastLoadedElt = i; 4999 continue; 5000 } 5001 if (Elt.getOpcode() == ISD::UNDEF) 5002 continue; 5003 5004 LoadSDNode *LD = cast<LoadSDNode>(Elt); 5005 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 5006 return SDValue(); 5007 LastLoadedElt = i; 5008 } 5009 5010 // If we have found an entire vector of loads and undefs, then return a large 5011 // load of the entire vector width starting at the base pointer. If we found 5012 // consecutive loads for the low half, generate a vzext_load node. 5013 if (LastLoadedElt == NumElems - 1) { 5014 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 5015 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5016 LDBase->getPointerInfo(), 5017 LDBase->isVolatile(), LDBase->isNonTemporal(), 5018 LDBase->isInvariant(), 0); 5019 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5020 LDBase->getPointerInfo(), 5021 LDBase->isVolatile(), LDBase->isNonTemporal(), 5022 LDBase->isInvariant(), LDBase->getAlignment()); 5023 } else if (NumElems == 4 && LastLoadedElt == 1 && 5024 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5025 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5026 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5027 SDValue ResNode = 5028 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64, 5029 LDBase->getPointerInfo(), 5030 LDBase->getAlignment(), 5031 false/*isVolatile*/, true/*ReadMem*/, 5032 false/*WriteMem*/); 5033 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5034 } 5035 return SDValue(); 5036} 5037 5038/// isVectorBroadcast - Check if the node chain is suitable to be xformed to 5039/// a vbroadcast node. We support two patterns: 5040/// 1. A splat BUILD_VECTOR which uses a single scalar load. 5041/// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5042/// a scalar load. 5043/// The scalar load node is returned when a pattern is found, 5044/// or SDValue() otherwise. 5045static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) { 5046 EVT VT = Op.getValueType(); 5047 SDValue V = Op; 5048 5049 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 5050 V = V.getOperand(0); 5051 5052 //A suspected load to be broadcasted. 5053 SDValue Ld; 5054 5055 switch (V.getOpcode()) { 5056 default: 5057 // Unknown pattern found. 5058 return SDValue(); 5059 5060 case ISD::BUILD_VECTOR: { 5061 // The BUILD_VECTOR node must be a splat. 5062 if (!isSplatVector(V.getNode())) 5063 return SDValue(); 5064 5065 Ld = V.getOperand(0); 5066 5067 // The suspected load node has several users. Make sure that all 5068 // of its users are from the BUILD_VECTOR node. 5069 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5070 return SDValue(); 5071 break; 5072 } 5073 5074 case ISD::VECTOR_SHUFFLE: { 5075 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5076 5077 // Shuffles must have a splat mask where the first element is 5078 // broadcasted. 5079 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5080 return SDValue(); 5081 5082 SDValue Sc = Op.getOperand(0); 5083 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR) 5084 return SDValue(); 5085 5086 Ld = Sc.getOperand(0); 5087 5088 // The scalar_to_vector node and the suspected 5089 // load node must have exactly one user. 5090 if (!Sc.hasOneUse() || !Ld.hasOneUse()) 5091 return SDValue(); 5092 break; 5093 } 5094 } 5095 5096 // The scalar source must be a normal load. 5097 if (!ISD::isNormalLoad(Ld.getNode())) 5098 return SDValue(); 5099 5100 bool Is256 = VT.getSizeInBits() == 256; 5101 bool Is128 = VT.getSizeInBits() == 128; 5102 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5103 5104 if (hasAVX2) { 5105 // VBroadcast to YMM 5106 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 || 5107 ScalarSize == 32 || ScalarSize == 64 )) 5108 return Ld; 5109 5110 // VBroadcast to XMM 5111 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 || 5112 ScalarSize == 16 || ScalarSize == 64 )) 5113 return Ld; 5114 } 5115 5116 // VBroadcast to YMM 5117 if (Is256 && (ScalarSize == 32 || ScalarSize == 64)) 5118 return Ld; 5119 5120 // VBroadcast to XMM 5121 if (Is128 && (ScalarSize == 32)) 5122 return Ld; 5123 5124 5125 // Unsupported broadcast. 5126 return SDValue(); 5127} 5128 5129SDValue 5130X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5131 DebugLoc dl = Op.getDebugLoc(); 5132 5133 EVT VT = Op.getValueType(); 5134 EVT ExtVT = VT.getVectorElementType(); 5135 unsigned NumElems = Op.getNumOperands(); 5136 5137 // Vectors containing all zeros can be matched by pxor and xorps later 5138 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5139 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5140 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5141 if (Op.getValueType() == MVT::v4i32 || 5142 Op.getValueType() == MVT::v8i32) 5143 return Op; 5144 5145 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl); 5146 } 5147 5148 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5149 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use 5150 // vpcmpeqd on 256-bit vectors. 5151 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5152 if (Op.getValueType() == MVT::v4i32 || 5153 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2())) 5154 return Op; 5155 5156 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl); 5157 } 5158 5159 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2()); 5160 if (Subtarget->hasAVX() && LD.getNode()) 5161 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD); 5162 5163 unsigned EVTBits = ExtVT.getSizeInBits(); 5164 5165 unsigned NumZero = 0; 5166 unsigned NumNonZero = 0; 5167 unsigned NonZeros = 0; 5168 bool IsAllConstants = true; 5169 SmallSet<SDValue, 8> Values; 5170 for (unsigned i = 0; i < NumElems; ++i) { 5171 SDValue Elt = Op.getOperand(i); 5172 if (Elt.getOpcode() == ISD::UNDEF) 5173 continue; 5174 Values.insert(Elt); 5175 if (Elt.getOpcode() != ISD::Constant && 5176 Elt.getOpcode() != ISD::ConstantFP) 5177 IsAllConstants = false; 5178 if (X86::isZeroNode(Elt)) 5179 NumZero++; 5180 else { 5181 NonZeros |= (1 << i); 5182 NumNonZero++; 5183 } 5184 } 5185 5186 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5187 if (NumNonZero == 0) 5188 return DAG.getUNDEF(VT); 5189 5190 // Special case for single non-zero, non-undef, element. 5191 if (NumNonZero == 1) { 5192 unsigned Idx = CountTrailingZeros_32(NonZeros); 5193 SDValue Item = Op.getOperand(Idx); 5194 5195 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5196 // the value are obviously zero, truncate the value to i32 and do the 5197 // insertion that way. Only do this if the value is non-constant or if the 5198 // value is a constant being inserted into element 0. It is cheaper to do 5199 // a constant pool load than it is to do a movd + shuffle. 5200 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5201 (!IsAllConstants || Idx == 0)) { 5202 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5203 // Handle SSE only. 5204 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5205 EVT VecVT = MVT::v4i32; 5206 unsigned VecElts = 4; 5207 5208 // Truncate the value (which may itself be a constant) to i32, and 5209 // convert it to a vector with movd (S2V+shuffle to zero extend). 5210 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5211 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5212 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5213 Subtarget->hasXMMInt(), DAG); 5214 5215 // Now we have our 32-bit value zero extended in the low element of 5216 // a vector. If Idx != 0, swizzle it into place. 5217 if (Idx != 0) { 5218 SmallVector<int, 4> Mask; 5219 Mask.push_back(Idx); 5220 for (unsigned i = 1; i != VecElts; ++i) 5221 Mask.push_back(i); 5222 Item = DAG.getVectorShuffle(VecVT, dl, Item, 5223 DAG.getUNDEF(Item.getValueType()), 5224 &Mask[0]); 5225 } 5226 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item); 5227 } 5228 } 5229 5230 // If we have a constant or non-constant insertion into the low element of 5231 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5232 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5233 // depending on what the source datatype is. 5234 if (Idx == 0) { 5235 if (NumZero == 0) { 5236 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5237 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5238 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5239 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5240 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5241 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(), 5242 DAG); 5243 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5244 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5245 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!"); 5246 EVT MiddleVT = MVT::v4i32; 5247 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item); 5248 Item = getShuffleVectorZeroOrUndef(Item, 0, true, 5249 Subtarget->hasXMMInt(), DAG); 5250 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5251 } 5252 } 5253 5254 // Is it a vector logical left shift? 5255 if (NumElems == 2 && Idx == 1 && 5256 X86::isZeroNode(Op.getOperand(0)) && 5257 !X86::isZeroNode(Op.getOperand(1))) { 5258 unsigned NumBits = VT.getSizeInBits(); 5259 return getVShift(true, VT, 5260 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5261 VT, Op.getOperand(1)), 5262 NumBits/2, DAG, *this, dl); 5263 } 5264 5265 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5266 return SDValue(); 5267 5268 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5269 // is a non-constant being inserted into an element other than the low one, 5270 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5271 // movd/movss) to move this into the low element, then shuffle it into 5272 // place. 5273 if (EVTBits == 32) { 5274 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5275 5276 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5277 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, 5278 Subtarget->hasXMMInt(), DAG); 5279 SmallVector<int, 8> MaskVec; 5280 for (unsigned i = 0; i < NumElems; i++) 5281 MaskVec.push_back(i == Idx ? 0 : 1); 5282 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5283 } 5284 } 5285 5286 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5287 if (Values.size() == 1) { 5288 if (EVTBits == 32) { 5289 // Instead of a shuffle like this: 5290 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5291 // Check if it's possible to issue this instead. 5292 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5293 unsigned Idx = CountTrailingZeros_32(NonZeros); 5294 SDValue Item = Op.getOperand(Idx); 5295 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5296 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5297 } 5298 return SDValue(); 5299 } 5300 5301 // A vector full of immediates; various special cases are already 5302 // handled, so this is best done with a single constant-pool load. 5303 if (IsAllConstants) 5304 return SDValue(); 5305 5306 // For AVX-length vectors, build the individual 128-bit pieces and use 5307 // shuffles to put them in place. 5308 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) { 5309 SmallVector<SDValue, 32> V; 5310 for (unsigned i = 0; i < NumElems; ++i) 5311 V.push_back(Op.getOperand(i)); 5312 5313 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5314 5315 // Build both the lower and upper subvector. 5316 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5317 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5318 NumElems/2); 5319 5320 // Recreate the wider vector with the lower and upper part. 5321 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower, 5322 DAG.getConstant(0, MVT::i32), DAG, dl); 5323 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32), 5324 DAG, dl); 5325 } 5326 5327 // Let legalizer expand 2-wide build_vectors. 5328 if (EVTBits == 64) { 5329 if (NumNonZero == 1) { 5330 // One half is zero or undef. 5331 unsigned Idx = CountTrailingZeros_32(NonZeros); 5332 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5333 Op.getOperand(Idx)); 5334 return getShuffleVectorZeroOrUndef(V2, Idx, true, 5335 Subtarget->hasXMMInt(), DAG); 5336 } 5337 return SDValue(); 5338 } 5339 5340 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5341 if (EVTBits == 8 && NumElems == 16) { 5342 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5343 *this); 5344 if (V.getNode()) return V; 5345 } 5346 5347 if (EVTBits == 16 && NumElems == 8) { 5348 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5349 *this); 5350 if (V.getNode()) return V; 5351 } 5352 5353 // If element VT is == 32 bits, turn it into a number of shuffles. 5354 SmallVector<SDValue, 8> V; 5355 V.resize(NumElems); 5356 if (NumElems == 4 && NumZero > 0) { 5357 for (unsigned i = 0; i < 4; ++i) { 5358 bool isZero = !(NonZeros & (1 << i)); 5359 if (isZero) 5360 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl); 5361 else 5362 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5363 } 5364 5365 for (unsigned i = 0; i < 2; ++i) { 5366 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5367 default: break; 5368 case 0: 5369 V[i] = V[i*2]; // Must be a zero vector. 5370 break; 5371 case 1: 5372 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5373 break; 5374 case 2: 5375 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5376 break; 5377 case 3: 5378 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5379 break; 5380 } 5381 } 5382 5383 SmallVector<int, 8> MaskVec; 5384 bool Reverse = (NonZeros & 0x3) == 2; 5385 for (unsigned i = 0; i < 2; ++i) 5386 MaskVec.push_back(Reverse ? 1-i : i); 5387 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5388 for (unsigned i = 0; i < 2; ++i) 5389 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems); 5390 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5391 } 5392 5393 if (Values.size() > 1 && VT.getSizeInBits() == 128) { 5394 // Check for a build vector of consecutive loads. 5395 for (unsigned i = 0; i < NumElems; ++i) 5396 V[i] = Op.getOperand(i); 5397 5398 // Check for elements which are consecutive loads. 5399 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5400 if (LD.getNode()) 5401 return LD; 5402 5403 // For SSE 4.1, use insertps to put the high elements into the low element. 5404 if (getSubtarget()->hasSSE41orAVX()) { 5405 SDValue Result; 5406 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5407 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5408 else 5409 Result = DAG.getUNDEF(VT); 5410 5411 for (unsigned i = 1; i < NumElems; ++i) { 5412 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5413 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5414 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5415 } 5416 return Result; 5417 } 5418 5419 // Otherwise, expand into a number of unpckl*, start by extending each of 5420 // our (non-undef) elements to the full vector width with the element in the 5421 // bottom slot of the vector (which generates no code for SSE). 5422 for (unsigned i = 0; i < NumElems; ++i) { 5423 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5424 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5425 else 5426 V[i] = DAG.getUNDEF(VT); 5427 } 5428 5429 // Next, we iteratively mix elements, e.g. for v4f32: 5430 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5431 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5432 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5433 unsigned EltStride = NumElems >> 1; 5434 while (EltStride != 0) { 5435 for (unsigned i = 0; i < EltStride; ++i) { 5436 // If V[i+EltStride] is undef and this is the first round of mixing, 5437 // then it is safe to just drop this shuffle: V[i] is already in the 5438 // right place, the one element (since it's the first round) being 5439 // inserted as undef can be dropped. This isn't safe for successive 5440 // rounds because they will permute elements within both vectors. 5441 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5442 EltStride == NumElems/2) 5443 continue; 5444 5445 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5446 } 5447 EltStride >>= 1; 5448 } 5449 return V[0]; 5450 } 5451 return SDValue(); 5452} 5453 5454// LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place 5455// them in a MMX register. This is better than doing a stack convert. 5456static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5457 DebugLoc dl = Op.getDebugLoc(); 5458 EVT ResVT = Op.getValueType(); 5459 5460 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 || 5461 ResVT == MVT::v8i16 || ResVT == MVT::v16i8); 5462 int Mask[2]; 5463 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0)); 5464 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5465 InVec = Op.getOperand(1); 5466 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5467 unsigned NumElts = ResVT.getVectorNumElements(); 5468 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5469 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp, 5470 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1)); 5471 } else { 5472 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec); 5473 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec); 5474 Mask[0] = 0; Mask[1] = 2; 5475 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask); 5476 } 5477 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp); 5478} 5479 5480// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5481// to create 256-bit vectors from two other 128-bit ones. 5482static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5483 DebugLoc dl = Op.getDebugLoc(); 5484 EVT ResVT = Op.getValueType(); 5485 5486 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide"); 5487 5488 SDValue V1 = Op.getOperand(0); 5489 SDValue V2 = Op.getOperand(1); 5490 unsigned NumElems = ResVT.getVectorNumElements(); 5491 5492 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1, 5493 DAG.getConstant(0, MVT::i32), DAG, dl); 5494 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 5495 DAG, dl); 5496} 5497 5498SDValue 5499X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const { 5500 EVT ResVT = Op.getValueType(); 5501 5502 assert(Op.getNumOperands() == 2); 5503 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) && 5504 "Unsupported CONCAT_VECTORS for value type"); 5505 5506 // We support concatenate two MMX registers and place them in a MMX register. 5507 // This is better than doing a stack convert. 5508 if (ResVT.is128BitVector()) 5509 return LowerMMXCONCAT_VECTORS(Op, DAG); 5510 5511 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5512 // from two other 128-bit ones. 5513 return LowerAVXCONCAT_VECTORS(Op, DAG); 5514} 5515 5516// v8i16 shuffles - Prefer shuffles in the following order: 5517// 1. [all] pshuflw, pshufhw, optional move 5518// 2. [ssse3] 1 x pshufb 5519// 3. [ssse3] 2 x pshufb + 1 x por 5520// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5521SDValue 5522X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op, 5523 SelectionDAG &DAG) const { 5524 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5525 SDValue V1 = SVOp->getOperand(0); 5526 SDValue V2 = SVOp->getOperand(1); 5527 DebugLoc dl = SVOp->getDebugLoc(); 5528 SmallVector<int, 8> MaskVals; 5529 5530 // Determine if more than 1 of the words in each of the low and high quadwords 5531 // of the result come from the same quadword of one of the two inputs. Undef 5532 // mask values count as coming from any quadword, for better codegen. 5533 unsigned LoQuad[] = { 0, 0, 0, 0 }; 5534 unsigned HiQuad[] = { 0, 0, 0, 0 }; 5535 BitVector InputQuads(4); 5536 for (unsigned i = 0; i < 8; ++i) { 5537 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 5538 int EltIdx = SVOp->getMaskElt(i); 5539 MaskVals.push_back(EltIdx); 5540 if (EltIdx < 0) { 5541 ++Quad[0]; 5542 ++Quad[1]; 5543 ++Quad[2]; 5544 ++Quad[3]; 5545 continue; 5546 } 5547 ++Quad[EltIdx / 4]; 5548 InputQuads.set(EltIdx / 4); 5549 } 5550 5551 int BestLoQuad = -1; 5552 unsigned MaxQuad = 1; 5553 for (unsigned i = 0; i < 4; ++i) { 5554 if (LoQuad[i] > MaxQuad) { 5555 BestLoQuad = i; 5556 MaxQuad = LoQuad[i]; 5557 } 5558 } 5559 5560 int BestHiQuad = -1; 5561 MaxQuad = 1; 5562 for (unsigned i = 0; i < 4; ++i) { 5563 if (HiQuad[i] > MaxQuad) { 5564 BestHiQuad = i; 5565 MaxQuad = HiQuad[i]; 5566 } 5567 } 5568 5569 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5570 // of the two input vectors, shuffle them into one input vector so only a 5571 // single pshufb instruction is necessary. If There are more than 2 input 5572 // quads, disable the next transformation since it does not help SSSE3. 5573 bool V1Used = InputQuads[0] || InputQuads[1]; 5574 bool V2Used = InputQuads[2] || InputQuads[3]; 5575 if (Subtarget->hasSSSE3orAVX()) { 5576 if (InputQuads.count() == 2 && V1Used && V2Used) { 5577 BestLoQuad = InputQuads.find_first(); 5578 BestHiQuad = InputQuads.find_next(BestLoQuad); 5579 } 5580 if (InputQuads.count() > 2) { 5581 BestLoQuad = -1; 5582 BestHiQuad = -1; 5583 } 5584 } 5585 5586 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5587 // the shuffle mask. If a quad is scored as -1, that means that it contains 5588 // words from all 4 input quadwords. 5589 SDValue NewV; 5590 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5591 SmallVector<int, 8> MaskV; 5592 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad); 5593 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad); 5594 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5595 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5596 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5597 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5598 5599 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5600 // source words for the shuffle, to aid later transformations. 5601 bool AllWordsInNewV = true; 5602 bool InOrder[2] = { true, true }; 5603 for (unsigned i = 0; i != 8; ++i) { 5604 int idx = MaskVals[i]; 5605 if (idx != (int)i) 5606 InOrder[i/4] = false; 5607 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5608 continue; 5609 AllWordsInNewV = false; 5610 break; 5611 } 5612 5613 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5614 if (AllWordsInNewV) { 5615 for (int i = 0; i != 8; ++i) { 5616 int idx = MaskVals[i]; 5617 if (idx < 0) 5618 continue; 5619 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5620 if ((idx != i) && idx < 4) 5621 pshufhw = false; 5622 if ((idx != i) && idx > 3) 5623 pshuflw = false; 5624 } 5625 V1 = NewV; 5626 V2Used = false; 5627 BestLoQuad = 0; 5628 BestHiQuad = 1; 5629 } 5630 5631 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5632 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5633 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5634 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5635 unsigned TargetMask = 0; 5636 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5637 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5638 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()): 5639 X86::getShufflePSHUFLWImmediate(NewV.getNode()); 5640 V1 = NewV.getOperand(0); 5641 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5642 } 5643 } 5644 5645 // If we have SSSE3, and all words of the result are from 1 input vector, 5646 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5647 // is present, fall back to case 4. 5648 if (Subtarget->hasSSSE3orAVX()) { 5649 SmallVector<SDValue,16> pshufbMask; 5650 5651 // If we have elements from both input vectors, set the high bit of the 5652 // shuffle mask element to zero out elements that come from V2 in the V1 5653 // mask, and elements that come from V1 in the V2 mask, so that the two 5654 // results can be OR'd together. 5655 bool TwoInputs = V1Used && V2Used; 5656 for (unsigned i = 0; i != 8; ++i) { 5657 int EltIdx = MaskVals[i] * 2; 5658 if (TwoInputs && (EltIdx >= 16)) { 5659 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5660 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5661 continue; 5662 } 5663 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5664 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8)); 5665 } 5666 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5667 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5668 DAG.getNode(ISD::BUILD_VECTOR, dl, 5669 MVT::v16i8, &pshufbMask[0], 16)); 5670 if (!TwoInputs) 5671 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5672 5673 // Calculate the shuffle mask for the second input, shuffle it, and 5674 // OR it with the first shuffled input. 5675 pshufbMask.clear(); 5676 for (unsigned i = 0; i != 8; ++i) { 5677 int EltIdx = MaskVals[i] * 2; 5678 if (EltIdx < 16) { 5679 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5680 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5681 continue; 5682 } 5683 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5684 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8)); 5685 } 5686 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5687 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5688 DAG.getNode(ISD::BUILD_VECTOR, dl, 5689 MVT::v16i8, &pshufbMask[0], 16)); 5690 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5691 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5692 } 5693 5694 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5695 // and update MaskVals with new element order. 5696 BitVector InOrder(8); 5697 if (BestLoQuad >= 0) { 5698 SmallVector<int, 8> MaskV; 5699 for (int i = 0; i != 4; ++i) { 5700 int idx = MaskVals[i]; 5701 if (idx < 0) { 5702 MaskV.push_back(-1); 5703 InOrder.set(i); 5704 } else if ((idx / 4) == BestLoQuad) { 5705 MaskV.push_back(idx & 3); 5706 InOrder.set(i); 5707 } else { 5708 MaskV.push_back(-1); 5709 } 5710 } 5711 for (unsigned i = 4; i != 8; ++i) 5712 MaskV.push_back(i); 5713 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5714 &MaskV[0]); 5715 5716 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX()) 5717 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5718 NewV.getOperand(0), 5719 X86::getShufflePSHUFLWImmediate(NewV.getNode()), 5720 DAG); 5721 } 5722 5723 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5724 // and update MaskVals with the new element order. 5725 if (BestHiQuad >= 0) { 5726 SmallVector<int, 8> MaskV; 5727 for (unsigned i = 0; i != 4; ++i) 5728 MaskV.push_back(i); 5729 for (unsigned i = 4; i != 8; ++i) { 5730 int idx = MaskVals[i]; 5731 if (idx < 0) { 5732 MaskV.push_back(-1); 5733 InOrder.set(i); 5734 } else if ((idx / 4) == BestHiQuad) { 5735 MaskV.push_back((idx & 3) + 4); 5736 InOrder.set(i); 5737 } else { 5738 MaskV.push_back(-1); 5739 } 5740 } 5741 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5742 &MaskV[0]); 5743 5744 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX()) 5745 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 5746 NewV.getOperand(0), 5747 X86::getShufflePSHUFHWImmediate(NewV.getNode()), 5748 DAG); 5749 } 5750 5751 // In case BestHi & BestLo were both -1, which means each quadword has a word 5752 // from each of the four input quadwords, calculate the InOrder bitvector now 5753 // before falling through to the insert/extract cleanup. 5754 if (BestLoQuad == -1 && BestHiQuad == -1) { 5755 NewV = V1; 5756 for (int i = 0; i != 8; ++i) 5757 if (MaskVals[i] < 0 || MaskVals[i] == i) 5758 InOrder.set(i); 5759 } 5760 5761 // The other elements are put in the right place using pextrw and pinsrw. 5762 for (unsigned i = 0; i != 8; ++i) { 5763 if (InOrder[i]) 5764 continue; 5765 int EltIdx = MaskVals[i]; 5766 if (EltIdx < 0) 5767 continue; 5768 SDValue ExtOp = (EltIdx < 8) 5769 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 5770 DAG.getIntPtrConstant(EltIdx)) 5771 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 5772 DAG.getIntPtrConstant(EltIdx - 8)); 5773 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 5774 DAG.getIntPtrConstant(i)); 5775 } 5776 return NewV; 5777} 5778 5779// v16i8 shuffles - Prefer shuffles in the following order: 5780// 1. [ssse3] 1 x pshufb 5781// 2. [ssse3] 2 x pshufb + 1 x por 5782// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5783static 5784SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5785 SelectionDAG &DAG, 5786 const X86TargetLowering &TLI) { 5787 SDValue V1 = SVOp->getOperand(0); 5788 SDValue V2 = SVOp->getOperand(1); 5789 DebugLoc dl = SVOp->getDebugLoc(); 5790 SmallVector<int, 16> MaskVals; 5791 SVOp->getMask(MaskVals); 5792 5793 // If we have SSSE3, case 1 is generated when all result bytes come from 5794 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5795 // present, fall back to case 3. 5796 // FIXME: kill V2Only once shuffles are canonizalized by getNode. 5797 bool V1Only = true; 5798 bool V2Only = true; 5799 for (unsigned i = 0; i < 16; ++i) { 5800 int EltIdx = MaskVals[i]; 5801 if (EltIdx < 0) 5802 continue; 5803 if (EltIdx < 16) 5804 V2Only = false; 5805 else 5806 V1Only = false; 5807 } 5808 5809 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5810 if (TLI.getSubtarget()->hasSSSE3orAVX()) { 5811 SmallVector<SDValue,16> pshufbMask; 5812 5813 // If all result elements are from one input vector, then only translate 5814 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5815 // 5816 // Otherwise, we have elements from both input vectors, and must zero out 5817 // elements that come from V2 in the first mask, and V1 in the second mask 5818 // so that we can OR them together. 5819 bool TwoInputs = !(V1Only || V2Only); 5820 for (unsigned i = 0; i != 16; ++i) { 5821 int EltIdx = MaskVals[i]; 5822 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) { 5823 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5824 continue; 5825 } 5826 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5827 } 5828 // If all the elements are from V2, assign it to V1 and return after 5829 // building the first pshufb. 5830 if (V2Only) 5831 V1 = V2; 5832 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5833 DAG.getNode(ISD::BUILD_VECTOR, dl, 5834 MVT::v16i8, &pshufbMask[0], 16)); 5835 if (!TwoInputs) 5836 return V1; 5837 5838 // Calculate the shuffle mask for the second input, shuffle it, and 5839 // OR it with the first shuffled input. 5840 pshufbMask.clear(); 5841 for (unsigned i = 0; i != 16; ++i) { 5842 int EltIdx = MaskVals[i]; 5843 if (EltIdx < 16) { 5844 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 5845 continue; 5846 } 5847 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8)); 5848 } 5849 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5850 DAG.getNode(ISD::BUILD_VECTOR, dl, 5851 MVT::v16i8, &pshufbMask[0], 16)); 5852 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5853 } 5854 5855 // No SSSE3 - Calculate in place words and then fix all out of place words 5856 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 5857 // the 16 different words that comprise the two doublequadword input vectors. 5858 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5859 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 5860 SDValue NewV = V2Only ? V2 : V1; 5861 for (int i = 0; i != 8; ++i) { 5862 int Elt0 = MaskVals[i*2]; 5863 int Elt1 = MaskVals[i*2+1]; 5864 5865 // This word of the result is all undef, skip it. 5866 if (Elt0 < 0 && Elt1 < 0) 5867 continue; 5868 5869 // This word of the result is already in the correct place, skip it. 5870 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1)) 5871 continue; 5872 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17)) 5873 continue; 5874 5875 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 5876 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 5877 SDValue InsElt; 5878 5879 // If Elt0 and Elt1 are defined, are consecutive, and can be load 5880 // using a single extract together, load it and store it. 5881 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 5882 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5883 DAG.getIntPtrConstant(Elt1 / 2)); 5884 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5885 DAG.getIntPtrConstant(i)); 5886 continue; 5887 } 5888 5889 // If Elt1 is defined, extract it from the appropriate source. If the 5890 // source byte is not also odd, shift the extracted word left 8 bits 5891 // otherwise clear the bottom 8 bits if we need to do an or. 5892 if (Elt1 >= 0) { 5893 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 5894 DAG.getIntPtrConstant(Elt1 / 2)); 5895 if ((Elt1 & 1) == 0) 5896 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 5897 DAG.getConstant(8, 5898 TLI.getShiftAmountTy(InsElt.getValueType()))); 5899 else if (Elt0 >= 0) 5900 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 5901 DAG.getConstant(0xFF00, MVT::i16)); 5902 } 5903 // If Elt0 is defined, extract it from the appropriate source. If the 5904 // source byte is not also even, shift the extracted word right 8 bits. If 5905 // Elt1 was also defined, OR the extracted values together before 5906 // inserting them in the result. 5907 if (Elt0 >= 0) { 5908 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 5909 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 5910 if ((Elt0 & 1) != 0) 5911 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 5912 DAG.getConstant(8, 5913 TLI.getShiftAmountTy(InsElt0.getValueType()))); 5914 else if (Elt1 >= 0) 5915 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 5916 DAG.getConstant(0x00FF, MVT::i16)); 5917 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 5918 : InsElt0; 5919 } 5920 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 5921 DAG.getIntPtrConstant(i)); 5922 } 5923 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 5924} 5925 5926/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 5927/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 5928/// done when every pair / quad of shuffle mask elements point to elements in 5929/// the right sequence. e.g. 5930/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 5931static 5932SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 5933 SelectionDAG &DAG, DebugLoc dl) { 5934 EVT VT = SVOp->getValueType(0); 5935 SDValue V1 = SVOp->getOperand(0); 5936 SDValue V2 = SVOp->getOperand(1); 5937 unsigned NumElems = VT.getVectorNumElements(); 5938 unsigned NewWidth = (NumElems == 4) ? 2 : 4; 5939 EVT NewVT; 5940 switch (VT.getSimpleVT().SimpleTy) { 5941 default: assert(false && "Unexpected!"); 5942 case MVT::v4f32: NewVT = MVT::v2f64; break; 5943 case MVT::v4i32: NewVT = MVT::v2i64; break; 5944 case MVT::v8i16: NewVT = MVT::v4i32; break; 5945 case MVT::v16i8: NewVT = MVT::v4i32; break; 5946 } 5947 5948 int Scale = NumElems / NewWidth; 5949 SmallVector<int, 8> MaskVec; 5950 for (unsigned i = 0; i < NumElems; i += Scale) { 5951 int StartIdx = -1; 5952 for (int j = 0; j < Scale; ++j) { 5953 int EltIdx = SVOp->getMaskElt(i+j); 5954 if (EltIdx < 0) 5955 continue; 5956 if (StartIdx == -1) 5957 StartIdx = EltIdx - (EltIdx % Scale); 5958 if (EltIdx != StartIdx + j) 5959 return SDValue(); 5960 } 5961 if (StartIdx == -1) 5962 MaskVec.push_back(-1); 5963 else 5964 MaskVec.push_back(StartIdx / Scale); 5965 } 5966 5967 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1); 5968 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2); 5969 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 5970} 5971 5972/// getVZextMovL - Return a zero-extending vector move low node. 5973/// 5974static SDValue getVZextMovL(EVT VT, EVT OpVT, 5975 SDValue SrcOp, SelectionDAG &DAG, 5976 const X86Subtarget *Subtarget, DebugLoc dl) { 5977 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 5978 LoadSDNode *LD = NULL; 5979 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 5980 LD = dyn_cast<LoadSDNode>(SrcOp); 5981 if (!LD) { 5982 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 5983 // instead. 5984 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 5985 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 5986 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 5987 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 5988 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 5989 // PR2108 5990 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 5991 return DAG.getNode(ISD::BITCAST, dl, VT, 5992 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 5993 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5994 OpVT, 5995 SrcOp.getOperand(0) 5996 .getOperand(0)))); 5997 } 5998 } 5999 } 6000 6001 return DAG.getNode(ISD::BITCAST, dl, VT, 6002 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6003 DAG.getNode(ISD::BITCAST, dl, 6004 OpVT, SrcOp))); 6005} 6006 6007/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector 6008/// shuffle node referes to only one lane in the sources. 6009static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) { 6010 EVT VT = SVOp->getValueType(0); 6011 int NumElems = VT.getVectorNumElements(); 6012 int HalfSize = NumElems/2; 6013 SmallVector<int, 16> M; 6014 SVOp->getMask(M); 6015 bool MatchA = false, MatchB = false; 6016 6017 for (int l = 0; l < NumElems*2; l += HalfSize) { 6018 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) { 6019 MatchA = true; 6020 break; 6021 } 6022 } 6023 6024 for (int l = 0; l < NumElems*2; l += HalfSize) { 6025 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) { 6026 MatchB = true; 6027 break; 6028 } 6029 } 6030 6031 return MatchA && MatchB; 6032} 6033 6034/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6035/// which could not be matched by any known target speficic shuffle 6036static SDValue 6037LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6038 if (areShuffleHalvesWithinDisjointLanes(SVOp)) { 6039 // If each half of a vector shuffle node referes to only one lane in the 6040 // source vectors, extract each used 128-bit lane and shuffle them using 6041 // 128-bit shuffles. Then, concatenate the results. Otherwise leave 6042 // the work to the legalizer. 6043 DebugLoc dl = SVOp->getDebugLoc(); 6044 EVT VT = SVOp->getValueType(0); 6045 int NumElems = VT.getVectorNumElements(); 6046 int HalfSize = NumElems/2; 6047 6048 // Extract the reference for each half 6049 int FstVecExtractIdx = 0, SndVecExtractIdx = 0; 6050 int FstVecOpNum = 0, SndVecOpNum = 0; 6051 for (int i = 0; i < HalfSize; ++i) { 6052 int Elt = SVOp->getMaskElt(i); 6053 if (SVOp->getMaskElt(i) < 0) 6054 continue; 6055 FstVecOpNum = Elt/NumElems; 6056 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 6057 break; 6058 } 6059 for (int i = HalfSize; i < NumElems; ++i) { 6060 int Elt = SVOp->getMaskElt(i); 6061 if (SVOp->getMaskElt(i) < 0) 6062 continue; 6063 SndVecOpNum = Elt/NumElems; 6064 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize; 6065 break; 6066 } 6067 6068 // Extract the subvectors 6069 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum), 6070 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl); 6071 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum), 6072 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl); 6073 6074 // Generate 128-bit shuffles 6075 SmallVector<int, 16> MaskV1, MaskV2; 6076 for (int i = 0; i < HalfSize; ++i) { 6077 int Elt = SVOp->getMaskElt(i); 6078 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize); 6079 } 6080 for (int i = HalfSize; i < NumElems; ++i) { 6081 int Elt = SVOp->getMaskElt(i); 6082 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize); 6083 } 6084 6085 EVT NVT = V1.getValueType(); 6086 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]); 6087 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]); 6088 6089 // Concatenate the result back 6090 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1, 6091 DAG.getConstant(0, MVT::i32), DAG, dl); 6092 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32), 6093 DAG, dl); 6094 } 6095 6096 return SDValue(); 6097} 6098 6099/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6100/// 4 elements, and match them with several different shuffle types. 6101static SDValue 6102LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6103 SDValue V1 = SVOp->getOperand(0); 6104 SDValue V2 = SVOp->getOperand(1); 6105 DebugLoc dl = SVOp->getDebugLoc(); 6106 EVT VT = SVOp->getValueType(0); 6107 6108 assert(VT.getSizeInBits() == 128 && "Unsupported vector size"); 6109 6110 SmallVector<std::pair<int, int>, 8> Locs; 6111 Locs.resize(4); 6112 SmallVector<int, 8> Mask1(4U, -1); 6113 SmallVector<int, 8> PermMask; 6114 SVOp->getMask(PermMask); 6115 6116 unsigned NumHi = 0; 6117 unsigned NumLo = 0; 6118 for (unsigned i = 0; i != 4; ++i) { 6119 int Idx = PermMask[i]; 6120 if (Idx < 0) { 6121 Locs[i] = std::make_pair(-1, -1); 6122 } else { 6123 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6124 if (Idx < 4) { 6125 Locs[i] = std::make_pair(0, NumLo); 6126 Mask1[NumLo] = Idx; 6127 NumLo++; 6128 } else { 6129 Locs[i] = std::make_pair(1, NumHi); 6130 if (2+NumHi < 4) 6131 Mask1[2+NumHi] = Idx; 6132 NumHi++; 6133 } 6134 } 6135 } 6136 6137 if (NumLo <= 2 && NumHi <= 2) { 6138 // If no more than two elements come from either vector. This can be 6139 // implemented with two shuffles. First shuffle gather the elements. 6140 // The second shuffle, which takes the first shuffle as both of its 6141 // vector operands, put the elements into the right order. 6142 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6143 6144 SmallVector<int, 8> Mask2(4U, -1); 6145 6146 for (unsigned i = 0; i != 4; ++i) { 6147 if (Locs[i].first == -1) 6148 continue; 6149 else { 6150 unsigned Idx = (i < 2) ? 0 : 4; 6151 Idx += Locs[i].first * 2 + Locs[i].second; 6152 Mask2[i] = Idx; 6153 } 6154 } 6155 6156 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6157 } else if (NumLo == 3 || NumHi == 3) { 6158 // Otherwise, we must have three elements from one vector, call it X, and 6159 // one element from the other, call it Y. First, use a shufps to build an 6160 // intermediate vector with the one element from Y and the element from X 6161 // that will be in the same half in the final destination (the indexes don't 6162 // matter). Then, use a shufps to build the final vector, taking the half 6163 // containing the element from Y from the intermediate, and the other half 6164 // from X. 6165 if (NumHi == 3) { 6166 // Normalize it so the 3 elements come from V1. 6167 CommuteVectorShuffleMask(PermMask, VT); 6168 std::swap(V1, V2); 6169 } 6170 6171 // Find the element from V2. 6172 unsigned HiIndex; 6173 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6174 int Val = PermMask[HiIndex]; 6175 if (Val < 0) 6176 continue; 6177 if (Val >= 4) 6178 break; 6179 } 6180 6181 Mask1[0] = PermMask[HiIndex]; 6182 Mask1[1] = -1; 6183 Mask1[2] = PermMask[HiIndex^1]; 6184 Mask1[3] = -1; 6185 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6186 6187 if (HiIndex >= 2) { 6188 Mask1[0] = PermMask[0]; 6189 Mask1[1] = PermMask[1]; 6190 Mask1[2] = HiIndex & 1 ? 6 : 4; 6191 Mask1[3] = HiIndex & 1 ? 4 : 6; 6192 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6193 } else { 6194 Mask1[0] = HiIndex & 1 ? 2 : 0; 6195 Mask1[1] = HiIndex & 1 ? 0 : 2; 6196 Mask1[2] = PermMask[2]; 6197 Mask1[3] = PermMask[3]; 6198 if (Mask1[2] >= 0) 6199 Mask1[2] += 4; 6200 if (Mask1[3] >= 0) 6201 Mask1[3] += 4; 6202 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6203 } 6204 } 6205 6206 // Break it into (shuffle shuffle_hi, shuffle_lo). 6207 Locs.clear(); 6208 Locs.resize(4); 6209 SmallVector<int,8> LoMask(4U, -1); 6210 SmallVector<int,8> HiMask(4U, -1); 6211 6212 SmallVector<int,8> *MaskPtr = &LoMask; 6213 unsigned MaskIdx = 0; 6214 unsigned LoIdx = 0; 6215 unsigned HiIdx = 2; 6216 for (unsigned i = 0; i != 4; ++i) { 6217 if (i == 2) { 6218 MaskPtr = &HiMask; 6219 MaskIdx = 1; 6220 LoIdx = 0; 6221 HiIdx = 2; 6222 } 6223 int Idx = PermMask[i]; 6224 if (Idx < 0) { 6225 Locs[i] = std::make_pair(-1, -1); 6226 } else if (Idx < 4) { 6227 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6228 (*MaskPtr)[LoIdx] = Idx; 6229 LoIdx++; 6230 } else { 6231 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6232 (*MaskPtr)[HiIdx] = Idx; 6233 HiIdx++; 6234 } 6235 } 6236 6237 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6238 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6239 SmallVector<int, 8> MaskOps; 6240 for (unsigned i = 0; i != 4; ++i) { 6241 if (Locs[i].first == -1) { 6242 MaskOps.push_back(-1); 6243 } else { 6244 unsigned Idx = Locs[i].first * 4 + Locs[i].second; 6245 MaskOps.push_back(Idx); 6246 } 6247 } 6248 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6249} 6250 6251static bool MayFoldVectorLoad(SDValue V) { 6252 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6253 V = V.getOperand(0); 6254 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6255 V = V.getOperand(0); 6256 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6257 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6258 // BUILD_VECTOR (load), undef 6259 V = V.getOperand(0); 6260 if (MayFoldLoad(V)) 6261 return true; 6262 return false; 6263} 6264 6265// FIXME: the version above should always be used. Since there's 6266// a bug where several vector shuffles can't be folded because the 6267// DAG is not updated during lowering and a node claims to have two 6268// uses while it only has one, use this version, and let isel match 6269// another instruction if the load really happens to have more than 6270// one use. Remove this version after this bug get fixed. 6271// rdar://8434668, PR8156 6272static bool RelaxedMayFoldVectorLoad(SDValue V) { 6273 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6274 V = V.getOperand(0); 6275 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6276 V = V.getOperand(0); 6277 if (ISD::isNormalLoad(V.getNode())) 6278 return true; 6279 return false; 6280} 6281 6282/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by 6283/// a vector extract, and if both can be later optimized into a single load. 6284/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked 6285/// here because otherwise a target specific shuffle node is going to be 6286/// emitted for this shuffle, and the optimization not done. 6287/// FIXME: This is probably not the best approach, but fix the problem 6288/// until the right path is decided. 6289static 6290bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG, 6291 const TargetLowering &TLI) { 6292 EVT VT = V.getValueType(); 6293 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V); 6294 6295 // Be sure that the vector shuffle is present in a pattern like this: 6296 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr) 6297 if (!V.hasOneUse()) 6298 return false; 6299 6300 SDNode *N = *V.getNode()->use_begin(); 6301 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 6302 return false; 6303 6304 SDValue EltNo = N->getOperand(1); 6305 if (!isa<ConstantSDNode>(EltNo)) 6306 return false; 6307 6308 // If the bit convert changed the number of elements, it is unsafe 6309 // to examine the mask. 6310 bool HasShuffleIntoBitcast = false; 6311 if (V.getOpcode() == ISD::BITCAST) { 6312 EVT SrcVT = V.getOperand(0).getValueType(); 6313 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements()) 6314 return false; 6315 V = V.getOperand(0); 6316 HasShuffleIntoBitcast = true; 6317 } 6318 6319 // Select the input vector, guarding against out of range extract vector. 6320 unsigned NumElems = VT.getVectorNumElements(); 6321 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6322 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt); 6323 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1); 6324 6325 // Skip one more bit_convert if necessary 6326 if (V.getOpcode() == ISD::BITCAST) 6327 V = V.getOperand(0); 6328 6329 if (ISD::isNormalLoad(V.getNode())) { 6330 // Is the original load suitable? 6331 LoadSDNode *LN0 = cast<LoadSDNode>(V); 6332 6333 // FIXME: avoid the multi-use bug that is preventing lots of 6334 // of foldings to be detected, this is still wrong of course, but 6335 // give the temporary desired behavior, and if it happens that 6336 // the load has real more uses, during isel it will not fold, and 6337 // will generate poor code. 6338 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse() 6339 return false; 6340 6341 if (!HasShuffleIntoBitcast) 6342 return true; 6343 6344 // If there's a bitcast before the shuffle, check if the load type and 6345 // alignment is valid. 6346 unsigned Align = LN0->getAlignment(); 6347 unsigned NewAlign = 6348 TLI.getTargetData()->getABITypeAlignment( 6349 VT.getTypeForEVT(*DAG.getContext())); 6350 6351 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 6352 return false; 6353 } 6354 6355 return true; 6356} 6357 6358static 6359SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 6360 EVT VT = Op.getValueType(); 6361 6362 // Canonizalize to v2f64. 6363 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6364 return DAG.getNode(ISD::BITCAST, dl, VT, 6365 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6366 V1, DAG)); 6367} 6368 6369static 6370SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 6371 bool HasXMMInt) { 6372 SDValue V1 = Op.getOperand(0); 6373 SDValue V2 = Op.getOperand(1); 6374 EVT VT = Op.getValueType(); 6375 6376 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6377 6378 if (HasXMMInt && VT == MVT::v2f64) 6379 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6380 6381 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6382 return DAG.getNode(ISD::BITCAST, dl, VT, 6383 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6384 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6385 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6386} 6387 6388static 6389SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 6390 SDValue V1 = Op.getOperand(0); 6391 SDValue V2 = Op.getOperand(1); 6392 EVT VT = Op.getValueType(); 6393 6394 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6395 "unsupported shuffle type"); 6396 6397 if (V2.getOpcode() == ISD::UNDEF) 6398 V2 = V1; 6399 6400 // v4i32 or v4f32 6401 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6402} 6403 6404static inline unsigned getSHUFPOpcode(EVT VT) { 6405 switch(VT.getSimpleVT().SimpleTy) { 6406 case MVT::v8i32: // Use fp unit for int unpack. 6407 case MVT::v8f32: 6408 case MVT::v4i32: // Use fp unit for int unpack. 6409 case MVT::v4f32: return X86ISD::SHUFPS; 6410 case MVT::v4i64: // Use fp unit for int unpack. 6411 case MVT::v4f64: 6412 case MVT::v2i64: // Use fp unit for int unpack. 6413 case MVT::v2f64: return X86ISD::SHUFPD; 6414 default: 6415 llvm_unreachable("Unknown type for shufp*"); 6416 } 6417 return 0; 6418} 6419 6420static 6421SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) { 6422 SDValue V1 = Op.getOperand(0); 6423 SDValue V2 = Op.getOperand(1); 6424 EVT VT = Op.getValueType(); 6425 unsigned NumElems = VT.getVectorNumElements(); 6426 6427 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6428 // operand of these instructions is only memory, so check if there's a 6429 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6430 // same masks. 6431 bool CanFoldLoad = false; 6432 6433 // Trivial case, when V2 comes from a load. 6434 if (MayFoldVectorLoad(V2)) 6435 CanFoldLoad = true; 6436 6437 // When V1 is a load, it can be folded later into a store in isel, example: 6438 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6439 // turns into: 6440 // (MOVLPSmr addr:$src1, VR128:$src2) 6441 // So, recognize this potential and also use MOVLPS or MOVLPD 6442 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6443 CanFoldLoad = true; 6444 6445 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6446 if (CanFoldLoad) { 6447 if (HasXMMInt && NumElems == 2) 6448 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6449 6450 if (NumElems == 4) 6451 // If we don't care about the second element, procede to use movss. 6452 if (SVOp->getMaskElt(1) != -1) 6453 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6454 } 6455 6456 // movl and movlp will both match v2i64, but v2i64 is never matched by 6457 // movl earlier because we make it strict to avoid messing with the movlp load 6458 // folding logic (see the code above getMOVLP call). Match it here then, 6459 // this is horrible, but will stay like this until we move all shuffle 6460 // matching to x86 specific nodes. Note that for the 1st condition all 6461 // types are matched with movsd. 6462 if (HasXMMInt) { 6463 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6464 // as to remove this logic from here, as much as possible 6465 if (NumElems == 2 || !X86::isMOVLMask(SVOp)) 6466 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6467 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6468 } 6469 6470 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6471 6472 // Invert the operand order and use SHUFPS to match it. 6473 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1, 6474 X86::getShuffleSHUFImmediate(SVOp), DAG); 6475} 6476 6477static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) { 6478 switch(VT.getSimpleVT().SimpleTy) { 6479 case MVT::v32i8: 6480 case MVT::v16i8: 6481 case MVT::v16i16: 6482 case MVT::v8i16: 6483 case MVT::v4i32: 6484 case MVT::v2i64: return X86ISD::PUNPCKL; 6485 case MVT::v8i32: 6486 case MVT::v4i64: 6487 if (HasAVX2) return X86ISD::PUNPCKL; 6488 // else use fp unit for int unpack. 6489 case MVT::v8f32: 6490 case MVT::v4f32: 6491 case MVT::v4f64: 6492 case MVT::v2f64: return X86ISD::UNPCKLP; 6493 default: 6494 llvm_unreachable("Unknown type for unpckl"); 6495 } 6496 return 0; 6497} 6498 6499static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) { 6500 switch(VT.getSimpleVT().SimpleTy) { 6501 case MVT::v32i8: 6502 case MVT::v16i8: 6503 case MVT::v16i16: 6504 case MVT::v8i16: 6505 case MVT::v4i32: 6506 case MVT::v2i64: return X86ISD::PUNPCKH; 6507 case MVT::v4i64: 6508 case MVT::v8i32: 6509 if (HasAVX2) return X86ISD::PUNPCKH; 6510 // else use fp unit for int unpack. 6511 case MVT::v8f32: 6512 case MVT::v4f32: 6513 case MVT::v4f64: 6514 case MVT::v2f64: return X86ISD::UNPCKHP; 6515 default: 6516 llvm_unreachable("Unknown type for unpckh"); 6517 } 6518 return 0; 6519} 6520 6521static 6522SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG, 6523 const TargetLowering &TLI, 6524 const X86Subtarget *Subtarget) { 6525 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6526 EVT VT = Op.getValueType(); 6527 DebugLoc dl = Op.getDebugLoc(); 6528 SDValue V1 = Op.getOperand(0); 6529 SDValue V2 = Op.getOperand(1); 6530 6531 if (isZeroShuffle(SVOp)) 6532 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl); 6533 6534 // Handle splat operations 6535 if (SVOp->isSplat()) { 6536 unsigned NumElem = VT.getVectorNumElements(); 6537 int Size = VT.getSizeInBits(); 6538 // Special case, this is the only place now where it's allowed to return 6539 // a vector_shuffle operation without using a target specific node, because 6540 // *hopefully* it will be optimized away by the dag combiner. FIXME: should 6541 // this be moved to DAGCombine instead? 6542 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI)) 6543 return Op; 6544 6545 // Use vbroadcast whenever the splat comes from a foldable load 6546 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2()); 6547 if (Subtarget->hasAVX() && LD.getNode()) 6548 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD); 6549 6550 // Handle splats by matching through known shuffle masks 6551 if ((Size == 128 && NumElem <= 4) || 6552 (Size == 256 && NumElem < 8)) 6553 return SDValue(); 6554 6555 // All remaning splats are promoted to target supported vector shuffles. 6556 return PromoteSplat(SVOp, DAG); 6557 } 6558 6559 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6560 // do it! 6561 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 6562 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6563 if (NewOp.getNode()) 6564 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6565 } else if ((VT == MVT::v4i32 || 6566 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) { 6567 // FIXME: Figure out a cleaner way to do this. 6568 // Try to make use of movq to zero out the top part. 6569 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6570 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6571 if (NewOp.getNode()) { 6572 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false)) 6573 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0), 6574 DAG, Subtarget, dl); 6575 } 6576 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6577 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6578 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp))) 6579 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1), 6580 DAG, Subtarget, dl); 6581 } 6582 } 6583 return SDValue(); 6584} 6585 6586SDValue 6587X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6588 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6589 SDValue V1 = Op.getOperand(0); 6590 SDValue V2 = Op.getOperand(1); 6591 EVT VT = Op.getValueType(); 6592 DebugLoc dl = Op.getDebugLoc(); 6593 unsigned NumElems = VT.getVectorNumElements(); 6594 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6595 bool V1IsSplat = false; 6596 bool V2IsSplat = false; 6597 bool HasXMMInt = Subtarget->hasXMMInt(); 6598 bool HasAVX2 = Subtarget->hasAVX2(); 6599 MachineFunction &MF = DAG.getMachineFunction(); 6600 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize); 6601 6602 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 6603 6604 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef"); 6605 6606 // Vector shuffle lowering takes 3 steps: 6607 // 6608 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6609 // narrowing and commutation of operands should be handled. 6610 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6611 // shuffle nodes. 6612 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6613 // so the shuffle can be broken into other shuffles and the legalizer can 6614 // try the lowering again. 6615 // 6616 // The general idea is that no vector_shuffle operation should be left to 6617 // be matched during isel, all of them must be converted to a target specific 6618 // node here. 6619 6620 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6621 // narrowing and commutation of operands should be handled. The actual code 6622 // doesn't include all of those, work in progress... 6623 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget); 6624 if (NewOp.getNode()) 6625 return NewOp; 6626 6627 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6628 // unpckh_undef). Only use pshufd if speed is more important than size. 6629 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp)) 6630 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1, 6631 DAG); 6632 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp)) 6633 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1, 6634 DAG); 6635 6636 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() && 6637 V2IsUndef && RelaxedMayFoldVectorLoad(V1)) 6638 return getMOVDDup(Op, dl, V1, DAG); 6639 6640 if (X86::isMOVHLPS_v_undef_Mask(SVOp)) 6641 return getMOVHighToLow(Op, dl, DAG); 6642 6643 // Use to match splats 6644 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef && 6645 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6646 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1, 6647 DAG); 6648 6649 if (X86::isPSHUFDMask(SVOp)) { 6650 // The actual implementation will match the mask in the if above and then 6651 // during isel it can match several different instructions, not only pshufd 6652 // as its name says, sad but true, emulate the behavior for now... 6653 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6654 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6655 6656 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp); 6657 6658 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6659 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6660 6661 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1, 6662 TargetMask, DAG); 6663 } 6664 6665 // Check if this can be converted into a logical shift. 6666 bool isLeft = false; 6667 unsigned ShAmt = 0; 6668 SDValue ShVal; 6669 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6670 if (isShift && ShVal.hasOneUse()) { 6671 // If the shifted value has multiple uses, it may be cheaper to use 6672 // v_set0 + movlhps or movhlps, etc. 6673 EVT EltVT = VT.getVectorElementType(); 6674 ShAmt *= EltVT.getSizeInBits(); 6675 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6676 } 6677 6678 if (X86::isMOVLMask(SVOp)) { 6679 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6680 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6681 if (!X86::isMOVLPMask(SVOp)) { 6682 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6683 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6684 6685 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6686 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6687 } 6688 } 6689 6690 // FIXME: fold these into legal mask. 6691 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2)) 6692 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt); 6693 6694 if (X86::isMOVHLPSMask(SVOp)) 6695 return getMOVHighToLow(Op, dl, DAG); 6696 6697 if (X86::isMOVSHDUPMask(SVOp, Subtarget)) 6698 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6699 6700 if (X86::isMOVSLDUPMask(SVOp, Subtarget)) 6701 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6702 6703 if (X86::isMOVLPMask(SVOp)) 6704 return getMOVLP(Op, dl, DAG, HasXMMInt); 6705 6706 if (ShouldXformToMOVHLPS(SVOp) || 6707 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp)) 6708 return CommuteVectorShuffle(SVOp, DAG); 6709 6710 if (isShift) { 6711 // No better options. Use a vshl / vsrl. 6712 EVT EltVT = VT.getVectorElementType(); 6713 ShAmt *= EltVT.getSizeInBits(); 6714 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6715 } 6716 6717 bool Commuted = false; 6718 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6719 // 1,1,1,1 -> v8i16 though. 6720 V1IsSplat = isSplatVector(V1.getNode()); 6721 V2IsSplat = isSplatVector(V2.getNode()); 6722 6723 // Canonicalize the splat or undef, if present, to be on the RHS. 6724 if (V1IsSplat && !V2IsSplat) { 6725 Op = CommuteVectorShuffle(SVOp, DAG); 6726 SVOp = cast<ShuffleVectorSDNode>(Op); 6727 V1 = SVOp->getOperand(0); 6728 V2 = SVOp->getOperand(1); 6729 std::swap(V1IsSplat, V2IsSplat); 6730 Commuted = true; 6731 } 6732 6733 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) { 6734 // Shuffling low element of v1 into undef, just return v1. 6735 if (V2IsUndef) 6736 return V1; 6737 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6738 // the instruction selector will not match, so get a canonical MOVL with 6739 // swapped operands to undo the commute. 6740 return getMOVL(DAG, dl, VT, V2, V1); 6741 } 6742 6743 if (X86::isUNPCKLMask(SVOp, HasAVX2)) 6744 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2, 6745 DAG); 6746 6747 if (X86::isUNPCKHMask(SVOp, HasAVX2)) 6748 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2, 6749 DAG); 6750 6751 if (V2IsSplat) { 6752 // Normalize mask so all entries that point to V2 points to its first 6753 // element then try to match unpck{h|l} again. If match, return a 6754 // new vector_shuffle with the corrected mask. 6755 SDValue NewMask = NormalizeMask(SVOp, DAG); 6756 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask); 6757 if (NSVOp != SVOp) { 6758 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) { 6759 return NewMask; 6760 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) { 6761 return NewMask; 6762 } 6763 } 6764 } 6765 6766 if (Commuted) { 6767 // Commute is back and try unpck* again. 6768 // FIXME: this seems wrong. 6769 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG); 6770 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp); 6771 6772 if (X86::isUNPCKLMask(NewSVOp, HasAVX2)) 6773 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1, 6774 DAG); 6775 6776 if (X86::isUNPCKHMask(NewSVOp, HasAVX2)) 6777 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1, 6778 DAG); 6779 } 6780 6781 // Normalize the node to match x86 shuffle ops if needed 6782 if (!V2IsUndef && (isCommutedSHUFP(SVOp) || 6783 isCommutedVSHUFPY(SVOp, Subtarget->hasAVX()))) 6784 return CommuteVectorShuffle(SVOp, DAG); 6785 6786 // The checks below are all present in isShuffleMaskLegal, but they are 6787 // inlined here right now to enable us to directly emit target specific 6788 // nodes, and remove one by one until they don't return Op anymore. 6789 SmallVector<int, 16> M; 6790 SVOp->getMask(M); 6791 6792 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX())) 6793 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 6794 X86::getShufflePALIGNRImmediate(SVOp), 6795 DAG); 6796 6797 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 6798 SVOp->getSplatIndex() == 0 && V2IsUndef) { 6799 if (VT == MVT::v2f64) 6800 return getTargetShuffleNode(X86ISD::UNPCKLP, dl, VT, V1, V1, DAG); 6801 if (VT == MVT::v2i64) 6802 return getTargetShuffleNode(X86ISD::PUNPCKL, dl, VT, V1, V1, DAG); 6803 } 6804 6805 if (isPSHUFHWMask(M, VT)) 6806 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 6807 X86::getShufflePSHUFHWImmediate(SVOp), 6808 DAG); 6809 6810 if (isPSHUFLWMask(M, VT)) 6811 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 6812 X86::getShufflePSHUFLWImmediate(SVOp), 6813 DAG); 6814 6815 if (isSHUFPMask(M, VT)) 6816 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6817 X86::getShuffleSHUFImmediate(SVOp), DAG); 6818 6819 if (X86::isUNPCKL_v_undef_Mask(SVOp)) 6820 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1, 6821 DAG); 6822 if (X86::isUNPCKH_v_undef_Mask(SVOp)) 6823 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1, 6824 DAG); 6825 6826 //===--------------------------------------------------------------------===// 6827 // Generate target specific nodes for 128 or 256-bit shuffles only 6828 // supported in the AVX instruction set. 6829 // 6830 6831 // Handle VMOVDDUPY permutations 6832 if (isMOVDDUPYMask(SVOp, Subtarget)) 6833 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 6834 6835 // Handle VPERMILPS/D* permutations 6836 if (isVPERMILPMask(M, VT, Subtarget->hasAVX())) 6837 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, 6838 getShuffleVPERMILPImmediate(SVOp), DAG); 6839 6840 // Handle VPERM2F128/VPERM2I128 permutations 6841 if (isVPERM2X128Mask(M, VT, Subtarget->hasAVX())) 6842 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1, 6843 V2, getShuffleVPERM2X128Immediate(SVOp), DAG); 6844 6845 // Handle VSHUFPS/DY permutations 6846 if (isVSHUFPYMask(M, VT, Subtarget->hasAVX())) 6847 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, 6848 getShuffleVSHUFPYImmediate(SVOp), DAG); 6849 6850 //===--------------------------------------------------------------------===// 6851 // Since no target specific shuffle was selected for this generic one, 6852 // lower it into other known shuffles. FIXME: this isn't true yet, but 6853 // this is the plan. 6854 // 6855 6856 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 6857 if (VT == MVT::v8i16) { 6858 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG); 6859 if (NewOp.getNode()) 6860 return NewOp; 6861 } 6862 6863 if (VT == MVT::v16i8) { 6864 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 6865 if (NewOp.getNode()) 6866 return NewOp; 6867 } 6868 6869 // Handle all 128-bit wide vectors with 4 elements, and match them with 6870 // several different shuffle types. 6871 if (NumElems == 4 && VT.getSizeInBits() == 128) 6872 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 6873 6874 // Handle general 256-bit shuffles 6875 if (VT.is256BitVector()) 6876 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 6877 6878 return SDValue(); 6879} 6880 6881SDValue 6882X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 6883 SelectionDAG &DAG) const { 6884 EVT VT = Op.getValueType(); 6885 DebugLoc dl = Op.getDebugLoc(); 6886 6887 if (Op.getOperand(0).getValueType().getSizeInBits() != 128) 6888 return SDValue(); 6889 6890 if (VT.getSizeInBits() == 8) { 6891 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 6892 Op.getOperand(0), Op.getOperand(1)); 6893 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6894 DAG.getValueType(VT)); 6895 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6896 } else if (VT.getSizeInBits() == 16) { 6897 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6898 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 6899 if (Idx == 0) 6900 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6901 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6902 DAG.getNode(ISD::BITCAST, dl, 6903 MVT::v4i32, 6904 Op.getOperand(0)), 6905 Op.getOperand(1))); 6906 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 6907 Op.getOperand(0), Op.getOperand(1)); 6908 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 6909 DAG.getValueType(VT)); 6910 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6911 } else if (VT == MVT::f32) { 6912 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 6913 // the result back to FR32 register. It's only worth matching if the 6914 // result has a single use which is a store or a bitcast to i32. And in 6915 // the case of a store, it's not worth it if the index is a constant 0, 6916 // because a MOVSSmr can be used instead, which is smaller and faster. 6917 if (!Op.hasOneUse()) 6918 return SDValue(); 6919 SDNode *User = *Op.getNode()->use_begin(); 6920 if ((User->getOpcode() != ISD::STORE || 6921 (isa<ConstantSDNode>(Op.getOperand(1)) && 6922 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 6923 (User->getOpcode() != ISD::BITCAST || 6924 User->getValueType(0) != MVT::i32)) 6925 return SDValue(); 6926 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6927 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 6928 Op.getOperand(0)), 6929 Op.getOperand(1)); 6930 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 6931 } else if (VT == MVT::i32 || VT == MVT::i64) { 6932 // ExtractPS/pextrq works with constant index. 6933 if (isa<ConstantSDNode>(Op.getOperand(1))) 6934 return Op; 6935 } 6936 return SDValue(); 6937} 6938 6939 6940SDValue 6941X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6942 SelectionDAG &DAG) const { 6943 if (!isa<ConstantSDNode>(Op.getOperand(1))) 6944 return SDValue(); 6945 6946 SDValue Vec = Op.getOperand(0); 6947 EVT VecVT = Vec.getValueType(); 6948 6949 // If this is a 256-bit vector result, first extract the 128-bit vector and 6950 // then extract the element from the 128-bit vector. 6951 if (VecVT.getSizeInBits() == 256) { 6952 DebugLoc dl = Op.getNode()->getDebugLoc(); 6953 unsigned NumElems = VecVT.getVectorNumElements(); 6954 SDValue Idx = Op.getOperand(1); 6955 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 6956 6957 // Get the 128-bit vector. 6958 bool Upper = IdxVal >= NumElems/2; 6959 Vec = Extract128BitVector(Vec, 6960 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl); 6961 6962 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 6963 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx); 6964 } 6965 6966 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length"); 6967 6968 if (Subtarget->hasSSE41orAVX()) { 6969 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 6970 if (Res.getNode()) 6971 return Res; 6972 } 6973 6974 EVT VT = Op.getValueType(); 6975 DebugLoc dl = Op.getDebugLoc(); 6976 // TODO: handle v16i8. 6977 if (VT.getSizeInBits() == 16) { 6978 SDValue Vec = Op.getOperand(0); 6979 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6980 if (Idx == 0) 6981 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 6982 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 6983 DAG.getNode(ISD::BITCAST, dl, 6984 MVT::v4i32, Vec), 6985 Op.getOperand(1))); 6986 // Transform it so it match pextrw which produces a 32-bit result. 6987 EVT EltVT = MVT::i32; 6988 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 6989 Op.getOperand(0), Op.getOperand(1)); 6990 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 6991 DAG.getValueType(VT)); 6992 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 6993 } else if (VT.getSizeInBits() == 32) { 6994 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6995 if (Idx == 0) 6996 return Op; 6997 6998 // SHUFPS the element to the lowest double word, then movss. 6999 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 7000 EVT VVT = Op.getOperand(0).getValueType(); 7001 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7002 DAG.getUNDEF(VVT), Mask); 7003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7004 DAG.getIntPtrConstant(0)); 7005 } else if (VT.getSizeInBits() == 64) { 7006 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 7007 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 7008 // to match extract_elt for f64. 7009 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7010 if (Idx == 0) 7011 return Op; 7012 7013 // UNPCKHPD the element to the lowest double word, then movsd. 7014 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 7015 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 7016 int Mask[2] = { 1, -1 }; 7017 EVT VVT = Op.getOperand(0).getValueType(); 7018 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7019 DAG.getUNDEF(VVT), Mask); 7020 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7021 DAG.getIntPtrConstant(0)); 7022 } 7023 7024 return SDValue(); 7025} 7026 7027SDValue 7028X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 7029 SelectionDAG &DAG) const { 7030 EVT VT = Op.getValueType(); 7031 EVT EltVT = VT.getVectorElementType(); 7032 DebugLoc dl = Op.getDebugLoc(); 7033 7034 SDValue N0 = Op.getOperand(0); 7035 SDValue N1 = Op.getOperand(1); 7036 SDValue N2 = Op.getOperand(2); 7037 7038 if (VT.getSizeInBits() == 256) 7039 return SDValue(); 7040 7041 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 7042 isa<ConstantSDNode>(N2)) { 7043 unsigned Opc; 7044 if (VT == MVT::v8i16) 7045 Opc = X86ISD::PINSRW; 7046 else if (VT == MVT::v16i8) 7047 Opc = X86ISD::PINSRB; 7048 else 7049 Opc = X86ISD::PINSRB; 7050 7051 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 7052 // argument. 7053 if (N1.getValueType() != MVT::i32) 7054 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7055 if (N2.getValueType() != MVT::i32) 7056 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7057 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 7058 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 7059 // Bits [7:6] of the constant are the source select. This will always be 7060 // zero here. The DAG Combiner may combine an extract_elt index into these 7061 // bits. For example (insert (extract, 3), 2) could be matched by putting 7062 // the '3' into bits [7:6] of X86ISD::INSERTPS. 7063 // Bits [5:4] of the constant are the destination select. This is the 7064 // value of the incoming immediate. 7065 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 7066 // combine either bitwise AND or insert of float 0.0 to set these bits. 7067 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 7068 // Create this as a scalar to vector.. 7069 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7070 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7071 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 7072 isa<ConstantSDNode>(N2)) { 7073 // PINSR* works with constant index. 7074 return Op; 7075 } 7076 return SDValue(); 7077} 7078 7079SDValue 7080X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7081 EVT VT = Op.getValueType(); 7082 EVT EltVT = VT.getVectorElementType(); 7083 7084 DebugLoc dl = Op.getDebugLoc(); 7085 SDValue N0 = Op.getOperand(0); 7086 SDValue N1 = Op.getOperand(1); 7087 SDValue N2 = Op.getOperand(2); 7088 7089 // If this is a 256-bit vector result, first extract the 128-bit vector, 7090 // insert the element into the extracted half and then place it back. 7091 if (VT.getSizeInBits() == 256) { 7092 if (!isa<ConstantSDNode>(N2)) 7093 return SDValue(); 7094 7095 // Get the desired 128-bit vector half. 7096 unsigned NumElems = VT.getVectorNumElements(); 7097 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7098 bool Upper = IdxVal >= NumElems/2; 7099 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32); 7100 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl); 7101 7102 // Insert the element into the desired half. 7103 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, 7104 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2); 7105 7106 // Insert the changed part back to the 256-bit vector 7107 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl); 7108 } 7109 7110 if (Subtarget->hasSSE41orAVX()) 7111 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7112 7113 if (EltVT == MVT::i8) 7114 return SDValue(); 7115 7116 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7117 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7118 // as its second argument. 7119 if (N1.getValueType() != MVT::i32) 7120 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7121 if (N2.getValueType() != MVT::i32) 7122 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7123 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7124 } 7125 return SDValue(); 7126} 7127 7128SDValue 7129X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { 7130 LLVMContext *Context = DAG.getContext(); 7131 DebugLoc dl = Op.getDebugLoc(); 7132 EVT OpVT = Op.getValueType(); 7133 7134 // If this is a 256-bit vector result, first insert into a 128-bit 7135 // vector and then insert into the 256-bit vector. 7136 if (OpVT.getSizeInBits() > 128) { 7137 // Insert into a 128-bit vector. 7138 EVT VT128 = EVT::getVectorVT(*Context, 7139 OpVT.getVectorElementType(), 7140 OpVT.getVectorNumElements() / 2); 7141 7142 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7143 7144 // Insert the 128-bit vector. 7145 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op, 7146 DAG.getConstant(0, MVT::i32), 7147 DAG, dl); 7148 } 7149 7150 if (Op.getValueType() == MVT::v1i64 && 7151 Op.getOperand(0).getValueType() == MVT::i64) 7152 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7153 7154 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7155 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 && 7156 "Expected an SSE type!"); 7157 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), 7158 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7159} 7160 7161// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7162// a simple subregister reference or explicit instructions to grab 7163// upper bits of a vector. 7164SDValue 7165X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7166 if (Subtarget->hasAVX()) { 7167 DebugLoc dl = Op.getNode()->getDebugLoc(); 7168 SDValue Vec = Op.getNode()->getOperand(0); 7169 SDValue Idx = Op.getNode()->getOperand(1); 7170 7171 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 7172 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) { 7173 return Extract128BitVector(Vec, Idx, DAG, dl); 7174 } 7175 } 7176 return SDValue(); 7177} 7178 7179// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7180// simple superregister reference or explicit instructions to insert 7181// the upper bits of a vector. 7182SDValue 7183X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { 7184 if (Subtarget->hasAVX()) { 7185 DebugLoc dl = Op.getNode()->getDebugLoc(); 7186 SDValue Vec = Op.getNode()->getOperand(0); 7187 SDValue SubVec = Op.getNode()->getOperand(1); 7188 SDValue Idx = Op.getNode()->getOperand(2); 7189 7190 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 7191 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) { 7192 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl); 7193 } 7194 } 7195 return SDValue(); 7196} 7197 7198// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7199// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7200// one of the above mentioned nodes. It has to be wrapped because otherwise 7201// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7202// be used to form addressing mode. These wrapped nodes will be selected 7203// into MOV32ri. 7204SDValue 7205X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7206 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7207 7208 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7209 // global base reg. 7210 unsigned char OpFlag = 0; 7211 unsigned WrapperKind = X86ISD::Wrapper; 7212 CodeModel::Model M = getTargetMachine().getCodeModel(); 7213 7214 if (Subtarget->isPICStyleRIPRel() && 7215 (M == CodeModel::Small || M == CodeModel::Kernel)) 7216 WrapperKind = X86ISD::WrapperRIP; 7217 else if (Subtarget->isPICStyleGOT()) 7218 OpFlag = X86II::MO_GOTOFF; 7219 else if (Subtarget->isPICStyleStubPIC()) 7220 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7221 7222 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7223 CP->getAlignment(), 7224 CP->getOffset(), OpFlag); 7225 DebugLoc DL = CP->getDebugLoc(); 7226 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7227 // With PIC, the address is actually $g + Offset. 7228 if (OpFlag) { 7229 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7230 DAG.getNode(X86ISD::GlobalBaseReg, 7231 DebugLoc(), getPointerTy()), 7232 Result); 7233 } 7234 7235 return Result; 7236} 7237 7238SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7239 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7240 7241 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7242 // global base reg. 7243 unsigned char OpFlag = 0; 7244 unsigned WrapperKind = X86ISD::Wrapper; 7245 CodeModel::Model M = getTargetMachine().getCodeModel(); 7246 7247 if (Subtarget->isPICStyleRIPRel() && 7248 (M == CodeModel::Small || M == CodeModel::Kernel)) 7249 WrapperKind = X86ISD::WrapperRIP; 7250 else if (Subtarget->isPICStyleGOT()) 7251 OpFlag = X86II::MO_GOTOFF; 7252 else if (Subtarget->isPICStyleStubPIC()) 7253 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7254 7255 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7256 OpFlag); 7257 DebugLoc DL = JT->getDebugLoc(); 7258 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7259 7260 // With PIC, the address is actually $g + Offset. 7261 if (OpFlag) 7262 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7263 DAG.getNode(X86ISD::GlobalBaseReg, 7264 DebugLoc(), getPointerTy()), 7265 Result); 7266 7267 return Result; 7268} 7269 7270SDValue 7271X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7272 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7273 7274 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7275 // global base reg. 7276 unsigned char OpFlag = 0; 7277 unsigned WrapperKind = X86ISD::Wrapper; 7278 CodeModel::Model M = getTargetMachine().getCodeModel(); 7279 7280 if (Subtarget->isPICStyleRIPRel() && 7281 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7282 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7283 OpFlag = X86II::MO_GOTPCREL; 7284 WrapperKind = X86ISD::WrapperRIP; 7285 } else if (Subtarget->isPICStyleGOT()) { 7286 OpFlag = X86II::MO_GOT; 7287 } else if (Subtarget->isPICStyleStubPIC()) { 7288 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7289 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7290 OpFlag = X86II::MO_DARWIN_NONLAZY; 7291 } 7292 7293 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7294 7295 DebugLoc DL = Op.getDebugLoc(); 7296 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7297 7298 7299 // With PIC, the address is actually $g + Offset. 7300 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7301 !Subtarget->is64Bit()) { 7302 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7303 DAG.getNode(X86ISD::GlobalBaseReg, 7304 DebugLoc(), getPointerTy()), 7305 Result); 7306 } 7307 7308 // For symbols that require a load from a stub to get the address, emit the 7309 // load. 7310 if (isGlobalStubReference(OpFlag)) 7311 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7312 MachinePointerInfo::getGOT(), false, false, false, 0); 7313 7314 return Result; 7315} 7316 7317SDValue 7318X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7319 // Create the TargetBlockAddressAddress node. 7320 unsigned char OpFlags = 7321 Subtarget->ClassifyBlockAddressReference(); 7322 CodeModel::Model M = getTargetMachine().getCodeModel(); 7323 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7324 DebugLoc dl = Op.getDebugLoc(); 7325 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), 7326 /*isTarget=*/true, OpFlags); 7327 7328 if (Subtarget->isPICStyleRIPRel() && 7329 (M == CodeModel::Small || M == CodeModel::Kernel)) 7330 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7331 else 7332 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7333 7334 // With PIC, the address is actually $g + Offset. 7335 if (isGlobalRelativeToPICBase(OpFlags)) { 7336 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7337 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7338 Result); 7339 } 7340 7341 return Result; 7342} 7343 7344SDValue 7345X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 7346 int64_t Offset, 7347 SelectionDAG &DAG) const { 7348 // Create the TargetGlobalAddress node, folding in the constant 7349 // offset if it is legal. 7350 unsigned char OpFlags = 7351 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7352 CodeModel::Model M = getTargetMachine().getCodeModel(); 7353 SDValue Result; 7354 if (OpFlags == X86II::MO_NO_FLAG && 7355 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7356 // A direct static reference to a global. 7357 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7358 Offset = 0; 7359 } else { 7360 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7361 } 7362 7363 if (Subtarget->isPICStyleRIPRel() && 7364 (M == CodeModel::Small || M == CodeModel::Kernel)) 7365 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7366 else 7367 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7368 7369 // With PIC, the address is actually $g + Offset. 7370 if (isGlobalRelativeToPICBase(OpFlags)) { 7371 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7372 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7373 Result); 7374 } 7375 7376 // For globals that require a load from a stub to get the address, emit the 7377 // load. 7378 if (isGlobalStubReference(OpFlags)) 7379 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7380 MachinePointerInfo::getGOT(), false, false, false, 0); 7381 7382 // If there was a non-zero offset that we didn't fold, create an explicit 7383 // addition for it. 7384 if (Offset != 0) 7385 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7386 DAG.getConstant(Offset, getPointerTy())); 7387 7388 return Result; 7389} 7390 7391SDValue 7392X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7393 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7394 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7395 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 7396} 7397 7398static SDValue 7399GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7400 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7401 unsigned char OperandFlags) { 7402 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7403 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7404 DebugLoc dl = GA->getDebugLoc(); 7405 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7406 GA->getValueType(0), 7407 GA->getOffset(), 7408 OperandFlags); 7409 if (InFlag) { 7410 SDValue Ops[] = { Chain, TGA, *InFlag }; 7411 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3); 7412 } else { 7413 SDValue Ops[] = { Chain, TGA }; 7414 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2); 7415 } 7416 7417 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7418 MFI->setAdjustsStack(true); 7419 7420 SDValue Flag = Chain.getValue(1); 7421 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7422} 7423 7424// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7425static SDValue 7426LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7427 const EVT PtrVT) { 7428 SDValue InFlag; 7429 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 7430 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7431 DAG.getNode(X86ISD::GlobalBaseReg, 7432 DebugLoc(), PtrVT), InFlag); 7433 InFlag = Chain.getValue(1); 7434 7435 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7436} 7437 7438// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7439static SDValue 7440LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7441 const EVT PtrVT) { 7442 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7443 X86::RAX, X86II::MO_TLSGD); 7444} 7445 7446// Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or 7447// "local exec" model. 7448static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7449 const EVT PtrVT, TLSModel::Model model, 7450 bool is64Bit) { 7451 DebugLoc dl = GA->getDebugLoc(); 7452 7453 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7454 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7455 is64Bit ? 257 : 256)); 7456 7457 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7458 DAG.getIntPtrConstant(0), 7459 MachinePointerInfo(Ptr), 7460 false, false, false, 0); 7461 7462 unsigned char OperandFlags = 0; 7463 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7464 // initialexec. 7465 unsigned WrapperKind = X86ISD::Wrapper; 7466 if (model == TLSModel::LocalExec) { 7467 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7468 } else if (is64Bit) { 7469 assert(model == TLSModel::InitialExec); 7470 OperandFlags = X86II::MO_GOTTPOFF; 7471 WrapperKind = X86ISD::WrapperRIP; 7472 } else { 7473 assert(model == TLSModel::InitialExec); 7474 OperandFlags = X86II::MO_INDNTPOFF; 7475 } 7476 7477 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial 7478 // exec) 7479 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7480 GA->getValueType(0), 7481 GA->getOffset(), OperandFlags); 7482 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7483 7484 if (model == TLSModel::InitialExec) 7485 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7486 MachinePointerInfo::getGOT(), false, false, false, 0); 7487 7488 // The address of the thread local variable is the add of the thread 7489 // pointer with the offset of the variable. 7490 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7491} 7492 7493SDValue 7494X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7495 7496 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7497 const GlobalValue *GV = GA->getGlobal(); 7498 7499 if (Subtarget->isTargetELF()) { 7500 // TODO: implement the "local dynamic" model 7501 // TODO: implement the "initial exec"model for pic executables 7502 7503 // If GV is an alias then use the aliasee for determining 7504 // thread-localness. 7505 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7506 GV = GA->resolveAliasedGlobal(false); 7507 7508 TLSModel::Model model 7509 = getTLSModel(GV, getTargetMachine().getRelocationModel()); 7510 7511 switch (model) { 7512 case TLSModel::GeneralDynamic: 7513 case TLSModel::LocalDynamic: // not implemented 7514 if (Subtarget->is64Bit()) 7515 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7516 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7517 7518 case TLSModel::InitialExec: 7519 case TLSModel::LocalExec: 7520 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7521 Subtarget->is64Bit()); 7522 } 7523 } else if (Subtarget->isTargetDarwin()) { 7524 // Darwin only has one model of TLS. Lower to that. 7525 unsigned char OpFlag = 0; 7526 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7527 X86ISD::WrapperRIP : X86ISD::Wrapper; 7528 7529 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7530 // global base reg. 7531 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7532 !Subtarget->is64Bit(); 7533 if (PIC32) 7534 OpFlag = X86II::MO_TLVP_PIC_BASE; 7535 else 7536 OpFlag = X86II::MO_TLVP; 7537 DebugLoc DL = Op.getDebugLoc(); 7538 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7539 GA->getValueType(0), 7540 GA->getOffset(), OpFlag); 7541 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7542 7543 // With PIC32, the address is actually $g + Offset. 7544 if (PIC32) 7545 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7546 DAG.getNode(X86ISD::GlobalBaseReg, 7547 DebugLoc(), getPointerTy()), 7548 Offset); 7549 7550 // Lowering the machine isd will make sure everything is in the right 7551 // location. 7552 SDValue Chain = DAG.getEntryNode(); 7553 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7554 SDValue Args[] = { Chain, Offset }; 7555 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7556 7557 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7558 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7559 MFI->setAdjustsStack(true); 7560 7561 // And our return value (tls address) is in the standard call return value 7562 // location. 7563 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7564 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 7565 Chain.getValue(1)); 7566 } 7567 7568 assert(false && 7569 "TLS not implemented for this target."); 7570 7571 llvm_unreachable("Unreachable"); 7572 return SDValue(); 7573} 7574 7575 7576/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and 7577/// take a 2 x i32 value to shift plus a shift amount. 7578SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const { 7579 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7580 EVT VT = Op.getValueType(); 7581 unsigned VTBits = VT.getSizeInBits(); 7582 DebugLoc dl = Op.getDebugLoc(); 7583 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7584 SDValue ShOpLo = Op.getOperand(0); 7585 SDValue ShOpHi = Op.getOperand(1); 7586 SDValue ShAmt = Op.getOperand(2); 7587 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7588 DAG.getConstant(VTBits - 1, MVT::i8)) 7589 : DAG.getConstant(0, VT); 7590 7591 SDValue Tmp2, Tmp3; 7592 if (Op.getOpcode() == ISD::SHL_PARTS) { 7593 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7594 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7595 } else { 7596 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7597 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7598 } 7599 7600 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7601 DAG.getConstant(VTBits, MVT::i8)); 7602 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7603 AndNode, DAG.getConstant(0, MVT::i8)); 7604 7605 SDValue Hi, Lo; 7606 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7607 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7608 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7609 7610 if (Op.getOpcode() == ISD::SHL_PARTS) { 7611 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7612 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7613 } else { 7614 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7615 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7616 } 7617 7618 SDValue Ops[2] = { Lo, Hi }; 7619 return DAG.getMergeValues(Ops, 2, dl); 7620} 7621 7622SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7623 SelectionDAG &DAG) const { 7624 EVT SrcVT = Op.getOperand(0).getValueType(); 7625 7626 if (SrcVT.isVector()) 7627 return SDValue(); 7628 7629 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7630 "Unknown SINT_TO_FP to lower!"); 7631 7632 // These are really Legal; return the operand so the caller accepts it as 7633 // Legal. 7634 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 7635 return Op; 7636 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 7637 Subtarget->is64Bit()) { 7638 return Op; 7639 } 7640 7641 DebugLoc dl = Op.getDebugLoc(); 7642 unsigned Size = SrcVT.getSizeInBits()/8; 7643 MachineFunction &MF = DAG.getMachineFunction(); 7644 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 7645 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7646 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7647 StackSlot, 7648 MachinePointerInfo::getFixedStack(SSFI), 7649 false, false, 0); 7650 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 7651} 7652 7653SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 7654 SDValue StackSlot, 7655 SelectionDAG &DAG) const { 7656 // Build the FILD 7657 DebugLoc DL = Op.getDebugLoc(); 7658 SDVTList Tys; 7659 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 7660 if (useSSE) 7661 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 7662 else 7663 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 7664 7665 unsigned ByteSize = SrcVT.getSizeInBits()/8; 7666 7667 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 7668 MachineMemOperand *MMO; 7669 if (FI) { 7670 int SSFI = FI->getIndex(); 7671 MMO = 7672 DAG.getMachineFunction() 7673 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7674 MachineMemOperand::MOLoad, ByteSize, ByteSize); 7675 } else { 7676 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 7677 StackSlot = StackSlot.getOperand(1); 7678 } 7679 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 7680 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 7681 X86ISD::FILD, DL, 7682 Tys, Ops, array_lengthof(Ops), 7683 SrcVT, MMO); 7684 7685 if (useSSE) { 7686 Chain = Result.getValue(1); 7687 SDValue InFlag = Result.getValue(2); 7688 7689 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 7690 // shouldn't be necessary except that RFP cannot be live across 7691 // multiple blocks. When stackifier is fixed, they can be uncoupled. 7692 MachineFunction &MF = DAG.getMachineFunction(); 7693 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 7694 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 7695 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7696 Tys = DAG.getVTList(MVT::Other); 7697 SDValue Ops[] = { 7698 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 7699 }; 7700 MachineMemOperand *MMO = 7701 DAG.getMachineFunction() 7702 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7703 MachineMemOperand::MOStore, SSFISize, SSFISize); 7704 7705 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 7706 Ops, array_lengthof(Ops), 7707 Op.getValueType(), MMO); 7708 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 7709 MachinePointerInfo::getFixedStack(SSFI), 7710 false, false, false, 0); 7711 } 7712 7713 return Result; 7714} 7715 7716// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 7717SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 7718 SelectionDAG &DAG) const { 7719 // This algorithm is not obvious. Here it is in C code, more or less: 7720 /* 7721 double uint64_to_double( uint32_t hi, uint32_t lo ) { 7722 static const __m128i exp = { 0x4330000045300000ULL, 0 }; 7723 static const __m128d bias = { 0x1.0p84, 0x1.0p52 }; 7724 7725 // Copy ints to xmm registers. 7726 __m128i xh = _mm_cvtsi32_si128( hi ); 7727 __m128i xl = _mm_cvtsi32_si128( lo ); 7728 7729 // Combine into low half of a single xmm register. 7730 __m128i x = _mm_unpacklo_epi32( xh, xl ); 7731 __m128d d; 7732 double sd; 7733 7734 // Merge in appropriate exponents to give the integer bits the right 7735 // magnitude. 7736 x = _mm_unpacklo_epi32( x, exp ); 7737 7738 // Subtract away the biases to deal with the IEEE-754 double precision 7739 // implicit 1. 7740 d = _mm_sub_pd( (__m128d) x, bias ); 7741 7742 // All conversions up to here are exact. The correctly rounded result is 7743 // calculated using the current rounding mode using the following 7744 // horizontal add. 7745 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) ); 7746 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this 7747 // store doesn't really need to be here (except 7748 // maybe to zero the other double) 7749 return sd; 7750 } 7751 */ 7752 7753 DebugLoc dl = Op.getDebugLoc(); 7754 LLVMContext *Context = DAG.getContext(); 7755 7756 // Build some magic constants. 7757 std::vector<Constant*> CV0; 7758 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000))); 7759 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000))); 7760 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7761 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0))); 7762 Constant *C0 = ConstantVector::get(CV0); 7763 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 7764 7765 std::vector<Constant*> CV1; 7766 CV1.push_back( 7767 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 7768 CV1.push_back( 7769 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 7770 Constant *C1 = ConstantVector::get(CV1); 7771 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 7772 7773 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7774 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7775 Op.getOperand(0), 7776 DAG.getIntPtrConstant(1))); 7777 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7778 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 7779 Op.getOperand(0), 7780 DAG.getIntPtrConstant(0))); 7781 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2); 7782 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 7783 MachinePointerInfo::getConstantPool(), 7784 false, false, false, 16); 7785 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0); 7786 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2); 7787 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 7788 MachinePointerInfo::getConstantPool(), 7789 false, false, false, 16); 7790 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 7791 7792 // Add the halves; easiest way is to swap them into another reg first. 7793 int ShufMask[2] = { 1, -1 }; 7794 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, 7795 DAG.getUNDEF(MVT::v2f64), ShufMask); 7796 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub); 7797 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add, 7798 DAG.getIntPtrConstant(0)); 7799} 7800 7801// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 7802SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 7803 SelectionDAG &DAG) const { 7804 DebugLoc dl = Op.getDebugLoc(); 7805 // FP constant to bias correct the final result. 7806 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 7807 MVT::f64); 7808 7809 // Load the 32-bit value into an XMM register. 7810 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 7811 Op.getOperand(0)); 7812 7813 // Zero out the upper parts of the register. 7814 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(), 7815 DAG); 7816 7817 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7818 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 7819 DAG.getIntPtrConstant(0)); 7820 7821 // Or the load with the bias. 7822 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 7823 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7824 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7825 MVT::v2f64, Load)), 7826 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 7827 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 7828 MVT::v2f64, Bias))); 7829 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 7830 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 7831 DAG.getIntPtrConstant(0)); 7832 7833 // Subtract the bias. 7834 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 7835 7836 // Handle final rounding. 7837 EVT DestVT = Op.getValueType(); 7838 7839 if (DestVT.bitsLT(MVT::f64)) { 7840 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 7841 DAG.getIntPtrConstant(0)); 7842 } else if (DestVT.bitsGT(MVT::f64)) { 7843 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 7844 } 7845 7846 // Handle final rounding. 7847 return Sub; 7848} 7849 7850SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 7851 SelectionDAG &DAG) const { 7852 SDValue N0 = Op.getOperand(0); 7853 DebugLoc dl = Op.getDebugLoc(); 7854 7855 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 7856 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 7857 // the optimization here. 7858 if (DAG.SignBitIsZero(N0)) 7859 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 7860 7861 EVT SrcVT = N0.getValueType(); 7862 EVT DstVT = Op.getValueType(); 7863 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 7864 return LowerUINT_TO_FP_i64(Op, DAG); 7865 else if (SrcVT == MVT::i32 && X86ScalarSSEf64) 7866 return LowerUINT_TO_FP_i32(Op, DAG); 7867 7868 // Make a 64-bit buffer, and use it to build an FILD. 7869 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 7870 if (SrcVT == MVT::i32) { 7871 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 7872 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 7873 getPointerTy(), StackSlot, WordOff); 7874 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7875 StackSlot, MachinePointerInfo(), 7876 false, false, 0); 7877 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 7878 OffsetSlot, MachinePointerInfo(), 7879 false, false, 0); 7880 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 7881 return Fild; 7882 } 7883 7884 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 7885 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7886 StackSlot, MachinePointerInfo(), 7887 false, false, 0); 7888 // For i64 source, we need to add the appropriate power of 2 if the input 7889 // was negative. This is the same as the optimization in 7890 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 7891 // we must be careful to do the computation in x87 extended precision, not 7892 // in SSE. (The generic code can't know it's OK to do this, or how to.) 7893 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 7894 MachineMemOperand *MMO = 7895 DAG.getMachineFunction() 7896 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7897 MachineMemOperand::MOLoad, 8, 8); 7898 7899 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 7900 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 7901 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 7902 MVT::i64, MMO); 7903 7904 APInt FF(32, 0x5F800000ULL); 7905 7906 // Check whether the sign bit is set. 7907 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 7908 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 7909 ISD::SETLT); 7910 7911 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 7912 SDValue FudgePtr = DAG.getConstantPool( 7913 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 7914 getPointerTy()); 7915 7916 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 7917 SDValue Zero = DAG.getIntPtrConstant(0); 7918 SDValue Four = DAG.getIntPtrConstant(4); 7919 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 7920 Zero, Four); 7921 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 7922 7923 // Load the value out, extending it from f32 to f80. 7924 // FIXME: Avoid the extend by constructing the right constant pool? 7925 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 7926 FudgePtr, MachinePointerInfo::getConstantPool(), 7927 MVT::f32, false, false, 4); 7928 // Extend everything to 80 bits to force it to be done on x87. 7929 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 7930 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 7931} 7932 7933std::pair<SDValue,SDValue> X86TargetLowering:: 7934FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const { 7935 DebugLoc DL = Op.getDebugLoc(); 7936 7937 EVT DstTy = Op.getValueType(); 7938 7939 if (!IsSigned) { 7940 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 7941 DstTy = MVT::i64; 7942 } 7943 7944 assert(DstTy.getSimpleVT() <= MVT::i64 && 7945 DstTy.getSimpleVT() >= MVT::i16 && 7946 "Unknown FP_TO_SINT to lower!"); 7947 7948 // These are really Legal. 7949 if (DstTy == MVT::i32 && 7950 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7951 return std::make_pair(SDValue(), SDValue()); 7952 if (Subtarget->is64Bit() && 7953 DstTy == MVT::i64 && 7954 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 7955 return std::make_pair(SDValue(), SDValue()); 7956 7957 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary 7958 // stack slot. 7959 MachineFunction &MF = DAG.getMachineFunction(); 7960 unsigned MemSize = DstTy.getSizeInBits()/8; 7961 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7963 7964 7965 7966 unsigned Opc; 7967 switch (DstTy.getSimpleVT().SimpleTy) { 7968 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 7969 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 7970 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 7971 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 7972 } 7973 7974 SDValue Chain = DAG.getEntryNode(); 7975 SDValue Value = Op.getOperand(0); 7976 EVT TheVT = Op.getOperand(0).getValueType(); 7977 if (isScalarFPTypeInSSEReg(TheVT)) { 7978 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 7979 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 7980 MachinePointerInfo::getFixedStack(SSFI), 7981 false, false, 0); 7982 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 7983 SDValue Ops[] = { 7984 Chain, StackSlot, DAG.getValueType(TheVT) 7985 }; 7986 7987 MachineMemOperand *MMO = 7988 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7989 MachineMemOperand::MOLoad, MemSize, MemSize); 7990 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 7991 DstTy, MMO); 7992 Chain = Value.getValue(1); 7993 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 7994 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7995 } 7996 7997 MachineMemOperand *MMO = 7998 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7999 MachineMemOperand::MOStore, MemSize, MemSize); 8000 8001 // Build the FP_TO_INT*_IN_MEM 8002 SDValue Ops[] = { Chain, Value, StackSlot }; 8003 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8004 Ops, 3, DstTy, MMO); 8005 8006 return std::make_pair(FIST, StackSlot); 8007} 8008 8009SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8010 SelectionDAG &DAG) const { 8011 if (Op.getValueType().isVector()) 8012 return SDValue(); 8013 8014 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true); 8015 SDValue FIST = Vals.first, StackSlot = Vals.second; 8016 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8017 if (FIST.getNode() == 0) return Op; 8018 8019 // Load the result. 8020 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8021 FIST, StackSlot, MachinePointerInfo(), 8022 false, false, false, 0); 8023} 8024 8025SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8026 SelectionDAG &DAG) const { 8027 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false); 8028 SDValue FIST = Vals.first, StackSlot = Vals.second; 8029 assert(FIST.getNode() && "Unexpected failure"); 8030 8031 // Load the result. 8032 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8033 FIST, StackSlot, MachinePointerInfo(), 8034 false, false, false, 0); 8035} 8036 8037SDValue X86TargetLowering::LowerFABS(SDValue Op, 8038 SelectionDAG &DAG) const { 8039 LLVMContext *Context = DAG.getContext(); 8040 DebugLoc dl = Op.getDebugLoc(); 8041 EVT VT = Op.getValueType(); 8042 EVT EltVT = VT; 8043 if (VT.isVector()) 8044 EltVT = VT.getVectorElementType(); 8045 std::vector<Constant*> CV; 8046 if (EltVT == MVT::f64) { 8047 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 8048 CV.push_back(C); 8049 CV.push_back(C); 8050 } else { 8051 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 8052 CV.push_back(C); 8053 CV.push_back(C); 8054 CV.push_back(C); 8055 CV.push_back(C); 8056 } 8057 Constant *C = ConstantVector::get(CV); 8058 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8059 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8060 MachinePointerInfo::getConstantPool(), 8061 false, false, false, 16); 8062 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 8063} 8064 8065SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 8066 LLVMContext *Context = DAG.getContext(); 8067 DebugLoc dl = Op.getDebugLoc(); 8068 EVT VT = Op.getValueType(); 8069 EVT EltVT = VT; 8070 if (VT.isVector()) 8071 EltVT = VT.getVectorElementType(); 8072 std::vector<Constant*> CV; 8073 if (EltVT == MVT::f64) { 8074 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 8075 CV.push_back(C); 8076 CV.push_back(C); 8077 } else { 8078 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 8079 CV.push_back(C); 8080 CV.push_back(C); 8081 CV.push_back(C); 8082 CV.push_back(C); 8083 } 8084 Constant *C = ConstantVector::get(CV); 8085 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8086 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8087 MachinePointerInfo::getConstantPool(), 8088 false, false, false, 16); 8089 if (VT.isVector()) { 8090 return DAG.getNode(ISD::BITCAST, dl, VT, 8091 DAG.getNode(ISD::XOR, dl, MVT::v2i64, 8092 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8093 Op.getOperand(0)), 8094 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask))); 8095 } else { 8096 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8097 } 8098} 8099 8100SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8101 LLVMContext *Context = DAG.getContext(); 8102 SDValue Op0 = Op.getOperand(0); 8103 SDValue Op1 = Op.getOperand(1); 8104 DebugLoc dl = Op.getDebugLoc(); 8105 EVT VT = Op.getValueType(); 8106 EVT SrcVT = Op1.getValueType(); 8107 8108 // If second operand is smaller, extend it first. 8109 if (SrcVT.bitsLT(VT)) { 8110 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8111 SrcVT = VT; 8112 } 8113 // And if it is bigger, shrink it first. 8114 if (SrcVT.bitsGT(VT)) { 8115 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8116 SrcVT = VT; 8117 } 8118 8119 // At this point the operands and the result should have the same 8120 // type, and that won't be f80 since that is not custom lowered. 8121 8122 // First get the sign bit of second operand. 8123 std::vector<Constant*> CV; 8124 if (SrcVT == MVT::f64) { 8125 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 8126 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8127 } else { 8128 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 8129 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8130 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8131 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8132 } 8133 Constant *C = ConstantVector::get(CV); 8134 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8135 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8136 MachinePointerInfo::getConstantPool(), 8137 false, false, false, 16); 8138 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8139 8140 // Shift sign bit right or left if the two operands have different types. 8141 if (SrcVT.bitsGT(VT)) { 8142 // Op0 is MVT::f32, Op1 is MVT::f64. 8143 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8144 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8145 DAG.getConstant(32, MVT::i32)); 8146 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8147 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8148 DAG.getIntPtrConstant(0)); 8149 } 8150 8151 // Clear first operand sign bit. 8152 CV.clear(); 8153 if (VT == MVT::f64) { 8154 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8155 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8156 } else { 8157 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8158 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8159 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8160 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8161 } 8162 C = ConstantVector::get(CV); 8163 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8164 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8165 MachinePointerInfo::getConstantPool(), 8166 false, false, false, 16); 8167 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8168 8169 // Or the value with the sign bit. 8170 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8171} 8172 8173SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const { 8174 SDValue N0 = Op.getOperand(0); 8175 DebugLoc dl = Op.getDebugLoc(); 8176 EVT VT = Op.getValueType(); 8177 8178 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8179 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8180 DAG.getConstant(1, VT)); 8181 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8182} 8183 8184/// Emit nodes that will be selected as "test Op0,Op0", or something 8185/// equivalent. 8186SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8187 SelectionDAG &DAG) const { 8188 DebugLoc dl = Op.getDebugLoc(); 8189 8190 // CF and OF aren't always set the way we want. Determine which 8191 // of these we need. 8192 bool NeedCF = false; 8193 bool NeedOF = false; 8194 switch (X86CC) { 8195 default: break; 8196 case X86::COND_A: case X86::COND_AE: 8197 case X86::COND_B: case X86::COND_BE: 8198 NeedCF = true; 8199 break; 8200 case X86::COND_G: case X86::COND_GE: 8201 case X86::COND_L: case X86::COND_LE: 8202 case X86::COND_O: case X86::COND_NO: 8203 NeedOF = true; 8204 break; 8205 } 8206 8207 // See if we can use the EFLAGS value from the operand instead of 8208 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8209 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8210 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8211 // Emit a CMP with 0, which is the TEST pattern. 8212 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8213 DAG.getConstant(0, Op.getValueType())); 8214 8215 unsigned Opcode = 0; 8216 unsigned NumOperands = 0; 8217 switch (Op.getNode()->getOpcode()) { 8218 case ISD::ADD: 8219 // Due to an isel shortcoming, be conservative if this add is likely to be 8220 // selected as part of a load-modify-store instruction. When the root node 8221 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8222 // uses of other nodes in the match, such as the ADD in this case. This 8223 // leads to the ADD being left around and reselected, with the result being 8224 // two adds in the output. Alas, even if none our users are stores, that 8225 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8226 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8227 // climbing the DAG back to the root, and it doesn't seem to be worth the 8228 // effort. 8229 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8230 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8231 if (UI->getOpcode() != ISD::CopyToReg && 8232 UI->getOpcode() != ISD::SETCC && 8233 UI->getOpcode() != ISD::STORE) 8234 goto default_case; 8235 8236 if (ConstantSDNode *C = 8237 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) { 8238 // An add of one will be selected as an INC. 8239 if (C->getAPIntValue() == 1) { 8240 Opcode = X86ISD::INC; 8241 NumOperands = 1; 8242 break; 8243 } 8244 8245 // An add of negative one (subtract of one) will be selected as a DEC. 8246 if (C->getAPIntValue().isAllOnesValue()) { 8247 Opcode = X86ISD::DEC; 8248 NumOperands = 1; 8249 break; 8250 } 8251 } 8252 8253 // Otherwise use a regular EFLAGS-setting add. 8254 Opcode = X86ISD::ADD; 8255 NumOperands = 2; 8256 break; 8257 case ISD::AND: { 8258 // If the primary and result isn't used, don't bother using X86ISD::AND, 8259 // because a TEST instruction will be better. 8260 bool NonFlagUse = false; 8261 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8262 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 8263 SDNode *User = *UI; 8264 unsigned UOpNo = UI.getOperandNo(); 8265 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 8266 // Look pass truncate. 8267 UOpNo = User->use_begin().getOperandNo(); 8268 User = *User->use_begin(); 8269 } 8270 8271 if (User->getOpcode() != ISD::BRCOND && 8272 User->getOpcode() != ISD::SETCC && 8273 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) { 8274 NonFlagUse = true; 8275 break; 8276 } 8277 } 8278 8279 if (!NonFlagUse) 8280 break; 8281 } 8282 // FALL THROUGH 8283 case ISD::SUB: 8284 case ISD::OR: 8285 case ISD::XOR: 8286 // Due to the ISEL shortcoming noted above, be conservative if this op is 8287 // likely to be selected as part of a load-modify-store instruction. 8288 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8289 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8290 if (UI->getOpcode() == ISD::STORE) 8291 goto default_case; 8292 8293 // Otherwise use a regular EFLAGS-setting instruction. 8294 switch (Op.getNode()->getOpcode()) { 8295 default: llvm_unreachable("unexpected operator!"); 8296 case ISD::SUB: Opcode = X86ISD::SUB; break; 8297 case ISD::OR: Opcode = X86ISD::OR; break; 8298 case ISD::XOR: Opcode = X86ISD::XOR; break; 8299 case ISD::AND: Opcode = X86ISD::AND; break; 8300 } 8301 8302 NumOperands = 2; 8303 break; 8304 case X86ISD::ADD: 8305 case X86ISD::SUB: 8306 case X86ISD::INC: 8307 case X86ISD::DEC: 8308 case X86ISD::OR: 8309 case X86ISD::XOR: 8310 case X86ISD::AND: 8311 return SDValue(Op.getNode(), 1); 8312 default: 8313 default_case: 8314 break; 8315 } 8316 8317 if (Opcode == 0) 8318 // Emit a CMP with 0, which is the TEST pattern. 8319 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8320 DAG.getConstant(0, Op.getValueType())); 8321 8322 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 8323 SmallVector<SDValue, 4> Ops; 8324 for (unsigned i = 0; i != NumOperands; ++i) 8325 Ops.push_back(Op.getOperand(i)); 8326 8327 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 8328 DAG.ReplaceAllUsesWith(Op, New); 8329 return SDValue(New.getNode(), 1); 8330} 8331 8332/// Emit nodes that will be selected as "cmp Op0,Op1", or something 8333/// equivalent. 8334SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 8335 SelectionDAG &DAG) const { 8336 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 8337 if (C->getAPIntValue() == 0) 8338 return EmitTest(Op0, X86CC, DAG); 8339 8340 DebugLoc dl = Op0.getDebugLoc(); 8341 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 8342} 8343 8344/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 8345/// if it's possible. 8346SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 8347 DebugLoc dl, SelectionDAG &DAG) const { 8348 SDValue Op0 = And.getOperand(0); 8349 SDValue Op1 = And.getOperand(1); 8350 if (Op0.getOpcode() == ISD::TRUNCATE) 8351 Op0 = Op0.getOperand(0); 8352 if (Op1.getOpcode() == ISD::TRUNCATE) 8353 Op1 = Op1.getOperand(0); 8354 8355 SDValue LHS, RHS; 8356 if (Op1.getOpcode() == ISD::SHL) 8357 std::swap(Op0, Op1); 8358 if (Op0.getOpcode() == ISD::SHL) { 8359 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 8360 if (And00C->getZExtValue() == 1) { 8361 // If we looked past a truncate, check that it's only truncating away 8362 // known zeros. 8363 unsigned BitWidth = Op0.getValueSizeInBits(); 8364 unsigned AndBitWidth = And.getValueSizeInBits(); 8365 if (BitWidth > AndBitWidth) { 8366 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones; 8367 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones); 8368 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 8369 return SDValue(); 8370 } 8371 LHS = Op1; 8372 RHS = Op0.getOperand(1); 8373 } 8374 } else if (Op1.getOpcode() == ISD::Constant) { 8375 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 8376 uint64_t AndRHSVal = AndRHS->getZExtValue(); 8377 SDValue AndLHS = Op0; 8378 8379 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) { 8380 LHS = AndLHS.getOperand(0); 8381 RHS = AndLHS.getOperand(1); 8382 } 8383 8384 // Use BT if the immediate can't be encoded in a TEST instruction. 8385 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) { 8386 LHS = AndLHS; 8387 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType()); 8388 } 8389 } 8390 8391 if (LHS.getNode()) { 8392 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 8393 // instruction. Since the shift amount is in-range-or-undefined, we know 8394 // that doing a bittest on the i32 value is ok. We extend to i32 because 8395 // the encoding for the i16 version is larger than the i32 version. 8396 // Also promote i16 to i32 for performance / code size reason. 8397 if (LHS.getValueType() == MVT::i8 || 8398 LHS.getValueType() == MVT::i16) 8399 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 8400 8401 // If the operand types disagree, extend the shift amount to match. Since 8402 // BT ignores high bits (like shifts) we can use anyextend. 8403 if (LHS.getValueType() != RHS.getValueType()) 8404 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 8405 8406 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 8407 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 8408 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8409 DAG.getConstant(Cond, MVT::i8), BT); 8410 } 8411 8412 return SDValue(); 8413} 8414 8415SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 8416 8417 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); 8418 8419 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 8420 SDValue Op0 = Op.getOperand(0); 8421 SDValue Op1 = Op.getOperand(1); 8422 DebugLoc dl = Op.getDebugLoc(); 8423 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8424 8425 // Optimize to BT if possible. 8426 // Lower (X & (1 << N)) == 0 to BT(X, N). 8427 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 8428 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 8429 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 8430 Op1.getOpcode() == ISD::Constant && 8431 cast<ConstantSDNode>(Op1)->isNullValue() && 8432 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8433 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 8434 if (NewSetCC.getNode()) 8435 return NewSetCC; 8436 } 8437 8438 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 8439 // these. 8440 if (Op1.getOpcode() == ISD::Constant && 8441 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 8442 cast<ConstantSDNode>(Op1)->isNullValue()) && 8443 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 8444 8445 // If the input is a setcc, then reuse the input setcc or use a new one with 8446 // the inverted condition. 8447 if (Op0.getOpcode() == X86ISD::SETCC) { 8448 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 8449 bool Invert = (CC == ISD::SETNE) ^ 8450 cast<ConstantSDNode>(Op1)->isNullValue(); 8451 if (!Invert) return Op0; 8452 8453 CCode = X86::GetOppositeBranchCondition(CCode); 8454 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8455 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 8456 } 8457 } 8458 8459 bool isFP = Op1.getValueType().isFloatingPoint(); 8460 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 8461 if (X86CC == X86::COND_INVALID) 8462 return SDValue(); 8463 8464 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 8465 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 8466 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 8467} 8468 8469// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 8470// ones, and then concatenate the result back. 8471static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 8472 EVT VT = Op.getValueType(); 8473 8474 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC && 8475 "Unsupported value type for operation"); 8476 8477 int NumElems = VT.getVectorNumElements(); 8478 DebugLoc dl = Op.getDebugLoc(); 8479 SDValue CC = Op.getOperand(2); 8480 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 8481 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 8482 8483 // Extract the LHS vectors 8484 SDValue LHS = Op.getOperand(0); 8485 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 8486 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 8487 8488 // Extract the RHS vectors 8489 SDValue RHS = Op.getOperand(1); 8490 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 8491 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 8492 8493 // Issue the operation on the smaller types and concatenate the result back 8494 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 8495 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 8496 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 8497 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 8498 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 8499} 8500 8501 8502SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 8503 SDValue Cond; 8504 SDValue Op0 = Op.getOperand(0); 8505 SDValue Op1 = Op.getOperand(1); 8506 SDValue CC = Op.getOperand(2); 8507 EVT VT = Op.getValueType(); 8508 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 8509 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 8510 DebugLoc dl = Op.getDebugLoc(); 8511 8512 if (isFP) { 8513 unsigned SSECC = 8; 8514 EVT EltVT = Op0.getValueType().getVectorElementType(); 8515 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 8516 8517 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD; 8518 bool Swap = false; 8519 8520 // SSE Condition code mapping: 8521 // 0 - EQ 8522 // 1 - LT 8523 // 2 - LE 8524 // 3 - UNORD 8525 // 4 - NEQ 8526 // 5 - NLT 8527 // 6 - NLE 8528 // 7 - ORD 8529 switch (SetCCOpcode) { 8530 default: break; 8531 case ISD::SETOEQ: 8532 case ISD::SETEQ: SSECC = 0; break; 8533 case ISD::SETOGT: 8534 case ISD::SETGT: Swap = true; // Fallthrough 8535 case ISD::SETLT: 8536 case ISD::SETOLT: SSECC = 1; break; 8537 case ISD::SETOGE: 8538 case ISD::SETGE: Swap = true; // Fallthrough 8539 case ISD::SETLE: 8540 case ISD::SETOLE: SSECC = 2; break; 8541 case ISD::SETUO: SSECC = 3; break; 8542 case ISD::SETUNE: 8543 case ISD::SETNE: SSECC = 4; break; 8544 case ISD::SETULE: Swap = true; 8545 case ISD::SETUGE: SSECC = 5; break; 8546 case ISD::SETULT: Swap = true; 8547 case ISD::SETUGT: SSECC = 6; break; 8548 case ISD::SETO: SSECC = 7; break; 8549 } 8550 if (Swap) 8551 std::swap(Op0, Op1); 8552 8553 // In the two special cases we can't handle, emit two comparisons. 8554 if (SSECC == 8) { 8555 if (SetCCOpcode == ISD::SETUEQ) { 8556 SDValue UNORD, EQ; 8557 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8)); 8558 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8)); 8559 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ); 8560 } else if (SetCCOpcode == ISD::SETONE) { 8561 SDValue ORD, NEQ; 8562 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8)); 8563 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8)); 8564 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ); 8565 } 8566 llvm_unreachable("Illegal FP comparison"); 8567 } 8568 // Handle all other FP comparisons here. 8569 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8)); 8570 } 8571 8572 // Break 256-bit integer vector compare into smaller ones. 8573 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 8574 return Lower256IntVSETCC(Op, DAG); 8575 8576 // We are handling one of the integer comparisons here. Since SSE only has 8577 // GT and EQ comparisons for integer, swapping operands and multiple 8578 // operations may be required for some comparisons. 8579 unsigned Opc = 0, EQOpc = 0, GTOpc = 0; 8580 bool Swap = false, Invert = false, FlipSigns = false; 8581 8582 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) { 8583 default: break; 8584 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break; 8585 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break; 8586 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break; 8587 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break; 8588 } 8589 8590 switch (SetCCOpcode) { 8591 default: break; 8592 case ISD::SETNE: Invert = true; 8593 case ISD::SETEQ: Opc = EQOpc; break; 8594 case ISD::SETLT: Swap = true; 8595 case ISD::SETGT: Opc = GTOpc; break; 8596 case ISD::SETGE: Swap = true; 8597 case ISD::SETLE: Opc = GTOpc; Invert = true; break; 8598 case ISD::SETULT: Swap = true; 8599 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break; 8600 case ISD::SETUGE: Swap = true; 8601 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break; 8602 } 8603 if (Swap) 8604 std::swap(Op0, Op1); 8605 8606 // Check that the operation in question is available (most are plain SSE2, 8607 // but PCMPGTQ and PCMPEQQ have different requirements). 8608 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX()) 8609 return SDValue(); 8610 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX()) 8611 return SDValue(); 8612 8613 // Since SSE has no unsigned integer comparisons, we need to flip the sign 8614 // bits of the inputs before performing those operations. 8615 if (FlipSigns) { 8616 EVT EltVT = VT.getVectorElementType(); 8617 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 8618 EltVT); 8619 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 8620 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 8621 SignBits.size()); 8622 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 8623 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 8624 } 8625 8626 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 8627 8628 // If the logical-not of the result is required, perform that now. 8629 if (Invert) 8630 Result = DAG.getNOT(dl, Result, VT); 8631 8632 return Result; 8633} 8634 8635// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 8636static bool isX86LogicalCmp(SDValue Op) { 8637 unsigned Opc = Op.getNode()->getOpcode(); 8638 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI) 8639 return true; 8640 if (Op.getResNo() == 1 && 8641 (Opc == X86ISD::ADD || 8642 Opc == X86ISD::SUB || 8643 Opc == X86ISD::ADC || 8644 Opc == X86ISD::SBB || 8645 Opc == X86ISD::SMUL || 8646 Opc == X86ISD::UMUL || 8647 Opc == X86ISD::INC || 8648 Opc == X86ISD::DEC || 8649 Opc == X86ISD::OR || 8650 Opc == X86ISD::XOR || 8651 Opc == X86ISD::AND)) 8652 return true; 8653 8654 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 8655 return true; 8656 8657 return false; 8658} 8659 8660static bool isZero(SDValue V) { 8661 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8662 return C && C->isNullValue(); 8663} 8664 8665static bool isAllOnes(SDValue V) { 8666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 8667 return C && C->isAllOnesValue(); 8668} 8669 8670SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8671 bool addTest = true; 8672 SDValue Cond = Op.getOperand(0); 8673 SDValue Op1 = Op.getOperand(1); 8674 SDValue Op2 = Op.getOperand(2); 8675 DebugLoc DL = Op.getDebugLoc(); 8676 SDValue CC; 8677 8678 if (Cond.getOpcode() == ISD::SETCC) { 8679 SDValue NewCond = LowerSETCC(Cond, DAG); 8680 if (NewCond.getNode()) 8681 Cond = NewCond; 8682 } 8683 8684 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 8685 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 8686 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 8687 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 8688 if (Cond.getOpcode() == X86ISD::SETCC && 8689 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 8690 isZero(Cond.getOperand(1).getOperand(1))) { 8691 SDValue Cmp = Cond.getOperand(1); 8692 8693 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 8694 8695 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 8696 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 8697 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 8698 8699 SDValue CmpOp0 = Cmp.getOperand(0); 8700 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 8701 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 8702 8703 SDValue Res = // Res = 0 or -1. 8704 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8705 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 8706 8707 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 8708 Res = DAG.getNOT(DL, Res, Res.getValueType()); 8709 8710 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 8711 if (N2C == 0 || !N2C->isNullValue()) 8712 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 8713 return Res; 8714 } 8715 } 8716 8717 // Look past (and (setcc_carry (cmp ...)), 1). 8718 if (Cond.getOpcode() == ISD::AND && 8719 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8720 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8721 if (C && C->getAPIntValue() == 1) 8722 Cond = Cond.getOperand(0); 8723 } 8724 8725 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8726 // setting operand in place of the X86ISD::SETCC. 8727 unsigned CondOpcode = Cond.getOpcode(); 8728 if (CondOpcode == X86ISD::SETCC || 8729 CondOpcode == X86ISD::SETCC_CARRY) { 8730 CC = Cond.getOperand(0); 8731 8732 SDValue Cmp = Cond.getOperand(1); 8733 unsigned Opc = Cmp.getOpcode(); 8734 EVT VT = Op.getValueType(); 8735 8736 bool IllegalFPCMov = false; 8737 if (VT.isFloatingPoint() && !VT.isVector() && 8738 !isScalarFPTypeInSSEReg(VT)) // FPStack? 8739 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 8740 8741 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 8742 Opc == X86ISD::BT) { // FIXME 8743 Cond = Cmp; 8744 addTest = false; 8745 } 8746 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 8747 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 8748 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 8749 Cond.getOperand(0).getValueType() != MVT::i8)) { 8750 SDValue LHS = Cond.getOperand(0); 8751 SDValue RHS = Cond.getOperand(1); 8752 unsigned X86Opcode; 8753 unsigned X86Cond; 8754 SDVTList VTs; 8755 switch (CondOpcode) { 8756 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 8757 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 8758 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 8759 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 8760 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 8761 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 8762 default: llvm_unreachable("unexpected overflowing operator"); 8763 } 8764 if (CondOpcode == ISD::UMULO) 8765 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 8766 MVT::i32); 8767 else 8768 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 8769 8770 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 8771 8772 if (CondOpcode == ISD::UMULO) 8773 Cond = X86Op.getValue(2); 8774 else 8775 Cond = X86Op.getValue(1); 8776 8777 CC = DAG.getConstant(X86Cond, MVT::i8); 8778 addTest = false; 8779 } 8780 8781 if (addTest) { 8782 // Look pass the truncate. 8783 if (Cond.getOpcode() == ISD::TRUNCATE) 8784 Cond = Cond.getOperand(0); 8785 8786 // We know the result of AND is compared against zero. Try to match 8787 // it to BT. 8788 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 8789 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 8790 if (NewSetCC.getNode()) { 8791 CC = NewSetCC.getOperand(0); 8792 Cond = NewSetCC.getOperand(1); 8793 addTest = false; 8794 } 8795 } 8796 } 8797 8798 if (addTest) { 8799 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 8800 Cond = EmitTest(Cond, X86::COND_NE, DAG); 8801 } 8802 8803 // a < b ? -1 : 0 -> RES = ~setcc_carry 8804 // a < b ? 0 : -1 -> RES = setcc_carry 8805 // a >= b ? -1 : 0 -> RES = setcc_carry 8806 // a >= b ? 0 : -1 -> RES = ~setcc_carry 8807 if (Cond.getOpcode() == X86ISD::CMP) { 8808 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 8809 8810 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 8811 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 8812 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 8813 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 8814 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 8815 return DAG.getNOT(DL, Res, Res.getValueType()); 8816 return Res; 8817 } 8818 } 8819 8820 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 8821 // condition is true. 8822 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 8823 SDValue Ops[] = { Op2, Op1, CC, Cond }; 8824 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 8825} 8826 8827// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 8828// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 8829// from the AND / OR. 8830static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 8831 Opc = Op.getOpcode(); 8832 if (Opc != ISD::OR && Opc != ISD::AND) 8833 return false; 8834 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8835 Op.getOperand(0).hasOneUse() && 8836 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 8837 Op.getOperand(1).hasOneUse()); 8838} 8839 8840// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 8841// 1 and that the SETCC node has a single use. 8842static bool isXor1OfSetCC(SDValue Op) { 8843 if (Op.getOpcode() != ISD::XOR) 8844 return false; 8845 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8846 if (N1C && N1C->getAPIntValue() == 1) { 8847 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 8848 Op.getOperand(0).hasOneUse(); 8849 } 8850 return false; 8851} 8852 8853SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 8854 bool addTest = true; 8855 SDValue Chain = Op.getOperand(0); 8856 SDValue Cond = Op.getOperand(1); 8857 SDValue Dest = Op.getOperand(2); 8858 DebugLoc dl = Op.getDebugLoc(); 8859 SDValue CC; 8860 bool Inverted = false; 8861 8862 if (Cond.getOpcode() == ISD::SETCC) { 8863 // Check for setcc([su]{add,sub,mul}o == 0). 8864 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 8865 isa<ConstantSDNode>(Cond.getOperand(1)) && 8866 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 8867 Cond.getOperand(0).getResNo() == 1 && 8868 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 8869 Cond.getOperand(0).getOpcode() == ISD::UADDO || 8870 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 8871 Cond.getOperand(0).getOpcode() == ISD::USUBO || 8872 Cond.getOperand(0).getOpcode() == ISD::SMULO || 8873 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 8874 Inverted = true; 8875 Cond = Cond.getOperand(0); 8876 } else { 8877 SDValue NewCond = LowerSETCC(Cond, DAG); 8878 if (NewCond.getNode()) 8879 Cond = NewCond; 8880 } 8881 } 8882#if 0 8883 // FIXME: LowerXALUO doesn't handle these!! 8884 else if (Cond.getOpcode() == X86ISD::ADD || 8885 Cond.getOpcode() == X86ISD::SUB || 8886 Cond.getOpcode() == X86ISD::SMUL || 8887 Cond.getOpcode() == X86ISD::UMUL) 8888 Cond = LowerXALUO(Cond, DAG); 8889#endif 8890 8891 // Look pass (and (setcc_carry (cmp ...)), 1). 8892 if (Cond.getOpcode() == ISD::AND && 8893 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 8894 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 8895 if (C && C->getAPIntValue() == 1) 8896 Cond = Cond.getOperand(0); 8897 } 8898 8899 // If condition flag is set by a X86ISD::CMP, then use it as the condition 8900 // setting operand in place of the X86ISD::SETCC. 8901 unsigned CondOpcode = Cond.getOpcode(); 8902 if (CondOpcode == X86ISD::SETCC || 8903 CondOpcode == X86ISD::SETCC_CARRY) { 8904 CC = Cond.getOperand(0); 8905 8906 SDValue Cmp = Cond.getOperand(1); 8907 unsigned Opc = Cmp.getOpcode(); 8908 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 8909 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 8910 Cond = Cmp; 8911 addTest = false; 8912 } else { 8913 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 8914 default: break; 8915 case X86::COND_O: 8916 case X86::COND_B: 8917 // These can only come from an arithmetic instruction with overflow, 8918 // e.g. SADDO, UADDO. 8919 Cond = Cond.getNode()->getOperand(1); 8920 addTest = false; 8921 break; 8922 } 8923 } 8924 } 8925 CondOpcode = Cond.getOpcode(); 8926 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 8927 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 8928 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 8929 Cond.getOperand(0).getValueType() != MVT::i8)) { 8930 SDValue LHS = Cond.getOperand(0); 8931 SDValue RHS = Cond.getOperand(1); 8932 unsigned X86Opcode; 8933 unsigned X86Cond; 8934 SDVTList VTs; 8935 switch (CondOpcode) { 8936 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 8937 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 8938 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 8939 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 8940 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 8941 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 8942 default: llvm_unreachable("unexpected overflowing operator"); 8943 } 8944 if (Inverted) 8945 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 8946 if (CondOpcode == ISD::UMULO) 8947 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 8948 MVT::i32); 8949 else 8950 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 8951 8952 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 8953 8954 if (CondOpcode == ISD::UMULO) 8955 Cond = X86Op.getValue(2); 8956 else 8957 Cond = X86Op.getValue(1); 8958 8959 CC = DAG.getConstant(X86Cond, MVT::i8); 8960 addTest = false; 8961 } else { 8962 unsigned CondOpc; 8963 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 8964 SDValue Cmp = Cond.getOperand(0).getOperand(1); 8965 if (CondOpc == ISD::OR) { 8966 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 8967 // two branches instead of an explicit OR instruction with a 8968 // separate test. 8969 if (Cmp == Cond.getOperand(1).getOperand(1) && 8970 isX86LogicalCmp(Cmp)) { 8971 CC = Cond.getOperand(0).getOperand(0); 8972 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 8973 Chain, Dest, CC, Cmp); 8974 CC = Cond.getOperand(1).getOperand(0); 8975 Cond = Cmp; 8976 addTest = false; 8977 } 8978 } else { // ISD::AND 8979 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 8980 // two branches instead of an explicit AND instruction with a 8981 // separate test. However, we only do this if this block doesn't 8982 // have a fall-through edge, because this requires an explicit 8983 // jmp when the condition is false. 8984 if (Cmp == Cond.getOperand(1).getOperand(1) && 8985 isX86LogicalCmp(Cmp) && 8986 Op.getNode()->hasOneUse()) { 8987 X86::CondCode CCode = 8988 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 8989 CCode = X86::GetOppositeBranchCondition(CCode); 8990 CC = DAG.getConstant(CCode, MVT::i8); 8991 SDNode *User = *Op.getNode()->use_begin(); 8992 // Look for an unconditional branch following this conditional branch. 8993 // We need this because we need to reverse the successors in order 8994 // to implement FCMP_OEQ. 8995 if (User->getOpcode() == ISD::BR) { 8996 SDValue FalseBB = User->getOperand(1); 8997 SDNode *NewBR = 8998 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 8999 assert(NewBR == User); 9000 (void)NewBR; 9001 Dest = FalseBB; 9002 9003 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9004 Chain, Dest, CC, Cmp); 9005 X86::CondCode CCode = 9006 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 9007 CCode = X86::GetOppositeBranchCondition(CCode); 9008 CC = DAG.getConstant(CCode, MVT::i8); 9009 Cond = Cmp; 9010 addTest = false; 9011 } 9012 } 9013 } 9014 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 9015 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 9016 // It should be transformed during dag combiner except when the condition 9017 // is set by a arithmetics with overflow node. 9018 X86::CondCode CCode = 9019 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9020 CCode = X86::GetOppositeBranchCondition(CCode); 9021 CC = DAG.getConstant(CCode, MVT::i8); 9022 Cond = Cond.getOperand(0).getOperand(1); 9023 addTest = false; 9024 } else if (Cond.getOpcode() == ISD::SETCC && 9025 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 9026 // For FCMP_OEQ, we can emit 9027 // two branches instead of an explicit AND instruction with a 9028 // separate test. However, we only do this if this block doesn't 9029 // have a fall-through edge, because this requires an explicit 9030 // jmp when the condition is false. 9031 if (Op.getNode()->hasOneUse()) { 9032 SDNode *User = *Op.getNode()->use_begin(); 9033 // Look for an unconditional branch following this conditional branch. 9034 // We need this because we need to reverse the successors in order 9035 // to implement FCMP_OEQ. 9036 if (User->getOpcode() == ISD::BR) { 9037 SDValue FalseBB = User->getOperand(1); 9038 SDNode *NewBR = 9039 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9040 assert(NewBR == User); 9041 (void)NewBR; 9042 Dest = FalseBB; 9043 9044 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9045 Cond.getOperand(0), Cond.getOperand(1)); 9046 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9047 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9048 Chain, Dest, CC, Cmp); 9049 CC = DAG.getConstant(X86::COND_P, MVT::i8); 9050 Cond = Cmp; 9051 addTest = false; 9052 } 9053 } 9054 } else if (Cond.getOpcode() == ISD::SETCC && 9055 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 9056 // For FCMP_UNE, we can emit 9057 // two branches instead of an explicit AND instruction with a 9058 // separate test. However, we only do this if this block doesn't 9059 // have a fall-through edge, because this requires an explicit 9060 // jmp when the condition is false. 9061 if (Op.getNode()->hasOneUse()) { 9062 SDNode *User = *Op.getNode()->use_begin(); 9063 // Look for an unconditional branch following this conditional branch. 9064 // We need this because we need to reverse the successors in order 9065 // to implement FCMP_UNE. 9066 if (User->getOpcode() == ISD::BR) { 9067 SDValue FalseBB = User->getOperand(1); 9068 SDNode *NewBR = 9069 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9070 assert(NewBR == User); 9071 (void)NewBR; 9072 9073 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9074 Cond.getOperand(0), Cond.getOperand(1)); 9075 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9076 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9077 Chain, Dest, CC, Cmp); 9078 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 9079 Cond = Cmp; 9080 addTest = false; 9081 Dest = FalseBB; 9082 } 9083 } 9084 } 9085 } 9086 9087 if (addTest) { 9088 // Look pass the truncate. 9089 if (Cond.getOpcode() == ISD::TRUNCATE) 9090 Cond = Cond.getOperand(0); 9091 9092 // We know the result of AND is compared against zero. Try to match 9093 // it to BT. 9094 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9095 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 9096 if (NewSetCC.getNode()) { 9097 CC = NewSetCC.getOperand(0); 9098 Cond = NewSetCC.getOperand(1); 9099 addTest = false; 9100 } 9101 } 9102 } 9103 9104 if (addTest) { 9105 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9106 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9107 } 9108 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9109 Chain, Dest, CC, Cond); 9110} 9111 9112 9113// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 9114// Calls to _alloca is needed to probe the stack when allocating more than 4k 9115// bytes in one go. Touching the stack at 4K increments is necessary to ensure 9116// that the guard pages used by the OS virtual memory manager are allocated in 9117// correct sequence. 9118SDValue 9119X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 9120 SelectionDAG &DAG) const { 9121 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 9122 EnableSegmentedStacks) && 9123 "This should be used only on Windows targets or when segmented stacks " 9124 "are being used"); 9125 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 9126 DebugLoc dl = Op.getDebugLoc(); 9127 9128 // Get the inputs. 9129 SDValue Chain = Op.getOperand(0); 9130 SDValue Size = Op.getOperand(1); 9131 // FIXME: Ensure alignment here 9132 9133 bool Is64Bit = Subtarget->is64Bit(); 9134 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 9135 9136 if (EnableSegmentedStacks) { 9137 MachineFunction &MF = DAG.getMachineFunction(); 9138 MachineRegisterInfo &MRI = MF.getRegInfo(); 9139 9140 if (Is64Bit) { 9141 // The 64 bit implementation of segmented stacks needs to clobber both r10 9142 // r11. This makes it impossible to use it along with nested parameters. 9143 const Function *F = MF.getFunction(); 9144 9145 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 9146 I != E; I++) 9147 if (I->hasNestAttr()) 9148 report_fatal_error("Cannot use segmented stacks with functions that " 9149 "have nested arguments."); 9150 } 9151 9152 const TargetRegisterClass *AddrRegClass = 9153 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 9154 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 9155 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 9156 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 9157 DAG.getRegister(Vreg, SPTy)); 9158 SDValue Ops1[2] = { Value, Chain }; 9159 return DAG.getMergeValues(Ops1, 2, dl); 9160 } else { 9161 SDValue Flag; 9162 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 9163 9164 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 9165 Flag = Chain.getValue(1); 9166 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9167 9168 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 9169 Flag = Chain.getValue(1); 9170 9171 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1); 9172 9173 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 9174 return DAG.getMergeValues(Ops1, 2, dl); 9175 } 9176} 9177 9178SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 9179 MachineFunction &MF = DAG.getMachineFunction(); 9180 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 9181 9182 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9183 DebugLoc DL = Op.getDebugLoc(); 9184 9185 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 9186 // vastart just stores the address of the VarArgsFrameIndex slot into the 9187 // memory location argument. 9188 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9189 getPointerTy()); 9190 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 9191 MachinePointerInfo(SV), false, false, 0); 9192 } 9193 9194 // __va_list_tag: 9195 // gp_offset (0 - 6 * 8) 9196 // fp_offset (48 - 48 + 8 * 16) 9197 // overflow_arg_area (point to parameters coming in memory). 9198 // reg_save_area 9199 SmallVector<SDValue, 8> MemOps; 9200 SDValue FIN = Op.getOperand(1); 9201 // Store gp_offset 9202 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 9203 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 9204 MVT::i32), 9205 FIN, MachinePointerInfo(SV), false, false, 0); 9206 MemOps.push_back(Store); 9207 9208 // Store fp_offset 9209 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9210 FIN, DAG.getIntPtrConstant(4)); 9211 Store = DAG.getStore(Op.getOperand(0), DL, 9212 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 9213 MVT::i32), 9214 FIN, MachinePointerInfo(SV, 4), false, false, 0); 9215 MemOps.push_back(Store); 9216 9217 // Store ptr to overflow_arg_area 9218 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9219 FIN, DAG.getIntPtrConstant(4)); 9220 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 9221 getPointerTy()); 9222 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 9223 MachinePointerInfo(SV, 8), 9224 false, false, 0); 9225 MemOps.push_back(Store); 9226 9227 // Store ptr to reg_save_area. 9228 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 9229 FIN, DAG.getIntPtrConstant(8)); 9230 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 9231 getPointerTy()); 9232 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 9233 MachinePointerInfo(SV, 16), false, false, 0); 9234 MemOps.push_back(Store); 9235 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 9236 &MemOps[0], MemOps.size()); 9237} 9238 9239SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 9240 assert(Subtarget->is64Bit() && 9241 "LowerVAARG only handles 64-bit va_arg!"); 9242 assert((Subtarget->isTargetLinux() || 9243 Subtarget->isTargetDarwin()) && 9244 "Unhandled target in LowerVAARG"); 9245 assert(Op.getNode()->getNumOperands() == 4); 9246 SDValue Chain = Op.getOperand(0); 9247 SDValue SrcPtr = Op.getOperand(1); 9248 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 9249 unsigned Align = Op.getConstantOperandVal(3); 9250 DebugLoc dl = Op.getDebugLoc(); 9251 9252 EVT ArgVT = Op.getNode()->getValueType(0); 9253 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 9254 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy); 9255 uint8_t ArgMode; 9256 9257 // Decide which area this value should be read from. 9258 // TODO: Implement the AMD64 ABI in its entirety. This simple 9259 // selection mechanism works only for the basic types. 9260 if (ArgVT == MVT::f80) { 9261 llvm_unreachable("va_arg for f80 not yet implemented"); 9262 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 9263 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 9264 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 9265 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 9266 } else { 9267 llvm_unreachable("Unhandled argument type in LowerVAARG"); 9268 } 9269 9270 if (ArgMode == 2) { 9271 // Sanity Check: Make sure using fp_offset makes sense. 9272 assert(!UseSoftFloat && 9273 !(DAG.getMachineFunction() 9274 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) && 9275 Subtarget->hasXMM()); 9276 } 9277 9278 // Insert VAARG_64 node into the DAG 9279 // VAARG_64 returns two values: Variable Argument Address, Chain 9280 SmallVector<SDValue, 11> InstOps; 9281 InstOps.push_back(Chain); 9282 InstOps.push_back(SrcPtr); 9283 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 9284 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 9285 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 9286 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 9287 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 9288 VTs, &InstOps[0], InstOps.size(), 9289 MVT::i64, 9290 MachinePointerInfo(SV), 9291 /*Align=*/0, 9292 /*Volatile=*/false, 9293 /*ReadMem=*/true, 9294 /*WriteMem=*/true); 9295 Chain = VAARG.getValue(1); 9296 9297 // Load the next argument and return it 9298 return DAG.getLoad(ArgVT, dl, 9299 Chain, 9300 VAARG, 9301 MachinePointerInfo(), 9302 false, false, false, 0); 9303} 9304 9305SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 9306 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 9307 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 9308 SDValue Chain = Op.getOperand(0); 9309 SDValue DstPtr = Op.getOperand(1); 9310 SDValue SrcPtr = Op.getOperand(2); 9311 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 9312 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9313 DebugLoc DL = Op.getDebugLoc(); 9314 9315 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 9316 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 9317 false, 9318 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 9319} 9320 9321SDValue 9322X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { 9323 DebugLoc dl = Op.getDebugLoc(); 9324 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9325 switch (IntNo) { 9326 default: return SDValue(); // Don't custom lower most intrinsics. 9327 // Comparison intrinsics. 9328 case Intrinsic::x86_sse_comieq_ss: 9329 case Intrinsic::x86_sse_comilt_ss: 9330 case Intrinsic::x86_sse_comile_ss: 9331 case Intrinsic::x86_sse_comigt_ss: 9332 case Intrinsic::x86_sse_comige_ss: 9333 case Intrinsic::x86_sse_comineq_ss: 9334 case Intrinsic::x86_sse_ucomieq_ss: 9335 case Intrinsic::x86_sse_ucomilt_ss: 9336 case Intrinsic::x86_sse_ucomile_ss: 9337 case Intrinsic::x86_sse_ucomigt_ss: 9338 case Intrinsic::x86_sse_ucomige_ss: 9339 case Intrinsic::x86_sse_ucomineq_ss: 9340 case Intrinsic::x86_sse2_comieq_sd: 9341 case Intrinsic::x86_sse2_comilt_sd: 9342 case Intrinsic::x86_sse2_comile_sd: 9343 case Intrinsic::x86_sse2_comigt_sd: 9344 case Intrinsic::x86_sse2_comige_sd: 9345 case Intrinsic::x86_sse2_comineq_sd: 9346 case Intrinsic::x86_sse2_ucomieq_sd: 9347 case Intrinsic::x86_sse2_ucomilt_sd: 9348 case Intrinsic::x86_sse2_ucomile_sd: 9349 case Intrinsic::x86_sse2_ucomigt_sd: 9350 case Intrinsic::x86_sse2_ucomige_sd: 9351 case Intrinsic::x86_sse2_ucomineq_sd: { 9352 unsigned Opc = 0; 9353 ISD::CondCode CC = ISD::SETCC_INVALID; 9354 switch (IntNo) { 9355 default: break; 9356 case Intrinsic::x86_sse_comieq_ss: 9357 case Intrinsic::x86_sse2_comieq_sd: 9358 Opc = X86ISD::COMI; 9359 CC = ISD::SETEQ; 9360 break; 9361 case Intrinsic::x86_sse_comilt_ss: 9362 case Intrinsic::x86_sse2_comilt_sd: 9363 Opc = X86ISD::COMI; 9364 CC = ISD::SETLT; 9365 break; 9366 case Intrinsic::x86_sse_comile_ss: 9367 case Intrinsic::x86_sse2_comile_sd: 9368 Opc = X86ISD::COMI; 9369 CC = ISD::SETLE; 9370 break; 9371 case Intrinsic::x86_sse_comigt_ss: 9372 case Intrinsic::x86_sse2_comigt_sd: 9373 Opc = X86ISD::COMI; 9374 CC = ISD::SETGT; 9375 break; 9376 case Intrinsic::x86_sse_comige_ss: 9377 case Intrinsic::x86_sse2_comige_sd: 9378 Opc = X86ISD::COMI; 9379 CC = ISD::SETGE; 9380 break; 9381 case Intrinsic::x86_sse_comineq_ss: 9382 case Intrinsic::x86_sse2_comineq_sd: 9383 Opc = X86ISD::COMI; 9384 CC = ISD::SETNE; 9385 break; 9386 case Intrinsic::x86_sse_ucomieq_ss: 9387 case Intrinsic::x86_sse2_ucomieq_sd: 9388 Opc = X86ISD::UCOMI; 9389 CC = ISD::SETEQ; 9390 break; 9391 case Intrinsic::x86_sse_ucomilt_ss: 9392 case Intrinsic::x86_sse2_ucomilt_sd: 9393 Opc = X86ISD::UCOMI; 9394 CC = ISD::SETLT; 9395 break; 9396 case Intrinsic::x86_sse_ucomile_ss: 9397 case Intrinsic::x86_sse2_ucomile_sd: 9398 Opc = X86ISD::UCOMI; 9399 CC = ISD::SETLE; 9400 break; 9401 case Intrinsic::x86_sse_ucomigt_ss: 9402 case Intrinsic::x86_sse2_ucomigt_sd: 9403 Opc = X86ISD::UCOMI; 9404 CC = ISD::SETGT; 9405 break; 9406 case Intrinsic::x86_sse_ucomige_ss: 9407 case Intrinsic::x86_sse2_ucomige_sd: 9408 Opc = X86ISD::UCOMI; 9409 CC = ISD::SETGE; 9410 break; 9411 case Intrinsic::x86_sse_ucomineq_ss: 9412 case Intrinsic::x86_sse2_ucomineq_sd: 9413 Opc = X86ISD::UCOMI; 9414 CC = ISD::SETNE; 9415 break; 9416 } 9417 9418 SDValue LHS = Op.getOperand(1); 9419 SDValue RHS = Op.getOperand(2); 9420 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 9421 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 9422 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 9423 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9424 DAG.getConstant(X86CC, MVT::i8), Cond); 9425 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9426 } 9427 // Arithmetic intrinsics. 9428 case Intrinsic::x86_sse3_hadd_ps: 9429 case Intrinsic::x86_sse3_hadd_pd: 9430 case Intrinsic::x86_avx_hadd_ps_256: 9431 case Intrinsic::x86_avx_hadd_pd_256: 9432 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(), 9433 Op.getOperand(1), Op.getOperand(2)); 9434 case Intrinsic::x86_sse3_hsub_ps: 9435 case Intrinsic::x86_sse3_hsub_pd: 9436 case Intrinsic::x86_avx_hsub_ps_256: 9437 case Intrinsic::x86_avx_hsub_pd_256: 9438 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(), 9439 Op.getOperand(1), Op.getOperand(2)); 9440 case Intrinsic::x86_avx2_psllv_d: 9441 case Intrinsic::x86_avx2_psllv_q: 9442 case Intrinsic::x86_avx2_psllv_d_256: 9443 case Intrinsic::x86_avx2_psllv_q_256: 9444 return DAG.getNode(ISD::SHL, dl, Op.getValueType(), 9445 Op.getOperand(1), Op.getOperand(2)); 9446 case Intrinsic::x86_avx2_psrlv_d: 9447 case Intrinsic::x86_avx2_psrlv_q: 9448 case Intrinsic::x86_avx2_psrlv_d_256: 9449 case Intrinsic::x86_avx2_psrlv_q_256: 9450 return DAG.getNode(ISD::SRL, dl, Op.getValueType(), 9451 Op.getOperand(1), Op.getOperand(2)); 9452 case Intrinsic::x86_avx2_psrav_d: 9453 case Intrinsic::x86_avx2_psrav_d_256: 9454 return DAG.getNode(ISD::SRA, dl, Op.getValueType(), 9455 Op.getOperand(1), Op.getOperand(2)); 9456 9457 // ptest and testp intrinsics. The intrinsic these come from are designed to 9458 // return an integer value, not just an instruction so lower it to the ptest 9459 // or testp pattern and a setcc for the result. 9460 case Intrinsic::x86_sse41_ptestz: 9461 case Intrinsic::x86_sse41_ptestc: 9462 case Intrinsic::x86_sse41_ptestnzc: 9463 case Intrinsic::x86_avx_ptestz_256: 9464 case Intrinsic::x86_avx_ptestc_256: 9465 case Intrinsic::x86_avx_ptestnzc_256: 9466 case Intrinsic::x86_avx_vtestz_ps: 9467 case Intrinsic::x86_avx_vtestc_ps: 9468 case Intrinsic::x86_avx_vtestnzc_ps: 9469 case Intrinsic::x86_avx_vtestz_pd: 9470 case Intrinsic::x86_avx_vtestc_pd: 9471 case Intrinsic::x86_avx_vtestnzc_pd: 9472 case Intrinsic::x86_avx_vtestz_ps_256: 9473 case Intrinsic::x86_avx_vtestc_ps_256: 9474 case Intrinsic::x86_avx_vtestnzc_ps_256: 9475 case Intrinsic::x86_avx_vtestz_pd_256: 9476 case Intrinsic::x86_avx_vtestc_pd_256: 9477 case Intrinsic::x86_avx_vtestnzc_pd_256: { 9478 bool IsTestPacked = false; 9479 unsigned X86CC = 0; 9480 switch (IntNo) { 9481 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 9482 case Intrinsic::x86_avx_vtestz_ps: 9483 case Intrinsic::x86_avx_vtestz_pd: 9484 case Intrinsic::x86_avx_vtestz_ps_256: 9485 case Intrinsic::x86_avx_vtestz_pd_256: 9486 IsTestPacked = true; // Fallthrough 9487 case Intrinsic::x86_sse41_ptestz: 9488 case Intrinsic::x86_avx_ptestz_256: 9489 // ZF = 1 9490 X86CC = X86::COND_E; 9491 break; 9492 case Intrinsic::x86_avx_vtestc_ps: 9493 case Intrinsic::x86_avx_vtestc_pd: 9494 case Intrinsic::x86_avx_vtestc_ps_256: 9495 case Intrinsic::x86_avx_vtestc_pd_256: 9496 IsTestPacked = true; // Fallthrough 9497 case Intrinsic::x86_sse41_ptestc: 9498 case Intrinsic::x86_avx_ptestc_256: 9499 // CF = 1 9500 X86CC = X86::COND_B; 9501 break; 9502 case Intrinsic::x86_avx_vtestnzc_ps: 9503 case Intrinsic::x86_avx_vtestnzc_pd: 9504 case Intrinsic::x86_avx_vtestnzc_ps_256: 9505 case Intrinsic::x86_avx_vtestnzc_pd_256: 9506 IsTestPacked = true; // Fallthrough 9507 case Intrinsic::x86_sse41_ptestnzc: 9508 case Intrinsic::x86_avx_ptestnzc_256: 9509 // ZF and CF = 0 9510 X86CC = X86::COND_A; 9511 break; 9512 } 9513 9514 SDValue LHS = Op.getOperand(1); 9515 SDValue RHS = Op.getOperand(2); 9516 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 9517 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 9518 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 9519 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 9520 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 9521 } 9522 9523 // Fix vector shift instructions where the last operand is a non-immediate 9524 // i32 value. 9525 case Intrinsic::x86_avx2_pslli_w: 9526 case Intrinsic::x86_avx2_pslli_d: 9527 case Intrinsic::x86_avx2_pslli_q: 9528 case Intrinsic::x86_avx2_psrli_w: 9529 case Intrinsic::x86_avx2_psrli_d: 9530 case Intrinsic::x86_avx2_psrli_q: 9531 case Intrinsic::x86_avx2_psrai_w: 9532 case Intrinsic::x86_avx2_psrai_d: 9533 case Intrinsic::x86_sse2_pslli_w: 9534 case Intrinsic::x86_sse2_pslli_d: 9535 case Intrinsic::x86_sse2_pslli_q: 9536 case Intrinsic::x86_sse2_psrli_w: 9537 case Intrinsic::x86_sse2_psrli_d: 9538 case Intrinsic::x86_sse2_psrli_q: 9539 case Intrinsic::x86_sse2_psrai_w: 9540 case Intrinsic::x86_sse2_psrai_d: 9541 case Intrinsic::x86_mmx_pslli_w: 9542 case Intrinsic::x86_mmx_pslli_d: 9543 case Intrinsic::x86_mmx_pslli_q: 9544 case Intrinsic::x86_mmx_psrli_w: 9545 case Intrinsic::x86_mmx_psrli_d: 9546 case Intrinsic::x86_mmx_psrli_q: 9547 case Intrinsic::x86_mmx_psrai_w: 9548 case Intrinsic::x86_mmx_psrai_d: { 9549 SDValue ShAmt = Op.getOperand(2); 9550 if (isa<ConstantSDNode>(ShAmt)) 9551 return SDValue(); 9552 9553 unsigned NewIntNo = 0; 9554 EVT ShAmtVT = MVT::v4i32; 9555 switch (IntNo) { 9556 case Intrinsic::x86_sse2_pslli_w: 9557 NewIntNo = Intrinsic::x86_sse2_psll_w; 9558 break; 9559 case Intrinsic::x86_sse2_pslli_d: 9560 NewIntNo = Intrinsic::x86_sse2_psll_d; 9561 break; 9562 case Intrinsic::x86_sse2_pslli_q: 9563 NewIntNo = Intrinsic::x86_sse2_psll_q; 9564 break; 9565 case Intrinsic::x86_sse2_psrli_w: 9566 NewIntNo = Intrinsic::x86_sse2_psrl_w; 9567 break; 9568 case Intrinsic::x86_sse2_psrli_d: 9569 NewIntNo = Intrinsic::x86_sse2_psrl_d; 9570 break; 9571 case Intrinsic::x86_sse2_psrli_q: 9572 NewIntNo = Intrinsic::x86_sse2_psrl_q; 9573 break; 9574 case Intrinsic::x86_sse2_psrai_w: 9575 NewIntNo = Intrinsic::x86_sse2_psra_w; 9576 break; 9577 case Intrinsic::x86_sse2_psrai_d: 9578 NewIntNo = Intrinsic::x86_sse2_psra_d; 9579 break; 9580 case Intrinsic::x86_avx2_pslli_w: 9581 NewIntNo = Intrinsic::x86_avx2_psll_w; 9582 break; 9583 case Intrinsic::x86_avx2_pslli_d: 9584 NewIntNo = Intrinsic::x86_avx2_psll_d; 9585 break; 9586 case Intrinsic::x86_avx2_pslli_q: 9587 NewIntNo = Intrinsic::x86_avx2_psll_q; 9588 break; 9589 case Intrinsic::x86_avx2_psrli_w: 9590 NewIntNo = Intrinsic::x86_avx2_psrl_w; 9591 break; 9592 case Intrinsic::x86_avx2_psrli_d: 9593 NewIntNo = Intrinsic::x86_avx2_psrl_d; 9594 break; 9595 case Intrinsic::x86_avx2_psrli_q: 9596 NewIntNo = Intrinsic::x86_avx2_psrl_q; 9597 break; 9598 case Intrinsic::x86_avx2_psrai_w: 9599 NewIntNo = Intrinsic::x86_avx2_psra_w; 9600 break; 9601 case Intrinsic::x86_avx2_psrai_d: 9602 NewIntNo = Intrinsic::x86_avx2_psra_d; 9603 break; 9604 default: { 9605 ShAmtVT = MVT::v2i32; 9606 switch (IntNo) { 9607 case Intrinsic::x86_mmx_pslli_w: 9608 NewIntNo = Intrinsic::x86_mmx_psll_w; 9609 break; 9610 case Intrinsic::x86_mmx_pslli_d: 9611 NewIntNo = Intrinsic::x86_mmx_psll_d; 9612 break; 9613 case Intrinsic::x86_mmx_pslli_q: 9614 NewIntNo = Intrinsic::x86_mmx_psll_q; 9615 break; 9616 case Intrinsic::x86_mmx_psrli_w: 9617 NewIntNo = Intrinsic::x86_mmx_psrl_w; 9618 break; 9619 case Intrinsic::x86_mmx_psrli_d: 9620 NewIntNo = Intrinsic::x86_mmx_psrl_d; 9621 break; 9622 case Intrinsic::x86_mmx_psrli_q: 9623 NewIntNo = Intrinsic::x86_mmx_psrl_q; 9624 break; 9625 case Intrinsic::x86_mmx_psrai_w: 9626 NewIntNo = Intrinsic::x86_mmx_psra_w; 9627 break; 9628 case Intrinsic::x86_mmx_psrai_d: 9629 NewIntNo = Intrinsic::x86_mmx_psra_d; 9630 break; 9631 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 9632 } 9633 break; 9634 } 9635 } 9636 9637 // The vector shift intrinsics with scalars uses 32b shift amounts but 9638 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 9639 // to be zero. 9640 SDValue ShOps[4]; 9641 ShOps[0] = ShAmt; 9642 ShOps[1] = DAG.getConstant(0, MVT::i32); 9643 if (ShAmtVT == MVT::v4i32) { 9644 ShOps[2] = DAG.getUNDEF(MVT::i32); 9645 ShOps[3] = DAG.getUNDEF(MVT::i32); 9646 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4); 9647 } else { 9648 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2); 9649// FIXME this must be lowered to get rid of the invalid type. 9650 } 9651 9652 EVT VT = Op.getValueType(); 9653 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt); 9654 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 9655 DAG.getConstant(NewIntNo, MVT::i32), 9656 Op.getOperand(1), ShAmt); 9657 } 9658 } 9659} 9660 9661SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 9662 SelectionDAG &DAG) const { 9663 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9664 MFI->setReturnAddressIsTaken(true); 9665 9666 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9667 DebugLoc dl = Op.getDebugLoc(); 9668 9669 if (Depth > 0) { 9670 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 9671 SDValue Offset = 9672 DAG.getConstant(TD->getPointerSize(), 9673 Subtarget->is64Bit() ? MVT::i64 : MVT::i32); 9674 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9675 DAG.getNode(ISD::ADD, dl, getPointerTy(), 9676 FrameAddr, Offset), 9677 MachinePointerInfo(), false, false, false, 0); 9678 } 9679 9680 // Just load the return address. 9681 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 9682 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), 9683 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 9684} 9685 9686SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 9687 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 9688 MFI->setFrameAddressIsTaken(true); 9689 9690 EVT VT = Op.getValueType(); 9691 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 9692 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9693 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 9694 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 9695 while (Depth--) 9696 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 9697 MachinePointerInfo(), 9698 false, false, false, 0); 9699 return FrameAddr; 9700} 9701 9702SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 9703 SelectionDAG &DAG) const { 9704 return DAG.getIntPtrConstant(2*TD->getPointerSize()); 9705} 9706 9707SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 9708 MachineFunction &MF = DAG.getMachineFunction(); 9709 SDValue Chain = Op.getOperand(0); 9710 SDValue Offset = Op.getOperand(1); 9711 SDValue Handler = Op.getOperand(2); 9712 DebugLoc dl = Op.getDebugLoc(); 9713 9714 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 9715 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 9716 getPointerTy()); 9717 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 9718 9719 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 9720 DAG.getIntPtrConstant(TD->getPointerSize())); 9721 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 9722 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 9723 false, false, 0); 9724 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 9725 MF.getRegInfo().addLiveOut(StoreAddrReg); 9726 9727 return DAG.getNode(X86ISD::EH_RETURN, dl, 9728 MVT::Other, 9729 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 9730} 9731 9732SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 9733 SelectionDAG &DAG) const { 9734 return Op.getOperand(0); 9735} 9736 9737SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 9738 SelectionDAG &DAG) const { 9739 SDValue Root = Op.getOperand(0); 9740 SDValue Trmp = Op.getOperand(1); // trampoline 9741 SDValue FPtr = Op.getOperand(2); // nested function 9742 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 9743 DebugLoc dl = Op.getDebugLoc(); 9744 9745 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 9746 9747 if (Subtarget->is64Bit()) { 9748 SDValue OutChains[6]; 9749 9750 // Large code-model. 9751 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 9752 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 9753 9754 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10); 9755 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11); 9756 9757 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 9758 9759 // Load the pointer to the nested function into R11. 9760 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 9761 SDValue Addr = Trmp; 9762 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9763 Addr, MachinePointerInfo(TrmpAddr), 9764 false, false, 0); 9765 9766 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9767 DAG.getConstant(2, MVT::i64)); 9768 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 9769 MachinePointerInfo(TrmpAddr, 2), 9770 false, false, 2); 9771 9772 // Load the 'nest' parameter value into R10. 9773 // R10 is specified in X86CallingConv.td 9774 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 9775 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9776 DAG.getConstant(10, MVT::i64)); 9777 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9778 Addr, MachinePointerInfo(TrmpAddr, 10), 9779 false, false, 0); 9780 9781 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9782 DAG.getConstant(12, MVT::i64)); 9783 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 9784 MachinePointerInfo(TrmpAddr, 12), 9785 false, false, 2); 9786 9787 // Jump to the nested function. 9788 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 9789 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9790 DAG.getConstant(20, MVT::i64)); 9791 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 9792 Addr, MachinePointerInfo(TrmpAddr, 20), 9793 false, false, 0); 9794 9795 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 9796 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 9797 DAG.getConstant(22, MVT::i64)); 9798 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 9799 MachinePointerInfo(TrmpAddr, 22), 9800 false, false, 0); 9801 9802 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 9803 } else { 9804 const Function *Func = 9805 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 9806 CallingConv::ID CC = Func->getCallingConv(); 9807 unsigned NestReg; 9808 9809 switch (CC) { 9810 default: 9811 llvm_unreachable("Unsupported calling convention"); 9812 case CallingConv::C: 9813 case CallingConv::X86_StdCall: { 9814 // Pass 'nest' parameter in ECX. 9815 // Must be kept in sync with X86CallingConv.td 9816 NestReg = X86::ECX; 9817 9818 // Check that ECX wasn't needed by an 'inreg' parameter. 9819 FunctionType *FTy = Func->getFunctionType(); 9820 const AttrListPtr &Attrs = Func->getAttributes(); 9821 9822 if (!Attrs.isEmpty() && !Func->isVarArg()) { 9823 unsigned InRegCount = 0; 9824 unsigned Idx = 1; 9825 9826 for (FunctionType::param_iterator I = FTy->param_begin(), 9827 E = FTy->param_end(); I != E; ++I, ++Idx) 9828 if (Attrs.paramHasAttr(Idx, Attribute::InReg)) 9829 // FIXME: should only count parameters that are lowered to integers. 9830 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 9831 9832 if (InRegCount > 2) { 9833 report_fatal_error("Nest register in use - reduce number of inreg" 9834 " parameters!"); 9835 } 9836 } 9837 break; 9838 } 9839 case CallingConv::X86_FastCall: 9840 case CallingConv::X86_ThisCall: 9841 case CallingConv::Fast: 9842 // Pass 'nest' parameter in EAX. 9843 // Must be kept in sync with X86CallingConv.td 9844 NestReg = X86::EAX; 9845 break; 9846 } 9847 9848 SDValue OutChains[4]; 9849 SDValue Addr, Disp; 9850 9851 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9852 DAG.getConstant(10, MVT::i32)); 9853 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 9854 9855 // This is storing the opcode for MOV32ri. 9856 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 9857 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg); 9858 OutChains[0] = DAG.getStore(Root, dl, 9859 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 9860 Trmp, MachinePointerInfo(TrmpAddr), 9861 false, false, 0); 9862 9863 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9864 DAG.getConstant(1, MVT::i32)); 9865 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 9866 MachinePointerInfo(TrmpAddr, 1), 9867 false, false, 1); 9868 9869 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 9870 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9871 DAG.getConstant(5, MVT::i32)); 9872 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 9873 MachinePointerInfo(TrmpAddr, 5), 9874 false, false, 1); 9875 9876 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 9877 DAG.getConstant(6, MVT::i32)); 9878 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 9879 MachinePointerInfo(TrmpAddr, 6), 9880 false, false, 1); 9881 9882 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 9883 } 9884} 9885 9886SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 9887 SelectionDAG &DAG) const { 9888 /* 9889 The rounding mode is in bits 11:10 of FPSR, and has the following 9890 settings: 9891 00 Round to nearest 9892 01 Round to -inf 9893 10 Round to +inf 9894 11 Round to 0 9895 9896 FLT_ROUNDS, on the other hand, expects the following: 9897 -1 Undefined 9898 0 Round to 0 9899 1 Round to nearest 9900 2 Round to +inf 9901 3 Round to -inf 9902 9903 To perform the conversion, we do: 9904 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 9905 */ 9906 9907 MachineFunction &MF = DAG.getMachineFunction(); 9908 const TargetMachine &TM = MF.getTarget(); 9909 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 9910 unsigned StackAlignment = TFI.getStackAlignment(); 9911 EVT VT = Op.getValueType(); 9912 DebugLoc DL = Op.getDebugLoc(); 9913 9914 // Save FP Control Word to stack slot 9915 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 9916 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 9917 9918 9919 MachineMemOperand *MMO = 9920 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 9921 MachineMemOperand::MOStore, 2, 2); 9922 9923 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 9924 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 9925 DAG.getVTList(MVT::Other), 9926 Ops, 2, MVT::i16, MMO); 9927 9928 // Load FP Control Word from stack slot 9929 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 9930 MachinePointerInfo(), false, false, false, 0); 9931 9932 // Transform as necessary 9933 SDValue CWD1 = 9934 DAG.getNode(ISD::SRL, DL, MVT::i16, 9935 DAG.getNode(ISD::AND, DL, MVT::i16, 9936 CWD, DAG.getConstant(0x800, MVT::i16)), 9937 DAG.getConstant(11, MVT::i8)); 9938 SDValue CWD2 = 9939 DAG.getNode(ISD::SRL, DL, MVT::i16, 9940 DAG.getNode(ISD::AND, DL, MVT::i16, 9941 CWD, DAG.getConstant(0x400, MVT::i16)), 9942 DAG.getConstant(9, MVT::i8)); 9943 9944 SDValue RetVal = 9945 DAG.getNode(ISD::AND, DL, MVT::i16, 9946 DAG.getNode(ISD::ADD, DL, MVT::i16, 9947 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 9948 DAG.getConstant(1, MVT::i16)), 9949 DAG.getConstant(3, MVT::i16)); 9950 9951 9952 return DAG.getNode((VT.getSizeInBits() < 16 ? 9953 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 9954} 9955 9956SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const { 9957 EVT VT = Op.getValueType(); 9958 EVT OpVT = VT; 9959 unsigned NumBits = VT.getSizeInBits(); 9960 DebugLoc dl = Op.getDebugLoc(); 9961 9962 Op = Op.getOperand(0); 9963 if (VT == MVT::i8) { 9964 // Zero extend to i32 since there is not an i8 bsr. 9965 OpVT = MVT::i32; 9966 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 9967 } 9968 9969 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 9970 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 9971 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 9972 9973 // If src is zero (i.e. bsr sets ZF), returns NumBits. 9974 SDValue Ops[] = { 9975 Op, 9976 DAG.getConstant(NumBits+NumBits-1, OpVT), 9977 DAG.getConstant(X86::COND_E, MVT::i8), 9978 Op.getValue(1) 9979 }; 9980 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 9981 9982 // Finally xor with NumBits-1. 9983 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 9984 9985 if (VT == MVT::i8) 9986 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 9987 return Op; 9988} 9989 9990SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const { 9991 EVT VT = Op.getValueType(); 9992 EVT OpVT = VT; 9993 unsigned NumBits = VT.getSizeInBits(); 9994 DebugLoc dl = Op.getDebugLoc(); 9995 9996 Op = Op.getOperand(0); 9997 if (VT == MVT::i8) { 9998 OpVT = MVT::i32; 9999 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 10000 } 10001 10002 // Issue a bsf (scan bits forward) which also sets EFLAGS. 10003 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 10004 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 10005 10006 // If src is zero (i.e. bsf sets ZF), returns NumBits. 10007 SDValue Ops[] = { 10008 Op, 10009 DAG.getConstant(NumBits, OpVT), 10010 DAG.getConstant(X86::COND_E, MVT::i8), 10011 Op.getValue(1) 10012 }; 10013 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 10014 10015 if (VT == MVT::i8) 10016 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 10017 return Op; 10018} 10019 10020// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 10021// ones, and then concatenate the result back. 10022static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 10023 EVT VT = Op.getValueType(); 10024 10025 assert(VT.getSizeInBits() == 256 && VT.isInteger() && 10026 "Unsupported value type for operation"); 10027 10028 int NumElems = VT.getVectorNumElements(); 10029 DebugLoc dl = Op.getDebugLoc(); 10030 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 10031 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 10032 10033 // Extract the LHS vectors 10034 SDValue LHS = Op.getOperand(0); 10035 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 10036 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 10037 10038 // Extract the RHS vectors 10039 SDValue RHS = Op.getOperand(1); 10040 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl); 10041 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl); 10042 10043 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10044 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10045 10046 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 10047 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 10048 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 10049} 10050 10051SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const { 10052 assert(Op.getValueType().getSizeInBits() == 256 && 10053 Op.getValueType().isInteger() && 10054 "Only handle AVX 256-bit vector integer operation"); 10055 return Lower256IntArith(Op, DAG); 10056} 10057 10058SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const { 10059 assert(Op.getValueType().getSizeInBits() == 256 && 10060 Op.getValueType().isInteger() && 10061 "Only handle AVX 256-bit vector integer operation"); 10062 return Lower256IntArith(Op, DAG); 10063} 10064 10065SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10066 EVT VT = Op.getValueType(); 10067 10068 // Decompose 256-bit ops into smaller 128-bit ops. 10069 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()) 10070 return Lower256IntArith(Op, DAG); 10071 10072 DebugLoc dl = Op.getDebugLoc(); 10073 10074 SDValue A = Op.getOperand(0); 10075 SDValue B = Op.getOperand(1); 10076 10077 if (VT == MVT::v4i64) { 10078 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2"); 10079 10080 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32); 10081 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32); 10082 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b ); 10083 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi ); 10084 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b ); 10085 // 10086 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 ); 10087 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 ); 10088 // return AloBlo + AloBhi + AhiBlo; 10089 10090 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10091 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 10092 A, DAG.getConstant(32, MVT::i32)); 10093 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10094 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 10095 B, DAG.getConstant(32, MVT::i32)); 10096 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10097 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10098 A, B); 10099 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10100 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10101 A, Bhi); 10102 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10103 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32), 10104 Ahi, B); 10105 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10106 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 10107 AloBhi, DAG.getConstant(32, MVT::i32)); 10108 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10109 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 10110 AhiBlo, DAG.getConstant(32, MVT::i32)); 10111 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 10112 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 10113 return Res; 10114 } 10115 10116 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply"); 10117 10118 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32); 10119 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32); 10120 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b ); 10121 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi ); 10122 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b ); 10123 // 10124 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 ); 10125 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 ); 10126 // return AloBlo + AloBhi + AhiBlo; 10127 10128 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10129 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10130 A, DAG.getConstant(32, MVT::i32)); 10131 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10132 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10133 B, DAG.getConstant(32, MVT::i32)); 10134 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10135 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10136 A, B); 10137 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10138 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10139 A, Bhi); 10140 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10141 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32), 10142 Ahi, B); 10143 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10144 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10145 AloBhi, DAG.getConstant(32, MVT::i32)); 10146 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10147 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10148 AhiBlo, DAG.getConstant(32, MVT::i32)); 10149 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 10150 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 10151 return Res; 10152} 10153 10154SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 10155 10156 EVT VT = Op.getValueType(); 10157 DebugLoc dl = Op.getDebugLoc(); 10158 SDValue R = Op.getOperand(0); 10159 SDValue Amt = Op.getOperand(1); 10160 LLVMContext *Context = DAG.getContext(); 10161 10162 if (!Subtarget->hasXMMInt()) 10163 return SDValue(); 10164 10165 // Optimize shl/srl/sra with constant shift amount. 10166 if (isSplatVector(Amt.getNode())) { 10167 SDValue SclrAmt = Amt->getOperand(0); 10168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 10169 uint64_t ShiftAmt = C->getZExtValue(); 10170 10171 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) { 10172 // Make a large shift. 10173 SDValue SHL = 10174 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10175 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10176 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10177 // Zero out the rightmost bits. 10178 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt), 10179 MVT::i8)); 10180 return DAG.getNode(ISD::AND, dl, VT, SHL, 10181 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10182 } 10183 10184 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL) 10185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10186 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 10187 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10188 10189 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL) 10190 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10191 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 10192 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10193 10194 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL) 10195 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10196 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10197 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10198 10199 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) { 10200 // Make a large shift. 10201 SDValue SRL = 10202 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10203 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 10204 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10205 // Zero out the leftmost bits. 10206 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 10207 MVT::i8)); 10208 return DAG.getNode(ISD::AND, dl, VT, SRL, 10209 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 10210 } 10211 10212 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL) 10213 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10214 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 10215 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10216 10217 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL) 10218 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10219 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 10220 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10221 10222 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL) 10223 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10224 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 10225 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10226 10227 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA) 10228 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10229 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 10230 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10231 10232 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA) 10233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10234 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 10235 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10236 10237 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) { 10238 if (ShiftAmt == 7) { 10239 // R s>> 7 === R s< 0 10240 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl); 10241 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R); 10242 } 10243 10244 // R s>> a === ((R u>> a) ^ m) - m 10245 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 10246 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 10247 MVT::i8)); 10248 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 10249 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 10250 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 10251 return Res; 10252 } 10253 10254 if (Subtarget->hasAVX2() && VT == MVT::v32i8) { 10255 if (Op.getOpcode() == ISD::SHL) { 10256 // Make a large shift. 10257 SDValue SHL = 10258 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10259 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32), 10260 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10261 // Zero out the rightmost bits. 10262 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt), 10263 MVT::i8)); 10264 return DAG.getNode(ISD::AND, dl, VT, SHL, 10265 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 10266 } 10267 if (Op.getOpcode() == ISD::SRL) { 10268 // Make a large shift. 10269 SDValue SRL = 10270 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10271 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32), 10272 R, DAG.getConstant(ShiftAmt, MVT::i32)); 10273 // Zero out the leftmost bits. 10274 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 10275 MVT::i8)); 10276 return DAG.getNode(ISD::AND, dl, VT, SRL, 10277 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 10278 } 10279 if (Op.getOpcode() == ISD::SRA) { 10280 if (ShiftAmt == 7) { 10281 // R s>> 7 === R s< 0 10282 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl); 10283 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R); 10284 } 10285 10286 // R s>> a === ((R u>> a) ^ m) - m 10287 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 10288 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt, 10289 MVT::i8)); 10290 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32); 10291 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 10292 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 10293 return Res; 10294 } 10295 } 10296 } 10297 } 10298 10299 // Lower SHL with variable shift amount. 10300 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 10301 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10302 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 10303 Op.getOperand(1), DAG.getConstant(23, MVT::i32)); 10304 10305 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U)); 10306 10307 std::vector<Constant*> CV(4, CI); 10308 Constant *C = ConstantVector::get(CV); 10309 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10310 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10311 MachinePointerInfo::getConstantPool(), 10312 false, false, false, 16); 10313 10314 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 10315 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 10316 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 10317 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 10318 } 10319 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 10320 // a = a << 5; 10321 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10322 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 10323 Op.getOperand(1), DAG.getConstant(5, MVT::i32)); 10324 10325 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15)); 10326 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63)); 10327 10328 std::vector<Constant*> CVM1(16, CM1); 10329 std::vector<Constant*> CVM2(16, CM2); 10330 Constant *C = ConstantVector::get(CVM1); 10331 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10332 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10333 MachinePointerInfo::getConstantPool(), 10334 false, false, false, 16); 10335 10336 // r = pblendv(r, psllw(r & (char16)15, 4), a); 10337 M = DAG.getNode(ISD::AND, dl, VT, R, M); 10338 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10339 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 10340 DAG.getConstant(4, MVT::i32)); 10341 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M); 10342 // a += a 10343 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10344 10345 C = ConstantVector::get(CVM2); 10346 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 10347 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 10348 MachinePointerInfo::getConstantPool(), 10349 false, false, false, 16); 10350 10351 // r = pblendv(r, psllw(r & (char16)63, 2), a); 10352 M = DAG.getNode(ISD::AND, dl, VT, R, M); 10353 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10354 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M, 10355 DAG.getConstant(2, MVT::i32)); 10356 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M); 10357 // a += a 10358 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 10359 10360 // return pblendv(r, r+r, a); 10361 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, 10362 R, DAG.getNode(ISD::ADD, dl, VT, R, R)); 10363 return R; 10364 } 10365 10366 // Decompose 256-bit shifts into smaller 128-bit shifts. 10367 if (VT.getSizeInBits() == 256) { 10368 int NumElems = VT.getVectorNumElements(); 10369 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10370 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10371 10372 // Extract the two vectors 10373 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl); 10374 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32), 10375 DAG, dl); 10376 10377 // Recreate the shift amount vectors 10378 SDValue Amt1, Amt2; 10379 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 10380 // Constant shift amount 10381 SmallVector<SDValue, 4> Amt1Csts; 10382 SmallVector<SDValue, 4> Amt2Csts; 10383 for (int i = 0; i < NumElems/2; ++i) 10384 Amt1Csts.push_back(Amt->getOperand(i)); 10385 for (int i = NumElems/2; i < NumElems; ++i) 10386 Amt2Csts.push_back(Amt->getOperand(i)); 10387 10388 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10389 &Amt1Csts[0], NumElems/2); 10390 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 10391 &Amt2Csts[0], NumElems/2); 10392 } else { 10393 // Variable shift amount 10394 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl); 10395 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32), 10396 DAG, dl); 10397 } 10398 10399 // Issue new vector shifts for the smaller types 10400 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 10401 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 10402 10403 // Concatenate the result back 10404 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 10405 } 10406 10407 return SDValue(); 10408} 10409 10410SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const { 10411 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 10412 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 10413 // looks for this combo and may remove the "setcc" instruction if the "setcc" 10414 // has only one use. 10415 SDNode *N = Op.getNode(); 10416 SDValue LHS = N->getOperand(0); 10417 SDValue RHS = N->getOperand(1); 10418 unsigned BaseOp = 0; 10419 unsigned Cond = 0; 10420 DebugLoc DL = Op.getDebugLoc(); 10421 switch (Op.getOpcode()) { 10422 default: llvm_unreachable("Unknown ovf instruction!"); 10423 case ISD::SADDO: 10424 // A subtract of one will be selected as a INC. Note that INC doesn't 10425 // set CF, so we can't do this for UADDO. 10426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10427 if (C->isOne()) { 10428 BaseOp = X86ISD::INC; 10429 Cond = X86::COND_O; 10430 break; 10431 } 10432 BaseOp = X86ISD::ADD; 10433 Cond = X86::COND_O; 10434 break; 10435 case ISD::UADDO: 10436 BaseOp = X86ISD::ADD; 10437 Cond = X86::COND_B; 10438 break; 10439 case ISD::SSUBO: 10440 // A subtract of one will be selected as a DEC. Note that DEC doesn't 10441 // set CF, so we can't do this for USUBO. 10442 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 10443 if (C->isOne()) { 10444 BaseOp = X86ISD::DEC; 10445 Cond = X86::COND_O; 10446 break; 10447 } 10448 BaseOp = X86ISD::SUB; 10449 Cond = X86::COND_O; 10450 break; 10451 case ISD::USUBO: 10452 BaseOp = X86ISD::SUB; 10453 Cond = X86::COND_B; 10454 break; 10455 case ISD::SMULO: 10456 BaseOp = X86ISD::SMUL; 10457 Cond = X86::COND_O; 10458 break; 10459 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 10460 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 10461 MVT::i32); 10462 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 10463 10464 SDValue SetCC = 10465 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 10466 DAG.getConstant(X86::COND_O, MVT::i32), 10467 SDValue(Sum.getNode(), 2)); 10468 10469 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10470 } 10471 } 10472 10473 // Also sets EFLAGS. 10474 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 10475 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 10476 10477 SDValue SetCC = 10478 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 10479 DAG.getConstant(Cond, MVT::i32), 10480 SDValue(Sum.getNode(), 1)); 10481 10482 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 10483} 10484 10485SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{ 10486 DebugLoc dl = Op.getDebugLoc(); 10487 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 10488 EVT VT = Op.getValueType(); 10489 10490 if (Subtarget->hasXMMInt() && VT.isVector()) { 10491 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 10492 ExtraVT.getScalarType().getSizeInBits(); 10493 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 10494 10495 unsigned SHLIntrinsicsID = 0; 10496 unsigned SRAIntrinsicsID = 0; 10497 switch (VT.getSimpleVT().SimpleTy) { 10498 default: 10499 return SDValue(); 10500 case MVT::v4i32: 10501 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d; 10502 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d; 10503 break; 10504 case MVT::v8i16: 10505 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w; 10506 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w; 10507 break; 10508 case MVT::v8i32: 10509 case MVT::v16i16: 10510 if (!Subtarget->hasAVX()) 10511 return SDValue(); 10512 if (!Subtarget->hasAVX2()) { 10513 // needs to be split 10514 int NumElems = VT.getVectorNumElements(); 10515 SDValue Idx0 = DAG.getConstant(0, MVT::i32); 10516 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32); 10517 10518 // Extract the LHS vectors 10519 SDValue LHS = Op.getOperand(0); 10520 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl); 10521 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl); 10522 10523 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10524 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 10525 10526 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 10527 int ExtraNumElems = ExtraVT.getVectorNumElements(); 10528 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT, 10529 ExtraNumElems/2); 10530 SDValue Extra = DAG.getValueType(ExtraVT); 10531 10532 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra); 10533 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra); 10534 10535 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);; 10536 } 10537 if (VT == MVT::v8i32) { 10538 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d; 10539 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d; 10540 } else { 10541 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w; 10542 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w; 10543 } 10544 } 10545 10546 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10547 DAG.getConstant(SHLIntrinsicsID, MVT::i32), 10548 Op.getOperand(0), ShAmt); 10549 10550 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, 10551 DAG.getConstant(SRAIntrinsicsID, MVT::i32), 10552 Tmp1, ShAmt); 10553 } 10554 10555 return SDValue(); 10556} 10557 10558 10559SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{ 10560 DebugLoc dl = Op.getDebugLoc(); 10561 10562 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2. 10563 // There isn't any reason to disable it if the target processor supports it. 10564 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) { 10565 SDValue Chain = Op.getOperand(0); 10566 SDValue Zero = DAG.getConstant(0, MVT::i32); 10567 SDValue Ops[] = { 10568 DAG.getRegister(X86::ESP, MVT::i32), // Base 10569 DAG.getTargetConstant(1, MVT::i8), // Scale 10570 DAG.getRegister(0, MVT::i32), // Index 10571 DAG.getTargetConstant(0, MVT::i32), // Disp 10572 DAG.getRegister(0, MVT::i32), // Segment. 10573 Zero, 10574 Chain 10575 }; 10576 SDNode *Res = 10577 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10578 array_lengthof(Ops)); 10579 return SDValue(Res, 0); 10580 } 10581 10582 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 10583 if (!isDev) 10584 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10585 10586 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10587 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 10588 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 10589 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 10590 10591 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 10592 if (!Op1 && !Op2 && !Op3 && Op4) 10593 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 10594 10595 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 10596 if (Op1 && !Op2 && !Op3 && !Op4) 10597 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 10598 10599 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 10600 // (MFENCE)>; 10601 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10602} 10603 10604SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op, 10605 SelectionDAG &DAG) const { 10606 DebugLoc dl = Op.getDebugLoc(); 10607 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 10608 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 10609 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 10610 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10611 10612 // The only fence that needs an instruction is a sequentially-consistent 10613 // cross-thread fence. 10614 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 10615 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 10616 // no-sse2). There isn't any reason to disable it if the target processor 10617 // supports it. 10618 if (Subtarget->hasXMMInt() || Subtarget->is64Bit()) 10619 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 10620 10621 SDValue Chain = Op.getOperand(0); 10622 SDValue Zero = DAG.getConstant(0, MVT::i32); 10623 SDValue Ops[] = { 10624 DAG.getRegister(X86::ESP, MVT::i32), // Base 10625 DAG.getTargetConstant(1, MVT::i8), // Scale 10626 DAG.getRegister(0, MVT::i32), // Index 10627 DAG.getTargetConstant(0, MVT::i32), // Disp 10628 DAG.getRegister(0, MVT::i32), // Segment. 10629 Zero, 10630 Chain 10631 }; 10632 SDNode *Res = 10633 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 10634 array_lengthof(Ops)); 10635 return SDValue(Res, 0); 10636 } 10637 10638 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 10639 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 10640} 10641 10642 10643SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 10644 EVT T = Op.getValueType(); 10645 DebugLoc DL = Op.getDebugLoc(); 10646 unsigned Reg = 0; 10647 unsigned size = 0; 10648 switch(T.getSimpleVT().SimpleTy) { 10649 default: 10650 assert(false && "Invalid value type!"); 10651 case MVT::i8: Reg = X86::AL; size = 1; break; 10652 case MVT::i16: Reg = X86::AX; size = 2; break; 10653 case MVT::i32: Reg = X86::EAX; size = 4; break; 10654 case MVT::i64: 10655 assert(Subtarget->is64Bit() && "Node not type legal!"); 10656 Reg = X86::RAX; size = 8; 10657 break; 10658 } 10659 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 10660 Op.getOperand(2), SDValue()); 10661 SDValue Ops[] = { cpIn.getValue(0), 10662 Op.getOperand(1), 10663 Op.getOperand(3), 10664 DAG.getTargetConstant(size, MVT::i8), 10665 cpIn.getValue(1) }; 10666 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10667 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 10668 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 10669 Ops, 5, T, MMO); 10670 SDValue cpOut = 10671 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 10672 return cpOut; 10673} 10674 10675SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op, 10676 SelectionDAG &DAG) const { 10677 assert(Subtarget->is64Bit() && "Result not type legalized?"); 10678 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10679 SDValue TheChain = Op.getOperand(0); 10680 DebugLoc dl = Op.getDebugLoc(); 10681 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10682 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 10683 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 10684 rax.getValue(2)); 10685 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 10686 DAG.getConstant(32, MVT::i8)); 10687 SDValue Ops[] = { 10688 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 10689 rdx.getValue(1) 10690 }; 10691 return DAG.getMergeValues(Ops, 2, dl); 10692} 10693 10694SDValue X86TargetLowering::LowerBITCAST(SDValue Op, 10695 SelectionDAG &DAG) const { 10696 EVT SrcVT = Op.getOperand(0).getValueType(); 10697 EVT DstVT = Op.getValueType(); 10698 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() && 10699 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 10700 assert((DstVT == MVT::i64 || 10701 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 10702 "Unexpected custom BITCAST"); 10703 // i64 <=> MMX conversions are Legal. 10704 if (SrcVT==MVT::i64 && DstVT.isVector()) 10705 return Op; 10706 if (DstVT==MVT::i64 && SrcVT.isVector()) 10707 return Op; 10708 // MMX <=> MMX conversions are Legal. 10709 if (SrcVT.isVector() && DstVT.isVector()) 10710 return Op; 10711 // All other conversions need to be expanded. 10712 return SDValue(); 10713} 10714 10715SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const { 10716 SDNode *Node = Op.getNode(); 10717 DebugLoc dl = Node->getDebugLoc(); 10718 EVT T = Node->getValueType(0); 10719 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 10720 DAG.getConstant(0, T), Node->getOperand(2)); 10721 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 10722 cast<AtomicSDNode>(Node)->getMemoryVT(), 10723 Node->getOperand(0), 10724 Node->getOperand(1), negOp, 10725 cast<AtomicSDNode>(Node)->getSrcValue(), 10726 cast<AtomicSDNode>(Node)->getAlignment(), 10727 cast<AtomicSDNode>(Node)->getOrdering(), 10728 cast<AtomicSDNode>(Node)->getSynchScope()); 10729} 10730 10731static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 10732 SDNode *Node = Op.getNode(); 10733 DebugLoc dl = Node->getDebugLoc(); 10734 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10735 10736 // Convert seq_cst store -> xchg 10737 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 10738 // FIXME: On 32-bit, store -> fist or movq would be more efficient 10739 // (The only way to get a 16-byte store is cmpxchg16b) 10740 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 10741 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 10742 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 10743 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 10744 cast<AtomicSDNode>(Node)->getMemoryVT(), 10745 Node->getOperand(0), 10746 Node->getOperand(1), Node->getOperand(2), 10747 cast<AtomicSDNode>(Node)->getMemOperand(), 10748 cast<AtomicSDNode>(Node)->getOrdering(), 10749 cast<AtomicSDNode>(Node)->getSynchScope()); 10750 return Swap.getValue(1); 10751 } 10752 // Other atomic stores have a simple pattern. 10753 return Op; 10754} 10755 10756static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 10757 EVT VT = Op.getNode()->getValueType(0); 10758 10759 // Let legalize expand this if it isn't a legal type yet. 10760 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10761 return SDValue(); 10762 10763 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 10764 10765 unsigned Opc; 10766 bool ExtraOp = false; 10767 switch (Op.getOpcode()) { 10768 default: assert(0 && "Invalid code"); 10769 case ISD::ADDC: Opc = X86ISD::ADD; break; 10770 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 10771 case ISD::SUBC: Opc = X86ISD::SUB; break; 10772 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 10773 } 10774 10775 if (!ExtraOp) 10776 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10777 Op.getOperand(1)); 10778 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 10779 Op.getOperand(1), Op.getOperand(2)); 10780} 10781 10782/// LowerOperation - Provide custom lowering hooks for some operations. 10783/// 10784SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10785 switch (Op.getOpcode()) { 10786 default: llvm_unreachable("Should not custom lower this!"); 10787 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 10788 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG); 10789 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG); 10790 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG); 10791 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 10792 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 10793 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10794 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 10795 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10796 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10797 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10798 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); 10799 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG); 10800 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10801 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10802 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10803 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10804 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 10805 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10806 case ISD::SHL_PARTS: 10807 case ISD::SRA_PARTS: 10808 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 10809 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 10810 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 10811 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 10812 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 10813 case ISD::FABS: return LowerFABS(Op, DAG); 10814 case ISD::FNEG: return LowerFNEG(Op, DAG); 10815 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 10816 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 10817 case ISD::SETCC: return LowerSETCC(Op, DAG); 10818 case ISD::SELECT: return LowerSELECT(Op, DAG); 10819 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 10820 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10821 case ISD::VASTART: return LowerVASTART(Op, DAG); 10822 case ISD::VAARG: return LowerVAARG(Op, DAG); 10823 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10824 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10825 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10826 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10827 case ISD::FRAME_TO_ARGS_OFFSET: 10828 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 10829 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10830 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 10831 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10832 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10833 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10834 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 10835 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 10836 case ISD::MUL: return LowerMUL(Op, DAG); 10837 case ISD::SRA: 10838 case ISD::SRL: 10839 case ISD::SHL: return LowerShift(Op, DAG); 10840 case ISD::SADDO: 10841 case ISD::UADDO: 10842 case ISD::SSUBO: 10843 case ISD::USUBO: 10844 case ISD::SMULO: 10845 case ISD::UMULO: return LowerXALUO(Op, DAG); 10846 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG); 10847 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10848 case ISD::ADDC: 10849 case ISD::ADDE: 10850 case ISD::SUBC: 10851 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 10852 case ISD::ADD: return LowerADD(Op, DAG); 10853 case ISD::SUB: return LowerSUB(Op, DAG); 10854 } 10855} 10856 10857static void ReplaceATOMIC_LOAD(SDNode *Node, 10858 SmallVectorImpl<SDValue> &Results, 10859 SelectionDAG &DAG) { 10860 DebugLoc dl = Node->getDebugLoc(); 10861 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 10862 10863 // Convert wide load -> cmpxchg8b/cmpxchg16b 10864 // FIXME: On 32-bit, load -> fild or movq would be more efficient 10865 // (The only way to get a 16-byte load is cmpxchg16b) 10866 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 10867 SDValue Zero = DAG.getConstant(0, VT); 10868 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 10869 Node->getOperand(0), 10870 Node->getOperand(1), Zero, Zero, 10871 cast<AtomicSDNode>(Node)->getMemOperand(), 10872 cast<AtomicSDNode>(Node)->getOrdering(), 10873 cast<AtomicSDNode>(Node)->getSynchScope()); 10874 Results.push_back(Swap.getValue(0)); 10875 Results.push_back(Swap.getValue(1)); 10876} 10877 10878void X86TargetLowering:: 10879ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 10880 SelectionDAG &DAG, unsigned NewOp) const { 10881 DebugLoc dl = Node->getDebugLoc(); 10882 assert (Node->getValueType(0) == MVT::i64 && 10883 "Only know how to expand i64 atomics"); 10884 10885 SDValue Chain = Node->getOperand(0); 10886 SDValue In1 = Node->getOperand(1); 10887 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10888 Node->getOperand(2), DAG.getIntPtrConstant(0)); 10889 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 10890 Node->getOperand(2), DAG.getIntPtrConstant(1)); 10891 SDValue Ops[] = { Chain, In1, In2L, In2H }; 10892 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10893 SDValue Result = 10894 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 10895 cast<MemSDNode>(Node)->getMemOperand()); 10896 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 10897 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 10898 Results.push_back(Result.getValue(2)); 10899} 10900 10901/// ReplaceNodeResults - Replace a node with an illegal result type 10902/// with a new node built out of custom code. 10903void X86TargetLowering::ReplaceNodeResults(SDNode *N, 10904 SmallVectorImpl<SDValue>&Results, 10905 SelectionDAG &DAG) const { 10906 DebugLoc dl = N->getDebugLoc(); 10907 switch (N->getOpcode()) { 10908 default: 10909 assert(false && "Do not know how to custom type legalize this operation!"); 10910 return; 10911 case ISD::SIGN_EXTEND_INREG: 10912 case ISD::ADDC: 10913 case ISD::ADDE: 10914 case ISD::SUBC: 10915 case ISD::SUBE: 10916 // We don't want to expand or promote these. 10917 return; 10918 case ISD::FP_TO_SINT: { 10919 std::pair<SDValue,SDValue> Vals = 10920 FP_TO_INTHelper(SDValue(N, 0), DAG, true); 10921 SDValue FIST = Vals.first, StackSlot = Vals.second; 10922 if (FIST.getNode() != 0) { 10923 EVT VT = N->getValueType(0); 10924 // Return a load from the stack slot. 10925 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 10926 MachinePointerInfo(), 10927 false, false, false, 0)); 10928 } 10929 return; 10930 } 10931 case ISD::READCYCLECOUNTER: { 10932 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10933 SDValue TheChain = N->getOperand(0); 10934 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 10935 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 10936 rd.getValue(1)); 10937 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 10938 eax.getValue(2)); 10939 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 10940 SDValue Ops[] = { eax, edx }; 10941 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 10942 Results.push_back(edx.getValue(1)); 10943 return; 10944 } 10945 case ISD::ATOMIC_CMP_SWAP: { 10946 EVT T = N->getValueType(0); 10947 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 10948 bool Regs64bit = T == MVT::i128; 10949 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 10950 SDValue cpInL, cpInH; 10951 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10952 DAG.getConstant(0, HalfT)); 10953 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 10954 DAG.getConstant(1, HalfT)); 10955 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 10956 Regs64bit ? X86::RAX : X86::EAX, 10957 cpInL, SDValue()); 10958 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 10959 Regs64bit ? X86::RDX : X86::EDX, 10960 cpInH, cpInL.getValue(1)); 10961 SDValue swapInL, swapInH; 10962 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10963 DAG.getConstant(0, HalfT)); 10964 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 10965 DAG.getConstant(1, HalfT)); 10966 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 10967 Regs64bit ? X86::RBX : X86::EBX, 10968 swapInL, cpInH.getValue(1)); 10969 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 10970 Regs64bit ? X86::RCX : X86::ECX, 10971 swapInH, swapInL.getValue(1)); 10972 SDValue Ops[] = { swapInH.getValue(0), 10973 N->getOperand(1), 10974 swapInH.getValue(1) }; 10975 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 10976 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 10977 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 10978 X86ISD::LCMPXCHG8_DAG; 10979 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 10980 Ops, 3, T, MMO); 10981 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 10982 Regs64bit ? X86::RAX : X86::EAX, 10983 HalfT, Result.getValue(1)); 10984 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 10985 Regs64bit ? X86::RDX : X86::EDX, 10986 HalfT, cpOutL.getValue(2)); 10987 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 10988 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 10989 Results.push_back(cpOutH.getValue(1)); 10990 return; 10991 } 10992 case ISD::ATOMIC_LOAD_ADD: 10993 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG); 10994 return; 10995 case ISD::ATOMIC_LOAD_AND: 10996 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG); 10997 return; 10998 case ISD::ATOMIC_LOAD_NAND: 10999 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG); 11000 return; 11001 case ISD::ATOMIC_LOAD_OR: 11002 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG); 11003 return; 11004 case ISD::ATOMIC_LOAD_SUB: 11005 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG); 11006 return; 11007 case ISD::ATOMIC_LOAD_XOR: 11008 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG); 11009 return; 11010 case ISD::ATOMIC_SWAP: 11011 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG); 11012 return; 11013 case ISD::ATOMIC_LOAD: 11014 ReplaceATOMIC_LOAD(N, Results, DAG); 11015 } 11016} 11017 11018const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 11019 switch (Opcode) { 11020 default: return NULL; 11021 case X86ISD::BSF: return "X86ISD::BSF"; 11022 case X86ISD::BSR: return "X86ISD::BSR"; 11023 case X86ISD::SHLD: return "X86ISD::SHLD"; 11024 case X86ISD::SHRD: return "X86ISD::SHRD"; 11025 case X86ISD::FAND: return "X86ISD::FAND"; 11026 case X86ISD::FOR: return "X86ISD::FOR"; 11027 case X86ISD::FXOR: return "X86ISD::FXOR"; 11028 case X86ISD::FSRL: return "X86ISD::FSRL"; 11029 case X86ISD::FILD: return "X86ISD::FILD"; 11030 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 11031 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 11032 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 11033 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 11034 case X86ISD::FLD: return "X86ISD::FLD"; 11035 case X86ISD::FST: return "X86ISD::FST"; 11036 case X86ISD::CALL: return "X86ISD::CALL"; 11037 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 11038 case X86ISD::BT: return "X86ISD::BT"; 11039 case X86ISD::CMP: return "X86ISD::CMP"; 11040 case X86ISD::COMI: return "X86ISD::COMI"; 11041 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 11042 case X86ISD::SETCC: return "X86ISD::SETCC"; 11043 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 11044 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 11045 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 11046 case X86ISD::CMOV: return "X86ISD::CMOV"; 11047 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 11048 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 11049 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 11050 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 11051 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 11052 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 11053 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 11054 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 11055 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 11056 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 11057 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 11058 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 11059 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 11060 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 11061 case X86ISD::PSIGN: return "X86ISD::PSIGN"; 11062 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 11063 case X86ISD::FHADD: return "X86ISD::FHADD"; 11064 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 11065 case X86ISD::FMAX: return "X86ISD::FMAX"; 11066 case X86ISD::FMIN: return "X86ISD::FMIN"; 11067 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 11068 case X86ISD::FRCP: return "X86ISD::FRCP"; 11069 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 11070 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 11071 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 11072 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 11073 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 11074 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 11075 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 11076 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 11077 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 11078 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 11079 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 11080 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 11081 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 11082 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 11083 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 11084 case X86ISD::VSHL: return "X86ISD::VSHL"; 11085 case X86ISD::VSRL: return "X86ISD::VSRL"; 11086 case X86ISD::CMPPD: return "X86ISD::CMPPD"; 11087 case X86ISD::CMPPS: return "X86ISD::CMPPS"; 11088 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB"; 11089 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW"; 11090 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD"; 11091 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ"; 11092 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB"; 11093 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW"; 11094 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD"; 11095 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ"; 11096 case X86ISD::ADD: return "X86ISD::ADD"; 11097 case X86ISD::SUB: return "X86ISD::SUB"; 11098 case X86ISD::ADC: return "X86ISD::ADC"; 11099 case X86ISD::SBB: return "X86ISD::SBB"; 11100 case X86ISD::SMUL: return "X86ISD::SMUL"; 11101 case X86ISD::UMUL: return "X86ISD::UMUL"; 11102 case X86ISD::INC: return "X86ISD::INC"; 11103 case X86ISD::DEC: return "X86ISD::DEC"; 11104 case X86ISD::OR: return "X86ISD::OR"; 11105 case X86ISD::XOR: return "X86ISD::XOR"; 11106 case X86ISD::AND: return "X86ISD::AND"; 11107 case X86ISD::ANDN: return "X86ISD::ANDN"; 11108 case X86ISD::BLSI: return "X86ISD::BLSI"; 11109 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 11110 case X86ISD::BLSR: return "X86ISD::BLSR"; 11111 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 11112 case X86ISD::PTEST: return "X86ISD::PTEST"; 11113 case X86ISD::TESTP: return "X86ISD::TESTP"; 11114 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 11115 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 11116 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 11117 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD"; 11118 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 11119 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD"; 11120 case X86ISD::SHUFPS: return "X86ISD::SHUFPS"; 11121 case X86ISD::SHUFPD: return "X86ISD::SHUFPD"; 11122 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 11123 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 11124 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 11125 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD"; 11126 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 11127 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 11128 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 11129 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 11130 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 11131 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD"; 11132 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD"; 11133 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 11134 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 11135 case X86ISD::UNPCKLP: return "X86ISD::UNPCKLP"; 11136 case X86ISD::UNPCKHP: return "X86ISD::UNPCKHP"; 11137 case X86ISD::PUNPCKL: return "X86ISD::PUNPCKL"; 11138 case X86ISD::PUNPCKH: return "X86ISD::PUNPCKH"; 11139 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 11140 case X86ISD::VPERMILP: return "X86ISD::VPERMILP"; 11141 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128"; 11142 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 11143 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 11144 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 11145 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 11146 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 11147 } 11148} 11149 11150// isLegalAddressingMode - Return true if the addressing mode represented 11151// by AM is legal for this target, for a load/store of the specified type. 11152bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 11153 Type *Ty) const { 11154 // X86 supports extremely general addressing modes. 11155 CodeModel::Model M = getTargetMachine().getCodeModel(); 11156 Reloc::Model R = getTargetMachine().getRelocationModel(); 11157 11158 // X86 allows a sign-extended 32-bit immediate field as a displacement. 11159 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 11160 return false; 11161 11162 if (AM.BaseGV) { 11163 unsigned GVFlags = 11164 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 11165 11166 // If a reference to this global requires an extra load, we can't fold it. 11167 if (isGlobalStubReference(GVFlags)) 11168 return false; 11169 11170 // If BaseGV requires a register for the PIC base, we cannot also have a 11171 // BaseReg specified. 11172 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 11173 return false; 11174 11175 // If lower 4G is not available, then we must use rip-relative addressing. 11176 if ((M != CodeModel::Small || R != Reloc::Static) && 11177 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 11178 return false; 11179 } 11180 11181 switch (AM.Scale) { 11182 case 0: 11183 case 1: 11184 case 2: 11185 case 4: 11186 case 8: 11187 // These scales always work. 11188 break; 11189 case 3: 11190 case 5: 11191 case 9: 11192 // These scales are formed with basereg+scalereg. Only accept if there is 11193 // no basereg yet. 11194 if (AM.HasBaseReg) 11195 return false; 11196 break; 11197 default: // Other stuff never works. 11198 return false; 11199 } 11200 11201 return true; 11202} 11203 11204 11205bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 11206 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 11207 return false; 11208 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 11209 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 11210 if (NumBits1 <= NumBits2) 11211 return false; 11212 return true; 11213} 11214 11215bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 11216 if (!VT1.isInteger() || !VT2.isInteger()) 11217 return false; 11218 unsigned NumBits1 = VT1.getSizeInBits(); 11219 unsigned NumBits2 = VT2.getSizeInBits(); 11220 if (NumBits1 <= NumBits2) 11221 return false; 11222 return true; 11223} 11224 11225bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 11226 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11227 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 11228} 11229 11230bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 11231 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 11232 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 11233} 11234 11235bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 11236 // i16 instructions are longer (0x66 prefix) and potentially slower. 11237 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 11238} 11239 11240/// isShuffleMaskLegal - Targets can use this to indicate that they only 11241/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 11242/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 11243/// are assumed to be legal. 11244bool 11245X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 11246 EVT VT) const { 11247 // Very little shuffling can be done for 64-bit vectors right now. 11248 if (VT.getSizeInBits() == 64) 11249 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()); 11250 11251 // FIXME: pshufb, blends, shifts. 11252 return (VT.getVectorNumElements() == 2 || 11253 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 11254 isMOVLMask(M, VT) || 11255 isSHUFPMask(M, VT) || 11256 isPSHUFDMask(M, VT) || 11257 isPSHUFHWMask(M, VT) || 11258 isPSHUFLWMask(M, VT) || 11259 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) || 11260 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) || 11261 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) || 11262 isUNPCKL_v_undef_Mask(M, VT) || 11263 isUNPCKH_v_undef_Mask(M, VT)); 11264} 11265 11266bool 11267X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 11268 EVT VT) const { 11269 unsigned NumElts = VT.getVectorNumElements(); 11270 // FIXME: This collection of masks seems suspect. 11271 if (NumElts == 2) 11272 return true; 11273 if (NumElts == 4 && VT.getSizeInBits() == 128) { 11274 return (isMOVLMask(Mask, VT) || 11275 isCommutedMOVLMask(Mask, VT, true) || 11276 isSHUFPMask(Mask, VT) || 11277 isCommutedSHUFPMask(Mask, VT)); 11278 } 11279 return false; 11280} 11281 11282//===----------------------------------------------------------------------===// 11283// X86 Scheduler Hooks 11284//===----------------------------------------------------------------------===// 11285 11286// private utility function 11287MachineBasicBlock * 11288X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr, 11289 MachineBasicBlock *MBB, 11290 unsigned regOpc, 11291 unsigned immOpc, 11292 unsigned LoadOpc, 11293 unsigned CXchgOpc, 11294 unsigned notOpc, 11295 unsigned EAXreg, 11296 TargetRegisterClass *RC, 11297 bool invSrc) const { 11298 // For the atomic bitwise operator, we generate 11299 // thisMBB: 11300 // newMBB: 11301 // ld t1 = [bitinstr.addr] 11302 // op t2 = t1, [bitinstr.val] 11303 // mov EAX = t1 11304 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11305 // bz newMBB 11306 // fallthrough -->nextMBB 11307 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11308 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11309 MachineFunction::iterator MBBIter = MBB; 11310 ++MBBIter; 11311 11312 /// First build the CFG 11313 MachineFunction *F = MBB->getParent(); 11314 MachineBasicBlock *thisMBB = MBB; 11315 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11316 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11317 F->insert(MBBIter, newMBB); 11318 F->insert(MBBIter, nextMBB); 11319 11320 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11321 nextMBB->splice(nextMBB->begin(), thisMBB, 11322 llvm::next(MachineBasicBlock::iterator(bInstr)), 11323 thisMBB->end()); 11324 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11325 11326 // Update thisMBB to fall through to newMBB 11327 thisMBB->addSuccessor(newMBB); 11328 11329 // newMBB jumps to itself and fall through to nextMBB 11330 newMBB->addSuccessor(nextMBB); 11331 newMBB->addSuccessor(newMBB); 11332 11333 // Insert instructions into newMBB based on incoming instruction 11334 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11335 "unexpected number of operands"); 11336 DebugLoc dl = bInstr->getDebugLoc(); 11337 MachineOperand& destOper = bInstr->getOperand(0); 11338 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11339 int numArgs = bInstr->getNumOperands() - 1; 11340 for (int i=0; i < numArgs; ++i) 11341 argOpers[i] = &bInstr->getOperand(i+1); 11342 11343 // x86 address has 4 operands: base, index, scale, and displacement 11344 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11345 int valArgIndx = lastAddrIndx + 1; 11346 11347 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11348 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1); 11349 for (int i=0; i <= lastAddrIndx; ++i) 11350 (*MIB).addOperand(*argOpers[i]); 11351 11352 unsigned tt = F->getRegInfo().createVirtualRegister(RC); 11353 if (invSrc) { 11354 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1); 11355 } 11356 else 11357 tt = t1; 11358 11359 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11360 assert((argOpers[valArgIndx]->isReg() || 11361 argOpers[valArgIndx]->isImm()) && 11362 "invalid operand"); 11363 if (argOpers[valArgIndx]->isReg()) 11364 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2); 11365 else 11366 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2); 11367 MIB.addReg(tt); 11368 (*MIB).addOperand(*argOpers[valArgIndx]); 11369 11370 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg); 11371 MIB.addReg(t1); 11372 11373 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc)); 11374 for (int i=0; i <= lastAddrIndx; ++i) 11375 (*MIB).addOperand(*argOpers[i]); 11376 MIB.addReg(t2); 11377 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11378 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11379 bInstr->memoperands_end()); 11380 11381 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11382 MIB.addReg(EAXreg); 11383 11384 // insert branch 11385 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11386 11387 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11388 return nextMBB; 11389} 11390 11391// private utility function: 64 bit atomics on 32 bit host. 11392MachineBasicBlock * 11393X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr, 11394 MachineBasicBlock *MBB, 11395 unsigned regOpcL, 11396 unsigned regOpcH, 11397 unsigned immOpcL, 11398 unsigned immOpcH, 11399 bool invSrc) const { 11400 // For the atomic bitwise operator, we generate 11401 // thisMBB (instructions are in pairs, except cmpxchg8b) 11402 // ld t1,t2 = [bitinstr.addr] 11403 // newMBB: 11404 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4) 11405 // op t5, t6 <- out1, out2, [bitinstr.val] 11406 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val]) 11407 // mov ECX, EBX <- t5, t6 11408 // mov EAX, EDX <- t1, t2 11409 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit] 11410 // mov t3, t4 <- EAX, EDX 11411 // bz newMBB 11412 // result in out1, out2 11413 // fallthrough -->nextMBB 11414 11415 const TargetRegisterClass *RC = X86::GR32RegisterClass; 11416 const unsigned LoadOpc = X86::MOV32rm; 11417 const unsigned NotOpc = X86::NOT32r; 11418 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11419 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11420 MachineFunction::iterator MBBIter = MBB; 11421 ++MBBIter; 11422 11423 /// First build the CFG 11424 MachineFunction *F = MBB->getParent(); 11425 MachineBasicBlock *thisMBB = MBB; 11426 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11427 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11428 F->insert(MBBIter, newMBB); 11429 F->insert(MBBIter, nextMBB); 11430 11431 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11432 nextMBB->splice(nextMBB->begin(), thisMBB, 11433 llvm::next(MachineBasicBlock::iterator(bInstr)), 11434 thisMBB->end()); 11435 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11436 11437 // Update thisMBB to fall through to newMBB 11438 thisMBB->addSuccessor(newMBB); 11439 11440 // newMBB jumps to itself and fall through to nextMBB 11441 newMBB->addSuccessor(nextMBB); 11442 newMBB->addSuccessor(newMBB); 11443 11444 DebugLoc dl = bInstr->getDebugLoc(); 11445 // Insert instructions into newMBB based on incoming instruction 11446 // There are 8 "real" operands plus 9 implicit def/uses, ignored here. 11447 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 && 11448 "unexpected number of operands"); 11449 MachineOperand& dest1Oper = bInstr->getOperand(0); 11450 MachineOperand& dest2Oper = bInstr->getOperand(1); 11451 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11452 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) { 11453 argOpers[i] = &bInstr->getOperand(i+2); 11454 11455 // We use some of the operands multiple times, so conservatively just 11456 // clear any kill flags that might be present. 11457 if (argOpers[i]->isReg() && argOpers[i]->isUse()) 11458 argOpers[i]->setIsKill(false); 11459 } 11460 11461 // x86 address has 5 operands: base, index, scale, displacement, and segment. 11462 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11463 11464 unsigned t1 = F->getRegInfo().createVirtualRegister(RC); 11465 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1); 11466 for (int i=0; i <= lastAddrIndx; ++i) 11467 (*MIB).addOperand(*argOpers[i]); 11468 unsigned t2 = F->getRegInfo().createVirtualRegister(RC); 11469 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2); 11470 // add 4 to displacement. 11471 for (int i=0; i <= lastAddrIndx-2; ++i) 11472 (*MIB).addOperand(*argOpers[i]); 11473 MachineOperand newOp3 = *(argOpers[3]); 11474 if (newOp3.isImm()) 11475 newOp3.setImm(newOp3.getImm()+4); 11476 else 11477 newOp3.setOffset(newOp3.getOffset()+4); 11478 (*MIB).addOperand(newOp3); 11479 (*MIB).addOperand(*argOpers[lastAddrIndx]); 11480 11481 // t3/4 are defined later, at the bottom of the loop 11482 unsigned t3 = F->getRegInfo().createVirtualRegister(RC); 11483 unsigned t4 = F->getRegInfo().createVirtualRegister(RC); 11484 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg()) 11485 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB); 11486 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg()) 11487 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB); 11488 11489 // The subsequent operations should be using the destination registers of 11490 //the PHI instructions. 11491 if (invSrc) { 11492 t1 = F->getRegInfo().createVirtualRegister(RC); 11493 t2 = F->getRegInfo().createVirtualRegister(RC); 11494 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg()); 11495 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg()); 11496 } else { 11497 t1 = dest1Oper.getReg(); 11498 t2 = dest2Oper.getReg(); 11499 } 11500 11501 int valArgIndx = lastAddrIndx + 1; 11502 assert((argOpers[valArgIndx]->isReg() || 11503 argOpers[valArgIndx]->isImm()) && 11504 "invalid operand"); 11505 unsigned t5 = F->getRegInfo().createVirtualRegister(RC); 11506 unsigned t6 = F->getRegInfo().createVirtualRegister(RC); 11507 if (argOpers[valArgIndx]->isReg()) 11508 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5); 11509 else 11510 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5); 11511 if (regOpcL != X86::MOV32rr) 11512 MIB.addReg(t1); 11513 (*MIB).addOperand(*argOpers[valArgIndx]); 11514 assert(argOpers[valArgIndx + 1]->isReg() == 11515 argOpers[valArgIndx]->isReg()); 11516 assert(argOpers[valArgIndx + 1]->isImm() == 11517 argOpers[valArgIndx]->isImm()); 11518 if (argOpers[valArgIndx + 1]->isReg()) 11519 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6); 11520 else 11521 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6); 11522 if (regOpcH != X86::MOV32rr) 11523 MIB.addReg(t2); 11524 (*MIB).addOperand(*argOpers[valArgIndx + 1]); 11525 11526 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11527 MIB.addReg(t1); 11528 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX); 11529 MIB.addReg(t2); 11530 11531 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX); 11532 MIB.addReg(t5); 11533 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX); 11534 MIB.addReg(t6); 11535 11536 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B)); 11537 for (int i=0; i <= lastAddrIndx; ++i) 11538 (*MIB).addOperand(*argOpers[i]); 11539 11540 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11541 (*MIB).setMemRefs(bInstr->memoperands_begin(), 11542 bInstr->memoperands_end()); 11543 11544 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3); 11545 MIB.addReg(X86::EAX); 11546 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4); 11547 MIB.addReg(X86::EDX); 11548 11549 // insert branch 11550 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11551 11552 bInstr->eraseFromParent(); // The pseudo instruction is gone now. 11553 return nextMBB; 11554} 11555 11556// private utility function 11557MachineBasicBlock * 11558X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr, 11559 MachineBasicBlock *MBB, 11560 unsigned cmovOpc) const { 11561 // For the atomic min/max operator, we generate 11562 // thisMBB: 11563 // newMBB: 11564 // ld t1 = [min/max.addr] 11565 // mov t2 = [min/max.val] 11566 // cmp t1, t2 11567 // cmov[cond] t2 = t1 11568 // mov EAX = t1 11569 // lcs dest = [bitinstr.addr], t2 [EAX is implicit] 11570 // bz newMBB 11571 // fallthrough -->nextMBB 11572 // 11573 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11574 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11575 MachineFunction::iterator MBBIter = MBB; 11576 ++MBBIter; 11577 11578 /// First build the CFG 11579 MachineFunction *F = MBB->getParent(); 11580 MachineBasicBlock *thisMBB = MBB; 11581 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB); 11582 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB); 11583 F->insert(MBBIter, newMBB); 11584 F->insert(MBBIter, nextMBB); 11585 11586 // Transfer the remainder of thisMBB and its successor edges to nextMBB. 11587 nextMBB->splice(nextMBB->begin(), thisMBB, 11588 llvm::next(MachineBasicBlock::iterator(mInstr)), 11589 thisMBB->end()); 11590 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11591 11592 // Update thisMBB to fall through to newMBB 11593 thisMBB->addSuccessor(newMBB); 11594 11595 // newMBB jumps to newMBB and fall through to nextMBB 11596 newMBB->addSuccessor(nextMBB); 11597 newMBB->addSuccessor(newMBB); 11598 11599 DebugLoc dl = mInstr->getDebugLoc(); 11600 // Insert instructions into newMBB based on incoming instruction 11601 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 && 11602 "unexpected number of operands"); 11603 MachineOperand& destOper = mInstr->getOperand(0); 11604 MachineOperand* argOpers[2 + X86::AddrNumOperands]; 11605 int numArgs = mInstr->getNumOperands() - 1; 11606 for (int i=0; i < numArgs; ++i) 11607 argOpers[i] = &mInstr->getOperand(i+1); 11608 11609 // x86 address has 4 operands: base, index, scale, and displacement 11610 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3] 11611 int valArgIndx = lastAddrIndx + 1; 11612 11613 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11614 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1); 11615 for (int i=0; i <= lastAddrIndx; ++i) 11616 (*MIB).addOperand(*argOpers[i]); 11617 11618 // We only support register and immediate values 11619 assert((argOpers[valArgIndx]->isReg() || 11620 argOpers[valArgIndx]->isImm()) && 11621 "invalid operand"); 11622 11623 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11624 if (argOpers[valArgIndx]->isReg()) 11625 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2); 11626 else 11627 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2); 11628 (*MIB).addOperand(*argOpers[valArgIndx]); 11629 11630 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX); 11631 MIB.addReg(t1); 11632 11633 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr)); 11634 MIB.addReg(t1); 11635 MIB.addReg(t2); 11636 11637 // Generate movc 11638 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass); 11639 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3); 11640 MIB.addReg(t2); 11641 MIB.addReg(t1); 11642 11643 // Cmp and exchange if none has modified the memory location 11644 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32)); 11645 for (int i=0; i <= lastAddrIndx; ++i) 11646 (*MIB).addOperand(*argOpers[i]); 11647 MIB.addReg(t3); 11648 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand"); 11649 (*MIB).setMemRefs(mInstr->memoperands_begin(), 11650 mInstr->memoperands_end()); 11651 11652 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg()); 11653 MIB.addReg(X86::EAX); 11654 11655 // insert branch 11656 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB); 11657 11658 mInstr->eraseFromParent(); // The pseudo instruction is gone now. 11659 return nextMBB; 11660} 11661 11662// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 11663// or XMM0_V32I8 in AVX all of this code can be replaced with that 11664// in the .td file. 11665MachineBasicBlock * 11666X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB, 11667 unsigned numArgs, bool memArg) const { 11668 assert(Subtarget->hasSSE42orAVX() && 11669 "Target must have SSE4.2 or AVX features enabled"); 11670 11671 DebugLoc dl = MI->getDebugLoc(); 11672 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11673 unsigned Opc; 11674 if (!Subtarget->hasAVX()) { 11675 if (memArg) 11676 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm; 11677 else 11678 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr; 11679 } else { 11680 if (memArg) 11681 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm; 11682 else 11683 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr; 11684 } 11685 11686 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 11687 for (unsigned i = 0; i < numArgs; ++i) { 11688 MachineOperand &Op = MI->getOperand(i+1); 11689 if (!(Op.isReg() && Op.isImplicit())) 11690 MIB.addOperand(Op); 11691 } 11692 BuildMI(*BB, MI, dl, 11693 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr), 11694 MI->getOperand(0).getReg()) 11695 .addReg(X86::XMM0); 11696 11697 MI->eraseFromParent(); 11698 return BB; 11699} 11700 11701MachineBasicBlock * 11702X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const { 11703 DebugLoc dl = MI->getDebugLoc(); 11704 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11705 11706 // Address into RAX/EAX, other two args into ECX, EDX. 11707 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 11708 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 11709 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 11710 for (int i = 0; i < X86::AddrNumOperands; ++i) 11711 MIB.addOperand(MI->getOperand(i)); 11712 11713 unsigned ValOps = X86::AddrNumOperands; 11714 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11715 .addReg(MI->getOperand(ValOps).getReg()); 11716 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 11717 .addReg(MI->getOperand(ValOps+1).getReg()); 11718 11719 // The instruction doesn't actually take any operands though. 11720 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 11721 11722 MI->eraseFromParent(); // The pseudo is gone now. 11723 return BB; 11724} 11725 11726MachineBasicBlock * 11727X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const { 11728 DebugLoc dl = MI->getDebugLoc(); 11729 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11730 11731 // First arg in ECX, the second in EAX. 11732 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 11733 .addReg(MI->getOperand(0).getReg()); 11734 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX) 11735 .addReg(MI->getOperand(1).getReg()); 11736 11737 // The instruction doesn't actually take any operands though. 11738 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr)); 11739 11740 MI->eraseFromParent(); // The pseudo is gone now. 11741 return BB; 11742} 11743 11744MachineBasicBlock * 11745X86TargetLowering::EmitVAARG64WithCustomInserter( 11746 MachineInstr *MI, 11747 MachineBasicBlock *MBB) const { 11748 // Emit va_arg instruction on X86-64. 11749 11750 // Operands to this pseudo-instruction: 11751 // 0 ) Output : destination address (reg) 11752 // 1-5) Input : va_list address (addr, i64mem) 11753 // 6 ) ArgSize : Size (in bytes) of vararg type 11754 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 11755 // 8 ) Align : Alignment of type 11756 // 9 ) EFLAGS (implicit-def) 11757 11758 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 11759 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 11760 11761 unsigned DestReg = MI->getOperand(0).getReg(); 11762 MachineOperand &Base = MI->getOperand(1); 11763 MachineOperand &Scale = MI->getOperand(2); 11764 MachineOperand &Index = MI->getOperand(3); 11765 MachineOperand &Disp = MI->getOperand(4); 11766 MachineOperand &Segment = MI->getOperand(5); 11767 unsigned ArgSize = MI->getOperand(6).getImm(); 11768 unsigned ArgMode = MI->getOperand(7).getImm(); 11769 unsigned Align = MI->getOperand(8).getImm(); 11770 11771 // Memory Reference 11772 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 11773 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 11774 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 11775 11776 // Machine Information 11777 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 11778 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 11779 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 11780 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 11781 DebugLoc DL = MI->getDebugLoc(); 11782 11783 // struct va_list { 11784 // i32 gp_offset 11785 // i32 fp_offset 11786 // i64 overflow_area (address) 11787 // i64 reg_save_area (address) 11788 // } 11789 // sizeof(va_list) = 24 11790 // alignment(va_list) = 8 11791 11792 unsigned TotalNumIntRegs = 6; 11793 unsigned TotalNumXMMRegs = 8; 11794 bool UseGPOffset = (ArgMode == 1); 11795 bool UseFPOffset = (ArgMode == 2); 11796 unsigned MaxOffset = TotalNumIntRegs * 8 + 11797 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 11798 11799 /* Align ArgSize to a multiple of 8 */ 11800 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 11801 bool NeedsAlign = (Align > 8); 11802 11803 MachineBasicBlock *thisMBB = MBB; 11804 MachineBasicBlock *overflowMBB; 11805 MachineBasicBlock *offsetMBB; 11806 MachineBasicBlock *endMBB; 11807 11808 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 11809 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 11810 unsigned OffsetReg = 0; 11811 11812 if (!UseGPOffset && !UseFPOffset) { 11813 // If we only pull from the overflow region, we don't create a branch. 11814 // We don't need to alter control flow. 11815 OffsetDestReg = 0; // unused 11816 OverflowDestReg = DestReg; 11817 11818 offsetMBB = NULL; 11819 overflowMBB = thisMBB; 11820 endMBB = thisMBB; 11821 } else { 11822 // First emit code to check if gp_offset (or fp_offset) is below the bound. 11823 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 11824 // If not, pull from overflow_area. (branch to overflowMBB) 11825 // 11826 // thisMBB 11827 // | . 11828 // | . 11829 // offsetMBB overflowMBB 11830 // | . 11831 // | . 11832 // endMBB 11833 11834 // Registers for the PHI in endMBB 11835 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 11836 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 11837 11838 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 11839 MachineFunction *MF = MBB->getParent(); 11840 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11841 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11842 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 11843 11844 MachineFunction::iterator MBBIter = MBB; 11845 ++MBBIter; 11846 11847 // Insert the new basic blocks 11848 MF->insert(MBBIter, offsetMBB); 11849 MF->insert(MBBIter, overflowMBB); 11850 MF->insert(MBBIter, endMBB); 11851 11852 // Transfer the remainder of MBB and its successor edges to endMBB. 11853 endMBB->splice(endMBB->begin(), thisMBB, 11854 llvm::next(MachineBasicBlock::iterator(MI)), 11855 thisMBB->end()); 11856 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 11857 11858 // Make offsetMBB and overflowMBB successors of thisMBB 11859 thisMBB->addSuccessor(offsetMBB); 11860 thisMBB->addSuccessor(overflowMBB); 11861 11862 // endMBB is a successor of both offsetMBB and overflowMBB 11863 offsetMBB->addSuccessor(endMBB); 11864 overflowMBB->addSuccessor(endMBB); 11865 11866 // Load the offset value into a register 11867 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11868 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 11869 .addOperand(Base) 11870 .addOperand(Scale) 11871 .addOperand(Index) 11872 .addDisp(Disp, UseFPOffset ? 4 : 0) 11873 .addOperand(Segment) 11874 .setMemRefs(MMOBegin, MMOEnd); 11875 11876 // Check if there is enough room left to pull this argument. 11877 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 11878 .addReg(OffsetReg) 11879 .addImm(MaxOffset + 8 - ArgSizeA8); 11880 11881 // Branch to "overflowMBB" if offset >= max 11882 // Fall through to "offsetMBB" otherwise 11883 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 11884 .addMBB(overflowMBB); 11885 } 11886 11887 // In offsetMBB, emit code to use the reg_save_area. 11888 if (offsetMBB) { 11889 assert(OffsetReg != 0); 11890 11891 // Read the reg_save_area address. 11892 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 11893 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 11894 .addOperand(Base) 11895 .addOperand(Scale) 11896 .addOperand(Index) 11897 .addDisp(Disp, 16) 11898 .addOperand(Segment) 11899 .setMemRefs(MMOBegin, MMOEnd); 11900 11901 // Zero-extend the offset 11902 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 11903 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 11904 .addImm(0) 11905 .addReg(OffsetReg) 11906 .addImm(X86::sub_32bit); 11907 11908 // Add the offset to the reg_save_area to get the final address. 11909 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 11910 .addReg(OffsetReg64) 11911 .addReg(RegSaveReg); 11912 11913 // Compute the offset for the next argument 11914 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 11915 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 11916 .addReg(OffsetReg) 11917 .addImm(UseFPOffset ? 16 : 8); 11918 11919 // Store it back into the va_list. 11920 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 11921 .addOperand(Base) 11922 .addOperand(Scale) 11923 .addOperand(Index) 11924 .addDisp(Disp, UseFPOffset ? 4 : 0) 11925 .addOperand(Segment) 11926 .addReg(NextOffsetReg) 11927 .setMemRefs(MMOBegin, MMOEnd); 11928 11929 // Jump to endMBB 11930 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 11931 .addMBB(endMBB); 11932 } 11933 11934 // 11935 // Emit code to use overflow area 11936 // 11937 11938 // Load the overflow_area address into a register. 11939 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 11940 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 11941 .addOperand(Base) 11942 .addOperand(Scale) 11943 .addOperand(Index) 11944 .addDisp(Disp, 8) 11945 .addOperand(Segment) 11946 .setMemRefs(MMOBegin, MMOEnd); 11947 11948 // If we need to align it, do so. Otherwise, just copy the address 11949 // to OverflowDestReg. 11950 if (NeedsAlign) { 11951 // Align the overflow address 11952 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 11953 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 11954 11955 // aligned_addr = (addr + (align-1)) & ~(align-1) 11956 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 11957 .addReg(OverflowAddrReg) 11958 .addImm(Align-1); 11959 11960 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 11961 .addReg(TmpReg) 11962 .addImm(~(uint64_t)(Align-1)); 11963 } else { 11964 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 11965 .addReg(OverflowAddrReg); 11966 } 11967 11968 // Compute the next overflow address after this argument. 11969 // (the overflow address should be kept 8-byte aligned) 11970 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 11971 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 11972 .addReg(OverflowDestReg) 11973 .addImm(ArgSizeA8); 11974 11975 // Store the new overflow address. 11976 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 11977 .addOperand(Base) 11978 .addOperand(Scale) 11979 .addOperand(Index) 11980 .addDisp(Disp, 8) 11981 .addOperand(Segment) 11982 .addReg(NextAddrReg) 11983 .setMemRefs(MMOBegin, MMOEnd); 11984 11985 // If we branched, emit the PHI to the front of endMBB. 11986 if (offsetMBB) { 11987 BuildMI(*endMBB, endMBB->begin(), DL, 11988 TII->get(X86::PHI), DestReg) 11989 .addReg(OffsetDestReg).addMBB(offsetMBB) 11990 .addReg(OverflowDestReg).addMBB(overflowMBB); 11991 } 11992 11993 // Erase the pseudo instruction 11994 MI->eraseFromParent(); 11995 11996 return endMBB; 11997} 11998 11999MachineBasicBlock * 12000X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 12001 MachineInstr *MI, 12002 MachineBasicBlock *MBB) const { 12003 // Emit code to save XMM registers to the stack. The ABI says that the 12004 // number of registers to save is given in %al, so it's theoretically 12005 // possible to do an indirect jump trick to avoid saving all of them, 12006 // however this code takes a simpler approach and just executes all 12007 // of the stores if %al is non-zero. It's less code, and it's probably 12008 // easier on the hardware branch predictor, and stores aren't all that 12009 // expensive anyway. 12010 12011 // Create the new basic blocks. One block contains all the XMM stores, 12012 // and one block is the final destination regardless of whether any 12013 // stores were performed. 12014 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 12015 MachineFunction *F = MBB->getParent(); 12016 MachineFunction::iterator MBBIter = MBB; 12017 ++MBBIter; 12018 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 12019 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 12020 F->insert(MBBIter, XMMSaveMBB); 12021 F->insert(MBBIter, EndMBB); 12022 12023 // Transfer the remainder of MBB and its successor edges to EndMBB. 12024 EndMBB->splice(EndMBB->begin(), MBB, 12025 llvm::next(MachineBasicBlock::iterator(MI)), 12026 MBB->end()); 12027 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 12028 12029 // The original block will now fall through to the XMM save block. 12030 MBB->addSuccessor(XMMSaveMBB); 12031 // The XMMSaveMBB will fall through to the end block. 12032 XMMSaveMBB->addSuccessor(EndMBB); 12033 12034 // Now add the instructions. 12035 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12036 DebugLoc DL = MI->getDebugLoc(); 12037 12038 unsigned CountReg = MI->getOperand(0).getReg(); 12039 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 12040 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 12041 12042 if (!Subtarget->isTargetWin64()) { 12043 // If %al is 0, branch around the XMM save block. 12044 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 12045 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 12046 MBB->addSuccessor(EndMBB); 12047 } 12048 12049 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr; 12050 // In the XMM save block, save all the XMM argument registers. 12051 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 12052 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 12053 MachineMemOperand *MMO = 12054 F->getMachineMemOperand( 12055 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 12056 MachineMemOperand::MOStore, 12057 /*Size=*/16, /*Align=*/16); 12058 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 12059 .addFrameIndex(RegSaveFrameIndex) 12060 .addImm(/*Scale=*/1) 12061 .addReg(/*IndexReg=*/0) 12062 .addImm(/*Disp=*/Offset) 12063 .addReg(/*Segment=*/0) 12064 .addReg(MI->getOperand(i).getReg()) 12065 .addMemOperand(MMO); 12066 } 12067 12068 MI->eraseFromParent(); // The pseudo instruction is gone now. 12069 12070 return EndMBB; 12071} 12072 12073MachineBasicBlock * 12074X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 12075 MachineBasicBlock *BB) const { 12076 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12077 DebugLoc DL = MI->getDebugLoc(); 12078 12079 // To "insert" a SELECT_CC instruction, we actually have to insert the 12080 // diamond control-flow pattern. The incoming instruction knows the 12081 // destination vreg to set, the condition code register to branch on, the 12082 // true/false values to select between, and a branch opcode to use. 12083 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12084 MachineFunction::iterator It = BB; 12085 ++It; 12086 12087 // thisMBB: 12088 // ... 12089 // TrueVal = ... 12090 // cmpTY ccX, r1, r2 12091 // bCC copy1MBB 12092 // fallthrough --> copy0MBB 12093 MachineBasicBlock *thisMBB = BB; 12094 MachineFunction *F = BB->getParent(); 12095 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12096 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12097 F->insert(It, copy0MBB); 12098 F->insert(It, sinkMBB); 12099 12100 // If the EFLAGS register isn't dead in the terminator, then claim that it's 12101 // live into the sink and copy blocks. 12102 if (!MI->killsRegister(X86::EFLAGS)) { 12103 copy0MBB->addLiveIn(X86::EFLAGS); 12104 sinkMBB->addLiveIn(X86::EFLAGS); 12105 } 12106 12107 // Transfer the remainder of BB and its successor edges to sinkMBB. 12108 sinkMBB->splice(sinkMBB->begin(), BB, 12109 llvm::next(MachineBasicBlock::iterator(MI)), 12110 BB->end()); 12111 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12112 12113 // Add the true and fallthrough blocks as its successors. 12114 BB->addSuccessor(copy0MBB); 12115 BB->addSuccessor(sinkMBB); 12116 12117 // Create the conditional branch instruction. 12118 unsigned Opc = 12119 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 12120 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 12121 12122 // copy0MBB: 12123 // %FalseValue = ... 12124 // # fallthrough to sinkMBB 12125 copy0MBB->addSuccessor(sinkMBB); 12126 12127 // sinkMBB: 12128 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12129 // ... 12130 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12131 TII->get(X86::PHI), MI->getOperand(0).getReg()) 12132 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 12133 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 12134 12135 MI->eraseFromParent(); // The pseudo instruction is gone now. 12136 return sinkMBB; 12137} 12138 12139MachineBasicBlock * 12140X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 12141 bool Is64Bit) const { 12142 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12143 DebugLoc DL = MI->getDebugLoc(); 12144 MachineFunction *MF = BB->getParent(); 12145 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12146 12147 assert(EnableSegmentedStacks); 12148 12149 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 12150 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 12151 12152 // BB: 12153 // ... [Till the alloca] 12154 // If stacklet is not large enough, jump to mallocMBB 12155 // 12156 // bumpMBB: 12157 // Allocate by subtracting from RSP 12158 // Jump to continueMBB 12159 // 12160 // mallocMBB: 12161 // Allocate by call to runtime 12162 // 12163 // continueMBB: 12164 // ... 12165 // [rest of original BB] 12166 // 12167 12168 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12169 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12170 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 12171 12172 MachineRegisterInfo &MRI = MF->getRegInfo(); 12173 const TargetRegisterClass *AddrRegClass = 12174 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 12175 12176 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12177 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 12178 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 12179 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 12180 sizeVReg = MI->getOperand(1).getReg(), 12181 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 12182 12183 MachineFunction::iterator MBBIter = BB; 12184 ++MBBIter; 12185 12186 MF->insert(MBBIter, bumpMBB); 12187 MF->insert(MBBIter, mallocMBB); 12188 MF->insert(MBBIter, continueMBB); 12189 12190 continueMBB->splice(continueMBB->begin(), BB, llvm::next 12191 (MachineBasicBlock::iterator(MI)), BB->end()); 12192 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 12193 12194 // Add code to the main basic block to check if the stack limit has been hit, 12195 // and if so, jump to mallocMBB otherwise to bumpMBB. 12196 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 12197 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 12198 .addReg(tmpSPVReg).addReg(sizeVReg); 12199 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 12200 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg) 12201 .addReg(SPLimitVReg); 12202 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 12203 12204 // bumpMBB simply decreases the stack pointer, since we know the current 12205 // stacklet has enough space. 12206 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 12207 .addReg(SPLimitVReg); 12208 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 12209 .addReg(SPLimitVReg); 12210 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12211 12212 // Calls into a routine in libgcc to allocate more space from the heap. 12213 if (Is64Bit) { 12214 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 12215 .addReg(sizeVReg); 12216 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 12217 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI); 12218 } else { 12219 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 12220 .addImm(12); 12221 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 12222 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 12223 .addExternalSymbol("__morestack_allocate_stack_space"); 12224 } 12225 12226 if (!Is64Bit) 12227 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 12228 .addImm(16); 12229 12230 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 12231 .addReg(Is64Bit ? X86::RAX : X86::EAX); 12232 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 12233 12234 // Set up the CFG correctly. 12235 BB->addSuccessor(bumpMBB); 12236 BB->addSuccessor(mallocMBB); 12237 mallocMBB->addSuccessor(continueMBB); 12238 bumpMBB->addSuccessor(continueMBB); 12239 12240 // Take care of the PHI nodes. 12241 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 12242 MI->getOperand(0).getReg()) 12243 .addReg(mallocPtrVReg).addMBB(mallocMBB) 12244 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 12245 12246 // Delete the original pseudo instruction. 12247 MI->eraseFromParent(); 12248 12249 // And we're done. 12250 return continueMBB; 12251} 12252 12253MachineBasicBlock * 12254X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 12255 MachineBasicBlock *BB) const { 12256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12257 DebugLoc DL = MI->getDebugLoc(); 12258 12259 assert(!Subtarget->isTargetEnvMacho()); 12260 12261 // The lowering is pretty easy: we're just emitting the call to _alloca. The 12262 // non-trivial part is impdef of ESP. 12263 12264 if (Subtarget->isTargetWin64()) { 12265 if (Subtarget->isTargetCygMing()) { 12266 // ___chkstk(Mingw64): 12267 // Clobbers R10, R11, RAX and EFLAGS. 12268 // Updates RSP. 12269 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12270 .addExternalSymbol("___chkstk") 12271 .addReg(X86::RAX, RegState::Implicit) 12272 .addReg(X86::RSP, RegState::Implicit) 12273 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 12274 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 12275 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12276 } else { 12277 // __chkstk(MSVCRT): does not update stack pointer. 12278 // Clobbers R10, R11 and EFLAGS. 12279 // FIXME: RAX(allocated size) might be reused and not killed. 12280 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 12281 .addExternalSymbol("__chkstk") 12282 .addReg(X86::RAX, RegState::Implicit) 12283 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12284 // RAX has the offset to subtracted from RSP. 12285 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 12286 .addReg(X86::RSP) 12287 .addReg(X86::RAX); 12288 } 12289 } else { 12290 const char *StackProbeSymbol = 12291 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 12292 12293 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 12294 .addExternalSymbol(StackProbeSymbol) 12295 .addReg(X86::EAX, RegState::Implicit) 12296 .addReg(X86::ESP, RegState::Implicit) 12297 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 12298 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 12299 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 12300 } 12301 12302 MI->eraseFromParent(); // The pseudo instruction is gone now. 12303 return BB; 12304} 12305 12306MachineBasicBlock * 12307X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 12308 MachineBasicBlock *BB) const { 12309 // This is pretty easy. We're taking the value that we received from 12310 // our load from the relocation, sticking it in either RDI (x86-64) 12311 // or EAX and doing an indirect call. The return value will then 12312 // be in the normal return register. 12313 const X86InstrInfo *TII 12314 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 12315 DebugLoc DL = MI->getDebugLoc(); 12316 MachineFunction *F = BB->getParent(); 12317 12318 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 12319 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 12320 12321 if (Subtarget->is64Bit()) { 12322 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12323 TII->get(X86::MOV64rm), X86::RDI) 12324 .addReg(X86::RIP) 12325 .addImm(0).addReg(0) 12326 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12327 MI->getOperand(3).getTargetFlags()) 12328 .addReg(0); 12329 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 12330 addDirectMem(MIB, X86::RDI); 12331 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 12332 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12333 TII->get(X86::MOV32rm), X86::EAX) 12334 .addReg(0) 12335 .addImm(0).addReg(0) 12336 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12337 MI->getOperand(3).getTargetFlags()) 12338 .addReg(0); 12339 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12340 addDirectMem(MIB, X86::EAX); 12341 } else { 12342 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 12343 TII->get(X86::MOV32rm), X86::EAX) 12344 .addReg(TII->getGlobalBaseReg(F)) 12345 .addImm(0).addReg(0) 12346 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 12347 MI->getOperand(3).getTargetFlags()) 12348 .addReg(0); 12349 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 12350 addDirectMem(MIB, X86::EAX); 12351 } 12352 12353 MI->eraseFromParent(); // The pseudo instruction is gone now. 12354 return BB; 12355} 12356 12357MachineBasicBlock * 12358X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 12359 MachineBasicBlock *BB) const { 12360 switch (MI->getOpcode()) { 12361 default: assert(0 && "Unexpected instr type to insert"); 12362 case X86::TAILJMPd64: 12363 case X86::TAILJMPr64: 12364 case X86::TAILJMPm64: 12365 assert(0 && "TAILJMP64 would not be touched here."); 12366 case X86::TCRETURNdi64: 12367 case X86::TCRETURNri64: 12368 case X86::TCRETURNmi64: 12369 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset. 12370 // On AMD64, additional defs should be added before register allocation. 12371 if (!Subtarget->isTargetWin64()) { 12372 MI->addRegisterDefined(X86::RSI); 12373 MI->addRegisterDefined(X86::RDI); 12374 MI->addRegisterDefined(X86::XMM6); 12375 MI->addRegisterDefined(X86::XMM7); 12376 MI->addRegisterDefined(X86::XMM8); 12377 MI->addRegisterDefined(X86::XMM9); 12378 MI->addRegisterDefined(X86::XMM10); 12379 MI->addRegisterDefined(X86::XMM11); 12380 MI->addRegisterDefined(X86::XMM12); 12381 MI->addRegisterDefined(X86::XMM13); 12382 MI->addRegisterDefined(X86::XMM14); 12383 MI->addRegisterDefined(X86::XMM15); 12384 } 12385 return BB; 12386 case X86::WIN_ALLOCA: 12387 return EmitLoweredWinAlloca(MI, BB); 12388 case X86::SEG_ALLOCA_32: 12389 return EmitLoweredSegAlloca(MI, BB, false); 12390 case X86::SEG_ALLOCA_64: 12391 return EmitLoweredSegAlloca(MI, BB, true); 12392 case X86::TLSCall_32: 12393 case X86::TLSCall_64: 12394 return EmitLoweredTLSCall(MI, BB); 12395 case X86::CMOV_GR8: 12396 case X86::CMOV_FR32: 12397 case X86::CMOV_FR64: 12398 case X86::CMOV_V4F32: 12399 case X86::CMOV_V2F64: 12400 case X86::CMOV_V2I64: 12401 case X86::CMOV_V8F32: 12402 case X86::CMOV_V4F64: 12403 case X86::CMOV_V4I64: 12404 case X86::CMOV_GR16: 12405 case X86::CMOV_GR32: 12406 case X86::CMOV_RFP32: 12407 case X86::CMOV_RFP64: 12408 case X86::CMOV_RFP80: 12409 return EmitLoweredSelect(MI, BB); 12410 12411 case X86::FP32_TO_INT16_IN_MEM: 12412 case X86::FP32_TO_INT32_IN_MEM: 12413 case X86::FP32_TO_INT64_IN_MEM: 12414 case X86::FP64_TO_INT16_IN_MEM: 12415 case X86::FP64_TO_INT32_IN_MEM: 12416 case X86::FP64_TO_INT64_IN_MEM: 12417 case X86::FP80_TO_INT16_IN_MEM: 12418 case X86::FP80_TO_INT32_IN_MEM: 12419 case X86::FP80_TO_INT64_IN_MEM: { 12420 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12421 DebugLoc DL = MI->getDebugLoc(); 12422 12423 // Change the floating point control register to use "round towards zero" 12424 // mode when truncating to an integer value. 12425 MachineFunction *F = BB->getParent(); 12426 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 12427 addFrameReference(BuildMI(*BB, MI, DL, 12428 TII->get(X86::FNSTCW16m)), CWFrameIdx); 12429 12430 // Load the old value of the high byte of the control word... 12431 unsigned OldCW = 12432 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass); 12433 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 12434 CWFrameIdx); 12435 12436 // Set the high part to be round to zero... 12437 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 12438 .addImm(0xC7F); 12439 12440 // Reload the modified control word now... 12441 addFrameReference(BuildMI(*BB, MI, DL, 12442 TII->get(X86::FLDCW16m)), CWFrameIdx); 12443 12444 // Restore the memory image of control word to original value 12445 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 12446 .addReg(OldCW); 12447 12448 // Get the X86 opcode to use. 12449 unsigned Opc; 12450 switch (MI->getOpcode()) { 12451 default: llvm_unreachable("illegal opcode!"); 12452 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 12453 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 12454 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 12455 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 12456 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 12457 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 12458 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 12459 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 12460 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 12461 } 12462 12463 X86AddressMode AM; 12464 MachineOperand &Op = MI->getOperand(0); 12465 if (Op.isReg()) { 12466 AM.BaseType = X86AddressMode::RegBase; 12467 AM.Base.Reg = Op.getReg(); 12468 } else { 12469 AM.BaseType = X86AddressMode::FrameIndexBase; 12470 AM.Base.FrameIndex = Op.getIndex(); 12471 } 12472 Op = MI->getOperand(1); 12473 if (Op.isImm()) 12474 AM.Scale = Op.getImm(); 12475 Op = MI->getOperand(2); 12476 if (Op.isImm()) 12477 AM.IndexReg = Op.getImm(); 12478 Op = MI->getOperand(3); 12479 if (Op.isGlobal()) { 12480 AM.GV = Op.getGlobal(); 12481 } else { 12482 AM.Disp = Op.getImm(); 12483 } 12484 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 12485 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 12486 12487 // Reload the original control word now. 12488 addFrameReference(BuildMI(*BB, MI, DL, 12489 TII->get(X86::FLDCW16m)), CWFrameIdx); 12490 12491 MI->eraseFromParent(); // The pseudo instruction is gone now. 12492 return BB; 12493 } 12494 // String/text processing lowering. 12495 case X86::PCMPISTRM128REG: 12496 case X86::VPCMPISTRM128REG: 12497 return EmitPCMP(MI, BB, 3, false /* in-mem */); 12498 case X86::PCMPISTRM128MEM: 12499 case X86::VPCMPISTRM128MEM: 12500 return EmitPCMP(MI, BB, 3, true /* in-mem */); 12501 case X86::PCMPESTRM128REG: 12502 case X86::VPCMPESTRM128REG: 12503 return EmitPCMP(MI, BB, 5, false /* in mem */); 12504 case X86::PCMPESTRM128MEM: 12505 case X86::VPCMPESTRM128MEM: 12506 return EmitPCMP(MI, BB, 5, true /* in mem */); 12507 12508 // Thread synchronization. 12509 case X86::MONITOR: 12510 return EmitMonitor(MI, BB); 12511 case X86::MWAIT: 12512 return EmitMwait(MI, BB); 12513 12514 // Atomic Lowering. 12515 case X86::ATOMAND32: 12516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12517 X86::AND32ri, X86::MOV32rm, 12518 X86::LCMPXCHG32, 12519 X86::NOT32r, X86::EAX, 12520 X86::GR32RegisterClass); 12521 case X86::ATOMOR32: 12522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 12523 X86::OR32ri, X86::MOV32rm, 12524 X86::LCMPXCHG32, 12525 X86::NOT32r, X86::EAX, 12526 X86::GR32RegisterClass); 12527 case X86::ATOMXOR32: 12528 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr, 12529 X86::XOR32ri, X86::MOV32rm, 12530 X86::LCMPXCHG32, 12531 X86::NOT32r, X86::EAX, 12532 X86::GR32RegisterClass); 12533 case X86::ATOMNAND32: 12534 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr, 12535 X86::AND32ri, X86::MOV32rm, 12536 X86::LCMPXCHG32, 12537 X86::NOT32r, X86::EAX, 12538 X86::GR32RegisterClass, true); 12539 case X86::ATOMMIN32: 12540 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr); 12541 case X86::ATOMMAX32: 12542 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr); 12543 case X86::ATOMUMIN32: 12544 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr); 12545 case X86::ATOMUMAX32: 12546 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr); 12547 12548 case X86::ATOMAND16: 12549 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12550 X86::AND16ri, X86::MOV16rm, 12551 X86::LCMPXCHG16, 12552 X86::NOT16r, X86::AX, 12553 X86::GR16RegisterClass); 12554 case X86::ATOMOR16: 12555 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 12556 X86::OR16ri, X86::MOV16rm, 12557 X86::LCMPXCHG16, 12558 X86::NOT16r, X86::AX, 12559 X86::GR16RegisterClass); 12560 case X86::ATOMXOR16: 12561 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr, 12562 X86::XOR16ri, X86::MOV16rm, 12563 X86::LCMPXCHG16, 12564 X86::NOT16r, X86::AX, 12565 X86::GR16RegisterClass); 12566 case X86::ATOMNAND16: 12567 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr, 12568 X86::AND16ri, X86::MOV16rm, 12569 X86::LCMPXCHG16, 12570 X86::NOT16r, X86::AX, 12571 X86::GR16RegisterClass, true); 12572 case X86::ATOMMIN16: 12573 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr); 12574 case X86::ATOMMAX16: 12575 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr); 12576 case X86::ATOMUMIN16: 12577 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr); 12578 case X86::ATOMUMAX16: 12579 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr); 12580 12581 case X86::ATOMAND8: 12582 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12583 X86::AND8ri, X86::MOV8rm, 12584 X86::LCMPXCHG8, 12585 X86::NOT8r, X86::AL, 12586 X86::GR8RegisterClass); 12587 case X86::ATOMOR8: 12588 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 12589 X86::OR8ri, X86::MOV8rm, 12590 X86::LCMPXCHG8, 12591 X86::NOT8r, X86::AL, 12592 X86::GR8RegisterClass); 12593 case X86::ATOMXOR8: 12594 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr, 12595 X86::XOR8ri, X86::MOV8rm, 12596 X86::LCMPXCHG8, 12597 X86::NOT8r, X86::AL, 12598 X86::GR8RegisterClass); 12599 case X86::ATOMNAND8: 12600 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr, 12601 X86::AND8ri, X86::MOV8rm, 12602 X86::LCMPXCHG8, 12603 X86::NOT8r, X86::AL, 12604 X86::GR8RegisterClass, true); 12605 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way. 12606 // This group is for 64-bit host. 12607 case X86::ATOMAND64: 12608 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12609 X86::AND64ri32, X86::MOV64rm, 12610 X86::LCMPXCHG64, 12611 X86::NOT64r, X86::RAX, 12612 X86::GR64RegisterClass); 12613 case X86::ATOMOR64: 12614 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 12615 X86::OR64ri32, X86::MOV64rm, 12616 X86::LCMPXCHG64, 12617 X86::NOT64r, X86::RAX, 12618 X86::GR64RegisterClass); 12619 case X86::ATOMXOR64: 12620 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr, 12621 X86::XOR64ri32, X86::MOV64rm, 12622 X86::LCMPXCHG64, 12623 X86::NOT64r, X86::RAX, 12624 X86::GR64RegisterClass); 12625 case X86::ATOMNAND64: 12626 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr, 12627 X86::AND64ri32, X86::MOV64rm, 12628 X86::LCMPXCHG64, 12629 X86::NOT64r, X86::RAX, 12630 X86::GR64RegisterClass, true); 12631 case X86::ATOMMIN64: 12632 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr); 12633 case X86::ATOMMAX64: 12634 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr); 12635 case X86::ATOMUMIN64: 12636 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr); 12637 case X86::ATOMUMAX64: 12638 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr); 12639 12640 // This group does 64-bit operations on a 32-bit host. 12641 case X86::ATOMAND6432: 12642 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12643 X86::AND32rr, X86::AND32rr, 12644 X86::AND32ri, X86::AND32ri, 12645 false); 12646 case X86::ATOMOR6432: 12647 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12648 X86::OR32rr, X86::OR32rr, 12649 X86::OR32ri, X86::OR32ri, 12650 false); 12651 case X86::ATOMXOR6432: 12652 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12653 X86::XOR32rr, X86::XOR32rr, 12654 X86::XOR32ri, X86::XOR32ri, 12655 false); 12656 case X86::ATOMNAND6432: 12657 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12658 X86::AND32rr, X86::AND32rr, 12659 X86::AND32ri, X86::AND32ri, 12660 true); 12661 case X86::ATOMADD6432: 12662 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12663 X86::ADD32rr, X86::ADC32rr, 12664 X86::ADD32ri, X86::ADC32ri, 12665 false); 12666 case X86::ATOMSUB6432: 12667 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12668 X86::SUB32rr, X86::SBB32rr, 12669 X86::SUB32ri, X86::SBB32ri, 12670 false); 12671 case X86::ATOMSWAP6432: 12672 return EmitAtomicBit6432WithCustomInserter(MI, BB, 12673 X86::MOV32rr, X86::MOV32rr, 12674 X86::MOV32ri, X86::MOV32ri, 12675 false); 12676 case X86::VASTART_SAVE_XMM_REGS: 12677 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 12678 12679 case X86::VAARG_64: 12680 return EmitVAARG64WithCustomInserter(MI, BB); 12681 } 12682} 12683 12684//===----------------------------------------------------------------------===// 12685// X86 Optimization Hooks 12686//===----------------------------------------------------------------------===// 12687 12688void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 12689 const APInt &Mask, 12690 APInt &KnownZero, 12691 APInt &KnownOne, 12692 const SelectionDAG &DAG, 12693 unsigned Depth) const { 12694 unsigned Opc = Op.getOpcode(); 12695 assert((Opc >= ISD::BUILTIN_OP_END || 12696 Opc == ISD::INTRINSIC_WO_CHAIN || 12697 Opc == ISD::INTRINSIC_W_CHAIN || 12698 Opc == ISD::INTRINSIC_VOID) && 12699 "Should use MaskedValueIsZero if you don't know whether Op" 12700 " is a target node!"); 12701 12702 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything. 12703 switch (Opc) { 12704 default: break; 12705 case X86ISD::ADD: 12706 case X86ISD::SUB: 12707 case X86ISD::ADC: 12708 case X86ISD::SBB: 12709 case X86ISD::SMUL: 12710 case X86ISD::UMUL: 12711 case X86ISD::INC: 12712 case X86ISD::DEC: 12713 case X86ISD::OR: 12714 case X86ISD::XOR: 12715 case X86ISD::AND: 12716 // These nodes' second result is a boolean. 12717 if (Op.getResNo() == 0) 12718 break; 12719 // Fallthrough 12720 case X86ISD::SETCC: 12721 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(), 12722 Mask.getBitWidth() - 1); 12723 break; 12724 case ISD::INTRINSIC_WO_CHAIN: { 12725 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 12726 unsigned NumLoBits = 0; 12727 switch (IntId) { 12728 default: break; 12729 case Intrinsic::x86_sse_movmsk_ps: 12730 case Intrinsic::x86_avx_movmsk_ps_256: 12731 case Intrinsic::x86_sse2_movmsk_pd: 12732 case Intrinsic::x86_avx_movmsk_pd_256: 12733 case Intrinsic::x86_mmx_pmovmskb: 12734 case Intrinsic::x86_sse2_pmovmskb_128: { 12735 // High bits of movmskp{s|d}, pmovmskb are known zero. 12736 switch (IntId) { 12737 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 12738 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 12739 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 12740 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 12741 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 12742 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 12743 } 12744 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(), 12745 Mask.getBitWidth() - NumLoBits); 12746 break; 12747 } 12748 } 12749 break; 12750 } 12751 } 12752} 12753 12754unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 12755 unsigned Depth) const { 12756 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 12757 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 12758 return Op.getValueType().getScalarType().getSizeInBits(); 12759 12760 // Fallback case. 12761 return 1; 12762} 12763 12764/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 12765/// node is a GlobalAddress + offset. 12766bool X86TargetLowering::isGAPlusOffset(SDNode *N, 12767 const GlobalValue* &GA, 12768 int64_t &Offset) const { 12769 if (N->getOpcode() == X86ISD::Wrapper) { 12770 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 12771 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 12772 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 12773 return true; 12774 } 12775 } 12776 return TargetLowering::isGAPlusOffset(N, GA, Offset); 12777} 12778 12779/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 12780/// same as extracting the high 128-bit part of 256-bit vector and then 12781/// inserting the result into the low part of a new 256-bit vector 12782static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 12783 EVT VT = SVOp->getValueType(0); 12784 int NumElems = VT.getVectorNumElements(); 12785 12786 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12787 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j) 12788 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12789 SVOp->getMaskElt(j) >= 0) 12790 return false; 12791 12792 return true; 12793} 12794 12795/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 12796/// same as extracting the low 128-bit part of 256-bit vector and then 12797/// inserting the result into the high part of a new 256-bit vector 12798static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 12799 EVT VT = SVOp->getValueType(0); 12800 int NumElems = VT.getVectorNumElements(); 12801 12802 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12803 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j) 12804 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 12805 SVOp->getMaskElt(j) >= 0) 12806 return false; 12807 12808 return true; 12809} 12810 12811/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 12812static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 12813 TargetLowering::DAGCombinerInfo &DCI) { 12814 DebugLoc dl = N->getDebugLoc(); 12815 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 12816 SDValue V1 = SVOp->getOperand(0); 12817 SDValue V2 = SVOp->getOperand(1); 12818 EVT VT = SVOp->getValueType(0); 12819 int NumElems = VT.getVectorNumElements(); 12820 12821 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 12822 V2.getOpcode() == ISD::CONCAT_VECTORS) { 12823 // 12824 // 0,0,0,... 12825 // | 12826 // V UNDEF BUILD_VECTOR UNDEF 12827 // \ / \ / 12828 // CONCAT_VECTOR CONCAT_VECTOR 12829 // \ / 12830 // \ / 12831 // RESULT: V + zero extended 12832 // 12833 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 12834 V2.getOperand(1).getOpcode() != ISD::UNDEF || 12835 V1.getOperand(1).getOpcode() != ISD::UNDEF) 12836 return SDValue(); 12837 12838 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 12839 return SDValue(); 12840 12841 // To match the shuffle mask, the first half of the mask should 12842 // be exactly the first vector, and all the rest a splat with the 12843 // first element of the second one. 12844 for (int i = 0; i < NumElems/2; ++i) 12845 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 12846 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 12847 return SDValue(); 12848 12849 // Emit a zeroed vector and insert the desired subvector on its 12850 // first half. 12851 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl); 12852 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 12853 DAG.getConstant(0, MVT::i32), DAG, dl); 12854 return DCI.CombineTo(N, InsV); 12855 } 12856 12857 //===--------------------------------------------------------------------===// 12858 // Combine some shuffles into subvector extracts and inserts: 12859 // 12860 12861 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 12862 if (isShuffleHigh128VectorInsertLow(SVOp)) { 12863 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32), 12864 DAG, dl); 12865 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12866 V, DAG.getConstant(0, MVT::i32), DAG, dl); 12867 return DCI.CombineTo(N, InsV); 12868 } 12869 12870 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 12871 if (isShuffleLow128VectorInsertHigh(SVOp)) { 12872 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl); 12873 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), 12874 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl); 12875 return DCI.CombineTo(N, InsV); 12876 } 12877 12878 return SDValue(); 12879} 12880 12881/// PerformShuffleCombine - Performs several different shuffle combines. 12882static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 12883 TargetLowering::DAGCombinerInfo &DCI, 12884 const X86Subtarget *Subtarget) { 12885 DebugLoc dl = N->getDebugLoc(); 12886 EVT VT = N->getValueType(0); 12887 12888 // Don't create instructions with illegal types after legalize types has run. 12889 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12890 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 12891 return SDValue(); 12892 12893 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 12894 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 && 12895 N->getOpcode() == ISD::VECTOR_SHUFFLE) 12896 return PerformShuffleCombine256(N, DAG, DCI); 12897 12898 // Only handle 128 wide vector from here on. 12899 if (VT.getSizeInBits() != 128) 12900 return SDValue(); 12901 12902 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 12903 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 12904 // consecutive, non-overlapping, and in the right order. 12905 SmallVector<SDValue, 16> Elts; 12906 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 12907 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 12908 12909 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 12910} 12911 12912/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 12913/// generation and convert it from being a bunch of shuffles and extracts 12914/// to a simple store and scalar loads to extract the elements. 12915static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 12916 const TargetLowering &TLI) { 12917 SDValue InputVector = N->getOperand(0); 12918 12919 // Only operate on vectors of 4 elements, where the alternative shuffling 12920 // gets to be more expensive. 12921 if (InputVector.getValueType() != MVT::v4i32) 12922 return SDValue(); 12923 12924 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 12925 // single use which is a sign-extend or zero-extend, and all elements are 12926 // used. 12927 SmallVector<SDNode *, 4> Uses; 12928 unsigned ExtractedElements = 0; 12929 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 12930 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 12931 if (UI.getUse().getResNo() != InputVector.getResNo()) 12932 return SDValue(); 12933 12934 SDNode *Extract = *UI; 12935 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12936 return SDValue(); 12937 12938 if (Extract->getValueType(0) != MVT::i32) 12939 return SDValue(); 12940 if (!Extract->hasOneUse()) 12941 return SDValue(); 12942 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 12943 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 12944 return SDValue(); 12945 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 12946 return SDValue(); 12947 12948 // Record which element was extracted. 12949 ExtractedElements |= 12950 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 12951 12952 Uses.push_back(Extract); 12953 } 12954 12955 // If not all the elements were used, this may not be worthwhile. 12956 if (ExtractedElements != 15) 12957 return SDValue(); 12958 12959 // Ok, we've now decided to do the transformation. 12960 DebugLoc dl = InputVector.getDebugLoc(); 12961 12962 // Store the value to a temporary stack slot. 12963 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 12964 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 12965 MachinePointerInfo(), false, false, 0); 12966 12967 // Replace each use (extract) with a load of the appropriate element. 12968 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 12969 UE = Uses.end(); UI != UE; ++UI) { 12970 SDNode *Extract = *UI; 12971 12972 // cOMpute the element's address. 12973 SDValue Idx = Extract->getOperand(1); 12974 unsigned EltSize = 12975 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 12976 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 12977 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 12978 12979 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 12980 StackPtr, OffsetVal); 12981 12982 // Load the scalar. 12983 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 12984 ScalarAddr, MachinePointerInfo(), 12985 false, false, false, 0); 12986 12987 // Replace the exact with the load. 12988 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 12989 } 12990 12991 // The replacement was made in place; don't return anything. 12992 return SDValue(); 12993} 12994 12995/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 12996/// nodes. 12997static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 12998 const X86Subtarget *Subtarget) { 12999 DebugLoc DL = N->getDebugLoc(); 13000 SDValue Cond = N->getOperand(0); 13001 // Get the LHS/RHS of the select. 13002 SDValue LHS = N->getOperand(1); 13003 SDValue RHS = N->getOperand(2); 13004 EVT VT = LHS.getValueType(); 13005 13006 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 13007 // instructions match the semantics of the common C idiom x<y?x:y but not 13008 // x<=y?x:y, because of how they handle negative zero (which can be 13009 // ignored in unsafe-math mode). 13010 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 13011 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 13012 (Subtarget->hasXMMInt() || 13013 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 13014 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 13015 13016 unsigned Opcode = 0; 13017 // Check for x CC y ? x : y. 13018 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 13019 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 13020 switch (CC) { 13021 default: break; 13022 case ISD::SETULT: 13023 // Converting this to a min would handle NaNs incorrectly, and swapping 13024 // the operands would cause it to handle comparisons between positive 13025 // and negative zero incorrectly. 13026 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13027 if (!UnsafeFPMath && 13028 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13029 break; 13030 std::swap(LHS, RHS); 13031 } 13032 Opcode = X86ISD::FMIN; 13033 break; 13034 case ISD::SETOLE: 13035 // Converting this to a min would handle comparisons between positive 13036 // and negative zero incorrectly. 13037 if (!UnsafeFPMath && 13038 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13039 break; 13040 Opcode = X86ISD::FMIN; 13041 break; 13042 case ISD::SETULE: 13043 // Converting this to a min would handle both negative zeros and NaNs 13044 // incorrectly, but we can swap the operands to fix both. 13045 std::swap(LHS, RHS); 13046 case ISD::SETOLT: 13047 case ISD::SETLT: 13048 case ISD::SETLE: 13049 Opcode = X86ISD::FMIN; 13050 break; 13051 13052 case ISD::SETOGE: 13053 // Converting this to a max would handle comparisons between positive 13054 // and negative zero incorrectly. 13055 if (!UnsafeFPMath && 13056 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 13057 break; 13058 Opcode = X86ISD::FMAX; 13059 break; 13060 case ISD::SETUGT: 13061 // Converting this to a max would handle NaNs incorrectly, and swapping 13062 // the operands would cause it to handle comparisons between positive 13063 // and negative zero incorrectly. 13064 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 13065 if (!UnsafeFPMath && 13066 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 13067 break; 13068 std::swap(LHS, RHS); 13069 } 13070 Opcode = X86ISD::FMAX; 13071 break; 13072 case ISD::SETUGE: 13073 // Converting this to a max would handle both negative zeros and NaNs 13074 // incorrectly, but we can swap the operands to fix both. 13075 std::swap(LHS, RHS); 13076 case ISD::SETOGT: 13077 case ISD::SETGT: 13078 case ISD::SETGE: 13079 Opcode = X86ISD::FMAX; 13080 break; 13081 } 13082 // Check for x CC y ? y : x -- a min/max with reversed arms. 13083 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 13084 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 13085 switch (CC) { 13086 default: break; 13087 case ISD::SETOGE: 13088 // Converting this to a min would handle comparisons between positive 13089 // and negative zero incorrectly, and swapping the operands would 13090 // cause it to handle NaNs incorrectly. 13091 if (!UnsafeFPMath && 13092 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 13093 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13094 break; 13095 std::swap(LHS, RHS); 13096 } 13097 Opcode = X86ISD::FMIN; 13098 break; 13099 case ISD::SETUGT: 13100 // Converting this to a min would handle NaNs incorrectly. 13101 if (!UnsafeFPMath && 13102 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 13103 break; 13104 Opcode = X86ISD::FMIN; 13105 break; 13106 case ISD::SETUGE: 13107 // Converting this to a min would handle both negative zeros and NaNs 13108 // incorrectly, but we can swap the operands to fix both. 13109 std::swap(LHS, RHS); 13110 case ISD::SETOGT: 13111 case ISD::SETGT: 13112 case ISD::SETGE: 13113 Opcode = X86ISD::FMIN; 13114 break; 13115 13116 case ISD::SETULT: 13117 // Converting this to a max would handle NaNs incorrectly. 13118 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13119 break; 13120 Opcode = X86ISD::FMAX; 13121 break; 13122 case ISD::SETOLE: 13123 // Converting this to a max would handle comparisons between positive 13124 // and negative zero incorrectly, and swapping the operands would 13125 // cause it to handle NaNs incorrectly. 13126 if (!UnsafeFPMath && 13127 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 13128 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 13129 break; 13130 std::swap(LHS, RHS); 13131 } 13132 Opcode = X86ISD::FMAX; 13133 break; 13134 case ISD::SETULE: 13135 // Converting this to a max would handle both negative zeros and NaNs 13136 // incorrectly, but we can swap the operands to fix both. 13137 std::swap(LHS, RHS); 13138 case ISD::SETOLT: 13139 case ISD::SETLT: 13140 case ISD::SETLE: 13141 Opcode = X86ISD::FMAX; 13142 break; 13143 } 13144 } 13145 13146 if (Opcode) 13147 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 13148 } 13149 13150 // If this is a select between two integer constants, try to do some 13151 // optimizations. 13152 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 13153 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 13154 // Don't do this for crazy integer types. 13155 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 13156 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 13157 // so that TrueC (the true value) is larger than FalseC. 13158 bool NeedsCondInvert = false; 13159 13160 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 13161 // Efficiently invertible. 13162 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 13163 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 13164 isa<ConstantSDNode>(Cond.getOperand(1))))) { 13165 NeedsCondInvert = true; 13166 std::swap(TrueC, FalseC); 13167 } 13168 13169 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 13170 if (FalseC->getAPIntValue() == 0 && 13171 TrueC->getAPIntValue().isPowerOf2()) { 13172 if (NeedsCondInvert) // Invert the condition if needed. 13173 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13174 DAG.getConstant(1, Cond.getValueType())); 13175 13176 // Zero extend the condition if needed. 13177 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 13178 13179 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13180 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 13181 DAG.getConstant(ShAmt, MVT::i8)); 13182 } 13183 13184 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 13185 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13186 if (NeedsCondInvert) // Invert the condition if needed. 13187 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13188 DAG.getConstant(1, Cond.getValueType())); 13189 13190 // Zero extend the condition if needed. 13191 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13192 FalseC->getValueType(0), Cond); 13193 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13194 SDValue(FalseC, 0)); 13195 } 13196 13197 // Optimize cases that will turn into an LEA instruction. This requires 13198 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13199 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13200 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13201 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13202 13203 bool isFastMultiplier = false; 13204 if (Diff < 10) { 13205 switch ((unsigned char)Diff) { 13206 default: break; 13207 case 1: // result = add base, cond 13208 case 2: // result = lea base( , cond*2) 13209 case 3: // result = lea base(cond, cond*2) 13210 case 4: // result = lea base( , cond*4) 13211 case 5: // result = lea base(cond, cond*4) 13212 case 8: // result = lea base( , cond*8) 13213 case 9: // result = lea base(cond, cond*8) 13214 isFastMultiplier = true; 13215 break; 13216 } 13217 } 13218 13219 if (isFastMultiplier) { 13220 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13221 if (NeedsCondInvert) // Invert the condition if needed. 13222 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 13223 DAG.getConstant(1, Cond.getValueType())); 13224 13225 // Zero extend the condition if needed. 13226 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13227 Cond); 13228 // Scale the condition by the difference. 13229 if (Diff != 1) 13230 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13231 DAG.getConstant(Diff, Cond.getValueType())); 13232 13233 // Add the base if non-zero. 13234 if (FalseC->getAPIntValue() != 0) 13235 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13236 SDValue(FalseC, 0)); 13237 return Cond; 13238 } 13239 } 13240 } 13241 } 13242 13243 return SDValue(); 13244} 13245 13246/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 13247static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 13248 TargetLowering::DAGCombinerInfo &DCI) { 13249 DebugLoc DL = N->getDebugLoc(); 13250 13251 // If the flag operand isn't dead, don't touch this CMOV. 13252 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 13253 return SDValue(); 13254 13255 SDValue FalseOp = N->getOperand(0); 13256 SDValue TrueOp = N->getOperand(1); 13257 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 13258 SDValue Cond = N->getOperand(3); 13259 if (CC == X86::COND_E || CC == X86::COND_NE) { 13260 switch (Cond.getOpcode()) { 13261 default: break; 13262 case X86ISD::BSR: 13263 case X86ISD::BSF: 13264 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 13265 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 13266 return (CC == X86::COND_E) ? FalseOp : TrueOp; 13267 } 13268 } 13269 13270 // If this is a select between two integer constants, try to do some 13271 // optimizations. Note that the operands are ordered the opposite of SELECT 13272 // operands. 13273 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 13274 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 13275 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 13276 // larger than FalseC (the false value). 13277 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 13278 CC = X86::GetOppositeBranchCondition(CC); 13279 std::swap(TrueC, FalseC); 13280 } 13281 13282 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 13283 // This is efficient for any integer data type (including i8/i16) and 13284 // shift amount. 13285 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 13286 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13287 DAG.getConstant(CC, MVT::i8), Cond); 13288 13289 // Zero extend the condition if needed. 13290 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 13291 13292 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 13293 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 13294 DAG.getConstant(ShAmt, MVT::i8)); 13295 if (N->getNumValues() == 2) // Dead flag value? 13296 return DCI.CombineTo(N, Cond, SDValue()); 13297 return Cond; 13298 } 13299 13300 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 13301 // for any integer data type, including i8/i16. 13302 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 13303 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13304 DAG.getConstant(CC, MVT::i8), Cond); 13305 13306 // Zero extend the condition if needed. 13307 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 13308 FalseC->getValueType(0), Cond); 13309 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13310 SDValue(FalseC, 0)); 13311 13312 if (N->getNumValues() == 2) // Dead flag value? 13313 return DCI.CombineTo(N, Cond, SDValue()); 13314 return Cond; 13315 } 13316 13317 // Optimize cases that will turn into an LEA instruction. This requires 13318 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 13319 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 13320 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 13321 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 13322 13323 bool isFastMultiplier = false; 13324 if (Diff < 10) { 13325 switch ((unsigned char)Diff) { 13326 default: break; 13327 case 1: // result = add base, cond 13328 case 2: // result = lea base( , cond*2) 13329 case 3: // result = lea base(cond, cond*2) 13330 case 4: // result = lea base( , cond*4) 13331 case 5: // result = lea base(cond, cond*4) 13332 case 8: // result = lea base( , cond*8) 13333 case 9: // result = lea base(cond, cond*8) 13334 isFastMultiplier = true; 13335 break; 13336 } 13337 } 13338 13339 if (isFastMultiplier) { 13340 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 13341 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 13342 DAG.getConstant(CC, MVT::i8), Cond); 13343 // Zero extend the condition if needed. 13344 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 13345 Cond); 13346 // Scale the condition by the difference. 13347 if (Diff != 1) 13348 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 13349 DAG.getConstant(Diff, Cond.getValueType())); 13350 13351 // Add the base if non-zero. 13352 if (FalseC->getAPIntValue() != 0) 13353 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 13354 SDValue(FalseC, 0)); 13355 if (N->getNumValues() == 2) // Dead flag value? 13356 return DCI.CombineTo(N, Cond, SDValue()); 13357 return Cond; 13358 } 13359 } 13360 } 13361 } 13362 return SDValue(); 13363} 13364 13365 13366/// PerformMulCombine - Optimize a single multiply with constant into two 13367/// in order to implement it with two cheaper instructions, e.g. 13368/// LEA + SHL, LEA + LEA. 13369static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 13370 TargetLowering::DAGCombinerInfo &DCI) { 13371 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 13372 return SDValue(); 13373 13374 EVT VT = N->getValueType(0); 13375 if (VT != MVT::i64) 13376 return SDValue(); 13377 13378 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13379 if (!C) 13380 return SDValue(); 13381 uint64_t MulAmt = C->getZExtValue(); 13382 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 13383 return SDValue(); 13384 13385 uint64_t MulAmt1 = 0; 13386 uint64_t MulAmt2 = 0; 13387 if ((MulAmt % 9) == 0) { 13388 MulAmt1 = 9; 13389 MulAmt2 = MulAmt / 9; 13390 } else if ((MulAmt % 5) == 0) { 13391 MulAmt1 = 5; 13392 MulAmt2 = MulAmt / 5; 13393 } else if ((MulAmt % 3) == 0) { 13394 MulAmt1 = 3; 13395 MulAmt2 = MulAmt / 3; 13396 } 13397 if (MulAmt2 && 13398 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 13399 DebugLoc DL = N->getDebugLoc(); 13400 13401 if (isPowerOf2_64(MulAmt2) && 13402 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 13403 // If second multiplifer is pow2, issue it first. We want the multiply by 13404 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 13405 // is an add. 13406 std::swap(MulAmt1, MulAmt2); 13407 13408 SDValue NewMul; 13409 if (isPowerOf2_64(MulAmt1)) 13410 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 13411 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 13412 else 13413 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 13414 DAG.getConstant(MulAmt1, VT)); 13415 13416 if (isPowerOf2_64(MulAmt2)) 13417 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 13418 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 13419 else 13420 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 13421 DAG.getConstant(MulAmt2, VT)); 13422 13423 // Do not add new nodes to DAG combiner worklist. 13424 DCI.CombineTo(N, NewMul, false); 13425 } 13426 return SDValue(); 13427} 13428 13429static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 13430 SDValue N0 = N->getOperand(0); 13431 SDValue N1 = N->getOperand(1); 13432 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 13433 EVT VT = N0.getValueType(); 13434 13435 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 13436 // since the result of setcc_c is all zero's or all ones. 13437 if (VT.isInteger() && !VT.isVector() && 13438 N1C && N0.getOpcode() == ISD::AND && 13439 N0.getOperand(1).getOpcode() == ISD::Constant) { 13440 SDValue N00 = N0.getOperand(0); 13441 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 13442 ((N00.getOpcode() == ISD::ANY_EXTEND || 13443 N00.getOpcode() == ISD::ZERO_EXTEND) && 13444 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 13445 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 13446 APInt ShAmt = N1C->getAPIntValue(); 13447 Mask = Mask.shl(ShAmt); 13448 if (Mask != 0) 13449 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 13450 N00, DAG.getConstant(Mask, VT)); 13451 } 13452 } 13453 13454 13455 // Hardware support for vector shifts is sparse which makes us scalarize the 13456 // vector operations in many cases. Also, on sandybridge ADD is faster than 13457 // shl. 13458 // (shl V, 1) -> add V,V 13459 if (isSplatVector(N1.getNode())) { 13460 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 13461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 13462 // We shift all of the values by one. In many cases we do not have 13463 // hardware support for this operation. This is better expressed as an ADD 13464 // of two values. 13465 if (N1C && (1 == N1C->getZExtValue())) { 13466 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0); 13467 } 13468 } 13469 13470 return SDValue(); 13471} 13472 13473/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 13474/// when possible. 13475static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 13476 const X86Subtarget *Subtarget) { 13477 EVT VT = N->getValueType(0); 13478 if (N->getOpcode() == ISD::SHL) { 13479 SDValue V = PerformSHLCombine(N, DAG); 13480 if (V.getNode()) return V; 13481 } 13482 13483 // On X86 with SSE2 support, we can transform this to a vector shift if 13484 // all elements are shifted by the same amount. We can't do this in legalize 13485 // because the a constant vector is typically transformed to a constant pool 13486 // so we have no knowledge of the shift amount. 13487 if (!Subtarget->hasXMMInt()) 13488 return SDValue(); 13489 13490 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 && 13491 (!Subtarget->hasAVX2() || 13492 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16))) 13493 return SDValue(); 13494 13495 SDValue ShAmtOp = N->getOperand(1); 13496 EVT EltVT = VT.getVectorElementType(); 13497 DebugLoc DL = N->getDebugLoc(); 13498 SDValue BaseShAmt = SDValue(); 13499 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 13500 unsigned NumElts = VT.getVectorNumElements(); 13501 unsigned i = 0; 13502 for (; i != NumElts; ++i) { 13503 SDValue Arg = ShAmtOp.getOperand(i); 13504 if (Arg.getOpcode() == ISD::UNDEF) continue; 13505 BaseShAmt = Arg; 13506 break; 13507 } 13508 for (; i != NumElts; ++i) { 13509 SDValue Arg = ShAmtOp.getOperand(i); 13510 if (Arg.getOpcode() == ISD::UNDEF) continue; 13511 if (Arg != BaseShAmt) { 13512 return SDValue(); 13513 } 13514 } 13515 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 13516 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 13517 SDValue InVec = ShAmtOp.getOperand(0); 13518 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 13519 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 13520 unsigned i = 0; 13521 for (; i != NumElts; ++i) { 13522 SDValue Arg = InVec.getOperand(i); 13523 if (Arg.getOpcode() == ISD::UNDEF) continue; 13524 BaseShAmt = Arg; 13525 break; 13526 } 13527 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 13528 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 13529 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 13530 if (C->getZExtValue() == SplatIdx) 13531 BaseShAmt = InVec.getOperand(1); 13532 } 13533 } 13534 if (BaseShAmt.getNode() == 0) 13535 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 13536 DAG.getIntPtrConstant(0)); 13537 } else 13538 return SDValue(); 13539 13540 // The shift amount is an i32. 13541 if (EltVT.bitsGT(MVT::i32)) 13542 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 13543 else if (EltVT.bitsLT(MVT::i32)) 13544 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 13545 13546 // The shift amount is identical so we can do a vector shift. 13547 SDValue ValOp = N->getOperand(0); 13548 switch (N->getOpcode()) { 13549 default: 13550 llvm_unreachable("Unknown shift opcode!"); 13551 break; 13552 case ISD::SHL: 13553 if (VT == MVT::v2i64) 13554 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13555 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32), 13556 ValOp, BaseShAmt); 13557 if (VT == MVT::v4i32) 13558 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13559 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32), 13560 ValOp, BaseShAmt); 13561 if (VT == MVT::v8i16) 13562 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13563 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), 13564 ValOp, BaseShAmt); 13565 if (VT == MVT::v4i64) 13566 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13567 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32), 13568 ValOp, BaseShAmt); 13569 if (VT == MVT::v8i32) 13570 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13571 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32), 13572 ValOp, BaseShAmt); 13573 if (VT == MVT::v16i16) 13574 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13575 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32), 13576 ValOp, BaseShAmt); 13577 break; 13578 case ISD::SRA: 13579 if (VT == MVT::v4i32) 13580 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13581 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32), 13582 ValOp, BaseShAmt); 13583 if (VT == MVT::v8i16) 13584 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13585 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32), 13586 ValOp, BaseShAmt); 13587 if (VT == MVT::v8i32) 13588 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13589 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32), 13590 ValOp, BaseShAmt); 13591 if (VT == MVT::v16i16) 13592 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13593 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32), 13594 ValOp, BaseShAmt); 13595 break; 13596 case ISD::SRL: 13597 if (VT == MVT::v2i64) 13598 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13599 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32), 13600 ValOp, BaseShAmt); 13601 if (VT == MVT::v4i32) 13602 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13603 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32), 13604 ValOp, BaseShAmt); 13605 if (VT == MVT::v8i16) 13606 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13607 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32), 13608 ValOp, BaseShAmt); 13609 if (VT == MVT::v4i64) 13610 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13611 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32), 13612 ValOp, BaseShAmt); 13613 if (VT == MVT::v8i32) 13614 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13615 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32), 13616 ValOp, BaseShAmt); 13617 if (VT == MVT::v16i16) 13618 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 13619 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32), 13620 ValOp, BaseShAmt); 13621 break; 13622 } 13623 return SDValue(); 13624} 13625 13626 13627// CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 13628// where both setccs reference the same FP CMP, and rewrite for CMPEQSS 13629// and friends. Likewise for OR -> CMPNEQSS. 13630static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 13631 TargetLowering::DAGCombinerInfo &DCI, 13632 const X86Subtarget *Subtarget) { 13633 unsigned opcode; 13634 13635 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 13636 // we're requiring SSE2 for both. 13637 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 13638 SDValue N0 = N->getOperand(0); 13639 SDValue N1 = N->getOperand(1); 13640 SDValue CMP0 = N0->getOperand(1); 13641 SDValue CMP1 = N1->getOperand(1); 13642 DebugLoc DL = N->getDebugLoc(); 13643 13644 // The SETCCs should both refer to the same CMP. 13645 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 13646 return SDValue(); 13647 13648 SDValue CMP00 = CMP0->getOperand(0); 13649 SDValue CMP01 = CMP0->getOperand(1); 13650 EVT VT = CMP00.getValueType(); 13651 13652 if (VT == MVT::f32 || VT == MVT::f64) { 13653 bool ExpectingFlags = false; 13654 // Check for any users that want flags: 13655 for (SDNode::use_iterator UI = N->use_begin(), 13656 UE = N->use_end(); 13657 !ExpectingFlags && UI != UE; ++UI) 13658 switch (UI->getOpcode()) { 13659 default: 13660 case ISD::BR_CC: 13661 case ISD::BRCOND: 13662 case ISD::SELECT: 13663 ExpectingFlags = true; 13664 break; 13665 case ISD::CopyToReg: 13666 case ISD::SIGN_EXTEND: 13667 case ISD::ZERO_EXTEND: 13668 case ISD::ANY_EXTEND: 13669 break; 13670 } 13671 13672 if (!ExpectingFlags) { 13673 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 13674 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 13675 13676 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 13677 X86::CondCode tmp = cc0; 13678 cc0 = cc1; 13679 cc1 = tmp; 13680 } 13681 13682 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 13683 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 13684 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 13685 X86ISD::NodeType NTOperator = is64BitFP ? 13686 X86ISD::FSETCCsd : X86ISD::FSETCCss; 13687 // FIXME: need symbolic constants for these magic numbers. 13688 // See X86ATTInstPrinter.cpp:printSSECC(). 13689 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 13690 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 13691 DAG.getConstant(x86cc, MVT::i8)); 13692 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 13693 OnesOrZeroesF); 13694 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 13695 DAG.getConstant(1, MVT::i32)); 13696 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 13697 return OneBitOfTruth; 13698 } 13699 } 13700 } 13701 } 13702 return SDValue(); 13703} 13704 13705/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 13706/// so it can be folded inside ANDNP. 13707static bool CanFoldXORWithAllOnes(const SDNode *N) { 13708 EVT VT = N->getValueType(0); 13709 13710 // Match direct AllOnes for 128 and 256-bit vectors 13711 if (ISD::isBuildVectorAllOnes(N)) 13712 return true; 13713 13714 // Look through a bit convert. 13715 if (N->getOpcode() == ISD::BITCAST) 13716 N = N->getOperand(0).getNode(); 13717 13718 // Sometimes the operand may come from a insert_subvector building a 256-bit 13719 // allones vector 13720 if (VT.getSizeInBits() == 256 && 13721 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 13722 SDValue V1 = N->getOperand(0); 13723 SDValue V2 = N->getOperand(1); 13724 13725 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 13726 V1.getOperand(0).getOpcode() == ISD::UNDEF && 13727 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 13728 ISD::isBuildVectorAllOnes(V2.getNode())) 13729 return true; 13730 } 13731 13732 return false; 13733} 13734 13735static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 13736 TargetLowering::DAGCombinerInfo &DCI, 13737 const X86Subtarget *Subtarget) { 13738 if (DCI.isBeforeLegalizeOps()) 13739 return SDValue(); 13740 13741 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13742 if (R.getNode()) 13743 return R; 13744 13745 EVT VT = N->getValueType(0); 13746 13747 // Create ANDN, BLSI, and BLSR instructions 13748 // BLSI is X & (-X) 13749 // BLSR is X & (X-1) 13750 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 13751 SDValue N0 = N->getOperand(0); 13752 SDValue N1 = N->getOperand(1); 13753 DebugLoc DL = N->getDebugLoc(); 13754 13755 // Check LHS for not 13756 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1))) 13757 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1); 13758 // Check RHS for not 13759 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1))) 13760 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0); 13761 13762 // Check LHS for neg 13763 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 13764 isZero(N0.getOperand(0))) 13765 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 13766 13767 // Check RHS for neg 13768 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 13769 isZero(N1.getOperand(0))) 13770 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 13771 13772 // Check LHS for X-1 13773 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 13774 isAllOnes(N0.getOperand(1))) 13775 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 13776 13777 // Check RHS for X-1 13778 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 13779 isAllOnes(N1.getOperand(1))) 13780 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 13781 13782 return SDValue(); 13783 } 13784 13785 // Want to form ANDNP nodes: 13786 // 1) In the hopes of then easily combining them with OR and AND nodes 13787 // to form PBLEND/PSIGN. 13788 // 2) To match ANDN packed intrinsics 13789 if (VT != MVT::v2i64 && VT != MVT::v4i64) 13790 return SDValue(); 13791 13792 SDValue N0 = N->getOperand(0); 13793 SDValue N1 = N->getOperand(1); 13794 DebugLoc DL = N->getDebugLoc(); 13795 13796 // Check LHS for vnot 13797 if (N0.getOpcode() == ISD::XOR && 13798 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 13799 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 13800 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 13801 13802 // Check RHS for vnot 13803 if (N1.getOpcode() == ISD::XOR && 13804 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 13805 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 13806 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 13807 13808 return SDValue(); 13809} 13810 13811static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 13812 TargetLowering::DAGCombinerInfo &DCI, 13813 const X86Subtarget *Subtarget) { 13814 if (DCI.isBeforeLegalizeOps()) 13815 return SDValue(); 13816 13817 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 13818 if (R.getNode()) 13819 return R; 13820 13821 EVT VT = N->getValueType(0); 13822 13823 SDValue N0 = N->getOperand(0); 13824 SDValue N1 = N->getOperand(1); 13825 13826 // look for psign/blend 13827 if (VT == MVT::v2i64 || VT == MVT::v4i64) { 13828 if (!Subtarget->hasSSSE3orAVX() || 13829 (VT == MVT::v4i64 && !Subtarget->hasAVX2())) 13830 return SDValue(); 13831 13832 // Canonicalize pandn to RHS 13833 if (N0.getOpcode() == X86ISD::ANDNP) 13834 std::swap(N0, N1); 13835 // or (and (m, x), (pandn m, y)) 13836 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 13837 SDValue Mask = N1.getOperand(0); 13838 SDValue X = N1.getOperand(1); 13839 SDValue Y; 13840 if (N0.getOperand(0) == Mask) 13841 Y = N0.getOperand(1); 13842 if (N0.getOperand(1) == Mask) 13843 Y = N0.getOperand(0); 13844 13845 // Check to see if the mask appeared in both the AND and ANDNP and 13846 if (!Y.getNode()) 13847 return SDValue(); 13848 13849 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 13850 if (Mask.getOpcode() != ISD::BITCAST || 13851 X.getOpcode() != ISD::BITCAST || 13852 Y.getOpcode() != ISD::BITCAST) 13853 return SDValue(); 13854 13855 // Look through mask bitcast. 13856 Mask = Mask.getOperand(0); 13857 EVT MaskVT = Mask.getValueType(); 13858 13859 // Validate that the Mask operand is a vector sra node. The sra node 13860 // will be an intrinsic. 13861 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN) 13862 return SDValue(); 13863 13864 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 13865 // there is no psrai.b 13866 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) { 13867 case Intrinsic::x86_sse2_psrai_w: 13868 case Intrinsic::x86_sse2_psrai_d: 13869 case Intrinsic::x86_avx2_psrai_w: 13870 case Intrinsic::x86_avx2_psrai_d: 13871 break; 13872 default: return SDValue(); 13873 } 13874 13875 // Check that the SRA is all signbits. 13876 SDValue SraC = Mask.getOperand(2); 13877 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 13878 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 13879 if ((SraAmt + 1) != EltBits) 13880 return SDValue(); 13881 13882 DebugLoc DL = N->getDebugLoc(); 13883 13884 // Now we know we at least have a plendvb with the mask val. See if 13885 // we can form a psignb/w/d. 13886 // psign = x.type == y.type == mask.type && y = sub(0, x); 13887 X = X.getOperand(0); 13888 Y = Y.getOperand(0); 13889 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 13890 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 13891 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() && 13892 (EltBits == 8 || EltBits == 16 || EltBits == 32)) { 13893 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, 13894 Mask.getOperand(1)); 13895 return DAG.getNode(ISD::BITCAST, DL, VT, Sign); 13896 } 13897 // PBLENDVB only available on SSE 4.1 13898 if (!Subtarget->hasSSE41orAVX()) 13899 return SDValue(); 13900 13901 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8; 13902 13903 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X); 13904 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y); 13905 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask); 13906 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); 13907 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 13908 } 13909 } 13910 13911 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 13912 return SDValue(); 13913 13914 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 13915 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 13916 std::swap(N0, N1); 13917 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 13918 return SDValue(); 13919 if (!N0.hasOneUse() || !N1.hasOneUse()) 13920 return SDValue(); 13921 13922 SDValue ShAmt0 = N0.getOperand(1); 13923 if (ShAmt0.getValueType() != MVT::i8) 13924 return SDValue(); 13925 SDValue ShAmt1 = N1.getOperand(1); 13926 if (ShAmt1.getValueType() != MVT::i8) 13927 return SDValue(); 13928 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 13929 ShAmt0 = ShAmt0.getOperand(0); 13930 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 13931 ShAmt1 = ShAmt1.getOperand(0); 13932 13933 DebugLoc DL = N->getDebugLoc(); 13934 unsigned Opc = X86ISD::SHLD; 13935 SDValue Op0 = N0.getOperand(0); 13936 SDValue Op1 = N1.getOperand(0); 13937 if (ShAmt0.getOpcode() == ISD::SUB) { 13938 Opc = X86ISD::SHRD; 13939 std::swap(Op0, Op1); 13940 std::swap(ShAmt0, ShAmt1); 13941 } 13942 13943 unsigned Bits = VT.getSizeInBits(); 13944 if (ShAmt1.getOpcode() == ISD::SUB) { 13945 SDValue Sum = ShAmt1.getOperand(0); 13946 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 13947 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 13948 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 13949 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 13950 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 13951 return DAG.getNode(Opc, DL, VT, 13952 Op0, Op1, 13953 DAG.getNode(ISD::TRUNCATE, DL, 13954 MVT::i8, ShAmt0)); 13955 } 13956 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 13957 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 13958 if (ShAmt0C && 13959 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 13960 return DAG.getNode(Opc, DL, VT, 13961 N0.getOperand(0), N1.getOperand(0), 13962 DAG.getNode(ISD::TRUNCATE, DL, 13963 MVT::i8, ShAmt0)); 13964 } 13965 13966 return SDValue(); 13967} 13968 13969static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 13970 TargetLowering::DAGCombinerInfo &DCI, 13971 const X86Subtarget *Subtarget) { 13972 if (DCI.isBeforeLegalizeOps()) 13973 return SDValue(); 13974 13975 EVT VT = N->getValueType(0); 13976 13977 if (VT != MVT::i32 && VT != MVT::i64) 13978 return SDValue(); 13979 13980 // Create BLSMSK instructions by finding X ^ (X-1) 13981 SDValue N0 = N->getOperand(0); 13982 SDValue N1 = N->getOperand(1); 13983 DebugLoc DL = N->getDebugLoc(); 13984 13985 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 13986 isAllOnes(N0.getOperand(1))) 13987 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 13988 13989 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 13990 isAllOnes(N1.getOperand(1))) 13991 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 13992 13993 return SDValue(); 13994} 13995 13996/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 13997static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 13998 const X86Subtarget *Subtarget) { 13999 LoadSDNode *Ld = cast<LoadSDNode>(N); 14000 EVT RegVT = Ld->getValueType(0); 14001 EVT MemVT = Ld->getMemoryVT(); 14002 DebugLoc dl = Ld->getDebugLoc(); 14003 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14004 14005 ISD::LoadExtType Ext = Ld->getExtensionType(); 14006 14007 // If this is a vector EXT Load then attempt to optimize it using a 14008 // shuffle. We need SSE4 for the shuffles. 14009 // TODO: It is possible to support ZExt by zeroing the undef values 14010 // during the shuffle phase or after the shuffle. 14011 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) { 14012 assert(MemVT != RegVT && "Cannot extend to the same type"); 14013 assert(MemVT.isVector() && "Must load a vector from memory"); 14014 14015 unsigned NumElems = RegVT.getVectorNumElements(); 14016 unsigned RegSz = RegVT.getSizeInBits(); 14017 unsigned MemSz = MemVT.getSizeInBits(); 14018 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 14019 // All sizes must be a power of two 14020 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue(); 14021 14022 // Attempt to load the original value using a single load op. 14023 // Find a scalar type which is equal to the loaded word size. 14024 MVT SclrLoadTy = MVT::i8; 14025 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14026 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14027 MVT Tp = (MVT::SimpleValueType)tp; 14028 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) { 14029 SclrLoadTy = Tp; 14030 break; 14031 } 14032 } 14033 14034 // Proceed if a load word is found. 14035 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue(); 14036 14037 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 14038 RegSz/SclrLoadTy.getSizeInBits()); 14039 14040 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 14041 RegSz/MemVT.getScalarType().getSizeInBits()); 14042 // Can't shuffle using an illegal type. 14043 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 14044 14045 // Perform a single load. 14046 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 14047 Ld->getBasePtr(), 14048 Ld->getPointerInfo(), Ld->isVolatile(), 14049 Ld->isNonTemporal(), Ld->isInvariant(), 14050 Ld->getAlignment()); 14051 14052 // Insert the word loaded into a vector. 14053 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 14054 LoadUnitVecVT, ScalarLoad); 14055 14056 // Bitcast the loaded value to a vector of the original element type, in 14057 // the size of the target vector type. 14058 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector); 14059 unsigned SizeRatio = RegSz/MemSz; 14060 14061 // Redistribute the loaded elements into the different locations. 14062 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14063 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i; 14064 14065 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 14066 DAG.getUNDEF(SlicedVec.getValueType()), 14067 ShuffleVec.data()); 14068 14069 // Bitcast to the requested type. 14070 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 14071 // Replace the original load with the new sequence 14072 // and return the new chain. 14073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff); 14074 return SDValue(ScalarLoad.getNode(), 1); 14075 } 14076 14077 return SDValue(); 14078} 14079 14080/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 14081static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 14082 const X86Subtarget *Subtarget) { 14083 StoreSDNode *St = cast<StoreSDNode>(N); 14084 EVT VT = St->getValue().getValueType(); 14085 EVT StVT = St->getMemoryVT(); 14086 DebugLoc dl = St->getDebugLoc(); 14087 SDValue StoredVal = St->getOperand(1); 14088 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14089 14090 // If we are saving a concatination of two XMM registers, perform two stores. 14091 // This is better in Sandy Bridge cause one 256-bit mem op is done via two 14092 // 128-bit ones. If in the future the cost becomes only one memory access the 14093 // first version would be better. 14094 if (VT.getSizeInBits() == 256 && 14095 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS && 14096 StoredVal.getNumOperands() == 2) { 14097 14098 SDValue Value0 = StoredVal.getOperand(0); 14099 SDValue Value1 = StoredVal.getOperand(1); 14100 14101 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 14102 SDValue Ptr0 = St->getBasePtr(); 14103 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 14104 14105 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 14106 St->getPointerInfo(), St->isVolatile(), 14107 St->isNonTemporal(), St->getAlignment()); 14108 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 14109 St->getPointerInfo(), St->isVolatile(), 14110 St->isNonTemporal(), St->getAlignment()); 14111 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 14112 } 14113 14114 // Optimize trunc store (of multiple scalars) to shuffle and store. 14115 // First, pack all of the elements in one place. Next, store to memory 14116 // in fewer chunks. 14117 if (St->isTruncatingStore() && VT.isVector()) { 14118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14119 unsigned NumElems = VT.getVectorNumElements(); 14120 assert(StVT != VT && "Cannot truncate to the same type"); 14121 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 14122 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 14123 14124 // From, To sizes and ElemCount must be pow of two 14125 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 14126 // We are going to use the original vector elt for storing. 14127 // Accumulated smaller vector elements must be a multiple of the store size. 14128 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 14129 14130 unsigned SizeRatio = FromSz / ToSz; 14131 14132 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 14133 14134 // Create a type on which we perform the shuffle 14135 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 14136 StVT.getScalarType(), NumElems*SizeRatio); 14137 14138 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 14139 14140 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 14141 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 14142 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio; 14143 14144 // Can't shuffle using an illegal type 14145 if (!TLI.isTypeLegal(WideVecVT)) return SDValue(); 14146 14147 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 14148 DAG.getUNDEF(WideVec.getValueType()), 14149 ShuffleVec.data()); 14150 // At this point all of the data is stored at the bottom of the 14151 // register. We now need to save it to mem. 14152 14153 // Find the largest store unit 14154 MVT StoreType = MVT::i8; 14155 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 14156 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 14157 MVT Tp = (MVT::SimpleValueType)tp; 14158 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz) 14159 StoreType = Tp; 14160 } 14161 14162 // Bitcast the original vector into a vector of store-size units 14163 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 14164 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits()); 14165 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 14166 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 14167 SmallVector<SDValue, 8> Chains; 14168 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 14169 TLI.getPointerTy()); 14170 SDValue Ptr = St->getBasePtr(); 14171 14172 // Perform one or more big stores into memory. 14173 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) { 14174 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 14175 StoreType, ShuffWide, 14176 DAG.getIntPtrConstant(i)); 14177 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 14178 St->getPointerInfo(), St->isVolatile(), 14179 St->isNonTemporal(), St->getAlignment()); 14180 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14181 Chains.push_back(Ch); 14182 } 14183 14184 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 14185 Chains.size()); 14186 } 14187 14188 14189 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 14190 // the FP state in cases where an emms may be missing. 14191 // A preferable solution to the general problem is to figure out the right 14192 // places to insert EMMS. This qualifies as a quick hack. 14193 14194 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 14195 if (VT.getSizeInBits() != 64) 14196 return SDValue(); 14197 14198 const Function *F = DAG.getMachineFunction().getFunction(); 14199 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat); 14200 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 14201 && Subtarget->hasXMMInt(); 14202 if ((VT.isVector() || 14203 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 14204 isa<LoadSDNode>(St->getValue()) && 14205 !cast<LoadSDNode>(St->getValue())->isVolatile() && 14206 St->getChain().hasOneUse() && !St->isVolatile()) { 14207 SDNode* LdVal = St->getValue().getNode(); 14208 LoadSDNode *Ld = 0; 14209 int TokenFactorIndex = -1; 14210 SmallVector<SDValue, 8> Ops; 14211 SDNode* ChainVal = St->getChain().getNode(); 14212 // Must be a store of a load. We currently handle two cases: the load 14213 // is a direct child, and it's under an intervening TokenFactor. It is 14214 // possible to dig deeper under nested TokenFactors. 14215 if (ChainVal == LdVal) 14216 Ld = cast<LoadSDNode>(St->getChain()); 14217 else if (St->getValue().hasOneUse() && 14218 ChainVal->getOpcode() == ISD::TokenFactor) { 14219 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) { 14220 if (ChainVal->getOperand(i).getNode() == LdVal) { 14221 TokenFactorIndex = i; 14222 Ld = cast<LoadSDNode>(St->getValue()); 14223 } else 14224 Ops.push_back(ChainVal->getOperand(i)); 14225 } 14226 } 14227 14228 if (!Ld || !ISD::isNormalLoad(Ld)) 14229 return SDValue(); 14230 14231 // If this is not the MMX case, i.e. we are just turning i64 load/store 14232 // into f64 load/store, avoid the transformation if there are multiple 14233 // uses of the loaded value. 14234 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 14235 return SDValue(); 14236 14237 DebugLoc LdDL = Ld->getDebugLoc(); 14238 DebugLoc StDL = N->getDebugLoc(); 14239 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 14240 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 14241 // pair instead. 14242 if (Subtarget->is64Bit() || F64IsLegal) { 14243 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 14244 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 14245 Ld->getPointerInfo(), Ld->isVolatile(), 14246 Ld->isNonTemporal(), Ld->isInvariant(), 14247 Ld->getAlignment()); 14248 SDValue NewChain = NewLd.getValue(1); 14249 if (TokenFactorIndex != -1) { 14250 Ops.push_back(NewChain); 14251 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14252 Ops.size()); 14253 } 14254 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 14255 St->getPointerInfo(), 14256 St->isVolatile(), St->isNonTemporal(), 14257 St->getAlignment()); 14258 } 14259 14260 // Otherwise, lower to two pairs of 32-bit loads / stores. 14261 SDValue LoAddr = Ld->getBasePtr(); 14262 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 14263 DAG.getConstant(4, MVT::i32)); 14264 14265 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 14266 Ld->getPointerInfo(), 14267 Ld->isVolatile(), Ld->isNonTemporal(), 14268 Ld->isInvariant(), Ld->getAlignment()); 14269 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 14270 Ld->getPointerInfo().getWithOffset(4), 14271 Ld->isVolatile(), Ld->isNonTemporal(), 14272 Ld->isInvariant(), 14273 MinAlign(Ld->getAlignment(), 4)); 14274 14275 SDValue NewChain = LoLd.getValue(1); 14276 if (TokenFactorIndex != -1) { 14277 Ops.push_back(LoLd); 14278 Ops.push_back(HiLd); 14279 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 14280 Ops.size()); 14281 } 14282 14283 LoAddr = St->getBasePtr(); 14284 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 14285 DAG.getConstant(4, MVT::i32)); 14286 14287 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 14288 St->getPointerInfo(), 14289 St->isVolatile(), St->isNonTemporal(), 14290 St->getAlignment()); 14291 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 14292 St->getPointerInfo().getWithOffset(4), 14293 St->isVolatile(), 14294 St->isNonTemporal(), 14295 MinAlign(St->getAlignment(), 4)); 14296 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 14297 } 14298 return SDValue(); 14299} 14300 14301/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 14302/// and return the operands for the horizontal operation in LHS and RHS. A 14303/// horizontal operation performs the binary operation on successive elements 14304/// of its first operand, then on successive elements of its second operand, 14305/// returning the resulting values in a vector. For example, if 14306/// A = < float a0, float a1, float a2, float a3 > 14307/// and 14308/// B = < float b0, float b1, float b2, float b3 > 14309/// then the result of doing a horizontal operation on A and B is 14310/// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 14311/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 14312/// A horizontal-op B, for some already available A and B, and if so then LHS is 14313/// set to A, RHS to B, and the routine returns 'true'. 14314/// Note that the binary operation should have the property that if one of the 14315/// operands is UNDEF then the result is UNDEF. 14316static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) { 14317 // Look for the following pattern: if 14318 // A = < float a0, float a1, float a2, float a3 > 14319 // B = < float b0, float b1, float b2, float b3 > 14320 // and 14321 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 14322 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 14323 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 14324 // which is A horizontal-op B. 14325 14326 // At least one of the operands should be a vector shuffle. 14327 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 14328 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 14329 return false; 14330 14331 EVT VT = LHS.getValueType(); 14332 unsigned NumElts = VT.getVectorNumElements(); 14333 unsigned NumLanes = VT.getSizeInBits()/128; 14334 unsigned NumLaneElts = NumElts / NumLanes; 14335 14336 // View LHS in the form 14337 // LHS = VECTOR_SHUFFLE A, B, LMask 14338 // If LHS is not a shuffle then pretend it is the shuffle 14339 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 14340 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 14341 // type VT. 14342 SDValue A, B; 14343 SmallVector<int, 16> LMask(NumElts); 14344 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 14345 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 14346 A = LHS.getOperand(0); 14347 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 14348 B = LHS.getOperand(1); 14349 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask); 14350 } else { 14351 if (LHS.getOpcode() != ISD::UNDEF) 14352 A = LHS; 14353 for (unsigned i = 0; i != NumElts; ++i) 14354 LMask[i] = i; 14355 } 14356 14357 // Likewise, view RHS in the form 14358 // RHS = VECTOR_SHUFFLE C, D, RMask 14359 SDValue C, D; 14360 SmallVector<int, 16> RMask(NumElts); 14361 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 14362 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 14363 C = RHS.getOperand(0); 14364 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 14365 D = RHS.getOperand(1); 14366 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask); 14367 } else { 14368 if (RHS.getOpcode() != ISD::UNDEF) 14369 C = RHS; 14370 for (unsigned i = 0; i != NumElts; ++i) 14371 RMask[i] = i; 14372 } 14373 14374 // Check that the shuffles are both shuffling the same vectors. 14375 if (!(A == C && B == D) && !(A == D && B == C)) 14376 return false; 14377 14378 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 14379 if (!A.getNode() && !B.getNode()) 14380 return false; 14381 14382 // If A and B occur in reverse order in RHS, then "swap" them (which means 14383 // rewriting the mask). 14384 if (A != C) 14385 for (unsigned i = 0; i != NumElts; ++i) { 14386 unsigned Idx = RMask[i]; 14387 if (Idx < NumElts) 14388 RMask[i] += NumElts; 14389 else if (Idx < 2*NumElts) 14390 RMask[i] -= NumElts; 14391 } 14392 14393 // At this point LHS and RHS are equivalent to 14394 // LHS = VECTOR_SHUFFLE A, B, LMask 14395 // RHS = VECTOR_SHUFFLE A, B, RMask 14396 // Check that the masks correspond to performing a horizontal operation. 14397 for (unsigned l = 0; l != NumLanes; ++l) { 14398 unsigned LaneStart = l*NumLaneElts; 14399 for (unsigned i = 0; i != NumLaneElts/2; ++i) { 14400 unsigned LIdx = LMask[i+LaneStart]; 14401 unsigned RIdx = RMask[i+LaneStart]; 14402 14403 // Ignore any UNDEF components. 14404 if (LIdx >= 2*NumElts || RIdx >= 2*NumElts || 14405 (!A.getNode() && (LIdx < NumElts || RIdx < NumElts)) || 14406 (!B.getNode() && (LIdx >= NumElts || RIdx >= NumElts))) 14407 continue; 14408 14409 // Check that successive elements are being operated on. If not, this is 14410 // not a horizontal operation. 14411 if (!(LIdx == 2*i + LaneStart && RIdx == 2*i + LaneStart + 1) && 14412 !(isCommutative && LIdx == 2*i + LaneStart + 1 && RIdx == 2*i + LaneStart)) 14413 return false; 14414 } 14415 for (unsigned i = 0; i != NumLaneElts/2; ++i) { 14416 unsigned LIdx = LMask[i+(NumLaneElts/2)+LaneStart]; 14417 unsigned RIdx = RMask[i+(NumLaneElts/2)+LaneStart]; 14418 14419 // Ignore any UNDEF components. 14420 if (LIdx >= 2*NumElts || RIdx >= 2*NumElts || 14421 (!A.getNode() && (LIdx < NumElts || RIdx < NumElts)) || 14422 (!B.getNode() && (LIdx >= NumElts || RIdx >= NumElts))) 14423 continue; 14424 14425 // Check that successive elements are being operated on. If not, this is 14426 // not a horizontal operation. 14427 if (!(LIdx == 2*i + LaneStart + NumElts && RIdx == 2*i + LaneStart + NumElts + 1) && 14428 !(isCommutative && LIdx == 2*i + LaneStart + NumElts + 1 && RIdx == 2*i + LaneStart + NumElts)) 14429 return false; 14430 } 14431 } 14432 14433 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 14434 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 14435 return true; 14436} 14437 14438/// PerformFADDCombine - Do target-specific dag combines on floating point adds. 14439static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 14440 const X86Subtarget *Subtarget) { 14441 EVT VT = N->getValueType(0); 14442 SDValue LHS = N->getOperand(0); 14443 SDValue RHS = N->getOperand(1); 14444 14445 // Try to synthesize horizontal adds from adds of shuffles. 14446 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 14447 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 14448 isHorizontalBinOp(LHS, RHS, true)) 14449 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS); 14450 return SDValue(); 14451} 14452 14453/// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 14454static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 14455 const X86Subtarget *Subtarget) { 14456 EVT VT = N->getValueType(0); 14457 SDValue LHS = N->getOperand(0); 14458 SDValue RHS = N->getOperand(1); 14459 14460 // Try to synthesize horizontal subs from subs of shuffles. 14461 if (((Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 14462 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 14463 isHorizontalBinOp(LHS, RHS, false)) 14464 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS); 14465 return SDValue(); 14466} 14467 14468/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 14469/// X86ISD::FXOR nodes. 14470static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 14471 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 14472 // F[X]OR(0.0, x) -> x 14473 // F[X]OR(x, 0.0) -> x 14474 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 14475 if (C->getValueAPF().isPosZero()) 14476 return N->getOperand(1); 14477 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 14478 if (C->getValueAPF().isPosZero()) 14479 return N->getOperand(0); 14480 return SDValue(); 14481} 14482 14483/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 14484static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 14485 // FAND(0.0, x) -> 0.0 14486 // FAND(x, 0.0) -> 0.0 14487 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 14488 if (C->getValueAPF().isPosZero()) 14489 return N->getOperand(0); 14490 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 14491 if (C->getValueAPF().isPosZero()) 14492 return N->getOperand(1); 14493 return SDValue(); 14494} 14495 14496static SDValue PerformBTCombine(SDNode *N, 14497 SelectionDAG &DAG, 14498 TargetLowering::DAGCombinerInfo &DCI) { 14499 // BT ignores high bits in the bit index operand. 14500 SDValue Op1 = N->getOperand(1); 14501 if (Op1.hasOneUse()) { 14502 unsigned BitWidth = Op1.getValueSizeInBits(); 14503 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 14504 APInt KnownZero, KnownOne; 14505 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 14506 !DCI.isBeforeLegalizeOps()); 14507 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14508 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 14509 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 14510 DCI.CommitTargetLoweringOpt(TLO); 14511 } 14512 return SDValue(); 14513} 14514 14515static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 14516 SDValue Op = N->getOperand(0); 14517 if (Op.getOpcode() == ISD::BITCAST) 14518 Op = Op.getOperand(0); 14519 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 14520 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 14521 VT.getVectorElementType().getSizeInBits() == 14522 OpVT.getVectorElementType().getSizeInBits()) { 14523 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 14524 } 14525 return SDValue(); 14526} 14527 14528static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) { 14529 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 14530 // (and (i32 x86isd::setcc_carry), 1) 14531 // This eliminates the zext. This transformation is necessary because 14532 // ISD::SETCC is always legalized to i8. 14533 DebugLoc dl = N->getDebugLoc(); 14534 SDValue N0 = N->getOperand(0); 14535 EVT VT = N->getValueType(0); 14536 if (N0.getOpcode() == ISD::AND && 14537 N0.hasOneUse() && 14538 N0.getOperand(0).hasOneUse()) { 14539 SDValue N00 = N0.getOperand(0); 14540 if (N00.getOpcode() != X86ISD::SETCC_CARRY) 14541 return SDValue(); 14542 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 14543 if (!C || C->getZExtValue() != 1) 14544 return SDValue(); 14545 return DAG.getNode(ISD::AND, dl, VT, 14546 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 14547 N00.getOperand(0), N00.getOperand(1)), 14548 DAG.getConstant(1, VT)); 14549 } 14550 14551 return SDValue(); 14552} 14553 14554// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 14555static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) { 14556 unsigned X86CC = N->getConstantOperandVal(0); 14557 SDValue EFLAG = N->getOperand(1); 14558 DebugLoc DL = N->getDebugLoc(); 14559 14560 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 14561 // a zext and produces an all-ones bit which is more useful than 0/1 in some 14562 // cases. 14563 if (X86CC == X86::COND_B) 14564 return DAG.getNode(ISD::AND, DL, MVT::i8, 14565 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 14566 DAG.getConstant(X86CC, MVT::i8), EFLAG), 14567 DAG.getConstant(1, MVT::i8)); 14568 14569 return SDValue(); 14570} 14571 14572static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 14573 const X86TargetLowering *XTLI) { 14574 SDValue Op0 = N->getOperand(0); 14575 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 14576 // a 32-bit target where SSE doesn't support i64->FP operations. 14577 if (Op0.getOpcode() == ISD::LOAD) { 14578 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 14579 EVT VT = Ld->getValueType(0); 14580 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 14581 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 14582 !XTLI->getSubtarget()->is64Bit() && 14583 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 14584 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 14585 Ld->getChain(), Op0, DAG); 14586 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 14587 return FILDChain; 14588 } 14589 } 14590 return SDValue(); 14591} 14592 14593// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 14594static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 14595 X86TargetLowering::DAGCombinerInfo &DCI) { 14596 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 14597 // the result is either zero or one (depending on the input carry bit). 14598 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 14599 if (X86::isZeroNode(N->getOperand(0)) && 14600 X86::isZeroNode(N->getOperand(1)) && 14601 // We don't have a good way to replace an EFLAGS use, so only do this when 14602 // dead right now. 14603 SDValue(N, 1).use_empty()) { 14604 DebugLoc DL = N->getDebugLoc(); 14605 EVT VT = N->getValueType(0); 14606 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 14607 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 14608 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 14609 DAG.getConstant(X86::COND_B,MVT::i8), 14610 N->getOperand(2)), 14611 DAG.getConstant(1, VT)); 14612 return DCI.CombineTo(N, Res1, CarryOut); 14613 } 14614 14615 return SDValue(); 14616} 14617 14618// fold (add Y, (sete X, 0)) -> adc 0, Y 14619// (add Y, (setne X, 0)) -> sbb -1, Y 14620// (sub (sete X, 0), Y) -> sbb 0, Y 14621// (sub (setne X, 0), Y) -> adc -1, Y 14622static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 14623 DebugLoc DL = N->getDebugLoc(); 14624 14625 // Look through ZExts. 14626 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 14627 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 14628 return SDValue(); 14629 14630 SDValue SetCC = Ext.getOperand(0); 14631 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 14632 return SDValue(); 14633 14634 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 14635 if (CC != X86::COND_E && CC != X86::COND_NE) 14636 return SDValue(); 14637 14638 SDValue Cmp = SetCC.getOperand(1); 14639 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 14640 !X86::isZeroNode(Cmp.getOperand(1)) || 14641 !Cmp.getOperand(0).getValueType().isInteger()) 14642 return SDValue(); 14643 14644 SDValue CmpOp0 = Cmp.getOperand(0); 14645 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 14646 DAG.getConstant(1, CmpOp0.getValueType())); 14647 14648 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 14649 if (CC == X86::COND_NE) 14650 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 14651 DL, OtherVal.getValueType(), OtherVal, 14652 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 14653 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 14654 DL, OtherVal.getValueType(), OtherVal, 14655 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 14656} 14657 14658/// PerformADDCombine - Do target-specific dag combines on integer adds. 14659static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG, 14660 const X86Subtarget *Subtarget) { 14661 EVT VT = N->getValueType(0); 14662 SDValue Op0 = N->getOperand(0); 14663 SDValue Op1 = N->getOperand(1); 14664 14665 // Try to synthesize horizontal adds from adds of shuffles. 14666 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 14667 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || MVT::v8i32))) && 14668 isHorizontalBinOp(Op0, Op1, true)) 14669 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1); 14670 14671 return OptimizeConditionalInDecrement(N, DAG); 14672} 14673 14674static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG, 14675 const X86Subtarget *Subtarget) { 14676 SDValue Op0 = N->getOperand(0); 14677 SDValue Op1 = N->getOperand(1); 14678 14679 // X86 can't encode an immediate LHS of a sub. See if we can push the 14680 // negation into a preceding instruction. 14681 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 14682 // If the RHS of the sub is a XOR with one use and a constant, invert the 14683 // immediate. Then add one to the LHS of the sub so we can turn 14684 // X-Y -> X+~Y+1, saving one register. 14685 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 14686 isa<ConstantSDNode>(Op1.getOperand(1))) { 14687 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 14688 EVT VT = Op0.getValueType(); 14689 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT, 14690 Op1.getOperand(0), 14691 DAG.getConstant(~XorC, VT)); 14692 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor, 14693 DAG.getConstant(C->getAPIntValue()+1, VT)); 14694 } 14695 } 14696 14697 // Try to synthesize horizontal adds from adds of shuffles. 14698 EVT VT = N->getValueType(0); 14699 if (((Subtarget->hasSSSE3orAVX() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 14700 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 14701 isHorizontalBinOp(Op0, Op1, true)) 14702 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1); 14703 14704 return OptimizeConditionalInDecrement(N, DAG); 14705} 14706 14707SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 14708 DAGCombinerInfo &DCI) const { 14709 SelectionDAG &DAG = DCI.DAG; 14710 switch (N->getOpcode()) { 14711 default: break; 14712 case ISD::EXTRACT_VECTOR_ELT: 14713 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this); 14714 case ISD::VSELECT: 14715 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget); 14716 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI); 14717 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget); 14718 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget); 14719 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 14720 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 14721 case ISD::SHL: 14722 case ISD::SRA: 14723 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget); 14724 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 14725 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 14726 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 14727 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget); 14728 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 14729 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 14730 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 14731 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 14732 case X86ISD::FXOR: 14733 case X86ISD::FOR: return PerformFORCombine(N, DAG); 14734 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 14735 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 14736 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 14737 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG); 14738 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG); 14739 case X86ISD::SHUFPS: // Handle all target specific shuffles 14740 case X86ISD::SHUFPD: 14741 case X86ISD::PALIGN: 14742 case X86ISD::PUNPCKH: 14743 case X86ISD::UNPCKHP: 14744 case X86ISD::PUNPCKL: 14745 case X86ISD::UNPCKLP: 14746 case X86ISD::MOVHLPS: 14747 case X86ISD::MOVLHPS: 14748 case X86ISD::PSHUFD: 14749 case X86ISD::PSHUFHW: 14750 case X86ISD::PSHUFLW: 14751 case X86ISD::MOVSS: 14752 case X86ISD::MOVSD: 14753 case X86ISD::VPERMILP: 14754 case X86ISD::VPERM2X128: 14755 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 14756 } 14757 14758 return SDValue(); 14759} 14760 14761/// isTypeDesirableForOp - Return true if the target has native support for 14762/// the specified value type and it is 'desirable' to use the type for the 14763/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 14764/// instruction encodings are longer and some i16 instructions are slow. 14765bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 14766 if (!isTypeLegal(VT)) 14767 return false; 14768 if (VT != MVT::i16) 14769 return true; 14770 14771 switch (Opc) { 14772 default: 14773 return true; 14774 case ISD::LOAD: 14775 case ISD::SIGN_EXTEND: 14776 case ISD::ZERO_EXTEND: 14777 case ISD::ANY_EXTEND: 14778 case ISD::SHL: 14779 case ISD::SRL: 14780 case ISD::SUB: 14781 case ISD::ADD: 14782 case ISD::MUL: 14783 case ISD::AND: 14784 case ISD::OR: 14785 case ISD::XOR: 14786 return false; 14787 } 14788} 14789 14790/// IsDesirableToPromoteOp - This method query the target whether it is 14791/// beneficial for dag combiner to promote the specified node. If true, it 14792/// should return the desired promotion type by reference. 14793bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 14794 EVT VT = Op.getValueType(); 14795 if (VT != MVT::i16) 14796 return false; 14797 14798 bool Promote = false; 14799 bool Commute = false; 14800 switch (Op.getOpcode()) { 14801 default: break; 14802 case ISD::LOAD: { 14803 LoadSDNode *LD = cast<LoadSDNode>(Op); 14804 // If the non-extending load has a single use and it's not live out, then it 14805 // might be folded. 14806 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 14807 Op.hasOneUse()*/) { 14808 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 14809 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 14810 // The only case where we'd want to promote LOAD (rather then it being 14811 // promoted as an operand is when it's only use is liveout. 14812 if (UI->getOpcode() != ISD::CopyToReg) 14813 return false; 14814 } 14815 } 14816 Promote = true; 14817 break; 14818 } 14819 case ISD::SIGN_EXTEND: 14820 case ISD::ZERO_EXTEND: 14821 case ISD::ANY_EXTEND: 14822 Promote = true; 14823 break; 14824 case ISD::SHL: 14825 case ISD::SRL: { 14826 SDValue N0 = Op.getOperand(0); 14827 // Look out for (store (shl (load), x)). 14828 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 14829 return false; 14830 Promote = true; 14831 break; 14832 } 14833 case ISD::ADD: 14834 case ISD::MUL: 14835 case ISD::AND: 14836 case ISD::OR: 14837 case ISD::XOR: 14838 Commute = true; 14839 // fallthrough 14840 case ISD::SUB: { 14841 SDValue N0 = Op.getOperand(0); 14842 SDValue N1 = Op.getOperand(1); 14843 if (!Commute && MayFoldLoad(N1)) 14844 return false; 14845 // Avoid disabling potential load folding opportunities. 14846 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 14847 return false; 14848 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 14849 return false; 14850 Promote = true; 14851 } 14852 } 14853 14854 PVT = MVT::i32; 14855 return Promote; 14856} 14857 14858//===----------------------------------------------------------------------===// 14859// X86 Inline Assembly Support 14860//===----------------------------------------------------------------------===// 14861 14862bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 14863 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 14864 14865 std::string AsmStr = IA->getAsmString(); 14866 14867 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 14868 SmallVector<StringRef, 4> AsmPieces; 14869 SplitString(AsmStr, AsmPieces, ";\n"); 14870 14871 switch (AsmPieces.size()) { 14872 default: return false; 14873 case 1: 14874 AsmStr = AsmPieces[0]; 14875 AsmPieces.clear(); 14876 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace. 14877 14878 // FIXME: this should verify that we are targeting a 486 or better. If not, 14879 // we will turn this bswap into something that will be lowered to logical ops 14880 // instead of emitting the bswap asm. For now, we don't support 486 or lower 14881 // so don't worry about this. 14882 // bswap $0 14883 if (AsmPieces.size() == 2 && 14884 (AsmPieces[0] == "bswap" || 14885 AsmPieces[0] == "bswapq" || 14886 AsmPieces[0] == "bswapl") && 14887 (AsmPieces[1] == "$0" || 14888 AsmPieces[1] == "${0:q}")) { 14889 // No need to check constraints, nothing other than the equivalent of 14890 // "=r,0" would be valid here. 14891 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14892 if (!Ty || Ty->getBitWidth() % 16 != 0) 14893 return false; 14894 return IntrinsicLowering::LowerToByteSwap(CI); 14895 } 14896 // rorw $$8, ${0:w} --> llvm.bswap.i16 14897 if (CI->getType()->isIntegerTy(16) && 14898 AsmPieces.size() == 3 && 14899 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") && 14900 AsmPieces[1] == "$$8," && 14901 AsmPieces[2] == "${0:w}" && 14902 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14903 AsmPieces.clear(); 14904 const std::string &ConstraintsStr = IA->getConstraintString(); 14905 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14906 std::sort(AsmPieces.begin(), AsmPieces.end()); 14907 if (AsmPieces.size() == 4 && 14908 AsmPieces[0] == "~{cc}" && 14909 AsmPieces[1] == "~{dirflag}" && 14910 AsmPieces[2] == "~{flags}" && 14911 AsmPieces[3] == "~{fpsr}") { 14912 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14913 if (!Ty || Ty->getBitWidth() % 16 != 0) 14914 return false; 14915 return IntrinsicLowering::LowerToByteSwap(CI); 14916 } 14917 } 14918 break; 14919 case 3: 14920 if (CI->getType()->isIntegerTy(32) && 14921 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) { 14922 SmallVector<StringRef, 4> Words; 14923 SplitString(AsmPieces[0], Words, " \t,"); 14924 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14925 Words[2] == "${0:w}") { 14926 Words.clear(); 14927 SplitString(AsmPieces[1], Words, " \t,"); 14928 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" && 14929 Words[2] == "$0") { 14930 Words.clear(); 14931 SplitString(AsmPieces[2], Words, " \t,"); 14932 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" && 14933 Words[2] == "${0:w}") { 14934 AsmPieces.clear(); 14935 const std::string &ConstraintsStr = IA->getConstraintString(); 14936 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 14937 std::sort(AsmPieces.begin(), AsmPieces.end()); 14938 if (AsmPieces.size() == 4 && 14939 AsmPieces[0] == "~{cc}" && 14940 AsmPieces[1] == "~{dirflag}" && 14941 AsmPieces[2] == "~{flags}" && 14942 AsmPieces[3] == "~{fpsr}") { 14943 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14944 if (!Ty || Ty->getBitWidth() % 16 != 0) 14945 return false; 14946 return IntrinsicLowering::LowerToByteSwap(CI); 14947 } 14948 } 14949 } 14950 } 14951 } 14952 14953 if (CI->getType()->isIntegerTy(64)) { 14954 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 14955 if (Constraints.size() >= 2 && 14956 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 14957 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 14958 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 14959 SmallVector<StringRef, 4> Words; 14960 SplitString(AsmPieces[0], Words, " \t"); 14961 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") { 14962 Words.clear(); 14963 SplitString(AsmPieces[1], Words, " \t"); 14964 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") { 14965 Words.clear(); 14966 SplitString(AsmPieces[2], Words, " \t,"); 14967 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" && 14968 Words[2] == "%edx") { 14969 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 14970 if (!Ty || Ty->getBitWidth() % 16 != 0) 14971 return false; 14972 return IntrinsicLowering::LowerToByteSwap(CI); 14973 } 14974 } 14975 } 14976 } 14977 } 14978 break; 14979 } 14980 return false; 14981} 14982 14983 14984 14985/// getConstraintType - Given a constraint letter, return the type of 14986/// constraint it is for this target. 14987X86TargetLowering::ConstraintType 14988X86TargetLowering::getConstraintType(const std::string &Constraint) const { 14989 if (Constraint.size() == 1) { 14990 switch (Constraint[0]) { 14991 case 'R': 14992 case 'q': 14993 case 'Q': 14994 case 'f': 14995 case 't': 14996 case 'u': 14997 case 'y': 14998 case 'x': 14999 case 'Y': 15000 case 'l': 15001 return C_RegisterClass; 15002 case 'a': 15003 case 'b': 15004 case 'c': 15005 case 'd': 15006 case 'S': 15007 case 'D': 15008 case 'A': 15009 return C_Register; 15010 case 'I': 15011 case 'J': 15012 case 'K': 15013 case 'L': 15014 case 'M': 15015 case 'N': 15016 case 'G': 15017 case 'C': 15018 case 'e': 15019 case 'Z': 15020 return C_Other; 15021 default: 15022 break; 15023 } 15024 } 15025 return TargetLowering::getConstraintType(Constraint); 15026} 15027 15028/// Examine constraint type and operand type and determine a weight value. 15029/// This object must already have been set up with the operand type 15030/// and the current alternative constraint selected. 15031TargetLowering::ConstraintWeight 15032 X86TargetLowering::getSingleConstraintMatchWeight( 15033 AsmOperandInfo &info, const char *constraint) const { 15034 ConstraintWeight weight = CW_Invalid; 15035 Value *CallOperandVal = info.CallOperandVal; 15036 // If we don't have a value, we can't do a match, 15037 // but allow it at the lowest weight. 15038 if (CallOperandVal == NULL) 15039 return CW_Default; 15040 Type *type = CallOperandVal->getType(); 15041 // Look at the constraint type. 15042 switch (*constraint) { 15043 default: 15044 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 15045 case 'R': 15046 case 'q': 15047 case 'Q': 15048 case 'a': 15049 case 'b': 15050 case 'c': 15051 case 'd': 15052 case 'S': 15053 case 'D': 15054 case 'A': 15055 if (CallOperandVal->getType()->isIntegerTy()) 15056 weight = CW_SpecificReg; 15057 break; 15058 case 'f': 15059 case 't': 15060 case 'u': 15061 if (type->isFloatingPointTy()) 15062 weight = CW_SpecificReg; 15063 break; 15064 case 'y': 15065 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 15066 weight = CW_SpecificReg; 15067 break; 15068 case 'x': 15069 case 'Y': 15070 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM()) 15071 weight = CW_Register; 15072 break; 15073 case 'I': 15074 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 15075 if (C->getZExtValue() <= 31) 15076 weight = CW_Constant; 15077 } 15078 break; 15079 case 'J': 15080 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15081 if (C->getZExtValue() <= 63) 15082 weight = CW_Constant; 15083 } 15084 break; 15085 case 'K': 15086 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15087 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 15088 weight = CW_Constant; 15089 } 15090 break; 15091 case 'L': 15092 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15093 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 15094 weight = CW_Constant; 15095 } 15096 break; 15097 case 'M': 15098 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15099 if (C->getZExtValue() <= 3) 15100 weight = CW_Constant; 15101 } 15102 break; 15103 case 'N': 15104 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15105 if (C->getZExtValue() <= 0xff) 15106 weight = CW_Constant; 15107 } 15108 break; 15109 case 'G': 15110 case 'C': 15111 if (dyn_cast<ConstantFP>(CallOperandVal)) { 15112 weight = CW_Constant; 15113 } 15114 break; 15115 case 'e': 15116 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15117 if ((C->getSExtValue() >= -0x80000000LL) && 15118 (C->getSExtValue() <= 0x7fffffffLL)) 15119 weight = CW_Constant; 15120 } 15121 break; 15122 case 'Z': 15123 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 15124 if (C->getZExtValue() <= 0xffffffff) 15125 weight = CW_Constant; 15126 } 15127 break; 15128 } 15129 return weight; 15130} 15131 15132/// LowerXConstraint - try to replace an X constraint, which matches anything, 15133/// with another that has more specific requirements based on the type of the 15134/// corresponding operand. 15135const char *X86TargetLowering:: 15136LowerXConstraint(EVT ConstraintVT) const { 15137 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 15138 // 'f' like normal targets. 15139 if (ConstraintVT.isFloatingPoint()) { 15140 if (Subtarget->hasXMMInt()) 15141 return "Y"; 15142 if (Subtarget->hasXMM()) 15143 return "x"; 15144 } 15145 15146 return TargetLowering::LowerXConstraint(ConstraintVT); 15147} 15148 15149/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 15150/// vector. If it is invalid, don't add anything to Ops. 15151void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 15152 std::string &Constraint, 15153 std::vector<SDValue>&Ops, 15154 SelectionDAG &DAG) const { 15155 SDValue Result(0, 0); 15156 15157 // Only support length 1 constraints for now. 15158 if (Constraint.length() > 1) return; 15159 15160 char ConstraintLetter = Constraint[0]; 15161 switch (ConstraintLetter) { 15162 default: break; 15163 case 'I': 15164 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15165 if (C->getZExtValue() <= 31) { 15166 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15167 break; 15168 } 15169 } 15170 return; 15171 case 'J': 15172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15173 if (C->getZExtValue() <= 63) { 15174 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15175 break; 15176 } 15177 } 15178 return; 15179 case 'K': 15180 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15181 if ((int8_t)C->getSExtValue() == C->getSExtValue()) { 15182 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15183 break; 15184 } 15185 } 15186 return; 15187 case 'N': 15188 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15189 if (C->getZExtValue() <= 255) { 15190 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15191 break; 15192 } 15193 } 15194 return; 15195 case 'e': { 15196 // 32-bit signed value 15197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15198 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 15199 C->getSExtValue())) { 15200 // Widen to 64 bits here to get it sign extended. 15201 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 15202 break; 15203 } 15204 // FIXME gcc accepts some relocatable values here too, but only in certain 15205 // memory models; it's complicated. 15206 } 15207 return; 15208 } 15209 case 'Z': { 15210 // 32-bit unsigned value 15211 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 15212 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 15213 C->getZExtValue())) { 15214 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 15215 break; 15216 } 15217 } 15218 // FIXME gcc accepts some relocatable values here too, but only in certain 15219 // memory models; it's complicated. 15220 return; 15221 } 15222 case 'i': { 15223 // Literal immediates are always ok. 15224 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 15225 // Widen to 64 bits here to get it sign extended. 15226 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 15227 break; 15228 } 15229 15230 // In any sort of PIC mode addresses need to be computed at runtime by 15231 // adding in a register or some sort of table lookup. These can't 15232 // be used as immediates. 15233 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 15234 return; 15235 15236 // If we are in non-pic codegen mode, we allow the address of a global (with 15237 // an optional displacement) to be used with 'i'. 15238 GlobalAddressSDNode *GA = 0; 15239 int64_t Offset = 0; 15240 15241 // Match either (GA), (GA+C), (GA+C1+C2), etc. 15242 while (1) { 15243 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 15244 Offset += GA->getOffset(); 15245 break; 15246 } else if (Op.getOpcode() == ISD::ADD) { 15247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 15248 Offset += C->getZExtValue(); 15249 Op = Op.getOperand(0); 15250 continue; 15251 } 15252 } else if (Op.getOpcode() == ISD::SUB) { 15253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 15254 Offset += -C->getZExtValue(); 15255 Op = Op.getOperand(0); 15256 continue; 15257 } 15258 } 15259 15260 // Otherwise, this isn't something we can handle, reject it. 15261 return; 15262 } 15263 15264 const GlobalValue *GV = GA->getGlobal(); 15265 // If we require an extra load to get this address, as in PIC mode, we 15266 // can't accept it. 15267 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 15268 getTargetMachine()))) 15269 return; 15270 15271 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 15272 GA->getValueType(0), Offset); 15273 break; 15274 } 15275 } 15276 15277 if (Result.getNode()) { 15278 Ops.push_back(Result); 15279 return; 15280 } 15281 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 15282} 15283 15284std::pair<unsigned, const TargetRegisterClass*> 15285X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 15286 EVT VT) const { 15287 // First, see if this is a constraint that directly corresponds to an LLVM 15288 // register class. 15289 if (Constraint.size() == 1) { 15290 // GCC Constraint Letters 15291 switch (Constraint[0]) { 15292 default: break; 15293 // TODO: Slight differences here in allocation order and leaving 15294 // RIP in the class. Do they matter any more here than they do 15295 // in the normal allocation? 15296 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 15297 if (Subtarget->is64Bit()) { 15298 if (VT == MVT::i32 || VT == MVT::f32) 15299 return std::make_pair(0U, X86::GR32RegisterClass); 15300 else if (VT == MVT::i16) 15301 return std::make_pair(0U, X86::GR16RegisterClass); 15302 else if (VT == MVT::i8 || VT == MVT::i1) 15303 return std::make_pair(0U, X86::GR8RegisterClass); 15304 else if (VT == MVT::i64 || VT == MVT::f64) 15305 return std::make_pair(0U, X86::GR64RegisterClass); 15306 break; 15307 } 15308 // 32-bit fallthrough 15309 case 'Q': // Q_REGS 15310 if (VT == MVT::i32 || VT == MVT::f32) 15311 return std::make_pair(0U, X86::GR32_ABCDRegisterClass); 15312 else if (VT == MVT::i16) 15313 return std::make_pair(0U, X86::GR16_ABCDRegisterClass); 15314 else if (VT == MVT::i8 || VT == MVT::i1) 15315 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass); 15316 else if (VT == MVT::i64) 15317 return std::make_pair(0U, X86::GR64_ABCDRegisterClass); 15318 break; 15319 case 'r': // GENERAL_REGS 15320 case 'l': // INDEX_REGS 15321 if (VT == MVT::i8 || VT == MVT::i1) 15322 return std::make_pair(0U, X86::GR8RegisterClass); 15323 if (VT == MVT::i16) 15324 return std::make_pair(0U, X86::GR16RegisterClass); 15325 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 15326 return std::make_pair(0U, X86::GR32RegisterClass); 15327 return std::make_pair(0U, X86::GR64RegisterClass); 15328 case 'R': // LEGACY_REGS 15329 if (VT == MVT::i8 || VT == MVT::i1) 15330 return std::make_pair(0U, X86::GR8_NOREXRegisterClass); 15331 if (VT == MVT::i16) 15332 return std::make_pair(0U, X86::GR16_NOREXRegisterClass); 15333 if (VT == MVT::i32 || !Subtarget->is64Bit()) 15334 return std::make_pair(0U, X86::GR32_NOREXRegisterClass); 15335 return std::make_pair(0U, X86::GR64_NOREXRegisterClass); 15336 case 'f': // FP Stack registers. 15337 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 15338 // value to the correct fpstack register class. 15339 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 15340 return std::make_pair(0U, X86::RFP32RegisterClass); 15341 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 15342 return std::make_pair(0U, X86::RFP64RegisterClass); 15343 return std::make_pair(0U, X86::RFP80RegisterClass); 15344 case 'y': // MMX_REGS if MMX allowed. 15345 if (!Subtarget->hasMMX()) break; 15346 return std::make_pair(0U, X86::VR64RegisterClass); 15347 case 'Y': // SSE_REGS if SSE2 allowed 15348 if (!Subtarget->hasXMMInt()) break; 15349 // FALL THROUGH. 15350 case 'x': // SSE_REGS if SSE1 allowed 15351 if (!Subtarget->hasXMM()) break; 15352 15353 switch (VT.getSimpleVT().SimpleTy) { 15354 default: break; 15355 // Scalar SSE types. 15356 case MVT::f32: 15357 case MVT::i32: 15358 return std::make_pair(0U, X86::FR32RegisterClass); 15359 case MVT::f64: 15360 case MVT::i64: 15361 return std::make_pair(0U, X86::FR64RegisterClass); 15362 // Vector types. 15363 case MVT::v16i8: 15364 case MVT::v8i16: 15365 case MVT::v4i32: 15366 case MVT::v2i64: 15367 case MVT::v4f32: 15368 case MVT::v2f64: 15369 return std::make_pair(0U, X86::VR128RegisterClass); 15370 } 15371 break; 15372 } 15373 } 15374 15375 // Use the default implementation in TargetLowering to convert the register 15376 // constraint into a member of a register class. 15377 std::pair<unsigned, const TargetRegisterClass*> Res; 15378 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 15379 15380 // Not found as a standard register? 15381 if (Res.second == 0) { 15382 // Map st(0) -> st(7) -> ST0 15383 if (Constraint.size() == 7 && Constraint[0] == '{' && 15384 tolower(Constraint[1]) == 's' && 15385 tolower(Constraint[2]) == 't' && 15386 Constraint[3] == '(' && 15387 (Constraint[4] >= '0' && Constraint[4] <= '7') && 15388 Constraint[5] == ')' && 15389 Constraint[6] == '}') { 15390 15391 Res.first = X86::ST0+Constraint[4]-'0'; 15392 Res.second = X86::RFP80RegisterClass; 15393 return Res; 15394 } 15395 15396 // GCC allows "st(0)" to be called just plain "st". 15397 if (StringRef("{st}").equals_lower(Constraint)) { 15398 Res.first = X86::ST0; 15399 Res.second = X86::RFP80RegisterClass; 15400 return Res; 15401 } 15402 15403 // flags -> EFLAGS 15404 if (StringRef("{flags}").equals_lower(Constraint)) { 15405 Res.first = X86::EFLAGS; 15406 Res.second = X86::CCRRegisterClass; 15407 return Res; 15408 } 15409 15410 // 'A' means EAX + EDX. 15411 if (Constraint == "A") { 15412 Res.first = X86::EAX; 15413 Res.second = X86::GR32_ADRegisterClass; 15414 return Res; 15415 } 15416 return Res; 15417 } 15418 15419 // Otherwise, check to see if this is a register class of the wrong value 15420 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 15421 // turn into {ax},{dx}. 15422 if (Res.second->hasType(VT)) 15423 return Res; // Correct type already, nothing to do. 15424 15425 // All of the single-register GCC register classes map their values onto 15426 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 15427 // really want an 8-bit or 32-bit register, map to the appropriate register 15428 // class and return the appropriate register. 15429 if (Res.second == X86::GR16RegisterClass) { 15430 if (VT == MVT::i8) { 15431 unsigned DestReg = 0; 15432 switch (Res.first) { 15433 default: break; 15434 case X86::AX: DestReg = X86::AL; break; 15435 case X86::DX: DestReg = X86::DL; break; 15436 case X86::CX: DestReg = X86::CL; break; 15437 case X86::BX: DestReg = X86::BL; break; 15438 } 15439 if (DestReg) { 15440 Res.first = DestReg; 15441 Res.second = X86::GR8RegisterClass; 15442 } 15443 } else if (VT == MVT::i32) { 15444 unsigned DestReg = 0; 15445 switch (Res.first) { 15446 default: break; 15447 case X86::AX: DestReg = X86::EAX; break; 15448 case X86::DX: DestReg = X86::EDX; break; 15449 case X86::CX: DestReg = X86::ECX; break; 15450 case X86::BX: DestReg = X86::EBX; break; 15451 case X86::SI: DestReg = X86::ESI; break; 15452 case X86::DI: DestReg = X86::EDI; break; 15453 case X86::BP: DestReg = X86::EBP; break; 15454 case X86::SP: DestReg = X86::ESP; break; 15455 } 15456 if (DestReg) { 15457 Res.first = DestReg; 15458 Res.second = X86::GR32RegisterClass; 15459 } 15460 } else if (VT == MVT::i64) { 15461 unsigned DestReg = 0; 15462 switch (Res.first) { 15463 default: break; 15464 case X86::AX: DestReg = X86::RAX; break; 15465 case X86::DX: DestReg = X86::RDX; break; 15466 case X86::CX: DestReg = X86::RCX; break; 15467 case X86::BX: DestReg = X86::RBX; break; 15468 case X86::SI: DestReg = X86::RSI; break; 15469 case X86::DI: DestReg = X86::RDI; break; 15470 case X86::BP: DestReg = X86::RBP; break; 15471 case X86::SP: DestReg = X86::RSP; break; 15472 } 15473 if (DestReg) { 15474 Res.first = DestReg; 15475 Res.second = X86::GR64RegisterClass; 15476 } 15477 } 15478 } else if (Res.second == X86::FR32RegisterClass || 15479 Res.second == X86::FR64RegisterClass || 15480 Res.second == X86::VR128RegisterClass) { 15481 // Handle references to XMM physical registers that got mapped into the 15482 // wrong class. This can happen with constraints like {xmm0} where the 15483 // target independent register mapper will just pick the first match it can 15484 // find, ignoring the required type. 15485 if (VT == MVT::f32) 15486 Res.second = X86::FR32RegisterClass; 15487 else if (VT == MVT::f64) 15488 Res.second = X86::FR64RegisterClass; 15489 else if (X86::VR128RegisterClass->hasType(VT)) 15490 Res.second = X86::VR128RegisterClass; 15491 } 15492 15493 return Res; 15494} 15495