X86ISelLowering.cpp revision e6d8fa7d0b4352902886930debe459b9f477303e
1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the interfaces that X86 uses to lower LLVM code into a 11// selection DAG. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "x86-isel" 16#include "X86ISelLowering.h" 17#include "Utils/X86ShuffleDecode.h" 18#include "X86.h" 19#include "X86InstrBuilder.h" 20#include "X86TargetMachine.h" 21#include "X86TargetObjectFile.h" 22#include "llvm/ADT/SmallSet.h" 23#include "llvm/ADT/Statistic.h" 24#include "llvm/ADT/StringExtras.h" 25#include "llvm/ADT/VariadicFunction.h" 26#include "llvm/CodeGen/IntrinsicLowering.h" 27#include "llvm/CodeGen/MachineFrameInfo.h" 28#include "llvm/CodeGen/MachineFunction.h" 29#include "llvm/CodeGen/MachineInstrBuilder.h" 30#include "llvm/CodeGen/MachineJumpTableInfo.h" 31#include "llvm/CodeGen/MachineModuleInfo.h" 32#include "llvm/CodeGen/MachineRegisterInfo.h" 33#include "llvm/IR/CallingConv.h" 34#include "llvm/IR/Constants.h" 35#include "llvm/IR/DerivedTypes.h" 36#include "llvm/IR/Function.h" 37#include "llvm/IR/GlobalAlias.h" 38#include "llvm/IR/GlobalVariable.h" 39#include "llvm/IR/Instructions.h" 40#include "llvm/IR/Intrinsics.h" 41#include "llvm/IR/LLVMContext.h" 42#include "llvm/MC/MCAsmInfo.h" 43#include "llvm/MC/MCContext.h" 44#include "llvm/MC/MCExpr.h" 45#include "llvm/MC/MCSymbol.h" 46#include "llvm/Support/CallSite.h" 47#include "llvm/Support/Debug.h" 48#include "llvm/Support/ErrorHandling.h" 49#include "llvm/Support/MathExtras.h" 50#include "llvm/Target/TargetOptions.h" 51#include <bitset> 52#include <cctype> 53using namespace llvm; 54 55STATISTIC(NumTailCalls, "Number of tail calls"); 56 57// Forward declarations. 58static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 59 SDValue V2); 60 61/// Generate a DAG to grab 128-bits from a vector > 128 bits. This 62/// sets things up to match to an AVX VEXTRACTF128 instruction or a 63/// simple subregister reference. Idx is an index in the 128 bits we 64/// want. It need not be aligned to a 128-bit bounday. That makes 65/// lowering EXTRACT_VECTOR_ELT operations easier. 66static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal, 67 SelectionDAG &DAG, DebugLoc dl) { 68 EVT VT = Vec.getValueType(); 69 assert(VT.is256BitVector() && "Unexpected vector size!"); 70 EVT ElVT = VT.getVectorElementType(); 71 unsigned Factor = VT.getSizeInBits()/128; 72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 73 VT.getVectorNumElements()/Factor); 74 75 // Extract from UNDEF is UNDEF. 76 if (Vec.getOpcode() == ISD::UNDEF) 77 return DAG.getUNDEF(ResultVT); 78 79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR 80 // we can match to VEXTRACTF128. 81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits(); 82 83 // This is the index of the first element of the 128-bit chunk 84 // we want. 85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128) 86 * ElemsPerChunk); 87 88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, 90 VecIdx); 91 92 return Result; 93} 94 95/// Generate a DAG to put 128-bits into a vector > 128 bits. This 96/// sets things up to match to an AVX VINSERTF128 instruction or a 97/// simple superregister reference. Idx is an index in the 128 bits 98/// we want. It need not be aligned to a 128-bit bounday. That makes 99/// lowering INSERT_VECTOR_ELT operations easier. 100static SDValue Insert128BitVector(SDValue Result, SDValue Vec, 101 unsigned IdxVal, SelectionDAG &DAG, 102 DebugLoc dl) { 103 // Inserting UNDEF is Result 104 if (Vec.getOpcode() == ISD::UNDEF) 105 return Result; 106 107 EVT VT = Vec.getValueType(); 108 assert(VT.is128BitVector() && "Unexpected vector size!"); 109 110 EVT ElVT = VT.getVectorElementType(); 111 EVT ResultVT = Result.getValueType(); 112 113 // Insert the relevant 128 bits. 114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits(); 115 116 // This is the index of the first element of the 128-bit chunk 117 // we want. 118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128) 119 * ElemsPerChunk); 120 121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal); 122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, 123 VecIdx); 124} 125 126/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128 127/// instructions. This is used because creating CONCAT_VECTOR nodes of 128/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower 129/// large BUILD_VECTORS. 130static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT, 131 unsigned NumElems, SelectionDAG &DAG, 132 DebugLoc dl) { 133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl); 134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl); 135} 136 137static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) { 138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>(); 139 bool is64Bit = Subtarget->is64Bit(); 140 141 if (Subtarget->isTargetEnvMacho()) { 142 if (is64Bit) 143 return new X86_64MachoTargetObjectFile(); 144 return new TargetLoweringObjectFileMachO(); 145 } 146 147 if (Subtarget->isTargetLinux()) 148 return new X86LinuxTargetObjectFile(); 149 if (Subtarget->isTargetELF()) 150 return new TargetLoweringObjectFileELF(); 151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 152 return new TargetLoweringObjectFileCOFF(); 153 llvm_unreachable("unknown subtarget type"); 154} 155 156X86TargetLowering::X86TargetLowering(X86TargetMachine &TM) 157 : TargetLowering(TM, createTLOF(TM)) { 158 Subtarget = &TM.getSubtarget<X86Subtarget>(); 159 X86ScalarSSEf64 = Subtarget->hasSSE2(); 160 X86ScalarSSEf32 = Subtarget->hasSSE1(); 161 162 RegInfo = TM.getRegisterInfo(); 163 TD = getDataLayout(); 164 165 // Set up the TargetLowering object. 166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }; 167 168 // X86 is weird, it always uses i8 for shift amounts and setcc results. 169 setBooleanContents(ZeroOrOneBooleanContent); 170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks. 171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 172 173 // For 64-bit since we have so many registers use the ILP scheduler, for 174 // 32-bit code use the register pressure specific scheduling. 175 // For Atom, always use ILP scheduling. 176 if (Subtarget->isAtom()) 177 setSchedulingPreference(Sched::ILP); 178 else if (Subtarget->is64Bit()) 179 setSchedulingPreference(Sched::ILP); 180 else 181 setSchedulingPreference(Sched::RegPressure); 182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister()); 183 184 // Bypass i32 with i8 on Atom when compiling with O2 185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) 186 addBypassSlowDiv(32, 8); 187 188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) { 189 // Setup Windows compiler runtime calls. 190 setLibcallName(RTLIB::SDIV_I64, "_alldiv"); 191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv"); 192 setLibcallName(RTLIB::SREM_I64, "_allrem"); 193 setLibcallName(RTLIB::UREM_I64, "_aullrem"); 194 setLibcallName(RTLIB::MUL_I64, "_allmul"); 195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall); 196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall); 197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall); 198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall); 199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall); 200 201 // The _ftol2 runtime function has an unusual calling conv, which 202 // is modeled by a special pseudo-instruction. 203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0); 204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0); 205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0); 206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0); 207 } 208 209 if (Subtarget->isTargetDarwin()) { 210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp. 211 setUseUnderscoreSetJmp(false); 212 setUseUnderscoreLongJmp(false); 213 } else if (Subtarget->isTargetMingw()) { 214 // MS runtime is weird: it exports _setjmp, but longjmp! 215 setUseUnderscoreSetJmp(true); 216 setUseUnderscoreLongJmp(false); 217 } else { 218 setUseUnderscoreSetJmp(true); 219 setUseUnderscoreLongJmp(true); 220 } 221 222 // Set up the register classes. 223 addRegisterClass(MVT::i8, &X86::GR8RegClass); 224 addRegisterClass(MVT::i16, &X86::GR16RegClass); 225 addRegisterClass(MVT::i32, &X86::GR32RegClass); 226 if (Subtarget->is64Bit()) 227 addRegisterClass(MVT::i64, &X86::GR64RegClass); 228 229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 230 231 // We don't accept any truncstore of integer registers. 232 setTruncStoreAction(MVT::i64, MVT::i32, Expand); 233 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand); 235 setTruncStoreAction(MVT::i32, MVT::i16, Expand); 236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand); 237 setTruncStoreAction(MVT::i16, MVT::i8, Expand); 238 239 // SETOEQ and SETUNE require checking two conditions. 240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand); 241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand); 242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand); 243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand); 244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand); 245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand); 246 247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this 248 // operation. 249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote); 250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote); 251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote); 252 253 if (Subtarget->is64Bit()) { 254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote); 255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 256 } else if (!TM.Options.UseSoftFloat) { 257 // We have an algorithm for SSE2->double, and we turn this into a 258 // 64-bit FILD followed by conditional FADD for other targets. 259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom); 260 // We have an algorithm for SSE2, and we turn this into a 64-bit 261 // FILD for other targets. 262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom); 263 } 264 265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have 266 // this operation. 267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote); 268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote); 269 270 if (!TM.Options.UseSoftFloat) { 271 // SSE has no i16 to fp conversion, only i32 272 if (X86ScalarSSEf32) { 273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 274 // f32 and f64 cases are Legal, f80 case is not 275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 276 } else { 277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom); 278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom); 279 } 280 } else { 281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote); 282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote); 283 } 284 285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64 286 // are Legal, f80 is custom lowered. 287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom); 288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom); 289 290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have 291 // this operation. 292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote); 293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote); 294 295 if (X86ScalarSSEf32) { 296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote); 297 // f32 and f64 cases are Legal, f80 case is not 298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 299 } else { 300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom); 301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom); 302 } 303 304 // Handle FP_TO_UINT by promoting the destination to a larger signed 305 // conversion. 306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote); 307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote); 308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote); 309 310 if (Subtarget->is64Bit()) { 311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand); 312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote); 313 } else if (!TM.Options.UseSoftFloat) { 314 // Since AVX is a superset of SSE3, only check for SSE here. 315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3()) 316 // Expand FP_TO_UINT into a select. 317 // FIXME: We would like to use a Custom expander here eventually to do 318 // the optimal thing for SSE vs. the default expansion in the legalizer. 319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand); 320 else 321 // With SSE3 we can use fisttpll to convert to a signed i64; without 322 // SSE, we're stuck with a fistpll. 323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom); 324 } 325 326 if (isTargetFTOL()) { 327 // Use the _ftol2 runtime function, which has a pseudo-instruction 328 // to handle its weird calling convention. 329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom); 330 } 331 332 // TODO: when we have SSE, these could be more efficient, by using movd/movq. 333 if (!X86ScalarSSEf64) { 334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand); 335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand); 336 if (Subtarget->is64Bit()) { 337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand); 338 // Without SSE, i64->f64 goes through memory. 339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand); 340 } 341 } 342 343 // Scalar integer divide and remainder are lowered to use operations that 344 // produce two results, to match the available instructions. This exposes 345 // the two-result form to trivial CSE, which is able to combine x/y and x%y 346 // into a single instruction. 347 // 348 // Scalar integer multiply-high is also lowered to use two-result 349 // operations, to match the available instructions. However, plain multiply 350 // (low) operations are left as Legal, as there are single-result 351 // instructions for this in x86. Using the two-result multiply instructions 352 // when both high and low results are needed must be arranged by dagcombine. 353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 354 MVT VT = IntVTs[i]; 355 setOperationAction(ISD::MULHS, VT, Expand); 356 setOperationAction(ISD::MULHU, VT, Expand); 357 setOperationAction(ISD::SDIV, VT, Expand); 358 setOperationAction(ISD::UDIV, VT, Expand); 359 setOperationAction(ISD::SREM, VT, Expand); 360 setOperationAction(ISD::UREM, VT, Expand); 361 362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences. 363 setOperationAction(ISD::ADDC, VT, Custom); 364 setOperationAction(ISD::ADDE, VT, Custom); 365 setOperationAction(ISD::SUBC, VT, Custom); 366 setOperationAction(ISD::SUBE, VT, Custom); 367 } 368 369 setOperationAction(ISD::BR_JT , MVT::Other, Expand); 370 setOperationAction(ISD::BRCOND , MVT::Other, Custom); 371 setOperationAction(ISD::BR_CC , MVT::Other, Expand); 372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand); 373 if (Subtarget->is64Bit()) 374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal); 375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal); 376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal); 377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand); 378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand); 379 setOperationAction(ISD::FREM , MVT::f32 , Expand); 380 setOperationAction(ISD::FREM , MVT::f64 , Expand); 381 setOperationAction(ISD::FREM , MVT::f80 , Expand); 382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom); 383 384 // Promote the i8 variants and force them on up to i32 which has a shorter 385 // encoding. 386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote); 387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32); 388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote); 389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32); 390 if (Subtarget->hasBMI()) { 391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand); 392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand); 393 if (Subtarget->is64Bit()) 394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); 395 } else { 396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom); 397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom); 398 if (Subtarget->is64Bit()) 399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom); 400 } 401 402 if (Subtarget->hasLZCNT()) { 403 // When promoting the i8 variants, force them to i32 for a shorter 404 // encoding. 405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote); 406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32); 407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote); 408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32); 409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand); 410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand); 411 if (Subtarget->is64Bit()) 412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); 413 } else { 414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom); 415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom); 416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom); 417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom); 418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom); 419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom); 420 if (Subtarget->is64Bit()) { 421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom); 422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom); 423 } 424 } 425 426 if (Subtarget->hasPOPCNT()) { 427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote); 428 } else { 429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand); 430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand); 431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand); 432 if (Subtarget->is64Bit()) 433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand); 434 } 435 436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom); 437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand); 438 439 // These should be promoted to a larger select which is supported. 440 setOperationAction(ISD::SELECT , MVT::i1 , Promote); 441 // X86 wants to expand cmov itself. 442 setOperationAction(ISD::SELECT , MVT::i8 , Custom); 443 setOperationAction(ISD::SELECT , MVT::i16 , Custom); 444 setOperationAction(ISD::SELECT , MVT::i32 , Custom); 445 setOperationAction(ISD::SELECT , MVT::f32 , Custom); 446 setOperationAction(ISD::SELECT , MVT::f64 , Custom); 447 setOperationAction(ISD::SELECT , MVT::f80 , Custom); 448 setOperationAction(ISD::SETCC , MVT::i8 , Custom); 449 setOperationAction(ISD::SETCC , MVT::i16 , Custom); 450 setOperationAction(ISD::SETCC , MVT::i32 , Custom); 451 setOperationAction(ISD::SETCC , MVT::f32 , Custom); 452 setOperationAction(ISD::SETCC , MVT::f64 , Custom); 453 setOperationAction(ISD::SETCC , MVT::f80 , Custom); 454 if (Subtarget->is64Bit()) { 455 setOperationAction(ISD::SELECT , MVT::i64 , Custom); 456 setOperationAction(ISD::SETCC , MVT::i64 , Custom); 457 } 458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom); 459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support 460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 461 // support continuation, user-level threading, and etc.. As a result, no 462 // other SjLj exception interfaces are implemented and please don't build 463 // your own exception handling based on them. 464 // LLVM/Clang supports zero-cost DWARF exception handling. 465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 467 468 // Darwin ABI issue. 469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom); 470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom); 471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom); 472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom); 473 if (Subtarget->is64Bit()) 474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom); 476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom); 477 if (Subtarget->is64Bit()) { 478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom); 479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom); 480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom); 481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom); 482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom); 483 } 484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86) 485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom); 486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom); 487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom); 488 if (Subtarget->is64Bit()) { 489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom); 490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom); 491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom); 492 } 493 494 if (Subtarget->hasSSE1()) 495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal); 496 497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom); 498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom); 499 500 // On X86 and X86-64, atomic operations are lowered to locked instructions. 501 // Locked instructions, in turn, have implicit fence semantics (all memory 502 // operations are flushed before issuing the locked instruction, and they 503 // are not buffered), so we can fold away the common pattern of 504 // fence-atomic-fence. 505 setShouldFoldAtomicFences(true); 506 507 // Expand certain atomics 508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) { 509 MVT VT = IntVTs[i]; 510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom); 511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom); 512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom); 513 } 514 515 if (!Subtarget->is64Bit()) { 516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom); 517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom); 518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom); 521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom); 522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom); 523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom); 524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom); 525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom); 526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom); 527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom); 528 } 529 530 if (Subtarget->hasCmpxchg16b()) { 531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 532 } 533 534 // FIXME - use subtarget debug flags 535 if (!Subtarget->isTargetDarwin() && 536 !Subtarget->isTargetELF() && 537 !Subtarget->isTargetCygMing()) { 538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand); 539 } 540 541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand); 542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand); 543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand); 544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand); 545 if (Subtarget->is64Bit()) { 546 setExceptionPointerRegister(X86::RAX); 547 setExceptionSelectorRegister(X86::RDX); 548 } else { 549 setExceptionPointerRegister(X86::EAX); 550 setExceptionSelectorRegister(X86::EDX); 551 } 552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom); 553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom); 554 555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 557 558 setOperationAction(ISD::TRAP, MVT::Other, Legal); 559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 560 561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 562 setOperationAction(ISD::VASTART , MVT::Other, Custom); 563 setOperationAction(ISD::VAEND , MVT::Other, Expand); 564 if (Subtarget->is64Bit()) { 565 setOperationAction(ISD::VAARG , MVT::Other, Custom); 566 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 567 } else { 568 setOperationAction(ISD::VAARG , MVT::Other, Expand); 569 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 570 } 571 572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 574 575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) 576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 577 MVT::i64 : MVT::i32, Custom); 578 else if (TM.Options.EnableSegmentedStacks) 579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 580 MVT::i64 : MVT::i32, Custom); 581 else 582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ? 583 MVT::i64 : MVT::i32, Expand); 584 585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) { 586 // f32 and f64 use SSE. 587 // Set up the FP register classes. 588 addRegisterClass(MVT::f32, &X86::FR32RegClass); 589 addRegisterClass(MVT::f64, &X86::FR64RegClass); 590 591 // Use ANDPD to simulate FABS. 592 setOperationAction(ISD::FABS , MVT::f64, Custom); 593 setOperationAction(ISD::FABS , MVT::f32, Custom); 594 595 // Use XORP to simulate FNEG. 596 setOperationAction(ISD::FNEG , MVT::f64, Custom); 597 setOperationAction(ISD::FNEG , MVT::f32, Custom); 598 599 // Use ANDPD and ORPD to simulate FCOPYSIGN. 600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 602 603 // Lower this to FGETSIGNx86 plus an AND. 604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom); 605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom); 606 607 // We don't support sin/cos/fmod 608 setOperationAction(ISD::FSIN , MVT::f64, Expand); 609 setOperationAction(ISD::FCOS , MVT::f64, Expand); 610 setOperationAction(ISD::FSIN , MVT::f32, Expand); 611 setOperationAction(ISD::FCOS , MVT::f32, Expand); 612 613 // Expand FP immediates into loads from the stack, except for the special 614 // cases we handle. 615 addLegalFPImmediate(APFloat(+0.0)); // xorpd 616 addLegalFPImmediate(APFloat(+0.0f)); // xorps 617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) { 618 // Use SSE for f32, x87 for f64. 619 // Set up the FP register classes. 620 addRegisterClass(MVT::f32, &X86::FR32RegClass); 621 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 622 623 // Use ANDPS to simulate FABS. 624 setOperationAction(ISD::FABS , MVT::f32, Custom); 625 626 // Use XORP to simulate FNEG. 627 setOperationAction(ISD::FNEG , MVT::f32, Custom); 628 629 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 630 631 // Use ANDPS and ORPS to simulate FCOPYSIGN. 632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 634 635 // We don't support sin/cos/fmod 636 setOperationAction(ISD::FSIN , MVT::f32, Expand); 637 setOperationAction(ISD::FCOS , MVT::f32, Expand); 638 639 // Special cases we handle for FP constants. 640 addLegalFPImmediate(APFloat(+0.0f)); // xorps 641 addLegalFPImmediate(APFloat(+0.0)); // FLD0 642 addLegalFPImmediate(APFloat(+1.0)); // FLD1 643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 645 646 if (!TM.Options.UnsafeFPMath) { 647 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 648 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 649 } 650 } else if (!TM.Options.UseSoftFloat) { 651 // f32 and f64 in x87. 652 // Set up the FP register classes. 653 addRegisterClass(MVT::f64, &X86::RFP64RegClass); 654 addRegisterClass(MVT::f32, &X86::RFP32RegClass); 655 656 setOperationAction(ISD::UNDEF, MVT::f64, Expand); 657 setOperationAction(ISD::UNDEF, MVT::f32, Expand); 658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 660 661 if (!TM.Options.UnsafeFPMath) { 662 setOperationAction(ISD::FSIN , MVT::f32 , Expand); 663 setOperationAction(ISD::FSIN , MVT::f64 , Expand); 664 setOperationAction(ISD::FCOS , MVT::f32 , Expand); 665 setOperationAction(ISD::FCOS , MVT::f64 , Expand); 666 } 667 addLegalFPImmediate(APFloat(+0.0)); // FLD0 668 addLegalFPImmediate(APFloat(+1.0)); // FLD1 669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS 670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS 671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0 672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1 673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS 674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS 675 } 676 677 // We don't support FMA. 678 setOperationAction(ISD::FMA, MVT::f64, Expand); 679 setOperationAction(ISD::FMA, MVT::f32, Expand); 680 681 // Long double always uses X87. 682 if (!TM.Options.UseSoftFloat) { 683 addRegisterClass(MVT::f80, &X86::RFP80RegClass); 684 setOperationAction(ISD::UNDEF, MVT::f80, Expand); 685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand); 686 { 687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended); 688 addLegalFPImmediate(TmpFlt); // FLD0 689 TmpFlt.changeSign(); 690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS 691 692 bool ignored; 693 APFloat TmpFlt2(+1.0); 694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven, 695 &ignored); 696 addLegalFPImmediate(TmpFlt2); // FLD1 697 TmpFlt2.changeSign(); 698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS 699 } 700 701 if (!TM.Options.UnsafeFPMath) { 702 setOperationAction(ISD::FSIN , MVT::f80 , Expand); 703 setOperationAction(ISD::FCOS , MVT::f80 , Expand); 704 } 705 706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand); 707 setOperationAction(ISD::FCEIL, MVT::f80, Expand); 708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand); 709 setOperationAction(ISD::FRINT, MVT::f80, Expand); 710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand); 711 setOperationAction(ISD::FMA, MVT::f80, Expand); 712 } 713 714 // Always use a library call for pow. 715 setOperationAction(ISD::FPOW , MVT::f32 , Expand); 716 setOperationAction(ISD::FPOW , MVT::f64 , Expand); 717 setOperationAction(ISD::FPOW , MVT::f80 , Expand); 718 719 setOperationAction(ISD::FLOG, MVT::f80, Expand); 720 setOperationAction(ISD::FLOG2, MVT::f80, Expand); 721 setOperationAction(ISD::FLOG10, MVT::f80, Expand); 722 setOperationAction(ISD::FEXP, MVT::f80, Expand); 723 setOperationAction(ISD::FEXP2, MVT::f80, Expand); 724 725 // First set operation action for all vector types to either promote 726 // (for widening) or expand (for scalarization). Then we will selectively 727 // turn on ones that can be effectively codegen'd. 728 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 730 MVT VT = (MVT::SimpleValueType)i; 731 setOperationAction(ISD::ADD , VT, Expand); 732 setOperationAction(ISD::SUB , VT, Expand); 733 setOperationAction(ISD::FADD, VT, Expand); 734 setOperationAction(ISD::FNEG, VT, Expand); 735 setOperationAction(ISD::FSUB, VT, Expand); 736 setOperationAction(ISD::MUL , VT, Expand); 737 setOperationAction(ISD::FMUL, VT, Expand); 738 setOperationAction(ISD::SDIV, VT, Expand); 739 setOperationAction(ISD::UDIV, VT, Expand); 740 setOperationAction(ISD::FDIV, VT, Expand); 741 setOperationAction(ISD::SREM, VT, Expand); 742 setOperationAction(ISD::UREM, VT, Expand); 743 setOperationAction(ISD::LOAD, VT, Expand); 744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand); 745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand); 746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand); 748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand); 749 setOperationAction(ISD::FABS, VT, Expand); 750 setOperationAction(ISD::FSIN, VT, Expand); 751 setOperationAction(ISD::FCOS, VT, Expand); 752 setOperationAction(ISD::FREM, VT, Expand); 753 setOperationAction(ISD::FMA, VT, Expand); 754 setOperationAction(ISD::FPOWI, VT, Expand); 755 setOperationAction(ISD::FSQRT, VT, Expand); 756 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 757 setOperationAction(ISD::FFLOOR, VT, Expand); 758 setOperationAction(ISD::FCEIL, VT, Expand); 759 setOperationAction(ISD::FTRUNC, VT, Expand); 760 setOperationAction(ISD::FRINT, VT, Expand); 761 setOperationAction(ISD::FNEARBYINT, VT, Expand); 762 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 763 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 764 setOperationAction(ISD::SDIVREM, VT, Expand); 765 setOperationAction(ISD::UDIVREM, VT, Expand); 766 setOperationAction(ISD::FPOW, VT, Expand); 767 setOperationAction(ISD::CTPOP, VT, Expand); 768 setOperationAction(ISD::CTTZ, VT, Expand); 769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); 770 setOperationAction(ISD::CTLZ, VT, Expand); 771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); 772 setOperationAction(ISD::SHL, VT, Expand); 773 setOperationAction(ISD::SRA, VT, Expand); 774 setOperationAction(ISD::SRL, VT, Expand); 775 setOperationAction(ISD::ROTL, VT, Expand); 776 setOperationAction(ISD::ROTR, VT, Expand); 777 setOperationAction(ISD::BSWAP, VT, Expand); 778 setOperationAction(ISD::SETCC, VT, Expand); 779 setOperationAction(ISD::FLOG, VT, Expand); 780 setOperationAction(ISD::FLOG2, VT, Expand); 781 setOperationAction(ISD::FLOG10, VT, Expand); 782 setOperationAction(ISD::FEXP, VT, Expand); 783 setOperationAction(ISD::FEXP2, VT, Expand); 784 setOperationAction(ISD::FP_TO_UINT, VT, Expand); 785 setOperationAction(ISD::FP_TO_SINT, VT, Expand); 786 setOperationAction(ISD::UINT_TO_FP, VT, Expand); 787 setOperationAction(ISD::SINT_TO_FP, VT, Expand); 788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand); 789 setOperationAction(ISD::TRUNCATE, VT, Expand); 790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand); 791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand); 792 setOperationAction(ISD::ANY_EXTEND, VT, Expand); 793 setOperationAction(ISD::VSELECT, VT, Expand); 794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE; 795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT) 796 setTruncStoreAction(VT, 797 (MVT::SimpleValueType)InnerVT, Expand); 798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand); 799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand); 800 setLoadExtAction(ISD::EXTLOAD, VT, Expand); 801 } 802 803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones 804 // with -msoft-float, disable use of MMX as well. 805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) { 806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass); 807 // No operations on x86mmx supported, everything uses intrinsics. 808 } 809 810 // MMX-sized vectors (other than x86mmx) are expected to be expanded 811 // into smaller operations. 812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand); 813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand); 814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand); 815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand); 816 setOperationAction(ISD::AND, MVT::v8i8, Expand); 817 setOperationAction(ISD::AND, MVT::v4i16, Expand); 818 setOperationAction(ISD::AND, MVT::v2i32, Expand); 819 setOperationAction(ISD::AND, MVT::v1i64, Expand); 820 setOperationAction(ISD::OR, MVT::v8i8, Expand); 821 setOperationAction(ISD::OR, MVT::v4i16, Expand); 822 setOperationAction(ISD::OR, MVT::v2i32, Expand); 823 setOperationAction(ISD::OR, MVT::v1i64, Expand); 824 setOperationAction(ISD::XOR, MVT::v8i8, Expand); 825 setOperationAction(ISD::XOR, MVT::v4i16, Expand); 826 setOperationAction(ISD::XOR, MVT::v2i32, Expand); 827 setOperationAction(ISD::XOR, MVT::v1i64, Expand); 828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand); 829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand); 830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand); 831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand); 832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand); 833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand); 834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand); 835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand); 836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand); 837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand); 838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand); 839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand); 840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand); 841 842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) { 843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass); 844 845 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom); 851 setOperationAction(ISD::FABS, MVT::v4f32, Custom); 852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal); 853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom); 855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom); 857 } 858 859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) { 860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass); 861 862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM 863 // registers cannot be used even for integer operations. 864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass); 865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass); 866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass); 867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass); 868 869 setOperationAction(ISD::ADD, MVT::v16i8, Legal); 870 setOperationAction(ISD::ADD, MVT::v8i16, Legal); 871 setOperationAction(ISD::ADD, MVT::v4i32, Legal); 872 setOperationAction(ISD::ADD, MVT::v2i64, Legal); 873 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 874 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 875 setOperationAction(ISD::SUB, MVT::v16i8, Legal); 876 setOperationAction(ISD::SUB, MVT::v8i16, Legal); 877 setOperationAction(ISD::SUB, MVT::v4i32, Legal); 878 setOperationAction(ISD::SUB, MVT::v2i64, Legal); 879 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 880 setOperationAction(ISD::FADD, MVT::v2f64, Legal); 881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal); 882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal); 883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom); 886 setOperationAction(ISD::FABS, MVT::v2f64, Custom); 887 888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom); 890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom); 891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom); 892 893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom); 894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom); 895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 898 899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt. 900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 901 MVT VT = (MVT::SimpleValueType)i; 902 // Do not attempt to custom lower non-power-of-2 vectors 903 if (!isPowerOf2_32(VT.getVectorNumElements())) 904 continue; 905 // Do not attempt to custom lower non-128-bit vectors 906 if (!VT.is128BitVector()) 907 continue; 908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 911 } 912 913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom); 919 920 if (Subtarget->is64Bit()) { 921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 923 } 924 925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) { 927 MVT VT = (MVT::SimpleValueType)i; 928 929 // Do not attempt to promote non-128-bit vectors 930 if (!VT.is128BitVector()) 931 continue; 932 933 setOperationAction(ISD::AND, VT, Promote); 934 AddPromotedToType (ISD::AND, VT, MVT::v2i64); 935 setOperationAction(ISD::OR, VT, Promote); 936 AddPromotedToType (ISD::OR, VT, MVT::v2i64); 937 setOperationAction(ISD::XOR, VT, Promote); 938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64); 939 setOperationAction(ISD::LOAD, VT, Promote); 940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64); 941 setOperationAction(ISD::SELECT, VT, Promote); 942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64); 943 } 944 945 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 946 947 // Custom lower v2i64 and v2f64 selects. 948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal); 950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom); 951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom); 952 953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 955 956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 958 // As there is no 64-bit GPR available, we need build a special custom 959 // sequence to convert from v2i32 to v2f32. 960 if (!Subtarget->is64Bit()) 961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom); 962 963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom); 965 966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal); 967 } 968 969 if (Subtarget->hasSSE41()) { 970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 971 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 973 setOperationAction(ISD::FRINT, MVT::f32, Legal); 974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 976 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 978 setOperationAction(ISD::FRINT, MVT::f64, Legal); 979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 980 981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 991 992 // FIXME: Do we need to handle scalar-to-vector here? 993 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 994 995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal); 997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1000 1001 // i8 and i16 vectors are custom , because the source register and source 1002 // source memory operand types are not the same width. f32 vectors are 1003 // custom since the immediate controlling the insert encodes additional 1004 // information. 1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1009 1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom); 1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom); 1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom); 1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom); 1014 1015 // FIXME: these should be Legal but thats only for the case where 1016 // the index is constant. For now custom expand to deal with that. 1017 if (Subtarget->is64Bit()) { 1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom); 1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom); 1020 } 1021 } 1022 1023 if (Subtarget->hasSSE2()) { 1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom); 1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom); 1026 1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom); 1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom); 1029 1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom); 1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom); 1032 1033 if (Subtarget->hasInt256()) { 1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal); 1036 1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal); 1039 1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal); 1041 } else { 1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom); 1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom); 1044 1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom); 1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom); 1047 1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom); 1049 } 1050 setOperationAction(ISD::SDIV, MVT::v8i16, Custom); 1051 setOperationAction(ISD::SDIV, MVT::v4i32, Custom); 1052 } 1053 1054 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) { 1055 addRegisterClass(MVT::v32i8, &X86::VR256RegClass); 1056 addRegisterClass(MVT::v16i16, &X86::VR256RegClass); 1057 addRegisterClass(MVT::v8i32, &X86::VR256RegClass); 1058 addRegisterClass(MVT::v8f32, &X86::VR256RegClass); 1059 addRegisterClass(MVT::v4i64, &X86::VR256RegClass); 1060 addRegisterClass(MVT::v4f64, &X86::VR256RegClass); 1061 1062 setOperationAction(ISD::LOAD, MVT::v8f32, Legal); 1063 setOperationAction(ISD::LOAD, MVT::v4f64, Legal); 1064 setOperationAction(ISD::LOAD, MVT::v4i64, Legal); 1065 1066 setOperationAction(ISD::FADD, MVT::v8f32, Legal); 1067 setOperationAction(ISD::FSUB, MVT::v8f32, Legal); 1068 setOperationAction(ISD::FMUL, MVT::v8f32, Legal); 1069 setOperationAction(ISD::FDIV, MVT::v8f32, Legal); 1070 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal); 1071 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal); 1072 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal); 1073 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal); 1074 setOperationAction(ISD::FRINT, MVT::v8f32, Legal); 1075 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal); 1076 setOperationAction(ISD::FNEG, MVT::v8f32, Custom); 1077 setOperationAction(ISD::FABS, MVT::v8f32, Custom); 1078 1079 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 1080 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 1081 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 1082 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1083 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1084 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1085 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1086 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1087 setOperationAction(ISD::FRINT, MVT::v4f64, Legal); 1088 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal); 1089 setOperationAction(ISD::FNEG, MVT::v4f64, Custom); 1090 setOperationAction(ISD::FABS, MVT::v4f64, Custom); 1091 1092 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom); 1093 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom); 1094 1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom); 1096 1097 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal); 1098 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal); 1099 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal); 1100 1101 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1102 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom); 1103 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 1104 1105 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal); 1106 1107 setOperationAction(ISD::SRL, MVT::v16i16, Custom); 1108 setOperationAction(ISD::SRL, MVT::v32i8, Custom); 1109 1110 setOperationAction(ISD::SHL, MVT::v16i16, Custom); 1111 setOperationAction(ISD::SHL, MVT::v32i8, Custom); 1112 1113 setOperationAction(ISD::SRA, MVT::v16i16, Custom); 1114 setOperationAction(ISD::SRA, MVT::v32i8, Custom); 1115 1116 setOperationAction(ISD::SDIV, MVT::v16i16, Custom); 1117 1118 setOperationAction(ISD::SETCC, MVT::v32i8, Custom); 1119 setOperationAction(ISD::SETCC, MVT::v16i16, Custom); 1120 setOperationAction(ISD::SETCC, MVT::v8i32, Custom); 1121 setOperationAction(ISD::SETCC, MVT::v4i64, Custom); 1122 1123 setOperationAction(ISD::SELECT, MVT::v4f64, Custom); 1124 setOperationAction(ISD::SELECT, MVT::v4i64, Custom); 1125 setOperationAction(ISD::SELECT, MVT::v8f32, Custom); 1126 1127 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 1128 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal); 1129 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal); 1130 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal); 1131 1132 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom); 1133 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom); 1134 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom); 1135 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom); 1136 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom); 1137 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom); 1138 1139 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) { 1140 setOperationAction(ISD::FMA, MVT::v8f32, Legal); 1141 setOperationAction(ISD::FMA, MVT::v4f64, Legal); 1142 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 1143 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1144 setOperationAction(ISD::FMA, MVT::f32, Legal); 1145 setOperationAction(ISD::FMA, MVT::f64, Legal); 1146 } 1147 1148 if (Subtarget->hasInt256()) { 1149 setOperationAction(ISD::ADD, MVT::v4i64, Legal); 1150 setOperationAction(ISD::ADD, MVT::v8i32, Legal); 1151 setOperationAction(ISD::ADD, MVT::v16i16, Legal); 1152 setOperationAction(ISD::ADD, MVT::v32i8, Legal); 1153 1154 setOperationAction(ISD::SUB, MVT::v4i64, Legal); 1155 setOperationAction(ISD::SUB, MVT::v8i32, Legal); 1156 setOperationAction(ISD::SUB, MVT::v16i16, Legal); 1157 setOperationAction(ISD::SUB, MVT::v32i8, Legal); 1158 1159 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1160 setOperationAction(ISD::MUL, MVT::v8i32, Legal); 1161 setOperationAction(ISD::MUL, MVT::v16i16, Legal); 1162 // Don't lower v32i8 because there is no 128-bit byte mul 1163 1164 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal); 1165 1166 setOperationAction(ISD::SRL, MVT::v4i64, Legal); 1167 setOperationAction(ISD::SRL, MVT::v8i32, Legal); 1168 1169 setOperationAction(ISD::SHL, MVT::v4i64, Legal); 1170 setOperationAction(ISD::SHL, MVT::v8i32, Legal); 1171 1172 setOperationAction(ISD::SRA, MVT::v8i32, Legal); 1173 1174 setOperationAction(ISD::SDIV, MVT::v8i32, Custom); 1175 } else { 1176 setOperationAction(ISD::ADD, MVT::v4i64, Custom); 1177 setOperationAction(ISD::ADD, MVT::v8i32, Custom); 1178 setOperationAction(ISD::ADD, MVT::v16i16, Custom); 1179 setOperationAction(ISD::ADD, MVT::v32i8, Custom); 1180 1181 setOperationAction(ISD::SUB, MVT::v4i64, Custom); 1182 setOperationAction(ISD::SUB, MVT::v8i32, Custom); 1183 setOperationAction(ISD::SUB, MVT::v16i16, Custom); 1184 setOperationAction(ISD::SUB, MVT::v32i8, Custom); 1185 1186 setOperationAction(ISD::MUL, MVT::v4i64, Custom); 1187 setOperationAction(ISD::MUL, MVT::v8i32, Custom); 1188 setOperationAction(ISD::MUL, MVT::v16i16, Custom); 1189 // Don't lower v32i8 because there is no 128-bit byte mul 1190 1191 setOperationAction(ISD::SRL, MVT::v4i64, Custom); 1192 setOperationAction(ISD::SRL, MVT::v8i32, Custom); 1193 1194 setOperationAction(ISD::SHL, MVT::v4i64, Custom); 1195 setOperationAction(ISD::SHL, MVT::v8i32, Custom); 1196 1197 setOperationAction(ISD::SRA, MVT::v8i32, Custom); 1198 } 1199 1200 // Custom lower several nodes for 256-bit types. 1201 for (int i = MVT::FIRST_VECTOR_VALUETYPE; 1202 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) { 1203 MVT VT = (MVT::SimpleValueType)i; 1204 1205 // Extract subvector is special because the value type 1206 // (result) is 128-bit but the source is 256-bit wide. 1207 if (VT.is128BitVector()) 1208 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 1209 1210 // Do not attempt to custom lower other non-256-bit vectors 1211 if (!VT.is256BitVector()) 1212 continue; 1213 1214 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 1215 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 1216 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 1217 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 1218 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom); 1219 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom); 1220 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom); 1221 } 1222 1223 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64. 1224 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) { 1225 MVT VT = (MVT::SimpleValueType)i; 1226 1227 // Do not attempt to promote non-256-bit vectors 1228 if (!VT.is256BitVector()) 1229 continue; 1230 1231 setOperationAction(ISD::AND, VT, Promote); 1232 AddPromotedToType (ISD::AND, VT, MVT::v4i64); 1233 setOperationAction(ISD::OR, VT, Promote); 1234 AddPromotedToType (ISD::OR, VT, MVT::v4i64); 1235 setOperationAction(ISD::XOR, VT, Promote); 1236 AddPromotedToType (ISD::XOR, VT, MVT::v4i64); 1237 setOperationAction(ISD::LOAD, VT, Promote); 1238 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64); 1239 setOperationAction(ISD::SELECT, VT, Promote); 1240 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64); 1241 } 1242 } 1243 1244 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion 1245 // of this type with custom code. 1246 for (int VT = MVT::FIRST_VECTOR_VALUETYPE; 1247 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) { 1248 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, 1249 Custom); 1250 } 1251 1252 // We want to custom lower some of our intrinsics. 1253 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 1254 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 1255 1256 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't 1257 // handle type legalization for these operations here. 1258 // 1259 // FIXME: We really should do custom legalization for addition and 1260 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better 1261 // than generic legalization for 64-bit multiplication-with-overflow, though. 1262 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) { 1263 // Add/Sub/Mul with overflow operations are custom lowered. 1264 MVT VT = IntVTs[i]; 1265 setOperationAction(ISD::SADDO, VT, Custom); 1266 setOperationAction(ISD::UADDO, VT, Custom); 1267 setOperationAction(ISD::SSUBO, VT, Custom); 1268 setOperationAction(ISD::USUBO, VT, Custom); 1269 setOperationAction(ISD::SMULO, VT, Custom); 1270 setOperationAction(ISD::UMULO, VT, Custom); 1271 } 1272 1273 // There are no 8-bit 3-address imul/mul instructions 1274 setOperationAction(ISD::SMULO, MVT::i8, Expand); 1275 setOperationAction(ISD::UMULO, MVT::i8, Expand); 1276 1277 if (!Subtarget->is64Bit()) { 1278 // These libcalls are not available in 32-bit. 1279 setLibcallName(RTLIB::SHL_I128, 0); 1280 setLibcallName(RTLIB::SRL_I128, 0); 1281 setLibcallName(RTLIB::SRA_I128, 0); 1282 } 1283 1284 // We have target-specific dag combine patterns for the following nodes: 1285 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1286 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 1287 setTargetDAGCombine(ISD::VSELECT); 1288 setTargetDAGCombine(ISD::SELECT); 1289 setTargetDAGCombine(ISD::SHL); 1290 setTargetDAGCombine(ISD::SRA); 1291 setTargetDAGCombine(ISD::SRL); 1292 setTargetDAGCombine(ISD::OR); 1293 setTargetDAGCombine(ISD::AND); 1294 setTargetDAGCombine(ISD::ADD); 1295 setTargetDAGCombine(ISD::FADD); 1296 setTargetDAGCombine(ISD::FSUB); 1297 setTargetDAGCombine(ISD::FMA); 1298 setTargetDAGCombine(ISD::SUB); 1299 setTargetDAGCombine(ISD::LOAD); 1300 setTargetDAGCombine(ISD::STORE); 1301 setTargetDAGCombine(ISD::ZERO_EXTEND); 1302 setTargetDAGCombine(ISD::ANY_EXTEND); 1303 setTargetDAGCombine(ISD::SIGN_EXTEND); 1304 setTargetDAGCombine(ISD::TRUNCATE); 1305 setTargetDAGCombine(ISD::SINT_TO_FP); 1306 setTargetDAGCombine(ISD::SETCC); 1307 if (Subtarget->is64Bit()) 1308 setTargetDAGCombine(ISD::MUL); 1309 setTargetDAGCombine(ISD::XOR); 1310 1311 computeRegisterProperties(); 1312 1313 // On Darwin, -Os means optimize for size without hurting performance, 1314 // do not reduce the limit. 1315 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores 1316 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8; 1317 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores 1318 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1319 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores 1320 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4; 1321 setPrefLoopAlignment(4); // 2^4 bytes. 1322 benefitFromCodePlacementOpt = true; 1323 1324 // Predictable cmov don't hurt on atom because it's in-order. 1325 predictableSelectIsExpensive = !Subtarget->isAtom(); 1326 1327 setPrefFunctionAlignment(4); // 2^4 bytes. 1328} 1329 1330EVT X86TargetLowering::getSetCCResultType(EVT VT) const { 1331 if (!VT.isVector()) return MVT::i8; 1332 return VT.changeVectorElementTypeToInteger(); 1333} 1334 1335/// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1336/// the desired ByVal argument alignment. 1337static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) { 1338 if (MaxAlign == 16) 1339 return; 1340 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1341 if (VTy->getBitWidth() == 128) 1342 MaxAlign = 16; 1343 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1344 unsigned EltAlign = 0; 1345 getMaxByValAlign(ATy->getElementType(), EltAlign); 1346 if (EltAlign > MaxAlign) 1347 MaxAlign = EltAlign; 1348 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1349 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1350 unsigned EltAlign = 0; 1351 getMaxByValAlign(STy->getElementType(i), EltAlign); 1352 if (EltAlign > MaxAlign) 1353 MaxAlign = EltAlign; 1354 if (MaxAlign == 16) 1355 break; 1356 } 1357 } 1358} 1359 1360/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1361/// function arguments in the caller parameter area. For X86, aggregates 1362/// that contain SSE vectors are placed at 16-byte boundaries while the rest 1363/// are at 4-byte boundaries. 1364unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const { 1365 if (Subtarget->is64Bit()) { 1366 // Max of 8 and alignment of type. 1367 unsigned TyAlign = TD->getABITypeAlignment(Ty); 1368 if (TyAlign > 8) 1369 return TyAlign; 1370 return 8; 1371 } 1372 1373 unsigned Align = 4; 1374 if (Subtarget->hasSSE1()) 1375 getMaxByValAlign(Ty, Align); 1376 return Align; 1377} 1378 1379/// getOptimalMemOpType - Returns the target specific optimal type for load 1380/// and store operations as a result of memset, memcpy, and memmove 1381/// lowering. If DstAlign is zero that means it's safe to destination 1382/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 1383/// means there isn't a need to check it against alignment requirement, 1384/// probably because the source does not need to be loaded. If 'IsMemset' is 1385/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 1386/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 1387/// source is constant so it does not need to be loaded. 1388/// It returns EVT::Other if the type should be determined using generic 1389/// target-independent logic. 1390EVT 1391X86TargetLowering::getOptimalMemOpType(uint64_t Size, 1392 unsigned DstAlign, unsigned SrcAlign, 1393 bool IsMemset, bool ZeroMemset, 1394 bool MemcpyStrSrc, 1395 MachineFunction &MF) const { 1396 const Function *F = MF.getFunction(); 1397 if ((!IsMemset || ZeroMemset) && 1398 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 1399 Attribute::NoImplicitFloat)) { 1400 if (Size >= 16 && 1401 (Subtarget->isUnalignedMemAccessFast() || 1402 ((DstAlign == 0 || DstAlign >= 16) && 1403 (SrcAlign == 0 || SrcAlign >= 16)))) { 1404 if (Size >= 32) { 1405 if (Subtarget->hasInt256()) 1406 return MVT::v8i32; 1407 if (Subtarget->hasFp256()) 1408 return MVT::v8f32; 1409 } 1410 if (Subtarget->hasSSE2()) 1411 return MVT::v4i32; 1412 if (Subtarget->hasSSE1()) 1413 return MVT::v4f32; 1414 } else if (!MemcpyStrSrc && Size >= 8 && 1415 !Subtarget->is64Bit() && 1416 Subtarget->hasSSE2()) { 1417 // Do not use f64 to lower memcpy if source is string constant. It's 1418 // better to use i32 to avoid the loads. 1419 return MVT::f64; 1420 } 1421 } 1422 if (Subtarget->is64Bit() && Size >= 8) 1423 return MVT::i64; 1424 return MVT::i32; 1425} 1426 1427bool X86TargetLowering::isSafeMemOpType(MVT VT) const { 1428 if (VT == MVT::f32) 1429 return X86ScalarSSEf32; 1430 else if (VT == MVT::f64) 1431 return X86ScalarSSEf64; 1432 return true; 1433} 1434 1435bool 1436X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const { 1437 if (Fast) 1438 *Fast = Subtarget->isUnalignedMemAccessFast(); 1439 return true; 1440} 1441 1442/// getJumpTableEncoding - Return the entry encoding for a jump table in the 1443/// current function. The returned value is a member of the 1444/// MachineJumpTableInfo::JTEntryKind enum. 1445unsigned X86TargetLowering::getJumpTableEncoding() const { 1446 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF 1447 // symbol. 1448 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1449 Subtarget->isPICStyleGOT()) 1450 return MachineJumpTableInfo::EK_Custom32; 1451 1452 // Otherwise, use the normal jump table encoding heuristics. 1453 return TargetLowering::getJumpTableEncoding(); 1454} 1455 1456const MCExpr * 1457X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 1458 const MachineBasicBlock *MBB, 1459 unsigned uid,MCContext &Ctx) const{ 1460 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ && 1461 Subtarget->isPICStyleGOT()); 1462 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF 1463 // entries. 1464 return MCSymbolRefExpr::Create(MBB->getSymbol(), 1465 MCSymbolRefExpr::VK_GOTOFF, Ctx); 1466} 1467 1468/// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 1469/// jumptable. 1470SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table, 1471 SelectionDAG &DAG) const { 1472 if (!Subtarget->is64Bit()) 1473 // This doesn't have DebugLoc associated with it, but is not really the 1474 // same as a Register. 1475 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()); 1476 return Table; 1477} 1478 1479/// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 1480/// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 1481/// MCExpr. 1482const MCExpr *X86TargetLowering:: 1483getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, 1484 MCContext &Ctx) const { 1485 // X86-64 uses RIP relative addressing based on the jump table label. 1486 if (Subtarget->isPICStyleRIPRel()) 1487 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 1488 1489 // Otherwise, the reference is relative to the PIC base. 1490 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx); 1491} 1492 1493// FIXME: Why this routine is here? Move to RegInfo! 1494std::pair<const TargetRegisterClass*, uint8_t> 1495X86TargetLowering::findRepresentativeClass(MVT VT) const{ 1496 const TargetRegisterClass *RRC = 0; 1497 uint8_t Cost = 1; 1498 switch (VT.SimpleTy) { 1499 default: 1500 return TargetLowering::findRepresentativeClass(VT); 1501 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64: 1502 RRC = Subtarget->is64Bit() ? 1503 (const TargetRegisterClass*)&X86::GR64RegClass : 1504 (const TargetRegisterClass*)&X86::GR32RegClass; 1505 break; 1506 case MVT::x86mmx: 1507 RRC = &X86::VR64RegClass; 1508 break; 1509 case MVT::f32: case MVT::f64: 1510 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64: 1511 case MVT::v4f32: case MVT::v2f64: 1512 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32: 1513 case MVT::v4f64: 1514 RRC = &X86::VR128RegClass; 1515 break; 1516 } 1517 return std::make_pair(RRC, Cost); 1518} 1519 1520bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace, 1521 unsigned &Offset) const { 1522 if (!Subtarget->isTargetLinux()) 1523 return false; 1524 1525 if (Subtarget->is64Bit()) { 1526 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs: 1527 Offset = 0x28; 1528 if (getTargetMachine().getCodeModel() == CodeModel::Kernel) 1529 AddressSpace = 256; 1530 else 1531 AddressSpace = 257; 1532 } else { 1533 // %gs:0x14 on i386 1534 Offset = 0x14; 1535 AddressSpace = 256; 1536 } 1537 return true; 1538} 1539 1540//===----------------------------------------------------------------------===// 1541// Return Value Calling Convention Implementation 1542//===----------------------------------------------------------------------===// 1543 1544#include "X86GenCallingConv.inc" 1545 1546bool 1547X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, 1548 MachineFunction &MF, bool isVarArg, 1549 const SmallVectorImpl<ISD::OutputArg> &Outs, 1550 LLVMContext &Context) const { 1551 SmallVector<CCValAssign, 16> RVLocs; 1552 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1553 RVLocs, Context); 1554 return CCInfo.CheckReturn(Outs, RetCC_X86); 1555} 1556 1557SDValue 1558X86TargetLowering::LowerReturn(SDValue Chain, 1559 CallingConv::ID CallConv, bool isVarArg, 1560 const SmallVectorImpl<ISD::OutputArg> &Outs, 1561 const SmallVectorImpl<SDValue> &OutVals, 1562 DebugLoc dl, SelectionDAG &DAG) const { 1563 MachineFunction &MF = DAG.getMachineFunction(); 1564 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1565 1566 SmallVector<CCValAssign, 16> RVLocs; 1567 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1568 RVLocs, *DAG.getContext()); 1569 CCInfo.AnalyzeReturn(Outs, RetCC_X86); 1570 1571 // Add the regs to the liveout set for the function. 1572 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1573 for (unsigned i = 0; i != RVLocs.size(); ++i) 1574 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg())) 1575 MRI.addLiveOut(RVLocs[i].getLocReg()); 1576 1577 SDValue Flag; 1578 1579 SmallVector<SDValue, 6> RetOps; 1580 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1581 // Operand #1 = Bytes To Pop 1582 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), 1583 MVT::i16)); 1584 1585 // Copy the result values into the output registers. 1586 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1587 CCValAssign &VA = RVLocs[i]; 1588 assert(VA.isRegLoc() && "Can only return in registers!"); 1589 SDValue ValToCopy = OutVals[i]; 1590 EVT ValVT = ValToCopy.getValueType(); 1591 1592 // Promote values to the appropriate types 1593 if (VA.getLocInfo() == CCValAssign::SExt) 1594 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy); 1595 else if (VA.getLocInfo() == CCValAssign::ZExt) 1596 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy); 1597 else if (VA.getLocInfo() == CCValAssign::AExt) 1598 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy); 1599 else if (VA.getLocInfo() == CCValAssign::BCvt) 1600 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy); 1601 1602 // If this is x86-64, and we disabled SSE, we can't return FP values, 1603 // or SSE or MMX vectors. 1604 if ((ValVT == MVT::f32 || ValVT == MVT::f64 || 1605 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) && 1606 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) { 1607 report_fatal_error("SSE register return with SSE disabled"); 1608 } 1609 // Likewise we can't return F64 values with SSE1 only. gcc does so, but 1610 // llvm-gcc has never done it right and no one has noticed, so this 1611 // should be OK for now. 1612 if (ValVT == MVT::f64 && 1613 (Subtarget->is64Bit() && !Subtarget->hasSSE2())) 1614 report_fatal_error("SSE2 register return with SSE2 disabled"); 1615 1616 // Returns in ST0/ST1 are handled specially: these are pushed as operands to 1617 // the RET instruction and handled by the FP Stackifier. 1618 if (VA.getLocReg() == X86::ST0 || 1619 VA.getLocReg() == X86::ST1) { 1620 // If this is a copy from an xmm register to ST(0), use an FPExtend to 1621 // change the value to the FP stack register class. 1622 if (isScalarFPTypeInSSEReg(VA.getValVT())) 1623 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy); 1624 RetOps.push_back(ValToCopy); 1625 // Don't emit a copytoreg. 1626 continue; 1627 } 1628 1629 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64 1630 // which is returned in RAX / RDX. 1631 if (Subtarget->is64Bit()) { 1632 if (ValVT == MVT::x86mmx) { 1633 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) { 1634 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy); 1635 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 1636 ValToCopy); 1637 // If we don't have SSE2 available, convert to v4f32 so the generated 1638 // register is legal. 1639 if (!Subtarget->hasSSE2()) 1640 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy); 1641 } 1642 } 1643 } 1644 1645 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag); 1646 Flag = Chain.getValue(1); 1647 } 1648 1649 // The x86-64 ABI for returning structs by value requires that we copy 1650 // the sret argument into %rax for the return. We saved the argument into 1651 // a virtual register in the entry block, so now we copy the value out 1652 // and into %rax. 1653 if (Subtarget->is64Bit() && 1654 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) { 1655 MachineFunction &MF = DAG.getMachineFunction(); 1656 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1657 unsigned Reg = FuncInfo->getSRetReturnReg(); 1658 assert(Reg && 1659 "SRetReturnReg should have been set in LowerFormalArguments()."); 1660 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy()); 1661 1662 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag); 1663 Flag = Chain.getValue(1); 1664 1665 // RAX now acts like a return value. 1666 MRI.addLiveOut(X86::RAX); 1667 } 1668 1669 RetOps[0] = Chain; // Update chain. 1670 1671 // Add the flag if we have it. 1672 if (Flag.getNode()) 1673 RetOps.push_back(Flag); 1674 1675 return DAG.getNode(X86ISD::RET_FLAG, dl, 1676 MVT::Other, &RetOps[0], RetOps.size()); 1677} 1678 1679bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { 1680 if (N->getNumValues() != 1) 1681 return false; 1682 if (!N->hasNUsesOfValue(1, 0)) 1683 return false; 1684 1685 SDValue TCChain = Chain; 1686 SDNode *Copy = *N->use_begin(); 1687 if (Copy->getOpcode() == ISD::CopyToReg) { 1688 // If the copy has a glue operand, we conservatively assume it isn't safe to 1689 // perform a tail call. 1690 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue) 1691 return false; 1692 TCChain = Copy->getOperand(0); 1693 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 1694 return false; 1695 1696 bool HasRet = false; 1697 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end(); 1698 UI != UE; ++UI) { 1699 if (UI->getOpcode() != X86ISD::RET_FLAG) 1700 return false; 1701 HasRet = true; 1702 } 1703 1704 if (!HasRet) 1705 return false; 1706 1707 Chain = TCChain; 1708 return true; 1709} 1710 1711MVT 1712X86TargetLowering::getTypeForExtArgOrReturn(MVT VT, 1713 ISD::NodeType ExtendKind) const { 1714 MVT ReturnMVT; 1715 // TODO: Is this also valid on 32-bit? 1716 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND) 1717 ReturnMVT = MVT::i8; 1718 else 1719 ReturnMVT = MVT::i32; 1720 1721 MVT MinVT = getRegisterType(ReturnMVT); 1722 return VT.bitsLT(MinVT) ? MinVT : VT; 1723} 1724 1725/// LowerCallResult - Lower the result values of a call into the 1726/// appropriate copies out of appropriate physical registers. 1727/// 1728SDValue 1729X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, 1730 CallingConv::ID CallConv, bool isVarArg, 1731 const SmallVectorImpl<ISD::InputArg> &Ins, 1732 DebugLoc dl, SelectionDAG &DAG, 1733 SmallVectorImpl<SDValue> &InVals) const { 1734 1735 // Assign locations to each value returned by this call. 1736 SmallVector<CCValAssign, 16> RVLocs; 1737 bool Is64Bit = Subtarget->is64Bit(); 1738 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), 1739 getTargetMachine(), RVLocs, *DAG.getContext()); 1740 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 1741 1742 // Copy all of the result registers out of their specified physreg. 1743 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 1744 CCValAssign &VA = RVLocs[i]; 1745 EVT CopyVT = VA.getValVT(); 1746 1747 // If this is x86-64, and we disabled SSE, we can't return FP values 1748 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) && 1749 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) { 1750 report_fatal_error("SSE register return with SSE disabled"); 1751 } 1752 1753 SDValue Val; 1754 1755 // If this is a call to a function that returns an fp value on the floating 1756 // point stack, we must guarantee the value is popped from the stack, so 1757 // a CopyFromReg is not good enough - the copy instruction may be eliminated 1758 // if the return value is not used. We use the FpPOP_RETVAL instruction 1759 // instead. 1760 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) { 1761 // If we prefer to use the value in xmm registers, copy it out as f80 and 1762 // use a truncate to move it from fp stack reg to xmm reg. 1763 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80; 1764 SDValue Ops[] = { Chain, InFlag }; 1765 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT, 1766 MVT::Other, MVT::Glue, Ops, 2), 1); 1767 Val = Chain.getValue(0); 1768 1769 // Round the f80 to the right size, which also moves it to the appropriate 1770 // xmm register. 1771 if (CopyVT != VA.getValVT()) 1772 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val, 1773 // This truncation won't change the value. 1774 DAG.getIntPtrConstant(1)); 1775 } else { 1776 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), 1777 CopyVT, InFlag).getValue(1); 1778 Val = Chain.getValue(0); 1779 } 1780 InFlag = Chain.getValue(2); 1781 InVals.push_back(Val); 1782 } 1783 1784 return Chain; 1785} 1786 1787//===----------------------------------------------------------------------===// 1788// C & StdCall & Fast Calling Convention implementation 1789//===----------------------------------------------------------------------===// 1790// StdCall calling convention seems to be standard for many Windows' API 1791// routines and around. It differs from C calling convention just a little: 1792// callee should clean up the stack, not caller. Symbols should be also 1793// decorated in some fancy way :) It doesn't support any vector arguments. 1794// For info on fast calling convention see Fast Calling Convention (tail call) 1795// implementation LowerX86_32FastCCCallTo. 1796 1797/// CallIsStructReturn - Determines whether a call uses struct return 1798/// semantics. 1799enum StructReturnType { 1800 NotStructReturn, 1801 RegStructReturn, 1802 StackStructReturn 1803}; 1804static StructReturnType 1805callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) { 1806 if (Outs.empty()) 1807 return NotStructReturn; 1808 1809 const ISD::ArgFlagsTy &Flags = Outs[0].Flags; 1810 if (!Flags.isSRet()) 1811 return NotStructReturn; 1812 if (Flags.isInReg()) 1813 return RegStructReturn; 1814 return StackStructReturn; 1815} 1816 1817/// ArgsAreStructReturn - Determines whether a function uses struct 1818/// return semantics. 1819static StructReturnType 1820argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) { 1821 if (Ins.empty()) 1822 return NotStructReturn; 1823 1824 const ISD::ArgFlagsTy &Flags = Ins[0].Flags; 1825 if (!Flags.isSRet()) 1826 return NotStructReturn; 1827 if (Flags.isInReg()) 1828 return RegStructReturn; 1829 return StackStructReturn; 1830} 1831 1832/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 1833/// by "Src" to address "Dst" with size and alignment information specified by 1834/// the specific parameter attribute. The copy will be passed as a byval 1835/// function parameter. 1836static SDValue 1837CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, 1838 ISD::ArgFlagsTy Flags, SelectionDAG &DAG, 1839 DebugLoc dl) { 1840 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32); 1841 1842 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 1843 /*isVolatile*/false, /*AlwaysInline=*/true, 1844 MachinePointerInfo(), MachinePointerInfo()); 1845} 1846 1847/// IsTailCallConvention - Return true if the calling convention is one that 1848/// supports tail call optimization. 1849static bool IsTailCallConvention(CallingConv::ID CC) { 1850 return (CC == CallingConv::Fast || CC == CallingConv::GHC || 1851 CC == CallingConv::HiPE); 1852} 1853 1854bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 1855 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls) 1856 return false; 1857 1858 CallSite CS(CI); 1859 CallingConv::ID CalleeCC = CS.getCallingConv(); 1860 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C) 1861 return false; 1862 1863 return true; 1864} 1865 1866/// FuncIsMadeTailCallSafe - Return true if the function is being made into 1867/// a tailcall target by changing its ABI. 1868static bool FuncIsMadeTailCallSafe(CallingConv::ID CC, 1869 bool GuaranteedTailCallOpt) { 1870 return GuaranteedTailCallOpt && IsTailCallConvention(CC); 1871} 1872 1873SDValue 1874X86TargetLowering::LowerMemArgument(SDValue Chain, 1875 CallingConv::ID CallConv, 1876 const SmallVectorImpl<ISD::InputArg> &Ins, 1877 DebugLoc dl, SelectionDAG &DAG, 1878 const CCValAssign &VA, 1879 MachineFrameInfo *MFI, 1880 unsigned i) const { 1881 // Create the nodes corresponding to a load from this parameter slot. 1882 ISD::ArgFlagsTy Flags = Ins[i].Flags; 1883 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv, 1884 getTargetMachine().Options.GuaranteedTailCallOpt); 1885 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal(); 1886 EVT ValVT; 1887 1888 // If value is passed by pointer we have address passed instead of the value 1889 // itself. 1890 if (VA.getLocInfo() == CCValAssign::Indirect) 1891 ValVT = VA.getLocVT(); 1892 else 1893 ValVT = VA.getValVT(); 1894 1895 // FIXME: For now, all byval parameter objects are marked mutable. This can be 1896 // changed with more analysis. 1897 // In case of tail call optimization mark all arguments mutable. Since they 1898 // could be overwritten by lowering of arguments in case of a tail call. 1899 if (Flags.isByVal()) { 1900 unsigned Bytes = Flags.getByValSize(); 1901 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects. 1902 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable); 1903 return DAG.getFrameIndex(FI, getPointerTy()); 1904 } else { 1905 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8, 1906 VA.getLocMemOffset(), isImmutable); 1907 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy()); 1908 return DAG.getLoad(ValVT, dl, Chain, FIN, 1909 MachinePointerInfo::getFixedStack(FI), 1910 false, false, false, 0); 1911 } 1912} 1913 1914SDValue 1915X86TargetLowering::LowerFormalArguments(SDValue Chain, 1916 CallingConv::ID CallConv, 1917 bool isVarArg, 1918 const SmallVectorImpl<ISD::InputArg> &Ins, 1919 DebugLoc dl, 1920 SelectionDAG &DAG, 1921 SmallVectorImpl<SDValue> &InVals) 1922 const { 1923 MachineFunction &MF = DAG.getMachineFunction(); 1924 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 1925 1926 const Function* Fn = MF.getFunction(); 1927 if (Fn->hasExternalLinkage() && 1928 Subtarget->isTargetCygMing() && 1929 Fn->getName() == "main") 1930 FuncInfo->setForceFramePointer(true); 1931 1932 MachineFrameInfo *MFI = MF.getFrameInfo(); 1933 bool Is64Bit = Subtarget->is64Bit(); 1934 bool IsWindows = Subtarget->isTargetWindows(); 1935 bool IsWin64 = Subtarget->isTargetWin64(); 1936 1937 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 1938 "Var args not supported with calling convention fastcc, ghc or hipe"); 1939 1940 // Assign locations to all of the incoming arguments. 1941 SmallVector<CCValAssign, 16> ArgLocs; 1942 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 1943 ArgLocs, *DAG.getContext()); 1944 1945 // Allocate shadow area for Win64 1946 if (IsWin64) { 1947 CCInfo.AllocateStack(32, 8); 1948 } 1949 1950 CCInfo.AnalyzeFormalArguments(Ins, CC_X86); 1951 1952 unsigned LastVal = ~0U; 1953 SDValue ArgValue; 1954 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 1955 CCValAssign &VA = ArgLocs[i]; 1956 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later 1957 // places. 1958 assert(VA.getValNo() != LastVal && 1959 "Don't support value assigned to multiple locs yet"); 1960 (void)LastVal; 1961 LastVal = VA.getValNo(); 1962 1963 if (VA.isRegLoc()) { 1964 EVT RegVT = VA.getLocVT(); 1965 const TargetRegisterClass *RC; 1966 if (RegVT == MVT::i32) 1967 RC = &X86::GR32RegClass; 1968 else if (Is64Bit && RegVT == MVT::i64) 1969 RC = &X86::GR64RegClass; 1970 else if (RegVT == MVT::f32) 1971 RC = &X86::FR32RegClass; 1972 else if (RegVT == MVT::f64) 1973 RC = &X86::FR64RegClass; 1974 else if (RegVT.is256BitVector()) 1975 RC = &X86::VR256RegClass; 1976 else if (RegVT.is128BitVector()) 1977 RC = &X86::VR128RegClass; 1978 else if (RegVT == MVT::x86mmx) 1979 RC = &X86::VR64RegClass; 1980 else 1981 llvm_unreachable("Unknown argument type!"); 1982 1983 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 1984 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT); 1985 1986 // If this is an 8 or 16-bit value, it is really passed promoted to 32 1987 // bits. Insert an assert[sz]ext to capture this, then truncate to the 1988 // right size. 1989 if (VA.getLocInfo() == CCValAssign::SExt) 1990 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue, 1991 DAG.getValueType(VA.getValVT())); 1992 else if (VA.getLocInfo() == CCValAssign::ZExt) 1993 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue, 1994 DAG.getValueType(VA.getValVT())); 1995 else if (VA.getLocInfo() == CCValAssign::BCvt) 1996 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue); 1997 1998 if (VA.isExtInLoc()) { 1999 // Handle MMX values passed in XMM regs. 2000 if (RegVT.isVector()) 2001 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue); 2002 else 2003 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue); 2004 } 2005 } else { 2006 assert(VA.isMemLoc()); 2007 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i); 2008 } 2009 2010 // If value is passed via pointer - do a load. 2011 if (VA.getLocInfo() == CCValAssign::Indirect) 2012 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, 2013 MachinePointerInfo(), false, false, false, 0); 2014 2015 InVals.push_back(ArgValue); 2016 } 2017 2018 // The x86-64 ABI for returning structs by value requires that we copy 2019 // the sret argument into %rax for the return. Save the argument into 2020 // a virtual register so that we can access it from the return points. 2021 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) { 2022 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 2023 unsigned Reg = FuncInfo->getSRetReturnReg(); 2024 if (!Reg) { 2025 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64)); 2026 FuncInfo->setSRetReturnReg(Reg); 2027 } 2028 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]); 2029 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain); 2030 } 2031 2032 unsigned StackSize = CCInfo.getNextStackOffset(); 2033 // Align stack specially for tail calls. 2034 if (FuncIsMadeTailCallSafe(CallConv, 2035 MF.getTarget().Options.GuaranteedTailCallOpt)) 2036 StackSize = GetAlignedArgumentStackSize(StackSize, DAG); 2037 2038 // If the function takes variable number of arguments, make a frame index for 2039 // the start of the first vararg value... for expansion of llvm.va_start. 2040 if (isVarArg) { 2041 if (Is64Bit || (CallConv != CallingConv::X86_FastCall && 2042 CallConv != CallingConv::X86_ThisCall)) { 2043 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true)); 2044 } 2045 if (Is64Bit) { 2046 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0; 2047 2048 // FIXME: We should really autogenerate these arrays 2049 static const uint16_t GPR64ArgRegsWin64[] = { 2050 X86::RCX, X86::RDX, X86::R8, X86::R9 2051 }; 2052 static const uint16_t GPR64ArgRegs64Bit[] = { 2053 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9 2054 }; 2055 static const uint16_t XMMArgRegs64Bit[] = { 2056 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2057 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2058 }; 2059 const uint16_t *GPR64ArgRegs; 2060 unsigned NumXMMRegs = 0; 2061 2062 if (IsWin64) { 2063 // The XMM registers which might contain var arg parameters are shadowed 2064 // in their paired GPR. So we only need to save the GPR to their home 2065 // slots. 2066 TotalNumIntRegs = 4; 2067 GPR64ArgRegs = GPR64ArgRegsWin64; 2068 } else { 2069 TotalNumIntRegs = 6; TotalNumXMMRegs = 8; 2070 GPR64ArgRegs = GPR64ArgRegs64Bit; 2071 2072 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, 2073 TotalNumXMMRegs); 2074 } 2075 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 2076 TotalNumIntRegs); 2077 2078 bool NoImplicitFloatOps = Fn->getAttributes(). 2079 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 2080 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) && 2081 "SSE register cannot be used when SSE is disabled!"); 2082 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat && 2083 NoImplicitFloatOps) && 2084 "SSE register cannot be used when SSE is disabled!"); 2085 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps || 2086 !Subtarget->hasSSE1()) 2087 // Kernel mode asks for SSE to be disabled, so don't push them 2088 // on the stack. 2089 TotalNumXMMRegs = 0; 2090 2091 if (IsWin64) { 2092 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering(); 2093 // Get to the caller-allocated home save location. Add 8 to account 2094 // for the return address. 2095 int HomeOffset = TFI.getOffsetOfLocalArea() + 8; 2096 FuncInfo->setRegSaveFrameIndex( 2097 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false)); 2098 // Fixup to set vararg frame on shadow area (4 x i64). 2099 if (NumIntRegs < 4) 2100 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex()); 2101 } else { 2102 // For X86-64, if there are vararg parameters that are passed via 2103 // registers, then we must store them to their spots on the stack so 2104 // they may be loaded by deferencing the result of va_next. 2105 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8); 2106 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16); 2107 FuncInfo->setRegSaveFrameIndex( 2108 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16, 2109 false)); 2110 } 2111 2112 // Store the integer parameter registers. 2113 SmallVector<SDValue, 8> MemOps; 2114 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 2115 getPointerTy()); 2116 unsigned Offset = FuncInfo->getVarArgsGPOffset(); 2117 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) { 2118 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN, 2119 DAG.getIntPtrConstant(Offset)); 2120 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs], 2121 &X86::GR64RegClass); 2122 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 2123 SDValue Store = 2124 DAG.getStore(Val.getValue(1), dl, Val, FIN, 2125 MachinePointerInfo::getFixedStack( 2126 FuncInfo->getRegSaveFrameIndex(), Offset), 2127 false, false, 0); 2128 MemOps.push_back(Store); 2129 Offset += 8; 2130 } 2131 2132 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) { 2133 // Now store the XMM (fp + vector) parameter registers. 2134 SmallVector<SDValue, 11> SaveXMMOps; 2135 SaveXMMOps.push_back(Chain); 2136 2137 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass); 2138 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8); 2139 SaveXMMOps.push_back(ALVal); 2140 2141 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2142 FuncInfo->getRegSaveFrameIndex())); 2143 SaveXMMOps.push_back(DAG.getIntPtrConstant( 2144 FuncInfo->getVarArgsFPOffset())); 2145 2146 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) { 2147 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs], 2148 &X86::VR128RegClass); 2149 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32); 2150 SaveXMMOps.push_back(Val); 2151 } 2152 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl, 2153 MVT::Other, 2154 &SaveXMMOps[0], SaveXMMOps.size())); 2155 } 2156 2157 if (!MemOps.empty()) 2158 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2159 &MemOps[0], MemOps.size()); 2160 } 2161 } 2162 2163 // Some CCs need callee pop. 2164 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2165 MF.getTarget().Options.GuaranteedTailCallOpt)) { 2166 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything. 2167 } else { 2168 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing. 2169 // If this is an sret function, the return should pop the hidden pointer. 2170 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2171 argsAreStructReturn(Ins) == StackStructReturn) 2172 FuncInfo->setBytesToPopOnReturn(4); 2173 } 2174 2175 if (!Is64Bit) { 2176 // RegSaveFrameIndex is X86-64 only. 2177 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA); 2178 if (CallConv == CallingConv::X86_FastCall || 2179 CallConv == CallingConv::X86_ThisCall) 2180 // fastcc functions can't have varargs. 2181 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA); 2182 } 2183 2184 FuncInfo->setArgumentStackSize(StackSize); 2185 2186 return Chain; 2187} 2188 2189SDValue 2190X86TargetLowering::LowerMemOpCallTo(SDValue Chain, 2191 SDValue StackPtr, SDValue Arg, 2192 DebugLoc dl, SelectionDAG &DAG, 2193 const CCValAssign &VA, 2194 ISD::ArgFlagsTy Flags) const { 2195 unsigned LocMemOffset = VA.getLocMemOffset(); 2196 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset); 2197 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff); 2198 if (Flags.isByVal()) 2199 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl); 2200 2201 return DAG.getStore(Chain, dl, Arg, PtrOff, 2202 MachinePointerInfo::getStack(LocMemOffset), 2203 false, false, 0); 2204} 2205 2206/// EmitTailCallLoadRetAddr - Emit a load of return address if tail call 2207/// optimization is performed and it is required. 2208SDValue 2209X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 2210 SDValue &OutRetAddr, SDValue Chain, 2211 bool IsTailCall, bool Is64Bit, 2212 int FPDiff, DebugLoc dl) const { 2213 // Adjust the Return address stack slot. 2214 EVT VT = getPointerTy(); 2215 OutRetAddr = getReturnAddressFrameIndex(DAG); 2216 2217 // Load the "old" Return address. 2218 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(), 2219 false, false, false, 0); 2220 return SDValue(OutRetAddr.getNode(), 1); 2221} 2222 2223/// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call 2224/// optimization is performed and it is required (FPDiff!=0). 2225static SDValue 2226EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 2227 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT, 2228 unsigned SlotSize, int FPDiff, DebugLoc dl) { 2229 // Store the return address to the appropriate stack slot. 2230 if (!FPDiff) return Chain; 2231 // Calculate the new stack slot for the return address. 2232 int NewReturnAddrFI = 2233 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false); 2234 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT); 2235 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx, 2236 MachinePointerInfo::getFixedStack(NewReturnAddrFI), 2237 false, false, 0); 2238 return Chain; 2239} 2240 2241SDValue 2242X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 2243 SmallVectorImpl<SDValue> &InVals) const { 2244 SelectionDAG &DAG = CLI.DAG; 2245 DebugLoc &dl = CLI.DL; 2246 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2247 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2248 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2249 SDValue Chain = CLI.Chain; 2250 SDValue Callee = CLI.Callee; 2251 CallingConv::ID CallConv = CLI.CallConv; 2252 bool &isTailCall = CLI.IsTailCall; 2253 bool isVarArg = CLI.IsVarArg; 2254 2255 MachineFunction &MF = DAG.getMachineFunction(); 2256 bool Is64Bit = Subtarget->is64Bit(); 2257 bool IsWin64 = Subtarget->isTargetWin64(); 2258 bool IsWindows = Subtarget->isTargetWindows(); 2259 StructReturnType SR = callIsStructReturn(Outs); 2260 bool IsSibcall = false; 2261 2262 if (MF.getTarget().Options.DisableTailCalls) 2263 isTailCall = false; 2264 2265 if (isTailCall) { 2266 // Check if it's really possible to do a tail call. 2267 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, 2268 isVarArg, SR != NotStructReturn, 2269 MF.getFunction()->hasStructRetAttr(), CLI.RetTy, 2270 Outs, OutVals, Ins, DAG); 2271 2272 // Sibcalls are automatically detected tailcalls which do not require 2273 // ABI changes. 2274 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall) 2275 IsSibcall = true; 2276 2277 if (isTailCall) 2278 ++NumTailCalls; 2279 } 2280 2281 assert(!(isVarArg && IsTailCallConvention(CallConv)) && 2282 "Var args not supported with calling convention fastcc, ghc or hipe"); 2283 2284 // Analyze operands of the call, assigning locations to each operand. 2285 SmallVector<CCValAssign, 16> ArgLocs; 2286 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), 2287 ArgLocs, *DAG.getContext()); 2288 2289 // Allocate shadow area for Win64 2290 if (IsWin64) { 2291 CCInfo.AllocateStack(32, 8); 2292 } 2293 2294 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2295 2296 // Get a count of how many bytes are to be pushed on the stack. 2297 unsigned NumBytes = CCInfo.getNextStackOffset(); 2298 if (IsSibcall) 2299 // This is a sibcall. The memory operands are available in caller's 2300 // own caller's stack. 2301 NumBytes = 0; 2302 else if (getTargetMachine().Options.GuaranteedTailCallOpt && 2303 IsTailCallConvention(CallConv)) 2304 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG); 2305 2306 int FPDiff = 0; 2307 if (isTailCall && !IsSibcall) { 2308 // Lower arguments at fp - stackoffset + fpdiff. 2309 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>(); 2310 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn(); 2311 2312 FPDiff = NumBytesCallerPushed - NumBytes; 2313 2314 // Set the delta of movement of the returnaddr stackslot. 2315 // But only set if delta is greater than previous delta. 2316 if (FPDiff < X86Info->getTCReturnAddrDelta()) 2317 X86Info->setTCReturnAddrDelta(FPDiff); 2318 } 2319 2320 if (!IsSibcall) 2321 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true)); 2322 2323 SDValue RetAddrFrIdx; 2324 // Load return address for tail calls. 2325 if (isTailCall && FPDiff) 2326 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, 2327 Is64Bit, FPDiff, dl); 2328 2329 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2330 SmallVector<SDValue, 8> MemOpChains; 2331 SDValue StackPtr; 2332 2333 // Walk the register/memloc assignments, inserting copies/loads. In the case 2334 // of tail call optimization arguments are handle later. 2335 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2336 CCValAssign &VA = ArgLocs[i]; 2337 EVT RegVT = VA.getLocVT(); 2338 SDValue Arg = OutVals[i]; 2339 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2340 bool isByVal = Flags.isByVal(); 2341 2342 // Promote the value if needed. 2343 switch (VA.getLocInfo()) { 2344 default: llvm_unreachable("Unknown loc info!"); 2345 case CCValAssign::Full: break; 2346 case CCValAssign::SExt: 2347 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg); 2348 break; 2349 case CCValAssign::ZExt: 2350 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg); 2351 break; 2352 case CCValAssign::AExt: 2353 if (RegVT.is128BitVector()) { 2354 // Special case: passing MMX values in XMM registers. 2355 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 2356 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg); 2357 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg); 2358 } else 2359 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg); 2360 break; 2361 case CCValAssign::BCvt: 2362 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg); 2363 break; 2364 case CCValAssign::Indirect: { 2365 // Store the argument. 2366 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT()); 2367 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 2368 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot, 2369 MachinePointerInfo::getFixedStack(FI), 2370 false, false, 0); 2371 Arg = SpillSlot; 2372 break; 2373 } 2374 } 2375 2376 if (VA.isRegLoc()) { 2377 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2378 if (isVarArg && IsWin64) { 2379 // Win64 ABI requires argument XMM reg to be copied to the corresponding 2380 // shadow reg if callee is a varargs function. 2381 unsigned ShadowReg = 0; 2382 switch (VA.getLocReg()) { 2383 case X86::XMM0: ShadowReg = X86::RCX; break; 2384 case X86::XMM1: ShadowReg = X86::RDX; break; 2385 case X86::XMM2: ShadowReg = X86::R8; break; 2386 case X86::XMM3: ShadowReg = X86::R9; break; 2387 } 2388 if (ShadowReg) 2389 RegsToPass.push_back(std::make_pair(ShadowReg, Arg)); 2390 } 2391 } else if (!IsSibcall && (!isTailCall || isByVal)) { 2392 assert(VA.isMemLoc()); 2393 if (StackPtr.getNode() == 0) 2394 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 2395 getPointerTy()); 2396 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg, 2397 dl, DAG, VA, Flags)); 2398 } 2399 } 2400 2401 if (!MemOpChains.empty()) 2402 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2403 &MemOpChains[0], MemOpChains.size()); 2404 2405 if (Subtarget->isPICStyleGOT()) { 2406 // ELF / PIC requires GOT in the EBX register before function calls via PLT 2407 // GOT pointer. 2408 if (!isTailCall) { 2409 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX), 2410 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy()))); 2411 } else { 2412 // If we are tail calling and generating PIC/GOT style code load the 2413 // address of the callee into ECX. The value in ecx is used as target of 2414 // the tail jump. This is done to circumvent the ebx/callee-saved problem 2415 // for tail calls on PIC/GOT architectures. Normally we would just put the 2416 // address of GOT into ebx and then call target@PLT. But for tail calls 2417 // ebx would be restored (since ebx is callee saved) before jumping to the 2418 // target@PLT. 2419 2420 // Note: The actual moving to ECX is done further down. 2421 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 2422 if (G && !G->getGlobal()->hasHiddenVisibility() && 2423 !G->getGlobal()->hasProtectedVisibility()) 2424 Callee = LowerGlobalAddress(Callee, DAG); 2425 else if (isa<ExternalSymbolSDNode>(Callee)) 2426 Callee = LowerExternalSymbol(Callee, DAG); 2427 } 2428 } 2429 2430 if (Is64Bit && isVarArg && !IsWin64) { 2431 // From AMD64 ABI document: 2432 // For calls that may call functions that use varargs or stdargs 2433 // (prototype-less calls or calls to functions containing ellipsis (...) in 2434 // the declaration) %al is used as hidden argument to specify the number 2435 // of SSE registers used. The contents of %al do not need to match exactly 2436 // the number of registers, but must be an ubound on the number of SSE 2437 // registers used and is in the range 0 - 8 inclusive. 2438 2439 // Count the number of XMM registers allocated. 2440 static const uint16_t XMMArgRegs[] = { 2441 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3, 2442 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7 2443 }; 2444 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8); 2445 assert((Subtarget->hasSSE1() || !NumXMMRegs) 2446 && "SSE registers cannot be used when SSE is disabled"); 2447 2448 RegsToPass.push_back(std::make_pair(unsigned(X86::AL), 2449 DAG.getConstant(NumXMMRegs, MVT::i8))); 2450 } 2451 2452 // For tail calls lower the arguments to the 'real' stack slot. 2453 if (isTailCall) { 2454 // Force all the incoming stack arguments to be loaded from the stack 2455 // before any new outgoing arguments are stored to the stack, because the 2456 // outgoing stack slots may alias the incoming argument stack slots, and 2457 // the alias isn't otherwise explicit. This is slightly more conservative 2458 // than necessary, because it means that each store effectively depends 2459 // on every argument instead of just those arguments it would clobber. 2460 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain); 2461 2462 SmallVector<SDValue, 8> MemOpChains2; 2463 SDValue FIN; 2464 int FI = 0; 2465 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2466 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2467 CCValAssign &VA = ArgLocs[i]; 2468 if (VA.isRegLoc()) 2469 continue; 2470 assert(VA.isMemLoc()); 2471 SDValue Arg = OutVals[i]; 2472 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2473 // Create frame index. 2474 int32_t Offset = VA.getLocMemOffset()+FPDiff; 2475 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8; 2476 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); 2477 FIN = DAG.getFrameIndex(FI, getPointerTy()); 2478 2479 if (Flags.isByVal()) { 2480 // Copy relative to framepointer. 2481 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset()); 2482 if (StackPtr.getNode() == 0) 2483 StackPtr = DAG.getCopyFromReg(Chain, dl, 2484 RegInfo->getStackRegister(), 2485 getPointerTy()); 2486 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source); 2487 2488 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, 2489 ArgChain, 2490 Flags, DAG, dl)); 2491 } else { 2492 // Store relative to framepointer. 2493 MemOpChains2.push_back( 2494 DAG.getStore(ArgChain, dl, Arg, FIN, 2495 MachinePointerInfo::getFixedStack(FI), 2496 false, false, 0)); 2497 } 2498 } 2499 } 2500 2501 if (!MemOpChains2.empty()) 2502 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 2503 &MemOpChains2[0], MemOpChains2.size()); 2504 2505 // Store the return address to the appropriate stack slot. 2506 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, 2507 getPointerTy(), RegInfo->getSlotSize(), 2508 FPDiff, dl); 2509 } 2510 2511 // Build a sequence of copy-to-reg nodes chained together with token chain 2512 // and flag operands which copy the outgoing args into registers. 2513 SDValue InFlag; 2514 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 2515 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 2516 RegsToPass[i].second, InFlag); 2517 InFlag = Chain.getValue(1); 2518 } 2519 2520 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 2521 assert(Is64Bit && "Large code model is only legal in 64-bit mode."); 2522 // In the 64-bit large code model, we have to make all calls 2523 // through a register, since the call instruction's 32-bit 2524 // pc-relative offset may not be large enough to hold the whole 2525 // address. 2526 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2527 // If the callee is a GlobalAddress node (quite common, every direct call 2528 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack 2529 // it. 2530 2531 // We should use extra load for direct calls to dllimported functions in 2532 // non-JIT mode. 2533 const GlobalValue *GV = G->getGlobal(); 2534 if (!GV->hasDLLImportLinkage()) { 2535 unsigned char OpFlags = 0; 2536 bool ExtraLoad = false; 2537 unsigned WrapperKind = ISD::DELETED_NODE; 2538 2539 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to 2540 // external symbols most go through the PLT in PIC mode. If the symbol 2541 // has hidden or protected visibility, or if it is static or local, then 2542 // we don't need to use the PLT - we can directly call it. 2543 if (Subtarget->isTargetELF() && 2544 getTargetMachine().getRelocationModel() == Reloc::PIC_ && 2545 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) { 2546 OpFlags = X86II::MO_PLT; 2547 } else if (Subtarget->isPICStyleStubAny() && 2548 (GV->isDeclaration() || GV->isWeakForLinker()) && 2549 (!Subtarget->getTargetTriple().isMacOSX() || 2550 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2551 // PC-relative references to external symbols should go through $stub, 2552 // unless we're building with the leopard linker or later, which 2553 // automatically synthesizes these stubs. 2554 OpFlags = X86II::MO_DARWIN_STUB; 2555 } else if (Subtarget->isPICStyleRIPRel() && 2556 isa<Function>(GV) && 2557 cast<Function>(GV)->getAttributes(). 2558 hasAttribute(AttributeSet::FunctionIndex, 2559 Attribute::NonLazyBind)) { 2560 // If the function is marked as non-lazy, generate an indirect call 2561 // which loads from the GOT directly. This avoids runtime overhead 2562 // at the cost of eager binding (and one extra byte of encoding). 2563 OpFlags = X86II::MO_GOTPCREL; 2564 WrapperKind = X86ISD::WrapperRIP; 2565 ExtraLoad = true; 2566 } 2567 2568 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 2569 G->getOffset(), OpFlags); 2570 2571 // Add a wrapper if needed. 2572 if (WrapperKind != ISD::DELETED_NODE) 2573 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee); 2574 // Add extra indirection if needed. 2575 if (ExtraLoad) 2576 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee, 2577 MachinePointerInfo::getGOT(), 2578 false, false, false, 0); 2579 } 2580 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 2581 unsigned char OpFlags = 0; 2582 2583 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to 2584 // external symbols should go through the PLT. 2585 if (Subtarget->isTargetELF() && 2586 getTargetMachine().getRelocationModel() == Reloc::PIC_) { 2587 OpFlags = X86II::MO_PLT; 2588 } else if (Subtarget->isPICStyleStubAny() && 2589 (!Subtarget->getTargetTriple().isMacOSX() || 2590 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) { 2591 // PC-relative references to external symbols should go through $stub, 2592 // unless we're building with the leopard linker or later, which 2593 // automatically synthesizes these stubs. 2594 OpFlags = X86II::MO_DARWIN_STUB; 2595 } 2596 2597 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(), 2598 OpFlags); 2599 } 2600 2601 // Returns a chain & a flag for retval copy to use. 2602 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2603 SmallVector<SDValue, 8> Ops; 2604 2605 if (!IsSibcall && isTailCall) { 2606 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true), 2607 DAG.getIntPtrConstant(0, true), InFlag); 2608 InFlag = Chain.getValue(1); 2609 } 2610 2611 Ops.push_back(Chain); 2612 Ops.push_back(Callee); 2613 2614 if (isTailCall) 2615 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32)); 2616 2617 // Add argument registers to the end of the list so that they are known live 2618 // into the call. 2619 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 2620 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 2621 RegsToPass[i].second.getValueType())); 2622 2623 // Add a register mask operand representing the call-preserved registers. 2624 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo(); 2625 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv); 2626 assert(Mask && "Missing call preserved mask for calling convention"); 2627 Ops.push_back(DAG.getRegisterMask(Mask)); 2628 2629 if (InFlag.getNode()) 2630 Ops.push_back(InFlag); 2631 2632 if (isTailCall) { 2633 // We used to do: 2634 //// If this is the first return lowered for this function, add the regs 2635 //// to the liveout set for the function. 2636 // This isn't right, although it's probably harmless on x86; liveouts 2637 // should be computed from returns not tail calls. Consider a void 2638 // function making a tail call to a function returning int. 2639 return DAG.getNode(X86ISD::TC_RETURN, dl, 2640 NodeTys, &Ops[0], Ops.size()); 2641 } 2642 2643 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size()); 2644 InFlag = Chain.getValue(1); 2645 2646 // Create the CALLSEQ_END node. 2647 unsigned NumBytesForCalleeToPush; 2648 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, 2649 getTargetMachine().Options.GuaranteedTailCallOpt)) 2650 NumBytesForCalleeToPush = NumBytes; // Callee pops everything 2651 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows && 2652 SR == StackStructReturn) 2653 // If this is a call to a struct-return function, the callee 2654 // pops the hidden struct pointer, so we have to push it back. 2655 // This is common for Darwin/X86, Linux & Mingw32 targets. 2656 // For MSVC Win32 targets, the caller pops the hidden struct pointer. 2657 NumBytesForCalleeToPush = 4; 2658 else 2659 NumBytesForCalleeToPush = 0; // Callee pops nothing. 2660 2661 // Returns a flag for retval copy to use. 2662 if (!IsSibcall) { 2663 Chain = DAG.getCALLSEQ_END(Chain, 2664 DAG.getIntPtrConstant(NumBytes, true), 2665 DAG.getIntPtrConstant(NumBytesForCalleeToPush, 2666 true), 2667 InFlag); 2668 InFlag = Chain.getValue(1); 2669 } 2670 2671 // Handle result values, copying them out of physregs into vregs that we 2672 // return. 2673 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 2674 Ins, dl, DAG, InVals); 2675} 2676 2677//===----------------------------------------------------------------------===// 2678// Fast Calling Convention (tail call) implementation 2679//===----------------------------------------------------------------------===// 2680 2681// Like std call, callee cleans arguments, convention except that ECX is 2682// reserved for storing the tail called function address. Only 2 registers are 2683// free for argument passing (inreg). Tail call optimization is performed 2684// provided: 2685// * tailcallopt is enabled 2686// * caller/callee are fastcc 2687// On X86_64 architecture with GOT-style position independent code only local 2688// (within module) calls are supported at the moment. 2689// To keep the stack aligned according to platform abi the function 2690// GetAlignedArgumentStackSize ensures that argument delta is always multiples 2691// of stack alignment. (Dynamic linkers need this - darwin's dyld for example) 2692// If a tail called function callee has more arguments than the caller the 2693// caller needs to make sure that there is room to move the RETADDR to. This is 2694// achieved by reserving an area the size of the argument delta right after the 2695// original REtADDR, but before the saved framepointer or the spilled registers 2696// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4) 2697// stack layout: 2698// arg1 2699// arg2 2700// RETADDR 2701// [ new RETADDR 2702// move area ] 2703// (possible EBP) 2704// ESI 2705// EDI 2706// local1 .. 2707 2708/// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned 2709/// for a 16 byte align requirement. 2710unsigned 2711X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 2712 SelectionDAG& DAG) const { 2713 MachineFunction &MF = DAG.getMachineFunction(); 2714 const TargetMachine &TM = MF.getTarget(); 2715 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 2716 unsigned StackAlignment = TFI.getStackAlignment(); 2717 uint64_t AlignMask = StackAlignment - 1; 2718 int64_t Offset = StackSize; 2719 unsigned SlotSize = RegInfo->getSlotSize(); 2720 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) { 2721 // Number smaller than 12 so just add the difference. 2722 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask)); 2723 } else { 2724 // Mask out lower bits, add stackalignment once plus the 12 bytes. 2725 Offset = ((~AlignMask) & Offset) + StackAlignment + 2726 (StackAlignment-SlotSize); 2727 } 2728 return Offset; 2729} 2730 2731/// MatchingStackOffset - Return true if the given stack call argument is 2732/// already available in the same position (relatively) of the caller's 2733/// incoming argument stack. 2734static 2735bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags, 2736 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI, 2737 const X86InstrInfo *TII) { 2738 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8; 2739 int FI = INT_MAX; 2740 if (Arg.getOpcode() == ISD::CopyFromReg) { 2741 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg(); 2742 if (!TargetRegisterInfo::isVirtualRegister(VR)) 2743 return false; 2744 MachineInstr *Def = MRI->getVRegDef(VR); 2745 if (!Def) 2746 return false; 2747 if (!Flags.isByVal()) { 2748 if (!TII->isLoadFromStackSlot(Def, FI)) 2749 return false; 2750 } else { 2751 unsigned Opcode = Def->getOpcode(); 2752 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) && 2753 Def->getOperand(1).isFI()) { 2754 FI = Def->getOperand(1).getIndex(); 2755 Bytes = Flags.getByValSize(); 2756 } else 2757 return false; 2758 } 2759 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) { 2760 if (Flags.isByVal()) 2761 // ByVal argument is passed in as a pointer but it's now being 2762 // dereferenced. e.g. 2763 // define @foo(%struct.X* %A) { 2764 // tail call @bar(%struct.X* byval %A) 2765 // } 2766 return false; 2767 SDValue Ptr = Ld->getBasePtr(); 2768 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr); 2769 if (!FINode) 2770 return false; 2771 FI = FINode->getIndex(); 2772 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) { 2773 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg); 2774 FI = FINode->getIndex(); 2775 Bytes = Flags.getByValSize(); 2776 } else 2777 return false; 2778 2779 assert(FI != INT_MAX); 2780 if (!MFI->isFixedObjectIndex(FI)) 2781 return false; 2782 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI); 2783} 2784 2785/// IsEligibleForTailCallOptimization - Check whether the call is eligible 2786/// for tail call optimization. Targets which want to do tail call 2787/// optimization should implement this function. 2788bool 2789X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 2790 CallingConv::ID CalleeCC, 2791 bool isVarArg, 2792 bool isCalleeStructRet, 2793 bool isCallerStructRet, 2794 Type *RetTy, 2795 const SmallVectorImpl<ISD::OutputArg> &Outs, 2796 const SmallVectorImpl<SDValue> &OutVals, 2797 const SmallVectorImpl<ISD::InputArg> &Ins, 2798 SelectionDAG& DAG) const { 2799 if (!IsTailCallConvention(CalleeCC) && 2800 CalleeCC != CallingConv::C) 2801 return false; 2802 2803 // If -tailcallopt is specified, make fastcc functions tail-callable. 2804 const MachineFunction &MF = DAG.getMachineFunction(); 2805 const Function *CallerF = DAG.getMachineFunction().getFunction(); 2806 2807 // If the function return type is x86_fp80 and the callee return type is not, 2808 // then the FP_EXTEND of the call result is not a nop. It's not safe to 2809 // perform a tailcall optimization here. 2810 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty()) 2811 return false; 2812 2813 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2814 bool CCMatch = CallerCC == CalleeCC; 2815 2816 if (getTargetMachine().Options.GuaranteedTailCallOpt) { 2817 if (IsTailCallConvention(CalleeCC) && CCMatch) 2818 return true; 2819 return false; 2820 } 2821 2822 // Look for obvious safe cases to perform tail call optimization that do not 2823 // require ABI changes. This is what gcc calls sibcall. 2824 2825 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to 2826 // emit a special epilogue. 2827 if (RegInfo->needsStackRealignment(MF)) 2828 return false; 2829 2830 // Also avoid sibcall optimization if either caller or callee uses struct 2831 // return semantics. 2832 if (isCalleeStructRet || isCallerStructRet) 2833 return false; 2834 2835 // An stdcall caller is expected to clean up its arguments; the callee 2836 // isn't going to do that. 2837 if (!CCMatch && CallerCC==CallingConv::X86_StdCall) 2838 return false; 2839 2840 // Do not sibcall optimize vararg calls unless all arguments are passed via 2841 // registers. 2842 if (isVarArg && !Outs.empty()) { 2843 2844 // Optimizing for varargs on Win64 is unlikely to be safe without 2845 // additional testing. 2846 if (Subtarget->isTargetWin64()) 2847 return false; 2848 2849 SmallVector<CCValAssign, 16> ArgLocs; 2850 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2851 getTargetMachine(), ArgLocs, *DAG.getContext()); 2852 2853 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2854 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) 2855 if (!ArgLocs[i].isRegLoc()) 2856 return false; 2857 } 2858 2859 // If the call result is in ST0 / ST1, it needs to be popped off the x87 2860 // stack. Therefore, if it's not used by the call it is not safe to optimize 2861 // this into a sibcall. 2862 bool Unused = false; 2863 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 2864 if (!Ins[i].Used) { 2865 Unused = true; 2866 break; 2867 } 2868 } 2869 if (Unused) { 2870 SmallVector<CCValAssign, 16> RVLocs; 2871 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), 2872 getTargetMachine(), RVLocs, *DAG.getContext()); 2873 CCInfo.AnalyzeCallResult(Ins, RetCC_X86); 2874 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 2875 CCValAssign &VA = RVLocs[i]; 2876 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) 2877 return false; 2878 } 2879 } 2880 2881 // If the calling conventions do not match, then we'd better make sure the 2882 // results are returned in the same way as what the caller expects. 2883 if (!CCMatch) { 2884 SmallVector<CCValAssign, 16> RVLocs1; 2885 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), 2886 getTargetMachine(), RVLocs1, *DAG.getContext()); 2887 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86); 2888 2889 SmallVector<CCValAssign, 16> RVLocs2; 2890 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), 2891 getTargetMachine(), RVLocs2, *DAG.getContext()); 2892 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86); 2893 2894 if (RVLocs1.size() != RVLocs2.size()) 2895 return false; 2896 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) { 2897 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc()) 2898 return false; 2899 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo()) 2900 return false; 2901 if (RVLocs1[i].isRegLoc()) { 2902 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg()) 2903 return false; 2904 } else { 2905 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset()) 2906 return false; 2907 } 2908 } 2909 } 2910 2911 // If the callee takes no arguments then go on to check the results of the 2912 // call. 2913 if (!Outs.empty()) { 2914 // Check if stack adjustment is needed. For now, do not do this if any 2915 // argument is passed on the stack. 2916 SmallVector<CCValAssign, 16> ArgLocs; 2917 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), 2918 getTargetMachine(), ArgLocs, *DAG.getContext()); 2919 2920 // Allocate shadow area for Win64 2921 if (Subtarget->isTargetWin64()) { 2922 CCInfo.AllocateStack(32, 8); 2923 } 2924 2925 CCInfo.AnalyzeCallOperands(Outs, CC_X86); 2926 if (CCInfo.getNextStackOffset()) { 2927 MachineFunction &MF = DAG.getMachineFunction(); 2928 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) 2929 return false; 2930 2931 // Check if the arguments are already laid out in the right way as 2932 // the caller's fixed stack objects. 2933 MachineFrameInfo *MFI = MF.getFrameInfo(); 2934 const MachineRegisterInfo *MRI = &MF.getRegInfo(); 2935 const X86InstrInfo *TII = 2936 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo(); 2937 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2938 CCValAssign &VA = ArgLocs[i]; 2939 SDValue Arg = OutVals[i]; 2940 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2941 if (VA.getLocInfo() == CCValAssign::Indirect) 2942 return false; 2943 if (!VA.isRegLoc()) { 2944 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags, 2945 MFI, MRI, TII)) 2946 return false; 2947 } 2948 } 2949 } 2950 2951 // If the tailcall address may be in a register, then make sure it's 2952 // possible to register allocate for it. In 32-bit, the call address can 2953 // only target EAX, EDX, or ECX since the tail call must be scheduled after 2954 // callee-saved registers are restored. These happen to be the same 2955 // registers used to pass 'inreg' arguments so watch out for those. 2956 if (!Subtarget->is64Bit() && 2957 !isa<GlobalAddressSDNode>(Callee) && 2958 !isa<ExternalSymbolSDNode>(Callee)) { 2959 unsigned NumInRegs = 0; 2960 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2961 CCValAssign &VA = ArgLocs[i]; 2962 if (!VA.isRegLoc()) 2963 continue; 2964 unsigned Reg = VA.getLocReg(); 2965 switch (Reg) { 2966 default: break; 2967 case X86::EAX: case X86::EDX: case X86::ECX: 2968 if (++NumInRegs == 3) 2969 return false; 2970 break; 2971 } 2972 } 2973 } 2974 } 2975 2976 return true; 2977} 2978 2979FastISel * 2980X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 2981 const TargetLibraryInfo *libInfo) const { 2982 return X86::createFastISel(funcInfo, libInfo); 2983} 2984 2985//===----------------------------------------------------------------------===// 2986// Other Lowering Hooks 2987//===----------------------------------------------------------------------===// 2988 2989static bool MayFoldLoad(SDValue Op) { 2990 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode()); 2991} 2992 2993static bool MayFoldIntoStore(SDValue Op) { 2994 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin()); 2995} 2996 2997static bool isTargetShuffle(unsigned Opcode) { 2998 switch(Opcode) { 2999 default: return false; 3000 case X86ISD::PSHUFD: 3001 case X86ISD::PSHUFHW: 3002 case X86ISD::PSHUFLW: 3003 case X86ISD::SHUFP: 3004 case X86ISD::PALIGN: 3005 case X86ISD::MOVLHPS: 3006 case X86ISD::MOVLHPD: 3007 case X86ISD::MOVHLPS: 3008 case X86ISD::MOVLPS: 3009 case X86ISD::MOVLPD: 3010 case X86ISD::MOVSHDUP: 3011 case X86ISD::MOVSLDUP: 3012 case X86ISD::MOVDDUP: 3013 case X86ISD::MOVSS: 3014 case X86ISD::MOVSD: 3015 case X86ISD::UNPCKL: 3016 case X86ISD::UNPCKH: 3017 case X86ISD::VPERMILP: 3018 case X86ISD::VPERM2X128: 3019 case X86ISD::VPERMI: 3020 return true; 3021 } 3022} 3023 3024static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 3025 SDValue V1, SelectionDAG &DAG) { 3026 switch(Opc) { 3027 default: llvm_unreachable("Unknown x86 shuffle node"); 3028 case X86ISD::MOVSHDUP: 3029 case X86ISD::MOVSLDUP: 3030 case X86ISD::MOVDDUP: 3031 return DAG.getNode(Opc, dl, VT, V1); 3032 } 3033} 3034 3035static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 3036 SDValue V1, unsigned TargetMask, 3037 SelectionDAG &DAG) { 3038 switch(Opc) { 3039 default: llvm_unreachable("Unknown x86 shuffle node"); 3040 case X86ISD::PSHUFD: 3041 case X86ISD::PSHUFHW: 3042 case X86ISD::PSHUFLW: 3043 case X86ISD::VPERMILP: 3044 case X86ISD::VPERMI: 3045 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8)); 3046 } 3047} 3048 3049static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 3050 SDValue V1, SDValue V2, unsigned TargetMask, 3051 SelectionDAG &DAG) { 3052 switch(Opc) { 3053 default: llvm_unreachable("Unknown x86 shuffle node"); 3054 case X86ISD::PALIGN: 3055 case X86ISD::SHUFP: 3056 case X86ISD::VPERM2X128: 3057 return DAG.getNode(Opc, dl, VT, V1, V2, 3058 DAG.getConstant(TargetMask, MVT::i8)); 3059 } 3060} 3061 3062static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT, 3063 SDValue V1, SDValue V2, SelectionDAG &DAG) { 3064 switch(Opc) { 3065 default: llvm_unreachable("Unknown x86 shuffle node"); 3066 case X86ISD::MOVLHPS: 3067 case X86ISD::MOVLHPD: 3068 case X86ISD::MOVHLPS: 3069 case X86ISD::MOVLPS: 3070 case X86ISD::MOVLPD: 3071 case X86ISD::MOVSS: 3072 case X86ISD::MOVSD: 3073 case X86ISD::UNPCKL: 3074 case X86ISD::UNPCKH: 3075 return DAG.getNode(Opc, dl, VT, V1, V2); 3076 } 3077} 3078 3079SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const { 3080 MachineFunction &MF = DAG.getMachineFunction(); 3081 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 3082 int ReturnAddrIndex = FuncInfo->getRAIndex(); 3083 3084 if (ReturnAddrIndex == 0) { 3085 // Set up a frame object for the return address. 3086 unsigned SlotSize = RegInfo->getSlotSize(); 3087 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize, 3088 false); 3089 FuncInfo->setRAIndex(ReturnAddrIndex); 3090 } 3091 3092 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy()); 3093} 3094 3095bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, 3096 bool hasSymbolicDisplacement) { 3097 // Offset should fit into 32 bit immediate field. 3098 if (!isInt<32>(Offset)) 3099 return false; 3100 3101 // If we don't have a symbolic displacement - we don't have any extra 3102 // restrictions. 3103 if (!hasSymbolicDisplacement) 3104 return true; 3105 3106 // FIXME: Some tweaks might be needed for medium code model. 3107 if (M != CodeModel::Small && M != CodeModel::Kernel) 3108 return false; 3109 3110 // For small code model we assume that latest object is 16MB before end of 31 3111 // bits boundary. We may also accept pretty large negative constants knowing 3112 // that all objects are in the positive half of address space. 3113 if (M == CodeModel::Small && Offset < 16*1024*1024) 3114 return true; 3115 3116 // For kernel code model we know that all object resist in the negative half 3117 // of 32bits address space. We may not accept negative offsets, since they may 3118 // be just off and we may accept pretty large positive ones. 3119 if (M == CodeModel::Kernel && Offset > 0) 3120 return true; 3121 3122 return false; 3123} 3124 3125/// isCalleePop - Determines whether the callee is required to pop its 3126/// own arguments. Callee pop is necessary to support tail calls. 3127bool X86::isCalleePop(CallingConv::ID CallingConv, 3128 bool is64Bit, bool IsVarArg, bool TailCallOpt) { 3129 if (IsVarArg) 3130 return false; 3131 3132 switch (CallingConv) { 3133 default: 3134 return false; 3135 case CallingConv::X86_StdCall: 3136 return !is64Bit; 3137 case CallingConv::X86_FastCall: 3138 return !is64Bit; 3139 case CallingConv::X86_ThisCall: 3140 return !is64Bit; 3141 case CallingConv::Fast: 3142 return TailCallOpt; 3143 case CallingConv::GHC: 3144 return TailCallOpt; 3145 case CallingConv::HiPE: 3146 return TailCallOpt; 3147 } 3148} 3149 3150/// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86 3151/// specific condition code, returning the condition code and the LHS/RHS of the 3152/// comparison to make. 3153static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP, 3154 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) { 3155 if (!isFP) { 3156 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 3157 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) { 3158 // X > -1 -> X == 0, jump !sign. 3159 RHS = DAG.getConstant(0, RHS.getValueType()); 3160 return X86::COND_NS; 3161 } 3162 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) { 3163 // X < 0 -> X == 0, jump on sign. 3164 return X86::COND_S; 3165 } 3166 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) { 3167 // X < 1 -> X <= 0 3168 RHS = DAG.getConstant(0, RHS.getValueType()); 3169 return X86::COND_LE; 3170 } 3171 } 3172 3173 switch (SetCCOpcode) { 3174 default: llvm_unreachable("Invalid integer condition!"); 3175 case ISD::SETEQ: return X86::COND_E; 3176 case ISD::SETGT: return X86::COND_G; 3177 case ISD::SETGE: return X86::COND_GE; 3178 case ISD::SETLT: return X86::COND_L; 3179 case ISD::SETLE: return X86::COND_LE; 3180 case ISD::SETNE: return X86::COND_NE; 3181 case ISD::SETULT: return X86::COND_B; 3182 case ISD::SETUGT: return X86::COND_A; 3183 case ISD::SETULE: return X86::COND_BE; 3184 case ISD::SETUGE: return X86::COND_AE; 3185 } 3186 } 3187 3188 // First determine if it is required or is profitable to flip the operands. 3189 3190 // If LHS is a foldable load, but RHS is not, flip the condition. 3191 if (ISD::isNON_EXTLoad(LHS.getNode()) && 3192 !ISD::isNON_EXTLoad(RHS.getNode())) { 3193 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode); 3194 std::swap(LHS, RHS); 3195 } 3196 3197 switch (SetCCOpcode) { 3198 default: break; 3199 case ISD::SETOLT: 3200 case ISD::SETOLE: 3201 case ISD::SETUGT: 3202 case ISD::SETUGE: 3203 std::swap(LHS, RHS); 3204 break; 3205 } 3206 3207 // On a floating point condition, the flags are set as follows: 3208 // ZF PF CF op 3209 // 0 | 0 | 0 | X > Y 3210 // 0 | 0 | 1 | X < Y 3211 // 1 | 0 | 0 | X == Y 3212 // 1 | 1 | 1 | unordered 3213 switch (SetCCOpcode) { 3214 default: llvm_unreachable("Condcode should be pre-legalized away"); 3215 case ISD::SETUEQ: 3216 case ISD::SETEQ: return X86::COND_E; 3217 case ISD::SETOLT: // flipped 3218 case ISD::SETOGT: 3219 case ISD::SETGT: return X86::COND_A; 3220 case ISD::SETOLE: // flipped 3221 case ISD::SETOGE: 3222 case ISD::SETGE: return X86::COND_AE; 3223 case ISD::SETUGT: // flipped 3224 case ISD::SETULT: 3225 case ISD::SETLT: return X86::COND_B; 3226 case ISD::SETUGE: // flipped 3227 case ISD::SETULE: 3228 case ISD::SETLE: return X86::COND_BE; 3229 case ISD::SETONE: 3230 case ISD::SETNE: return X86::COND_NE; 3231 case ISD::SETUO: return X86::COND_P; 3232 case ISD::SETO: return X86::COND_NP; 3233 case ISD::SETOEQ: 3234 case ISD::SETUNE: return X86::COND_INVALID; 3235 } 3236} 3237 3238/// hasFPCMov - is there a floating point cmov for the specific X86 condition 3239/// code. Current x86 isa includes the following FP cmov instructions: 3240/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu. 3241static bool hasFPCMov(unsigned X86CC) { 3242 switch (X86CC) { 3243 default: 3244 return false; 3245 case X86::COND_B: 3246 case X86::COND_BE: 3247 case X86::COND_E: 3248 case X86::COND_P: 3249 case X86::COND_A: 3250 case X86::COND_AE: 3251 case X86::COND_NE: 3252 case X86::COND_NP: 3253 return true; 3254 } 3255} 3256 3257/// isFPImmLegal - Returns true if the target can instruction select the 3258/// specified FP immediate natively. If false, the legalizer will 3259/// materialize the FP immediate as a load from a constant pool. 3260bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 3261 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) { 3262 if (Imm.bitwiseIsEqual(LegalFPImmediates[i])) 3263 return true; 3264 } 3265 return false; 3266} 3267 3268/// isUndefOrInRange - Return true if Val is undef or if its value falls within 3269/// the specified range (L, H]. 3270static bool isUndefOrInRange(int Val, int Low, int Hi) { 3271 return (Val < 0) || (Val >= Low && Val < Hi); 3272} 3273 3274/// isUndefOrEqual - Val is either less than zero (undef) or equal to the 3275/// specified value. 3276static bool isUndefOrEqual(int Val, int CmpVal) { 3277 return (Val < 0 || Val == CmpVal); 3278} 3279 3280/// isSequentialOrUndefInRange - Return true if every element in Mask, beginning 3281/// from position Pos and ending in Pos+Size, falls within the specified 3282/// sequential range (L, L+Pos]. or is undef. 3283static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, 3284 unsigned Pos, unsigned Size, int Low) { 3285 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 3286 if (!isUndefOrEqual(Mask[i], Low)) 3287 return false; 3288 return true; 3289} 3290 3291/// isPSHUFDMask - Return true if the node specifies a shuffle of elements that 3292/// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference 3293/// the second operand. 3294static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) { 3295 if (VT == MVT::v4f32 || VT == MVT::v4i32 ) 3296 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4); 3297 if (VT == MVT::v2f64 || VT == MVT::v2i64) 3298 return (Mask[0] < 2 && Mask[1] < 2); 3299 return false; 3300} 3301 3302/// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that 3303/// is suitable for input to PSHUFHW. 3304static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3305 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3306 return false; 3307 3308 // Lower quadword copied in order or undef. 3309 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0)) 3310 return false; 3311 3312 // Upper quadword shuffled. 3313 for (unsigned i = 4; i != 8; ++i) 3314 if (!isUndefOrInRange(Mask[i], 4, 8)) 3315 return false; 3316 3317 if (VT == MVT::v16i16) { 3318 // Lower quadword copied in order or undef. 3319 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8)) 3320 return false; 3321 3322 // Upper quadword shuffled. 3323 for (unsigned i = 12; i != 16; ++i) 3324 if (!isUndefOrInRange(Mask[i], 12, 16)) 3325 return false; 3326 } 3327 3328 return true; 3329} 3330 3331/// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that 3332/// is suitable for input to PSHUFLW. 3333static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3334 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16)) 3335 return false; 3336 3337 // Upper quadword copied in order. 3338 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4)) 3339 return false; 3340 3341 // Lower quadword shuffled. 3342 for (unsigned i = 0; i != 4; ++i) 3343 if (!isUndefOrInRange(Mask[i], 0, 4)) 3344 return false; 3345 3346 if (VT == MVT::v16i16) { 3347 // Upper quadword copied in order. 3348 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12)) 3349 return false; 3350 3351 // Lower quadword shuffled. 3352 for (unsigned i = 8; i != 12; ++i) 3353 if (!isUndefOrInRange(Mask[i], 8, 12)) 3354 return false; 3355 } 3356 3357 return true; 3358} 3359 3360/// isPALIGNRMask - Return true if the node specifies a shuffle of elements that 3361/// is suitable for input to PALIGNR. 3362static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT, 3363 const X86Subtarget *Subtarget) { 3364 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) || 3365 (VT.is256BitVector() && !Subtarget->hasInt256())) 3366 return false; 3367 3368 unsigned NumElts = VT.getVectorNumElements(); 3369 unsigned NumLanes = VT.getSizeInBits()/128; 3370 unsigned NumLaneElts = NumElts/NumLanes; 3371 3372 // Do not handle 64-bit element shuffles with palignr. 3373 if (NumLaneElts == 2) 3374 return false; 3375 3376 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) { 3377 unsigned i; 3378 for (i = 0; i != NumLaneElts; ++i) { 3379 if (Mask[i+l] >= 0) 3380 break; 3381 } 3382 3383 // Lane is all undef, go to next lane 3384 if (i == NumLaneElts) 3385 continue; 3386 3387 int Start = Mask[i+l]; 3388 3389 // Make sure its in this lane in one of the sources 3390 if (!isUndefOrInRange(Start, l, l+NumLaneElts) && 3391 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts)) 3392 return false; 3393 3394 // If not lane 0, then we must match lane 0 3395 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l)) 3396 return false; 3397 3398 // Correct second source to be contiguous with first source 3399 if (Start >= (int)NumElts) 3400 Start -= NumElts - NumLaneElts; 3401 3402 // Make sure we're shifting in the right direction. 3403 if (Start <= (int)(i+l)) 3404 return false; 3405 3406 Start -= i; 3407 3408 // Check the rest of the elements to see if they are consecutive. 3409 for (++i; i != NumLaneElts; ++i) { 3410 int Idx = Mask[i+l]; 3411 3412 // Make sure its in this lane 3413 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) && 3414 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts)) 3415 return false; 3416 3417 // If not lane 0, then we must match lane 0 3418 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l)) 3419 return false; 3420 3421 if (Idx >= (int)NumElts) 3422 Idx -= NumElts - NumLaneElts; 3423 3424 if (!isUndefOrEqual(Idx, Start+i)) 3425 return false; 3426 3427 } 3428 } 3429 3430 return true; 3431} 3432 3433/// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming 3434/// the two vector operands have swapped position. 3435static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, 3436 unsigned NumElems) { 3437 for (unsigned i = 0; i != NumElems; ++i) { 3438 int idx = Mask[i]; 3439 if (idx < 0) 3440 continue; 3441 else if (idx < (int)NumElems) 3442 Mask[i] = idx + NumElems; 3443 else 3444 Mask[i] = idx - NumElems; 3445 } 3446} 3447 3448/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand 3449/// specifies a shuffle of elements that is suitable for input to 128/256-bit 3450/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be 3451/// reverse of what x86 shuffles want. 3452static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256, 3453 bool Commuted = false) { 3454 if (!HasFp256 && VT.is256BitVector()) 3455 return false; 3456 3457 unsigned NumElems = VT.getVectorNumElements(); 3458 unsigned NumLanes = VT.getSizeInBits()/128; 3459 unsigned NumLaneElems = NumElems/NumLanes; 3460 3461 if (NumLaneElems != 2 && NumLaneElems != 4) 3462 return false; 3463 3464 // VSHUFPSY divides the resulting vector into 4 chunks. 3465 // The sources are also splitted into 4 chunks, and each destination 3466 // chunk must come from a different source chunk. 3467 // 3468 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0 3469 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9 3470 // 3471 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4, 3472 // Y3..Y0, Y3..Y0, X3..X0, X3..X0 3473 // 3474 // VSHUFPDY divides the resulting vector into 4 chunks. 3475 // The sources are also splitted into 4 chunks, and each destination 3476 // chunk must come from a different source chunk. 3477 // 3478 // SRC1 => X3 X2 X1 X0 3479 // SRC2 => Y3 Y2 Y1 Y0 3480 // 3481 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0 3482 // 3483 unsigned HalfLaneElems = NumLaneElems/2; 3484 for (unsigned l = 0; l != NumElems; l += NumLaneElems) { 3485 for (unsigned i = 0; i != NumLaneElems; ++i) { 3486 int Idx = Mask[i+l]; 3487 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0); 3488 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems)) 3489 return false; 3490 // For VSHUFPSY, the mask of the second half must be the same as the 3491 // first but with the appropriate offsets. This works in the same way as 3492 // VPERMILPS works with masks. 3493 if (NumElems != 8 || l == 0 || Mask[i] < 0) 3494 continue; 3495 if (!isUndefOrEqual(Idx, Mask[i]+l)) 3496 return false; 3497 } 3498 } 3499 3500 return true; 3501} 3502 3503/// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand 3504/// specifies a shuffle of elements that is suitable for input to MOVHLPS. 3505static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) { 3506 if (!VT.is128BitVector()) 3507 return false; 3508 3509 unsigned NumElems = VT.getVectorNumElements(); 3510 3511 if (NumElems != 4) 3512 return false; 3513 3514 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3 3515 return isUndefOrEqual(Mask[0], 6) && 3516 isUndefOrEqual(Mask[1], 7) && 3517 isUndefOrEqual(Mask[2], 2) && 3518 isUndefOrEqual(Mask[3], 3); 3519} 3520 3521/// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form 3522/// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef, 3523/// <2, 3, 2, 3> 3524static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) { 3525 if (!VT.is128BitVector()) 3526 return false; 3527 3528 unsigned NumElems = VT.getVectorNumElements(); 3529 3530 if (NumElems != 4) 3531 return false; 3532 3533 return isUndefOrEqual(Mask[0], 2) && 3534 isUndefOrEqual(Mask[1], 3) && 3535 isUndefOrEqual(Mask[2], 2) && 3536 isUndefOrEqual(Mask[3], 3); 3537} 3538 3539/// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand 3540/// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}. 3541static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) { 3542 if (!VT.is128BitVector()) 3543 return false; 3544 3545 unsigned NumElems = VT.getVectorNumElements(); 3546 3547 if (NumElems != 2 && NumElems != 4) 3548 return false; 3549 3550 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3551 if (!isUndefOrEqual(Mask[i], i + NumElems)) 3552 return false; 3553 3554 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 3555 if (!isUndefOrEqual(Mask[i], i)) 3556 return false; 3557 3558 return true; 3559} 3560 3561/// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand 3562/// specifies a shuffle of elements that is suitable for input to MOVLHPS. 3563static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) { 3564 if (!VT.is128BitVector()) 3565 return false; 3566 3567 unsigned NumElems = VT.getVectorNumElements(); 3568 3569 if (NumElems != 2 && NumElems != 4) 3570 return false; 3571 3572 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3573 if (!isUndefOrEqual(Mask[i], i)) 3574 return false; 3575 3576 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 3577 if (!isUndefOrEqual(Mask[i + e], i + NumElems)) 3578 return false; 3579 3580 return true; 3581} 3582 3583// 3584// Some special combinations that can be optimized. 3585// 3586static 3587SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp, 3588 SelectionDAG &DAG) { 3589 EVT VT = SVOp->getValueType(0); 3590 DebugLoc dl = SVOp->getDebugLoc(); 3591 3592 if (VT != MVT::v8i32 && VT != MVT::v8f32) 3593 return SDValue(); 3594 3595 ArrayRef<int> Mask = SVOp->getMask(); 3596 3597 // These are the special masks that may be optimized. 3598 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14}; 3599 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15}; 3600 bool MatchEvenMask = true; 3601 bool MatchOddMask = true; 3602 for (int i=0; i<8; ++i) { 3603 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i])) 3604 MatchEvenMask = false; 3605 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i])) 3606 MatchOddMask = false; 3607 } 3608 3609 if (!MatchEvenMask && !MatchOddMask) 3610 return SDValue(); 3611 3612 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT); 3613 3614 SDValue Op0 = SVOp->getOperand(0); 3615 SDValue Op1 = SVOp->getOperand(1); 3616 3617 if (MatchEvenMask) { 3618 // Shift the second operand right to 32 bits. 3619 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 }; 3620 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask); 3621 } else { 3622 // Shift the first operand left to 32 bits. 3623 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 }; 3624 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask); 3625 } 3626 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15}; 3627 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask); 3628} 3629 3630/// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand 3631/// specifies a shuffle of elements that is suitable for input to UNPCKL. 3632static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT, 3633 bool HasInt256, bool V2IsSplat = false) { 3634 unsigned NumElts = VT.getVectorNumElements(); 3635 3636 assert((VT.is128BitVector() || VT.is256BitVector()) && 3637 "Unsupported vector type for unpckh"); 3638 3639 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3640 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3641 return false; 3642 3643 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3644 // independently on 128-bit lanes. 3645 unsigned NumLanes = VT.getSizeInBits()/128; 3646 unsigned NumLaneElts = NumElts/NumLanes; 3647 3648 for (unsigned l = 0; l != NumLanes; ++l) { 3649 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3650 i != (l+1)*NumLaneElts; 3651 i += 2, ++j) { 3652 int BitI = Mask[i]; 3653 int BitI1 = Mask[i+1]; 3654 if (!isUndefOrEqual(BitI, j)) 3655 return false; 3656 if (V2IsSplat) { 3657 if (!isUndefOrEqual(BitI1, NumElts)) 3658 return false; 3659 } else { 3660 if (!isUndefOrEqual(BitI1, j + NumElts)) 3661 return false; 3662 } 3663 } 3664 } 3665 3666 return true; 3667} 3668 3669/// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand 3670/// specifies a shuffle of elements that is suitable for input to UNPCKH. 3671static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT, 3672 bool HasInt256, bool V2IsSplat = false) { 3673 unsigned NumElts = VT.getVectorNumElements(); 3674 3675 assert((VT.is128BitVector() || VT.is256BitVector()) && 3676 "Unsupported vector type for unpckh"); 3677 3678 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3679 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3680 return false; 3681 3682 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3683 // independently on 128-bit lanes. 3684 unsigned NumLanes = VT.getSizeInBits()/128; 3685 unsigned NumLaneElts = NumElts/NumLanes; 3686 3687 for (unsigned l = 0; l != NumLanes; ++l) { 3688 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3689 i != (l+1)*NumLaneElts; i += 2, ++j) { 3690 int BitI = Mask[i]; 3691 int BitI1 = Mask[i+1]; 3692 if (!isUndefOrEqual(BitI, j)) 3693 return false; 3694 if (V2IsSplat) { 3695 if (isUndefOrEqual(BitI1, NumElts)) 3696 return false; 3697 } else { 3698 if (!isUndefOrEqual(BitI1, j+NumElts)) 3699 return false; 3700 } 3701 } 3702 } 3703 return true; 3704} 3705 3706/// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form 3707/// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef, 3708/// <0, 0, 1, 1> 3709static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3710 unsigned NumElts = VT.getVectorNumElements(); 3711 bool Is256BitVec = VT.is256BitVector(); 3712 3713 assert((VT.is128BitVector() || VT.is256BitVector()) && 3714 "Unsupported vector type for unpckh"); 3715 3716 if (Is256BitVec && NumElts != 4 && NumElts != 8 && 3717 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3718 return false; 3719 3720 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern 3721 // FIXME: Need a better way to get rid of this, there's no latency difference 3722 // between UNPCKLPD and MOVDDUP, the later should always be checked first and 3723 // the former later. We should also remove the "_undef" special mask. 3724 if (NumElts == 4 && Is256BitVec) 3725 return false; 3726 3727 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3728 // independently on 128-bit lanes. 3729 unsigned NumLanes = VT.getSizeInBits()/128; 3730 unsigned NumLaneElts = NumElts/NumLanes; 3731 3732 for (unsigned l = 0; l != NumLanes; ++l) { 3733 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts; 3734 i != (l+1)*NumLaneElts; 3735 i += 2, ++j) { 3736 int BitI = Mask[i]; 3737 int BitI1 = Mask[i+1]; 3738 3739 if (!isUndefOrEqual(BitI, j)) 3740 return false; 3741 if (!isUndefOrEqual(BitI1, j)) 3742 return false; 3743 } 3744 } 3745 3746 return true; 3747} 3748 3749/// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form 3750/// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef, 3751/// <2, 2, 3, 3> 3752static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) { 3753 unsigned NumElts = VT.getVectorNumElements(); 3754 3755 assert((VT.is128BitVector() || VT.is256BitVector()) && 3756 "Unsupported vector type for unpckh"); 3757 3758 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 && 3759 (!HasInt256 || (NumElts != 16 && NumElts != 32))) 3760 return false; 3761 3762 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate 3763 // independently on 128-bit lanes. 3764 unsigned NumLanes = VT.getSizeInBits()/128; 3765 unsigned NumLaneElts = NumElts/NumLanes; 3766 3767 for (unsigned l = 0; l != NumLanes; ++l) { 3768 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2; 3769 i != (l+1)*NumLaneElts; i += 2, ++j) { 3770 int BitI = Mask[i]; 3771 int BitI1 = Mask[i+1]; 3772 if (!isUndefOrEqual(BitI, j)) 3773 return false; 3774 if (!isUndefOrEqual(BitI1, j)) 3775 return false; 3776 } 3777 } 3778 return true; 3779} 3780 3781/// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand 3782/// specifies a shuffle of elements that is suitable for input to MOVSS, 3783/// MOVSD, and MOVD, i.e. setting the lowest element. 3784static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) { 3785 if (VT.getVectorElementType().getSizeInBits() < 32) 3786 return false; 3787 if (!VT.is128BitVector()) 3788 return false; 3789 3790 unsigned NumElts = VT.getVectorNumElements(); 3791 3792 if (!isUndefOrEqual(Mask[0], NumElts)) 3793 return false; 3794 3795 for (unsigned i = 1; i != NumElts; ++i) 3796 if (!isUndefOrEqual(Mask[i], i)) 3797 return false; 3798 3799 return true; 3800} 3801 3802/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered 3803/// as permutations between 128-bit chunks or halves. As an example: this 3804/// shuffle bellow: 3805/// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15> 3806/// The first half comes from the second half of V1 and the second half from the 3807/// the second half of V2. 3808static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 3809 if (!HasFp256 || !VT.is256BitVector()) 3810 return false; 3811 3812 // The shuffle result is divided into half A and half B. In total the two 3813 // sources have 4 halves, namely: C, D, E, F. The final values of A and 3814 // B must come from C, D, E or F. 3815 unsigned HalfSize = VT.getVectorNumElements()/2; 3816 bool MatchA = false, MatchB = false; 3817 3818 // Check if A comes from one of C, D, E, F. 3819 for (unsigned Half = 0; Half != 4; ++Half) { 3820 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) { 3821 MatchA = true; 3822 break; 3823 } 3824 } 3825 3826 // Check if B comes from one of C, D, E, F. 3827 for (unsigned Half = 0; Half != 4; ++Half) { 3828 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) { 3829 MatchB = true; 3830 break; 3831 } 3832 } 3833 3834 return MatchA && MatchB; 3835} 3836 3837/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle 3838/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions. 3839static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) { 3840 EVT VT = SVOp->getValueType(0); 3841 3842 unsigned HalfSize = VT.getVectorNumElements()/2; 3843 3844 unsigned FstHalf = 0, SndHalf = 0; 3845 for (unsigned i = 0; i < HalfSize; ++i) { 3846 if (SVOp->getMaskElt(i) > 0) { 3847 FstHalf = SVOp->getMaskElt(i)/HalfSize; 3848 break; 3849 } 3850 } 3851 for (unsigned i = HalfSize; i < HalfSize*2; ++i) { 3852 if (SVOp->getMaskElt(i) > 0) { 3853 SndHalf = SVOp->getMaskElt(i)/HalfSize; 3854 break; 3855 } 3856 } 3857 3858 return (FstHalf | (SndHalf << 4)); 3859} 3860 3861/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand 3862/// specifies a shuffle of elements that is suitable for input to VPERMILPD*. 3863/// Note that VPERMIL mask matching is different depending whether theunderlying 3864/// type is 32 or 64. In the VPERMILPS the high half of the mask should point 3865/// to the same elements of the low, but to the higher half of the source. 3866/// In VPERMILPD the two lanes could be shuffled independently of each other 3867/// with the same restriction that lanes can't be crossed. Also handles PSHUFDY. 3868static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 3869 if (!HasFp256) 3870 return false; 3871 3872 unsigned NumElts = VT.getVectorNumElements(); 3873 // Only match 256-bit with 32/64-bit types 3874 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8)) 3875 return false; 3876 3877 unsigned NumLanes = VT.getSizeInBits()/128; 3878 unsigned LaneSize = NumElts/NumLanes; 3879 for (unsigned l = 0; l != NumElts; l += LaneSize) { 3880 for (unsigned i = 0; i != LaneSize; ++i) { 3881 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize)) 3882 return false; 3883 if (NumElts != 8 || l == 0) 3884 continue; 3885 // VPERMILPS handling 3886 if (Mask[i] < 0) 3887 continue; 3888 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l)) 3889 return false; 3890 } 3891 } 3892 3893 return true; 3894} 3895 3896/// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse 3897/// of what x86 movss want. X86 movs requires the lowest element to be lowest 3898/// element of vector 2 and the other elements to come from vector 1 in order. 3899static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT, 3900 bool V2IsSplat = false, bool V2IsUndef = false) { 3901 if (!VT.is128BitVector()) 3902 return false; 3903 3904 unsigned NumOps = VT.getVectorNumElements(); 3905 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16) 3906 return false; 3907 3908 if (!isUndefOrEqual(Mask[0], 0)) 3909 return false; 3910 3911 for (unsigned i = 1; i != NumOps; ++i) 3912 if (!(isUndefOrEqual(Mask[i], i+NumOps) || 3913 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) || 3914 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps)))) 3915 return false; 3916 3917 return true; 3918} 3919 3920/// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3921/// specifies a shuffle of elements that is suitable for input to MOVSHDUP. 3922/// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7> 3923static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT, 3924 const X86Subtarget *Subtarget) { 3925 if (!Subtarget->hasSSE3()) 3926 return false; 3927 3928 unsigned NumElems = VT.getVectorNumElements(); 3929 3930 if ((VT.is128BitVector() && NumElems != 4) || 3931 (VT.is256BitVector() && NumElems != 8)) 3932 return false; 3933 3934 // "i+1" is the value the indexed mask element must have 3935 for (unsigned i = 0; i != NumElems; i += 2) 3936 if (!isUndefOrEqual(Mask[i], i+1) || 3937 !isUndefOrEqual(Mask[i+1], i+1)) 3938 return false; 3939 3940 return true; 3941} 3942 3943/// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3944/// specifies a shuffle of elements that is suitable for input to MOVSLDUP. 3945/// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6> 3946static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT, 3947 const X86Subtarget *Subtarget) { 3948 if (!Subtarget->hasSSE3()) 3949 return false; 3950 3951 unsigned NumElems = VT.getVectorNumElements(); 3952 3953 if ((VT.is128BitVector() && NumElems != 4) || 3954 (VT.is256BitVector() && NumElems != 8)) 3955 return false; 3956 3957 // "i" is the value the indexed mask element must have 3958 for (unsigned i = 0; i != NumElems; i += 2) 3959 if (!isUndefOrEqual(Mask[i], i) || 3960 !isUndefOrEqual(Mask[i+1], i)) 3961 return false; 3962 3963 return true; 3964} 3965 3966/// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand 3967/// specifies a shuffle of elements that is suitable for input to 256-bit 3968/// version of MOVDDUP. 3969static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) { 3970 if (!HasFp256 || !VT.is256BitVector()) 3971 return false; 3972 3973 unsigned NumElts = VT.getVectorNumElements(); 3974 if (NumElts != 4) 3975 return false; 3976 3977 for (unsigned i = 0; i != NumElts/2; ++i) 3978 if (!isUndefOrEqual(Mask[i], 0)) 3979 return false; 3980 for (unsigned i = NumElts/2; i != NumElts; ++i) 3981 if (!isUndefOrEqual(Mask[i], NumElts/2)) 3982 return false; 3983 return true; 3984} 3985 3986/// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand 3987/// specifies a shuffle of elements that is suitable for input to 128-bit 3988/// version of MOVDDUP. 3989static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) { 3990 if (!VT.is128BitVector()) 3991 return false; 3992 3993 unsigned e = VT.getVectorNumElements() / 2; 3994 for (unsigned i = 0; i != e; ++i) 3995 if (!isUndefOrEqual(Mask[i], i)) 3996 return false; 3997 for (unsigned i = 0; i != e; ++i) 3998 if (!isUndefOrEqual(Mask[e+i], i)) 3999 return false; 4000 return true; 4001} 4002 4003/// isVEXTRACTF128Index - Return true if the specified 4004/// EXTRACT_SUBVECTOR operand specifies a vector extract that is 4005/// suitable for input to VEXTRACTF128. 4006bool X86::isVEXTRACTF128Index(SDNode *N) { 4007 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4008 return false; 4009 4010 // The index should be aligned on a 128-bit boundary. 4011 uint64_t Index = 4012 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4013 4014 unsigned VL = N->getValueType(0).getVectorNumElements(); 4015 unsigned VBits = N->getValueType(0).getSizeInBits(); 4016 unsigned ElSize = VBits / VL; 4017 bool Result = (Index * ElSize) % 128 == 0; 4018 4019 return Result; 4020} 4021 4022/// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR 4023/// operand specifies a subvector insert that is suitable for input to 4024/// VINSERTF128. 4025bool X86::isVINSERTF128Index(SDNode *N) { 4026 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4027 return false; 4028 4029 // The index should be aligned on a 128-bit boundary. 4030 uint64_t Index = 4031 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4032 4033 unsigned VL = N->getValueType(0).getVectorNumElements(); 4034 unsigned VBits = N->getValueType(0).getSizeInBits(); 4035 unsigned ElSize = VBits / VL; 4036 bool Result = (Index * ElSize) % 128 == 0; 4037 4038 return Result; 4039} 4040 4041/// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle 4042/// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions. 4043/// Handles 128-bit and 256-bit. 4044static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) { 4045 EVT VT = N->getValueType(0); 4046 4047 assert((VT.is128BitVector() || VT.is256BitVector()) && 4048 "Unsupported vector type for PSHUF/SHUFP"); 4049 4050 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate 4051 // independently on 128-bit lanes. 4052 unsigned NumElts = VT.getVectorNumElements(); 4053 unsigned NumLanes = VT.getSizeInBits()/128; 4054 unsigned NumLaneElts = NumElts/NumLanes; 4055 4056 assert((NumLaneElts == 2 || NumLaneElts == 4) && 4057 "Only supports 2 or 4 elements per lane"); 4058 4059 unsigned Shift = (NumLaneElts == 4) ? 1 : 0; 4060 unsigned Mask = 0; 4061 for (unsigned i = 0; i != NumElts; ++i) { 4062 int Elt = N->getMaskElt(i); 4063 if (Elt < 0) continue; 4064 Elt &= NumLaneElts - 1; 4065 unsigned ShAmt = (i << Shift) % 8; 4066 Mask |= Elt << ShAmt; 4067 } 4068 4069 return Mask; 4070} 4071 4072/// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle 4073/// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction. 4074static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) { 4075 EVT VT = N->getValueType(0); 4076 4077 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4078 "Unsupported vector type for PSHUFHW"); 4079 4080 unsigned NumElts = VT.getVectorNumElements(); 4081 4082 unsigned Mask = 0; 4083 for (unsigned l = 0; l != NumElts; l += 8) { 4084 // 8 nodes per lane, but we only care about the last 4. 4085 for (unsigned i = 0; i < 4; ++i) { 4086 int Elt = N->getMaskElt(l+i+4); 4087 if (Elt < 0) continue; 4088 Elt &= 0x3; // only 2-bits. 4089 Mask |= Elt << (i * 2); 4090 } 4091 } 4092 4093 return Mask; 4094} 4095 4096/// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle 4097/// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction. 4098static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) { 4099 EVT VT = N->getValueType(0); 4100 4101 assert((VT == MVT::v8i16 || VT == MVT::v16i16) && 4102 "Unsupported vector type for PSHUFHW"); 4103 4104 unsigned NumElts = VT.getVectorNumElements(); 4105 4106 unsigned Mask = 0; 4107 for (unsigned l = 0; l != NumElts; l += 8) { 4108 // 8 nodes per lane, but we only care about the first 4. 4109 for (unsigned i = 0; i < 4; ++i) { 4110 int Elt = N->getMaskElt(l+i); 4111 if (Elt < 0) continue; 4112 Elt &= 0x3; // only 2-bits 4113 Mask |= Elt << (i * 2); 4114 } 4115 } 4116 4117 return Mask; 4118} 4119 4120/// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle 4121/// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction. 4122static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) { 4123 EVT VT = SVOp->getValueType(0); 4124 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3; 4125 4126 unsigned NumElts = VT.getVectorNumElements(); 4127 unsigned NumLanes = VT.getSizeInBits()/128; 4128 unsigned NumLaneElts = NumElts/NumLanes; 4129 4130 int Val = 0; 4131 unsigned i; 4132 for (i = 0; i != NumElts; ++i) { 4133 Val = SVOp->getMaskElt(i); 4134 if (Val >= 0) 4135 break; 4136 } 4137 if (Val >= (int)NumElts) 4138 Val -= NumElts - NumLaneElts; 4139 4140 assert(Val - i > 0 && "PALIGNR imm should be positive"); 4141 return (Val - i) * EltSize; 4142} 4143 4144/// getExtractVEXTRACTF128Immediate - Return the appropriate immediate 4145/// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128 4146/// instructions. 4147unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) { 4148 if (!isa<ConstantSDNode>(N->getOperand(1).getNode())) 4149 llvm_unreachable("Illegal extract subvector for VEXTRACTF128"); 4150 4151 uint64_t Index = 4152 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue(); 4153 4154 EVT VecVT = N->getOperand(0).getValueType(); 4155 EVT ElVT = VecVT.getVectorElementType(); 4156 4157 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4158 return Index / NumElemsPerChunk; 4159} 4160 4161/// getInsertVINSERTF128Immediate - Return the appropriate immediate 4162/// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128 4163/// instructions. 4164unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) { 4165 if (!isa<ConstantSDNode>(N->getOperand(2).getNode())) 4166 llvm_unreachable("Illegal insert subvector for VINSERTF128"); 4167 4168 uint64_t Index = 4169 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue(); 4170 4171 EVT VecVT = N->getValueType(0); 4172 EVT ElVT = VecVT.getVectorElementType(); 4173 4174 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits(); 4175 return Index / NumElemsPerChunk; 4176} 4177 4178/// getShuffleCLImmediate - Return the appropriate immediate to shuffle 4179/// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions. 4180/// Handles 256-bit. 4181static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) { 4182 EVT VT = N->getValueType(0); 4183 4184 unsigned NumElts = VT.getVectorNumElements(); 4185 4186 assert((VT.is256BitVector() && NumElts == 4) && 4187 "Unsupported vector type for VPERMQ/VPERMPD"); 4188 4189 unsigned Mask = 0; 4190 for (unsigned i = 0; i != NumElts; ++i) { 4191 int Elt = N->getMaskElt(i); 4192 if (Elt < 0) 4193 continue; 4194 Mask |= Elt << (i*2); 4195 } 4196 4197 return Mask; 4198} 4199/// isZeroNode - Returns true if Elt is a constant zero or a floating point 4200/// constant +0.0. 4201bool X86::isZeroNode(SDValue Elt) { 4202 return ((isa<ConstantSDNode>(Elt) && 4203 cast<ConstantSDNode>(Elt)->isNullValue()) || 4204 (isa<ConstantFPSDNode>(Elt) && 4205 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero())); 4206} 4207 4208/// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in 4209/// their permute mask. 4210static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp, 4211 SelectionDAG &DAG) { 4212 EVT VT = SVOp->getValueType(0); 4213 unsigned NumElems = VT.getVectorNumElements(); 4214 SmallVector<int, 8> MaskVec; 4215 4216 for (unsigned i = 0; i != NumElems; ++i) { 4217 int Idx = SVOp->getMaskElt(i); 4218 if (Idx >= 0) { 4219 if (Idx < (int)NumElems) 4220 Idx += NumElems; 4221 else 4222 Idx -= NumElems; 4223 } 4224 MaskVec.push_back(Idx); 4225 } 4226 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1), 4227 SVOp->getOperand(0), &MaskVec[0]); 4228} 4229 4230/// ShouldXformToMOVHLPS - Return true if the node should be transformed to 4231/// match movhlps. The lower half elements should come from upper half of 4232/// V1 (and in order), and the upper half elements should come from the upper 4233/// half of V2 (and in order). 4234static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) { 4235 if (!VT.is128BitVector()) 4236 return false; 4237 if (VT.getVectorNumElements() != 4) 4238 return false; 4239 for (unsigned i = 0, e = 2; i != e; ++i) 4240 if (!isUndefOrEqual(Mask[i], i+2)) 4241 return false; 4242 for (unsigned i = 2; i != 4; ++i) 4243 if (!isUndefOrEqual(Mask[i], i+4)) 4244 return false; 4245 return true; 4246} 4247 4248/// isScalarLoadToVector - Returns true if the node is a scalar load that 4249/// is promoted to a vector. It also returns the LoadSDNode by reference if 4250/// required. 4251static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) { 4252 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR) 4253 return false; 4254 N = N->getOperand(0).getNode(); 4255 if (!ISD::isNON_EXTLoad(N)) 4256 return false; 4257 if (LD) 4258 *LD = cast<LoadSDNode>(N); 4259 return true; 4260} 4261 4262// Test whether the given value is a vector value which will be legalized 4263// into a load. 4264static bool WillBeConstantPoolLoad(SDNode *N) { 4265 if (N->getOpcode() != ISD::BUILD_VECTOR) 4266 return false; 4267 4268 // Check for any non-constant elements. 4269 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 4270 switch (N->getOperand(i).getNode()->getOpcode()) { 4271 case ISD::UNDEF: 4272 case ISD::ConstantFP: 4273 case ISD::Constant: 4274 break; 4275 default: 4276 return false; 4277 } 4278 4279 // Vectors of all-zeros and all-ones are materialized with special 4280 // instructions rather than being loaded. 4281 return !ISD::isBuildVectorAllZeros(N) && 4282 !ISD::isBuildVectorAllOnes(N); 4283} 4284 4285/// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to 4286/// match movlp{s|d}. The lower half elements should come from lower half of 4287/// V1 (and in order), and the upper half elements should come from the upper 4288/// half of V2 (and in order). And since V1 will become the source of the 4289/// MOVLP, it must be either a vector load or a scalar load to vector. 4290static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, 4291 ArrayRef<int> Mask, EVT VT) { 4292 if (!VT.is128BitVector()) 4293 return false; 4294 4295 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1)) 4296 return false; 4297 // Is V2 is a vector load, don't do this transformation. We will try to use 4298 // load folding shufps op. 4299 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2)) 4300 return false; 4301 4302 unsigned NumElems = VT.getVectorNumElements(); 4303 4304 if (NumElems != 2 && NumElems != 4) 4305 return false; 4306 for (unsigned i = 0, e = NumElems/2; i != e; ++i) 4307 if (!isUndefOrEqual(Mask[i], i)) 4308 return false; 4309 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i) 4310 if (!isUndefOrEqual(Mask[i], i+NumElems)) 4311 return false; 4312 return true; 4313} 4314 4315/// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are 4316/// all the same. 4317static bool isSplatVector(SDNode *N) { 4318 if (N->getOpcode() != ISD::BUILD_VECTOR) 4319 return false; 4320 4321 SDValue SplatValue = N->getOperand(0); 4322 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i) 4323 if (N->getOperand(i) != SplatValue) 4324 return false; 4325 return true; 4326} 4327 4328/// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved 4329/// to an zero vector. 4330/// FIXME: move to dag combiner / method on ShuffleVectorSDNode 4331static bool isZeroShuffle(ShuffleVectorSDNode *N) { 4332 SDValue V1 = N->getOperand(0); 4333 SDValue V2 = N->getOperand(1); 4334 unsigned NumElems = N->getValueType(0).getVectorNumElements(); 4335 for (unsigned i = 0; i != NumElems; ++i) { 4336 int Idx = N->getMaskElt(i); 4337 if (Idx >= (int)NumElems) { 4338 unsigned Opc = V2.getOpcode(); 4339 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode())) 4340 continue; 4341 if (Opc != ISD::BUILD_VECTOR || 4342 !X86::isZeroNode(V2.getOperand(Idx-NumElems))) 4343 return false; 4344 } else if (Idx >= 0) { 4345 unsigned Opc = V1.getOpcode(); 4346 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode())) 4347 continue; 4348 if (Opc != ISD::BUILD_VECTOR || 4349 !X86::isZeroNode(V1.getOperand(Idx))) 4350 return false; 4351 } 4352 } 4353 return true; 4354} 4355 4356/// getZeroVector - Returns a vector of specified type with all zero elements. 4357/// 4358static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget, 4359 SelectionDAG &DAG, DebugLoc dl) { 4360 assert(VT.isVector() && "Expected a vector type"); 4361 4362 // Always build SSE zero vectors as <4 x i32> bitcasted 4363 // to their dest type. This ensures they get CSE'd. 4364 SDValue Vec; 4365 if (VT.is128BitVector()) { // SSE 4366 if (Subtarget->hasSSE2()) { // SSE2 4367 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4368 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4369 } else { // SSE1 4370 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4371 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst); 4372 } 4373 } else if (VT.is256BitVector()) { // AVX 4374 if (Subtarget->hasInt256()) { // AVX2 4375 SDValue Cst = DAG.getTargetConstant(0, MVT::i32); 4376 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4377 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8); 4378 } else { 4379 // 256-bit logic and arithmetic instructions in AVX are all 4380 // floating-point, no support for integer ops. Emit fp zeroed vectors. 4381 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32); 4382 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4383 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8); 4384 } 4385 } else 4386 llvm_unreachable("Unexpected vector type"); 4387 4388 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4389} 4390 4391/// getOnesVector - Returns a vector of specified type with all bits set. 4392/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with 4393/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately. 4394/// Then bitcast to their original type, ensuring they get CSE'd. 4395static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG, 4396 DebugLoc dl) { 4397 assert(VT.isVector() && "Expected a vector type"); 4398 4399 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32); 4400 SDValue Vec; 4401 if (VT.is256BitVector()) { 4402 if (HasInt256) { // AVX2 4403 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst }; 4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8); 4405 } else { // AVX 4406 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4407 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl); 4408 } 4409 } else if (VT.is128BitVector()) { 4410 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst); 4411 } else 4412 llvm_unreachable("Unexpected vector type"); 4413 4414 return DAG.getNode(ISD::BITCAST, dl, VT, Vec); 4415} 4416 4417/// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements 4418/// that point to V2 points to its first element. 4419static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) { 4420 for (unsigned i = 0; i != NumElems; ++i) { 4421 if (Mask[i] > (int)NumElems) { 4422 Mask[i] = NumElems; 4423 } 4424 } 4425} 4426 4427/// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd 4428/// operation of specified width. 4429static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4430 SDValue V2) { 4431 unsigned NumElems = VT.getVectorNumElements(); 4432 SmallVector<int, 8> Mask; 4433 Mask.push_back(NumElems); 4434 for (unsigned i = 1; i != NumElems; ++i) 4435 Mask.push_back(i); 4436 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4437} 4438 4439/// getUnpackl - Returns a vector_shuffle node for an unpackl operation. 4440static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4441 SDValue V2) { 4442 unsigned NumElems = VT.getVectorNumElements(); 4443 SmallVector<int, 8> Mask; 4444 for (unsigned i = 0, e = NumElems/2; i != e; ++i) { 4445 Mask.push_back(i); 4446 Mask.push_back(i + NumElems); 4447 } 4448 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4449} 4450 4451/// getUnpackh - Returns a vector_shuffle node for an unpackh operation. 4452static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1, 4453 SDValue V2) { 4454 unsigned NumElems = VT.getVectorNumElements(); 4455 SmallVector<int, 8> Mask; 4456 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) { 4457 Mask.push_back(i + Half); 4458 Mask.push_back(i + NumElems + Half); 4459 } 4460 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]); 4461} 4462 4463// PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by 4464// a generic shuffle instruction because the target has no such instructions. 4465// Generate shuffles which repeat i16 and i8 several times until they can be 4466// represented by v4f32 and then be manipulated by target suported shuffles. 4467static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) { 4468 EVT VT = V.getValueType(); 4469 int NumElems = VT.getVectorNumElements(); 4470 DebugLoc dl = V.getDebugLoc(); 4471 4472 while (NumElems > 4) { 4473 if (EltNo < NumElems/2) { 4474 V = getUnpackl(DAG, dl, VT, V, V); 4475 } else { 4476 V = getUnpackh(DAG, dl, VT, V, V); 4477 EltNo -= NumElems/2; 4478 } 4479 NumElems >>= 1; 4480 } 4481 return V; 4482} 4483 4484/// getLegalSplat - Generate a legal splat with supported x86 shuffles 4485static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) { 4486 EVT VT = V.getValueType(); 4487 DebugLoc dl = V.getDebugLoc(); 4488 4489 if (VT.is128BitVector()) { 4490 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V); 4491 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo }; 4492 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32), 4493 &SplatMask[0]); 4494 } else if (VT.is256BitVector()) { 4495 // To use VPERMILPS to splat scalars, the second half of indicies must 4496 // refer to the higher part, which is a duplication of the lower one, 4497 // because VPERMILPS can only handle in-lane permutations. 4498 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo, 4499 EltNo+4, EltNo+4, EltNo+4, EltNo+4 }; 4500 4501 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V); 4502 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32), 4503 &SplatMask[0]); 4504 } else 4505 llvm_unreachable("Vector size not supported"); 4506 4507 return DAG.getNode(ISD::BITCAST, dl, VT, V); 4508} 4509 4510/// PromoteSplat - Splat is promoted to target supported vector shuffles. 4511static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) { 4512 EVT SrcVT = SV->getValueType(0); 4513 SDValue V1 = SV->getOperand(0); 4514 DebugLoc dl = SV->getDebugLoc(); 4515 4516 int EltNo = SV->getSplatIndex(); 4517 int NumElems = SrcVT.getVectorNumElements(); 4518 bool Is256BitVec = SrcVT.is256BitVector(); 4519 4520 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) && 4521 "Unknown how to promote splat for type"); 4522 4523 // Extract the 128-bit part containing the splat element and update 4524 // the splat element index when it refers to the higher register. 4525 if (Is256BitVec) { 4526 V1 = Extract128BitVector(V1, EltNo, DAG, dl); 4527 if (EltNo >= NumElems/2) 4528 EltNo -= NumElems/2; 4529 } 4530 4531 // All i16 and i8 vector types can't be used directly by a generic shuffle 4532 // instruction because the target has no such instruction. Generate shuffles 4533 // which repeat i16 and i8 several times until they fit in i32, and then can 4534 // be manipulated by target suported shuffles. 4535 EVT EltVT = SrcVT.getVectorElementType(); 4536 if (EltVT == MVT::i8 || EltVT == MVT::i16) 4537 V1 = PromoteSplati8i16(V1, DAG, EltNo); 4538 4539 // Recreate the 256-bit vector and place the same 128-bit vector 4540 // into the low and high part. This is necessary because we want 4541 // to use VPERM* to shuffle the vectors 4542 if (Is256BitVec) { 4543 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1); 4544 } 4545 4546 return getLegalSplat(DAG, V1, EltNo); 4547} 4548 4549/// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified 4550/// vector of zero or undef vector. This produces a shuffle where the low 4551/// element of V2 is swizzled into the zero/undef vector, landing at element 4552/// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3). 4553static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx, 4554 bool IsZero, 4555 const X86Subtarget *Subtarget, 4556 SelectionDAG &DAG) { 4557 EVT VT = V2.getValueType(); 4558 SDValue V1 = IsZero 4559 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT); 4560 unsigned NumElems = VT.getVectorNumElements(); 4561 SmallVector<int, 16> MaskVec; 4562 for (unsigned i = 0; i != NumElems; ++i) 4563 // If this is the insertion idx, put the low elt of V2 here. 4564 MaskVec.push_back(i == Idx ? NumElems : i); 4565 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]); 4566} 4567 4568/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the 4569/// target specific opcode. Returns true if the Mask could be calculated. 4570/// Sets IsUnary to true if only uses one source. 4571static bool getTargetShuffleMask(SDNode *N, MVT VT, 4572 SmallVectorImpl<int> &Mask, bool &IsUnary) { 4573 unsigned NumElems = VT.getVectorNumElements(); 4574 SDValue ImmN; 4575 4576 IsUnary = false; 4577 switch(N->getOpcode()) { 4578 case X86ISD::SHUFP: 4579 ImmN = N->getOperand(N->getNumOperands()-1); 4580 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4581 break; 4582 case X86ISD::UNPCKH: 4583 DecodeUNPCKHMask(VT, Mask); 4584 break; 4585 case X86ISD::UNPCKL: 4586 DecodeUNPCKLMask(VT, Mask); 4587 break; 4588 case X86ISD::MOVHLPS: 4589 DecodeMOVHLPSMask(NumElems, Mask); 4590 break; 4591 case X86ISD::MOVLHPS: 4592 DecodeMOVLHPSMask(NumElems, Mask); 4593 break; 4594 case X86ISD::PSHUFD: 4595 case X86ISD::VPERMILP: 4596 ImmN = N->getOperand(N->getNumOperands()-1); 4597 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4598 IsUnary = true; 4599 break; 4600 case X86ISD::PSHUFHW: 4601 ImmN = N->getOperand(N->getNumOperands()-1); 4602 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4603 IsUnary = true; 4604 break; 4605 case X86ISD::PSHUFLW: 4606 ImmN = N->getOperand(N->getNumOperands()-1); 4607 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4608 IsUnary = true; 4609 break; 4610 case X86ISD::VPERMI: 4611 ImmN = N->getOperand(N->getNumOperands()-1); 4612 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4613 IsUnary = true; 4614 break; 4615 case X86ISD::MOVSS: 4616 case X86ISD::MOVSD: { 4617 // The index 0 always comes from the first element of the second source, 4618 // this is why MOVSS and MOVSD are used in the first place. The other 4619 // elements come from the other positions of the first source vector 4620 Mask.push_back(NumElems); 4621 for (unsigned i = 1; i != NumElems; ++i) { 4622 Mask.push_back(i); 4623 } 4624 break; 4625 } 4626 case X86ISD::VPERM2X128: 4627 ImmN = N->getOperand(N->getNumOperands()-1); 4628 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask); 4629 if (Mask.empty()) return false; 4630 break; 4631 case X86ISD::MOVDDUP: 4632 case X86ISD::MOVLHPD: 4633 case X86ISD::MOVLPD: 4634 case X86ISD::MOVLPS: 4635 case X86ISD::MOVSHDUP: 4636 case X86ISD::MOVSLDUP: 4637 case X86ISD::PALIGN: 4638 // Not yet implemented 4639 return false; 4640 default: llvm_unreachable("unknown target shuffle node"); 4641 } 4642 4643 return true; 4644} 4645 4646/// getShuffleScalarElt - Returns the scalar element that will make up the ith 4647/// element of the result of the vector shuffle. 4648static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG, 4649 unsigned Depth) { 4650 if (Depth == 6) 4651 return SDValue(); // Limit search depth. 4652 4653 SDValue V = SDValue(N, 0); 4654 EVT VT = V.getValueType(); 4655 unsigned Opcode = V.getOpcode(); 4656 4657 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars. 4658 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) { 4659 int Elt = SV->getMaskElt(Index); 4660 4661 if (Elt < 0) 4662 return DAG.getUNDEF(VT.getVectorElementType()); 4663 4664 unsigned NumElems = VT.getVectorNumElements(); 4665 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0) 4666 : SV->getOperand(1); 4667 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1); 4668 } 4669 4670 // Recurse into target specific vector shuffles to find scalars. 4671 if (isTargetShuffle(Opcode)) { 4672 MVT ShufVT = V.getValueType().getSimpleVT(); 4673 unsigned NumElems = ShufVT.getVectorNumElements(); 4674 SmallVector<int, 16> ShuffleMask; 4675 bool IsUnary; 4676 4677 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary)) 4678 return SDValue(); 4679 4680 int Elt = ShuffleMask[Index]; 4681 if (Elt < 0) 4682 return DAG.getUNDEF(ShufVT.getVectorElementType()); 4683 4684 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0) 4685 : N->getOperand(1); 4686 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, 4687 Depth+1); 4688 } 4689 4690 // Actual nodes that may contain scalar elements 4691 if (Opcode == ISD::BITCAST) { 4692 V = V.getOperand(0); 4693 EVT SrcVT = V.getValueType(); 4694 unsigned NumElems = VT.getVectorNumElements(); 4695 4696 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems) 4697 return SDValue(); 4698 } 4699 4700 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 4701 return (Index == 0) ? V.getOperand(0) 4702 : DAG.getUNDEF(VT.getVectorElementType()); 4703 4704 if (V.getOpcode() == ISD::BUILD_VECTOR) 4705 return V.getOperand(Index); 4706 4707 return SDValue(); 4708} 4709 4710/// getNumOfConsecutiveZeros - Return the number of elements of a vector 4711/// shuffle operation which come from a consecutively from a zero. The 4712/// search can start in two different directions, from left or right. 4713static 4714unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems, 4715 bool ZerosFromLeft, SelectionDAG &DAG) { 4716 unsigned i; 4717 for (i = 0; i != NumElems; ++i) { 4718 unsigned Index = ZerosFromLeft ? i : NumElems-i-1; 4719 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0); 4720 if (!(Elt.getNode() && 4721 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt)))) 4722 break; 4723 } 4724 4725 return i; 4726} 4727 4728/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE) 4729/// correspond consecutively to elements from one of the vector operands, 4730/// starting from its index OpIdx. Also tell OpNum which source vector operand. 4731static 4732bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, 4733 unsigned MaskI, unsigned MaskE, unsigned OpIdx, 4734 unsigned NumElems, unsigned &OpNum) { 4735 bool SeenV1 = false; 4736 bool SeenV2 = false; 4737 4738 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) { 4739 int Idx = SVOp->getMaskElt(i); 4740 // Ignore undef indicies 4741 if (Idx < 0) 4742 continue; 4743 4744 if (Idx < (int)NumElems) 4745 SeenV1 = true; 4746 else 4747 SeenV2 = true; 4748 4749 // Only accept consecutive elements from the same vector 4750 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2)) 4751 return false; 4752 } 4753 4754 OpNum = SeenV1 ? 0 : 1; 4755 return true; 4756} 4757 4758/// isVectorShiftRight - Returns true if the shuffle can be implemented as a 4759/// logical left shift of a vector. 4760static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4761 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4762 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4763 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4764 false /* check zeros from right */, DAG); 4765 unsigned OpSrc; 4766 4767 if (!NumZeros) 4768 return false; 4769 4770 // Considering the elements in the mask that are not consecutive zeros, 4771 // check if they consecutively come from only one of the source vectors. 4772 // 4773 // V1 = {X, A, B, C} 0 4774 // \ \ \ / 4775 // vector_shuffle V1, V2 <1, 2, 3, X> 4776 // 4777 if (!isShuffleMaskConsecutive(SVOp, 4778 0, // Mask Start Index 4779 NumElems-NumZeros, // Mask End Index(exclusive) 4780 NumZeros, // Where to start looking in the src vector 4781 NumElems, // Number of elements in vector 4782 OpSrc)) // Which source operand ? 4783 return false; 4784 4785 isLeft = false; 4786 ShAmt = NumZeros; 4787 ShVal = SVOp->getOperand(OpSrc); 4788 return true; 4789} 4790 4791/// isVectorShiftLeft - Returns true if the shuffle can be implemented as a 4792/// logical left shift of a vector. 4793static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4794 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4795 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements(); 4796 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, 4797 true /* check zeros from left */, DAG); 4798 unsigned OpSrc; 4799 4800 if (!NumZeros) 4801 return false; 4802 4803 // Considering the elements in the mask that are not consecutive zeros, 4804 // check if they consecutively come from only one of the source vectors. 4805 // 4806 // 0 { A, B, X, X } = V2 4807 // / \ / / 4808 // vector_shuffle V1, V2 <X, X, 4, 5> 4809 // 4810 if (!isShuffleMaskConsecutive(SVOp, 4811 NumZeros, // Mask Start Index 4812 NumElems, // Mask End Index(exclusive) 4813 0, // Where to start looking in the src vector 4814 NumElems, // Number of elements in vector 4815 OpSrc)) // Which source operand ? 4816 return false; 4817 4818 isLeft = true; 4819 ShAmt = NumZeros; 4820 ShVal = SVOp->getOperand(OpSrc); 4821 return true; 4822} 4823 4824/// isVectorShift - Returns true if the shuffle can be implemented as a 4825/// logical left or right shift of a vector. 4826static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG, 4827 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) { 4828 // Although the logic below support any bitwidth size, there are no 4829 // shift instructions which handle more than 128-bit vectors. 4830 if (!SVOp->getValueType(0).is128BitVector()) 4831 return false; 4832 4833 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) || 4834 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt)) 4835 return true; 4836 4837 return false; 4838} 4839 4840/// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8. 4841/// 4842static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros, 4843 unsigned NumNonZero, unsigned NumZero, 4844 SelectionDAG &DAG, 4845 const X86Subtarget* Subtarget, 4846 const TargetLowering &TLI) { 4847 if (NumNonZero > 8) 4848 return SDValue(); 4849 4850 DebugLoc dl = Op.getDebugLoc(); 4851 SDValue V(0, 0); 4852 bool First = true; 4853 for (unsigned i = 0; i < 16; ++i) { 4854 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0; 4855 if (ThisIsNonZero && First) { 4856 if (NumZero) 4857 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4858 else 4859 V = DAG.getUNDEF(MVT::v8i16); 4860 First = false; 4861 } 4862 4863 if ((i & 1) != 0) { 4864 SDValue ThisElt(0, 0), LastElt(0, 0); 4865 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0; 4866 if (LastIsNonZero) { 4867 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl, 4868 MVT::i16, Op.getOperand(i-1)); 4869 } 4870 if (ThisIsNonZero) { 4871 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i)); 4872 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, 4873 ThisElt, DAG.getConstant(8, MVT::i8)); 4874 if (LastIsNonZero) 4875 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt); 4876 } else 4877 ThisElt = LastElt; 4878 4879 if (ThisElt.getNode()) 4880 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt, 4881 DAG.getIntPtrConstant(i/2)); 4882 } 4883 } 4884 4885 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V); 4886} 4887 4888/// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16. 4889/// 4890static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros, 4891 unsigned NumNonZero, unsigned NumZero, 4892 SelectionDAG &DAG, 4893 const X86Subtarget* Subtarget, 4894 const TargetLowering &TLI) { 4895 if (NumNonZero > 4) 4896 return SDValue(); 4897 4898 DebugLoc dl = Op.getDebugLoc(); 4899 SDValue V(0, 0); 4900 bool First = true; 4901 for (unsigned i = 0; i < 8; ++i) { 4902 bool isNonZero = (NonZeros & (1 << i)) != 0; 4903 if (isNonZero) { 4904 if (First) { 4905 if (NumZero) 4906 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl); 4907 else 4908 V = DAG.getUNDEF(MVT::v8i16); 4909 First = false; 4910 } 4911 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, 4912 MVT::v8i16, V, Op.getOperand(i), 4913 DAG.getIntPtrConstant(i)); 4914 } 4915 } 4916 4917 return V; 4918} 4919 4920/// getVShift - Return a vector logical shift node. 4921/// 4922static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, 4923 unsigned NumBits, SelectionDAG &DAG, 4924 const TargetLowering &TLI, DebugLoc dl) { 4925 assert(VT.is128BitVector() && "Unknown type for VShift"); 4926 EVT ShVT = MVT::v2i64; 4927 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ; 4928 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp); 4929 return DAG.getNode(ISD::BITCAST, dl, VT, 4930 DAG.getNode(Opc, dl, ShVT, SrcOp, 4931 DAG.getConstant(NumBits, 4932 TLI.getShiftAmountTy(SrcOp.getValueType())))); 4933} 4934 4935SDValue 4936X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl, 4937 SelectionDAG &DAG) const { 4938 4939 // Check if the scalar load can be widened into a vector load. And if 4940 // the address is "base + cst" see if the cst can be "absorbed" into 4941 // the shuffle mask. 4942 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) { 4943 SDValue Ptr = LD->getBasePtr(); 4944 if (!ISD::isNormalLoad(LD) || LD->isVolatile()) 4945 return SDValue(); 4946 EVT PVT = LD->getValueType(0); 4947 if (PVT != MVT::i32 && PVT != MVT::f32) 4948 return SDValue(); 4949 4950 int FI = -1; 4951 int64_t Offset = 0; 4952 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) { 4953 FI = FINode->getIndex(); 4954 Offset = 0; 4955 } else if (DAG.isBaseWithConstantOffset(Ptr) && 4956 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 4957 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 4958 Offset = Ptr.getConstantOperandVal(1); 4959 Ptr = Ptr.getOperand(0); 4960 } else { 4961 return SDValue(); 4962 } 4963 4964 // FIXME: 256-bit vector instructions don't require a strict alignment, 4965 // improve this code to support it better. 4966 unsigned RequiredAlign = VT.getSizeInBits()/8; 4967 SDValue Chain = LD->getChain(); 4968 // Make sure the stack object alignment is at least 16 or 32. 4969 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4970 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) { 4971 if (MFI->isFixedObjectIndex(FI)) { 4972 // Can't change the alignment. FIXME: It's possible to compute 4973 // the exact stack offset and reference FI + adjust offset instead. 4974 // If someone *really* cares about this. That's the way to implement it. 4975 return SDValue(); 4976 } else { 4977 MFI->setObjectAlignment(FI, RequiredAlign); 4978 } 4979 } 4980 4981 // (Offset % 16 or 32) must be multiple of 4. Then address is then 4982 // Ptr + (Offset & ~15). 4983 if (Offset < 0) 4984 return SDValue(); 4985 if ((Offset % RequiredAlign) & 3) 4986 return SDValue(); 4987 int64_t StartOffset = Offset & ~(RequiredAlign-1); 4988 if (StartOffset) 4989 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(), 4990 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType())); 4991 4992 int EltNo = (Offset - StartOffset) >> 2; 4993 unsigned NumElems = VT.getVectorNumElements(); 4994 4995 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems); 4996 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr, 4997 LD->getPointerInfo().getWithOffset(StartOffset), 4998 false, false, false, 0); 4999 5000 SmallVector<int, 8> Mask; 5001 for (unsigned i = 0; i != NumElems; ++i) 5002 Mask.push_back(EltNo); 5003 5004 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]); 5005 } 5006 5007 return SDValue(); 5008} 5009 5010/// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 5011/// vector of type 'VT', see if the elements can be replaced by a single large 5012/// load which has the same value as a build_vector whose operands are 'elts'. 5013/// 5014/// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a 5015/// 5016/// FIXME: we'd also like to handle the case where the last elements are zero 5017/// rather than undef via VZEXT_LOAD, but we do not detect that case today. 5018/// There's even a handy isZeroNode for that purpose. 5019static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts, 5020 DebugLoc &DL, SelectionDAG &DAG) { 5021 EVT EltVT = VT.getVectorElementType(); 5022 unsigned NumElems = Elts.size(); 5023 5024 LoadSDNode *LDBase = NULL; 5025 unsigned LastLoadedElt = -1U; 5026 5027 // For each element in the initializer, see if we've found a load or an undef. 5028 // If we don't find an initial load element, or later load elements are 5029 // non-consecutive, bail out. 5030 for (unsigned i = 0; i < NumElems; ++i) { 5031 SDValue Elt = Elts[i]; 5032 5033 if (!Elt.getNode() || 5034 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode()))) 5035 return SDValue(); 5036 if (!LDBase) { 5037 if (Elt.getNode()->getOpcode() == ISD::UNDEF) 5038 return SDValue(); 5039 LDBase = cast<LoadSDNode>(Elt.getNode()); 5040 LastLoadedElt = i; 5041 continue; 5042 } 5043 if (Elt.getOpcode() == ISD::UNDEF) 5044 continue; 5045 5046 LoadSDNode *LD = cast<LoadSDNode>(Elt); 5047 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i)) 5048 return SDValue(); 5049 LastLoadedElt = i; 5050 } 5051 5052 // If we have found an entire vector of loads and undefs, then return a large 5053 // load of the entire vector width starting at the base pointer. If we found 5054 // consecutive loads for the low half, generate a vzext_load node. 5055 if (LastLoadedElt == NumElems - 1) { 5056 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16) 5057 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5058 LDBase->getPointerInfo(), 5059 LDBase->isVolatile(), LDBase->isNonTemporal(), 5060 LDBase->isInvariant(), 0); 5061 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(), 5062 LDBase->getPointerInfo(), 5063 LDBase->isVolatile(), LDBase->isNonTemporal(), 5064 LDBase->isInvariant(), LDBase->getAlignment()); 5065 } 5066 if (NumElems == 4 && LastLoadedElt == 1 && 5067 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) { 5068 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other); 5069 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() }; 5070 SDValue ResNode = 5071 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64, 5072 LDBase->getPointerInfo(), 5073 LDBase->getAlignment(), 5074 false/*isVolatile*/, true/*ReadMem*/, 5075 false/*WriteMem*/); 5076 5077 // Make sure the newly-created LOAD is in the same position as LDBase in 5078 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and 5079 // update uses of LDBase's output chain to use the TokenFactor. 5080 if (LDBase->hasAnyUseOfValue(1)) { 5081 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 5082 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1)); 5083 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain); 5084 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1), 5085 SDValue(ResNode.getNode(), 1)); 5086 } 5087 5088 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode); 5089 } 5090 return SDValue(); 5091} 5092 5093/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction 5094/// to generate a splat value for the following cases: 5095/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant. 5096/// 2. A splat shuffle which uses a scalar_to_vector node which comes from 5097/// a scalar load, or a constant. 5098/// The VBROADCAST node is returned when a pattern is found, 5099/// or SDValue() otherwise. 5100SDValue 5101X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const { 5102 if (!Subtarget->hasFp256()) 5103 return SDValue(); 5104 5105 EVT VT = Op.getValueType(); 5106 DebugLoc dl = Op.getDebugLoc(); 5107 5108 assert((VT.is128BitVector() || VT.is256BitVector()) && 5109 "Unsupported vector type for broadcast."); 5110 5111 SDValue Ld; 5112 bool ConstSplatVal; 5113 5114 switch (Op.getOpcode()) { 5115 default: 5116 // Unknown pattern found. 5117 return SDValue(); 5118 5119 case ISD::BUILD_VECTOR: { 5120 // The BUILD_VECTOR node must be a splat. 5121 if (!isSplatVector(Op.getNode())) 5122 return SDValue(); 5123 5124 Ld = Op.getOperand(0); 5125 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5126 Ld.getOpcode() == ISD::ConstantFP); 5127 5128 // The suspected load node has several users. Make sure that all 5129 // of its users are from the BUILD_VECTOR node. 5130 // Constants may have multiple users. 5131 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0)) 5132 return SDValue(); 5133 break; 5134 } 5135 5136 case ISD::VECTOR_SHUFFLE: { 5137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5138 5139 // Shuffles must have a splat mask where the first element is 5140 // broadcasted. 5141 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0) 5142 return SDValue(); 5143 5144 SDValue Sc = Op.getOperand(0); 5145 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR && 5146 Sc.getOpcode() != ISD::BUILD_VECTOR) { 5147 5148 if (!Subtarget->hasInt256()) 5149 return SDValue(); 5150 5151 // Use the register form of the broadcast instruction available on AVX2. 5152 if (VT.is256BitVector()) 5153 Sc = Extract128BitVector(Sc, 0, DAG, dl); 5154 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc); 5155 } 5156 5157 Ld = Sc.getOperand(0); 5158 ConstSplatVal = (Ld.getOpcode() == ISD::Constant || 5159 Ld.getOpcode() == ISD::ConstantFP); 5160 5161 // The scalar_to_vector node and the suspected 5162 // load node must have exactly one user. 5163 // Constants may have multiple users. 5164 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse())) 5165 return SDValue(); 5166 break; 5167 } 5168 } 5169 5170 bool Is256 = VT.is256BitVector(); 5171 5172 // Handle the broadcasting a single constant scalar from the constant pool 5173 // into a vector. On Sandybridge it is still better to load a constant vector 5174 // from the constant pool and not to broadcast it from a scalar. 5175 if (ConstSplatVal && Subtarget->hasInt256()) { 5176 EVT CVT = Ld.getValueType(); 5177 assert(!CVT.isVector() && "Must not broadcast a vector type"); 5178 unsigned ScalarSize = CVT.getSizeInBits(); 5179 5180 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) { 5181 const Constant *C = 0; 5182 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld)) 5183 C = CI->getConstantIntValue(); 5184 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld)) 5185 C = CF->getConstantFPValue(); 5186 5187 assert(C && "Invalid constant type"); 5188 5189 SDValue CP = DAG.getConstantPool(C, getPointerTy()); 5190 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment(); 5191 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP, 5192 MachinePointerInfo::getConstantPool(), 5193 false, false, false, Alignment); 5194 5195 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5196 } 5197 } 5198 5199 bool IsLoad = ISD::isNormalLoad(Ld.getNode()); 5200 unsigned ScalarSize = Ld.getValueType().getSizeInBits(); 5201 5202 // Handle AVX2 in-register broadcasts. 5203 if (!IsLoad && Subtarget->hasInt256() && 5204 (ScalarSize == 32 || (Is256 && ScalarSize == 64))) 5205 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5206 5207 // The scalar source must be a normal load. 5208 if (!IsLoad) 5209 return SDValue(); 5210 5211 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) 5212 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5213 5214 // The integer check is needed for the 64-bit into 128-bit so it doesn't match 5215 // double since there is no vbroadcastsd xmm 5216 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) { 5217 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64) 5218 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld); 5219 } 5220 5221 // Unsupported broadcast. 5222 return SDValue(); 5223} 5224 5225SDValue 5226X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const { 5227 EVT VT = Op.getValueType(); 5228 5229 // Skip if insert_vec_elt is not supported. 5230 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT)) 5231 return SDValue(); 5232 5233 DebugLoc DL = Op.getDebugLoc(); 5234 unsigned NumElems = Op.getNumOperands(); 5235 5236 SDValue VecIn1; 5237 SDValue VecIn2; 5238 SmallVector<unsigned, 4> InsertIndices; 5239 SmallVector<int, 8> Mask(NumElems, -1); 5240 5241 for (unsigned i = 0; i != NumElems; ++i) { 5242 unsigned Opc = Op.getOperand(i).getOpcode(); 5243 5244 if (Opc == ISD::UNDEF) 5245 continue; 5246 5247 if (Opc != ISD::EXTRACT_VECTOR_ELT) { 5248 // Quit if more than 1 elements need inserting. 5249 if (InsertIndices.size() > 1) 5250 return SDValue(); 5251 5252 InsertIndices.push_back(i); 5253 continue; 5254 } 5255 5256 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0); 5257 SDValue ExtIdx = Op.getOperand(i).getOperand(1); 5258 5259 // Quit if extracted from vector of different type. 5260 if (ExtractedFromVec.getValueType() != VT) 5261 return SDValue(); 5262 5263 // Quit if non-constant index. 5264 if (!isa<ConstantSDNode>(ExtIdx)) 5265 return SDValue(); 5266 5267 if (VecIn1.getNode() == 0) 5268 VecIn1 = ExtractedFromVec; 5269 else if (VecIn1 != ExtractedFromVec) { 5270 if (VecIn2.getNode() == 0) 5271 VecIn2 = ExtractedFromVec; 5272 else if (VecIn2 != ExtractedFromVec) 5273 // Quit if more than 2 vectors to shuffle 5274 return SDValue(); 5275 } 5276 5277 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue(); 5278 5279 if (ExtractedFromVec == VecIn1) 5280 Mask[i] = Idx; 5281 else if (ExtractedFromVec == VecIn2) 5282 Mask[i] = Idx + NumElems; 5283 } 5284 5285 if (VecIn1.getNode() == 0) 5286 return SDValue(); 5287 5288 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 5289 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]); 5290 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) { 5291 unsigned Idx = InsertIndices[i]; 5292 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx), 5293 DAG.getIntPtrConstant(Idx)); 5294 } 5295 5296 return NV; 5297} 5298 5299SDValue 5300X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { 5301 DebugLoc dl = Op.getDebugLoc(); 5302 5303 EVT VT = Op.getValueType(); 5304 EVT ExtVT = VT.getVectorElementType(); 5305 unsigned NumElems = Op.getNumOperands(); 5306 5307 // Vectors containing all zeros can be matched by pxor and xorps later 5308 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 5309 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd 5310 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts. 5311 if (VT == MVT::v4i32 || VT == MVT::v8i32) 5312 return Op; 5313 5314 return getZeroVector(VT, Subtarget, DAG, dl); 5315 } 5316 5317 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width 5318 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use 5319 // vpcmpeqd on 256-bit vectors. 5320 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 5321 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256())) 5322 return Op; 5323 5324 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl); 5325 } 5326 5327 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 5328 if (Broadcast.getNode()) 5329 return Broadcast; 5330 5331 unsigned EVTBits = ExtVT.getSizeInBits(); 5332 5333 unsigned NumZero = 0; 5334 unsigned NumNonZero = 0; 5335 unsigned NonZeros = 0; 5336 bool IsAllConstants = true; 5337 SmallSet<SDValue, 8> Values; 5338 for (unsigned i = 0; i < NumElems; ++i) { 5339 SDValue Elt = Op.getOperand(i); 5340 if (Elt.getOpcode() == ISD::UNDEF) 5341 continue; 5342 Values.insert(Elt); 5343 if (Elt.getOpcode() != ISD::Constant && 5344 Elt.getOpcode() != ISD::ConstantFP) 5345 IsAllConstants = false; 5346 if (X86::isZeroNode(Elt)) 5347 NumZero++; 5348 else { 5349 NonZeros |= (1 << i); 5350 NumNonZero++; 5351 } 5352 } 5353 5354 // All undef vector. Return an UNDEF. All zero vectors were handled above. 5355 if (NumNonZero == 0) 5356 return DAG.getUNDEF(VT); 5357 5358 // Special case for single non-zero, non-undef, element. 5359 if (NumNonZero == 1) { 5360 unsigned Idx = CountTrailingZeros_32(NonZeros); 5361 SDValue Item = Op.getOperand(Idx); 5362 5363 // If this is an insertion of an i64 value on x86-32, and if the top bits of 5364 // the value are obviously zero, truncate the value to i32 and do the 5365 // insertion that way. Only do this if the value is non-constant or if the 5366 // value is a constant being inserted into element 0. It is cheaper to do 5367 // a constant pool load than it is to do a movd + shuffle. 5368 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() && 5369 (!IsAllConstants || Idx == 0)) { 5370 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) { 5371 // Handle SSE only. 5372 assert(VT == MVT::v2i64 && "Expected an SSE value type!"); 5373 EVT VecVT = MVT::v4i32; 5374 unsigned VecElts = 4; 5375 5376 // Truncate the value (which may itself be a constant) to i32, and 5377 // convert it to a vector with movd (S2V+shuffle to zero extend). 5378 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item); 5379 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item); 5380 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5381 5382 // Now we have our 32-bit value zero extended in the low element of 5383 // a vector. If Idx != 0, swizzle it into place. 5384 if (Idx != 0) { 5385 SmallVector<int, 4> Mask; 5386 Mask.push_back(Idx); 5387 for (unsigned i = 1; i != VecElts; ++i) 5388 Mask.push_back(i); 5389 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT), 5390 &Mask[0]); 5391 } 5392 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5393 } 5394 } 5395 5396 // If we have a constant or non-constant insertion into the low element of 5397 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into 5398 // the rest of the elements. This will be matched as movd/movq/movss/movsd 5399 // depending on what the source datatype is. 5400 if (Idx == 0) { 5401 if (NumZero == 0) 5402 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5403 5404 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 || 5405 (ExtVT == MVT::i64 && Subtarget->is64Bit())) { 5406 if (VT.is256BitVector()) { 5407 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl); 5408 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec, 5409 Item, DAG.getIntPtrConstant(0)); 5410 } 5411 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5412 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5413 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector. 5414 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5415 } 5416 5417 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) { 5418 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item); 5419 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item); 5420 if (VT.is256BitVector()) { 5421 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl); 5422 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl); 5423 } else { 5424 assert(VT.is128BitVector() && "Expected an SSE value type!"); 5425 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG); 5426 } 5427 return DAG.getNode(ISD::BITCAST, dl, VT, Item); 5428 } 5429 } 5430 5431 // Is it a vector logical left shift? 5432 if (NumElems == 2 && Idx == 1 && 5433 X86::isZeroNode(Op.getOperand(0)) && 5434 !X86::isZeroNode(Op.getOperand(1))) { 5435 unsigned NumBits = VT.getSizeInBits(); 5436 return getVShift(true, VT, 5437 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 5438 VT, Op.getOperand(1)), 5439 NumBits/2, DAG, *this, dl); 5440 } 5441 5442 if (IsAllConstants) // Otherwise, it's better to do a constpool load. 5443 return SDValue(); 5444 5445 // Otherwise, if this is a vector with i32 or f32 elements, and the element 5446 // is a non-constant being inserted into an element other than the low one, 5447 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka 5448 // movd/movss) to move this into the low element, then shuffle it into 5449 // place. 5450 if (EVTBits == 32) { 5451 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item); 5452 5453 // Turn it into a shuffle of zero and zero-extended scalar to vector. 5454 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG); 5455 SmallVector<int, 8> MaskVec; 5456 for (unsigned i = 0; i != NumElems; ++i) 5457 MaskVec.push_back(i == Idx ? 0 : 1); 5458 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]); 5459 } 5460 } 5461 5462 // Splat is obviously ok. Let legalizer expand it to a shuffle. 5463 if (Values.size() == 1) { 5464 if (EVTBits == 32) { 5465 // Instead of a shuffle like this: 5466 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0> 5467 // Check if it's possible to issue this instead. 5468 // shuffle (vload ptr)), undef, <1, 1, 1, 1> 5469 unsigned Idx = CountTrailingZeros_32(NonZeros); 5470 SDValue Item = Op.getOperand(Idx); 5471 if (Op.getNode()->isOnlyUserOf(Item.getNode())) 5472 return LowerAsSplatVectorLoad(Item, VT, dl, DAG); 5473 } 5474 return SDValue(); 5475 } 5476 5477 // A vector full of immediates; various special cases are already 5478 // handled, so this is best done with a single constant-pool load. 5479 if (IsAllConstants) 5480 return SDValue(); 5481 5482 // For AVX-length vectors, build the individual 128-bit pieces and use 5483 // shuffles to put them in place. 5484 if (VT.is256BitVector()) { 5485 SmallVector<SDValue, 32> V; 5486 for (unsigned i = 0; i != NumElems; ++i) 5487 V.push_back(Op.getOperand(i)); 5488 5489 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2); 5490 5491 // Build both the lower and upper subvector. 5492 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2); 5493 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2], 5494 NumElems/2); 5495 5496 // Recreate the wider vector with the lower and upper part. 5497 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl); 5498 } 5499 5500 // Let legalizer expand 2-wide build_vectors. 5501 if (EVTBits == 64) { 5502 if (NumNonZero == 1) { 5503 // One half is zero or undef. 5504 unsigned Idx = CountTrailingZeros_32(NonZeros); 5505 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, 5506 Op.getOperand(Idx)); 5507 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG); 5508 } 5509 return SDValue(); 5510 } 5511 5512 // If element VT is < 32 bits, convert it to inserts into a zero vector. 5513 if (EVTBits == 8 && NumElems == 16) { 5514 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG, 5515 Subtarget, *this); 5516 if (V.getNode()) return V; 5517 } 5518 5519 if (EVTBits == 16 && NumElems == 8) { 5520 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG, 5521 Subtarget, *this); 5522 if (V.getNode()) return V; 5523 } 5524 5525 // If element VT is == 32 bits, turn it into a number of shuffles. 5526 SmallVector<SDValue, 8> V(NumElems); 5527 if (NumElems == 4 && NumZero > 0) { 5528 for (unsigned i = 0; i < 4; ++i) { 5529 bool isZero = !(NonZeros & (1 << i)); 5530 if (isZero) 5531 V[i] = getZeroVector(VT, Subtarget, DAG, dl); 5532 else 5533 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5534 } 5535 5536 for (unsigned i = 0; i < 2; ++i) { 5537 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) { 5538 default: break; 5539 case 0: 5540 V[i] = V[i*2]; // Must be a zero vector. 5541 break; 5542 case 1: 5543 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]); 5544 break; 5545 case 2: 5546 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]); 5547 break; 5548 case 3: 5549 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]); 5550 break; 5551 } 5552 } 5553 5554 bool Reverse1 = (NonZeros & 0x3) == 2; 5555 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2; 5556 int MaskVec[] = { 5557 Reverse1 ? 1 : 0, 5558 Reverse1 ? 0 : 1, 5559 static_cast<int>(Reverse2 ? NumElems+1 : NumElems), 5560 static_cast<int>(Reverse2 ? NumElems : NumElems+1) 5561 }; 5562 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]); 5563 } 5564 5565 if (Values.size() > 1 && VT.is128BitVector()) { 5566 // Check for a build vector of consecutive loads. 5567 for (unsigned i = 0; i < NumElems; ++i) 5568 V[i] = Op.getOperand(i); 5569 5570 // Check for elements which are consecutive loads. 5571 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG); 5572 if (LD.getNode()) 5573 return LD; 5574 5575 // Check for a build vector from mostly shuffle plus few inserting. 5576 SDValue Sh = buildFromShuffleMostly(Op, DAG); 5577 if (Sh.getNode()) 5578 return Sh; 5579 5580 // For SSE 4.1, use insertps to put the high elements into the low element. 5581 if (getSubtarget()->hasSSE41()) { 5582 SDValue Result; 5583 if (Op.getOperand(0).getOpcode() != ISD::UNDEF) 5584 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0)); 5585 else 5586 Result = DAG.getUNDEF(VT); 5587 5588 for (unsigned i = 1; i < NumElems; ++i) { 5589 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue; 5590 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result, 5591 Op.getOperand(i), DAG.getIntPtrConstant(i)); 5592 } 5593 return Result; 5594 } 5595 5596 // Otherwise, expand into a number of unpckl*, start by extending each of 5597 // our (non-undef) elements to the full vector width with the element in the 5598 // bottom slot of the vector (which generates no code for SSE). 5599 for (unsigned i = 0; i < NumElems; ++i) { 5600 if (Op.getOperand(i).getOpcode() != ISD::UNDEF) 5601 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i)); 5602 else 5603 V[i] = DAG.getUNDEF(VT); 5604 } 5605 5606 // Next, we iteratively mix elements, e.g. for v4f32: 5607 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0> 5608 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1> 5609 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0> 5610 unsigned EltStride = NumElems >> 1; 5611 while (EltStride != 0) { 5612 for (unsigned i = 0; i < EltStride; ++i) { 5613 // If V[i+EltStride] is undef and this is the first round of mixing, 5614 // then it is safe to just drop this shuffle: V[i] is already in the 5615 // right place, the one element (since it's the first round) being 5616 // inserted as undef can be dropped. This isn't safe for successive 5617 // rounds because they will permute elements within both vectors. 5618 if (V[i+EltStride].getOpcode() == ISD::UNDEF && 5619 EltStride == NumElems/2) 5620 continue; 5621 5622 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]); 5623 } 5624 EltStride >>= 1; 5625 } 5626 return V[0]; 5627 } 5628 return SDValue(); 5629} 5630 5631// LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction 5632// to create 256-bit vectors from two other 128-bit ones. 5633static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5634 DebugLoc dl = Op.getDebugLoc(); 5635 EVT ResVT = Op.getValueType(); 5636 5637 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide"); 5638 5639 SDValue V1 = Op.getOperand(0); 5640 SDValue V2 = Op.getOperand(1); 5641 unsigned NumElems = ResVT.getVectorNumElements(); 5642 5643 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl); 5644} 5645 5646static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) { 5647 assert(Op.getNumOperands() == 2); 5648 5649 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors 5650 // from two other 128-bit ones. 5651 return LowerAVXCONCAT_VECTORS(Op, DAG); 5652} 5653 5654// Try to lower a shuffle node into a simple blend instruction. 5655static SDValue 5656LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp, 5657 const X86Subtarget *Subtarget, SelectionDAG &DAG) { 5658 SDValue V1 = SVOp->getOperand(0); 5659 SDValue V2 = SVOp->getOperand(1); 5660 DebugLoc dl = SVOp->getDebugLoc(); 5661 EVT VT = SVOp->getValueType(0); 5662 EVT EltVT = VT.getVectorElementType(); 5663 unsigned NumElems = VT.getVectorNumElements(); 5664 5665 if (!Subtarget->hasSSE41() || EltVT == MVT::i8) 5666 return SDValue(); 5667 if (!Subtarget->hasInt256() && VT == MVT::v16i16) 5668 return SDValue(); 5669 5670 // Check the mask for BLEND and build the value. 5671 unsigned MaskValue = 0; 5672 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise. 5673 unsigned NumLanes = (NumElems-1)/8 + 1; 5674 unsigned NumElemsInLane = NumElems / NumLanes; 5675 5676 // Blend for v16i16 should be symetric for the both lanes. 5677 for (unsigned i = 0; i < NumElemsInLane; ++i) { 5678 5679 int SndLaneEltIdx = (NumLanes == 2) ? 5680 SVOp->getMaskElt(i + NumElemsInLane) : -1; 5681 int EltIdx = SVOp->getMaskElt(i); 5682 5683 if ((EltIdx == -1 || EltIdx == (int)i) && 5684 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane))) 5685 continue; 5686 5687 if (((unsigned)EltIdx == (i + NumElems)) && 5688 (SndLaneEltIdx == -1 || 5689 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane)) 5690 MaskValue |= (1<<i); 5691 else 5692 return SDValue(); 5693 } 5694 5695 // Convert i32 vectors to floating point if it is not AVX2. 5696 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors. 5697 EVT BlendVT = VT; 5698 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) { 5699 BlendVT = EVT::getVectorVT(*DAG.getContext(), 5700 EVT::getFloatingPointVT(EltVT.getSizeInBits()), 5701 NumElems); 5702 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1); 5703 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2); 5704 } 5705 5706 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2, 5707 DAG.getConstant(MaskValue, MVT::i32)); 5708 return DAG.getNode(ISD::BITCAST, dl, VT, Ret); 5709} 5710 5711// v8i16 shuffles - Prefer shuffles in the following order: 5712// 1. [all] pshuflw, pshufhw, optional move 5713// 2. [ssse3] 1 x pshufb 5714// 3. [ssse3] 2 x pshufb + 1 x por 5715// 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw) 5716static SDValue 5717LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget, 5718 SelectionDAG &DAG) { 5719 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 5720 SDValue V1 = SVOp->getOperand(0); 5721 SDValue V2 = SVOp->getOperand(1); 5722 DebugLoc dl = SVOp->getDebugLoc(); 5723 SmallVector<int, 8> MaskVals; 5724 5725 // Determine if more than 1 of the words in each of the low and high quadwords 5726 // of the result come from the same quadword of one of the two inputs. Undef 5727 // mask values count as coming from any quadword, for better codegen. 5728 unsigned LoQuad[] = { 0, 0, 0, 0 }; 5729 unsigned HiQuad[] = { 0, 0, 0, 0 }; 5730 std::bitset<4> InputQuads; 5731 for (unsigned i = 0; i < 8; ++i) { 5732 unsigned *Quad = i < 4 ? LoQuad : HiQuad; 5733 int EltIdx = SVOp->getMaskElt(i); 5734 MaskVals.push_back(EltIdx); 5735 if (EltIdx < 0) { 5736 ++Quad[0]; 5737 ++Quad[1]; 5738 ++Quad[2]; 5739 ++Quad[3]; 5740 continue; 5741 } 5742 ++Quad[EltIdx / 4]; 5743 InputQuads.set(EltIdx / 4); 5744 } 5745 5746 int BestLoQuad = -1; 5747 unsigned MaxQuad = 1; 5748 for (unsigned i = 0; i < 4; ++i) { 5749 if (LoQuad[i] > MaxQuad) { 5750 BestLoQuad = i; 5751 MaxQuad = LoQuad[i]; 5752 } 5753 } 5754 5755 int BestHiQuad = -1; 5756 MaxQuad = 1; 5757 for (unsigned i = 0; i < 4; ++i) { 5758 if (HiQuad[i] > MaxQuad) { 5759 BestHiQuad = i; 5760 MaxQuad = HiQuad[i]; 5761 } 5762 } 5763 5764 // For SSSE3, If all 8 words of the result come from only 1 quadword of each 5765 // of the two input vectors, shuffle them into one input vector so only a 5766 // single pshufb instruction is necessary. If There are more than 2 input 5767 // quads, disable the next transformation since it does not help SSSE3. 5768 bool V1Used = InputQuads[0] || InputQuads[1]; 5769 bool V2Used = InputQuads[2] || InputQuads[3]; 5770 if (Subtarget->hasSSSE3()) { 5771 if (InputQuads.count() == 2 && V1Used && V2Used) { 5772 BestLoQuad = InputQuads[0] ? 0 : 1; 5773 BestHiQuad = InputQuads[2] ? 2 : 3; 5774 } 5775 if (InputQuads.count() > 2) { 5776 BestLoQuad = -1; 5777 BestHiQuad = -1; 5778 } 5779 } 5780 5781 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update 5782 // the shuffle mask. If a quad is scored as -1, that means that it contains 5783 // words from all 4 input quadwords. 5784 SDValue NewV; 5785 if (BestLoQuad >= 0 || BestHiQuad >= 0) { 5786 int MaskV[] = { 5787 BestLoQuad < 0 ? 0 : BestLoQuad, 5788 BestHiQuad < 0 ? 1 : BestHiQuad 5789 }; 5790 NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 5791 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1), 5792 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]); 5793 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV); 5794 5795 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the 5796 // source words for the shuffle, to aid later transformations. 5797 bool AllWordsInNewV = true; 5798 bool InOrder[2] = { true, true }; 5799 for (unsigned i = 0; i != 8; ++i) { 5800 int idx = MaskVals[i]; 5801 if (idx != (int)i) 5802 InOrder[i/4] = false; 5803 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad) 5804 continue; 5805 AllWordsInNewV = false; 5806 break; 5807 } 5808 5809 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV; 5810 if (AllWordsInNewV) { 5811 for (int i = 0; i != 8; ++i) { 5812 int idx = MaskVals[i]; 5813 if (idx < 0) 5814 continue; 5815 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 5816 if ((idx != i) && idx < 4) 5817 pshufhw = false; 5818 if ((idx != i) && idx > 3) 5819 pshuflw = false; 5820 } 5821 V1 = NewV; 5822 V2Used = false; 5823 BestLoQuad = 0; 5824 BestHiQuad = 1; 5825 } 5826 5827 // If we've eliminated the use of V2, and the new mask is a pshuflw or 5828 // pshufhw, that's as cheap as it gets. Return the new shuffle. 5829 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) { 5830 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW; 5831 unsigned TargetMask = 0; 5832 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 5833 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]); 5834 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5835 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp): 5836 getShufflePSHUFLWImmediate(SVOp); 5837 V1 = NewV.getOperand(0); 5838 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG); 5839 } 5840 } 5841 5842 // If we have SSSE3, and all words of the result are from 1 input vector, 5843 // case 2 is generated, otherwise case 3 is generated. If no SSSE3 5844 // is present, fall back to case 4. 5845 if (Subtarget->hasSSSE3()) { 5846 SmallVector<SDValue,16> pshufbMask; 5847 5848 // If we have elements from both input vectors, set the high bit of the 5849 // shuffle mask element to zero out elements that come from V2 in the V1 5850 // mask, and elements that come from V1 in the V2 mask, so that the two 5851 // results can be OR'd together. 5852 bool TwoInputs = V1Used && V2Used; 5853 for (unsigned i = 0; i != 8; ++i) { 5854 int EltIdx = MaskVals[i] * 2; 5855 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx; 5856 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1; 5857 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5858 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5859 } 5860 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1); 5861 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5862 DAG.getNode(ISD::BUILD_VECTOR, dl, 5863 MVT::v16i8, &pshufbMask[0], 16)); 5864 if (!TwoInputs) 5865 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5866 5867 // Calculate the shuffle mask for the second input, shuffle it, and 5868 // OR it with the first shuffled input. 5869 pshufbMask.clear(); 5870 for (unsigned i = 0; i != 8; ++i) { 5871 int EltIdx = MaskVals[i] * 2; 5872 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16; 5873 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15; 5874 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8)); 5875 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8)); 5876 } 5877 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2); 5878 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 5879 DAG.getNode(ISD::BUILD_VECTOR, dl, 5880 MVT::v16i8, &pshufbMask[0], 16)); 5881 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 5882 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 5883 } 5884 5885 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order, 5886 // and update MaskVals with new element order. 5887 std::bitset<8> InOrder; 5888 if (BestLoQuad >= 0) { 5889 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 }; 5890 for (int i = 0; i != 4; ++i) { 5891 int idx = MaskVals[i]; 5892 if (idx < 0) { 5893 InOrder.set(i); 5894 } else if ((idx / 4) == BestLoQuad) { 5895 MaskV[i] = idx & 3; 5896 InOrder.set(i); 5897 } 5898 } 5899 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5900 &MaskV[0]); 5901 5902 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 5903 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5904 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16, 5905 NewV.getOperand(0), 5906 getShufflePSHUFLWImmediate(SVOp), DAG); 5907 } 5908 } 5909 5910 // If BestHi >= 0, generate a pshufhw to put the high elements in order, 5911 // and update MaskVals with the new element order. 5912 if (BestHiQuad >= 0) { 5913 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 }; 5914 for (unsigned i = 4; i != 8; ++i) { 5915 int idx = MaskVals[i]; 5916 if (idx < 0) { 5917 InOrder.set(i); 5918 } else if ((idx / 4) == BestHiQuad) { 5919 MaskV[i] = (idx & 3) + 4; 5920 InOrder.set(i); 5921 } 5922 } 5923 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16), 5924 &MaskV[0]); 5925 5926 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) { 5927 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode()); 5928 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16, 5929 NewV.getOperand(0), 5930 getShufflePSHUFHWImmediate(SVOp), DAG); 5931 } 5932 } 5933 5934 // In case BestHi & BestLo were both -1, which means each quadword has a word 5935 // from each of the four input quadwords, calculate the InOrder bitvector now 5936 // before falling through to the insert/extract cleanup. 5937 if (BestLoQuad == -1 && BestHiQuad == -1) { 5938 NewV = V1; 5939 for (int i = 0; i != 8; ++i) 5940 if (MaskVals[i] < 0 || MaskVals[i] == i) 5941 InOrder.set(i); 5942 } 5943 5944 // The other elements are put in the right place using pextrw and pinsrw. 5945 for (unsigned i = 0; i != 8; ++i) { 5946 if (InOrder[i]) 5947 continue; 5948 int EltIdx = MaskVals[i]; 5949 if (EltIdx < 0) 5950 continue; 5951 SDValue ExtOp = (EltIdx < 8) ? 5952 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1, 5953 DAG.getIntPtrConstant(EltIdx)) : 5954 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2, 5955 DAG.getIntPtrConstant(EltIdx - 8)); 5956 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp, 5957 DAG.getIntPtrConstant(i)); 5958 } 5959 return NewV; 5960} 5961 5962// v16i8 shuffles - Prefer shuffles in the following order: 5963// 1. [ssse3] 1 x pshufb 5964// 2. [ssse3] 2 x pshufb + 1 x por 5965// 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw 5966static 5967SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp, 5968 SelectionDAG &DAG, 5969 const X86TargetLowering &TLI) { 5970 SDValue V1 = SVOp->getOperand(0); 5971 SDValue V2 = SVOp->getOperand(1); 5972 DebugLoc dl = SVOp->getDebugLoc(); 5973 ArrayRef<int> MaskVals = SVOp->getMask(); 5974 5975 // If we have SSSE3, case 1 is generated when all result bytes come from 5976 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is 5977 // present, fall back to case 3. 5978 5979 // If SSSE3, use 1 pshufb instruction per vector with elements in the result. 5980 if (TLI.getSubtarget()->hasSSSE3()) { 5981 SmallVector<SDValue,16> pshufbMask; 5982 5983 // If all result elements are from one input vector, then only translate 5984 // undef mask values to 0x80 (zero out result) in the pshufb mask. 5985 // 5986 // Otherwise, we have elements from both input vectors, and must zero out 5987 // elements that come from V2 in the first mask, and V1 in the second mask 5988 // so that we can OR them together. 5989 for (unsigned i = 0; i != 16; ++i) { 5990 int EltIdx = MaskVals[i]; 5991 if (EltIdx < 0 || EltIdx >= 16) 5992 EltIdx = 0x80; 5993 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 5994 } 5995 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 5996 DAG.getNode(ISD::BUILD_VECTOR, dl, 5997 MVT::v16i8, &pshufbMask[0], 16)); 5998 5999 // As PSHUFB will zero elements with negative indices, it's safe to ignore 6000 // the 2nd operand if it's undefined or zero. 6001 if (V2.getOpcode() == ISD::UNDEF || 6002 ISD::isBuildVectorAllZeros(V2.getNode())) 6003 return V1; 6004 6005 // Calculate the shuffle mask for the second input, shuffle it, and 6006 // OR it with the first shuffled input. 6007 pshufbMask.clear(); 6008 for (unsigned i = 0; i != 16; ++i) { 6009 int EltIdx = MaskVals[i]; 6010 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16; 6011 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6012 } 6013 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 6014 DAG.getNode(ISD::BUILD_VECTOR, dl, 6015 MVT::v16i8, &pshufbMask[0], 16)); 6016 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2); 6017 } 6018 6019 // No SSSE3 - Calculate in place words and then fix all out of place words 6020 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from 6021 // the 16 different words that comprise the two doublequadword input vectors. 6022 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 6023 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 6024 SDValue NewV = V1; 6025 for (int i = 0; i != 8; ++i) { 6026 int Elt0 = MaskVals[i*2]; 6027 int Elt1 = MaskVals[i*2+1]; 6028 6029 // This word of the result is all undef, skip it. 6030 if (Elt0 < 0 && Elt1 < 0) 6031 continue; 6032 6033 // This word of the result is already in the correct place, skip it. 6034 if ((Elt0 == i*2) && (Elt1 == i*2+1)) 6035 continue; 6036 6037 SDValue Elt0Src = Elt0 < 16 ? V1 : V2; 6038 SDValue Elt1Src = Elt1 < 16 ? V1 : V2; 6039 SDValue InsElt; 6040 6041 // If Elt0 and Elt1 are defined, are consecutive, and can be load 6042 // using a single extract together, load it and store it. 6043 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) { 6044 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6045 DAG.getIntPtrConstant(Elt1 / 2)); 6046 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6047 DAG.getIntPtrConstant(i)); 6048 continue; 6049 } 6050 6051 // If Elt1 is defined, extract it from the appropriate source. If the 6052 // source byte is not also odd, shift the extracted word left 8 bits 6053 // otherwise clear the bottom 8 bits if we need to do an or. 6054 if (Elt1 >= 0) { 6055 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src, 6056 DAG.getIntPtrConstant(Elt1 / 2)); 6057 if ((Elt1 & 1) == 0) 6058 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt, 6059 DAG.getConstant(8, 6060 TLI.getShiftAmountTy(InsElt.getValueType()))); 6061 else if (Elt0 >= 0) 6062 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt, 6063 DAG.getConstant(0xFF00, MVT::i16)); 6064 } 6065 // If Elt0 is defined, extract it from the appropriate source. If the 6066 // source byte is not also even, shift the extracted word right 8 bits. If 6067 // Elt1 was also defined, OR the extracted values together before 6068 // inserting them in the result. 6069 if (Elt0 >= 0) { 6070 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, 6071 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2)); 6072 if ((Elt0 & 1) != 0) 6073 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0, 6074 DAG.getConstant(8, 6075 TLI.getShiftAmountTy(InsElt0.getValueType()))); 6076 else if (Elt1 >= 0) 6077 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0, 6078 DAG.getConstant(0x00FF, MVT::i16)); 6079 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0) 6080 : InsElt0; 6081 } 6082 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt, 6083 DAG.getIntPtrConstant(i)); 6084 } 6085 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV); 6086} 6087 6088// v32i8 shuffles - Translate to VPSHUFB if possible. 6089static 6090SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp, 6091 const X86Subtarget *Subtarget, 6092 SelectionDAG &DAG) { 6093 EVT VT = SVOp->getValueType(0); 6094 SDValue V1 = SVOp->getOperand(0); 6095 SDValue V2 = SVOp->getOperand(1); 6096 DebugLoc dl = SVOp->getDebugLoc(); 6097 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end()); 6098 6099 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6100 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode()); 6101 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode()); 6102 6103 // VPSHUFB may be generated if 6104 // (1) one of input vector is undefined or zeroinitializer. 6105 // The mask value 0x80 puts 0 in the corresponding slot of the vector. 6106 // And (2) the mask indexes don't cross the 128-bit lane. 6107 if (VT != MVT::v32i8 || !Subtarget->hasInt256() || 6108 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero)) 6109 return SDValue(); 6110 6111 if (V1IsAllZero && !V2IsAllZero) { 6112 CommuteVectorShuffleMask(MaskVals, 32); 6113 V1 = V2; 6114 } 6115 SmallVector<SDValue, 32> pshufbMask; 6116 for (unsigned i = 0; i != 32; i++) { 6117 int EltIdx = MaskVals[i]; 6118 if (EltIdx < 0 || EltIdx >= 32) 6119 EltIdx = 0x80; 6120 else { 6121 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16)) 6122 // Cross lane is not allowed. 6123 return SDValue(); 6124 EltIdx &= 0xf; 6125 } 6126 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8)); 6127 } 6128 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1, 6129 DAG.getNode(ISD::BUILD_VECTOR, dl, 6130 MVT::v32i8, &pshufbMask[0], 32)); 6131} 6132 6133/// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide 6134/// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be 6135/// done when every pair / quad of shuffle mask elements point to elements in 6136/// the right sequence. e.g. 6137/// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15> 6138static 6139SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp, 6140 SelectionDAG &DAG, DebugLoc dl) { 6141 MVT VT = SVOp->getValueType(0).getSimpleVT(); 6142 unsigned NumElems = VT.getVectorNumElements(); 6143 MVT NewVT; 6144 unsigned Scale; 6145 switch (VT.SimpleTy) { 6146 default: llvm_unreachable("Unexpected!"); 6147 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break; 6148 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break; 6149 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break; 6150 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break; 6151 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break; 6152 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break; 6153 } 6154 6155 SmallVector<int, 8> MaskVec; 6156 for (unsigned i = 0; i != NumElems; i += Scale) { 6157 int StartIdx = -1; 6158 for (unsigned j = 0; j != Scale; ++j) { 6159 int EltIdx = SVOp->getMaskElt(i+j); 6160 if (EltIdx < 0) 6161 continue; 6162 if (StartIdx < 0) 6163 StartIdx = (EltIdx / Scale); 6164 if (EltIdx != (int)(StartIdx*Scale + j)) 6165 return SDValue(); 6166 } 6167 MaskVec.push_back(StartIdx); 6168 } 6169 6170 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0)); 6171 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1)); 6172 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]); 6173} 6174 6175/// getVZextMovL - Return a zero-extending vector move low node. 6176/// 6177static SDValue getVZextMovL(EVT VT, EVT OpVT, 6178 SDValue SrcOp, SelectionDAG &DAG, 6179 const X86Subtarget *Subtarget, DebugLoc dl) { 6180 if (VT == MVT::v2f64 || VT == MVT::v4f32) { 6181 LoadSDNode *LD = NULL; 6182 if (!isScalarLoadToVector(SrcOp.getNode(), &LD)) 6183 LD = dyn_cast<LoadSDNode>(SrcOp); 6184 if (!LD) { 6185 // movssrr and movsdrr do not clear top bits. Try to use movd, movq 6186 // instead. 6187 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32; 6188 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) && 6189 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 6190 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST && 6191 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) { 6192 // PR2108 6193 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32; 6194 return DAG.getNode(ISD::BITCAST, dl, VT, 6195 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6196 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 6197 OpVT, 6198 SrcOp.getOperand(0) 6199 .getOperand(0)))); 6200 } 6201 } 6202 } 6203 6204 return DAG.getNode(ISD::BITCAST, dl, VT, 6205 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT, 6206 DAG.getNode(ISD::BITCAST, dl, 6207 OpVT, SrcOp))); 6208} 6209 6210/// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles 6211/// which could not be matched by any known target speficic shuffle 6212static SDValue 6213LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6214 6215 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG); 6216 if (NewOp.getNode()) 6217 return NewOp; 6218 6219 EVT VT = SVOp->getValueType(0); 6220 6221 unsigned NumElems = VT.getVectorNumElements(); 6222 unsigned NumLaneElems = NumElems / 2; 6223 6224 DebugLoc dl = SVOp->getDebugLoc(); 6225 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 6226 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems); 6227 SDValue Output[2]; 6228 6229 SmallVector<int, 16> Mask; 6230 for (unsigned l = 0; l < 2; ++l) { 6231 // Build a shuffle mask for the output, discovering on the fly which 6232 // input vectors to use as shuffle operands (recorded in InputUsed). 6233 // If building a suitable shuffle vector proves too hard, then bail 6234 // out with UseBuildVector set. 6235 bool UseBuildVector = false; 6236 int InputUsed[2] = { -1, -1 }; // Not yet discovered. 6237 unsigned LaneStart = l * NumLaneElems; 6238 for (unsigned i = 0; i != NumLaneElems; ++i) { 6239 // The mask element. This indexes into the input. 6240 int Idx = SVOp->getMaskElt(i+LaneStart); 6241 if (Idx < 0) { 6242 // the mask element does not index into any input vector. 6243 Mask.push_back(-1); 6244 continue; 6245 } 6246 6247 // The input vector this mask element indexes into. 6248 int Input = Idx / NumLaneElems; 6249 6250 // Turn the index into an offset from the start of the input vector. 6251 Idx -= Input * NumLaneElems; 6252 6253 // Find or create a shuffle vector operand to hold this input. 6254 unsigned OpNo; 6255 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) { 6256 if (InputUsed[OpNo] == Input) 6257 // This input vector is already an operand. 6258 break; 6259 if (InputUsed[OpNo] < 0) { 6260 // Create a new operand for this input vector. 6261 InputUsed[OpNo] = Input; 6262 break; 6263 } 6264 } 6265 6266 if (OpNo >= array_lengthof(InputUsed)) { 6267 // More than two input vectors used! Give up on trying to create a 6268 // shuffle vector. Insert all elements into a BUILD_VECTOR instead. 6269 UseBuildVector = true; 6270 break; 6271 } 6272 6273 // Add the mask index for the new shuffle vector. 6274 Mask.push_back(Idx + OpNo * NumLaneElems); 6275 } 6276 6277 if (UseBuildVector) { 6278 SmallVector<SDValue, 16> SVOps; 6279 for (unsigned i = 0; i != NumLaneElems; ++i) { 6280 // The mask element. This indexes into the input. 6281 int Idx = SVOp->getMaskElt(i+LaneStart); 6282 if (Idx < 0) { 6283 SVOps.push_back(DAG.getUNDEF(EltVT)); 6284 continue; 6285 } 6286 6287 // The input vector this mask element indexes into. 6288 int Input = Idx / NumElems; 6289 6290 // Turn the index into an offset from the start of the input vector. 6291 Idx -= Input * NumElems; 6292 6293 // Extract the vector element by hand. 6294 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, 6295 SVOp->getOperand(Input), 6296 DAG.getIntPtrConstant(Idx))); 6297 } 6298 6299 // Construct the output using a BUILD_VECTOR. 6300 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0], 6301 SVOps.size()); 6302 } else if (InputUsed[0] < 0) { 6303 // No input vectors were used! The result is undefined. 6304 Output[l] = DAG.getUNDEF(NVT); 6305 } else { 6306 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2), 6307 (InputUsed[0] % 2) * NumLaneElems, 6308 DAG, dl); 6309 // If only one input was used, use an undefined vector for the other. 6310 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) : 6311 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2), 6312 (InputUsed[1] % 2) * NumLaneElems, DAG, dl); 6313 // At least one input vector was used. Create a new shuffle vector. 6314 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]); 6315 } 6316 6317 Mask.clear(); 6318 } 6319 6320 // Concatenate the result back 6321 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]); 6322} 6323 6324/// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with 6325/// 4 elements, and match them with several different shuffle types. 6326static SDValue 6327LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) { 6328 SDValue V1 = SVOp->getOperand(0); 6329 SDValue V2 = SVOp->getOperand(1); 6330 DebugLoc dl = SVOp->getDebugLoc(); 6331 EVT VT = SVOp->getValueType(0); 6332 6333 assert(VT.is128BitVector() && "Unsupported vector size"); 6334 6335 std::pair<int, int> Locs[4]; 6336 int Mask1[] = { -1, -1, -1, -1 }; 6337 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end()); 6338 6339 unsigned NumHi = 0; 6340 unsigned NumLo = 0; 6341 for (unsigned i = 0; i != 4; ++i) { 6342 int Idx = PermMask[i]; 6343 if (Idx < 0) { 6344 Locs[i] = std::make_pair(-1, -1); 6345 } else { 6346 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!"); 6347 if (Idx < 4) { 6348 Locs[i] = std::make_pair(0, NumLo); 6349 Mask1[NumLo] = Idx; 6350 NumLo++; 6351 } else { 6352 Locs[i] = std::make_pair(1, NumHi); 6353 if (2+NumHi < 4) 6354 Mask1[2+NumHi] = Idx; 6355 NumHi++; 6356 } 6357 } 6358 } 6359 6360 if (NumLo <= 2 && NumHi <= 2) { 6361 // If no more than two elements come from either vector. This can be 6362 // implemented with two shuffles. First shuffle gather the elements. 6363 // The second shuffle, which takes the first shuffle as both of its 6364 // vector operands, put the elements into the right order. 6365 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6366 6367 int Mask2[] = { -1, -1, -1, -1 }; 6368 6369 for (unsigned i = 0; i != 4; ++i) 6370 if (Locs[i].first != -1) { 6371 unsigned Idx = (i < 2) ? 0 : 4; 6372 Idx += Locs[i].first * 2 + Locs[i].second; 6373 Mask2[i] = Idx; 6374 } 6375 6376 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]); 6377 } 6378 6379 if (NumLo == 3 || NumHi == 3) { 6380 // Otherwise, we must have three elements from one vector, call it X, and 6381 // one element from the other, call it Y. First, use a shufps to build an 6382 // intermediate vector with the one element from Y and the element from X 6383 // that will be in the same half in the final destination (the indexes don't 6384 // matter). Then, use a shufps to build the final vector, taking the half 6385 // containing the element from Y from the intermediate, and the other half 6386 // from X. 6387 if (NumHi == 3) { 6388 // Normalize it so the 3 elements come from V1. 6389 CommuteVectorShuffleMask(PermMask, 4); 6390 std::swap(V1, V2); 6391 } 6392 6393 // Find the element from V2. 6394 unsigned HiIndex; 6395 for (HiIndex = 0; HiIndex < 3; ++HiIndex) { 6396 int Val = PermMask[HiIndex]; 6397 if (Val < 0) 6398 continue; 6399 if (Val >= 4) 6400 break; 6401 } 6402 6403 Mask1[0] = PermMask[HiIndex]; 6404 Mask1[1] = -1; 6405 Mask1[2] = PermMask[HiIndex^1]; 6406 Mask1[3] = -1; 6407 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6408 6409 if (HiIndex >= 2) { 6410 Mask1[0] = PermMask[0]; 6411 Mask1[1] = PermMask[1]; 6412 Mask1[2] = HiIndex & 1 ? 6 : 4; 6413 Mask1[3] = HiIndex & 1 ? 4 : 6; 6414 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]); 6415 } 6416 6417 Mask1[0] = HiIndex & 1 ? 2 : 0; 6418 Mask1[1] = HiIndex & 1 ? 0 : 2; 6419 Mask1[2] = PermMask[2]; 6420 Mask1[3] = PermMask[3]; 6421 if (Mask1[2] >= 0) 6422 Mask1[2] += 4; 6423 if (Mask1[3] >= 0) 6424 Mask1[3] += 4; 6425 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]); 6426 } 6427 6428 // Break it into (shuffle shuffle_hi, shuffle_lo). 6429 int LoMask[] = { -1, -1, -1, -1 }; 6430 int HiMask[] = { -1, -1, -1, -1 }; 6431 6432 int *MaskPtr = LoMask; 6433 unsigned MaskIdx = 0; 6434 unsigned LoIdx = 0; 6435 unsigned HiIdx = 2; 6436 for (unsigned i = 0; i != 4; ++i) { 6437 if (i == 2) { 6438 MaskPtr = HiMask; 6439 MaskIdx = 1; 6440 LoIdx = 0; 6441 HiIdx = 2; 6442 } 6443 int Idx = PermMask[i]; 6444 if (Idx < 0) { 6445 Locs[i] = std::make_pair(-1, -1); 6446 } else if (Idx < 4) { 6447 Locs[i] = std::make_pair(MaskIdx, LoIdx); 6448 MaskPtr[LoIdx] = Idx; 6449 LoIdx++; 6450 } else { 6451 Locs[i] = std::make_pair(MaskIdx, HiIdx); 6452 MaskPtr[HiIdx] = Idx; 6453 HiIdx++; 6454 } 6455 } 6456 6457 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]); 6458 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]); 6459 int MaskOps[] = { -1, -1, -1, -1 }; 6460 for (unsigned i = 0; i != 4; ++i) 6461 if (Locs[i].first != -1) 6462 MaskOps[i] = Locs[i].first * 4 + Locs[i].second; 6463 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]); 6464} 6465 6466static bool MayFoldVectorLoad(SDValue V) { 6467 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST) 6468 V = V.getOperand(0); 6469 6470 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR) 6471 V = V.getOperand(0); 6472 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR && 6473 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF) 6474 // BUILD_VECTOR (load), undef 6475 V = V.getOperand(0); 6476 6477 return MayFoldLoad(V); 6478} 6479 6480static 6481SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) { 6482 EVT VT = Op.getValueType(); 6483 6484 // Canonizalize to v2f64. 6485 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 6486 return DAG.getNode(ISD::BITCAST, dl, VT, 6487 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64, 6488 V1, DAG)); 6489} 6490 6491static 6492SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, 6493 bool HasSSE2) { 6494 SDValue V1 = Op.getOperand(0); 6495 SDValue V2 = Op.getOperand(1); 6496 EVT VT = Op.getValueType(); 6497 6498 assert(VT != MVT::v2i64 && "unsupported shuffle type"); 6499 6500 if (HasSSE2 && VT == MVT::v2f64) 6501 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG); 6502 6503 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1) 6504 return DAG.getNode(ISD::BITCAST, dl, VT, 6505 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32, 6506 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1), 6507 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG)); 6508} 6509 6510static 6511SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) { 6512 SDValue V1 = Op.getOperand(0); 6513 SDValue V2 = Op.getOperand(1); 6514 EVT VT = Op.getValueType(); 6515 6516 assert((VT == MVT::v4i32 || VT == MVT::v4f32) && 6517 "unsupported shuffle type"); 6518 6519 if (V2.getOpcode() == ISD::UNDEF) 6520 V2 = V1; 6521 6522 // v4i32 or v4f32 6523 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG); 6524} 6525 6526static 6527SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) { 6528 SDValue V1 = Op.getOperand(0); 6529 SDValue V2 = Op.getOperand(1); 6530 EVT VT = Op.getValueType(); 6531 unsigned NumElems = VT.getVectorNumElements(); 6532 6533 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second 6534 // operand of these instructions is only memory, so check if there's a 6535 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the 6536 // same masks. 6537 bool CanFoldLoad = false; 6538 6539 // Trivial case, when V2 comes from a load. 6540 if (MayFoldVectorLoad(V2)) 6541 CanFoldLoad = true; 6542 6543 // When V1 is a load, it can be folded later into a store in isel, example: 6544 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1) 6545 // turns into: 6546 // (MOVLPSmr addr:$src1, VR128:$src2) 6547 // So, recognize this potential and also use MOVLPS or MOVLPD 6548 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op)) 6549 CanFoldLoad = true; 6550 6551 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6552 if (CanFoldLoad) { 6553 if (HasSSE2 && NumElems == 2) 6554 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG); 6555 6556 if (NumElems == 4) 6557 // If we don't care about the second element, proceed to use movss. 6558 if (SVOp->getMaskElt(1) != -1) 6559 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG); 6560 } 6561 6562 // movl and movlp will both match v2i64, but v2i64 is never matched by 6563 // movl earlier because we make it strict to avoid messing with the movlp load 6564 // folding logic (see the code above getMOVLP call). Match it here then, 6565 // this is horrible, but will stay like this until we move all shuffle 6566 // matching to x86 specific nodes. Note that for the 1st condition all 6567 // types are matched with movsd. 6568 if (HasSSE2) { 6569 // FIXME: isMOVLMask should be checked and matched before getMOVLP, 6570 // as to remove this logic from here, as much as possible 6571 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT)) 6572 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6573 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6574 } 6575 6576 assert(VT != MVT::v4i32 && "unsupported shuffle type"); 6577 6578 // Invert the operand order and use SHUFPS to match it. 6579 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1, 6580 getShuffleSHUFImmediate(SVOp), DAG); 6581} 6582 6583// Reduce a vector shuffle to zext. 6584SDValue 6585X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const { 6586 // PMOVZX is only available from SSE41. 6587 if (!Subtarget->hasSSE41()) 6588 return SDValue(); 6589 6590 EVT VT = Op.getValueType(); 6591 6592 // Only AVX2 support 256-bit vector integer extending. 6593 if (!Subtarget->hasInt256() && VT.is256BitVector()) 6594 return SDValue(); 6595 6596 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6597 DebugLoc DL = Op.getDebugLoc(); 6598 SDValue V1 = Op.getOperand(0); 6599 SDValue V2 = Op.getOperand(1); 6600 unsigned NumElems = VT.getVectorNumElements(); 6601 6602 // Extending is an unary operation and the element type of the source vector 6603 // won't be equal to or larger than i64. 6604 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() || 6605 VT.getVectorElementType() == MVT::i64) 6606 return SDValue(); 6607 6608 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4. 6609 unsigned Shift = 1; // Start from 2, i.e. 1 << 1. 6610 while ((1U << Shift) < NumElems) { 6611 if (SVOp->getMaskElt(1U << Shift) == 1) 6612 break; 6613 Shift += 1; 6614 // The maximal ratio is 8, i.e. from i8 to i64. 6615 if (Shift > 3) 6616 return SDValue(); 6617 } 6618 6619 // Check the shuffle mask. 6620 unsigned Mask = (1U << Shift) - 1; 6621 for (unsigned i = 0; i != NumElems; ++i) { 6622 int EltIdx = SVOp->getMaskElt(i); 6623 if ((i & Mask) != 0 && EltIdx != -1) 6624 return SDValue(); 6625 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift)) 6626 return SDValue(); 6627 } 6628 6629 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift; 6630 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits); 6631 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift); 6632 6633 if (!isTypeLegal(NVT)) 6634 return SDValue(); 6635 6636 // Simplify the operand as it's prepared to be fed into shuffle. 6637 unsigned SignificantBits = NVT.getSizeInBits() >> Shift; 6638 if (V1.getOpcode() == ISD::BITCAST && 6639 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR && 6640 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6641 V1.getOperand(0) 6642 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) { 6643 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x) 6644 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0); 6645 ConstantSDNode *CIdx = 6646 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1)); 6647 // If it's foldable, i.e. normal load with single use, we will let code 6648 // selection to fold it. Otherwise, we will short the conversion sequence. 6649 if (CIdx && CIdx->getZExtValue() == 0 && 6650 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) 6651 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V); 6652 } 6653 6654 return DAG.getNode(ISD::BITCAST, DL, VT, 6655 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1)); 6656} 6657 6658SDValue 6659X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const { 6660 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6661 EVT VT = Op.getValueType(); 6662 DebugLoc dl = Op.getDebugLoc(); 6663 SDValue V1 = Op.getOperand(0); 6664 SDValue V2 = Op.getOperand(1); 6665 6666 if (isZeroShuffle(SVOp)) 6667 return getZeroVector(VT, Subtarget, DAG, dl); 6668 6669 // Handle splat operations 6670 if (SVOp->isSplat()) { 6671 unsigned NumElem = VT.getVectorNumElements(); 6672 6673 // Use vbroadcast whenever the splat comes from a foldable load 6674 SDValue Broadcast = LowerVectorBroadcast(Op, DAG); 6675 if (Broadcast.getNode()) 6676 return Broadcast; 6677 6678 // Handle splats by matching through known shuffle masks 6679 if ((VT.is128BitVector() && NumElem <= 4) || 6680 (VT.is256BitVector() && NumElem <= 8)) 6681 return SDValue(); 6682 6683 // All remaning splats are promoted to target supported vector shuffles. 6684 return PromoteSplat(SVOp, DAG); 6685 } 6686 6687 // Check integer expanding shuffles. 6688 SDValue NewOp = lowerVectorIntExtend(Op, DAG); 6689 if (NewOp.getNode()) 6690 return NewOp; 6691 6692 // If the shuffle can be profitably rewritten as a narrower shuffle, then 6693 // do it! 6694 if (VT == MVT::v8i16 || VT == MVT::v16i8 || 6695 VT == MVT::v16i16 || VT == MVT::v32i8) { 6696 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6697 if (NewOp.getNode()) 6698 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp); 6699 } else if ((VT == MVT::v4i32 || 6700 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) { 6701 // FIXME: Figure out a cleaner way to do this. 6702 // Try to make use of movq to zero out the top part. 6703 if (ISD::isBuildVectorAllZeros(V2.getNode())) { 6704 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6705 if (NewOp.getNode()) { 6706 EVT NewVT = NewOp.getValueType(); 6707 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), 6708 NewVT, true, false)) 6709 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), 6710 DAG, Subtarget, dl); 6711 } 6712 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) { 6713 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl); 6714 if (NewOp.getNode()) { 6715 EVT NewVT = NewOp.getValueType(); 6716 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT)) 6717 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), 6718 DAG, Subtarget, dl); 6719 } 6720 } 6721 } 6722 return SDValue(); 6723} 6724 6725SDValue 6726X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { 6727 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 6728 SDValue V1 = Op.getOperand(0); 6729 SDValue V2 = Op.getOperand(1); 6730 EVT VT = Op.getValueType(); 6731 DebugLoc dl = Op.getDebugLoc(); 6732 unsigned NumElems = VT.getVectorNumElements(); 6733 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF; 6734 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF; 6735 bool V1IsSplat = false; 6736 bool V2IsSplat = false; 6737 bool HasSSE2 = Subtarget->hasSSE2(); 6738 bool HasFp256 = Subtarget->hasFp256(); 6739 bool HasInt256 = Subtarget->hasInt256(); 6740 MachineFunction &MF = DAG.getMachineFunction(); 6741 bool OptForSize = MF.getFunction()->getAttributes(). 6742 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize); 6743 6744 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles"); 6745 6746 if (V1IsUndef && V2IsUndef) 6747 return DAG.getUNDEF(VT); 6748 6749 assert(!V1IsUndef && "Op 1 of shuffle should not be undef"); 6750 6751 // Vector shuffle lowering takes 3 steps: 6752 // 6753 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable 6754 // narrowing and commutation of operands should be handled. 6755 // 2) Matching of shuffles with known shuffle masks to x86 target specific 6756 // shuffle nodes. 6757 // 3) Rewriting of unmatched masks into new generic shuffle operations, 6758 // so the shuffle can be broken into other shuffles and the legalizer can 6759 // try the lowering again. 6760 // 6761 // The general idea is that no vector_shuffle operation should be left to 6762 // be matched during isel, all of them must be converted to a target specific 6763 // node here. 6764 6765 // Normalize the input vectors. Here splats, zeroed vectors, profitable 6766 // narrowing and commutation of operands should be handled. The actual code 6767 // doesn't include all of those, work in progress... 6768 SDValue NewOp = NormalizeVectorShuffle(Op, DAG); 6769 if (NewOp.getNode()) 6770 return NewOp; 6771 6772 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end()); 6773 6774 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and 6775 // unpckh_undef). Only use pshufd if speed is more important than size. 6776 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 6777 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6778 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 6779 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6780 6781 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() && 6782 V2IsUndef && MayFoldVectorLoad(V1)) 6783 return getMOVDDup(Op, dl, V1, DAG); 6784 6785 if (isMOVHLPS_v_undef_Mask(M, VT)) 6786 return getMOVHighToLow(Op, dl, DAG); 6787 6788 // Use to match splats 6789 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef && 6790 (VT == MVT::v2f64 || VT == MVT::v2i64)) 6791 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6792 6793 if (isPSHUFDMask(M, VT)) { 6794 // The actual implementation will match the mask in the if above and then 6795 // during isel it can match several different instructions, not only pshufd 6796 // as its name says, sad but true, emulate the behavior for now... 6797 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64))) 6798 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG); 6799 6800 unsigned TargetMask = getShuffleSHUFImmediate(SVOp); 6801 6802 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32)) 6803 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG); 6804 6805 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64)) 6806 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, 6807 DAG); 6808 6809 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1, 6810 TargetMask, DAG); 6811 } 6812 6813 // Check if this can be converted into a logical shift. 6814 bool isLeft = false; 6815 unsigned ShAmt = 0; 6816 SDValue ShVal; 6817 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt); 6818 if (isShift && ShVal.hasOneUse()) { 6819 // If the shifted value has multiple uses, it may be cheaper to use 6820 // v_set0 + movlhps or movhlps, etc. 6821 EVT EltVT = VT.getVectorElementType(); 6822 ShAmt *= EltVT.getSizeInBits(); 6823 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6824 } 6825 6826 if (isMOVLMask(M, VT)) { 6827 if (ISD::isBuildVectorAllZeros(V1.getNode())) 6828 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl); 6829 if (!isMOVLPMask(M, VT)) { 6830 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64)) 6831 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG); 6832 6833 if (VT == MVT::v4i32 || VT == MVT::v4f32) 6834 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG); 6835 } 6836 } 6837 6838 // FIXME: fold these into legal mask. 6839 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256)) 6840 return getMOVLowToHigh(Op, dl, DAG, HasSSE2); 6841 6842 if (isMOVHLPSMask(M, VT)) 6843 return getMOVHighToLow(Op, dl, DAG); 6844 6845 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget)) 6846 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG); 6847 6848 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget)) 6849 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG); 6850 6851 if (isMOVLPMask(M, VT)) 6852 return getMOVLP(Op, dl, DAG, HasSSE2); 6853 6854 if (ShouldXformToMOVHLPS(M, VT) || 6855 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT)) 6856 return CommuteVectorShuffle(SVOp, DAG); 6857 6858 if (isShift) { 6859 // No better options. Use a vshldq / vsrldq. 6860 EVT EltVT = VT.getVectorElementType(); 6861 ShAmt *= EltVT.getSizeInBits(); 6862 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl); 6863 } 6864 6865 bool Commuted = false; 6866 // FIXME: This should also accept a bitcast of a splat? Be careful, not 6867 // 1,1,1,1 -> v8i16 though. 6868 V1IsSplat = isSplatVector(V1.getNode()); 6869 V2IsSplat = isSplatVector(V2.getNode()); 6870 6871 // Canonicalize the splat or undef, if present, to be on the RHS. 6872 if (!V2IsUndef && V1IsSplat && !V2IsSplat) { 6873 CommuteVectorShuffleMask(M, NumElems); 6874 std::swap(V1, V2); 6875 std::swap(V1IsSplat, V2IsSplat); 6876 Commuted = true; 6877 } 6878 6879 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) { 6880 // Shuffling low element of v1 into undef, just return v1. 6881 if (V2IsUndef) 6882 return V1; 6883 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which 6884 // the instruction selector will not match, so get a canonical MOVL with 6885 // swapped operands to undo the commute. 6886 return getMOVL(DAG, dl, VT, V2, V1); 6887 } 6888 6889 if (isUNPCKLMask(M, VT, HasInt256)) 6890 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6891 6892 if (isUNPCKHMask(M, VT, HasInt256)) 6893 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6894 6895 if (V2IsSplat) { 6896 // Normalize mask so all entries that point to V2 points to its first 6897 // element then try to match unpck{h|l} again. If match, return a 6898 // new vector_shuffle with the corrected mask.p 6899 SmallVector<int, 8> NewMask(M.begin(), M.end()); 6900 NormalizeMask(NewMask, NumElems); 6901 if (isUNPCKLMask(NewMask, VT, HasInt256, true)) 6902 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6903 if (isUNPCKHMask(NewMask, VT, HasInt256, true)) 6904 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6905 } 6906 6907 if (Commuted) { 6908 // Commute is back and try unpck* again. 6909 // FIXME: this seems wrong. 6910 CommuteVectorShuffleMask(M, NumElems); 6911 std::swap(V1, V2); 6912 std::swap(V1IsSplat, V2IsSplat); 6913 Commuted = false; 6914 6915 if (isUNPCKLMask(M, VT, HasInt256)) 6916 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG); 6917 6918 if (isUNPCKHMask(M, VT, HasInt256)) 6919 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG); 6920 } 6921 6922 // Normalize the node to match x86 shuffle ops if needed 6923 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true))) 6924 return CommuteVectorShuffle(SVOp, DAG); 6925 6926 // The checks below are all present in isShuffleMaskLegal, but they are 6927 // inlined here right now to enable us to directly emit target specific 6928 // nodes, and remove one by one until they don't return Op anymore. 6929 6930 if (isPALIGNRMask(M, VT, Subtarget)) 6931 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2, 6932 getShufflePALIGNRImmediate(SVOp), 6933 DAG); 6934 6935 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) && 6936 SVOp->getSplatIndex() == 0 && V2IsUndef) { 6937 if (VT == MVT::v2f64 || VT == MVT::v2i64) 6938 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6939 } 6940 6941 if (isPSHUFHWMask(M, VT, HasInt256)) 6942 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1, 6943 getShufflePSHUFHWImmediate(SVOp), 6944 DAG); 6945 6946 if (isPSHUFLWMask(M, VT, HasInt256)) 6947 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1, 6948 getShufflePSHUFLWImmediate(SVOp), 6949 DAG); 6950 6951 if (isSHUFPMask(M, VT, HasFp256)) 6952 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2, 6953 getShuffleSHUFImmediate(SVOp), DAG); 6954 6955 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256)) 6956 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG); 6957 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256)) 6958 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG); 6959 6960 //===--------------------------------------------------------------------===// 6961 // Generate target specific nodes for 128 or 256-bit shuffles only 6962 // supported in the AVX instruction set. 6963 // 6964 6965 // Handle VMOVDDUPY permutations 6966 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256)) 6967 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG); 6968 6969 // Handle VPERMILPS/D* permutations 6970 if (isVPERMILPMask(M, VT, HasFp256)) { 6971 if (HasInt256 && VT == MVT::v8i32) 6972 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, 6973 getShuffleSHUFImmediate(SVOp), DAG); 6974 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, 6975 getShuffleSHUFImmediate(SVOp), DAG); 6976 } 6977 6978 // Handle VPERM2F128/VPERM2I128 permutations 6979 if (isVPERM2X128Mask(M, VT, HasFp256)) 6980 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1, 6981 V2, getShuffleVPERM2X128Immediate(SVOp), DAG); 6982 6983 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG); 6984 if (BlendOp.getNode()) 6985 return BlendOp; 6986 6987 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) { 6988 SmallVector<SDValue, 8> permclMask; 6989 for (unsigned i = 0; i != 8; ++i) { 6990 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32)); 6991 } 6992 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, 6993 &permclMask[0], 8); 6994 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32 6995 return DAG.getNode(X86ISD::VPERMV, dl, VT, 6996 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1); 6997 } 6998 6999 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64)) 7000 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, 7001 getShuffleCLImmediate(SVOp), DAG); 7002 7003 //===--------------------------------------------------------------------===// 7004 // Since no target specific shuffle was selected for this generic one, 7005 // lower it into other known shuffles. FIXME: this isn't true yet, but 7006 // this is the plan. 7007 // 7008 7009 // Handle v8i16 specifically since SSE can do byte extraction and insertion. 7010 if (VT == MVT::v8i16) { 7011 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG); 7012 if (NewOp.getNode()) 7013 return NewOp; 7014 } 7015 7016 if (VT == MVT::v16i8) { 7017 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this); 7018 if (NewOp.getNode()) 7019 return NewOp; 7020 } 7021 7022 if (VT == MVT::v32i8) { 7023 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG); 7024 if (NewOp.getNode()) 7025 return NewOp; 7026 } 7027 7028 // Handle all 128-bit wide vectors with 4 elements, and match them with 7029 // several different shuffle types. 7030 if (NumElems == 4 && VT.is128BitVector()) 7031 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG); 7032 7033 // Handle general 256-bit shuffles 7034 if (VT.is256BitVector()) 7035 return LowerVECTOR_SHUFFLE_256(SVOp, DAG); 7036 7037 return SDValue(); 7038} 7039 7040SDValue 7041X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, 7042 SelectionDAG &DAG) const { 7043 EVT VT = Op.getValueType(); 7044 DebugLoc dl = Op.getDebugLoc(); 7045 7046 if (!Op.getOperand(0).getValueType().is128BitVector()) 7047 return SDValue(); 7048 7049 if (VT.getSizeInBits() == 8) { 7050 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, 7051 Op.getOperand(0), Op.getOperand(1)); 7052 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7053 DAG.getValueType(VT)); 7054 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7055 } 7056 7057 if (VT.getSizeInBits() == 16) { 7058 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7059 // If Idx is 0, it's cheaper to do a move instead of a pextrw. 7060 if (Idx == 0) 7061 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7062 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7063 DAG.getNode(ISD::BITCAST, dl, 7064 MVT::v4i32, 7065 Op.getOperand(0)), 7066 Op.getOperand(1))); 7067 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, 7068 Op.getOperand(0), Op.getOperand(1)); 7069 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract, 7070 DAG.getValueType(VT)); 7071 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7072 } 7073 7074 if (VT == MVT::f32) { 7075 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy 7076 // the result back to FR32 register. It's only worth matching if the 7077 // result has a single use which is a store or a bitcast to i32. And in 7078 // the case of a store, it's not worth it if the index is a constant 0, 7079 // because a MOVSSmr can be used instead, which is smaller and faster. 7080 if (!Op.hasOneUse()) 7081 return SDValue(); 7082 SDNode *User = *Op.getNode()->use_begin(); 7083 if ((User->getOpcode() != ISD::STORE || 7084 (isa<ConstantSDNode>(Op.getOperand(1)) && 7085 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) && 7086 (User->getOpcode() != ISD::BITCAST || 7087 User->getValueType(0) != MVT::i32)) 7088 return SDValue(); 7089 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7090 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, 7091 Op.getOperand(0)), 7092 Op.getOperand(1)); 7093 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract); 7094 } 7095 7096 if (VT == MVT::i32 || VT == MVT::i64) { 7097 // ExtractPS/pextrq works with constant index. 7098 if (isa<ConstantSDNode>(Op.getOperand(1))) 7099 return Op; 7100 } 7101 return SDValue(); 7102} 7103 7104SDValue 7105X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7106 SelectionDAG &DAG) const { 7107 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7108 return SDValue(); 7109 7110 SDValue Vec = Op.getOperand(0); 7111 EVT VecVT = Vec.getValueType(); 7112 7113 // If this is a 256-bit vector result, first extract the 128-bit vector and 7114 // then extract the element from the 128-bit vector. 7115 if (VecVT.is256BitVector()) { 7116 DebugLoc dl = Op.getNode()->getDebugLoc(); 7117 unsigned NumElems = VecVT.getVectorNumElements(); 7118 SDValue Idx = Op.getOperand(1); 7119 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7120 7121 // Get the 128-bit vector. 7122 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl); 7123 7124 if (IdxVal >= NumElems/2) 7125 IdxVal -= NumElems/2; 7126 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec, 7127 DAG.getConstant(IdxVal, MVT::i32)); 7128 } 7129 7130 assert(VecVT.is128BitVector() && "Unexpected vector length"); 7131 7132 if (Subtarget->hasSSE41()) { 7133 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG); 7134 if (Res.getNode()) 7135 return Res; 7136 } 7137 7138 EVT VT = Op.getValueType(); 7139 DebugLoc dl = Op.getDebugLoc(); 7140 // TODO: handle v16i8. 7141 if (VT.getSizeInBits() == 16) { 7142 SDValue Vec = Op.getOperand(0); 7143 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7144 if (Idx == 0) 7145 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, 7146 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, 7147 DAG.getNode(ISD::BITCAST, dl, 7148 MVT::v4i32, Vec), 7149 Op.getOperand(1))); 7150 // Transform it so it match pextrw which produces a 32-bit result. 7151 EVT EltVT = MVT::i32; 7152 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, 7153 Op.getOperand(0), Op.getOperand(1)); 7154 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract, 7155 DAG.getValueType(VT)); 7156 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert); 7157 } 7158 7159 if (VT.getSizeInBits() == 32) { 7160 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7161 if (Idx == 0) 7162 return Op; 7163 7164 // SHUFPS the element to the lowest double word, then movss. 7165 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 }; 7166 EVT VVT = Op.getOperand(0).getValueType(); 7167 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7168 DAG.getUNDEF(VVT), Mask); 7169 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7170 DAG.getIntPtrConstant(0)); 7171 } 7172 7173 if (VT.getSizeInBits() == 64) { 7174 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b 7175 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught 7176 // to match extract_elt for f64. 7177 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7178 if (Idx == 0) 7179 return Op; 7180 7181 // UNPCKHPD the element to the lowest double word, then movsd. 7182 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored 7183 // to a f64mem, the whole operation is folded into a single MOVHPDmr. 7184 int Mask[2] = { 1, -1 }; 7185 EVT VVT = Op.getOperand(0).getValueType(); 7186 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 7187 DAG.getUNDEF(VVT), Mask); 7188 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec, 7189 DAG.getIntPtrConstant(0)); 7190 } 7191 7192 return SDValue(); 7193} 7194 7195SDValue 7196X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, 7197 SelectionDAG &DAG) const { 7198 EVT VT = Op.getValueType(); 7199 EVT EltVT = VT.getVectorElementType(); 7200 DebugLoc dl = Op.getDebugLoc(); 7201 7202 SDValue N0 = Op.getOperand(0); 7203 SDValue N1 = Op.getOperand(1); 7204 SDValue N2 = Op.getOperand(2); 7205 7206 if (!VT.is128BitVector()) 7207 return SDValue(); 7208 7209 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) && 7210 isa<ConstantSDNode>(N2)) { 7211 unsigned Opc; 7212 if (VT == MVT::v8i16) 7213 Opc = X86ISD::PINSRW; 7214 else if (VT == MVT::v16i8) 7215 Opc = X86ISD::PINSRB; 7216 else 7217 Opc = X86ISD::PINSRB; 7218 7219 // Transform it so it match pinsr{b,w} which expects a GR32 as its second 7220 // argument. 7221 if (N1.getValueType() != MVT::i32) 7222 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7223 if (N2.getValueType() != MVT::i32) 7224 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7225 return DAG.getNode(Opc, dl, VT, N0, N1, N2); 7226 } 7227 7228 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) { 7229 // Bits [7:6] of the constant are the source select. This will always be 7230 // zero here. The DAG Combiner may combine an extract_elt index into these 7231 // bits. For example (insert (extract, 3), 2) could be matched by putting 7232 // the '3' into bits [7:6] of X86ISD::INSERTPS. 7233 // Bits [5:4] of the constant are the destination select. This is the 7234 // value of the incoming immediate. 7235 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may 7236 // combine either bitwise AND or insert of float 0.0 to set these bits. 7237 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4); 7238 // Create this as a scalar to vector.. 7239 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1); 7240 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2); 7241 } 7242 7243 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) { 7244 // PINSR* works with constant index. 7245 return Op; 7246 } 7247 return SDValue(); 7248} 7249 7250SDValue 7251X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { 7252 EVT VT = Op.getValueType(); 7253 EVT EltVT = VT.getVectorElementType(); 7254 7255 DebugLoc dl = Op.getDebugLoc(); 7256 SDValue N0 = Op.getOperand(0); 7257 SDValue N1 = Op.getOperand(1); 7258 SDValue N2 = Op.getOperand(2); 7259 7260 // If this is a 256-bit vector result, first extract the 128-bit vector, 7261 // insert the element into the extracted half and then place it back. 7262 if (VT.is256BitVector()) { 7263 if (!isa<ConstantSDNode>(N2)) 7264 return SDValue(); 7265 7266 // Get the desired 128-bit vector half. 7267 unsigned NumElems = VT.getVectorNumElements(); 7268 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue(); 7269 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl); 7270 7271 // Insert the element into the desired half. 7272 bool Upper = IdxVal >= NumElems/2; 7273 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1, 7274 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32)); 7275 7276 // Insert the changed part back to the 256-bit vector 7277 return Insert128BitVector(N0, V, IdxVal, DAG, dl); 7278 } 7279 7280 if (Subtarget->hasSSE41()) 7281 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG); 7282 7283 if (EltVT == MVT::i8) 7284 return SDValue(); 7285 7286 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) { 7287 // Transform it so it match pinsrw which expects a 16-bit value in a GR32 7288 // as its second argument. 7289 if (N1.getValueType() != MVT::i32) 7290 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1); 7291 if (N2.getValueType() != MVT::i32) 7292 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue()); 7293 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2); 7294 } 7295 return SDValue(); 7296} 7297 7298static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) { 7299 LLVMContext *Context = DAG.getContext(); 7300 DebugLoc dl = Op.getDebugLoc(); 7301 EVT OpVT = Op.getValueType(); 7302 7303 // If this is a 256-bit vector result, first insert into a 128-bit 7304 // vector and then insert into the 256-bit vector. 7305 if (!OpVT.is128BitVector()) { 7306 // Insert into a 128-bit vector. 7307 EVT VT128 = EVT::getVectorVT(*Context, 7308 OpVT.getVectorElementType(), 7309 OpVT.getVectorNumElements() / 2); 7310 7311 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0)); 7312 7313 // Insert the 128-bit vector. 7314 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl); 7315 } 7316 7317 if (OpVT == MVT::v1i64 && 7318 Op.getOperand(0).getValueType() == MVT::i64) 7319 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0)); 7320 7321 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0)); 7322 assert(OpVT.is128BitVector() && "Expected an SSE type!"); 7323 return DAG.getNode(ISD::BITCAST, dl, OpVT, 7324 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt)); 7325} 7326 7327// Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in 7328// a simple subregister reference or explicit instructions to grab 7329// upper bits of a vector. 7330static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7331 SelectionDAG &DAG) { 7332 if (Subtarget->hasFp256()) { 7333 DebugLoc dl = Op.getNode()->getDebugLoc(); 7334 SDValue Vec = Op.getNode()->getOperand(0); 7335 SDValue Idx = Op.getNode()->getOperand(1); 7336 7337 if (Op.getNode()->getValueType(0).is128BitVector() && 7338 Vec.getNode()->getValueType(0).is256BitVector() && 7339 isa<ConstantSDNode>(Idx)) { 7340 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7341 return Extract128BitVector(Vec, IdxVal, DAG, dl); 7342 } 7343 } 7344 return SDValue(); 7345} 7346 7347// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a 7348// simple superregister reference or explicit instructions to insert 7349// the upper bits of a vector. 7350static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget, 7351 SelectionDAG &DAG) { 7352 if (Subtarget->hasFp256()) { 7353 DebugLoc dl = Op.getNode()->getDebugLoc(); 7354 SDValue Vec = Op.getNode()->getOperand(0); 7355 SDValue SubVec = Op.getNode()->getOperand(1); 7356 SDValue Idx = Op.getNode()->getOperand(2); 7357 7358 if (Op.getNode()->getValueType(0).is256BitVector() && 7359 SubVec.getNode()->getValueType(0).is128BitVector() && 7360 isa<ConstantSDNode>(Idx)) { 7361 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 7362 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl); 7363 } 7364 } 7365 return SDValue(); 7366} 7367 7368// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 7369// their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is 7370// one of the above mentioned nodes. It has to be wrapped because otherwise 7371// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only 7372// be used to form addressing mode. These wrapped nodes will be selected 7373// into MOV32ri. 7374SDValue 7375X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { 7376 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 7377 7378 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7379 // global base reg. 7380 unsigned char OpFlag = 0; 7381 unsigned WrapperKind = X86ISD::Wrapper; 7382 CodeModel::Model M = getTargetMachine().getCodeModel(); 7383 7384 if (Subtarget->isPICStyleRIPRel() && 7385 (M == CodeModel::Small || M == CodeModel::Kernel)) 7386 WrapperKind = X86ISD::WrapperRIP; 7387 else if (Subtarget->isPICStyleGOT()) 7388 OpFlag = X86II::MO_GOTOFF; 7389 else if (Subtarget->isPICStyleStubPIC()) 7390 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7391 7392 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(), 7393 CP->getAlignment(), 7394 CP->getOffset(), OpFlag); 7395 DebugLoc DL = CP->getDebugLoc(); 7396 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7397 // With PIC, the address is actually $g + Offset. 7398 if (OpFlag) { 7399 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7400 DAG.getNode(X86ISD::GlobalBaseReg, 7401 DebugLoc(), getPointerTy()), 7402 Result); 7403 } 7404 7405 return Result; 7406} 7407 7408SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 7409 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 7410 7411 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7412 // global base reg. 7413 unsigned char OpFlag = 0; 7414 unsigned WrapperKind = X86ISD::Wrapper; 7415 CodeModel::Model M = getTargetMachine().getCodeModel(); 7416 7417 if (Subtarget->isPICStyleRIPRel() && 7418 (M == CodeModel::Small || M == CodeModel::Kernel)) 7419 WrapperKind = X86ISD::WrapperRIP; 7420 else if (Subtarget->isPICStyleGOT()) 7421 OpFlag = X86II::MO_GOTOFF; 7422 else if (Subtarget->isPICStyleStubPIC()) 7423 OpFlag = X86II::MO_PIC_BASE_OFFSET; 7424 7425 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(), 7426 OpFlag); 7427 DebugLoc DL = JT->getDebugLoc(); 7428 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7429 7430 // With PIC, the address is actually $g + Offset. 7431 if (OpFlag) 7432 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7433 DAG.getNode(X86ISD::GlobalBaseReg, 7434 DebugLoc(), getPointerTy()), 7435 Result); 7436 7437 return Result; 7438} 7439 7440SDValue 7441X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const { 7442 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 7443 7444 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7445 // global base reg. 7446 unsigned char OpFlag = 0; 7447 unsigned WrapperKind = X86ISD::Wrapper; 7448 CodeModel::Model M = getTargetMachine().getCodeModel(); 7449 7450 if (Subtarget->isPICStyleRIPRel() && 7451 (M == CodeModel::Small || M == CodeModel::Kernel)) { 7452 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) 7453 OpFlag = X86II::MO_GOTPCREL; 7454 WrapperKind = X86ISD::WrapperRIP; 7455 } else if (Subtarget->isPICStyleGOT()) { 7456 OpFlag = X86II::MO_GOT; 7457 } else if (Subtarget->isPICStyleStubPIC()) { 7458 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE; 7459 } else if (Subtarget->isPICStyleStubNoDynamic()) { 7460 OpFlag = X86II::MO_DARWIN_NONLAZY; 7461 } 7462 7463 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag); 7464 7465 DebugLoc DL = Op.getDebugLoc(); 7466 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7467 7468 // With PIC, the address is actually $g + Offset. 7469 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ && 7470 !Subtarget->is64Bit()) { 7471 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7472 DAG.getNode(X86ISD::GlobalBaseReg, 7473 DebugLoc(), getPointerTy()), 7474 Result); 7475 } 7476 7477 // For symbols that require a load from a stub to get the address, emit the 7478 // load. 7479 if (isGlobalStubReference(OpFlag)) 7480 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result, 7481 MachinePointerInfo::getGOT(), false, false, false, 0); 7482 7483 return Result; 7484} 7485 7486SDValue 7487X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { 7488 // Create the TargetBlockAddressAddress node. 7489 unsigned char OpFlags = 7490 Subtarget->ClassifyBlockAddressReference(); 7491 CodeModel::Model M = getTargetMachine().getCodeModel(); 7492 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 7493 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset(); 7494 DebugLoc dl = Op.getDebugLoc(); 7495 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset, 7496 OpFlags); 7497 7498 if (Subtarget->isPICStyleRIPRel() && 7499 (M == CodeModel::Small || M == CodeModel::Kernel)) 7500 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7501 else 7502 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7503 7504 // With PIC, the address is actually $g + Offset. 7505 if (isGlobalRelativeToPICBase(OpFlags)) { 7506 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7507 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7508 Result); 7509 } 7510 7511 return Result; 7512} 7513 7514SDValue 7515X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl, 7516 int64_t Offset, 7517 SelectionDAG &DAG) const { 7518 // Create the TargetGlobalAddress node, folding in the constant 7519 // offset if it is legal. 7520 unsigned char OpFlags = 7521 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 7522 CodeModel::Model M = getTargetMachine().getCodeModel(); 7523 SDValue Result; 7524 if (OpFlags == X86II::MO_NO_FLAG && 7525 X86::isOffsetSuitableForCodeModel(Offset, M)) { 7526 // A direct static reference to a global. 7527 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset); 7528 Offset = 0; 7529 } else { 7530 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags); 7531 } 7532 7533 if (Subtarget->isPICStyleRIPRel() && 7534 (M == CodeModel::Small || M == CodeModel::Kernel)) 7535 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result); 7536 else 7537 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result); 7538 7539 // With PIC, the address is actually $g + Offset. 7540 if (isGlobalRelativeToPICBase(OpFlags)) { 7541 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), 7542 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()), 7543 Result); 7544 } 7545 7546 // For globals that require a load from a stub to get the address, emit the 7547 // load. 7548 if (isGlobalStubReference(OpFlags)) 7549 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result, 7550 MachinePointerInfo::getGOT(), false, false, false, 0); 7551 7552 // If there was a non-zero offset that we didn't fold, create an explicit 7553 // addition for it. 7554 if (Offset != 0) 7555 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result, 7556 DAG.getConstant(Offset, getPointerTy())); 7557 7558 return Result; 7559} 7560 7561SDValue 7562X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { 7563 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 7564 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset(); 7565 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG); 7566} 7567 7568static SDValue 7569GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA, 7570 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg, 7571 unsigned char OperandFlags, bool LocalDynamic = false) { 7572 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7573 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7574 DebugLoc dl = GA->getDebugLoc(); 7575 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7576 GA->getValueType(0), 7577 GA->getOffset(), 7578 OperandFlags); 7579 7580 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR 7581 : X86ISD::TLSADDR; 7582 7583 if (InFlag) { 7584 SDValue Ops[] = { Chain, TGA, *InFlag }; 7585 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3); 7586 } else { 7587 SDValue Ops[] = { Chain, TGA }; 7588 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2); 7589 } 7590 7591 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 7592 MFI->setAdjustsStack(true); 7593 7594 SDValue Flag = Chain.getValue(1); 7595 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag); 7596} 7597 7598// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit 7599static SDValue 7600LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7601 const EVT PtrVT) { 7602 SDValue InFlag; 7603 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better 7604 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7605 DAG.getNode(X86ISD::GlobalBaseReg, 7606 DebugLoc(), PtrVT), InFlag); 7607 InFlag = Chain.getValue(1); 7608 7609 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD); 7610} 7611 7612// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit 7613static SDValue 7614LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7615 const EVT PtrVT) { 7616 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, 7617 X86::RAX, X86II::MO_TLSGD); 7618} 7619 7620static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA, 7621 SelectionDAG &DAG, 7622 const EVT PtrVT, 7623 bool is64Bit) { 7624 DebugLoc dl = GA->getDebugLoc(); 7625 7626 // Get the start address of the TLS block for this module. 7627 X86MachineFunctionInfo* MFI = DAG.getMachineFunction() 7628 .getInfo<X86MachineFunctionInfo>(); 7629 MFI->incNumLocalDynamicTLSAccesses(); 7630 7631 SDValue Base; 7632 if (is64Bit) { 7633 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX, 7634 X86II::MO_TLSLD, /*LocalDynamic=*/true); 7635 } else { 7636 SDValue InFlag; 7637 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX, 7638 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag); 7639 InFlag = Chain.getValue(1); 7640 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, 7641 X86II::MO_TLSLDM, /*LocalDynamic=*/true); 7642 } 7643 7644 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations 7645 // of Base. 7646 7647 // Build x@dtpoff. 7648 unsigned char OperandFlags = X86II::MO_DTPOFF; 7649 unsigned WrapperKind = X86ISD::Wrapper; 7650 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7651 GA->getValueType(0), 7652 GA->getOffset(), OperandFlags); 7653 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7654 7655 // Add x@dtpoff with the base. 7656 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base); 7657} 7658 7659// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model. 7660static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG, 7661 const EVT PtrVT, TLSModel::Model model, 7662 bool is64Bit, bool isPIC) { 7663 DebugLoc dl = GA->getDebugLoc(); 7664 7665 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit). 7666 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(), 7667 is64Bit ? 257 : 256)); 7668 7669 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 7670 DAG.getIntPtrConstant(0), 7671 MachinePointerInfo(Ptr), 7672 false, false, false, 0); 7673 7674 unsigned char OperandFlags = 0; 7675 // Most TLS accesses are not RIP relative, even on x86-64. One exception is 7676 // initialexec. 7677 unsigned WrapperKind = X86ISD::Wrapper; 7678 if (model == TLSModel::LocalExec) { 7679 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF; 7680 } else if (model == TLSModel::InitialExec) { 7681 if (is64Bit) { 7682 OperandFlags = X86II::MO_GOTTPOFF; 7683 WrapperKind = X86ISD::WrapperRIP; 7684 } else { 7685 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF; 7686 } 7687 } else { 7688 llvm_unreachable("Unexpected model"); 7689 } 7690 7691 // emit "addl x@ntpoff,%eax" (local exec) 7692 // or "addl x@indntpoff,%eax" (initial exec) 7693 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic) 7694 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7695 GA->getValueType(0), 7696 GA->getOffset(), OperandFlags); 7697 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA); 7698 7699 if (model == TLSModel::InitialExec) { 7700 if (isPIC && !is64Bit) { 7701 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, 7702 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), 7703 Offset); 7704 } 7705 7706 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset, 7707 MachinePointerInfo::getGOT(), false, false, false, 7708 0); 7709 } 7710 7711 // The address of the thread local variable is the add of the thread 7712 // pointer with the offset of the variable. 7713 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset); 7714} 7715 7716SDValue 7717X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { 7718 7719 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 7720 const GlobalValue *GV = GA->getGlobal(); 7721 7722 if (Subtarget->isTargetELF()) { 7723 TLSModel::Model model = getTargetMachine().getTLSModel(GV); 7724 7725 switch (model) { 7726 case TLSModel::GeneralDynamic: 7727 if (Subtarget->is64Bit()) 7728 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy()); 7729 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy()); 7730 case TLSModel::LocalDynamic: 7731 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(), 7732 Subtarget->is64Bit()); 7733 case TLSModel::InitialExec: 7734 case TLSModel::LocalExec: 7735 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, 7736 Subtarget->is64Bit(), 7737 getTargetMachine().getRelocationModel() == Reloc::PIC_); 7738 } 7739 llvm_unreachable("Unknown TLS model."); 7740 } 7741 7742 if (Subtarget->isTargetDarwin()) { 7743 // Darwin only has one model of TLS. Lower to that. 7744 unsigned char OpFlag = 0; 7745 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ? 7746 X86ISD::WrapperRIP : X86ISD::Wrapper; 7747 7748 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the 7749 // global base reg. 7750 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) && 7751 !Subtarget->is64Bit(); 7752 if (PIC32) 7753 OpFlag = X86II::MO_TLVP_PIC_BASE; 7754 else 7755 OpFlag = X86II::MO_TLVP; 7756 DebugLoc DL = Op.getDebugLoc(); 7757 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 7758 GA->getValueType(0), 7759 GA->getOffset(), OpFlag); 7760 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result); 7761 7762 // With PIC32, the address is actually $g + Offset. 7763 if (PIC32) 7764 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(), 7765 DAG.getNode(X86ISD::GlobalBaseReg, 7766 DebugLoc(), getPointerTy()), 7767 Offset); 7768 7769 // Lowering the machine isd will make sure everything is in the right 7770 // location. 7771 SDValue Chain = DAG.getEntryNode(); 7772 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7773 SDValue Args[] = { Chain, Offset }; 7774 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2); 7775 7776 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls. 7777 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 7778 MFI->setAdjustsStack(true); 7779 7780 // And our return value (tls address) is in the standard call return value 7781 // location. 7782 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 7783 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(), 7784 Chain.getValue(1)); 7785 } 7786 7787 if (Subtarget->isTargetWindows()) { 7788 // Just use the implicit TLS architecture 7789 // Need to generate someting similar to: 7790 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage 7791 // ; from TEB 7792 // mov ecx, dword [rel _tls_index]: Load index (from C runtime) 7793 // mov rcx, qword [rdx+rcx*8] 7794 // mov eax, .tls$:tlsvar 7795 // [rax+rcx] contains the address 7796 // Windows 64bit: gs:0x58 7797 // Windows 32bit: fs:__tls_array 7798 7799 // If GV is an alias then use the aliasee for determining 7800 // thread-localness. 7801 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 7802 GV = GA->resolveAliasedGlobal(false); 7803 DebugLoc dl = GA->getDebugLoc(); 7804 SDValue Chain = DAG.getEntryNode(); 7805 7806 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or 7807 // %gs:0x58 (64-bit). 7808 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit() 7809 ? Type::getInt8PtrTy(*DAG.getContext(), 7810 256) 7811 : Type::getInt32PtrTy(*DAG.getContext(), 7812 257)); 7813 7814 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, 7815 Subtarget->is64Bit() 7816 ? DAG.getIntPtrConstant(0x58) 7817 : DAG.getExternalSymbol("_tls_array", 7818 getPointerTy()), 7819 MachinePointerInfo(Ptr), 7820 false, false, false, 0); 7821 7822 // Load the _tls_index variable 7823 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy()); 7824 if (Subtarget->is64Bit()) 7825 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, 7826 IDX, MachinePointerInfo(), MVT::i32, 7827 false, false, 0); 7828 else 7829 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(), 7830 false, false, false, 0); 7831 7832 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), 7833 getPointerTy()); 7834 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale); 7835 7836 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX); 7837 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(), 7838 false, false, false, 0); 7839 7840 // Get the offset of start of .tls section 7841 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl, 7842 GA->getValueType(0), 7843 GA->getOffset(), X86II::MO_SECREL); 7844 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA); 7845 7846 // The address of the thread local variable is the add of the thread 7847 // pointer with the offset of the variable. 7848 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset); 7849 } 7850 7851 llvm_unreachable("TLS not implemented for this target."); 7852} 7853 7854/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values 7855/// and take a 2 x i32 value to shift plus a shift amount. 7856SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{ 7857 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 7858 EVT VT = Op.getValueType(); 7859 unsigned VTBits = VT.getSizeInBits(); 7860 DebugLoc dl = Op.getDebugLoc(); 7861 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS; 7862 SDValue ShOpLo = Op.getOperand(0); 7863 SDValue ShOpHi = Op.getOperand(1); 7864 SDValue ShAmt = Op.getOperand(2); 7865 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi, 7866 DAG.getConstant(VTBits - 1, MVT::i8)) 7867 : DAG.getConstant(0, VT); 7868 7869 SDValue Tmp2, Tmp3; 7870 if (Op.getOpcode() == ISD::SHL_PARTS) { 7871 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt); 7872 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 7873 } else { 7874 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt); 7875 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt); 7876 } 7877 7878 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt, 7879 DAG.getConstant(VTBits, MVT::i8)); 7880 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 7881 AndNode, DAG.getConstant(0, MVT::i8)); 7882 7883 SDValue Hi, Lo; 7884 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8); 7885 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond }; 7886 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond }; 7887 7888 if (Op.getOpcode() == ISD::SHL_PARTS) { 7889 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7890 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7891 } else { 7892 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4); 7893 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4); 7894 } 7895 7896 SDValue Ops[2] = { Lo, Hi }; 7897 return DAG.getMergeValues(Ops, 2, dl); 7898} 7899 7900SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, 7901 SelectionDAG &DAG) const { 7902 EVT SrcVT = Op.getOperand(0).getValueType(); 7903 7904 if (SrcVT.isVector()) 7905 return SDValue(); 7906 7907 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 && 7908 "Unknown SINT_TO_FP to lower!"); 7909 7910 // These are really Legal; return the operand so the caller accepts it as 7911 // Legal. 7912 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType())) 7913 return Op; 7914 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) && 7915 Subtarget->is64Bit()) { 7916 return Op; 7917 } 7918 7919 DebugLoc dl = Op.getDebugLoc(); 7920 unsigned Size = SrcVT.getSizeInBits()/8; 7921 MachineFunction &MF = DAG.getMachineFunction(); 7922 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false); 7923 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7924 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 7925 StackSlot, 7926 MachinePointerInfo::getFixedStack(SSFI), 7927 false, false, 0); 7928 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG); 7929} 7930 7931SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain, 7932 SDValue StackSlot, 7933 SelectionDAG &DAG) const { 7934 // Build the FILD 7935 DebugLoc DL = Op.getDebugLoc(); 7936 SDVTList Tys; 7937 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType()); 7938 if (useSSE) 7939 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue); 7940 else 7941 Tys = DAG.getVTList(Op.getValueType(), MVT::Other); 7942 7943 unsigned ByteSize = SrcVT.getSizeInBits()/8; 7944 7945 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot); 7946 MachineMemOperand *MMO; 7947 if (FI) { 7948 int SSFI = FI->getIndex(); 7949 MMO = 7950 DAG.getMachineFunction() 7951 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7952 MachineMemOperand::MOLoad, ByteSize, ByteSize); 7953 } else { 7954 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand(); 7955 StackSlot = StackSlot.getOperand(1); 7956 } 7957 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) }; 7958 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : 7959 X86ISD::FILD, DL, 7960 Tys, Ops, array_lengthof(Ops), 7961 SrcVT, MMO); 7962 7963 if (useSSE) { 7964 Chain = Result.getValue(1); 7965 SDValue InFlag = Result.getValue(2); 7966 7967 // FIXME: Currently the FST is flagged to the FILD_FLAG. This 7968 // shouldn't be necessary except that RFP cannot be live across 7969 // multiple blocks. When stackifier is fixed, they can be uncoupled. 7970 MachineFunction &MF = DAG.getMachineFunction(); 7971 unsigned SSFISize = Op.getValueType().getSizeInBits()/8; 7972 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false); 7973 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 7974 Tys = DAG.getVTList(MVT::Other); 7975 SDValue Ops[] = { 7976 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag 7977 }; 7978 MachineMemOperand *MMO = 7979 DAG.getMachineFunction() 7980 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 7981 MachineMemOperand::MOStore, SSFISize, SSFISize); 7982 7983 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, 7984 Ops, array_lengthof(Ops), 7985 Op.getValueType(), MMO); 7986 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot, 7987 MachinePointerInfo::getFixedStack(SSFI), 7988 false, false, false, 0); 7989 } 7990 7991 return Result; 7992} 7993 7994// LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion. 7995SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, 7996 SelectionDAG &DAG) const { 7997 // This algorithm is not obvious. Here it is what we're trying to output: 7998 /* 7999 movq %rax, %xmm0 8000 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U } 8001 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 } 8002 #ifdef __SSE3__ 8003 haddpd %xmm0, %xmm0 8004 #else 8005 pshufd $0x4e, %xmm0, %xmm1 8006 addpd %xmm1, %xmm0 8007 #endif 8008 */ 8009 8010 DebugLoc dl = Op.getDebugLoc(); 8011 LLVMContext *Context = DAG.getContext(); 8012 8013 // Build some magic constants. 8014 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 }; 8015 Constant *C0 = ConstantDataVector::get(*Context, CV0); 8016 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16); 8017 8018 SmallVector<Constant*,2> CV1; 8019 CV1.push_back( 8020 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)))); 8021 CV1.push_back( 8022 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)))); 8023 Constant *C1 = ConstantVector::get(CV1); 8024 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16); 8025 8026 // Load the 64-bit value into an XMM register. 8027 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, 8028 Op.getOperand(0)); 8029 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0, 8030 MachinePointerInfo::getConstantPool(), 8031 false, false, false, 16); 8032 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, 8033 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1), 8034 CLod0); 8035 8036 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1, 8037 MachinePointerInfo::getConstantPool(), 8038 false, false, false, 16); 8039 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1); 8040 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1); 8041 SDValue Result; 8042 8043 if (Subtarget->hasSSE3()) { 8044 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'. 8045 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub); 8046 } else { 8047 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub); 8048 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32, 8049 S2F, 0x4E, DAG); 8050 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, 8051 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle), 8052 Sub); 8053 } 8054 8055 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result, 8056 DAG.getIntPtrConstant(0)); 8057} 8058 8059// LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion. 8060SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, 8061 SelectionDAG &DAG) const { 8062 DebugLoc dl = Op.getDebugLoc(); 8063 // FP constant to bias correct the final result. 8064 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 8065 MVT::f64); 8066 8067 // Load the 32-bit value into an XMM register. 8068 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, 8069 Op.getOperand(0)); 8070 8071 // Zero out the upper parts of the register. 8072 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG); 8073 8074 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8075 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load), 8076 DAG.getIntPtrConstant(0)); 8077 8078 // Or the load with the bias. 8079 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, 8080 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8081 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8082 MVT::v2f64, Load)), 8083 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 8084 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, 8085 MVT::v2f64, Bias))); 8086 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, 8087 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or), 8088 DAG.getIntPtrConstant(0)); 8089 8090 // Subtract the bias. 8091 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias); 8092 8093 // Handle final rounding. 8094 EVT DestVT = Op.getValueType(); 8095 8096 if (DestVT.bitsLT(MVT::f64)) 8097 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub, 8098 DAG.getIntPtrConstant(0)); 8099 if (DestVT.bitsGT(MVT::f64)) 8100 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub); 8101 8102 // Handle final rounding. 8103 return Sub; 8104} 8105 8106SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op, 8107 SelectionDAG &DAG) const { 8108 SDValue N0 = Op.getOperand(0); 8109 EVT SVT = N0.getValueType(); 8110 DebugLoc dl = Op.getDebugLoc(); 8111 8112 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 || 8113 SVT == MVT::v8i8 || SVT == MVT::v8i16) && 8114 "Custom UINT_TO_FP is not supported!"); 8115 8116 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements()); 8117 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), 8118 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0)); 8119} 8120 8121SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, 8122 SelectionDAG &DAG) const { 8123 SDValue N0 = Op.getOperand(0); 8124 DebugLoc dl = Op.getDebugLoc(); 8125 8126 if (Op.getValueType().isVector()) 8127 return lowerUINT_TO_FP_vec(Op, DAG); 8128 8129 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't 8130 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform 8131 // the optimization here. 8132 if (DAG.SignBitIsZero(N0)) 8133 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0); 8134 8135 EVT SrcVT = N0.getValueType(); 8136 EVT DstVT = Op.getValueType(); 8137 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64) 8138 return LowerUINT_TO_FP_i64(Op, DAG); 8139 if (SrcVT == MVT::i32 && X86ScalarSSEf64) 8140 return LowerUINT_TO_FP_i32(Op, DAG); 8141 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32) 8142 return SDValue(); 8143 8144 // Make a 64-bit buffer, and use it to build an FILD. 8145 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64); 8146 if (SrcVT == MVT::i32) { 8147 SDValue WordOff = DAG.getConstant(4, getPointerTy()); 8148 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, 8149 getPointerTy(), StackSlot, WordOff); 8150 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8151 StackSlot, MachinePointerInfo(), 8152 false, false, 0); 8153 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32), 8154 OffsetSlot, MachinePointerInfo(), 8155 false, false, 0); 8156 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG); 8157 return Fild; 8158 } 8159 8160 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"); 8161 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), 8162 StackSlot, MachinePointerInfo(), 8163 false, false, 0); 8164 // For i64 source, we need to add the appropriate power of 2 if the input 8165 // was negative. This is the same as the optimization in 8166 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here, 8167 // we must be careful to do the computation in x87 extended precision, not 8168 // in SSE. (The generic code can't know it's OK to do this, or how to.) 8169 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex(); 8170 MachineMemOperand *MMO = 8171 DAG.getMachineFunction() 8172 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8173 MachineMemOperand::MOLoad, 8, 8); 8174 8175 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other); 8176 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) }; 8177 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3, 8178 MVT::i64, MMO); 8179 8180 APInt FF(32, 0x5F800000ULL); 8181 8182 // Check whether the sign bit is set. 8183 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), 8184 Op.getOperand(0), DAG.getConstant(0, MVT::i64), 8185 ISD::SETLT); 8186 8187 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits. 8188 SDValue FudgePtr = DAG.getConstantPool( 8189 ConstantInt::get(*DAG.getContext(), FF.zext(64)), 8190 getPointerTy()); 8191 8192 // Get a pointer to FF if the sign bit was set, or to 0 otherwise. 8193 SDValue Zero = DAG.getIntPtrConstant(0); 8194 SDValue Four = DAG.getIntPtrConstant(4); 8195 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet, 8196 Zero, Four); 8197 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset); 8198 8199 // Load the value out, extending it from f32 to f80. 8200 // FIXME: Avoid the extend by constructing the right constant pool? 8201 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), 8202 FudgePtr, MachinePointerInfo::getConstantPool(), 8203 MVT::f32, false, false, 4); 8204 // Extend everything to 80 bits to force it to be done on x87. 8205 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge); 8206 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0)); 8207} 8208 8209std::pair<SDValue,SDValue> X86TargetLowering:: 8210FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const { 8211 DebugLoc DL = Op.getDebugLoc(); 8212 8213 EVT DstTy = Op.getValueType(); 8214 8215 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) { 8216 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT"); 8217 DstTy = MVT::i64; 8218 } 8219 8220 assert(DstTy.getSimpleVT() <= MVT::i64 && 8221 DstTy.getSimpleVT() >= MVT::i16 && 8222 "Unknown FP_TO_INT to lower!"); 8223 8224 // These are really Legal. 8225 if (DstTy == MVT::i32 && 8226 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8227 return std::make_pair(SDValue(), SDValue()); 8228 if (Subtarget->is64Bit() && 8229 DstTy == MVT::i64 && 8230 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) 8231 return std::make_pair(SDValue(), SDValue()); 8232 8233 // We lower FP->int64 either into FISTP64 followed by a load from a temporary 8234 // stack slot, or into the FTOL runtime function. 8235 MachineFunction &MF = DAG.getMachineFunction(); 8236 unsigned MemSize = DstTy.getSizeInBits()/8; 8237 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8238 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8239 8240 unsigned Opc; 8241 if (!IsSigned && isIntegerTypeFTOL(DstTy)) 8242 Opc = X86ISD::WIN_FTOL; 8243 else 8244 switch (DstTy.getSimpleVT().SimpleTy) { 8245 default: llvm_unreachable("Invalid FP_TO_SINT to lower!"); 8246 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break; 8247 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break; 8248 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break; 8249 } 8250 8251 SDValue Chain = DAG.getEntryNode(); 8252 SDValue Value = Op.getOperand(0); 8253 EVT TheVT = Op.getOperand(0).getValueType(); 8254 // FIXME This causes a redundant load/store if the SSE-class value is already 8255 // in memory, such as if it is on the callstack. 8256 if (isScalarFPTypeInSSEReg(TheVT)) { 8257 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"); 8258 Chain = DAG.getStore(Chain, DL, Value, StackSlot, 8259 MachinePointerInfo::getFixedStack(SSFI), 8260 false, false, 0); 8261 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other); 8262 SDValue Ops[] = { 8263 Chain, StackSlot, DAG.getValueType(TheVT) 8264 }; 8265 8266 MachineMemOperand *MMO = 8267 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8268 MachineMemOperand::MOLoad, MemSize, MemSize); 8269 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3, 8270 DstTy, MMO); 8271 Chain = Value.getValue(1); 8272 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false); 8273 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 8274 } 8275 8276 MachineMemOperand *MMO = 8277 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 8278 MachineMemOperand::MOStore, MemSize, MemSize); 8279 8280 if (Opc != X86ISD::WIN_FTOL) { 8281 // Build the FP_TO_INT*_IN_MEM 8282 SDValue Ops[] = { Chain, Value, StackSlot }; 8283 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other), 8284 Ops, 3, DstTy, MMO); 8285 return std::make_pair(FIST, StackSlot); 8286 } else { 8287 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL, 8288 DAG.getVTList(MVT::Other, MVT::Glue), 8289 Chain, Value); 8290 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX, 8291 MVT::i32, ftol.getValue(1)); 8292 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX, 8293 MVT::i32, eax.getValue(2)); 8294 SDValue Ops[] = { eax, edx }; 8295 SDValue pair = IsReplace 8296 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2) 8297 : DAG.getMergeValues(Ops, 2, DL); 8298 return std::make_pair(pair, SDValue()); 8299 } 8300} 8301 8302static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG, 8303 const X86Subtarget *Subtarget) { 8304 EVT VT = Op->getValueType(0); 8305 SDValue In = Op->getOperand(0); 8306 EVT InVT = In.getValueType(); 8307 DebugLoc dl = Op->getDebugLoc(); 8308 8309 // Optimize vectors in AVX mode: 8310 // 8311 // v8i16 -> v8i32 8312 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32. 8313 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32. 8314 // Concat upper and lower parts. 8315 // 8316 // v4i32 -> v4i64 8317 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64. 8318 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64. 8319 // Concat upper and lower parts. 8320 // 8321 8322 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) && 8323 ((VT != MVT::v4i64) || (InVT != MVT::v4i32))) 8324 return SDValue(); 8325 8326 if (Subtarget->hasInt256()) 8327 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In); 8328 8329 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl); 8330 SDValue Undef = DAG.getUNDEF(InVT); 8331 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND; 8332 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8333 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef); 8334 8335 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8336 VT.getVectorNumElements()/2); 8337 8338 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo); 8339 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi); 8340 8341 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 8342} 8343 8344SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op, 8345 SelectionDAG &DAG) const { 8346 if (Subtarget->hasFp256()) { 8347 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8348 if (Res.getNode()) 8349 return Res; 8350 } 8351 8352 return SDValue(); 8353} 8354SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op, 8355 SelectionDAG &DAG) const { 8356 DebugLoc DL = Op.getDebugLoc(); 8357 EVT VT = Op.getValueType(); 8358 SDValue In = Op.getOperand(0); 8359 EVT SVT = In.getValueType(); 8360 8361 if (Subtarget->hasFp256()) { 8362 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget); 8363 if (Res.getNode()) 8364 return Res; 8365 } 8366 8367 if (!VT.is256BitVector() || !SVT.is128BitVector() || 8368 VT.getVectorNumElements() != SVT.getVectorNumElements()) 8369 return SDValue(); 8370 8371 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!"); 8372 8373 // AVX2 has better support of integer extending. 8374 if (Subtarget->hasInt256()) 8375 return DAG.getNode(X86ISD::VZEXT, DL, VT, In); 8376 8377 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In); 8378 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1}; 8379 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, 8380 DAG.getVectorShuffle(MVT::v8i16, DL, In, 8381 DAG.getUNDEF(MVT::v8i16), 8382 &Mask[0])); 8383 8384 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi); 8385} 8386 8387SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 8388 DebugLoc DL = Op.getDebugLoc(); 8389 EVT VT = Op.getValueType(); 8390 SDValue In = Op.getOperand(0); 8391 EVT SVT = In.getValueType(); 8392 8393 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) { 8394 // On AVX2, v4i64 -> v4i32 becomes VPERMD. 8395 if (Subtarget->hasInt256()) { 8396 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1}; 8397 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In); 8398 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32), 8399 ShufMask); 8400 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In, 8401 DAG.getIntPtrConstant(0)); 8402 } 8403 8404 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS. 8405 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8406 DAG.getIntPtrConstant(0)); 8407 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8408 DAG.getIntPtrConstant(2)); 8409 8410 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8411 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8412 8413 // The PSHUFD mask: 8414 static const int ShufMask1[] = {0, 2, 0, 0}; 8415 SDValue Undef = DAG.getUNDEF(VT); 8416 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1); 8417 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1); 8418 8419 // The MOVLHPS mask: 8420 static const int ShufMask2[] = {0, 1, 4, 5}; 8421 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2); 8422 } 8423 8424 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) { 8425 // On AVX2, v8i32 -> v8i16 becomed PSHUFB. 8426 if (Subtarget->hasInt256()) { 8427 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In); 8428 8429 SmallVector<SDValue,32> pshufbMask; 8430 for (unsigned i = 0; i < 2; ++i) { 8431 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8)); 8432 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8)); 8433 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8)); 8434 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8)); 8435 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8)); 8436 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8)); 8437 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8)); 8438 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8)); 8439 for (unsigned j = 0; j < 8; ++j) 8440 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8)); 8441 } 8442 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, 8443 &pshufbMask[0], 32); 8444 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV); 8445 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In); 8446 8447 static const int ShufMask[] = {0, 2, -1, -1}; 8448 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64), 8449 &ShufMask[0]); 8450 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In, 8451 DAG.getIntPtrConstant(0)); 8452 return DAG.getNode(ISD::BITCAST, DL, VT, In); 8453 } 8454 8455 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8456 DAG.getIntPtrConstant(0)); 8457 8458 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In, 8459 DAG.getIntPtrConstant(4)); 8460 8461 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo); 8462 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi); 8463 8464 // The PSHUFB mask: 8465 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13, 8466 -1, -1, -1, -1, -1, -1, -1, -1}; 8467 8468 SDValue Undef = DAG.getUNDEF(MVT::v16i8); 8469 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1); 8470 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1); 8471 8472 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo); 8473 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi); 8474 8475 // The MOVLHPS Mask: 8476 static const int ShufMask2[] = {0, 1, 4, 5}; 8477 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2); 8478 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res); 8479 } 8480 8481 // Handle truncation of V256 to V128 using shuffles. 8482 if (!VT.is128BitVector() || !SVT.is256BitVector()) 8483 return SDValue(); 8484 8485 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() && 8486 "Invalid op"); 8487 assert(Subtarget->hasFp256() && "256-bit vector without AVX!"); 8488 8489 unsigned NumElems = VT.getVectorNumElements(); 8490 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 8491 NumElems * 2); 8492 8493 SmallVector<int, 16> MaskVec(NumElems * 2, -1); 8494 // Prepare truncation shuffle mask 8495 for (unsigned i = 0; i != NumElems; ++i) 8496 MaskVec[i] = i * 2; 8497 SDValue V = DAG.getVectorShuffle(NVT, DL, 8498 DAG.getNode(ISD::BITCAST, DL, NVT, In), 8499 DAG.getUNDEF(NVT), &MaskVec[0]); 8500 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, 8501 DAG.getIntPtrConstant(0)); 8502} 8503 8504SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, 8505 SelectionDAG &DAG) const { 8506 if (Op.getValueType().isVector()) { 8507 if (Op.getValueType() == MVT::v8i16) 8508 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(), 8509 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(), 8510 MVT::v8i32, Op.getOperand(0))); 8511 return SDValue(); 8512 } 8513 8514 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8515 /*IsSigned=*/ true, /*IsReplace=*/ false); 8516 SDValue FIST = Vals.first, StackSlot = Vals.second; 8517 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal. 8518 if (FIST.getNode() == 0) return Op; 8519 8520 if (StackSlot.getNode()) 8521 // Load the result. 8522 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8523 FIST, StackSlot, MachinePointerInfo(), 8524 false, false, false, 0); 8525 8526 // The node is the result. 8527 return FIST; 8528} 8529 8530SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, 8531 SelectionDAG &DAG) const { 8532 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, 8533 /*IsSigned=*/ false, /*IsReplace=*/ false); 8534 SDValue FIST = Vals.first, StackSlot = Vals.second; 8535 assert(FIST.getNode() && "Unexpected failure"); 8536 8537 if (StackSlot.getNode()) 8538 // Load the result. 8539 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(), 8540 FIST, StackSlot, MachinePointerInfo(), 8541 false, false, false, 0); 8542 8543 // The node is the result. 8544 return FIST; 8545} 8546 8547SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op, 8548 SelectionDAG &DAG) const { 8549 DebugLoc DL = Op.getDebugLoc(); 8550 EVT VT = Op.getValueType(); 8551 SDValue In = Op.getOperand(0); 8552 EVT SVT = In.getValueType(); 8553 8554 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!"); 8555 8556 return DAG.getNode(X86ISD::VFPEXT, DL, VT, 8557 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, 8558 In, DAG.getUNDEF(SVT))); 8559} 8560 8561SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const { 8562 LLVMContext *Context = DAG.getContext(); 8563 DebugLoc dl = Op.getDebugLoc(); 8564 EVT VT = Op.getValueType(); 8565 EVT EltVT = VT; 8566 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 8567 if (VT.isVector()) { 8568 EltVT = VT.getVectorElementType(); 8569 NumElts = VT.getVectorNumElements(); 8570 } 8571 Constant *C; 8572 if (EltVT == MVT::f64) 8573 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))); 8574 else 8575 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))); 8576 C = ConstantVector::getSplat(NumElts, C); 8577 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 8578 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8579 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8580 MachinePointerInfo::getConstantPool(), 8581 false, false, false, Alignment); 8582 if (VT.isVector()) { 8583 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8584 return DAG.getNode(ISD::BITCAST, dl, VT, 8585 DAG.getNode(ISD::AND, dl, ANDVT, 8586 DAG.getNode(ISD::BITCAST, dl, ANDVT, 8587 Op.getOperand(0)), 8588 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask))); 8589 } 8590 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask); 8591} 8592 8593SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const { 8594 LLVMContext *Context = DAG.getContext(); 8595 DebugLoc dl = Op.getDebugLoc(); 8596 EVT VT = Op.getValueType(); 8597 EVT EltVT = VT; 8598 unsigned NumElts = VT == MVT::f64 ? 2 : 4; 8599 if (VT.isVector()) { 8600 EltVT = VT.getVectorElementType(); 8601 NumElts = VT.getVectorNumElements(); 8602 } 8603 Constant *C; 8604 if (EltVT == MVT::f64) 8605 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))); 8606 else 8607 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))); 8608 C = ConstantVector::getSplat(NumElts, C); 8609 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy()); 8610 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 8611 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8612 MachinePointerInfo::getConstantPool(), 8613 false, false, false, Alignment); 8614 if (VT.isVector()) { 8615 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8616 return DAG.getNode(ISD::BITCAST, dl, VT, 8617 DAG.getNode(ISD::XOR, dl, XORVT, 8618 DAG.getNode(ISD::BITCAST, dl, XORVT, 8619 Op.getOperand(0)), 8620 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask))); 8621 } 8622 8623 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask); 8624} 8625 8626SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { 8627 LLVMContext *Context = DAG.getContext(); 8628 SDValue Op0 = Op.getOperand(0); 8629 SDValue Op1 = Op.getOperand(1); 8630 DebugLoc dl = Op.getDebugLoc(); 8631 EVT VT = Op.getValueType(); 8632 EVT SrcVT = Op1.getValueType(); 8633 8634 // If second operand is smaller, extend it first. 8635 if (SrcVT.bitsLT(VT)) { 8636 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1); 8637 SrcVT = VT; 8638 } 8639 // And if it is bigger, shrink it first. 8640 if (SrcVT.bitsGT(VT)) { 8641 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1)); 8642 SrcVT = VT; 8643 } 8644 8645 // At this point the operands and the result should have the same 8646 // type, and that won't be f80 since that is not custom lowered. 8647 8648 // First get the sign bit of second operand. 8649 SmallVector<Constant*,4> CV; 8650 if (SrcVT == MVT::f64) { 8651 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))); 8652 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8653 } else { 8654 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)))); 8655 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8656 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8657 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8658 } 8659 Constant *C = ConstantVector::get(CV); 8660 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8661 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx, 8662 MachinePointerInfo::getConstantPool(), 8663 false, false, false, 16); 8664 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1); 8665 8666 // Shift sign bit right or left if the two operands have different types. 8667 if (SrcVT.bitsGT(VT)) { 8668 // Op0 is MVT::f32, Op1 is MVT::f64. 8669 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit); 8670 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit, 8671 DAG.getConstant(32, MVT::i32)); 8672 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit); 8673 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit, 8674 DAG.getIntPtrConstant(0)); 8675 } 8676 8677 // Clear first operand sign bit. 8678 CV.clear(); 8679 if (VT == MVT::f64) { 8680 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))))); 8681 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0)))); 8682 } else { 8683 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))))); 8684 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8685 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8686 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0)))); 8687 } 8688 C = ConstantVector::get(CV); 8689 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 8690 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 8691 MachinePointerInfo::getConstantPool(), 8692 false, false, false, 16); 8693 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2); 8694 8695 // Or the value with the sign bit. 8696 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit); 8697} 8698 8699static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) { 8700 SDValue N0 = Op.getOperand(0); 8701 DebugLoc dl = Op.getDebugLoc(); 8702 EVT VT = Op.getValueType(); 8703 8704 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1). 8705 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0, 8706 DAG.getConstant(1, VT)); 8707 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT)); 8708} 8709 8710// LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able. 8711// 8712SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const { 8713 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree."); 8714 8715 if (!Subtarget->hasSSE41()) 8716 return SDValue(); 8717 8718 if (!Op->hasOneUse()) 8719 return SDValue(); 8720 8721 SDNode *N = Op.getNode(); 8722 DebugLoc DL = N->getDebugLoc(); 8723 8724 SmallVector<SDValue, 8> Opnds; 8725 DenseMap<SDValue, unsigned> VecInMap; 8726 EVT VT = MVT::Other; 8727 8728 // Recognize a special case where a vector is casted into wide integer to 8729 // test all 0s. 8730 Opnds.push_back(N->getOperand(0)); 8731 Opnds.push_back(N->getOperand(1)); 8732 8733 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) { 8734 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot; 8735 // BFS traverse all OR'd operands. 8736 if (I->getOpcode() == ISD::OR) { 8737 Opnds.push_back(I->getOperand(0)); 8738 Opnds.push_back(I->getOperand(1)); 8739 // Re-evaluate the number of nodes to be traversed. 8740 e += 2; // 2 more nodes (LHS and RHS) are pushed. 8741 continue; 8742 } 8743 8744 // Quit if a non-EXTRACT_VECTOR_ELT 8745 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8746 return SDValue(); 8747 8748 // Quit if without a constant index. 8749 SDValue Idx = I->getOperand(1); 8750 if (!isa<ConstantSDNode>(Idx)) 8751 return SDValue(); 8752 8753 SDValue ExtractedFromVec = I->getOperand(0); 8754 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec); 8755 if (M == VecInMap.end()) { 8756 VT = ExtractedFromVec.getValueType(); 8757 // Quit if not 128/256-bit vector. 8758 if (!VT.is128BitVector() && !VT.is256BitVector()) 8759 return SDValue(); 8760 // Quit if not the same type. 8761 if (VecInMap.begin() != VecInMap.end() && 8762 VT != VecInMap.begin()->first.getValueType()) 8763 return SDValue(); 8764 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first; 8765 } 8766 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue(); 8767 } 8768 8769 assert((VT.is128BitVector() || VT.is256BitVector()) && 8770 "Not extracted from 128-/256-bit vector."); 8771 8772 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U; 8773 SmallVector<SDValue, 8> VecIns; 8774 8775 for (DenseMap<SDValue, unsigned>::const_iterator 8776 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) { 8777 // Quit if not all elements are used. 8778 if (I->second != FullMask) 8779 return SDValue(); 8780 VecIns.push_back(I->first); 8781 } 8782 8783 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64; 8784 8785 // Cast all vectors into TestVT for PTEST. 8786 for (unsigned i = 0, e = VecIns.size(); i < e; ++i) 8787 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]); 8788 8789 // If more than one full vectors are evaluated, OR them first before PTEST. 8790 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) { 8791 // Each iteration will OR 2 nodes and append the result until there is only 8792 // 1 node left, i.e. the final OR'd value of all vectors. 8793 SDValue LHS = VecIns[Slot]; 8794 SDValue RHS = VecIns[Slot + 1]; 8795 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS)); 8796 } 8797 8798 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, 8799 VecIns.back(), VecIns.back()); 8800} 8801 8802/// Emit nodes that will be selected as "test Op0,Op0", or something 8803/// equivalent. 8804SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, 8805 SelectionDAG &DAG) const { 8806 DebugLoc dl = Op.getDebugLoc(); 8807 8808 // CF and OF aren't always set the way we want. Determine which 8809 // of these we need. 8810 bool NeedCF = false; 8811 bool NeedOF = false; 8812 switch (X86CC) { 8813 default: break; 8814 case X86::COND_A: case X86::COND_AE: 8815 case X86::COND_B: case X86::COND_BE: 8816 NeedCF = true; 8817 break; 8818 case X86::COND_G: case X86::COND_GE: 8819 case X86::COND_L: case X86::COND_LE: 8820 case X86::COND_O: case X86::COND_NO: 8821 NeedOF = true; 8822 break; 8823 } 8824 8825 // See if we can use the EFLAGS value from the operand instead of 8826 // doing a separate TEST. TEST always sets OF and CF to 0, so unless 8827 // we prove that the arithmetic won't overflow, we can't use OF or CF. 8828 if (Op.getResNo() != 0 || NeedOF || NeedCF) 8829 // Emit a CMP with 0, which is the TEST pattern. 8830 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 8831 DAG.getConstant(0, Op.getValueType())); 8832 8833 unsigned Opcode = 0; 8834 unsigned NumOperands = 0; 8835 8836 // Truncate operations may prevent the merge of the SETCC instruction 8837 // and the arithmetic intruction before it. Attempt to truncate the operands 8838 // of the arithmetic instruction and use a reduced bit-width instruction. 8839 bool NeedTruncation = false; 8840 SDValue ArithOp = Op; 8841 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) { 8842 SDValue Arith = Op->getOperand(0); 8843 // Both the trunc and the arithmetic op need to have one user each. 8844 if (Arith->hasOneUse()) 8845 switch (Arith.getOpcode()) { 8846 default: break; 8847 case ISD::ADD: 8848 case ISD::SUB: 8849 case ISD::AND: 8850 case ISD::OR: 8851 case ISD::XOR: { 8852 NeedTruncation = true; 8853 ArithOp = Arith; 8854 } 8855 } 8856 } 8857 8858 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation 8859 // which may be the result of a CAST. We use the variable 'Op', which is the 8860 // non-casted variable when we check for possible users. 8861 switch (ArithOp.getOpcode()) { 8862 case ISD::ADD: 8863 // Due to an isel shortcoming, be conservative if this add is likely to be 8864 // selected as part of a load-modify-store instruction. When the root node 8865 // in a match is a store, isel doesn't know how to remap non-chain non-flag 8866 // uses of other nodes in the match, such as the ADD in this case. This 8867 // leads to the ADD being left around and reselected, with the result being 8868 // two adds in the output. Alas, even if none our users are stores, that 8869 // doesn't prove we're O.K. Ergo, if we have any parents that aren't 8870 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require 8871 // climbing the DAG back to the root, and it doesn't seem to be worth the 8872 // effort. 8873 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8874 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8875 if (UI->getOpcode() != ISD::CopyToReg && 8876 UI->getOpcode() != ISD::SETCC && 8877 UI->getOpcode() != ISD::STORE) 8878 goto default_case; 8879 8880 if (ConstantSDNode *C = 8881 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) { 8882 // An add of one will be selected as an INC. 8883 if (C->getAPIntValue() == 1) { 8884 Opcode = X86ISD::INC; 8885 NumOperands = 1; 8886 break; 8887 } 8888 8889 // An add of negative one (subtract of one) will be selected as a DEC. 8890 if (C->getAPIntValue().isAllOnesValue()) { 8891 Opcode = X86ISD::DEC; 8892 NumOperands = 1; 8893 break; 8894 } 8895 } 8896 8897 // Otherwise use a regular EFLAGS-setting add. 8898 Opcode = X86ISD::ADD; 8899 NumOperands = 2; 8900 break; 8901 case ISD::AND: { 8902 // If the primary and result isn't used, don't bother using X86ISD::AND, 8903 // because a TEST instruction will be better. 8904 bool NonFlagUse = false; 8905 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8906 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 8907 SDNode *User = *UI; 8908 unsigned UOpNo = UI.getOperandNo(); 8909 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) { 8910 // Look pass truncate. 8911 UOpNo = User->use_begin().getOperandNo(); 8912 User = *User->use_begin(); 8913 } 8914 8915 if (User->getOpcode() != ISD::BRCOND && 8916 User->getOpcode() != ISD::SETCC && 8917 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) { 8918 NonFlagUse = true; 8919 break; 8920 } 8921 } 8922 8923 if (!NonFlagUse) 8924 break; 8925 } 8926 // FALL THROUGH 8927 case ISD::SUB: 8928 case ISD::OR: 8929 case ISD::XOR: 8930 // Due to the ISEL shortcoming noted above, be conservative if this op is 8931 // likely to be selected as part of a load-modify-store instruction. 8932 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 8933 UE = Op.getNode()->use_end(); UI != UE; ++UI) 8934 if (UI->getOpcode() == ISD::STORE) 8935 goto default_case; 8936 8937 // Otherwise use a regular EFLAGS-setting instruction. 8938 switch (ArithOp.getOpcode()) { 8939 default: llvm_unreachable("unexpected operator!"); 8940 case ISD::SUB: Opcode = X86ISD::SUB; break; 8941 case ISD::XOR: Opcode = X86ISD::XOR; break; 8942 case ISD::AND: Opcode = X86ISD::AND; break; 8943 case ISD::OR: { 8944 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) { 8945 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG); 8946 if (EFLAGS.getNode()) 8947 return EFLAGS; 8948 } 8949 Opcode = X86ISD::OR; 8950 break; 8951 } 8952 } 8953 8954 NumOperands = 2; 8955 break; 8956 case X86ISD::ADD: 8957 case X86ISD::SUB: 8958 case X86ISD::INC: 8959 case X86ISD::DEC: 8960 case X86ISD::OR: 8961 case X86ISD::XOR: 8962 case X86ISD::AND: 8963 return SDValue(Op.getNode(), 1); 8964 default: 8965 default_case: 8966 break; 8967 } 8968 8969 // If we found that truncation is beneficial, perform the truncation and 8970 // update 'Op'. 8971 if (NeedTruncation) { 8972 EVT VT = Op.getValueType(); 8973 SDValue WideVal = Op->getOperand(0); 8974 EVT WideVT = WideVal.getValueType(); 8975 unsigned ConvertedOp = 0; 8976 // Use a target machine opcode to prevent further DAGCombine 8977 // optimizations that may separate the arithmetic operations 8978 // from the setcc node. 8979 switch (WideVal.getOpcode()) { 8980 default: break; 8981 case ISD::ADD: ConvertedOp = X86ISD::ADD; break; 8982 case ISD::SUB: ConvertedOp = X86ISD::SUB; break; 8983 case ISD::AND: ConvertedOp = X86ISD::AND; break; 8984 case ISD::OR: ConvertedOp = X86ISD::OR; break; 8985 case ISD::XOR: ConvertedOp = X86ISD::XOR; break; 8986 } 8987 8988 if (ConvertedOp) { 8989 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8990 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) { 8991 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0)); 8992 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1)); 8993 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1); 8994 } 8995 } 8996 } 8997 8998 if (Opcode == 0) 8999 // Emit a CMP with 0, which is the TEST pattern. 9000 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op, 9001 DAG.getConstant(0, Op.getValueType())); 9002 9003 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 9004 SmallVector<SDValue, 4> Ops; 9005 for (unsigned i = 0; i != NumOperands; ++i) 9006 Ops.push_back(Op.getOperand(i)); 9007 9008 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands); 9009 DAG.ReplaceAllUsesWith(Op, New); 9010 return SDValue(New.getNode(), 1); 9011} 9012 9013/// Emit nodes that will be selected as "cmp Op0,Op1", or something 9014/// equivalent. 9015SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC, 9016 SelectionDAG &DAG) const { 9017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) 9018 if (C->getAPIntValue() == 0) 9019 return EmitTest(Op0, X86CC, DAG); 9020 9021 DebugLoc dl = Op0.getDebugLoc(); 9022 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 || 9023 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) { 9024 // Use SUB instead of CMP to enable CSE between SUB and CMP. 9025 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32); 9026 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, 9027 Op0, Op1); 9028 return SDValue(Sub.getNode(), 1); 9029 } 9030 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1); 9031} 9032 9033/// Convert a comparison if required by the subtarget. 9034SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp, 9035 SelectionDAG &DAG) const { 9036 // If the subtarget does not support the FUCOMI instruction, floating-point 9037 // comparisons have to be converted. 9038 if (Subtarget->hasCMov() || 9039 Cmp.getOpcode() != X86ISD::CMP || 9040 !Cmp.getOperand(0).getValueType().isFloatingPoint() || 9041 !Cmp.getOperand(1).getValueType().isFloatingPoint()) 9042 return Cmp; 9043 9044 // The instruction selector will select an FUCOM instruction instead of 9045 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence 9046 // build an SDNode sequence that transfers the result from FPSW into EFLAGS: 9047 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8)))) 9048 DebugLoc dl = Cmp.getDebugLoc(); 9049 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp); 9050 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW); 9051 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW, 9052 DAG.getConstant(8, MVT::i8)); 9053 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl); 9054 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl); 9055} 9056 9057static bool isAllOnes(SDValue V) { 9058 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9059 return C && C->isAllOnesValue(); 9060} 9061 9062/// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node 9063/// if it's possible. 9064SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC, 9065 DebugLoc dl, SelectionDAG &DAG) const { 9066 SDValue Op0 = And.getOperand(0); 9067 SDValue Op1 = And.getOperand(1); 9068 if (Op0.getOpcode() == ISD::TRUNCATE) 9069 Op0 = Op0.getOperand(0); 9070 if (Op1.getOpcode() == ISD::TRUNCATE) 9071 Op1 = Op1.getOperand(0); 9072 9073 SDValue LHS, RHS; 9074 if (Op1.getOpcode() == ISD::SHL) 9075 std::swap(Op0, Op1); 9076 if (Op0.getOpcode() == ISD::SHL) { 9077 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0))) 9078 if (And00C->getZExtValue() == 1) { 9079 // If we looked past a truncate, check that it's only truncating away 9080 // known zeros. 9081 unsigned BitWidth = Op0.getValueSizeInBits(); 9082 unsigned AndBitWidth = And.getValueSizeInBits(); 9083 if (BitWidth > AndBitWidth) { 9084 APInt Zeros, Ones; 9085 DAG.ComputeMaskedBits(Op0, Zeros, Ones); 9086 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth) 9087 return SDValue(); 9088 } 9089 LHS = Op1; 9090 RHS = Op0.getOperand(1); 9091 } 9092 } else if (Op1.getOpcode() == ISD::Constant) { 9093 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1); 9094 uint64_t AndRHSVal = AndRHS->getZExtValue(); 9095 SDValue AndLHS = Op0; 9096 9097 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) { 9098 LHS = AndLHS.getOperand(0); 9099 RHS = AndLHS.getOperand(1); 9100 } 9101 9102 // Use BT if the immediate can't be encoded in a TEST instruction. 9103 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) { 9104 LHS = AndLHS; 9105 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType()); 9106 } 9107 } 9108 9109 if (LHS.getNode()) { 9110 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip 9111 // the condition code later. 9112 bool Invert = false; 9113 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) { 9114 Invert = true; 9115 LHS = LHS.getOperand(0); 9116 } 9117 9118 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT 9119 // instruction. Since the shift amount is in-range-or-undefined, we know 9120 // that doing a bittest on the i32 value is ok. We extend to i32 because 9121 // the encoding for the i16 version is larger than the i32 version. 9122 // Also promote i16 to i32 for performance / code size reason. 9123 if (LHS.getValueType() == MVT::i8 || 9124 LHS.getValueType() == MVT::i16) 9125 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS); 9126 9127 // If the operand types disagree, extend the shift amount to match. Since 9128 // BT ignores high bits (like shifts) we can use anyextend. 9129 if (LHS.getValueType() != RHS.getValueType()) 9130 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS); 9131 9132 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS); 9133 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B; 9134 // Flip the condition if the LHS was a not instruction 9135 if (Invert) 9136 Cond = X86::GetOppositeBranchCondition(Cond); 9137 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9138 DAG.getConstant(Cond, MVT::i8), BT); 9139 } 9140 9141 return SDValue(); 9142} 9143 9144SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 9145 9146 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); 9147 9148 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer"); 9149 SDValue Op0 = Op.getOperand(0); 9150 SDValue Op1 = Op.getOperand(1); 9151 DebugLoc dl = Op.getDebugLoc(); 9152 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 9153 9154 // Optimize to BT if possible. 9155 // Lower (X & (1 << N)) == 0 to BT(X, N). 9156 // Lower ((X >>u N) & 1) != 0 to BT(X, N). 9157 // Lower ((X >>s N) & 1) != 0 to BT(X, N). 9158 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && 9159 Op1.getOpcode() == ISD::Constant && 9160 cast<ConstantSDNode>(Op1)->isNullValue() && 9161 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9162 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG); 9163 if (NewSetCC.getNode()) 9164 return NewSetCC; 9165 } 9166 9167 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of 9168 // these. 9169 if (Op1.getOpcode() == ISD::Constant && 9170 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 || 9171 cast<ConstantSDNode>(Op1)->isNullValue()) && 9172 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 9173 9174 // If the input is a setcc, then reuse the input setcc or use a new one with 9175 // the inverted condition. 9176 if (Op0.getOpcode() == X86ISD::SETCC) { 9177 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0); 9178 bool Invert = (CC == ISD::SETNE) ^ 9179 cast<ConstantSDNode>(Op1)->isNullValue(); 9180 if (!Invert) return Op0; 9181 9182 CCode = X86::GetOppositeBranchCondition(CCode); 9183 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9184 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1)); 9185 } 9186 } 9187 9188 bool isFP = Op1.getValueType().isFloatingPoint(); 9189 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG); 9190 if (X86CC == X86::COND_INVALID) 9191 return SDValue(); 9192 9193 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG); 9194 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG); 9195 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 9196 DAG.getConstant(X86CC, MVT::i8), EFLAGS); 9197} 9198 9199// Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128 9200// ones, and then concatenate the result back. 9201static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) { 9202 EVT VT = Op.getValueType(); 9203 9204 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC && 9205 "Unsupported value type for operation"); 9206 9207 unsigned NumElems = VT.getVectorNumElements(); 9208 DebugLoc dl = Op.getDebugLoc(); 9209 SDValue CC = Op.getOperand(2); 9210 9211 // Extract the LHS vectors 9212 SDValue LHS = Op.getOperand(0); 9213 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 9214 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 9215 9216 // Extract the RHS vectors 9217 SDValue RHS = Op.getOperand(1); 9218 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 9219 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 9220 9221 // Issue the operation on the smaller types and concatenate the result back 9222 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 9223 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 9224 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 9225 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC), 9226 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC)); 9227} 9228 9229SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { 9230 SDValue Cond; 9231 SDValue Op0 = Op.getOperand(0); 9232 SDValue Op1 = Op.getOperand(1); 9233 SDValue CC = Op.getOperand(2); 9234 EVT VT = Op.getValueType(); 9235 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get(); 9236 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint(); 9237 DebugLoc dl = Op.getDebugLoc(); 9238 9239 if (isFP) { 9240#ifndef NDEBUG 9241 EVT EltVT = Op0.getValueType().getVectorElementType(); 9242 assert(EltVT == MVT::f32 || EltVT == MVT::f64); 9243#endif 9244 9245 unsigned SSECC; 9246 bool Swap = false; 9247 9248 // SSE Condition code mapping: 9249 // 0 - EQ 9250 // 1 - LT 9251 // 2 - LE 9252 // 3 - UNORD 9253 // 4 - NEQ 9254 // 5 - NLT 9255 // 6 - NLE 9256 // 7 - ORD 9257 switch (SetCCOpcode) { 9258 default: llvm_unreachable("Unexpected SETCC condition"); 9259 case ISD::SETOEQ: 9260 case ISD::SETEQ: SSECC = 0; break; 9261 case ISD::SETOGT: 9262 case ISD::SETGT: Swap = true; // Fallthrough 9263 case ISD::SETLT: 9264 case ISD::SETOLT: SSECC = 1; break; 9265 case ISD::SETOGE: 9266 case ISD::SETGE: Swap = true; // Fallthrough 9267 case ISD::SETLE: 9268 case ISD::SETOLE: SSECC = 2; break; 9269 case ISD::SETUO: SSECC = 3; break; 9270 case ISD::SETUNE: 9271 case ISD::SETNE: SSECC = 4; break; 9272 case ISD::SETULE: Swap = true; // Fallthrough 9273 case ISD::SETUGE: SSECC = 5; break; 9274 case ISD::SETULT: Swap = true; // Fallthrough 9275 case ISD::SETUGT: SSECC = 6; break; 9276 case ISD::SETO: SSECC = 7; break; 9277 case ISD::SETUEQ: 9278 case ISD::SETONE: SSECC = 8; break; 9279 } 9280 if (Swap) 9281 std::swap(Op0, Op1); 9282 9283 // In the two special cases we can't handle, emit two comparisons. 9284 if (SSECC == 8) { 9285 unsigned CC0, CC1; 9286 unsigned CombineOpc; 9287 if (SetCCOpcode == ISD::SETUEQ) { 9288 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR; 9289 } else { 9290 assert(SetCCOpcode == ISD::SETONE); 9291 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND; 9292 } 9293 9294 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9295 DAG.getConstant(CC0, MVT::i8)); 9296 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9297 DAG.getConstant(CC1, MVT::i8)); 9298 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1); 9299 } 9300 // Handle all other FP comparisons here. 9301 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1, 9302 DAG.getConstant(SSECC, MVT::i8)); 9303 } 9304 9305 // Break 256-bit integer vector compare into smaller ones. 9306 if (VT.is256BitVector() && !Subtarget->hasInt256()) 9307 return Lower256IntVSETCC(Op, DAG); 9308 9309 // We are handling one of the integer comparisons here. Since SSE only has 9310 // GT and EQ comparisons for integer, swapping operands and multiple 9311 // operations may be required for some comparisons. 9312 unsigned Opc; 9313 bool Swap = false, Invert = false, FlipSigns = false; 9314 9315 switch (SetCCOpcode) { 9316 default: llvm_unreachable("Unexpected SETCC condition"); 9317 case ISD::SETNE: Invert = true; 9318 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break; 9319 case ISD::SETLT: Swap = true; 9320 case ISD::SETGT: Opc = X86ISD::PCMPGT; break; 9321 case ISD::SETGE: Swap = true; 9322 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break; 9323 case ISD::SETULT: Swap = true; 9324 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break; 9325 case ISD::SETUGE: Swap = true; 9326 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break; 9327 } 9328 if (Swap) 9329 std::swap(Op0, Op1); 9330 9331 // Check that the operation in question is available (most are plain SSE2, 9332 // but PCMPGTQ and PCMPEQQ have different requirements). 9333 if (VT == MVT::v2i64) { 9334 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) 9335 return SDValue(); 9336 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) { 9337 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with 9338 // pcmpeqd + pshufd + pand. 9339 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!"); 9340 9341 // First cast everything to the right type, 9342 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0); 9343 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1); 9344 9345 // Do the compare. 9346 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1); 9347 9348 // Make sure the lower and upper halves are both all-ones. 9349 const int Mask[] = { 1, 0, 3, 2 }; 9350 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask); 9351 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf); 9352 9353 if (Invert) 9354 Result = DAG.getNOT(dl, Result, MVT::v4i32); 9355 9356 return DAG.getNode(ISD::BITCAST, dl, VT, Result); 9357 } 9358 } 9359 9360 // Since SSE has no unsigned integer comparisons, we need to flip the sign 9361 // bits of the inputs before performing those operations. 9362 if (FlipSigns) { 9363 EVT EltVT = VT.getVectorElementType(); 9364 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), 9365 EltVT); 9366 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit); 9367 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0], 9368 SignBits.size()); 9369 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec); 9370 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec); 9371 } 9372 9373 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1); 9374 9375 // If the logical-not of the result is required, perform that now. 9376 if (Invert) 9377 Result = DAG.getNOT(dl, Result, VT); 9378 9379 return Result; 9380} 9381 9382// isX86LogicalCmp - Return true if opcode is a X86 logical comparison. 9383static bool isX86LogicalCmp(SDValue Op) { 9384 unsigned Opc = Op.getNode()->getOpcode(); 9385 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI || 9386 Opc == X86ISD::SAHF) 9387 return true; 9388 if (Op.getResNo() == 1 && 9389 (Opc == X86ISD::ADD || 9390 Opc == X86ISD::SUB || 9391 Opc == X86ISD::ADC || 9392 Opc == X86ISD::SBB || 9393 Opc == X86ISD::SMUL || 9394 Opc == X86ISD::UMUL || 9395 Opc == X86ISD::INC || 9396 Opc == X86ISD::DEC || 9397 Opc == X86ISD::OR || 9398 Opc == X86ISD::XOR || 9399 Opc == X86ISD::AND)) 9400 return true; 9401 9402 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL) 9403 return true; 9404 9405 return false; 9406} 9407 9408static bool isZero(SDValue V) { 9409 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V); 9410 return C && C->isNullValue(); 9411} 9412 9413static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) { 9414 if (V.getOpcode() != ISD::TRUNCATE) 9415 return false; 9416 9417 SDValue VOp0 = V.getOperand(0); 9418 unsigned InBits = VOp0.getValueSizeInBits(); 9419 unsigned Bits = V.getValueSizeInBits(); 9420 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits)); 9421} 9422 9423SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 9424 bool addTest = true; 9425 SDValue Cond = Op.getOperand(0); 9426 SDValue Op1 = Op.getOperand(1); 9427 SDValue Op2 = Op.getOperand(2); 9428 DebugLoc DL = Op.getDebugLoc(); 9429 SDValue CC; 9430 9431 if (Cond.getOpcode() == ISD::SETCC) { 9432 SDValue NewCond = LowerSETCC(Cond, DAG); 9433 if (NewCond.getNode()) 9434 Cond = NewCond; 9435 } 9436 9437 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y 9438 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y 9439 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y 9440 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y 9441 if (Cond.getOpcode() == X86ISD::SETCC && 9442 Cond.getOperand(1).getOpcode() == X86ISD::CMP && 9443 isZero(Cond.getOperand(1).getOperand(1))) { 9444 SDValue Cmp = Cond.getOperand(1); 9445 9446 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue(); 9447 9448 if ((isAllOnes(Op1) || isAllOnes(Op2)) && 9449 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) { 9450 SDValue Y = isAllOnes(Op2) ? Op1 : Op2; 9451 9452 SDValue CmpOp0 = Cmp.getOperand(0); 9453 // Apply further optimizations for special cases 9454 // (select (x != 0), -1, 0) -> neg & sbb 9455 // (select (x == 0), 0, -1) -> neg & sbb 9456 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y)) 9457 if (YC->isNullValue() && 9458 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) { 9459 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32); 9460 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 9461 DAG.getConstant(0, CmpOp0.getValueType()), 9462 CmpOp0); 9463 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9464 DAG.getConstant(X86::COND_B, MVT::i8), 9465 SDValue(Neg.getNode(), 1)); 9466 return Res; 9467 } 9468 9469 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, 9470 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType())); 9471 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9472 9473 SDValue Res = // Res = 0 or -1. 9474 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9475 DAG.getConstant(X86::COND_B, MVT::i8), Cmp); 9476 9477 if (isAllOnes(Op1) != (CondCode == X86::COND_E)) 9478 Res = DAG.getNOT(DL, Res, Res.getValueType()); 9479 9480 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2); 9481 if (N2C == 0 || !N2C->isNullValue()) 9482 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y); 9483 return Res; 9484 } 9485 } 9486 9487 // Look past (and (setcc_carry (cmp ...)), 1). 9488 if (Cond.getOpcode() == ISD::AND && 9489 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 9490 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 9491 if (C && C->getAPIntValue() == 1) 9492 Cond = Cond.getOperand(0); 9493 } 9494 9495 // If condition flag is set by a X86ISD::CMP, then use it as the condition 9496 // setting operand in place of the X86ISD::SETCC. 9497 unsigned CondOpcode = Cond.getOpcode(); 9498 if (CondOpcode == X86ISD::SETCC || 9499 CondOpcode == X86ISD::SETCC_CARRY) { 9500 CC = Cond.getOperand(0); 9501 9502 SDValue Cmp = Cond.getOperand(1); 9503 unsigned Opc = Cmp.getOpcode(); 9504 EVT VT = Op.getValueType(); 9505 9506 bool IllegalFPCMov = false; 9507 if (VT.isFloatingPoint() && !VT.isVector() && 9508 !isScalarFPTypeInSSEReg(VT)) // FPStack? 9509 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue()); 9510 9511 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || 9512 Opc == X86ISD::BT) { // FIXME 9513 Cond = Cmp; 9514 addTest = false; 9515 } 9516 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 9517 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 9518 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 9519 Cond.getOperand(0).getValueType() != MVT::i8)) { 9520 SDValue LHS = Cond.getOperand(0); 9521 SDValue RHS = Cond.getOperand(1); 9522 unsigned X86Opcode; 9523 unsigned X86Cond; 9524 SDVTList VTs; 9525 switch (CondOpcode) { 9526 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9527 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9528 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9529 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9530 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9531 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9532 default: llvm_unreachable("unexpected overflowing operator"); 9533 } 9534 if (CondOpcode == ISD::UMULO) 9535 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9536 MVT::i32); 9537 else 9538 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9539 9540 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS); 9541 9542 if (CondOpcode == ISD::UMULO) 9543 Cond = X86Op.getValue(2); 9544 else 9545 Cond = X86Op.getValue(1); 9546 9547 CC = DAG.getConstant(X86Cond, MVT::i8); 9548 addTest = false; 9549 } 9550 9551 if (addTest) { 9552 // Look pass the truncate if the high bits are known zero. 9553 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 9554 Cond = Cond.getOperand(0); 9555 9556 // We know the result of AND is compared against zero. Try to match 9557 // it to BT. 9558 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9559 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG); 9560 if (NewSetCC.getNode()) { 9561 CC = NewSetCC.getOperand(0); 9562 Cond = NewSetCC.getOperand(1); 9563 addTest = false; 9564 } 9565 } 9566 } 9567 9568 if (addTest) { 9569 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9570 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9571 } 9572 9573 // a < b ? -1 : 0 -> RES = ~setcc_carry 9574 // a < b ? 0 : -1 -> RES = setcc_carry 9575 // a >= b ? -1 : 0 -> RES = setcc_carry 9576 // a >= b ? 0 : -1 -> RES = ~setcc_carry 9577 if (Cond.getOpcode() == X86ISD::SUB) { 9578 Cond = ConvertCmpIfNecessary(Cond, DAG); 9579 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue(); 9580 9581 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) && 9582 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) { 9583 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(), 9584 DAG.getConstant(X86::COND_B, MVT::i8), Cond); 9585 if (isAllOnes(Op1) != (CondCode == X86::COND_B)) 9586 return DAG.getNOT(DL, Res, Res.getValueType()); 9587 return Res; 9588 } 9589 } 9590 9591 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate 9592 // widen the cmov and push the truncate through. This avoids introducing a new 9593 // branch during isel and doesn't add any extensions. 9594 if (Op.getValueType() == MVT::i8 && 9595 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) { 9596 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0); 9597 if (T1.getValueType() == T2.getValueType() && 9598 // Blacklist CopyFromReg to avoid partial register stalls. 9599 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){ 9600 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue); 9601 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond); 9602 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov); 9603 } 9604 } 9605 9606 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if 9607 // condition is true. 9608 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue); 9609 SDValue Ops[] = { Op2, Op1, CC, Cond }; 9610 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops)); 9611} 9612 9613SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op, 9614 SelectionDAG &DAG) const { 9615 EVT VT = Op->getValueType(0); 9616 SDValue In = Op->getOperand(0); 9617 EVT InVT = In.getValueType(); 9618 DebugLoc dl = Op->getDebugLoc(); 9619 9620 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) && 9621 (VT != MVT::v8i32 || InVT != MVT::v8i16)) 9622 return SDValue(); 9623 9624 if (Subtarget->hasInt256()) 9625 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In); 9626 9627 // Optimize vectors in AVX mode 9628 // Sign extend v8i16 to v8i32 and 9629 // v4i32 to v4i64 9630 // 9631 // Divide input vector into two parts 9632 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1} 9633 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32 9634 // concat the vectors to original VT 9635 9636 unsigned NumElems = InVT.getVectorNumElements(); 9637 SDValue Undef = DAG.getUNDEF(InVT); 9638 9639 SmallVector<int,8> ShufMask1(NumElems, -1); 9640 for (unsigned i = 0; i != NumElems/2; ++i) 9641 ShufMask1[i] = i; 9642 9643 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]); 9644 9645 SmallVector<int,8> ShufMask2(NumElems, -1); 9646 for (unsigned i = 0; i != NumElems/2; ++i) 9647 ShufMask2[i] = i + NumElems/2; 9648 9649 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]); 9650 9651 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 9652 VT.getVectorNumElements()/2); 9653 9654 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 9655 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi); 9656 9657 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi); 9658} 9659 9660// isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or 9661// ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart 9662// from the AND / OR. 9663static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) { 9664 Opc = Op.getOpcode(); 9665 if (Opc != ISD::OR && Opc != ISD::AND) 9666 return false; 9667 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC && 9668 Op.getOperand(0).hasOneUse() && 9669 Op.getOperand(1).getOpcode() == X86ISD::SETCC && 9670 Op.getOperand(1).hasOneUse()); 9671} 9672 9673// isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and 9674// 1 and that the SETCC node has a single use. 9675static bool isXor1OfSetCC(SDValue Op) { 9676 if (Op.getOpcode() != ISD::XOR) 9677 return false; 9678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9679 if (N1C && N1C->getAPIntValue() == 1) { 9680 return Op.getOperand(0).getOpcode() == X86ISD::SETCC && 9681 Op.getOperand(0).hasOneUse(); 9682 } 9683 return false; 9684} 9685 9686SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 9687 bool addTest = true; 9688 SDValue Chain = Op.getOperand(0); 9689 SDValue Cond = Op.getOperand(1); 9690 SDValue Dest = Op.getOperand(2); 9691 DebugLoc dl = Op.getDebugLoc(); 9692 SDValue CC; 9693 bool Inverted = false; 9694 9695 if (Cond.getOpcode() == ISD::SETCC) { 9696 // Check for setcc([su]{add,sub,mul}o == 0). 9697 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ && 9698 isa<ConstantSDNode>(Cond.getOperand(1)) && 9699 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() && 9700 Cond.getOperand(0).getResNo() == 1 && 9701 (Cond.getOperand(0).getOpcode() == ISD::SADDO || 9702 Cond.getOperand(0).getOpcode() == ISD::UADDO || 9703 Cond.getOperand(0).getOpcode() == ISD::SSUBO || 9704 Cond.getOperand(0).getOpcode() == ISD::USUBO || 9705 Cond.getOperand(0).getOpcode() == ISD::SMULO || 9706 Cond.getOperand(0).getOpcode() == ISD::UMULO)) { 9707 Inverted = true; 9708 Cond = Cond.getOperand(0); 9709 } else { 9710 SDValue NewCond = LowerSETCC(Cond, DAG); 9711 if (NewCond.getNode()) 9712 Cond = NewCond; 9713 } 9714 } 9715#if 0 9716 // FIXME: LowerXALUO doesn't handle these!! 9717 else if (Cond.getOpcode() == X86ISD::ADD || 9718 Cond.getOpcode() == X86ISD::SUB || 9719 Cond.getOpcode() == X86ISD::SMUL || 9720 Cond.getOpcode() == X86ISD::UMUL) 9721 Cond = LowerXALUO(Cond, DAG); 9722#endif 9723 9724 // Look pass (and (setcc_carry (cmp ...)), 1). 9725 if (Cond.getOpcode() == ISD::AND && 9726 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) { 9727 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1)); 9728 if (C && C->getAPIntValue() == 1) 9729 Cond = Cond.getOperand(0); 9730 } 9731 9732 // If condition flag is set by a X86ISD::CMP, then use it as the condition 9733 // setting operand in place of the X86ISD::SETCC. 9734 unsigned CondOpcode = Cond.getOpcode(); 9735 if (CondOpcode == X86ISD::SETCC || 9736 CondOpcode == X86ISD::SETCC_CARRY) { 9737 CC = Cond.getOperand(0); 9738 9739 SDValue Cmp = Cond.getOperand(1); 9740 unsigned Opc = Cmp.getOpcode(); 9741 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp?? 9742 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) { 9743 Cond = Cmp; 9744 addTest = false; 9745 } else { 9746 switch (cast<ConstantSDNode>(CC)->getZExtValue()) { 9747 default: break; 9748 case X86::COND_O: 9749 case X86::COND_B: 9750 // These can only come from an arithmetic instruction with overflow, 9751 // e.g. SADDO, UADDO. 9752 Cond = Cond.getNode()->getOperand(1); 9753 addTest = false; 9754 break; 9755 } 9756 } 9757 } 9758 CondOpcode = Cond.getOpcode(); 9759 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO || 9760 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO || 9761 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) && 9762 Cond.getOperand(0).getValueType() != MVT::i8)) { 9763 SDValue LHS = Cond.getOperand(0); 9764 SDValue RHS = Cond.getOperand(1); 9765 unsigned X86Opcode; 9766 unsigned X86Cond; 9767 SDVTList VTs; 9768 switch (CondOpcode) { 9769 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break; 9770 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break; 9771 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break; 9772 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break; 9773 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break; 9774 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break; 9775 default: llvm_unreachable("unexpected overflowing operator"); 9776 } 9777 if (Inverted) 9778 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond); 9779 if (CondOpcode == ISD::UMULO) 9780 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(), 9781 MVT::i32); 9782 else 9783 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32); 9784 9785 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS); 9786 9787 if (CondOpcode == ISD::UMULO) 9788 Cond = X86Op.getValue(2); 9789 else 9790 Cond = X86Op.getValue(1); 9791 9792 CC = DAG.getConstant(X86Cond, MVT::i8); 9793 addTest = false; 9794 } else { 9795 unsigned CondOpc; 9796 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) { 9797 SDValue Cmp = Cond.getOperand(0).getOperand(1); 9798 if (CondOpc == ISD::OR) { 9799 // Also, recognize the pattern generated by an FCMP_UNE. We can emit 9800 // two branches instead of an explicit OR instruction with a 9801 // separate test. 9802 if (Cmp == Cond.getOperand(1).getOperand(1) && 9803 isX86LogicalCmp(Cmp)) { 9804 CC = Cond.getOperand(0).getOperand(0); 9805 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9806 Chain, Dest, CC, Cmp); 9807 CC = Cond.getOperand(1).getOperand(0); 9808 Cond = Cmp; 9809 addTest = false; 9810 } 9811 } else { // ISD::AND 9812 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit 9813 // two branches instead of an explicit AND instruction with a 9814 // separate test. However, we only do this if this block doesn't 9815 // have a fall-through edge, because this requires an explicit 9816 // jmp when the condition is false. 9817 if (Cmp == Cond.getOperand(1).getOperand(1) && 9818 isX86LogicalCmp(Cmp) && 9819 Op.getNode()->hasOneUse()) { 9820 X86::CondCode CCode = 9821 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9822 CCode = X86::GetOppositeBranchCondition(CCode); 9823 CC = DAG.getConstant(CCode, MVT::i8); 9824 SDNode *User = *Op.getNode()->use_begin(); 9825 // Look for an unconditional branch following this conditional branch. 9826 // We need this because we need to reverse the successors in order 9827 // to implement FCMP_OEQ. 9828 if (User->getOpcode() == ISD::BR) { 9829 SDValue FalseBB = User->getOperand(1); 9830 SDNode *NewBR = 9831 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9832 assert(NewBR == User); 9833 (void)NewBR; 9834 Dest = FalseBB; 9835 9836 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9837 Chain, Dest, CC, Cmp); 9838 X86::CondCode CCode = 9839 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0); 9840 CCode = X86::GetOppositeBranchCondition(CCode); 9841 CC = DAG.getConstant(CCode, MVT::i8); 9842 Cond = Cmp; 9843 addTest = false; 9844 } 9845 } 9846 } 9847 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) { 9848 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition. 9849 // It should be transformed during dag combiner except when the condition 9850 // is set by a arithmetics with overflow node. 9851 X86::CondCode CCode = 9852 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0); 9853 CCode = X86::GetOppositeBranchCondition(CCode); 9854 CC = DAG.getConstant(CCode, MVT::i8); 9855 Cond = Cond.getOperand(0).getOperand(1); 9856 addTest = false; 9857 } else if (Cond.getOpcode() == ISD::SETCC && 9858 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) { 9859 // For FCMP_OEQ, we can emit 9860 // two branches instead of an explicit AND instruction with a 9861 // separate test. However, we only do this if this block doesn't 9862 // have a fall-through edge, because this requires an explicit 9863 // jmp when the condition is false. 9864 if (Op.getNode()->hasOneUse()) { 9865 SDNode *User = *Op.getNode()->use_begin(); 9866 // Look for an unconditional branch following this conditional branch. 9867 // We need this because we need to reverse the successors in order 9868 // to implement FCMP_OEQ. 9869 if (User->getOpcode() == ISD::BR) { 9870 SDValue FalseBB = User->getOperand(1); 9871 SDNode *NewBR = 9872 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9873 assert(NewBR == User); 9874 (void)NewBR; 9875 Dest = FalseBB; 9876 9877 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9878 Cond.getOperand(0), Cond.getOperand(1)); 9879 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9880 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9881 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9882 Chain, Dest, CC, Cmp); 9883 CC = DAG.getConstant(X86::COND_P, MVT::i8); 9884 Cond = Cmp; 9885 addTest = false; 9886 } 9887 } 9888 } else if (Cond.getOpcode() == ISD::SETCC && 9889 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) { 9890 // For FCMP_UNE, we can emit 9891 // two branches instead of an explicit AND instruction with a 9892 // separate test. However, we only do this if this block doesn't 9893 // have a fall-through edge, because this requires an explicit 9894 // jmp when the condition is false. 9895 if (Op.getNode()->hasOneUse()) { 9896 SDNode *User = *Op.getNode()->use_begin(); 9897 // Look for an unconditional branch following this conditional branch. 9898 // We need this because we need to reverse the successors in order 9899 // to implement FCMP_UNE. 9900 if (User->getOpcode() == ISD::BR) { 9901 SDValue FalseBB = User->getOperand(1); 9902 SDNode *NewBR = 9903 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest); 9904 assert(NewBR == User); 9905 (void)NewBR; 9906 9907 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32, 9908 Cond.getOperand(0), Cond.getOperand(1)); 9909 Cmp = ConvertCmpIfNecessary(Cmp, DAG); 9910 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9911 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9912 Chain, Dest, CC, Cmp); 9913 CC = DAG.getConstant(X86::COND_NP, MVT::i8); 9914 Cond = Cmp; 9915 addTest = false; 9916 Dest = FalseBB; 9917 } 9918 } 9919 } 9920 } 9921 9922 if (addTest) { 9923 // Look pass the truncate if the high bits are known zero. 9924 if (isTruncWithZeroHighBitsInput(Cond, DAG)) 9925 Cond = Cond.getOperand(0); 9926 9927 // We know the result of AND is compared against zero. Try to match 9928 // it to BT. 9929 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 9930 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG); 9931 if (NewSetCC.getNode()) { 9932 CC = NewSetCC.getOperand(0); 9933 Cond = NewSetCC.getOperand(1); 9934 addTest = false; 9935 } 9936 } 9937 } 9938 9939 if (addTest) { 9940 CC = DAG.getConstant(X86::COND_NE, MVT::i8); 9941 Cond = EmitTest(Cond, X86::COND_NE, DAG); 9942 } 9943 Cond = ConvertCmpIfNecessary(Cond, DAG); 9944 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(), 9945 Chain, Dest, CC, Cond); 9946} 9947 9948// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets. 9949// Calls to _alloca is needed to probe the stack when allocating more than 4k 9950// bytes in one go. Touching the stack at 4K increments is necessary to ensure 9951// that the guard pages used by the OS virtual memory manager are allocated in 9952// correct sequence. 9953SDValue 9954X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 9955 SelectionDAG &DAG) const { 9956 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() || 9957 getTargetMachine().Options.EnableSegmentedStacks) && 9958 "This should be used only on Windows targets or when segmented stacks " 9959 "are being used"); 9960 assert(!Subtarget->isTargetEnvMacho() && "Not implemented"); 9961 DebugLoc dl = Op.getDebugLoc(); 9962 9963 // Get the inputs. 9964 SDValue Chain = Op.getOperand(0); 9965 SDValue Size = Op.getOperand(1); 9966 // FIXME: Ensure alignment here 9967 9968 bool Is64Bit = Subtarget->is64Bit(); 9969 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32; 9970 9971 if (getTargetMachine().Options.EnableSegmentedStacks) { 9972 MachineFunction &MF = DAG.getMachineFunction(); 9973 MachineRegisterInfo &MRI = MF.getRegInfo(); 9974 9975 if (Is64Bit) { 9976 // The 64 bit implementation of segmented stacks needs to clobber both r10 9977 // r11. This makes it impossible to use it along with nested parameters. 9978 const Function *F = MF.getFunction(); 9979 9980 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); 9981 I != E; ++I) 9982 if (I->hasNestAttr()) 9983 report_fatal_error("Cannot use segmented stacks with functions that " 9984 "have nested arguments."); 9985 } 9986 9987 const TargetRegisterClass *AddrRegClass = 9988 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32); 9989 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass); 9990 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size); 9991 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain, 9992 DAG.getRegister(Vreg, SPTy)); 9993 SDValue Ops1[2] = { Value, Chain }; 9994 return DAG.getMergeValues(Ops1, 2, dl); 9995 } else { 9996 SDValue Flag; 9997 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX); 9998 9999 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag); 10000 Flag = Chain.getValue(1); 10001 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10002 10003 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag); 10004 Flag = Chain.getValue(1); 10005 10006 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(), 10007 SPTy).getValue(1); 10008 10009 SDValue Ops1[2] = { Chain.getValue(0), Chain }; 10010 return DAG.getMergeValues(Ops1, 2, dl); 10011 } 10012} 10013 10014SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 10015 MachineFunction &MF = DAG.getMachineFunction(); 10016 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>(); 10017 10018 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10019 DebugLoc DL = Op.getDebugLoc(); 10020 10021 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) { 10022 // vastart just stores the address of the VarArgsFrameIndex slot into the 10023 // memory location argument. 10024 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10025 getPointerTy()); 10026 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 10027 MachinePointerInfo(SV), false, false, 0); 10028 } 10029 10030 // __va_list_tag: 10031 // gp_offset (0 - 6 * 8) 10032 // fp_offset (48 - 48 + 8 * 16) 10033 // overflow_arg_area (point to parameters coming in memory). 10034 // reg_save_area 10035 SmallVector<SDValue, 8> MemOps; 10036 SDValue FIN = Op.getOperand(1); 10037 // Store gp_offset 10038 SDValue Store = DAG.getStore(Op.getOperand(0), DL, 10039 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), 10040 MVT::i32), 10041 FIN, MachinePointerInfo(SV), false, false, 0); 10042 MemOps.push_back(Store); 10043 10044 // Store fp_offset 10045 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10046 FIN, DAG.getIntPtrConstant(4)); 10047 Store = DAG.getStore(Op.getOperand(0), DL, 10048 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), 10049 MVT::i32), 10050 FIN, MachinePointerInfo(SV, 4), false, false, 0); 10051 MemOps.push_back(Store); 10052 10053 // Store ptr to overflow_arg_area 10054 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10055 FIN, DAG.getIntPtrConstant(4)); 10056 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 10057 getPointerTy()); 10058 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, 10059 MachinePointerInfo(SV, 8), 10060 false, false, 0); 10061 MemOps.push_back(Store); 10062 10063 // Store ptr to reg_save_area. 10064 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), 10065 FIN, DAG.getIntPtrConstant(8)); 10066 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), 10067 getPointerTy()); 10068 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, 10069 MachinePointerInfo(SV, 16), false, false, 0); 10070 MemOps.push_back(Store); 10071 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 10072 &MemOps[0], MemOps.size()); 10073} 10074 10075SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 10076 assert(Subtarget->is64Bit() && 10077 "LowerVAARG only handles 64-bit va_arg!"); 10078 assert((Subtarget->isTargetLinux() || 10079 Subtarget->isTargetDarwin()) && 10080 "Unhandled target in LowerVAARG"); 10081 assert(Op.getNode()->getNumOperands() == 4); 10082 SDValue Chain = Op.getOperand(0); 10083 SDValue SrcPtr = Op.getOperand(1); 10084 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 10085 unsigned Align = Op.getConstantOperandVal(3); 10086 DebugLoc dl = Op.getDebugLoc(); 10087 10088 EVT ArgVT = Op.getNode()->getValueType(0); 10089 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 10090 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy); 10091 uint8_t ArgMode; 10092 10093 // Decide which area this value should be read from. 10094 // TODO: Implement the AMD64 ABI in its entirety. This simple 10095 // selection mechanism works only for the basic types. 10096 if (ArgVT == MVT::f80) { 10097 llvm_unreachable("va_arg for f80 not yet implemented"); 10098 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) { 10099 ArgMode = 2; // Argument passed in XMM register. Use fp_offset. 10100 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) { 10101 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset. 10102 } else { 10103 llvm_unreachable("Unhandled argument type in LowerVAARG"); 10104 } 10105 10106 if (ArgMode == 2) { 10107 // Sanity Check: Make sure using fp_offset makes sense. 10108 assert(!getTargetMachine().Options.UseSoftFloat && 10109 !(DAG.getMachineFunction() 10110 .getFunction()->getAttributes() 10111 .hasAttribute(AttributeSet::FunctionIndex, 10112 Attribute::NoImplicitFloat)) && 10113 Subtarget->hasSSE1()); 10114 } 10115 10116 // Insert VAARG_64 node into the DAG 10117 // VAARG_64 returns two values: Variable Argument Address, Chain 10118 SmallVector<SDValue, 11> InstOps; 10119 InstOps.push_back(Chain); 10120 InstOps.push_back(SrcPtr); 10121 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32)); 10122 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8)); 10123 InstOps.push_back(DAG.getConstant(Align, MVT::i32)); 10124 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other); 10125 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl, 10126 VTs, &InstOps[0], InstOps.size(), 10127 MVT::i64, 10128 MachinePointerInfo(SV), 10129 /*Align=*/0, 10130 /*Volatile=*/false, 10131 /*ReadMem=*/true, 10132 /*WriteMem=*/true); 10133 Chain = VAARG.getValue(1); 10134 10135 // Load the next argument and return it 10136 return DAG.getLoad(ArgVT, dl, 10137 Chain, 10138 VAARG, 10139 MachinePointerInfo(), 10140 false, false, false, 0); 10141} 10142 10143static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget, 10144 SelectionDAG &DAG) { 10145 // X86-64 va_list is a struct { i32, i32, i8*, i8* }. 10146 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!"); 10147 SDValue Chain = Op.getOperand(0); 10148 SDValue DstPtr = Op.getOperand(1); 10149 SDValue SrcPtr = Op.getOperand(2); 10150 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 10151 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 10152 DebugLoc DL = Op.getDebugLoc(); 10153 10154 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, 10155 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false, 10156 false, 10157 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV)); 10158} 10159 10160// getTargetVShiftNOde - Handle vector element shifts where the shift amount 10161// may or may not be a constant. Takes immediate version of shift as input. 10162static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT, 10163 SDValue SrcOp, SDValue ShAmt, 10164 SelectionDAG &DAG) { 10165 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32"); 10166 10167 if (isa<ConstantSDNode>(ShAmt)) { 10168 // Constant may be a TargetConstant. Use a regular constant. 10169 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 10170 switch (Opc) { 10171 default: llvm_unreachable("Unknown target vector shift node"); 10172 case X86ISD::VSHLI: 10173 case X86ISD::VSRLI: 10174 case X86ISD::VSRAI: 10175 return DAG.getNode(Opc, dl, VT, SrcOp, 10176 DAG.getConstant(ShiftAmt, MVT::i32)); 10177 } 10178 } 10179 10180 // Change opcode to non-immediate version 10181 switch (Opc) { 10182 default: llvm_unreachable("Unknown target vector shift node"); 10183 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break; 10184 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break; 10185 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break; 10186 } 10187 10188 // Need to build a vector containing shift amount 10189 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0 10190 SDValue ShOps[4]; 10191 ShOps[0] = ShAmt; 10192 ShOps[1] = DAG.getConstant(0, MVT::i32); 10193 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32); 10194 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4); 10195 10196 // The return type has to be a 128-bit type with the same element 10197 // type as the input type. 10198 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 10199 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits()); 10200 10201 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt); 10202 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt); 10203} 10204 10205static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) { 10206 DebugLoc dl = Op.getDebugLoc(); 10207 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10208 switch (IntNo) { 10209 default: return SDValue(); // Don't custom lower most intrinsics. 10210 // Comparison intrinsics. 10211 case Intrinsic::x86_sse_comieq_ss: 10212 case Intrinsic::x86_sse_comilt_ss: 10213 case Intrinsic::x86_sse_comile_ss: 10214 case Intrinsic::x86_sse_comigt_ss: 10215 case Intrinsic::x86_sse_comige_ss: 10216 case Intrinsic::x86_sse_comineq_ss: 10217 case Intrinsic::x86_sse_ucomieq_ss: 10218 case Intrinsic::x86_sse_ucomilt_ss: 10219 case Intrinsic::x86_sse_ucomile_ss: 10220 case Intrinsic::x86_sse_ucomigt_ss: 10221 case Intrinsic::x86_sse_ucomige_ss: 10222 case Intrinsic::x86_sse_ucomineq_ss: 10223 case Intrinsic::x86_sse2_comieq_sd: 10224 case Intrinsic::x86_sse2_comilt_sd: 10225 case Intrinsic::x86_sse2_comile_sd: 10226 case Intrinsic::x86_sse2_comigt_sd: 10227 case Intrinsic::x86_sse2_comige_sd: 10228 case Intrinsic::x86_sse2_comineq_sd: 10229 case Intrinsic::x86_sse2_ucomieq_sd: 10230 case Intrinsic::x86_sse2_ucomilt_sd: 10231 case Intrinsic::x86_sse2_ucomile_sd: 10232 case Intrinsic::x86_sse2_ucomigt_sd: 10233 case Intrinsic::x86_sse2_ucomige_sd: 10234 case Intrinsic::x86_sse2_ucomineq_sd: { 10235 unsigned Opc; 10236 ISD::CondCode CC; 10237 switch (IntNo) { 10238 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10239 case Intrinsic::x86_sse_comieq_ss: 10240 case Intrinsic::x86_sse2_comieq_sd: 10241 Opc = X86ISD::COMI; 10242 CC = ISD::SETEQ; 10243 break; 10244 case Intrinsic::x86_sse_comilt_ss: 10245 case Intrinsic::x86_sse2_comilt_sd: 10246 Opc = X86ISD::COMI; 10247 CC = ISD::SETLT; 10248 break; 10249 case Intrinsic::x86_sse_comile_ss: 10250 case Intrinsic::x86_sse2_comile_sd: 10251 Opc = X86ISD::COMI; 10252 CC = ISD::SETLE; 10253 break; 10254 case Intrinsic::x86_sse_comigt_ss: 10255 case Intrinsic::x86_sse2_comigt_sd: 10256 Opc = X86ISD::COMI; 10257 CC = ISD::SETGT; 10258 break; 10259 case Intrinsic::x86_sse_comige_ss: 10260 case Intrinsic::x86_sse2_comige_sd: 10261 Opc = X86ISD::COMI; 10262 CC = ISD::SETGE; 10263 break; 10264 case Intrinsic::x86_sse_comineq_ss: 10265 case Intrinsic::x86_sse2_comineq_sd: 10266 Opc = X86ISD::COMI; 10267 CC = ISD::SETNE; 10268 break; 10269 case Intrinsic::x86_sse_ucomieq_ss: 10270 case Intrinsic::x86_sse2_ucomieq_sd: 10271 Opc = X86ISD::UCOMI; 10272 CC = ISD::SETEQ; 10273 break; 10274 case Intrinsic::x86_sse_ucomilt_ss: 10275 case Intrinsic::x86_sse2_ucomilt_sd: 10276 Opc = X86ISD::UCOMI; 10277 CC = ISD::SETLT; 10278 break; 10279 case Intrinsic::x86_sse_ucomile_ss: 10280 case Intrinsic::x86_sse2_ucomile_sd: 10281 Opc = X86ISD::UCOMI; 10282 CC = ISD::SETLE; 10283 break; 10284 case Intrinsic::x86_sse_ucomigt_ss: 10285 case Intrinsic::x86_sse2_ucomigt_sd: 10286 Opc = X86ISD::UCOMI; 10287 CC = ISD::SETGT; 10288 break; 10289 case Intrinsic::x86_sse_ucomige_ss: 10290 case Intrinsic::x86_sse2_ucomige_sd: 10291 Opc = X86ISD::UCOMI; 10292 CC = ISD::SETGE; 10293 break; 10294 case Intrinsic::x86_sse_ucomineq_ss: 10295 case Intrinsic::x86_sse2_ucomineq_sd: 10296 Opc = X86ISD::UCOMI; 10297 CC = ISD::SETNE; 10298 break; 10299 } 10300 10301 SDValue LHS = Op.getOperand(1); 10302 SDValue RHS = Op.getOperand(2); 10303 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG); 10304 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!"); 10305 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS); 10306 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 10307 DAG.getConstant(X86CC, MVT::i8), Cond); 10308 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10309 } 10310 10311 // Arithmetic intrinsics. 10312 case Intrinsic::x86_sse2_pmulu_dq: 10313 case Intrinsic::x86_avx2_pmulu_dq: 10314 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(), 10315 Op.getOperand(1), Op.getOperand(2)); 10316 10317 // SSE2/AVX2 sub with unsigned saturation intrinsics 10318 case Intrinsic::x86_sse2_psubus_b: 10319 case Intrinsic::x86_sse2_psubus_w: 10320 case Intrinsic::x86_avx2_psubus_b: 10321 case Intrinsic::x86_avx2_psubus_w: 10322 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(), 10323 Op.getOperand(1), Op.getOperand(2)); 10324 10325 // SSE3/AVX horizontal add/sub intrinsics 10326 case Intrinsic::x86_sse3_hadd_ps: 10327 case Intrinsic::x86_sse3_hadd_pd: 10328 case Intrinsic::x86_avx_hadd_ps_256: 10329 case Intrinsic::x86_avx_hadd_pd_256: 10330 case Intrinsic::x86_sse3_hsub_ps: 10331 case Intrinsic::x86_sse3_hsub_pd: 10332 case Intrinsic::x86_avx_hsub_ps_256: 10333 case Intrinsic::x86_avx_hsub_pd_256: 10334 case Intrinsic::x86_ssse3_phadd_w_128: 10335 case Intrinsic::x86_ssse3_phadd_d_128: 10336 case Intrinsic::x86_avx2_phadd_w: 10337 case Intrinsic::x86_avx2_phadd_d: 10338 case Intrinsic::x86_ssse3_phsub_w_128: 10339 case Intrinsic::x86_ssse3_phsub_d_128: 10340 case Intrinsic::x86_avx2_phsub_w: 10341 case Intrinsic::x86_avx2_phsub_d: { 10342 unsigned Opcode; 10343 switch (IntNo) { 10344 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10345 case Intrinsic::x86_sse3_hadd_ps: 10346 case Intrinsic::x86_sse3_hadd_pd: 10347 case Intrinsic::x86_avx_hadd_ps_256: 10348 case Intrinsic::x86_avx_hadd_pd_256: 10349 Opcode = X86ISD::FHADD; 10350 break; 10351 case Intrinsic::x86_sse3_hsub_ps: 10352 case Intrinsic::x86_sse3_hsub_pd: 10353 case Intrinsic::x86_avx_hsub_ps_256: 10354 case Intrinsic::x86_avx_hsub_pd_256: 10355 Opcode = X86ISD::FHSUB; 10356 break; 10357 case Intrinsic::x86_ssse3_phadd_w_128: 10358 case Intrinsic::x86_ssse3_phadd_d_128: 10359 case Intrinsic::x86_avx2_phadd_w: 10360 case Intrinsic::x86_avx2_phadd_d: 10361 Opcode = X86ISD::HADD; 10362 break; 10363 case Intrinsic::x86_ssse3_phsub_w_128: 10364 case Intrinsic::x86_ssse3_phsub_d_128: 10365 case Intrinsic::x86_avx2_phsub_w: 10366 case Intrinsic::x86_avx2_phsub_d: 10367 Opcode = X86ISD::HSUB; 10368 break; 10369 } 10370 return DAG.getNode(Opcode, dl, Op.getValueType(), 10371 Op.getOperand(1), Op.getOperand(2)); 10372 } 10373 10374 // SSE2/SSE41/AVX2 integer max/min intrinsics. 10375 case Intrinsic::x86_sse2_pmaxu_b: 10376 case Intrinsic::x86_sse41_pmaxuw: 10377 case Intrinsic::x86_sse41_pmaxud: 10378 case Intrinsic::x86_avx2_pmaxu_b: 10379 case Intrinsic::x86_avx2_pmaxu_w: 10380 case Intrinsic::x86_avx2_pmaxu_d: 10381 case Intrinsic::x86_sse2_pminu_b: 10382 case Intrinsic::x86_sse41_pminuw: 10383 case Intrinsic::x86_sse41_pminud: 10384 case Intrinsic::x86_avx2_pminu_b: 10385 case Intrinsic::x86_avx2_pminu_w: 10386 case Intrinsic::x86_avx2_pminu_d: 10387 case Intrinsic::x86_sse41_pmaxsb: 10388 case Intrinsic::x86_sse2_pmaxs_w: 10389 case Intrinsic::x86_sse41_pmaxsd: 10390 case Intrinsic::x86_avx2_pmaxs_b: 10391 case Intrinsic::x86_avx2_pmaxs_w: 10392 case Intrinsic::x86_avx2_pmaxs_d: 10393 case Intrinsic::x86_sse41_pminsb: 10394 case Intrinsic::x86_sse2_pmins_w: 10395 case Intrinsic::x86_sse41_pminsd: 10396 case Intrinsic::x86_avx2_pmins_b: 10397 case Intrinsic::x86_avx2_pmins_w: 10398 case Intrinsic::x86_avx2_pmins_d: { 10399 unsigned Opcode; 10400 switch (IntNo) { 10401 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10402 case Intrinsic::x86_sse2_pmaxu_b: 10403 case Intrinsic::x86_sse41_pmaxuw: 10404 case Intrinsic::x86_sse41_pmaxud: 10405 case Intrinsic::x86_avx2_pmaxu_b: 10406 case Intrinsic::x86_avx2_pmaxu_w: 10407 case Intrinsic::x86_avx2_pmaxu_d: 10408 Opcode = X86ISD::UMAX; 10409 break; 10410 case Intrinsic::x86_sse2_pminu_b: 10411 case Intrinsic::x86_sse41_pminuw: 10412 case Intrinsic::x86_sse41_pminud: 10413 case Intrinsic::x86_avx2_pminu_b: 10414 case Intrinsic::x86_avx2_pminu_w: 10415 case Intrinsic::x86_avx2_pminu_d: 10416 Opcode = X86ISD::UMIN; 10417 break; 10418 case Intrinsic::x86_sse41_pmaxsb: 10419 case Intrinsic::x86_sse2_pmaxs_w: 10420 case Intrinsic::x86_sse41_pmaxsd: 10421 case Intrinsic::x86_avx2_pmaxs_b: 10422 case Intrinsic::x86_avx2_pmaxs_w: 10423 case Intrinsic::x86_avx2_pmaxs_d: 10424 Opcode = X86ISD::SMAX; 10425 break; 10426 case Intrinsic::x86_sse41_pminsb: 10427 case Intrinsic::x86_sse2_pmins_w: 10428 case Intrinsic::x86_sse41_pminsd: 10429 case Intrinsic::x86_avx2_pmins_b: 10430 case Intrinsic::x86_avx2_pmins_w: 10431 case Intrinsic::x86_avx2_pmins_d: 10432 Opcode = X86ISD::SMIN; 10433 break; 10434 } 10435 return DAG.getNode(Opcode, dl, Op.getValueType(), 10436 Op.getOperand(1), Op.getOperand(2)); 10437 } 10438 10439 // SSE/SSE2/AVX floating point max/min intrinsics. 10440 case Intrinsic::x86_sse_max_ps: 10441 case Intrinsic::x86_sse2_max_pd: 10442 case Intrinsic::x86_avx_max_ps_256: 10443 case Intrinsic::x86_avx_max_pd_256: 10444 case Intrinsic::x86_sse_min_ps: 10445 case Intrinsic::x86_sse2_min_pd: 10446 case Intrinsic::x86_avx_min_ps_256: 10447 case Intrinsic::x86_avx_min_pd_256: { 10448 unsigned Opcode; 10449 switch (IntNo) { 10450 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10451 case Intrinsic::x86_sse_max_ps: 10452 case Intrinsic::x86_sse2_max_pd: 10453 case Intrinsic::x86_avx_max_ps_256: 10454 case Intrinsic::x86_avx_max_pd_256: 10455 Opcode = X86ISD::FMAX; 10456 break; 10457 case Intrinsic::x86_sse_min_ps: 10458 case Intrinsic::x86_sse2_min_pd: 10459 case Intrinsic::x86_avx_min_ps_256: 10460 case Intrinsic::x86_avx_min_pd_256: 10461 Opcode = X86ISD::FMIN; 10462 break; 10463 } 10464 return DAG.getNode(Opcode, dl, Op.getValueType(), 10465 Op.getOperand(1), Op.getOperand(2)); 10466 } 10467 10468 // AVX2 variable shift intrinsics 10469 case Intrinsic::x86_avx2_psllv_d: 10470 case Intrinsic::x86_avx2_psllv_q: 10471 case Intrinsic::x86_avx2_psllv_d_256: 10472 case Intrinsic::x86_avx2_psllv_q_256: 10473 case Intrinsic::x86_avx2_psrlv_d: 10474 case Intrinsic::x86_avx2_psrlv_q: 10475 case Intrinsic::x86_avx2_psrlv_d_256: 10476 case Intrinsic::x86_avx2_psrlv_q_256: 10477 case Intrinsic::x86_avx2_psrav_d: 10478 case Intrinsic::x86_avx2_psrav_d_256: { 10479 unsigned Opcode; 10480 switch (IntNo) { 10481 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10482 case Intrinsic::x86_avx2_psllv_d: 10483 case Intrinsic::x86_avx2_psllv_q: 10484 case Intrinsic::x86_avx2_psllv_d_256: 10485 case Intrinsic::x86_avx2_psllv_q_256: 10486 Opcode = ISD::SHL; 10487 break; 10488 case Intrinsic::x86_avx2_psrlv_d: 10489 case Intrinsic::x86_avx2_psrlv_q: 10490 case Intrinsic::x86_avx2_psrlv_d_256: 10491 case Intrinsic::x86_avx2_psrlv_q_256: 10492 Opcode = ISD::SRL; 10493 break; 10494 case Intrinsic::x86_avx2_psrav_d: 10495 case Intrinsic::x86_avx2_psrav_d_256: 10496 Opcode = ISD::SRA; 10497 break; 10498 } 10499 return DAG.getNode(Opcode, dl, Op.getValueType(), 10500 Op.getOperand(1), Op.getOperand(2)); 10501 } 10502 10503 case Intrinsic::x86_ssse3_pshuf_b_128: 10504 case Intrinsic::x86_avx2_pshuf_b: 10505 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(), 10506 Op.getOperand(1), Op.getOperand(2)); 10507 10508 case Intrinsic::x86_ssse3_psign_b_128: 10509 case Intrinsic::x86_ssse3_psign_w_128: 10510 case Intrinsic::x86_ssse3_psign_d_128: 10511 case Intrinsic::x86_avx2_psign_b: 10512 case Intrinsic::x86_avx2_psign_w: 10513 case Intrinsic::x86_avx2_psign_d: 10514 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(), 10515 Op.getOperand(1), Op.getOperand(2)); 10516 10517 case Intrinsic::x86_sse41_insertps: 10518 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(), 10519 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 10520 10521 case Intrinsic::x86_avx_vperm2f128_ps_256: 10522 case Intrinsic::x86_avx_vperm2f128_pd_256: 10523 case Intrinsic::x86_avx_vperm2f128_si_256: 10524 case Intrinsic::x86_avx2_vperm2i128: 10525 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(), 10526 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 10527 10528 case Intrinsic::x86_avx2_permd: 10529 case Intrinsic::x86_avx2_permps: 10530 // Operands intentionally swapped. Mask is last operand to intrinsic, 10531 // but second operand for node/intruction. 10532 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(), 10533 Op.getOperand(2), Op.getOperand(1)); 10534 10535 case Intrinsic::x86_sse_sqrt_ps: 10536 case Intrinsic::x86_sse2_sqrt_pd: 10537 case Intrinsic::x86_avx_sqrt_ps_256: 10538 case Intrinsic::x86_avx_sqrt_pd_256: 10539 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1)); 10540 10541 // ptest and testp intrinsics. The intrinsic these come from are designed to 10542 // return an integer value, not just an instruction so lower it to the ptest 10543 // or testp pattern and a setcc for the result. 10544 case Intrinsic::x86_sse41_ptestz: 10545 case Intrinsic::x86_sse41_ptestc: 10546 case Intrinsic::x86_sse41_ptestnzc: 10547 case Intrinsic::x86_avx_ptestz_256: 10548 case Intrinsic::x86_avx_ptestc_256: 10549 case Intrinsic::x86_avx_ptestnzc_256: 10550 case Intrinsic::x86_avx_vtestz_ps: 10551 case Intrinsic::x86_avx_vtestc_ps: 10552 case Intrinsic::x86_avx_vtestnzc_ps: 10553 case Intrinsic::x86_avx_vtestz_pd: 10554 case Intrinsic::x86_avx_vtestc_pd: 10555 case Intrinsic::x86_avx_vtestnzc_pd: 10556 case Intrinsic::x86_avx_vtestz_ps_256: 10557 case Intrinsic::x86_avx_vtestc_ps_256: 10558 case Intrinsic::x86_avx_vtestnzc_ps_256: 10559 case Intrinsic::x86_avx_vtestz_pd_256: 10560 case Intrinsic::x86_avx_vtestc_pd_256: 10561 case Intrinsic::x86_avx_vtestnzc_pd_256: { 10562 bool IsTestPacked = false; 10563 unsigned X86CC; 10564 switch (IntNo) { 10565 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering."); 10566 case Intrinsic::x86_avx_vtestz_ps: 10567 case Intrinsic::x86_avx_vtestz_pd: 10568 case Intrinsic::x86_avx_vtestz_ps_256: 10569 case Intrinsic::x86_avx_vtestz_pd_256: 10570 IsTestPacked = true; // Fallthrough 10571 case Intrinsic::x86_sse41_ptestz: 10572 case Intrinsic::x86_avx_ptestz_256: 10573 // ZF = 1 10574 X86CC = X86::COND_E; 10575 break; 10576 case Intrinsic::x86_avx_vtestc_ps: 10577 case Intrinsic::x86_avx_vtestc_pd: 10578 case Intrinsic::x86_avx_vtestc_ps_256: 10579 case Intrinsic::x86_avx_vtestc_pd_256: 10580 IsTestPacked = true; // Fallthrough 10581 case Intrinsic::x86_sse41_ptestc: 10582 case Intrinsic::x86_avx_ptestc_256: 10583 // CF = 1 10584 X86CC = X86::COND_B; 10585 break; 10586 case Intrinsic::x86_avx_vtestnzc_ps: 10587 case Intrinsic::x86_avx_vtestnzc_pd: 10588 case Intrinsic::x86_avx_vtestnzc_ps_256: 10589 case Intrinsic::x86_avx_vtestnzc_pd_256: 10590 IsTestPacked = true; // Fallthrough 10591 case Intrinsic::x86_sse41_ptestnzc: 10592 case Intrinsic::x86_avx_ptestnzc_256: 10593 // ZF and CF = 0 10594 X86CC = X86::COND_A; 10595 break; 10596 } 10597 10598 SDValue LHS = Op.getOperand(1); 10599 SDValue RHS = Op.getOperand(2); 10600 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST; 10601 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS); 10602 SDValue CC = DAG.getConstant(X86CC, MVT::i8); 10603 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test); 10604 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10605 } 10606 10607 // SSE/AVX shift intrinsics 10608 case Intrinsic::x86_sse2_psll_w: 10609 case Intrinsic::x86_sse2_psll_d: 10610 case Intrinsic::x86_sse2_psll_q: 10611 case Intrinsic::x86_avx2_psll_w: 10612 case Intrinsic::x86_avx2_psll_d: 10613 case Intrinsic::x86_avx2_psll_q: 10614 case Intrinsic::x86_sse2_psrl_w: 10615 case Intrinsic::x86_sse2_psrl_d: 10616 case Intrinsic::x86_sse2_psrl_q: 10617 case Intrinsic::x86_avx2_psrl_w: 10618 case Intrinsic::x86_avx2_psrl_d: 10619 case Intrinsic::x86_avx2_psrl_q: 10620 case Intrinsic::x86_sse2_psra_w: 10621 case Intrinsic::x86_sse2_psra_d: 10622 case Intrinsic::x86_avx2_psra_w: 10623 case Intrinsic::x86_avx2_psra_d: { 10624 unsigned Opcode; 10625 switch (IntNo) { 10626 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10627 case Intrinsic::x86_sse2_psll_w: 10628 case Intrinsic::x86_sse2_psll_d: 10629 case Intrinsic::x86_sse2_psll_q: 10630 case Intrinsic::x86_avx2_psll_w: 10631 case Intrinsic::x86_avx2_psll_d: 10632 case Intrinsic::x86_avx2_psll_q: 10633 Opcode = X86ISD::VSHL; 10634 break; 10635 case Intrinsic::x86_sse2_psrl_w: 10636 case Intrinsic::x86_sse2_psrl_d: 10637 case Intrinsic::x86_sse2_psrl_q: 10638 case Intrinsic::x86_avx2_psrl_w: 10639 case Intrinsic::x86_avx2_psrl_d: 10640 case Intrinsic::x86_avx2_psrl_q: 10641 Opcode = X86ISD::VSRL; 10642 break; 10643 case Intrinsic::x86_sse2_psra_w: 10644 case Intrinsic::x86_sse2_psra_d: 10645 case Intrinsic::x86_avx2_psra_w: 10646 case Intrinsic::x86_avx2_psra_d: 10647 Opcode = X86ISD::VSRA; 10648 break; 10649 } 10650 return DAG.getNode(Opcode, dl, Op.getValueType(), 10651 Op.getOperand(1), Op.getOperand(2)); 10652 } 10653 10654 // SSE/AVX immediate shift intrinsics 10655 case Intrinsic::x86_sse2_pslli_w: 10656 case Intrinsic::x86_sse2_pslli_d: 10657 case Intrinsic::x86_sse2_pslli_q: 10658 case Intrinsic::x86_avx2_pslli_w: 10659 case Intrinsic::x86_avx2_pslli_d: 10660 case Intrinsic::x86_avx2_pslli_q: 10661 case Intrinsic::x86_sse2_psrli_w: 10662 case Intrinsic::x86_sse2_psrli_d: 10663 case Intrinsic::x86_sse2_psrli_q: 10664 case Intrinsic::x86_avx2_psrli_w: 10665 case Intrinsic::x86_avx2_psrli_d: 10666 case Intrinsic::x86_avx2_psrli_q: 10667 case Intrinsic::x86_sse2_psrai_w: 10668 case Intrinsic::x86_sse2_psrai_d: 10669 case Intrinsic::x86_avx2_psrai_w: 10670 case Intrinsic::x86_avx2_psrai_d: { 10671 unsigned Opcode; 10672 switch (IntNo) { 10673 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10674 case Intrinsic::x86_sse2_pslli_w: 10675 case Intrinsic::x86_sse2_pslli_d: 10676 case Intrinsic::x86_sse2_pslli_q: 10677 case Intrinsic::x86_avx2_pslli_w: 10678 case Intrinsic::x86_avx2_pslli_d: 10679 case Intrinsic::x86_avx2_pslli_q: 10680 Opcode = X86ISD::VSHLI; 10681 break; 10682 case Intrinsic::x86_sse2_psrli_w: 10683 case Intrinsic::x86_sse2_psrli_d: 10684 case Intrinsic::x86_sse2_psrli_q: 10685 case Intrinsic::x86_avx2_psrli_w: 10686 case Intrinsic::x86_avx2_psrli_d: 10687 case Intrinsic::x86_avx2_psrli_q: 10688 Opcode = X86ISD::VSRLI; 10689 break; 10690 case Intrinsic::x86_sse2_psrai_w: 10691 case Intrinsic::x86_sse2_psrai_d: 10692 case Intrinsic::x86_avx2_psrai_w: 10693 case Intrinsic::x86_avx2_psrai_d: 10694 Opcode = X86ISD::VSRAI; 10695 break; 10696 } 10697 return getTargetVShiftNode(Opcode, dl, Op.getValueType(), 10698 Op.getOperand(1), Op.getOperand(2), DAG); 10699 } 10700 10701 case Intrinsic::x86_sse42_pcmpistria128: 10702 case Intrinsic::x86_sse42_pcmpestria128: 10703 case Intrinsic::x86_sse42_pcmpistric128: 10704 case Intrinsic::x86_sse42_pcmpestric128: 10705 case Intrinsic::x86_sse42_pcmpistrio128: 10706 case Intrinsic::x86_sse42_pcmpestrio128: 10707 case Intrinsic::x86_sse42_pcmpistris128: 10708 case Intrinsic::x86_sse42_pcmpestris128: 10709 case Intrinsic::x86_sse42_pcmpistriz128: 10710 case Intrinsic::x86_sse42_pcmpestriz128: { 10711 unsigned Opcode; 10712 unsigned X86CC; 10713 switch (IntNo) { 10714 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10715 case Intrinsic::x86_sse42_pcmpistria128: 10716 Opcode = X86ISD::PCMPISTRI; 10717 X86CC = X86::COND_A; 10718 break; 10719 case Intrinsic::x86_sse42_pcmpestria128: 10720 Opcode = X86ISD::PCMPESTRI; 10721 X86CC = X86::COND_A; 10722 break; 10723 case Intrinsic::x86_sse42_pcmpistric128: 10724 Opcode = X86ISD::PCMPISTRI; 10725 X86CC = X86::COND_B; 10726 break; 10727 case Intrinsic::x86_sse42_pcmpestric128: 10728 Opcode = X86ISD::PCMPESTRI; 10729 X86CC = X86::COND_B; 10730 break; 10731 case Intrinsic::x86_sse42_pcmpistrio128: 10732 Opcode = X86ISD::PCMPISTRI; 10733 X86CC = X86::COND_O; 10734 break; 10735 case Intrinsic::x86_sse42_pcmpestrio128: 10736 Opcode = X86ISD::PCMPESTRI; 10737 X86CC = X86::COND_O; 10738 break; 10739 case Intrinsic::x86_sse42_pcmpistris128: 10740 Opcode = X86ISD::PCMPISTRI; 10741 X86CC = X86::COND_S; 10742 break; 10743 case Intrinsic::x86_sse42_pcmpestris128: 10744 Opcode = X86ISD::PCMPESTRI; 10745 X86CC = X86::COND_S; 10746 break; 10747 case Intrinsic::x86_sse42_pcmpistriz128: 10748 Opcode = X86ISD::PCMPISTRI; 10749 X86CC = X86::COND_E; 10750 break; 10751 case Intrinsic::x86_sse42_pcmpestriz128: 10752 Opcode = X86ISD::PCMPESTRI; 10753 X86CC = X86::COND_E; 10754 break; 10755 } 10756 SmallVector<SDValue, 5> NewOps; 10757 NewOps.append(Op->op_begin()+1, Op->op_end()); 10758 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 10759 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 10760 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, 10761 DAG.getConstant(X86CC, MVT::i8), 10762 SDValue(PCMP.getNode(), 1)); 10763 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC); 10764 } 10765 10766 case Intrinsic::x86_sse42_pcmpistri128: 10767 case Intrinsic::x86_sse42_pcmpestri128: { 10768 unsigned Opcode; 10769 if (IntNo == Intrinsic::x86_sse42_pcmpistri128) 10770 Opcode = X86ISD::PCMPISTRI; 10771 else 10772 Opcode = X86ISD::PCMPESTRI; 10773 10774 SmallVector<SDValue, 5> NewOps; 10775 NewOps.append(Op->op_begin()+1, Op->op_end()); 10776 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 10777 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size()); 10778 } 10779 case Intrinsic::x86_fma_vfmadd_ps: 10780 case Intrinsic::x86_fma_vfmadd_pd: 10781 case Intrinsic::x86_fma_vfmsub_ps: 10782 case Intrinsic::x86_fma_vfmsub_pd: 10783 case Intrinsic::x86_fma_vfnmadd_ps: 10784 case Intrinsic::x86_fma_vfnmadd_pd: 10785 case Intrinsic::x86_fma_vfnmsub_ps: 10786 case Intrinsic::x86_fma_vfnmsub_pd: 10787 case Intrinsic::x86_fma_vfmaddsub_ps: 10788 case Intrinsic::x86_fma_vfmaddsub_pd: 10789 case Intrinsic::x86_fma_vfmsubadd_ps: 10790 case Intrinsic::x86_fma_vfmsubadd_pd: 10791 case Intrinsic::x86_fma_vfmadd_ps_256: 10792 case Intrinsic::x86_fma_vfmadd_pd_256: 10793 case Intrinsic::x86_fma_vfmsub_ps_256: 10794 case Intrinsic::x86_fma_vfmsub_pd_256: 10795 case Intrinsic::x86_fma_vfnmadd_ps_256: 10796 case Intrinsic::x86_fma_vfnmadd_pd_256: 10797 case Intrinsic::x86_fma_vfnmsub_ps_256: 10798 case Intrinsic::x86_fma_vfnmsub_pd_256: 10799 case Intrinsic::x86_fma_vfmaddsub_ps_256: 10800 case Intrinsic::x86_fma_vfmaddsub_pd_256: 10801 case Intrinsic::x86_fma_vfmsubadd_ps_256: 10802 case Intrinsic::x86_fma_vfmsubadd_pd_256: { 10803 unsigned Opc; 10804 switch (IntNo) { 10805 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 10806 case Intrinsic::x86_fma_vfmadd_ps: 10807 case Intrinsic::x86_fma_vfmadd_pd: 10808 case Intrinsic::x86_fma_vfmadd_ps_256: 10809 case Intrinsic::x86_fma_vfmadd_pd_256: 10810 Opc = X86ISD::FMADD; 10811 break; 10812 case Intrinsic::x86_fma_vfmsub_ps: 10813 case Intrinsic::x86_fma_vfmsub_pd: 10814 case Intrinsic::x86_fma_vfmsub_ps_256: 10815 case Intrinsic::x86_fma_vfmsub_pd_256: 10816 Opc = X86ISD::FMSUB; 10817 break; 10818 case Intrinsic::x86_fma_vfnmadd_ps: 10819 case Intrinsic::x86_fma_vfnmadd_pd: 10820 case Intrinsic::x86_fma_vfnmadd_ps_256: 10821 case Intrinsic::x86_fma_vfnmadd_pd_256: 10822 Opc = X86ISD::FNMADD; 10823 break; 10824 case Intrinsic::x86_fma_vfnmsub_ps: 10825 case Intrinsic::x86_fma_vfnmsub_pd: 10826 case Intrinsic::x86_fma_vfnmsub_ps_256: 10827 case Intrinsic::x86_fma_vfnmsub_pd_256: 10828 Opc = X86ISD::FNMSUB; 10829 break; 10830 case Intrinsic::x86_fma_vfmaddsub_ps: 10831 case Intrinsic::x86_fma_vfmaddsub_pd: 10832 case Intrinsic::x86_fma_vfmaddsub_ps_256: 10833 case Intrinsic::x86_fma_vfmaddsub_pd_256: 10834 Opc = X86ISD::FMADDSUB; 10835 break; 10836 case Intrinsic::x86_fma_vfmsubadd_ps: 10837 case Intrinsic::x86_fma_vfmsubadd_pd: 10838 case Intrinsic::x86_fma_vfmsubadd_ps_256: 10839 case Intrinsic::x86_fma_vfmsubadd_pd_256: 10840 Opc = X86ISD::FMSUBADD; 10841 break; 10842 } 10843 10844 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1), 10845 Op.getOperand(2), Op.getOperand(3)); 10846 } 10847 } 10848} 10849 10850static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) { 10851 DebugLoc dl = Op.getDebugLoc(); 10852 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 10853 switch (IntNo) { 10854 default: return SDValue(); // Don't custom lower most intrinsics. 10855 10856 // RDRAND intrinsics. 10857 case Intrinsic::x86_rdrand_16: 10858 case Intrinsic::x86_rdrand_32: 10859 case Intrinsic::x86_rdrand_64: { 10860 // Emit the node with the right value type. 10861 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other); 10862 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0)); 10863 10864 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise 10865 // return the value from Rand, which is always 0, casted to i32. 10866 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)), 10867 DAG.getConstant(1, Op->getValueType(1)), 10868 DAG.getConstant(X86::COND_B, MVT::i32), 10869 SDValue(Result.getNode(), 1) }; 10870 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, 10871 DAG.getVTList(Op->getValueType(1), MVT::Glue), 10872 Ops, 4); 10873 10874 // Return { result, isValid, chain }. 10875 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid, 10876 SDValue(Result.getNode(), 2)); 10877 } 10878 } 10879} 10880 10881SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, 10882 SelectionDAG &DAG) const { 10883 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 10884 MFI->setReturnAddressIsTaken(true); 10885 10886 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10887 DebugLoc dl = Op.getDebugLoc(); 10888 EVT PtrVT = getPointerTy(); 10889 10890 if (Depth > 0) { 10891 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 10892 SDValue Offset = 10893 DAG.getConstant(RegInfo->getSlotSize(), PtrVT); 10894 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 10895 DAG.getNode(ISD::ADD, dl, PtrVT, 10896 FrameAddr, Offset), 10897 MachinePointerInfo(), false, false, false, 0); 10898 } 10899 10900 // Just load the return address. 10901 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG); 10902 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 10903 RetAddrFI, MachinePointerInfo(), false, false, false, 0); 10904} 10905 10906SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { 10907 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 10908 MFI->setFrameAddressIsTaken(true); 10909 10910 EVT VT = Op.getValueType(); 10911 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful 10912 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10913 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP; 10914 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT); 10915 while (Depth--) 10916 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, 10917 MachinePointerInfo(), 10918 false, false, false, 0); 10919 return FrameAddr; 10920} 10921 10922SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op, 10923 SelectionDAG &DAG) const { 10924 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize()); 10925} 10926 10927SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const { 10928 SDValue Chain = Op.getOperand(0); 10929 SDValue Offset = Op.getOperand(1); 10930 SDValue Handler = Op.getOperand(2); 10931 DebugLoc dl = Op.getDebugLoc(); 10932 10933 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, 10934 Subtarget->is64Bit() ? X86::RBP : X86::EBP, 10935 getPointerTy()); 10936 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX); 10937 10938 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame, 10939 DAG.getIntPtrConstant(RegInfo->getSlotSize())); 10940 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset); 10941 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(), 10942 false, false, 0); 10943 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr); 10944 10945 return DAG.getNode(X86ISD::EH_RETURN, dl, 10946 MVT::Other, 10947 Chain, DAG.getRegister(StoreAddrReg, getPointerTy())); 10948} 10949 10950SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 10951 SelectionDAG &DAG) const { 10952 DebugLoc DL = Op.getDebugLoc(); 10953 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL, 10954 DAG.getVTList(MVT::i32, MVT::Other), 10955 Op.getOperand(0), Op.getOperand(1)); 10956} 10957 10958SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 10959 SelectionDAG &DAG) const { 10960 DebugLoc DL = Op.getDebugLoc(); 10961 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 10962 Op.getOperand(0), Op.getOperand(1)); 10963} 10964 10965static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) { 10966 return Op.getOperand(0); 10967} 10968 10969SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 10970 SelectionDAG &DAG) const { 10971 SDValue Root = Op.getOperand(0); 10972 SDValue Trmp = Op.getOperand(1); // trampoline 10973 SDValue FPtr = Op.getOperand(2); // nested function 10974 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 10975 DebugLoc dl = Op.getDebugLoc(); 10976 10977 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 10978 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 10979 10980 if (Subtarget->is64Bit()) { 10981 SDValue OutChains[6]; 10982 10983 // Large code-model. 10984 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode. 10985 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode. 10986 10987 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7; 10988 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7; 10989 10990 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix 10991 10992 // Load the pointer to the nested function into R11. 10993 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11 10994 SDValue Addr = Trmp; 10995 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 10996 Addr, MachinePointerInfo(TrmpAddr), 10997 false, false, 0); 10998 10999 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11000 DAG.getConstant(2, MVT::i64)); 11001 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, 11002 MachinePointerInfo(TrmpAddr, 2), 11003 false, false, 2); 11004 11005 // Load the 'nest' parameter value into R10. 11006 // R10 is specified in X86CallingConv.td 11007 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10 11008 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11009 DAG.getConstant(10, MVT::i64)); 11010 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11011 Addr, MachinePointerInfo(TrmpAddr, 10), 11012 false, false, 0); 11013 11014 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11015 DAG.getConstant(12, MVT::i64)); 11016 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, 11017 MachinePointerInfo(TrmpAddr, 12), 11018 false, false, 2); 11019 11020 // Jump to the nested function. 11021 OpCode = (JMP64r << 8) | REX_WB; // jmpq *... 11022 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11023 DAG.getConstant(20, MVT::i64)); 11024 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16), 11025 Addr, MachinePointerInfo(TrmpAddr, 20), 11026 false, false, 0); 11027 11028 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11 11029 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp, 11030 DAG.getConstant(22, MVT::i64)); 11031 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr, 11032 MachinePointerInfo(TrmpAddr, 22), 11033 false, false, 0); 11034 11035 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6); 11036 } else { 11037 const Function *Func = 11038 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue()); 11039 CallingConv::ID CC = Func->getCallingConv(); 11040 unsigned NestReg; 11041 11042 switch (CC) { 11043 default: 11044 llvm_unreachable("Unsupported calling convention"); 11045 case CallingConv::C: 11046 case CallingConv::X86_StdCall: { 11047 // Pass 'nest' parameter in ECX. 11048 // Must be kept in sync with X86CallingConv.td 11049 NestReg = X86::ECX; 11050 11051 // Check that ECX wasn't needed by an 'inreg' parameter. 11052 FunctionType *FTy = Func->getFunctionType(); 11053 const AttributeSet &Attrs = Func->getAttributes(); 11054 11055 if (!Attrs.isEmpty() && !Func->isVarArg()) { 11056 unsigned InRegCount = 0; 11057 unsigned Idx = 1; 11058 11059 for (FunctionType::param_iterator I = FTy->param_begin(), 11060 E = FTy->param_end(); I != E; ++I, ++Idx) 11061 if (Attrs.hasAttribute(Idx, Attribute::InReg)) 11062 // FIXME: should only count parameters that are lowered to integers. 11063 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32; 11064 11065 if (InRegCount > 2) { 11066 report_fatal_error("Nest register in use - reduce number of inreg" 11067 " parameters!"); 11068 } 11069 } 11070 break; 11071 } 11072 case CallingConv::X86_FastCall: 11073 case CallingConv::X86_ThisCall: 11074 case CallingConv::Fast: 11075 // Pass 'nest' parameter in EAX. 11076 // Must be kept in sync with X86CallingConv.td 11077 NestReg = X86::EAX; 11078 break; 11079 } 11080 11081 SDValue OutChains[4]; 11082 SDValue Addr, Disp; 11083 11084 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11085 DAG.getConstant(10, MVT::i32)); 11086 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr); 11087 11088 // This is storing the opcode for MOV32ri. 11089 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte. 11090 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7; 11091 OutChains[0] = DAG.getStore(Root, dl, 11092 DAG.getConstant(MOV32ri|N86Reg, MVT::i8), 11093 Trmp, MachinePointerInfo(TrmpAddr), 11094 false, false, 0); 11095 11096 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11097 DAG.getConstant(1, MVT::i32)); 11098 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, 11099 MachinePointerInfo(TrmpAddr, 1), 11100 false, false, 1); 11101 11102 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode. 11103 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11104 DAG.getConstant(5, MVT::i32)); 11105 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr, 11106 MachinePointerInfo(TrmpAddr, 5), 11107 false, false, 1); 11108 11109 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp, 11110 DAG.getConstant(6, MVT::i32)); 11111 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, 11112 MachinePointerInfo(TrmpAddr, 6), 11113 false, false, 1); 11114 11115 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4); 11116 } 11117} 11118 11119SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 11120 SelectionDAG &DAG) const { 11121 /* 11122 The rounding mode is in bits 11:10 of FPSR, and has the following 11123 settings: 11124 00 Round to nearest 11125 01 Round to -inf 11126 10 Round to +inf 11127 11 Round to 0 11128 11129 FLT_ROUNDS, on the other hand, expects the following: 11130 -1 Undefined 11131 0 Round to 0 11132 1 Round to nearest 11133 2 Round to +inf 11134 3 Round to -inf 11135 11136 To perform the conversion, we do: 11137 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3) 11138 */ 11139 11140 MachineFunction &MF = DAG.getMachineFunction(); 11141 const TargetMachine &TM = MF.getTarget(); 11142 const TargetFrameLowering &TFI = *TM.getFrameLowering(); 11143 unsigned StackAlignment = TFI.getStackAlignment(); 11144 EVT VT = Op.getValueType(); 11145 DebugLoc DL = Op.getDebugLoc(); 11146 11147 // Save FP Control Word to stack slot 11148 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false); 11149 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy()); 11150 11151 MachineMemOperand *MMO = 11152 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI), 11153 MachineMemOperand::MOStore, 2, 2); 11154 11155 SDValue Ops[] = { DAG.getEntryNode(), StackSlot }; 11156 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL, 11157 DAG.getVTList(MVT::Other), 11158 Ops, 2, MVT::i16, MMO); 11159 11160 // Load FP Control Word from stack slot 11161 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, 11162 MachinePointerInfo(), false, false, false, 0); 11163 11164 // Transform as necessary 11165 SDValue CWD1 = 11166 DAG.getNode(ISD::SRL, DL, MVT::i16, 11167 DAG.getNode(ISD::AND, DL, MVT::i16, 11168 CWD, DAG.getConstant(0x800, MVT::i16)), 11169 DAG.getConstant(11, MVT::i8)); 11170 SDValue CWD2 = 11171 DAG.getNode(ISD::SRL, DL, MVT::i16, 11172 DAG.getNode(ISD::AND, DL, MVT::i16, 11173 CWD, DAG.getConstant(0x400, MVT::i16)), 11174 DAG.getConstant(9, MVT::i8)); 11175 11176 SDValue RetVal = 11177 DAG.getNode(ISD::AND, DL, MVT::i16, 11178 DAG.getNode(ISD::ADD, DL, MVT::i16, 11179 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2), 11180 DAG.getConstant(1, MVT::i16)), 11181 DAG.getConstant(3, MVT::i16)); 11182 11183 return DAG.getNode((VT.getSizeInBits() < 16 ? 11184 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal); 11185} 11186 11187static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) { 11188 EVT VT = Op.getValueType(); 11189 EVT OpVT = VT; 11190 unsigned NumBits = VT.getSizeInBits(); 11191 DebugLoc dl = Op.getDebugLoc(); 11192 11193 Op = Op.getOperand(0); 11194 if (VT == MVT::i8) { 11195 // Zero extend to i32 since there is not an i8 bsr. 11196 OpVT = MVT::i32; 11197 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11198 } 11199 11200 // Issue a bsr (scan bits in reverse) which also sets EFLAGS. 11201 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11202 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11203 11204 // If src is zero (i.e. bsr sets ZF), returns NumBits. 11205 SDValue Ops[] = { 11206 Op, 11207 DAG.getConstant(NumBits+NumBits-1, OpVT), 11208 DAG.getConstant(X86::COND_E, MVT::i8), 11209 Op.getValue(1) 11210 }; 11211 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops)); 11212 11213 // Finally xor with NumBits-1. 11214 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11215 11216 if (VT == MVT::i8) 11217 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11218 return Op; 11219} 11220 11221static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 11222 EVT VT = Op.getValueType(); 11223 EVT OpVT = VT; 11224 unsigned NumBits = VT.getSizeInBits(); 11225 DebugLoc dl = Op.getDebugLoc(); 11226 11227 Op = Op.getOperand(0); 11228 if (VT == MVT::i8) { 11229 // Zero extend to i32 since there is not an i8 bsr. 11230 OpVT = MVT::i32; 11231 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op); 11232 } 11233 11234 // Issue a bsr (scan bits in reverse). 11235 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32); 11236 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op); 11237 11238 // And xor with NumBits-1. 11239 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT)); 11240 11241 if (VT == MVT::i8) 11242 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op); 11243 return Op; 11244} 11245 11246static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) { 11247 EVT VT = Op.getValueType(); 11248 unsigned NumBits = VT.getSizeInBits(); 11249 DebugLoc dl = Op.getDebugLoc(); 11250 Op = Op.getOperand(0); 11251 11252 // Issue a bsf (scan bits forward) which also sets EFLAGS. 11253 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 11254 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op); 11255 11256 // If src is zero (i.e. bsf sets ZF), returns NumBits. 11257 SDValue Ops[] = { 11258 Op, 11259 DAG.getConstant(NumBits, VT), 11260 DAG.getConstant(X86::COND_E, MVT::i8), 11261 Op.getValue(1) 11262 }; 11263 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops)); 11264} 11265 11266// Lower256IntArith - Break a 256-bit integer operation into two new 128-bit 11267// ones, and then concatenate the result back. 11268static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) { 11269 EVT VT = Op.getValueType(); 11270 11271 assert(VT.is256BitVector() && VT.isInteger() && 11272 "Unsupported value type for operation"); 11273 11274 unsigned NumElems = VT.getVectorNumElements(); 11275 DebugLoc dl = Op.getDebugLoc(); 11276 11277 // Extract the LHS vectors 11278 SDValue LHS = Op.getOperand(0); 11279 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 11280 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 11281 11282 // Extract the RHS vectors 11283 SDValue RHS = Op.getOperand(1); 11284 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl); 11285 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl); 11286 11287 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11288 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11289 11290 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, 11291 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1), 11292 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2)); 11293} 11294 11295static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) { 11296 assert(Op.getValueType().is256BitVector() && 11297 Op.getValueType().isInteger() && 11298 "Only handle AVX 256-bit vector integer operation"); 11299 return Lower256IntArith(Op, DAG); 11300} 11301 11302static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) { 11303 assert(Op.getValueType().is256BitVector() && 11304 Op.getValueType().isInteger() && 11305 "Only handle AVX 256-bit vector integer operation"); 11306 return Lower256IntArith(Op, DAG); 11307} 11308 11309static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget, 11310 SelectionDAG &DAG) { 11311 DebugLoc dl = Op.getDebugLoc(); 11312 EVT VT = Op.getValueType(); 11313 11314 // Decompose 256-bit ops into smaller 128-bit ops. 11315 if (VT.is256BitVector() && !Subtarget->hasInt256()) 11316 return Lower256IntArith(Op, DAG); 11317 11318 SDValue A = Op.getOperand(0); 11319 SDValue B = Op.getOperand(1); 11320 11321 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle. 11322 if (VT == MVT::v4i32) { 11323 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() && 11324 "Should not custom lower when pmuldq is available!"); 11325 11326 // Extract the odd parts. 11327 const int UnpackMask[] = { 1, -1, 3, -1 }; 11328 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask); 11329 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask); 11330 11331 // Multiply the even parts. 11332 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B); 11333 // Now multiply odd parts. 11334 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds); 11335 11336 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens); 11337 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds); 11338 11339 // Merge the two vectors back together with a shuffle. This expands into 2 11340 // shuffles. 11341 const int ShufMask[] = { 0, 4, 2, 6 }; 11342 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask); 11343 } 11344 11345 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && 11346 "Only know how to lower V2I64/V4I64 multiply"); 11347 11348 // Ahi = psrlqi(a, 32); 11349 // Bhi = psrlqi(b, 32); 11350 // 11351 // AloBlo = pmuludq(a, b); 11352 // AloBhi = pmuludq(a, Bhi); 11353 // AhiBlo = pmuludq(Ahi, b); 11354 11355 // AloBhi = psllqi(AloBhi, 32); 11356 // AhiBlo = psllqi(AhiBlo, 32); 11357 // return AloBlo + AloBhi + AhiBlo; 11358 11359 SDValue ShAmt = DAG.getConstant(32, MVT::i32); 11360 11361 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt); 11362 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt); 11363 11364 // Bit cast to 32-bit vectors for MULUDQ 11365 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32; 11366 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A); 11367 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B); 11368 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi); 11369 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi); 11370 11371 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B); 11372 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi); 11373 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B); 11374 11375 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt); 11376 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt); 11377 11378 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi); 11379 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo); 11380} 11381 11382SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const { 11383 EVT VT = Op.getValueType(); 11384 EVT EltTy = VT.getVectorElementType(); 11385 unsigned NumElts = VT.getVectorNumElements(); 11386 SDValue N0 = Op.getOperand(0); 11387 DebugLoc dl = Op.getDebugLoc(); 11388 11389 // Lower sdiv X, pow2-const. 11390 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1)); 11391 if (!C) 11392 return SDValue(); 11393 11394 APInt SplatValue, SplatUndef; 11395 unsigned MinSplatBits; 11396 bool HasAnyUndefs; 11397 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs)) 11398 return SDValue(); 11399 11400 if ((SplatValue != 0) && 11401 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) { 11402 unsigned lg2 = SplatValue.countTrailingZeros(); 11403 // Splat the sign bit. 11404 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32); 11405 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG); 11406 // Add (N0 < 0) ? abs2 - 1 : 0; 11407 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32); 11408 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG); 11409 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL); 11410 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32); 11411 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG); 11412 11413 // If we're dividing by a positive value, we're done. Otherwise, we must 11414 // negate the result. 11415 if (SplatValue.isNonNegative()) 11416 return SRA; 11417 11418 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy)); 11419 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts); 11420 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA); 11421 } 11422 return SDValue(); 11423} 11424 11425SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const { 11426 11427 EVT VT = Op.getValueType(); 11428 DebugLoc dl = Op.getDebugLoc(); 11429 SDValue R = Op.getOperand(0); 11430 SDValue Amt = Op.getOperand(1); 11431 LLVMContext *Context = DAG.getContext(); 11432 11433 if (!Subtarget->hasSSE2()) 11434 return SDValue(); 11435 11436 // Optimize shl/srl/sra with constant shift amount. 11437 if (isSplatVector(Amt.getNode())) { 11438 SDValue SclrAmt = Amt->getOperand(0); 11439 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) { 11440 uint64_t ShiftAmt = C->getZExtValue(); 11441 11442 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 11443 (Subtarget->hasInt256() && 11444 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) { 11445 if (Op.getOpcode() == ISD::SHL) 11446 return DAG.getNode(X86ISD::VSHLI, dl, VT, R, 11447 DAG.getConstant(ShiftAmt, MVT::i32)); 11448 if (Op.getOpcode() == ISD::SRL) 11449 return DAG.getNode(X86ISD::VSRLI, dl, VT, R, 11450 DAG.getConstant(ShiftAmt, MVT::i32)); 11451 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64) 11452 return DAG.getNode(X86ISD::VSRAI, dl, VT, R, 11453 DAG.getConstant(ShiftAmt, MVT::i32)); 11454 } 11455 11456 if (VT == MVT::v16i8) { 11457 if (Op.getOpcode() == ISD::SHL) { 11458 // Make a large shift. 11459 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R, 11460 DAG.getConstant(ShiftAmt, MVT::i32)); 11461 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 11462 // Zero out the rightmost bits. 11463 SmallVector<SDValue, 16> V(16, 11464 DAG.getConstant(uint8_t(-1U << ShiftAmt), 11465 MVT::i8)); 11466 return DAG.getNode(ISD::AND, dl, VT, SHL, 11467 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 11468 } 11469 if (Op.getOpcode() == ISD::SRL) { 11470 // Make a large shift. 11471 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R, 11472 DAG.getConstant(ShiftAmt, MVT::i32)); 11473 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 11474 // Zero out the leftmost bits. 11475 SmallVector<SDValue, 16> V(16, 11476 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 11477 MVT::i8)); 11478 return DAG.getNode(ISD::AND, dl, VT, SRL, 11479 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16)); 11480 } 11481 if (Op.getOpcode() == ISD::SRA) { 11482 if (ShiftAmt == 7) { 11483 // R s>> 7 === R s< 0 11484 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 11485 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 11486 } 11487 11488 // R s>> a === ((R u>> a) ^ m) - m 11489 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 11490 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt, 11491 MVT::i8)); 11492 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16); 11493 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 11494 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 11495 return Res; 11496 } 11497 llvm_unreachable("Unknown shift opcode."); 11498 } 11499 11500 if (Subtarget->hasInt256() && VT == MVT::v32i8) { 11501 if (Op.getOpcode() == ISD::SHL) { 11502 // Make a large shift. 11503 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R, 11504 DAG.getConstant(ShiftAmt, MVT::i32)); 11505 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL); 11506 // Zero out the rightmost bits. 11507 SmallVector<SDValue, 32> V(32, 11508 DAG.getConstant(uint8_t(-1U << ShiftAmt), 11509 MVT::i8)); 11510 return DAG.getNode(ISD::AND, dl, VT, SHL, 11511 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 11512 } 11513 if (Op.getOpcode() == ISD::SRL) { 11514 // Make a large shift. 11515 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R, 11516 DAG.getConstant(ShiftAmt, MVT::i32)); 11517 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL); 11518 // Zero out the leftmost bits. 11519 SmallVector<SDValue, 32> V(32, 11520 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, 11521 MVT::i8)); 11522 return DAG.getNode(ISD::AND, dl, VT, SRL, 11523 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32)); 11524 } 11525 if (Op.getOpcode() == ISD::SRA) { 11526 if (ShiftAmt == 7) { 11527 // R s>> 7 === R s< 0 11528 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 11529 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R); 11530 } 11531 11532 // R s>> a === ((R u>> a) ^ m) - m 11533 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt); 11534 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt, 11535 MVT::i8)); 11536 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32); 11537 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask); 11538 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask); 11539 return Res; 11540 } 11541 llvm_unreachable("Unknown shift opcode."); 11542 } 11543 } 11544 } 11545 11546 // Lower SHL with variable shift amount. 11547 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) { 11548 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1), 11549 DAG.getConstant(23, MVT::i32)); 11550 11551 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U}; 11552 Constant *C = ConstantDataVector::get(*Context, CV); 11553 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16); 11554 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx, 11555 MachinePointerInfo::getConstantPool(), 11556 false, false, false, 16); 11557 11558 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend); 11559 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op); 11560 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op); 11561 return DAG.getNode(ISD::MUL, dl, VT, Op, R); 11562 } 11563 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) { 11564 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq."); 11565 11566 // a = a << 5; 11567 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1), 11568 DAG.getConstant(5, MVT::i32)); 11569 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op); 11570 11571 // Turn 'a' into a mask suitable for VSELECT 11572 SDValue VSelM = DAG.getConstant(0x80, VT); 11573 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11574 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11575 11576 SDValue CM1 = DAG.getConstant(0x0f, VT); 11577 SDValue CM2 = DAG.getConstant(0x3f, VT); 11578 11579 // r = VSELECT(r, psllw(r & (char16)15, 4), a); 11580 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1); 11581 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 11582 DAG.getConstant(4, MVT::i32), DAG); 11583 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 11584 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 11585 11586 // a += a 11587 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 11588 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11589 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11590 11591 // r = VSELECT(r, psllw(r & (char16)63, 2), a); 11592 M = DAG.getNode(ISD::AND, dl, VT, R, CM2); 11593 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 11594 DAG.getConstant(2, MVT::i32), DAG); 11595 M = DAG.getNode(ISD::BITCAST, dl, VT, M); 11596 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R); 11597 11598 // a += a 11599 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op); 11600 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op); 11601 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM); 11602 11603 // return VSELECT(r, r+r, a); 11604 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, 11605 DAG.getNode(ISD::ADD, dl, VT, R, R), R); 11606 return R; 11607 } 11608 11609 // Decompose 256-bit shifts into smaller 128-bit shifts. 11610 if (VT.is256BitVector()) { 11611 unsigned NumElems = VT.getVectorNumElements(); 11612 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11613 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11614 11615 // Extract the two vectors 11616 SDValue V1 = Extract128BitVector(R, 0, DAG, dl); 11617 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl); 11618 11619 // Recreate the shift amount vectors 11620 SDValue Amt1, Amt2; 11621 if (Amt.getOpcode() == ISD::BUILD_VECTOR) { 11622 // Constant shift amount 11623 SmallVector<SDValue, 4> Amt1Csts; 11624 SmallVector<SDValue, 4> Amt2Csts; 11625 for (unsigned i = 0; i != NumElems/2; ++i) 11626 Amt1Csts.push_back(Amt->getOperand(i)); 11627 for (unsigned i = NumElems/2; i != NumElems; ++i) 11628 Amt2Csts.push_back(Amt->getOperand(i)); 11629 11630 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 11631 &Amt1Csts[0], NumElems/2); 11632 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, 11633 &Amt2Csts[0], NumElems/2); 11634 } else { 11635 // Variable shift amount 11636 Amt1 = Extract128BitVector(Amt, 0, DAG, dl); 11637 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl); 11638 } 11639 11640 // Issue new vector shifts for the smaller types 11641 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1); 11642 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2); 11643 11644 // Concatenate the result back 11645 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2); 11646 } 11647 11648 return SDValue(); 11649} 11650 11651static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 11652 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus 11653 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering 11654 // looks for this combo and may remove the "setcc" instruction if the "setcc" 11655 // has only one use. 11656 SDNode *N = Op.getNode(); 11657 SDValue LHS = N->getOperand(0); 11658 SDValue RHS = N->getOperand(1); 11659 unsigned BaseOp = 0; 11660 unsigned Cond = 0; 11661 DebugLoc DL = Op.getDebugLoc(); 11662 switch (Op.getOpcode()) { 11663 default: llvm_unreachable("Unknown ovf instruction!"); 11664 case ISD::SADDO: 11665 // A subtract of one will be selected as a INC. Note that INC doesn't 11666 // set CF, so we can't do this for UADDO. 11667 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 11668 if (C->isOne()) { 11669 BaseOp = X86ISD::INC; 11670 Cond = X86::COND_O; 11671 break; 11672 } 11673 BaseOp = X86ISD::ADD; 11674 Cond = X86::COND_O; 11675 break; 11676 case ISD::UADDO: 11677 BaseOp = X86ISD::ADD; 11678 Cond = X86::COND_B; 11679 break; 11680 case ISD::SSUBO: 11681 // A subtract of one will be selected as a DEC. Note that DEC doesn't 11682 // set CF, so we can't do this for USUBO. 11683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) 11684 if (C->isOne()) { 11685 BaseOp = X86ISD::DEC; 11686 Cond = X86::COND_O; 11687 break; 11688 } 11689 BaseOp = X86ISD::SUB; 11690 Cond = X86::COND_O; 11691 break; 11692 case ISD::USUBO: 11693 BaseOp = X86ISD::SUB; 11694 Cond = X86::COND_B; 11695 break; 11696 case ISD::SMULO: 11697 BaseOp = X86ISD::SMUL; 11698 Cond = X86::COND_O; 11699 break; 11700 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs 11701 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0), 11702 MVT::i32); 11703 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS); 11704 11705 SDValue SetCC = 11706 DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 11707 DAG.getConstant(X86::COND_O, MVT::i32), 11708 SDValue(Sum.getNode(), 2)); 11709 11710 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 11711 } 11712 } 11713 11714 // Also sets EFLAGS. 11715 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32); 11716 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS); 11717 11718 SDValue SetCC = 11719 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1), 11720 DAG.getConstant(Cond, MVT::i32), 11721 SDValue(Sum.getNode(), 1)); 11722 11723 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC); 11724} 11725 11726SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 11727 SelectionDAG &DAG) const { 11728 DebugLoc dl = Op.getDebugLoc(); 11729 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 11730 EVT VT = Op.getValueType(); 11731 11732 if (!Subtarget->hasSSE2() || !VT.isVector()) 11733 return SDValue(); 11734 11735 unsigned BitsDiff = VT.getScalarType().getSizeInBits() - 11736 ExtraVT.getScalarType().getSizeInBits(); 11737 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32); 11738 11739 switch (VT.getSimpleVT().SimpleTy) { 11740 default: return SDValue(); 11741 case MVT::v8i32: 11742 case MVT::v16i16: 11743 if (!Subtarget->hasFp256()) 11744 return SDValue(); 11745 if (!Subtarget->hasInt256()) { 11746 // needs to be split 11747 unsigned NumElems = VT.getVectorNumElements(); 11748 11749 // Extract the LHS vectors 11750 SDValue LHS = Op.getOperand(0); 11751 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl); 11752 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl); 11753 11754 MVT EltVT = VT.getVectorElementType().getSimpleVT(); 11755 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2); 11756 11757 EVT ExtraEltVT = ExtraVT.getVectorElementType(); 11758 unsigned ExtraNumElems = ExtraVT.getVectorNumElements(); 11759 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT, 11760 ExtraNumElems/2); 11761 SDValue Extra = DAG.getValueType(ExtraVT); 11762 11763 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra); 11764 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra); 11765 11766 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2); 11767 } 11768 // fall through 11769 case MVT::v4i32: 11770 case MVT::v8i16: { 11771 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, 11772 Op.getOperand(0), ShAmt, DAG); 11773 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG); 11774 } 11775 } 11776} 11777 11778static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget, 11779 SelectionDAG &DAG) { 11780 DebugLoc dl = Op.getDebugLoc(); 11781 11782 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2. 11783 // There isn't any reason to disable it if the target processor supports it. 11784 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) { 11785 SDValue Chain = Op.getOperand(0); 11786 SDValue Zero = DAG.getConstant(0, MVT::i32); 11787 SDValue Ops[] = { 11788 DAG.getRegister(X86::ESP, MVT::i32), // Base 11789 DAG.getTargetConstant(1, MVT::i8), // Scale 11790 DAG.getRegister(0, MVT::i32), // Index 11791 DAG.getTargetConstant(0, MVT::i32), // Disp 11792 DAG.getRegister(0, MVT::i32), // Segment. 11793 Zero, 11794 Chain 11795 }; 11796 SDNode *Res = 11797 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 11798 array_lengthof(Ops)); 11799 return SDValue(Res, 0); 11800 } 11801 11802 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 11803 if (!isDev) 11804 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 11805 11806 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 11807 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 11808 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 11809 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 11810 11811 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>; 11812 if (!Op1 && !Op2 && !Op3 && Op4) 11813 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0)); 11814 11815 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>; 11816 if (Op1 && !Op2 && !Op3 && !Op4) 11817 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0)); 11818 11819 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)), 11820 // (MFENCE)>; 11821 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 11822} 11823 11824static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget, 11825 SelectionDAG &DAG) { 11826 DebugLoc dl = Op.getDebugLoc(); 11827 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 11828 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 11829 SynchronizationScope FenceScope = static_cast<SynchronizationScope>( 11830 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 11831 11832 // The only fence that needs an instruction is a sequentially-consistent 11833 // cross-thread fence. 11834 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) { 11835 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for 11836 // no-sse2). There isn't any reason to disable it if the target processor 11837 // supports it. 11838 if (Subtarget->hasSSE2() || Subtarget->is64Bit()) 11839 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0)); 11840 11841 SDValue Chain = Op.getOperand(0); 11842 SDValue Zero = DAG.getConstant(0, MVT::i32); 11843 SDValue Ops[] = { 11844 DAG.getRegister(X86::ESP, MVT::i32), // Base 11845 DAG.getTargetConstant(1, MVT::i8), // Scale 11846 DAG.getRegister(0, MVT::i32), // Index 11847 DAG.getTargetConstant(0, MVT::i32), // Disp 11848 DAG.getRegister(0, MVT::i32), // Segment. 11849 Zero, 11850 Chain 11851 }; 11852 SDNode *Res = 11853 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops, 11854 array_lengthof(Ops)); 11855 return SDValue(Res, 0); 11856 } 11857 11858 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 11859 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0)); 11860} 11861 11862static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget, 11863 SelectionDAG &DAG) { 11864 EVT T = Op.getValueType(); 11865 DebugLoc DL = Op.getDebugLoc(); 11866 unsigned Reg = 0; 11867 unsigned size = 0; 11868 switch(T.getSimpleVT().SimpleTy) { 11869 default: llvm_unreachable("Invalid value type!"); 11870 case MVT::i8: Reg = X86::AL; size = 1; break; 11871 case MVT::i16: Reg = X86::AX; size = 2; break; 11872 case MVT::i32: Reg = X86::EAX; size = 4; break; 11873 case MVT::i64: 11874 assert(Subtarget->is64Bit() && "Node not type legal!"); 11875 Reg = X86::RAX; size = 8; 11876 break; 11877 } 11878 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg, 11879 Op.getOperand(2), SDValue()); 11880 SDValue Ops[] = { cpIn.getValue(0), 11881 Op.getOperand(1), 11882 Op.getOperand(3), 11883 DAG.getTargetConstant(size, MVT::i8), 11884 cpIn.getValue(1) }; 11885 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 11886 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand(); 11887 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys, 11888 Ops, 5, T, MMO); 11889 SDValue cpOut = 11890 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1)); 11891 return cpOut; 11892} 11893 11894static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget, 11895 SelectionDAG &DAG) { 11896 assert(Subtarget->is64Bit() && "Result not type legalized?"); 11897 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 11898 SDValue TheChain = Op.getOperand(0); 11899 DebugLoc dl = Op.getDebugLoc(); 11900 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 11901 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1)); 11902 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64, 11903 rax.getValue(2)); 11904 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx, 11905 DAG.getConstant(32, MVT::i8)); 11906 SDValue Ops[] = { 11907 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp), 11908 rdx.getValue(1) 11909 }; 11910 return DAG.getMergeValues(Ops, 2, dl); 11911} 11912 11913SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 11914 EVT SrcVT = Op.getOperand(0).getValueType(); 11915 EVT DstVT = Op.getValueType(); 11916 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() && 11917 Subtarget->hasMMX() && "Unexpected custom BITCAST"); 11918 assert((DstVT == MVT::i64 || 11919 (DstVT.isVector() && DstVT.getSizeInBits()==64)) && 11920 "Unexpected custom BITCAST"); 11921 // i64 <=> MMX conversions are Legal. 11922 if (SrcVT==MVT::i64 && DstVT.isVector()) 11923 return Op; 11924 if (DstVT==MVT::i64 && SrcVT.isVector()) 11925 return Op; 11926 // MMX <=> MMX conversions are Legal. 11927 if (SrcVT.isVector() && DstVT.isVector()) 11928 return Op; 11929 // All other conversions need to be expanded. 11930 return SDValue(); 11931} 11932 11933static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) { 11934 SDNode *Node = Op.getNode(); 11935 DebugLoc dl = Node->getDebugLoc(); 11936 EVT T = Node->getValueType(0); 11937 SDValue negOp = DAG.getNode(ISD::SUB, dl, T, 11938 DAG.getConstant(0, T), Node->getOperand(2)); 11939 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, 11940 cast<AtomicSDNode>(Node)->getMemoryVT(), 11941 Node->getOperand(0), 11942 Node->getOperand(1), negOp, 11943 cast<AtomicSDNode>(Node)->getSrcValue(), 11944 cast<AtomicSDNode>(Node)->getAlignment(), 11945 cast<AtomicSDNode>(Node)->getOrdering(), 11946 cast<AtomicSDNode>(Node)->getSynchScope()); 11947} 11948 11949static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) { 11950 SDNode *Node = Op.getNode(); 11951 DebugLoc dl = Node->getDebugLoc(); 11952 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 11953 11954 // Convert seq_cst store -> xchg 11955 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b) 11956 // FIXME: On 32-bit, store -> fist or movq would be more efficient 11957 // (The only way to get a 16-byte store is cmpxchg16b) 11958 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment. 11959 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent || 11960 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 11961 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, 11962 cast<AtomicSDNode>(Node)->getMemoryVT(), 11963 Node->getOperand(0), 11964 Node->getOperand(1), Node->getOperand(2), 11965 cast<AtomicSDNode>(Node)->getMemOperand(), 11966 cast<AtomicSDNode>(Node)->getOrdering(), 11967 cast<AtomicSDNode>(Node)->getSynchScope()); 11968 return Swap.getValue(1); 11969 } 11970 // Other atomic stores have a simple pattern. 11971 return Op; 11972} 11973 11974static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 11975 EVT VT = Op.getNode()->getValueType(0); 11976 11977 // Let legalize expand this if it isn't a legal type yet. 11978 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 11979 return SDValue(); 11980 11981 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 11982 11983 unsigned Opc; 11984 bool ExtraOp = false; 11985 switch (Op.getOpcode()) { 11986 default: llvm_unreachable("Invalid code"); 11987 case ISD::ADDC: Opc = X86ISD::ADD; break; 11988 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break; 11989 case ISD::SUBC: Opc = X86ISD::SUB; break; 11990 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break; 11991 } 11992 11993 if (!ExtraOp) 11994 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 11995 Op.getOperand(1)); 11996 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0), 11997 Op.getOperand(1), Op.getOperand(2)); 11998} 11999 12000/// LowerOperation - Provide custom lowering hooks for some operations. 12001/// 12002SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 12003 switch (Op.getOpcode()) { 12004 default: llvm_unreachable("Should not custom lower this!"); 12005 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG); 12006 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG); 12007 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG); 12008 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG); 12009 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG); 12010 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG); 12011 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 12012 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG); 12013 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 12014 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 12015 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 12016 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG); 12017 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG); 12018 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 12019 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 12020 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 12021 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 12022 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG); 12023 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 12024 case ISD::SHL_PARTS: 12025 case ISD::SRA_PARTS: 12026 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG); 12027 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG); 12028 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG); 12029 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG); 12030 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG); 12031 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG); 12032 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG); 12033 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 12034 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG); 12035 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG); 12036 case ISD::FABS: return LowerFABS(Op, DAG); 12037 case ISD::FNEG: return LowerFNEG(Op, DAG); 12038 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); 12039 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG); 12040 case ISD::SETCC: return LowerSETCC(Op, DAG); 12041 case ISD::SELECT: return LowerSELECT(Op, DAG); 12042 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 12043 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 12044 case ISD::VASTART: return LowerVASTART(Op, DAG); 12045 case ISD::VAARG: return LowerVAARG(Op, DAG); 12046 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG); 12047 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 12048 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 12049 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 12050 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 12051 case ISD::FRAME_TO_ARGS_OFFSET: 12052 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG); 12053 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 12054 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG); 12055 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 12056 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 12057 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 12058 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 12059 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 12060 case ISD::CTLZ: return LowerCTLZ(Op, DAG); 12061 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG); 12062 case ISD::CTTZ: return LowerCTTZ(Op, DAG); 12063 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG); 12064 case ISD::SRA: 12065 case ISD::SRL: 12066 case ISD::SHL: return LowerShift(Op, DAG); 12067 case ISD::SADDO: 12068 case ISD::UADDO: 12069 case ISD::SSUBO: 12070 case ISD::USUBO: 12071 case ISD::SMULO: 12072 case ISD::UMULO: return LowerXALUO(Op, DAG); 12073 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG); 12074 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 12075 case ISD::ADDC: 12076 case ISD::ADDE: 12077 case ISD::SUBC: 12078 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 12079 case ISD::ADD: return LowerADD(Op, DAG); 12080 case ISD::SUB: return LowerSUB(Op, DAG); 12081 case ISD::SDIV: return LowerSDIV(Op, DAG); 12082 } 12083} 12084 12085static void ReplaceATOMIC_LOAD(SDNode *Node, 12086 SmallVectorImpl<SDValue> &Results, 12087 SelectionDAG &DAG) { 12088 DebugLoc dl = Node->getDebugLoc(); 12089 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT(); 12090 12091 // Convert wide load -> cmpxchg8b/cmpxchg16b 12092 // FIXME: On 32-bit, load -> fild or movq would be more efficient 12093 // (The only way to get a 16-byte load is cmpxchg16b) 12094 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment. 12095 SDValue Zero = DAG.getConstant(0, VT); 12096 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT, 12097 Node->getOperand(0), 12098 Node->getOperand(1), Zero, Zero, 12099 cast<AtomicSDNode>(Node)->getMemOperand(), 12100 cast<AtomicSDNode>(Node)->getOrdering(), 12101 cast<AtomicSDNode>(Node)->getSynchScope()); 12102 Results.push_back(Swap.getValue(0)); 12103 Results.push_back(Swap.getValue(1)); 12104} 12105 12106static void 12107ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results, 12108 SelectionDAG &DAG, unsigned NewOp) { 12109 DebugLoc dl = Node->getDebugLoc(); 12110 assert (Node->getValueType(0) == MVT::i64 && 12111 "Only know how to expand i64 atomics"); 12112 12113 SDValue Chain = Node->getOperand(0); 12114 SDValue In1 = Node->getOperand(1); 12115 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12116 Node->getOperand(2), DAG.getIntPtrConstant(0)); 12117 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, 12118 Node->getOperand(2), DAG.getIntPtrConstant(1)); 12119 SDValue Ops[] = { Chain, In1, In2L, In2H }; 12120 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 12121 SDValue Result = 12122 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64, 12123 cast<MemSDNode>(Node)->getMemOperand()); 12124 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)}; 12125 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2)); 12126 Results.push_back(Result.getValue(2)); 12127} 12128 12129/// ReplaceNodeResults - Replace a node with an illegal result type 12130/// with a new node built out of custom code. 12131void X86TargetLowering::ReplaceNodeResults(SDNode *N, 12132 SmallVectorImpl<SDValue>&Results, 12133 SelectionDAG &DAG) const { 12134 DebugLoc dl = N->getDebugLoc(); 12135 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12136 switch (N->getOpcode()) { 12137 default: 12138 llvm_unreachable("Do not know how to custom type legalize this operation!"); 12139 case ISD::SIGN_EXTEND_INREG: 12140 case ISD::ADDC: 12141 case ISD::ADDE: 12142 case ISD::SUBC: 12143 case ISD::SUBE: 12144 // We don't want to expand or promote these. 12145 return; 12146 case ISD::FP_TO_SINT: 12147 case ISD::FP_TO_UINT: { 12148 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 12149 12150 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType())) 12151 return; 12152 12153 std::pair<SDValue,SDValue> Vals = 12154 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true); 12155 SDValue FIST = Vals.first, StackSlot = Vals.second; 12156 if (FIST.getNode() != 0) { 12157 EVT VT = N->getValueType(0); 12158 // Return a load from the stack slot. 12159 if (StackSlot.getNode() != 0) 12160 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, 12161 MachinePointerInfo(), 12162 false, false, false, 0)); 12163 else 12164 Results.push_back(FIST); 12165 } 12166 return; 12167 } 12168 case ISD::UINT_TO_FP: { 12169 if (N->getOperand(0).getValueType() != MVT::v2i32 && 12170 N->getValueType(0) != MVT::v2f32) 12171 return; 12172 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, 12173 N->getOperand(0)); 12174 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), 12175 MVT::f64); 12176 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias); 12177 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn, 12178 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias)); 12179 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or); 12180 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias); 12181 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub)); 12182 return; 12183 } 12184 case ISD::FP_ROUND: { 12185 if (!TLI.isTypeLegal(N->getOperand(0).getValueType())) 12186 return; 12187 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0)); 12188 Results.push_back(V); 12189 return; 12190 } 12191 case ISD::READCYCLECOUNTER: { 12192 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12193 SDValue TheChain = N->getOperand(0); 12194 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1); 12195 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32, 12196 rd.getValue(1)); 12197 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32, 12198 eax.getValue(2)); 12199 // Use a buildpair to merge the two 32-bit values into a 64-bit one. 12200 SDValue Ops[] = { eax, edx }; 12201 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2)); 12202 Results.push_back(edx.getValue(1)); 12203 return; 12204 } 12205 case ISD::ATOMIC_CMP_SWAP: { 12206 EVT T = N->getValueType(0); 12207 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"); 12208 bool Regs64bit = T == MVT::i128; 12209 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32; 12210 SDValue cpInL, cpInH; 12211 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 12212 DAG.getConstant(0, HalfT)); 12213 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2), 12214 DAG.getConstant(1, HalfT)); 12215 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, 12216 Regs64bit ? X86::RAX : X86::EAX, 12217 cpInL, SDValue()); 12218 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, 12219 Regs64bit ? X86::RDX : X86::EDX, 12220 cpInH, cpInL.getValue(1)); 12221 SDValue swapInL, swapInH; 12222 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 12223 DAG.getConstant(0, HalfT)); 12224 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3), 12225 DAG.getConstant(1, HalfT)); 12226 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, 12227 Regs64bit ? X86::RBX : X86::EBX, 12228 swapInL, cpInH.getValue(1)); 12229 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, 12230 Regs64bit ? X86::RCX : X86::ECX, 12231 swapInH, swapInL.getValue(1)); 12232 SDValue Ops[] = { swapInH.getValue(0), 12233 N->getOperand(1), 12234 swapInH.getValue(1) }; 12235 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue); 12236 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand(); 12237 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG : 12238 X86ISD::LCMPXCHG8_DAG; 12239 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, 12240 Ops, 3, T, MMO); 12241 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, 12242 Regs64bit ? X86::RAX : X86::EAX, 12243 HalfT, Result.getValue(1)); 12244 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, 12245 Regs64bit ? X86::RDX : X86::EDX, 12246 HalfT, cpOutL.getValue(2)); 12247 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)}; 12248 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2)); 12249 Results.push_back(cpOutH.getValue(1)); 12250 return; 12251 } 12252 case ISD::ATOMIC_LOAD_ADD: 12253 case ISD::ATOMIC_LOAD_AND: 12254 case ISD::ATOMIC_LOAD_NAND: 12255 case ISD::ATOMIC_LOAD_OR: 12256 case ISD::ATOMIC_LOAD_SUB: 12257 case ISD::ATOMIC_LOAD_XOR: 12258 case ISD::ATOMIC_LOAD_MAX: 12259 case ISD::ATOMIC_LOAD_MIN: 12260 case ISD::ATOMIC_LOAD_UMAX: 12261 case ISD::ATOMIC_LOAD_UMIN: 12262 case ISD::ATOMIC_SWAP: { 12263 unsigned Opc; 12264 switch (N->getOpcode()) { 12265 default: llvm_unreachable("Unexpected opcode"); 12266 case ISD::ATOMIC_LOAD_ADD: 12267 Opc = X86ISD::ATOMADD64_DAG; 12268 break; 12269 case ISD::ATOMIC_LOAD_AND: 12270 Opc = X86ISD::ATOMAND64_DAG; 12271 break; 12272 case ISD::ATOMIC_LOAD_NAND: 12273 Opc = X86ISD::ATOMNAND64_DAG; 12274 break; 12275 case ISD::ATOMIC_LOAD_OR: 12276 Opc = X86ISD::ATOMOR64_DAG; 12277 break; 12278 case ISD::ATOMIC_LOAD_SUB: 12279 Opc = X86ISD::ATOMSUB64_DAG; 12280 break; 12281 case ISD::ATOMIC_LOAD_XOR: 12282 Opc = X86ISD::ATOMXOR64_DAG; 12283 break; 12284 case ISD::ATOMIC_LOAD_MAX: 12285 Opc = X86ISD::ATOMMAX64_DAG; 12286 break; 12287 case ISD::ATOMIC_LOAD_MIN: 12288 Opc = X86ISD::ATOMMIN64_DAG; 12289 break; 12290 case ISD::ATOMIC_LOAD_UMAX: 12291 Opc = X86ISD::ATOMUMAX64_DAG; 12292 break; 12293 case ISD::ATOMIC_LOAD_UMIN: 12294 Opc = X86ISD::ATOMUMIN64_DAG; 12295 break; 12296 case ISD::ATOMIC_SWAP: 12297 Opc = X86ISD::ATOMSWAP64_DAG; 12298 break; 12299 } 12300 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc); 12301 return; 12302 } 12303 case ISD::ATOMIC_LOAD: 12304 ReplaceATOMIC_LOAD(N, Results, DAG); 12305 } 12306} 12307 12308const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const { 12309 switch (Opcode) { 12310 default: return NULL; 12311 case X86ISD::BSF: return "X86ISD::BSF"; 12312 case X86ISD::BSR: return "X86ISD::BSR"; 12313 case X86ISD::SHLD: return "X86ISD::SHLD"; 12314 case X86ISD::SHRD: return "X86ISD::SHRD"; 12315 case X86ISD::FAND: return "X86ISD::FAND"; 12316 case X86ISD::FOR: return "X86ISD::FOR"; 12317 case X86ISD::FXOR: return "X86ISD::FXOR"; 12318 case X86ISD::FSRL: return "X86ISD::FSRL"; 12319 case X86ISD::FILD: return "X86ISD::FILD"; 12320 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG"; 12321 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM"; 12322 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM"; 12323 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM"; 12324 case X86ISD::FLD: return "X86ISD::FLD"; 12325 case X86ISD::FST: return "X86ISD::FST"; 12326 case X86ISD::CALL: return "X86ISD::CALL"; 12327 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG"; 12328 case X86ISD::BT: return "X86ISD::BT"; 12329 case X86ISD::CMP: return "X86ISD::CMP"; 12330 case X86ISD::COMI: return "X86ISD::COMI"; 12331 case X86ISD::UCOMI: return "X86ISD::UCOMI"; 12332 case X86ISD::SETCC: return "X86ISD::SETCC"; 12333 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY"; 12334 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd"; 12335 case X86ISD::FSETCCss: return "X86ISD::FSETCCss"; 12336 case X86ISD::CMOV: return "X86ISD::CMOV"; 12337 case X86ISD::BRCOND: return "X86ISD::BRCOND"; 12338 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG"; 12339 case X86ISD::REP_STOS: return "X86ISD::REP_STOS"; 12340 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS"; 12341 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg"; 12342 case X86ISD::Wrapper: return "X86ISD::Wrapper"; 12343 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP"; 12344 case X86ISD::PEXTRB: return "X86ISD::PEXTRB"; 12345 case X86ISD::PEXTRW: return "X86ISD::PEXTRW"; 12346 case X86ISD::INSERTPS: return "X86ISD::INSERTPS"; 12347 case X86ISD::PINSRB: return "X86ISD::PINSRB"; 12348 case X86ISD::PINSRW: return "X86ISD::PINSRW"; 12349 case X86ISD::PSHUFB: return "X86ISD::PSHUFB"; 12350 case X86ISD::ANDNP: return "X86ISD::ANDNP"; 12351 case X86ISD::PSIGN: return "X86ISD::PSIGN"; 12352 case X86ISD::BLENDV: return "X86ISD::BLENDV"; 12353 case X86ISD::BLENDI: return "X86ISD::BLENDI"; 12354 case X86ISD::SUBUS: return "X86ISD::SUBUS"; 12355 case X86ISD::HADD: return "X86ISD::HADD"; 12356 case X86ISD::HSUB: return "X86ISD::HSUB"; 12357 case X86ISD::FHADD: return "X86ISD::FHADD"; 12358 case X86ISD::FHSUB: return "X86ISD::FHSUB"; 12359 case X86ISD::UMAX: return "X86ISD::UMAX"; 12360 case X86ISD::UMIN: return "X86ISD::UMIN"; 12361 case X86ISD::SMAX: return "X86ISD::SMAX"; 12362 case X86ISD::SMIN: return "X86ISD::SMIN"; 12363 case X86ISD::FMAX: return "X86ISD::FMAX"; 12364 case X86ISD::FMIN: return "X86ISD::FMIN"; 12365 case X86ISD::FMAXC: return "X86ISD::FMAXC"; 12366 case X86ISD::FMINC: return "X86ISD::FMINC"; 12367 case X86ISD::FRSQRT: return "X86ISD::FRSQRT"; 12368 case X86ISD::FRCP: return "X86ISD::FRCP"; 12369 case X86ISD::TLSADDR: return "X86ISD::TLSADDR"; 12370 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR"; 12371 case X86ISD::TLSCALL: return "X86ISD::TLSCALL"; 12372 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP"; 12373 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP"; 12374 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN"; 12375 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN"; 12376 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m"; 12377 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r"; 12378 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG"; 12379 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG"; 12380 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG"; 12381 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG"; 12382 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG"; 12383 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG"; 12384 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG"; 12385 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG"; 12386 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL"; 12387 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL"; 12388 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD"; 12389 case X86ISD::VZEXT: return "X86ISD::VZEXT"; 12390 case X86ISD::VSEXT: return "X86ISD::VSEXT"; 12391 case X86ISD::VFPEXT: return "X86ISD::VFPEXT"; 12392 case X86ISD::VFPROUND: return "X86ISD::VFPROUND"; 12393 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ"; 12394 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ"; 12395 case X86ISD::VSHL: return "X86ISD::VSHL"; 12396 case X86ISD::VSRL: return "X86ISD::VSRL"; 12397 case X86ISD::VSRA: return "X86ISD::VSRA"; 12398 case X86ISD::VSHLI: return "X86ISD::VSHLI"; 12399 case X86ISD::VSRLI: return "X86ISD::VSRLI"; 12400 case X86ISD::VSRAI: return "X86ISD::VSRAI"; 12401 case X86ISD::CMPP: return "X86ISD::CMPP"; 12402 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ"; 12403 case X86ISD::PCMPGT: return "X86ISD::PCMPGT"; 12404 case X86ISD::ADD: return "X86ISD::ADD"; 12405 case X86ISD::SUB: return "X86ISD::SUB"; 12406 case X86ISD::ADC: return "X86ISD::ADC"; 12407 case X86ISD::SBB: return "X86ISD::SBB"; 12408 case X86ISD::SMUL: return "X86ISD::SMUL"; 12409 case X86ISD::UMUL: return "X86ISD::UMUL"; 12410 case X86ISD::INC: return "X86ISD::INC"; 12411 case X86ISD::DEC: return "X86ISD::DEC"; 12412 case X86ISD::OR: return "X86ISD::OR"; 12413 case X86ISD::XOR: return "X86ISD::XOR"; 12414 case X86ISD::AND: return "X86ISD::AND"; 12415 case X86ISD::BLSI: return "X86ISD::BLSI"; 12416 case X86ISD::BLSMSK: return "X86ISD::BLSMSK"; 12417 case X86ISD::BLSR: return "X86ISD::BLSR"; 12418 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM"; 12419 case X86ISD::PTEST: return "X86ISD::PTEST"; 12420 case X86ISD::TESTP: return "X86ISD::TESTP"; 12421 case X86ISD::PALIGN: return "X86ISD::PALIGN"; 12422 case X86ISD::PSHUFD: return "X86ISD::PSHUFD"; 12423 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW"; 12424 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW"; 12425 case X86ISD::SHUFP: return "X86ISD::SHUFP"; 12426 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS"; 12427 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD"; 12428 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS"; 12429 case X86ISD::MOVLPS: return "X86ISD::MOVLPS"; 12430 case X86ISD::MOVLPD: return "X86ISD::MOVLPD"; 12431 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP"; 12432 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP"; 12433 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP"; 12434 case X86ISD::MOVSD: return "X86ISD::MOVSD"; 12435 case X86ISD::MOVSS: return "X86ISD::MOVSS"; 12436 case X86ISD::UNPCKL: return "X86ISD::UNPCKL"; 12437 case X86ISD::UNPCKH: return "X86ISD::UNPCKH"; 12438 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST"; 12439 case X86ISD::VPERMILP: return "X86ISD::VPERMILP"; 12440 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128"; 12441 case X86ISD::VPERMV: return "X86ISD::VPERMV"; 12442 case X86ISD::VPERMI: return "X86ISD::VPERMI"; 12443 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ"; 12444 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS"; 12445 case X86ISD::VAARG_64: return "X86ISD::VAARG_64"; 12446 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA"; 12447 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER"; 12448 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA"; 12449 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL"; 12450 case X86ISD::SAHF: return "X86ISD::SAHF"; 12451 case X86ISD::RDRAND: return "X86ISD::RDRAND"; 12452 case X86ISD::FMADD: return "X86ISD::FMADD"; 12453 case X86ISD::FMSUB: return "X86ISD::FMSUB"; 12454 case X86ISD::FNMADD: return "X86ISD::FNMADD"; 12455 case X86ISD::FNMSUB: return "X86ISD::FNMSUB"; 12456 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB"; 12457 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD"; 12458 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI"; 12459 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI"; 12460 } 12461} 12462 12463// isLegalAddressingMode - Return true if the addressing mode represented 12464// by AM is legal for this target, for a load/store of the specified type. 12465bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 12466 Type *Ty) const { 12467 // X86 supports extremely general addressing modes. 12468 CodeModel::Model M = getTargetMachine().getCodeModel(); 12469 Reloc::Model R = getTargetMachine().getRelocationModel(); 12470 12471 // X86 allows a sign-extended 32-bit immediate field as a displacement. 12472 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL)) 12473 return false; 12474 12475 if (AM.BaseGV) { 12476 unsigned GVFlags = 12477 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine()); 12478 12479 // If a reference to this global requires an extra load, we can't fold it. 12480 if (isGlobalStubReference(GVFlags)) 12481 return false; 12482 12483 // If BaseGV requires a register for the PIC base, we cannot also have a 12484 // BaseReg specified. 12485 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags)) 12486 return false; 12487 12488 // If lower 4G is not available, then we must use rip-relative addressing. 12489 if ((M != CodeModel::Small || R != Reloc::Static) && 12490 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1)) 12491 return false; 12492 } 12493 12494 switch (AM.Scale) { 12495 case 0: 12496 case 1: 12497 case 2: 12498 case 4: 12499 case 8: 12500 // These scales always work. 12501 break; 12502 case 3: 12503 case 5: 12504 case 9: 12505 // These scales are formed with basereg+scalereg. Only accept if there is 12506 // no basereg yet. 12507 if (AM.HasBaseReg) 12508 return false; 12509 break; 12510 default: // Other stuff never works. 12511 return false; 12512 } 12513 12514 return true; 12515} 12516 12517bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 12518 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 12519 return false; 12520 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 12521 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 12522 return NumBits1 > NumBits2; 12523} 12524 12525bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const { 12526 return isInt<32>(Imm); 12527} 12528 12529bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const { 12530 // Can also use sub to handle negated immediates. 12531 return isInt<32>(Imm); 12532} 12533 12534bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 12535 if (!VT1.isInteger() || !VT2.isInteger()) 12536 return false; 12537 unsigned NumBits1 = VT1.getSizeInBits(); 12538 unsigned NumBits2 = VT2.getSizeInBits(); 12539 return NumBits1 > NumBits2; 12540} 12541 12542bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 12543 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 12544 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit(); 12545} 12546 12547bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 12548 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers. 12549 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit(); 12550} 12551 12552bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 12553 EVT VT1 = Val.getValueType(); 12554 if (isZExtFree(VT1, VT2)) 12555 return true; 12556 12557 if (Val.getOpcode() != ISD::LOAD) 12558 return false; 12559 12560 if (!VT1.isSimple() || !VT1.isInteger() || 12561 !VT2.isSimple() || !VT2.isInteger()) 12562 return false; 12563 12564 switch (VT1.getSimpleVT().SimpleTy) { 12565 default: break; 12566 case MVT::i8: 12567 case MVT::i16: 12568 case MVT::i32: 12569 // X86 has 8, 16, and 32-bit zero-extending loads. 12570 return true; 12571 } 12572 12573 return false; 12574} 12575 12576bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const { 12577 // i16 instructions are longer (0x66 prefix) and potentially slower. 12578 return !(VT1 == MVT::i32 && VT2 == MVT::i16); 12579} 12580 12581/// isShuffleMaskLegal - Targets can use this to indicate that they only 12582/// support *some* VECTOR_SHUFFLE operations, those with specific masks. 12583/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 12584/// are assumed to be legal. 12585bool 12586X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 12587 EVT VT) const { 12588 // Very little shuffling can be done for 64-bit vectors right now. 12589 if (VT.getSizeInBits() == 64) 12590 return false; 12591 12592 // FIXME: pshufb, blends, shifts. 12593 return (VT.getVectorNumElements() == 2 || 12594 ShuffleVectorSDNode::isSplatMask(&M[0], VT) || 12595 isMOVLMask(M, VT) || 12596 isSHUFPMask(M, VT, Subtarget->hasFp256()) || 12597 isPSHUFDMask(M, VT) || 12598 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) || 12599 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) || 12600 isPALIGNRMask(M, VT, Subtarget) || 12601 isUNPCKLMask(M, VT, Subtarget->hasInt256()) || 12602 isUNPCKHMask(M, VT, Subtarget->hasInt256()) || 12603 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) || 12604 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256())); 12605} 12606 12607bool 12608X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 12609 EVT VT) const { 12610 unsigned NumElts = VT.getVectorNumElements(); 12611 // FIXME: This collection of masks seems suspect. 12612 if (NumElts == 2) 12613 return true; 12614 if (NumElts == 4 && VT.is128BitVector()) { 12615 return (isMOVLMask(Mask, VT) || 12616 isCommutedMOVLMask(Mask, VT, true) || 12617 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) || 12618 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true)); 12619 } 12620 return false; 12621} 12622 12623//===----------------------------------------------------------------------===// 12624// X86 Scheduler Hooks 12625//===----------------------------------------------------------------------===// 12626 12627/// Utility function to emit xbegin specifying the start of an RTM region. 12628static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB, 12629 const TargetInstrInfo *TII) { 12630 DebugLoc DL = MI->getDebugLoc(); 12631 12632 const BasicBlock *BB = MBB->getBasicBlock(); 12633 MachineFunction::iterator I = MBB; 12634 ++I; 12635 12636 // For the v = xbegin(), we generate 12637 // 12638 // thisMBB: 12639 // xbegin sinkMBB 12640 // 12641 // mainMBB: 12642 // eax = -1 12643 // 12644 // sinkMBB: 12645 // v = eax 12646 12647 MachineBasicBlock *thisMBB = MBB; 12648 MachineFunction *MF = MBB->getParent(); 12649 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 12650 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 12651 MF->insert(I, mainMBB); 12652 MF->insert(I, sinkMBB); 12653 12654 // Transfer the remainder of BB and its successor edges to sinkMBB. 12655 sinkMBB->splice(sinkMBB->begin(), MBB, 12656 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12657 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 12658 12659 // thisMBB: 12660 // xbegin sinkMBB 12661 // # fallthrough to mainMBB 12662 // # abortion to sinkMBB 12663 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB); 12664 thisMBB->addSuccessor(mainMBB); 12665 thisMBB->addSuccessor(sinkMBB); 12666 12667 // mainMBB: 12668 // EAX = -1 12669 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1); 12670 mainMBB->addSuccessor(sinkMBB); 12671 12672 // sinkMBB: 12673 // EAX is live into the sinkMBB 12674 sinkMBB->addLiveIn(X86::EAX); 12675 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12676 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 12677 .addReg(X86::EAX); 12678 12679 MI->eraseFromParent(); 12680 return sinkMBB; 12681} 12682 12683// Get CMPXCHG opcode for the specified data type. 12684static unsigned getCmpXChgOpcode(EVT VT) { 12685 switch (VT.getSimpleVT().SimpleTy) { 12686 case MVT::i8: return X86::LCMPXCHG8; 12687 case MVT::i16: return X86::LCMPXCHG16; 12688 case MVT::i32: return X86::LCMPXCHG32; 12689 case MVT::i64: return X86::LCMPXCHG64; 12690 default: 12691 break; 12692 } 12693 llvm_unreachable("Invalid operand size!"); 12694} 12695 12696// Get LOAD opcode for the specified data type. 12697static unsigned getLoadOpcode(EVT VT) { 12698 switch (VT.getSimpleVT().SimpleTy) { 12699 case MVT::i8: return X86::MOV8rm; 12700 case MVT::i16: return X86::MOV16rm; 12701 case MVT::i32: return X86::MOV32rm; 12702 case MVT::i64: return X86::MOV64rm; 12703 default: 12704 break; 12705 } 12706 llvm_unreachable("Invalid operand size!"); 12707} 12708 12709// Get opcode of the non-atomic one from the specified atomic instruction. 12710static unsigned getNonAtomicOpcode(unsigned Opc) { 12711 switch (Opc) { 12712 case X86::ATOMAND8: return X86::AND8rr; 12713 case X86::ATOMAND16: return X86::AND16rr; 12714 case X86::ATOMAND32: return X86::AND32rr; 12715 case X86::ATOMAND64: return X86::AND64rr; 12716 case X86::ATOMOR8: return X86::OR8rr; 12717 case X86::ATOMOR16: return X86::OR16rr; 12718 case X86::ATOMOR32: return X86::OR32rr; 12719 case X86::ATOMOR64: return X86::OR64rr; 12720 case X86::ATOMXOR8: return X86::XOR8rr; 12721 case X86::ATOMXOR16: return X86::XOR16rr; 12722 case X86::ATOMXOR32: return X86::XOR32rr; 12723 case X86::ATOMXOR64: return X86::XOR64rr; 12724 } 12725 llvm_unreachable("Unhandled atomic-load-op opcode!"); 12726} 12727 12728// Get opcode of the non-atomic one from the specified atomic instruction with 12729// extra opcode. 12730static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc, 12731 unsigned &ExtraOpc) { 12732 switch (Opc) { 12733 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr; 12734 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr; 12735 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr; 12736 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr; 12737 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr; 12738 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr; 12739 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr; 12740 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr; 12741 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr; 12742 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr; 12743 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr; 12744 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr; 12745 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr; 12746 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr; 12747 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr; 12748 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr; 12749 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr; 12750 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr; 12751 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr; 12752 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr; 12753 } 12754 llvm_unreachable("Unhandled atomic-load-op opcode!"); 12755} 12756 12757// Get opcode of the non-atomic one from the specified atomic instruction for 12758// 64-bit data type on 32-bit target. 12759static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) { 12760 switch (Opc) { 12761 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr; 12762 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr; 12763 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr; 12764 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr; 12765 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr; 12766 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr; 12767 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr; 12768 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr; 12769 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr; 12770 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr; 12771 } 12772 llvm_unreachable("Unhandled atomic-load-op opcode!"); 12773} 12774 12775// Get opcode of the non-atomic one from the specified atomic instruction for 12776// 64-bit data type on 32-bit target with extra opcode. 12777static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc, 12778 unsigned &HiOpc, 12779 unsigned &ExtraOpc) { 12780 switch (Opc) { 12781 case X86::ATOMNAND6432: 12782 ExtraOpc = X86::NOT32r; 12783 HiOpc = X86::AND32rr; 12784 return X86::AND32rr; 12785 } 12786 llvm_unreachable("Unhandled atomic-load-op opcode!"); 12787} 12788 12789// Get pseudo CMOV opcode from the specified data type. 12790static unsigned getPseudoCMOVOpc(EVT VT) { 12791 switch (VT.getSimpleVT().SimpleTy) { 12792 case MVT::i8: return X86::CMOV_GR8; 12793 case MVT::i16: return X86::CMOV_GR16; 12794 case MVT::i32: return X86::CMOV_GR32; 12795 default: 12796 break; 12797 } 12798 llvm_unreachable("Unknown CMOV opcode!"); 12799} 12800 12801// EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions. 12802// They will be translated into a spin-loop or compare-exchange loop from 12803// 12804// ... 12805// dst = atomic-fetch-op MI.addr, MI.val 12806// ... 12807// 12808// to 12809// 12810// ... 12811// EAX = LOAD MI.addr 12812// loop: 12813// t1 = OP MI.val, EAX 12814// LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined] 12815// JNE loop 12816// sink: 12817// dst = EAX 12818// ... 12819MachineBasicBlock * 12820X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI, 12821 MachineBasicBlock *MBB) const { 12822 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 12823 DebugLoc DL = MI->getDebugLoc(); 12824 12825 MachineFunction *MF = MBB->getParent(); 12826 MachineRegisterInfo &MRI = MF->getRegInfo(); 12827 12828 const BasicBlock *BB = MBB->getBasicBlock(); 12829 MachineFunction::iterator I = MBB; 12830 ++I; 12831 12832 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 && 12833 "Unexpected number of operands"); 12834 12835 assert(MI->hasOneMemOperand() && 12836 "Expected atomic-load-op to have one memoperand"); 12837 12838 // Memory Reference 12839 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 12840 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 12841 12842 unsigned DstReg, SrcReg; 12843 unsigned MemOpndSlot; 12844 12845 unsigned CurOp = 0; 12846 12847 DstReg = MI->getOperand(CurOp++).getReg(); 12848 MemOpndSlot = CurOp; 12849 CurOp += X86::AddrNumOperands; 12850 SrcReg = MI->getOperand(CurOp++).getReg(); 12851 12852 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 12853 MVT::SimpleValueType VT = *RC->vt_begin(); 12854 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT); 12855 12856 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT); 12857 unsigned LOADOpc = getLoadOpcode(VT); 12858 12859 // For the atomic load-arith operator, we generate 12860 // 12861 // thisMBB: 12862 // EAX = LOAD [MI.addr] 12863 // mainMBB: 12864 // t1 = OP MI.val, EAX 12865 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined] 12866 // JNE mainMBB 12867 // sinkMBB: 12868 12869 MachineBasicBlock *thisMBB = MBB; 12870 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 12871 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 12872 MF->insert(I, mainMBB); 12873 MF->insert(I, sinkMBB); 12874 12875 MachineInstrBuilder MIB; 12876 12877 // Transfer the remainder of BB and its successor edges to sinkMBB. 12878 sinkMBB->splice(sinkMBB->begin(), MBB, 12879 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12880 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 12881 12882 // thisMBB: 12883 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg); 12884 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 12885 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 12886 MIB.setMemRefs(MMOBegin, MMOEnd); 12887 12888 thisMBB->addSuccessor(mainMBB); 12889 12890 // mainMBB: 12891 MachineBasicBlock *origMainMBB = mainMBB; 12892 mainMBB->addLiveIn(AccPhyReg); 12893 12894 // Copy AccPhyReg as it is used more than once. 12895 unsigned AccReg = MRI.createVirtualRegister(RC); 12896 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg) 12897 .addReg(AccPhyReg); 12898 12899 unsigned t1 = MRI.createVirtualRegister(RC); 12900 unsigned Opc = MI->getOpcode(); 12901 switch (Opc) { 12902 default: 12903 llvm_unreachable("Unhandled atomic-load-op opcode!"); 12904 case X86::ATOMAND8: 12905 case X86::ATOMAND16: 12906 case X86::ATOMAND32: 12907 case X86::ATOMAND64: 12908 case X86::ATOMOR8: 12909 case X86::ATOMOR16: 12910 case X86::ATOMOR32: 12911 case X86::ATOMOR64: 12912 case X86::ATOMXOR8: 12913 case X86::ATOMXOR16: 12914 case X86::ATOMXOR32: 12915 case X86::ATOMXOR64: { 12916 unsigned ARITHOpc = getNonAtomicOpcode(Opc); 12917 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg) 12918 .addReg(AccReg); 12919 break; 12920 } 12921 case X86::ATOMNAND8: 12922 case X86::ATOMNAND16: 12923 case X86::ATOMNAND32: 12924 case X86::ATOMNAND64: { 12925 unsigned t2 = MRI.createVirtualRegister(RC); 12926 unsigned NOTOpc; 12927 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc); 12928 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg) 12929 .addReg(AccReg); 12930 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2); 12931 break; 12932 } 12933 case X86::ATOMMAX8: 12934 case X86::ATOMMAX16: 12935 case X86::ATOMMAX32: 12936 case X86::ATOMMAX64: 12937 case X86::ATOMMIN8: 12938 case X86::ATOMMIN16: 12939 case X86::ATOMMIN32: 12940 case X86::ATOMMIN64: 12941 case X86::ATOMUMAX8: 12942 case X86::ATOMUMAX16: 12943 case X86::ATOMUMAX32: 12944 case X86::ATOMUMAX64: 12945 case X86::ATOMUMIN8: 12946 case X86::ATOMUMIN16: 12947 case X86::ATOMUMIN32: 12948 case X86::ATOMUMIN64: { 12949 unsigned CMPOpc; 12950 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc); 12951 12952 BuildMI(mainMBB, DL, TII->get(CMPOpc)) 12953 .addReg(SrcReg) 12954 .addReg(AccReg); 12955 12956 if (Subtarget->hasCMov()) { 12957 if (VT != MVT::i8) { 12958 // Native support 12959 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1) 12960 .addReg(SrcReg) 12961 .addReg(AccReg); 12962 } else { 12963 // Promote i8 to i32 to use CMOV32 12964 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32); 12965 unsigned SrcReg32 = MRI.createVirtualRegister(RC32); 12966 unsigned AccReg32 = MRI.createVirtualRegister(RC32); 12967 unsigned t2 = MRI.createVirtualRegister(RC32); 12968 12969 unsigned Undef = MRI.createVirtualRegister(RC32); 12970 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef); 12971 12972 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32) 12973 .addReg(Undef) 12974 .addReg(SrcReg) 12975 .addImm(X86::sub_8bit); 12976 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32) 12977 .addReg(Undef) 12978 .addReg(AccReg) 12979 .addImm(X86::sub_8bit); 12980 12981 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2) 12982 .addReg(SrcReg32) 12983 .addReg(AccReg32); 12984 12985 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1) 12986 .addReg(t2, 0, X86::sub_8bit); 12987 } 12988 } else { 12989 // Use pseudo select and lower them. 12990 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 12991 "Invalid atomic-load-op transformation!"); 12992 unsigned SelOpc = getPseudoCMOVOpc(VT); 12993 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc); 12994 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!"); 12995 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1) 12996 .addReg(SrcReg).addReg(AccReg) 12997 .addImm(CC); 12998 mainMBB = EmitLoweredSelect(MIB, mainMBB); 12999 } 13000 break; 13001 } 13002 } 13003 13004 // Copy AccPhyReg back from virtual register. 13005 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg) 13006 .addReg(AccReg); 13007 13008 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 13009 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 13010 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 13011 MIB.addReg(t1); 13012 MIB.setMemRefs(MMOBegin, MMOEnd); 13013 13014 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 13015 13016 mainMBB->addSuccessor(origMainMBB); 13017 mainMBB->addSuccessor(sinkMBB); 13018 13019 // sinkMBB: 13020 sinkMBB->addLiveIn(AccPhyReg); 13021 13022 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13023 TII->get(TargetOpcode::COPY), DstReg) 13024 .addReg(AccPhyReg); 13025 13026 MI->eraseFromParent(); 13027 return sinkMBB; 13028} 13029 13030// EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic 13031// instructions. They will be translated into a spin-loop or compare-exchange 13032// loop from 13033// 13034// ... 13035// dst = atomic-fetch-op MI.addr, MI.val 13036// ... 13037// 13038// to 13039// 13040// ... 13041// EAX = LOAD [MI.addr + 0] 13042// EDX = LOAD [MI.addr + 4] 13043// loop: 13044// EBX = OP MI.val.lo, EAX 13045// ECX = OP MI.val.hi, EDX 13046// LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13047// JNE loop 13048// sink: 13049// dst = EDX:EAX 13050// ... 13051MachineBasicBlock * 13052X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI, 13053 MachineBasicBlock *MBB) const { 13054 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13055 DebugLoc DL = MI->getDebugLoc(); 13056 13057 MachineFunction *MF = MBB->getParent(); 13058 MachineRegisterInfo &MRI = MF->getRegInfo(); 13059 13060 const BasicBlock *BB = MBB->getBasicBlock(); 13061 MachineFunction::iterator I = MBB; 13062 ++I; 13063 13064 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 && 13065 "Unexpected number of operands"); 13066 13067 assert(MI->hasOneMemOperand() && 13068 "Expected atomic-load-op32 to have one memoperand"); 13069 13070 // Memory Reference 13071 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13072 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13073 13074 unsigned DstLoReg, DstHiReg; 13075 unsigned SrcLoReg, SrcHiReg; 13076 unsigned MemOpndSlot; 13077 13078 unsigned CurOp = 0; 13079 13080 DstLoReg = MI->getOperand(CurOp++).getReg(); 13081 DstHiReg = MI->getOperand(CurOp++).getReg(); 13082 MemOpndSlot = CurOp; 13083 CurOp += X86::AddrNumOperands; 13084 SrcLoReg = MI->getOperand(CurOp++).getReg(); 13085 SrcHiReg = MI->getOperand(CurOp++).getReg(); 13086 13087 const TargetRegisterClass *RC = &X86::GR32RegClass; 13088 const TargetRegisterClass *RC8 = &X86::GR8RegClass; 13089 13090 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B; 13091 unsigned LOADOpc = X86::MOV32rm; 13092 13093 // For the atomic load-arith operator, we generate 13094 // 13095 // thisMBB: 13096 // EAX = LOAD [MI.addr + 0] 13097 // EDX = LOAD [MI.addr + 4] 13098 // mainMBB: 13099 // EBX = OP MI.vallo, EAX 13100 // ECX = OP MI.valhi, EDX 13101 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined] 13102 // JNE mainMBB 13103 // sinkMBB: 13104 13105 MachineBasicBlock *thisMBB = MBB; 13106 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 13107 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 13108 MF->insert(I, mainMBB); 13109 MF->insert(I, sinkMBB); 13110 13111 MachineInstrBuilder MIB; 13112 13113 // Transfer the remainder of BB and its successor edges to sinkMBB. 13114 sinkMBB->splice(sinkMBB->begin(), MBB, 13115 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 13116 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 13117 13118 // thisMBB: 13119 // Lo 13120 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX); 13121 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 13122 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 13123 MIB.setMemRefs(MMOBegin, MMOEnd); 13124 // Hi 13125 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX); 13126 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 13127 if (i == X86::AddrDisp) 13128 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32) 13129 else 13130 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 13131 } 13132 MIB.setMemRefs(MMOBegin, MMOEnd); 13133 13134 thisMBB->addSuccessor(mainMBB); 13135 13136 // mainMBB: 13137 MachineBasicBlock *origMainMBB = mainMBB; 13138 mainMBB->addLiveIn(X86::EAX); 13139 mainMBB->addLiveIn(X86::EDX); 13140 13141 // Copy EDX:EAX as they are used more than once. 13142 unsigned LoReg = MRI.createVirtualRegister(RC); 13143 unsigned HiReg = MRI.createVirtualRegister(RC); 13144 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX); 13145 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX); 13146 13147 unsigned t1L = MRI.createVirtualRegister(RC); 13148 unsigned t1H = MRI.createVirtualRegister(RC); 13149 13150 unsigned Opc = MI->getOpcode(); 13151 switch (Opc) { 13152 default: 13153 llvm_unreachable("Unhandled atomic-load-op6432 opcode!"); 13154 case X86::ATOMAND6432: 13155 case X86::ATOMOR6432: 13156 case X86::ATOMXOR6432: 13157 case X86::ATOMADD6432: 13158 case X86::ATOMSUB6432: { 13159 unsigned HiOpc; 13160 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13161 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg); 13162 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg); 13163 break; 13164 } 13165 case X86::ATOMNAND6432: { 13166 unsigned HiOpc, NOTOpc; 13167 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc); 13168 unsigned t2L = MRI.createVirtualRegister(RC); 13169 unsigned t2H = MRI.createVirtualRegister(RC); 13170 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg); 13171 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg); 13172 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L); 13173 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H); 13174 break; 13175 } 13176 case X86::ATOMMAX6432: 13177 case X86::ATOMMIN6432: 13178 case X86::ATOMUMAX6432: 13179 case X86::ATOMUMIN6432: { 13180 unsigned HiOpc; 13181 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13182 unsigned cL = MRI.createVirtualRegister(RC8); 13183 unsigned cH = MRI.createVirtualRegister(RC8); 13184 unsigned cL32 = MRI.createVirtualRegister(RC); 13185 unsigned cH32 = MRI.createVirtualRegister(RC); 13186 unsigned cc = MRI.createVirtualRegister(RC); 13187 // cl := cmp src_lo, lo 13188 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 13189 .addReg(SrcLoReg).addReg(LoReg); 13190 BuildMI(mainMBB, DL, TII->get(LoOpc), cL); 13191 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL); 13192 // ch := cmp src_hi, hi 13193 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr)) 13194 .addReg(SrcHiReg).addReg(HiReg); 13195 BuildMI(mainMBB, DL, TII->get(HiOpc), cH); 13196 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH); 13197 // cc := if (src_hi == hi) ? cl : ch; 13198 if (Subtarget->hasCMov()) { 13199 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc) 13200 .addReg(cH32).addReg(cL32); 13201 } else { 13202 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc) 13203 .addReg(cH32).addReg(cL32) 13204 .addImm(X86::COND_E); 13205 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13206 } 13207 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc); 13208 if (Subtarget->hasCMov()) { 13209 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L) 13210 .addReg(SrcLoReg).addReg(LoReg); 13211 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H) 13212 .addReg(SrcHiReg).addReg(HiReg); 13213 } else { 13214 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L) 13215 .addReg(SrcLoReg).addReg(LoReg) 13216 .addImm(X86::COND_NE); 13217 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13218 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H) 13219 .addReg(SrcHiReg).addReg(HiReg) 13220 .addImm(X86::COND_NE); 13221 mainMBB = EmitLoweredSelect(MIB, mainMBB); 13222 } 13223 break; 13224 } 13225 case X86::ATOMSWAP6432: { 13226 unsigned HiOpc; 13227 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc); 13228 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg); 13229 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg); 13230 break; 13231 } 13232 } 13233 13234 // Copy EDX:EAX back from HiReg:LoReg 13235 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg); 13236 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg); 13237 // Copy ECX:EBX from t1H:t1L 13238 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L); 13239 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H); 13240 13241 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc)); 13242 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 13243 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 13244 MIB.setMemRefs(MMOBegin, MMOEnd); 13245 13246 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB); 13247 13248 mainMBB->addSuccessor(origMainMBB); 13249 mainMBB->addSuccessor(sinkMBB); 13250 13251 // sinkMBB: 13252 sinkMBB->addLiveIn(X86::EAX); 13253 sinkMBB->addLiveIn(X86::EDX); 13254 13255 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13256 TII->get(TargetOpcode::COPY), DstLoReg) 13257 .addReg(X86::EAX); 13258 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13259 TII->get(TargetOpcode::COPY), DstHiReg) 13260 .addReg(X86::EDX); 13261 13262 MI->eraseFromParent(); 13263 return sinkMBB; 13264} 13265 13266// FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8 13267// or XMM0_V32I8 in AVX all of this code can be replaced with that 13268// in the .td file. 13269static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB, 13270 const TargetInstrInfo *TII) { 13271 unsigned Opc; 13272 switch (MI->getOpcode()) { 13273 default: llvm_unreachable("illegal opcode!"); 13274 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break; 13275 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break; 13276 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break; 13277 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break; 13278 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break; 13279 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break; 13280 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break; 13281 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break; 13282 } 13283 13284 DebugLoc dl = MI->getDebugLoc(); 13285 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 13286 13287 unsigned NumArgs = MI->getNumOperands(); 13288 for (unsigned i = 1; i < NumArgs; ++i) { 13289 MachineOperand &Op = MI->getOperand(i); 13290 if (!(Op.isReg() && Op.isImplicit())) 13291 MIB.addOperand(Op); 13292 } 13293 if (MI->hasOneMemOperand()) 13294 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 13295 13296 BuildMI(*BB, MI, dl, 13297 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13298 .addReg(X86::XMM0); 13299 13300 MI->eraseFromParent(); 13301 return BB; 13302} 13303 13304// FIXME: Custom handling because TableGen doesn't support multiple implicit 13305// defs in an instruction pattern 13306static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB, 13307 const TargetInstrInfo *TII) { 13308 unsigned Opc; 13309 switch (MI->getOpcode()) { 13310 default: llvm_unreachable("illegal opcode!"); 13311 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break; 13312 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break; 13313 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break; 13314 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break; 13315 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break; 13316 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break; 13317 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break; 13318 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break; 13319 } 13320 13321 DebugLoc dl = MI->getDebugLoc(); 13322 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc)); 13323 13324 unsigned NumArgs = MI->getNumOperands(); // remove the results 13325 for (unsigned i = 1; i < NumArgs; ++i) { 13326 MachineOperand &Op = MI->getOperand(i); 13327 if (!(Op.isReg() && Op.isImplicit())) 13328 MIB.addOperand(Op); 13329 } 13330 if (MI->hasOneMemOperand()) 13331 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end()); 13332 13333 BuildMI(*BB, MI, dl, 13334 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) 13335 .addReg(X86::ECX); 13336 13337 MI->eraseFromParent(); 13338 return BB; 13339} 13340 13341static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB, 13342 const TargetInstrInfo *TII, 13343 const X86Subtarget* Subtarget) { 13344 DebugLoc dl = MI->getDebugLoc(); 13345 13346 // Address into RAX/EAX, other two args into ECX, EDX. 13347 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r; 13348 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX; 13349 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg); 13350 for (int i = 0; i < X86::AddrNumOperands; ++i) 13351 MIB.addOperand(MI->getOperand(i)); 13352 13353 unsigned ValOps = X86::AddrNumOperands; 13354 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX) 13355 .addReg(MI->getOperand(ValOps).getReg()); 13356 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX) 13357 .addReg(MI->getOperand(ValOps+1).getReg()); 13358 13359 // The instruction doesn't actually take any operands though. 13360 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr)); 13361 13362 MI->eraseFromParent(); // The pseudo is gone now. 13363 return BB; 13364} 13365 13366MachineBasicBlock * 13367X86TargetLowering::EmitVAARG64WithCustomInserter( 13368 MachineInstr *MI, 13369 MachineBasicBlock *MBB) const { 13370 // Emit va_arg instruction on X86-64. 13371 13372 // Operands to this pseudo-instruction: 13373 // 0 ) Output : destination address (reg) 13374 // 1-5) Input : va_list address (addr, i64mem) 13375 // 6 ) ArgSize : Size (in bytes) of vararg type 13376 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset 13377 // 8 ) Align : Alignment of type 13378 // 9 ) EFLAGS (implicit-def) 13379 13380 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!"); 13381 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands"); 13382 13383 unsigned DestReg = MI->getOperand(0).getReg(); 13384 MachineOperand &Base = MI->getOperand(1); 13385 MachineOperand &Scale = MI->getOperand(2); 13386 MachineOperand &Index = MI->getOperand(3); 13387 MachineOperand &Disp = MI->getOperand(4); 13388 MachineOperand &Segment = MI->getOperand(5); 13389 unsigned ArgSize = MI->getOperand(6).getImm(); 13390 unsigned ArgMode = MI->getOperand(7).getImm(); 13391 unsigned Align = MI->getOperand(8).getImm(); 13392 13393 // Memory Reference 13394 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"); 13395 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 13396 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 13397 13398 // Machine Information 13399 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13400 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 13401 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64); 13402 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32); 13403 DebugLoc DL = MI->getDebugLoc(); 13404 13405 // struct va_list { 13406 // i32 gp_offset 13407 // i32 fp_offset 13408 // i64 overflow_area (address) 13409 // i64 reg_save_area (address) 13410 // } 13411 // sizeof(va_list) = 24 13412 // alignment(va_list) = 8 13413 13414 unsigned TotalNumIntRegs = 6; 13415 unsigned TotalNumXMMRegs = 8; 13416 bool UseGPOffset = (ArgMode == 1); 13417 bool UseFPOffset = (ArgMode == 2); 13418 unsigned MaxOffset = TotalNumIntRegs * 8 + 13419 (UseFPOffset ? TotalNumXMMRegs * 16 : 0); 13420 13421 /* Align ArgSize to a multiple of 8 */ 13422 unsigned ArgSizeA8 = (ArgSize + 7) & ~7; 13423 bool NeedsAlign = (Align > 8); 13424 13425 MachineBasicBlock *thisMBB = MBB; 13426 MachineBasicBlock *overflowMBB; 13427 MachineBasicBlock *offsetMBB; 13428 MachineBasicBlock *endMBB; 13429 13430 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB 13431 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB 13432 unsigned OffsetReg = 0; 13433 13434 if (!UseGPOffset && !UseFPOffset) { 13435 // If we only pull from the overflow region, we don't create a branch. 13436 // We don't need to alter control flow. 13437 OffsetDestReg = 0; // unused 13438 OverflowDestReg = DestReg; 13439 13440 offsetMBB = NULL; 13441 overflowMBB = thisMBB; 13442 endMBB = thisMBB; 13443 } else { 13444 // First emit code to check if gp_offset (or fp_offset) is below the bound. 13445 // If so, pull the argument from reg_save_area. (branch to offsetMBB) 13446 // If not, pull from overflow_area. (branch to overflowMBB) 13447 // 13448 // thisMBB 13449 // | . 13450 // | . 13451 // offsetMBB overflowMBB 13452 // | . 13453 // | . 13454 // endMBB 13455 13456 // Registers for the PHI in endMBB 13457 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass); 13458 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass); 13459 13460 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 13461 MachineFunction *MF = MBB->getParent(); 13462 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13463 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13464 endMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13465 13466 MachineFunction::iterator MBBIter = MBB; 13467 ++MBBIter; 13468 13469 // Insert the new basic blocks 13470 MF->insert(MBBIter, offsetMBB); 13471 MF->insert(MBBIter, overflowMBB); 13472 MF->insert(MBBIter, endMBB); 13473 13474 // Transfer the remainder of MBB and its successor edges to endMBB. 13475 endMBB->splice(endMBB->begin(), thisMBB, 13476 llvm::next(MachineBasicBlock::iterator(MI)), 13477 thisMBB->end()); 13478 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB); 13479 13480 // Make offsetMBB and overflowMBB successors of thisMBB 13481 thisMBB->addSuccessor(offsetMBB); 13482 thisMBB->addSuccessor(overflowMBB); 13483 13484 // endMBB is a successor of both offsetMBB and overflowMBB 13485 offsetMBB->addSuccessor(endMBB); 13486 overflowMBB->addSuccessor(endMBB); 13487 13488 // Load the offset value into a register 13489 OffsetReg = MRI.createVirtualRegister(OffsetRegClass); 13490 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg) 13491 .addOperand(Base) 13492 .addOperand(Scale) 13493 .addOperand(Index) 13494 .addDisp(Disp, UseFPOffset ? 4 : 0) 13495 .addOperand(Segment) 13496 .setMemRefs(MMOBegin, MMOEnd); 13497 13498 // Check if there is enough room left to pull this argument. 13499 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri)) 13500 .addReg(OffsetReg) 13501 .addImm(MaxOffset + 8 - ArgSizeA8); 13502 13503 // Branch to "overflowMBB" if offset >= max 13504 // Fall through to "offsetMBB" otherwise 13505 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE))) 13506 .addMBB(overflowMBB); 13507 } 13508 13509 // In offsetMBB, emit code to use the reg_save_area. 13510 if (offsetMBB) { 13511 assert(OffsetReg != 0); 13512 13513 // Read the reg_save_area address. 13514 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass); 13515 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg) 13516 .addOperand(Base) 13517 .addOperand(Scale) 13518 .addOperand(Index) 13519 .addDisp(Disp, 16) 13520 .addOperand(Segment) 13521 .setMemRefs(MMOBegin, MMOEnd); 13522 13523 // Zero-extend the offset 13524 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass); 13525 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64) 13526 .addImm(0) 13527 .addReg(OffsetReg) 13528 .addImm(X86::sub_32bit); 13529 13530 // Add the offset to the reg_save_area to get the final address. 13531 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg) 13532 .addReg(OffsetReg64) 13533 .addReg(RegSaveReg); 13534 13535 // Compute the offset for the next argument 13536 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass); 13537 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg) 13538 .addReg(OffsetReg) 13539 .addImm(UseFPOffset ? 16 : 8); 13540 13541 // Store it back into the va_list. 13542 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr)) 13543 .addOperand(Base) 13544 .addOperand(Scale) 13545 .addOperand(Index) 13546 .addDisp(Disp, UseFPOffset ? 4 : 0) 13547 .addOperand(Segment) 13548 .addReg(NextOffsetReg) 13549 .setMemRefs(MMOBegin, MMOEnd); 13550 13551 // Jump to endMBB 13552 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4)) 13553 .addMBB(endMBB); 13554 } 13555 13556 // 13557 // Emit code to use overflow area 13558 // 13559 13560 // Load the overflow_area address into a register. 13561 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass); 13562 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg) 13563 .addOperand(Base) 13564 .addOperand(Scale) 13565 .addOperand(Index) 13566 .addDisp(Disp, 8) 13567 .addOperand(Segment) 13568 .setMemRefs(MMOBegin, MMOEnd); 13569 13570 // If we need to align it, do so. Otherwise, just copy the address 13571 // to OverflowDestReg. 13572 if (NeedsAlign) { 13573 // Align the overflow address 13574 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2"); 13575 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass); 13576 13577 // aligned_addr = (addr + (align-1)) & ~(align-1) 13578 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg) 13579 .addReg(OverflowAddrReg) 13580 .addImm(Align-1); 13581 13582 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg) 13583 .addReg(TmpReg) 13584 .addImm(~(uint64_t)(Align-1)); 13585 } else { 13586 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg) 13587 .addReg(OverflowAddrReg); 13588 } 13589 13590 // Compute the next overflow address after this argument. 13591 // (the overflow address should be kept 8-byte aligned) 13592 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass); 13593 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg) 13594 .addReg(OverflowDestReg) 13595 .addImm(ArgSizeA8); 13596 13597 // Store the new overflow address. 13598 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr)) 13599 .addOperand(Base) 13600 .addOperand(Scale) 13601 .addOperand(Index) 13602 .addDisp(Disp, 8) 13603 .addOperand(Segment) 13604 .addReg(NextAddrReg) 13605 .setMemRefs(MMOBegin, MMOEnd); 13606 13607 // If we branched, emit the PHI to the front of endMBB. 13608 if (offsetMBB) { 13609 BuildMI(*endMBB, endMBB->begin(), DL, 13610 TII->get(X86::PHI), DestReg) 13611 .addReg(OffsetDestReg).addMBB(offsetMBB) 13612 .addReg(OverflowDestReg).addMBB(overflowMBB); 13613 } 13614 13615 // Erase the pseudo instruction 13616 MI->eraseFromParent(); 13617 13618 return endMBB; 13619} 13620 13621MachineBasicBlock * 13622X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter( 13623 MachineInstr *MI, 13624 MachineBasicBlock *MBB) const { 13625 // Emit code to save XMM registers to the stack. The ABI says that the 13626 // number of registers to save is given in %al, so it's theoretically 13627 // possible to do an indirect jump trick to avoid saving all of them, 13628 // however this code takes a simpler approach and just executes all 13629 // of the stores if %al is non-zero. It's less code, and it's probably 13630 // easier on the hardware branch predictor, and stores aren't all that 13631 // expensive anyway. 13632 13633 // Create the new basic blocks. One block contains all the XMM stores, 13634 // and one block is the final destination regardless of whether any 13635 // stores were performed. 13636 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 13637 MachineFunction *F = MBB->getParent(); 13638 MachineFunction::iterator MBBIter = MBB; 13639 ++MBBIter; 13640 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB); 13641 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB); 13642 F->insert(MBBIter, XMMSaveMBB); 13643 F->insert(MBBIter, EndMBB); 13644 13645 // Transfer the remainder of MBB and its successor edges to EndMBB. 13646 EndMBB->splice(EndMBB->begin(), MBB, 13647 llvm::next(MachineBasicBlock::iterator(MI)), 13648 MBB->end()); 13649 EndMBB->transferSuccessorsAndUpdatePHIs(MBB); 13650 13651 // The original block will now fall through to the XMM save block. 13652 MBB->addSuccessor(XMMSaveMBB); 13653 // The XMMSaveMBB will fall through to the end block. 13654 XMMSaveMBB->addSuccessor(EndMBB); 13655 13656 // Now add the instructions. 13657 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13658 DebugLoc DL = MI->getDebugLoc(); 13659 13660 unsigned CountReg = MI->getOperand(0).getReg(); 13661 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm(); 13662 int64_t VarArgsFPOffset = MI->getOperand(2).getImm(); 13663 13664 if (!Subtarget->isTargetWin64()) { 13665 // If %al is 0, branch around the XMM save block. 13666 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg); 13667 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB); 13668 MBB->addSuccessor(EndMBB); 13669 } 13670 13671 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr; 13672 // In the XMM save block, save all the XMM argument registers. 13673 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) { 13674 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset; 13675 MachineMemOperand *MMO = 13676 F->getMachineMemOperand( 13677 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset), 13678 MachineMemOperand::MOStore, 13679 /*Size=*/16, /*Align=*/16); 13680 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc)) 13681 .addFrameIndex(RegSaveFrameIndex) 13682 .addImm(/*Scale=*/1) 13683 .addReg(/*IndexReg=*/0) 13684 .addImm(/*Disp=*/Offset) 13685 .addReg(/*Segment=*/0) 13686 .addReg(MI->getOperand(i).getReg()) 13687 .addMemOperand(MMO); 13688 } 13689 13690 MI->eraseFromParent(); // The pseudo instruction is gone now. 13691 13692 return EndMBB; 13693} 13694 13695// The EFLAGS operand of SelectItr might be missing a kill marker 13696// because there were multiple uses of EFLAGS, and ISel didn't know 13697// which to mark. Figure out whether SelectItr should have had a 13698// kill marker, and set it if it should. Returns the correct kill 13699// marker value. 13700static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr, 13701 MachineBasicBlock* BB, 13702 const TargetRegisterInfo* TRI) { 13703 // Scan forward through BB for a use/def of EFLAGS. 13704 MachineBasicBlock::iterator miI(llvm::next(SelectItr)); 13705 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) { 13706 const MachineInstr& mi = *miI; 13707 if (mi.readsRegister(X86::EFLAGS)) 13708 return false; 13709 if (mi.definesRegister(X86::EFLAGS)) 13710 break; // Should have kill-flag - update below. 13711 } 13712 13713 // If we hit the end of the block, check whether EFLAGS is live into a 13714 // successor. 13715 if (miI == BB->end()) { 13716 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(), 13717 sEnd = BB->succ_end(); 13718 sItr != sEnd; ++sItr) { 13719 MachineBasicBlock* succ = *sItr; 13720 if (succ->isLiveIn(X86::EFLAGS)) 13721 return false; 13722 } 13723 } 13724 13725 // We found a def, or hit the end of the basic block and EFLAGS wasn't live 13726 // out. SelectMI should have a kill flag on EFLAGS. 13727 SelectItr->addRegisterKilled(X86::EFLAGS, TRI); 13728 return true; 13729} 13730 13731MachineBasicBlock * 13732X86TargetLowering::EmitLoweredSelect(MachineInstr *MI, 13733 MachineBasicBlock *BB) const { 13734 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13735 DebugLoc DL = MI->getDebugLoc(); 13736 13737 // To "insert" a SELECT_CC instruction, we actually have to insert the 13738 // diamond control-flow pattern. The incoming instruction knows the 13739 // destination vreg to set, the condition code register to branch on, the 13740 // true/false values to select between, and a branch opcode to use. 13741 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 13742 MachineFunction::iterator It = BB; 13743 ++It; 13744 13745 // thisMBB: 13746 // ... 13747 // TrueVal = ... 13748 // cmpTY ccX, r1, r2 13749 // bCC copy1MBB 13750 // fallthrough --> copy0MBB 13751 MachineBasicBlock *thisMBB = BB; 13752 MachineFunction *F = BB->getParent(); 13753 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 13754 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 13755 F->insert(It, copy0MBB); 13756 F->insert(It, sinkMBB); 13757 13758 // If the EFLAGS register isn't dead in the terminator, then claim that it's 13759 // live into the sink and copy blocks. 13760 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo(); 13761 if (!MI->killsRegister(X86::EFLAGS) && 13762 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) { 13763 copy0MBB->addLiveIn(X86::EFLAGS); 13764 sinkMBB->addLiveIn(X86::EFLAGS); 13765 } 13766 13767 // Transfer the remainder of BB and its successor edges to sinkMBB. 13768 sinkMBB->splice(sinkMBB->begin(), BB, 13769 llvm::next(MachineBasicBlock::iterator(MI)), 13770 BB->end()); 13771 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 13772 13773 // Add the true and fallthrough blocks as its successors. 13774 BB->addSuccessor(copy0MBB); 13775 BB->addSuccessor(sinkMBB); 13776 13777 // Create the conditional branch instruction. 13778 unsigned Opc = 13779 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm()); 13780 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB); 13781 13782 // copy0MBB: 13783 // %FalseValue = ... 13784 // # fallthrough to sinkMBB 13785 copy0MBB->addSuccessor(sinkMBB); 13786 13787 // sinkMBB: 13788 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 13789 // ... 13790 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 13791 TII->get(X86::PHI), MI->getOperand(0).getReg()) 13792 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB) 13793 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); 13794 13795 MI->eraseFromParent(); // The pseudo instruction is gone now. 13796 return sinkMBB; 13797} 13798 13799MachineBasicBlock * 13800X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB, 13801 bool Is64Bit) const { 13802 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13803 DebugLoc DL = MI->getDebugLoc(); 13804 MachineFunction *MF = BB->getParent(); 13805 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 13806 13807 assert(getTargetMachine().Options.EnableSegmentedStacks); 13808 13809 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS; 13810 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30; 13811 13812 // BB: 13813 // ... [Till the alloca] 13814 // If stacklet is not large enough, jump to mallocMBB 13815 // 13816 // bumpMBB: 13817 // Allocate by subtracting from RSP 13818 // Jump to continueMBB 13819 // 13820 // mallocMBB: 13821 // Allocate by call to runtime 13822 // 13823 // continueMBB: 13824 // ... 13825 // [rest of original BB] 13826 // 13827 13828 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13829 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13830 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB); 13831 13832 MachineRegisterInfo &MRI = MF->getRegInfo(); 13833 const TargetRegisterClass *AddrRegClass = 13834 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32); 13835 13836 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass), 13837 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass), 13838 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass), 13839 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass), 13840 sizeVReg = MI->getOperand(1).getReg(), 13841 physSPReg = Is64Bit ? X86::RSP : X86::ESP; 13842 13843 MachineFunction::iterator MBBIter = BB; 13844 ++MBBIter; 13845 13846 MF->insert(MBBIter, bumpMBB); 13847 MF->insert(MBBIter, mallocMBB); 13848 MF->insert(MBBIter, continueMBB); 13849 13850 continueMBB->splice(continueMBB->begin(), BB, llvm::next 13851 (MachineBasicBlock::iterator(MI)), BB->end()); 13852 continueMBB->transferSuccessorsAndUpdatePHIs(BB); 13853 13854 // Add code to the main basic block to check if the stack limit has been hit, 13855 // and if so, jump to mallocMBB otherwise to bumpMBB. 13856 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg); 13857 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg) 13858 .addReg(tmpSPVReg).addReg(sizeVReg); 13859 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr)) 13860 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg) 13861 .addReg(SPLimitVReg); 13862 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB); 13863 13864 // bumpMBB simply decreases the stack pointer, since we know the current 13865 // stacklet has enough space. 13866 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg) 13867 .addReg(SPLimitVReg); 13868 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg) 13869 .addReg(SPLimitVReg); 13870 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 13871 13872 // Calls into a routine in libgcc to allocate more space from the heap. 13873 const uint32_t *RegMask = 13874 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 13875 if (Is64Bit) { 13876 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI) 13877 .addReg(sizeVReg); 13878 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32)) 13879 .addExternalSymbol("__morestack_allocate_stack_space") 13880 .addRegMask(RegMask) 13881 .addReg(X86::RDI, RegState::Implicit) 13882 .addReg(X86::RAX, RegState::ImplicitDefine); 13883 } else { 13884 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg) 13885 .addImm(12); 13886 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg); 13887 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32)) 13888 .addExternalSymbol("__morestack_allocate_stack_space") 13889 .addRegMask(RegMask) 13890 .addReg(X86::EAX, RegState::ImplicitDefine); 13891 } 13892 13893 if (!Is64Bit) 13894 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg) 13895 .addImm(16); 13896 13897 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg) 13898 .addReg(Is64Bit ? X86::RAX : X86::EAX); 13899 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB); 13900 13901 // Set up the CFG correctly. 13902 BB->addSuccessor(bumpMBB); 13903 BB->addSuccessor(mallocMBB); 13904 mallocMBB->addSuccessor(continueMBB); 13905 bumpMBB->addSuccessor(continueMBB); 13906 13907 // Take care of the PHI nodes. 13908 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI), 13909 MI->getOperand(0).getReg()) 13910 .addReg(mallocPtrVReg).addMBB(mallocMBB) 13911 .addReg(bumpSPPtrVReg).addMBB(bumpMBB); 13912 13913 // Delete the original pseudo instruction. 13914 MI->eraseFromParent(); 13915 13916 // And we're done. 13917 return continueMBB; 13918} 13919 13920MachineBasicBlock * 13921X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI, 13922 MachineBasicBlock *BB) const { 13923 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 13924 DebugLoc DL = MI->getDebugLoc(); 13925 13926 assert(!Subtarget->isTargetEnvMacho()); 13927 13928 // The lowering is pretty easy: we're just emitting the call to _alloca. The 13929 // non-trivial part is impdef of ESP. 13930 13931 if (Subtarget->isTargetWin64()) { 13932 if (Subtarget->isTargetCygMing()) { 13933 // ___chkstk(Mingw64): 13934 // Clobbers R10, R11, RAX and EFLAGS. 13935 // Updates RSP. 13936 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 13937 .addExternalSymbol("___chkstk") 13938 .addReg(X86::RAX, RegState::Implicit) 13939 .addReg(X86::RSP, RegState::Implicit) 13940 .addReg(X86::RAX, RegState::Define | RegState::Implicit) 13941 .addReg(X86::RSP, RegState::Define | RegState::Implicit) 13942 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 13943 } else { 13944 // __chkstk(MSVCRT): does not update stack pointer. 13945 // Clobbers R10, R11 and EFLAGS. 13946 // FIXME: RAX(allocated size) might be reused and not killed. 13947 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA)) 13948 .addExternalSymbol("__chkstk") 13949 .addReg(X86::RAX, RegState::Implicit) 13950 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 13951 // RAX has the offset to subtracted from RSP. 13952 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP) 13953 .addReg(X86::RSP) 13954 .addReg(X86::RAX); 13955 } 13956 } else { 13957 const char *StackProbeSymbol = 13958 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca"; 13959 13960 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32)) 13961 .addExternalSymbol(StackProbeSymbol) 13962 .addReg(X86::EAX, RegState::Implicit) 13963 .addReg(X86::ESP, RegState::Implicit) 13964 .addReg(X86::EAX, RegState::Define | RegState::Implicit) 13965 .addReg(X86::ESP, RegState::Define | RegState::Implicit) 13966 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit); 13967 } 13968 13969 MI->eraseFromParent(); // The pseudo instruction is gone now. 13970 return BB; 13971} 13972 13973MachineBasicBlock * 13974X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI, 13975 MachineBasicBlock *BB) const { 13976 // This is pretty easy. We're taking the value that we received from 13977 // our load from the relocation, sticking it in either RDI (x86-64) 13978 // or EAX and doing an indirect call. The return value will then 13979 // be in the normal return register. 13980 const X86InstrInfo *TII 13981 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo()); 13982 DebugLoc DL = MI->getDebugLoc(); 13983 MachineFunction *F = BB->getParent(); 13984 13985 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?"); 13986 assert(MI->getOperand(3).isGlobal() && "This should be a global"); 13987 13988 // Get a register mask for the lowered call. 13989 // FIXME: The 32-bit calls have non-standard calling conventions. Use a 13990 // proper register mask. 13991 const uint32_t *RegMask = 13992 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C); 13993 if (Subtarget->is64Bit()) { 13994 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 13995 TII->get(X86::MOV64rm), X86::RDI) 13996 .addReg(X86::RIP) 13997 .addImm(0).addReg(0) 13998 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 13999 MI->getOperand(3).getTargetFlags()) 14000 .addReg(0); 14001 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m)); 14002 addDirectMem(MIB, X86::RDI); 14003 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask); 14004 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) { 14005 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14006 TII->get(X86::MOV32rm), X86::EAX) 14007 .addReg(0) 14008 .addImm(0).addReg(0) 14009 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14010 MI->getOperand(3).getTargetFlags()) 14011 .addReg(0); 14012 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14013 addDirectMem(MIB, X86::EAX); 14014 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14015 } else { 14016 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, 14017 TII->get(X86::MOV32rm), X86::EAX) 14018 .addReg(TII->getGlobalBaseReg(F)) 14019 .addImm(0).addReg(0) 14020 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0, 14021 MI->getOperand(3).getTargetFlags()) 14022 .addReg(0); 14023 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m)); 14024 addDirectMem(MIB, X86::EAX); 14025 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask); 14026 } 14027 14028 MI->eraseFromParent(); // The pseudo instruction is gone now. 14029 return BB; 14030} 14031 14032MachineBasicBlock * 14033X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, 14034 MachineBasicBlock *MBB) const { 14035 DebugLoc DL = MI->getDebugLoc(); 14036 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14037 14038 MachineFunction *MF = MBB->getParent(); 14039 MachineRegisterInfo &MRI = MF->getRegInfo(); 14040 14041 const BasicBlock *BB = MBB->getBasicBlock(); 14042 MachineFunction::iterator I = MBB; 14043 ++I; 14044 14045 // Memory Reference 14046 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14047 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14048 14049 unsigned DstReg; 14050 unsigned MemOpndSlot = 0; 14051 14052 unsigned CurOp = 0; 14053 14054 DstReg = MI->getOperand(CurOp++).getReg(); 14055 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 14056 assert(RC->hasType(MVT::i32) && "Invalid destination!"); 14057 unsigned mainDstReg = MRI.createVirtualRegister(RC); 14058 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 14059 14060 MemOpndSlot = CurOp; 14061 14062 MVT PVT = getPointerTy(); 14063 assert((PVT == MVT::i64 || PVT == MVT::i32) && 14064 "Invalid Pointer Size!"); 14065 14066 // For v = setjmp(buf), we generate 14067 // 14068 // thisMBB: 14069 // buf[LabelOffset] = restoreMBB 14070 // SjLjSetup restoreMBB 14071 // 14072 // mainMBB: 14073 // v_main = 0 14074 // 14075 // sinkMBB: 14076 // v = phi(main, restore) 14077 // 14078 // restoreMBB: 14079 // v_restore = 1 14080 14081 MachineBasicBlock *thisMBB = MBB; 14082 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 14083 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 14084 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB); 14085 MF->insert(I, mainMBB); 14086 MF->insert(I, sinkMBB); 14087 MF->push_back(restoreMBB); 14088 14089 MachineInstrBuilder MIB; 14090 14091 // Transfer the remainder of BB and its successor edges to sinkMBB. 14092 sinkMBB->splice(sinkMBB->begin(), MBB, 14093 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end()); 14094 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 14095 14096 // thisMBB: 14097 unsigned PtrStoreOpc = 0; 14098 unsigned LabelReg = 0; 14099 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 14100 Reloc::Model RM = getTargetMachine().getRelocationModel(); 14101 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) && 14102 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC); 14103 14104 // Prepare IP either in reg or imm. 14105 if (!UseImmLabel) { 14106 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr; 14107 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 14108 LabelReg = MRI.createVirtualRegister(PtrRC); 14109 if (Subtarget->is64Bit()) { 14110 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg) 14111 .addReg(X86::RIP) 14112 .addImm(0) 14113 .addReg(0) 14114 .addMBB(restoreMBB) 14115 .addReg(0); 14116 } else { 14117 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII); 14118 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg) 14119 .addReg(XII->getGlobalBaseReg(MF)) 14120 .addImm(0) 14121 .addReg(0) 14122 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference()) 14123 .addReg(0); 14124 } 14125 } else 14126 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi; 14127 // Store IP 14128 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc)); 14129 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14130 if (i == X86::AddrDisp) 14131 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset); 14132 else 14133 MIB.addOperand(MI->getOperand(MemOpndSlot + i)); 14134 } 14135 if (!UseImmLabel) 14136 MIB.addReg(LabelReg); 14137 else 14138 MIB.addMBB(restoreMBB); 14139 MIB.setMemRefs(MMOBegin, MMOEnd); 14140 // Setup 14141 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup)) 14142 .addMBB(restoreMBB); 14143 MIB.addRegMask(RegInfo->getNoPreservedMask()); 14144 thisMBB->addSuccessor(mainMBB); 14145 thisMBB->addSuccessor(restoreMBB); 14146 14147 // mainMBB: 14148 // EAX = 0 14149 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg); 14150 mainMBB->addSuccessor(sinkMBB); 14151 14152 // sinkMBB: 14153 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 14154 TII->get(X86::PHI), DstReg) 14155 .addReg(mainDstReg).addMBB(mainMBB) 14156 .addReg(restoreDstReg).addMBB(restoreMBB); 14157 14158 // restoreMBB: 14159 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1); 14160 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB); 14161 restoreMBB->addSuccessor(sinkMBB); 14162 14163 MI->eraseFromParent(); 14164 return sinkMBB; 14165} 14166 14167MachineBasicBlock * 14168X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, 14169 MachineBasicBlock *MBB) const { 14170 DebugLoc DL = MI->getDebugLoc(); 14171 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14172 14173 MachineFunction *MF = MBB->getParent(); 14174 MachineRegisterInfo &MRI = MF->getRegInfo(); 14175 14176 // Memory Reference 14177 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); 14178 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); 14179 14180 MVT PVT = getPointerTy(); 14181 assert((PVT == MVT::i64 || PVT == MVT::i32) && 14182 "Invalid Pointer Size!"); 14183 14184 const TargetRegisterClass *RC = 14185 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass; 14186 unsigned Tmp = MRI.createVirtualRegister(RC); 14187 // Since FP is only updated here but NOT referenced, it's treated as GPR. 14188 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP; 14189 unsigned SP = RegInfo->getStackRegister(); 14190 14191 MachineInstrBuilder MIB; 14192 14193 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 14194 const int64_t SPOffset = 2 * PVT.getStoreSize(); 14195 14196 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm; 14197 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r; 14198 14199 // Reload FP 14200 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP); 14201 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) 14202 MIB.addOperand(MI->getOperand(i)); 14203 MIB.setMemRefs(MMOBegin, MMOEnd); 14204 // Reload IP 14205 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp); 14206 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14207 if (i == X86::AddrDisp) 14208 MIB.addDisp(MI->getOperand(i), LabelOffset); 14209 else 14210 MIB.addOperand(MI->getOperand(i)); 14211 } 14212 MIB.setMemRefs(MMOBegin, MMOEnd); 14213 // Reload SP 14214 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP); 14215 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) { 14216 if (i == X86::AddrDisp) 14217 MIB.addDisp(MI->getOperand(i), SPOffset); 14218 else 14219 MIB.addOperand(MI->getOperand(i)); 14220 } 14221 MIB.setMemRefs(MMOBegin, MMOEnd); 14222 // Jump 14223 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp); 14224 14225 MI->eraseFromParent(); 14226 return MBB; 14227} 14228 14229MachineBasicBlock * 14230X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, 14231 MachineBasicBlock *BB) const { 14232 switch (MI->getOpcode()) { 14233 default: llvm_unreachable("Unexpected instr type to insert"); 14234 case X86::TAILJMPd64: 14235 case X86::TAILJMPr64: 14236 case X86::TAILJMPm64: 14237 llvm_unreachable("TAILJMP64 would not be touched here."); 14238 case X86::TCRETURNdi64: 14239 case X86::TCRETURNri64: 14240 case X86::TCRETURNmi64: 14241 return BB; 14242 case X86::WIN_ALLOCA: 14243 return EmitLoweredWinAlloca(MI, BB); 14244 case X86::SEG_ALLOCA_32: 14245 return EmitLoweredSegAlloca(MI, BB, false); 14246 case X86::SEG_ALLOCA_64: 14247 return EmitLoweredSegAlloca(MI, BB, true); 14248 case X86::TLSCall_32: 14249 case X86::TLSCall_64: 14250 return EmitLoweredTLSCall(MI, BB); 14251 case X86::CMOV_GR8: 14252 case X86::CMOV_FR32: 14253 case X86::CMOV_FR64: 14254 case X86::CMOV_V4F32: 14255 case X86::CMOV_V2F64: 14256 case X86::CMOV_V2I64: 14257 case X86::CMOV_V8F32: 14258 case X86::CMOV_V4F64: 14259 case X86::CMOV_V4I64: 14260 case X86::CMOV_GR16: 14261 case X86::CMOV_GR32: 14262 case X86::CMOV_RFP32: 14263 case X86::CMOV_RFP64: 14264 case X86::CMOV_RFP80: 14265 return EmitLoweredSelect(MI, BB); 14266 14267 case X86::FP32_TO_INT16_IN_MEM: 14268 case X86::FP32_TO_INT32_IN_MEM: 14269 case X86::FP32_TO_INT64_IN_MEM: 14270 case X86::FP64_TO_INT16_IN_MEM: 14271 case X86::FP64_TO_INT32_IN_MEM: 14272 case X86::FP64_TO_INT64_IN_MEM: 14273 case X86::FP80_TO_INT16_IN_MEM: 14274 case X86::FP80_TO_INT32_IN_MEM: 14275 case X86::FP80_TO_INT64_IN_MEM: { 14276 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo(); 14277 DebugLoc DL = MI->getDebugLoc(); 14278 14279 // Change the floating point control register to use "round towards zero" 14280 // mode when truncating to an integer value. 14281 MachineFunction *F = BB->getParent(); 14282 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false); 14283 addFrameReference(BuildMI(*BB, MI, DL, 14284 TII->get(X86::FNSTCW16m)), CWFrameIdx); 14285 14286 // Load the old value of the high byte of the control word... 14287 unsigned OldCW = 14288 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass); 14289 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW), 14290 CWFrameIdx); 14291 14292 // Set the high part to be round to zero... 14293 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx) 14294 .addImm(0xC7F); 14295 14296 // Reload the modified control word now... 14297 addFrameReference(BuildMI(*BB, MI, DL, 14298 TII->get(X86::FLDCW16m)), CWFrameIdx); 14299 14300 // Restore the memory image of control word to original value 14301 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx) 14302 .addReg(OldCW); 14303 14304 // Get the X86 opcode to use. 14305 unsigned Opc; 14306 switch (MI->getOpcode()) { 14307 default: llvm_unreachable("illegal opcode!"); 14308 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break; 14309 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break; 14310 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break; 14311 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break; 14312 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break; 14313 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break; 14314 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break; 14315 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break; 14316 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break; 14317 } 14318 14319 X86AddressMode AM; 14320 MachineOperand &Op = MI->getOperand(0); 14321 if (Op.isReg()) { 14322 AM.BaseType = X86AddressMode::RegBase; 14323 AM.Base.Reg = Op.getReg(); 14324 } else { 14325 AM.BaseType = X86AddressMode::FrameIndexBase; 14326 AM.Base.FrameIndex = Op.getIndex(); 14327 } 14328 Op = MI->getOperand(1); 14329 if (Op.isImm()) 14330 AM.Scale = Op.getImm(); 14331 Op = MI->getOperand(2); 14332 if (Op.isImm()) 14333 AM.IndexReg = Op.getImm(); 14334 Op = MI->getOperand(3); 14335 if (Op.isGlobal()) { 14336 AM.GV = Op.getGlobal(); 14337 } else { 14338 AM.Disp = Op.getImm(); 14339 } 14340 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM) 14341 .addReg(MI->getOperand(X86::AddrNumOperands).getReg()); 14342 14343 // Reload the original control word now. 14344 addFrameReference(BuildMI(*BB, MI, DL, 14345 TII->get(X86::FLDCW16m)), CWFrameIdx); 14346 14347 MI->eraseFromParent(); // The pseudo instruction is gone now. 14348 return BB; 14349 } 14350 // String/text processing lowering. 14351 case X86::PCMPISTRM128REG: 14352 case X86::VPCMPISTRM128REG: 14353 case X86::PCMPISTRM128MEM: 14354 case X86::VPCMPISTRM128MEM: 14355 case X86::PCMPESTRM128REG: 14356 case X86::VPCMPESTRM128REG: 14357 case X86::PCMPESTRM128MEM: 14358 case X86::VPCMPESTRM128MEM: 14359 assert(Subtarget->hasSSE42() && 14360 "Target must have SSE4.2 or AVX features enabled"); 14361 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo()); 14362 14363 // String/text processing lowering. 14364 case X86::PCMPISTRIREG: 14365 case X86::VPCMPISTRIREG: 14366 case X86::PCMPISTRIMEM: 14367 case X86::VPCMPISTRIMEM: 14368 case X86::PCMPESTRIREG: 14369 case X86::VPCMPESTRIREG: 14370 case X86::PCMPESTRIMEM: 14371 case X86::VPCMPESTRIMEM: 14372 assert(Subtarget->hasSSE42() && 14373 "Target must have SSE4.2 or AVX features enabled"); 14374 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo()); 14375 14376 // Thread synchronization. 14377 case X86::MONITOR: 14378 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget); 14379 14380 // xbegin 14381 case X86::XBEGIN: 14382 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo()); 14383 14384 // Atomic Lowering. 14385 case X86::ATOMAND8: 14386 case X86::ATOMAND16: 14387 case X86::ATOMAND32: 14388 case X86::ATOMAND64: 14389 // Fall through 14390 case X86::ATOMOR8: 14391 case X86::ATOMOR16: 14392 case X86::ATOMOR32: 14393 case X86::ATOMOR64: 14394 // Fall through 14395 case X86::ATOMXOR16: 14396 case X86::ATOMXOR8: 14397 case X86::ATOMXOR32: 14398 case X86::ATOMXOR64: 14399 // Fall through 14400 case X86::ATOMNAND8: 14401 case X86::ATOMNAND16: 14402 case X86::ATOMNAND32: 14403 case X86::ATOMNAND64: 14404 // Fall through 14405 case X86::ATOMMAX8: 14406 case X86::ATOMMAX16: 14407 case X86::ATOMMAX32: 14408 case X86::ATOMMAX64: 14409 // Fall through 14410 case X86::ATOMMIN8: 14411 case X86::ATOMMIN16: 14412 case X86::ATOMMIN32: 14413 case X86::ATOMMIN64: 14414 // Fall through 14415 case X86::ATOMUMAX8: 14416 case X86::ATOMUMAX16: 14417 case X86::ATOMUMAX32: 14418 case X86::ATOMUMAX64: 14419 // Fall through 14420 case X86::ATOMUMIN8: 14421 case X86::ATOMUMIN16: 14422 case X86::ATOMUMIN32: 14423 case X86::ATOMUMIN64: 14424 return EmitAtomicLoadArith(MI, BB); 14425 14426 // This group does 64-bit operations on a 32-bit host. 14427 case X86::ATOMAND6432: 14428 case X86::ATOMOR6432: 14429 case X86::ATOMXOR6432: 14430 case X86::ATOMNAND6432: 14431 case X86::ATOMADD6432: 14432 case X86::ATOMSUB6432: 14433 case X86::ATOMMAX6432: 14434 case X86::ATOMMIN6432: 14435 case X86::ATOMUMAX6432: 14436 case X86::ATOMUMIN6432: 14437 case X86::ATOMSWAP6432: 14438 return EmitAtomicLoadArith6432(MI, BB); 14439 14440 case X86::VASTART_SAVE_XMM_REGS: 14441 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB); 14442 14443 case X86::VAARG_64: 14444 return EmitVAARG64WithCustomInserter(MI, BB); 14445 14446 case X86::EH_SjLj_SetJmp32: 14447 case X86::EH_SjLj_SetJmp64: 14448 return emitEHSjLjSetJmp(MI, BB); 14449 14450 case X86::EH_SjLj_LongJmp32: 14451 case X86::EH_SjLj_LongJmp64: 14452 return emitEHSjLjLongJmp(MI, BB); 14453 } 14454} 14455 14456//===----------------------------------------------------------------------===// 14457// X86 Optimization Hooks 14458//===----------------------------------------------------------------------===// 14459 14460void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 14461 APInt &KnownZero, 14462 APInt &KnownOne, 14463 const SelectionDAG &DAG, 14464 unsigned Depth) const { 14465 unsigned BitWidth = KnownZero.getBitWidth(); 14466 unsigned Opc = Op.getOpcode(); 14467 assert((Opc >= ISD::BUILTIN_OP_END || 14468 Opc == ISD::INTRINSIC_WO_CHAIN || 14469 Opc == ISD::INTRINSIC_W_CHAIN || 14470 Opc == ISD::INTRINSIC_VOID) && 14471 "Should use MaskedValueIsZero if you don't know whether Op" 14472 " is a target node!"); 14473 14474 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 14475 switch (Opc) { 14476 default: break; 14477 case X86ISD::ADD: 14478 case X86ISD::SUB: 14479 case X86ISD::ADC: 14480 case X86ISD::SBB: 14481 case X86ISD::SMUL: 14482 case X86ISD::UMUL: 14483 case X86ISD::INC: 14484 case X86ISD::DEC: 14485 case X86ISD::OR: 14486 case X86ISD::XOR: 14487 case X86ISD::AND: 14488 // These nodes' second result is a boolean. 14489 if (Op.getResNo() == 0) 14490 break; 14491 // Fallthrough 14492 case X86ISD::SETCC: 14493 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 14494 break; 14495 case ISD::INTRINSIC_WO_CHAIN: { 14496 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14497 unsigned NumLoBits = 0; 14498 switch (IntId) { 14499 default: break; 14500 case Intrinsic::x86_sse_movmsk_ps: 14501 case Intrinsic::x86_avx_movmsk_ps_256: 14502 case Intrinsic::x86_sse2_movmsk_pd: 14503 case Intrinsic::x86_avx_movmsk_pd_256: 14504 case Intrinsic::x86_mmx_pmovmskb: 14505 case Intrinsic::x86_sse2_pmovmskb_128: 14506 case Intrinsic::x86_avx2_pmovmskb: { 14507 // High bits of movmskp{s|d}, pmovmskb are known zero. 14508 switch (IntId) { 14509 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 14510 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break; 14511 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break; 14512 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break; 14513 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break; 14514 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break; 14515 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break; 14516 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break; 14517 } 14518 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits); 14519 break; 14520 } 14521 } 14522 break; 14523 } 14524 } 14525} 14526 14527unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 14528 unsigned Depth) const { 14529 // SETCC_CARRY sets the dest to ~0 for true or 0 for false. 14530 if (Op.getOpcode() == X86ISD::SETCC_CARRY) 14531 return Op.getValueType().getScalarType().getSizeInBits(); 14532 14533 // Fallback case. 14534 return 1; 14535} 14536 14537/// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 14538/// node is a GlobalAddress + offset. 14539bool X86TargetLowering::isGAPlusOffset(SDNode *N, 14540 const GlobalValue* &GA, 14541 int64_t &Offset) const { 14542 if (N->getOpcode() == X86ISD::Wrapper) { 14543 if (isa<GlobalAddressSDNode>(N->getOperand(0))) { 14544 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal(); 14545 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset(); 14546 return true; 14547 } 14548 } 14549 return TargetLowering::isGAPlusOffset(N, GA, Offset); 14550} 14551 14552/// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the 14553/// same as extracting the high 128-bit part of 256-bit vector and then 14554/// inserting the result into the low part of a new 256-bit vector 14555static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) { 14556 EVT VT = SVOp->getValueType(0); 14557 unsigned NumElems = VT.getVectorNumElements(); 14558 14559 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 14560 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j) 14561 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 14562 SVOp->getMaskElt(j) >= 0) 14563 return false; 14564 14565 return true; 14566} 14567 14568/// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the 14569/// same as extracting the low 128-bit part of 256-bit vector and then 14570/// inserting the result into the high part of a new 256-bit vector 14571static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) { 14572 EVT VT = SVOp->getValueType(0); 14573 unsigned NumElems = VT.getVectorNumElements(); 14574 14575 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 14576 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j) 14577 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) || 14578 SVOp->getMaskElt(j) >= 0) 14579 return false; 14580 14581 return true; 14582} 14583 14584/// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors. 14585static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG, 14586 TargetLowering::DAGCombinerInfo &DCI, 14587 const X86Subtarget* Subtarget) { 14588 DebugLoc dl = N->getDebugLoc(); 14589 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 14590 SDValue V1 = SVOp->getOperand(0); 14591 SDValue V2 = SVOp->getOperand(1); 14592 EVT VT = SVOp->getValueType(0); 14593 unsigned NumElems = VT.getVectorNumElements(); 14594 14595 if (V1.getOpcode() == ISD::CONCAT_VECTORS && 14596 V2.getOpcode() == ISD::CONCAT_VECTORS) { 14597 // 14598 // 0,0,0,... 14599 // | 14600 // V UNDEF BUILD_VECTOR UNDEF 14601 // \ / \ / 14602 // CONCAT_VECTOR CONCAT_VECTOR 14603 // \ / 14604 // \ / 14605 // RESULT: V + zero extended 14606 // 14607 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR || 14608 V2.getOperand(1).getOpcode() != ISD::UNDEF || 14609 V1.getOperand(1).getOpcode() != ISD::UNDEF) 14610 return SDValue(); 14611 14612 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode())) 14613 return SDValue(); 14614 14615 // To match the shuffle mask, the first half of the mask should 14616 // be exactly the first vector, and all the rest a splat with the 14617 // first element of the second one. 14618 for (unsigned i = 0; i != NumElems/2; ++i) 14619 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) || 14620 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems)) 14621 return SDValue(); 14622 14623 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD. 14624 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) { 14625 if (Ld->hasNUsesOfValue(1, 0)) { 14626 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other); 14627 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() }; 14628 SDValue ResNode = 14629 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2, 14630 Ld->getMemoryVT(), 14631 Ld->getPointerInfo(), 14632 Ld->getAlignment(), 14633 false/*isVolatile*/, true/*ReadMem*/, 14634 false/*WriteMem*/); 14635 14636 // Make sure the newly-created LOAD is in the same position as Ld in 14637 // terms of dependency. We create a TokenFactor for Ld and ResNode, 14638 // and update uses of Ld's output chain to use the TokenFactor. 14639 if (Ld->hasAnyUseOfValue(1)) { 14640 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14641 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1)); 14642 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain); 14643 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1), 14644 SDValue(ResNode.getNode(), 1)); 14645 } 14646 14647 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode); 14648 } 14649 } 14650 14651 // Emit a zeroed vector and insert the desired subvector on its 14652 // first half. 14653 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl); 14654 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl); 14655 return DCI.CombineTo(N, InsV); 14656 } 14657 14658 //===--------------------------------------------------------------------===// 14659 // Combine some shuffles into subvector extracts and inserts: 14660 // 14661 14662 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u> 14663 if (isShuffleHigh128VectorInsertLow(SVOp)) { 14664 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl); 14665 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl); 14666 return DCI.CombineTo(N, InsV); 14667 } 14668 14669 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1> 14670 if (isShuffleLow128VectorInsertHigh(SVOp)) { 14671 SDValue V = Extract128BitVector(V1, 0, DAG, dl); 14672 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl); 14673 return DCI.CombineTo(N, InsV); 14674 } 14675 14676 return SDValue(); 14677} 14678 14679/// PerformShuffleCombine - Performs several different shuffle combines. 14680static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG, 14681 TargetLowering::DAGCombinerInfo &DCI, 14682 const X86Subtarget *Subtarget) { 14683 DebugLoc dl = N->getDebugLoc(); 14684 EVT VT = N->getValueType(0); 14685 14686 // Don't create instructions with illegal types after legalize types has run. 14687 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14688 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType())) 14689 return SDValue(); 14690 14691 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode 14692 if (Subtarget->hasFp256() && VT.is256BitVector() && 14693 N->getOpcode() == ISD::VECTOR_SHUFFLE) 14694 return PerformShuffleCombine256(N, DAG, DCI, Subtarget); 14695 14696 // Only handle 128 wide vector from here on. 14697 if (!VT.is128BitVector()) 14698 return SDValue(); 14699 14700 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3, 14701 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are 14702 // consecutive, non-overlapping, and in the right order. 14703 SmallVector<SDValue, 16> Elts; 14704 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 14705 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0)); 14706 14707 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG); 14708} 14709 14710/// PerformTruncateCombine - Converts truncate operation to 14711/// a sequence of vector shuffle operations. 14712/// It is possible when we truncate 256-bit vector to 128-bit vector 14713static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 14714 TargetLowering::DAGCombinerInfo &DCI, 14715 const X86Subtarget *Subtarget) { 14716 return SDValue(); 14717} 14718 14719/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target 14720/// specific shuffle of a load can be folded into a single element load. 14721/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but 14722/// shuffles have been customed lowered so we need to handle those here. 14723static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG, 14724 TargetLowering::DAGCombinerInfo &DCI) { 14725 if (DCI.isBeforeLegalizeOps()) 14726 return SDValue(); 14727 14728 SDValue InVec = N->getOperand(0); 14729 SDValue EltNo = N->getOperand(1); 14730 14731 if (!isa<ConstantSDNode>(EltNo)) 14732 return SDValue(); 14733 14734 EVT VT = InVec.getValueType(); 14735 14736 bool HasShuffleIntoBitcast = false; 14737 if (InVec.getOpcode() == ISD::BITCAST) { 14738 // Don't duplicate a load with other uses. 14739 if (!InVec.hasOneUse()) 14740 return SDValue(); 14741 EVT BCVT = InVec.getOperand(0).getValueType(); 14742 if (BCVT.getVectorNumElements() != VT.getVectorNumElements()) 14743 return SDValue(); 14744 InVec = InVec.getOperand(0); 14745 HasShuffleIntoBitcast = true; 14746 } 14747 14748 if (!isTargetShuffle(InVec.getOpcode())) 14749 return SDValue(); 14750 14751 // Don't duplicate a load with other uses. 14752 if (!InVec.hasOneUse()) 14753 return SDValue(); 14754 14755 SmallVector<int, 16> ShuffleMask; 14756 bool UnaryShuffle; 14757 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask, 14758 UnaryShuffle)) 14759 return SDValue(); 14760 14761 // Select the input vector, guarding against out of range extract vector. 14762 unsigned NumElems = VT.getVectorNumElements(); 14763 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 14764 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt]; 14765 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0) 14766 : InVec.getOperand(1); 14767 14768 // If inputs to shuffle are the same for both ops, then allow 2 uses 14769 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1; 14770 14771 if (LdNode.getOpcode() == ISD::BITCAST) { 14772 // Don't duplicate a load with other uses. 14773 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0)) 14774 return SDValue(); 14775 14776 AllowedUses = 1; // only allow 1 load use if we have a bitcast 14777 LdNode = LdNode.getOperand(0); 14778 } 14779 14780 if (!ISD::isNormalLoad(LdNode.getNode())) 14781 return SDValue(); 14782 14783 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode); 14784 14785 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile()) 14786 return SDValue(); 14787 14788 if (HasShuffleIntoBitcast) { 14789 // If there's a bitcast before the shuffle, check if the load type and 14790 // alignment is valid. 14791 unsigned Align = LN0->getAlignment(); 14792 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14793 unsigned NewAlign = TLI.getDataLayout()-> 14794 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 14795 14796 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT)) 14797 return SDValue(); 14798 } 14799 14800 // All checks match so transform back to vector_shuffle so that DAG combiner 14801 // can finish the job 14802 DebugLoc dl = N->getDebugLoc(); 14803 14804 // Create shuffle node taking into account the case that its a unary shuffle 14805 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1); 14806 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl, 14807 InVec.getOperand(0), Shuffle, 14808 &ShuffleMask[0]); 14809 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 14810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle, 14811 EltNo); 14812} 14813 14814/// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index 14815/// generation and convert it from being a bunch of shuffles and extracts 14816/// to a simple store and scalar loads to extract the elements. 14817static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG, 14818 TargetLowering::DAGCombinerInfo &DCI) { 14819 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI); 14820 if (NewOp.getNode()) 14821 return NewOp; 14822 14823 SDValue InputVector = N->getOperand(0); 14824 // Detect whether we are trying to convert from mmx to i32 and the bitcast 14825 // from mmx to v2i32 has a single usage. 14826 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST && 14827 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx && 14828 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32) 14829 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(), 14830 N->getValueType(0), 14831 InputVector.getNode()->getOperand(0)); 14832 14833 // Only operate on vectors of 4 elements, where the alternative shuffling 14834 // gets to be more expensive. 14835 if (InputVector.getValueType() != MVT::v4i32) 14836 return SDValue(); 14837 14838 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a 14839 // single use which is a sign-extend or zero-extend, and all elements are 14840 // used. 14841 SmallVector<SDNode *, 4> Uses; 14842 unsigned ExtractedElements = 0; 14843 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(), 14844 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) { 14845 if (UI.getUse().getResNo() != InputVector.getResNo()) 14846 return SDValue(); 14847 14848 SDNode *Extract = *UI; 14849 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14850 return SDValue(); 14851 14852 if (Extract->getValueType(0) != MVT::i32) 14853 return SDValue(); 14854 if (!Extract->hasOneUse()) 14855 return SDValue(); 14856 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND && 14857 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND) 14858 return SDValue(); 14859 if (!isa<ConstantSDNode>(Extract->getOperand(1))) 14860 return SDValue(); 14861 14862 // Record which element was extracted. 14863 ExtractedElements |= 14864 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue(); 14865 14866 Uses.push_back(Extract); 14867 } 14868 14869 // If not all the elements were used, this may not be worthwhile. 14870 if (ExtractedElements != 15) 14871 return SDValue(); 14872 14873 // Ok, we've now decided to do the transformation. 14874 DebugLoc dl = InputVector.getDebugLoc(); 14875 14876 // Store the value to a temporary stack slot. 14877 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType()); 14878 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, 14879 MachinePointerInfo(), false, false, 0); 14880 14881 // Replace each use (extract) with a load of the appropriate element. 14882 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(), 14883 UE = Uses.end(); UI != UE; ++UI) { 14884 SDNode *Extract = *UI; 14885 14886 // cOMpute the element's address. 14887 SDValue Idx = Extract->getOperand(1); 14888 unsigned EltSize = 14889 InputVector.getValueType().getVectorElementType().getSizeInBits()/8; 14890 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(); 14891 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14892 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy()); 14893 14894 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), 14895 StackPtr, OffsetVal); 14896 14897 // Load the scalar. 14898 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, 14899 ScalarAddr, MachinePointerInfo(), 14900 false, false, false, 0); 14901 14902 // Replace the exact with the load. 14903 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar); 14904 } 14905 14906 // The replacement was made in place; don't return anything. 14907 return SDValue(); 14908} 14909 14910/// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match. 14911static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, 14912 SDValue RHS, SelectionDAG &DAG, 14913 const X86Subtarget *Subtarget) { 14914 if (!VT.isVector()) 14915 return 0; 14916 14917 switch (VT.getSimpleVT().SimpleTy) { 14918 default: return 0; 14919 case MVT::v32i8: 14920 case MVT::v16i16: 14921 case MVT::v8i32: 14922 if (!Subtarget->hasAVX2()) 14923 return 0; 14924 case MVT::v16i8: 14925 case MVT::v8i16: 14926 case MVT::v4i32: 14927 if (!Subtarget->hasSSE2()) 14928 return 0; 14929 } 14930 14931 // SSE2 has only a small subset of the operations. 14932 bool hasUnsigned = Subtarget->hasSSE41() || 14933 (Subtarget->hasSSE2() && VT == MVT::v16i8); 14934 bool hasSigned = Subtarget->hasSSE41() || 14935 (Subtarget->hasSSE2() && VT == MVT::v8i16); 14936 14937 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14938 14939 // Check for x CC y ? x : y. 14940 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 14941 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 14942 switch (CC) { 14943 default: break; 14944 case ISD::SETULT: 14945 case ISD::SETULE: 14946 return hasUnsigned ? X86ISD::UMIN : 0; 14947 case ISD::SETUGT: 14948 case ISD::SETUGE: 14949 return hasUnsigned ? X86ISD::UMAX : 0; 14950 case ISD::SETLT: 14951 case ISD::SETLE: 14952 return hasSigned ? X86ISD::SMIN : 0; 14953 case ISD::SETGT: 14954 case ISD::SETGE: 14955 return hasSigned ? X86ISD::SMAX : 0; 14956 } 14957 // Check for x CC y ? y : x -- a min/max with reversed arms. 14958 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 14959 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 14960 switch (CC) { 14961 default: break; 14962 case ISD::SETULT: 14963 case ISD::SETULE: 14964 return hasUnsigned ? X86ISD::UMAX : 0; 14965 case ISD::SETUGT: 14966 case ISD::SETUGE: 14967 return hasUnsigned ? X86ISD::UMIN : 0; 14968 case ISD::SETLT: 14969 case ISD::SETLE: 14970 return hasSigned ? X86ISD::SMAX : 0; 14971 case ISD::SETGT: 14972 case ISD::SETGE: 14973 return hasSigned ? X86ISD::SMIN : 0; 14974 } 14975 } 14976 14977 return 0; 14978} 14979 14980/// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT 14981/// nodes. 14982static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG, 14983 TargetLowering::DAGCombinerInfo &DCI, 14984 const X86Subtarget *Subtarget) { 14985 DebugLoc DL = N->getDebugLoc(); 14986 SDValue Cond = N->getOperand(0); 14987 // Get the LHS/RHS of the select. 14988 SDValue LHS = N->getOperand(1); 14989 SDValue RHS = N->getOperand(2); 14990 EVT VT = LHS.getValueType(); 14991 14992 // If we have SSE[12] support, try to form min/max nodes. SSE min/max 14993 // instructions match the semantics of the common C idiom x<y?x:y but not 14994 // x<=y?x:y, because of how they handle negative zero (which can be 14995 // ignored in unsafe-math mode). 14996 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() && 14997 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) && 14998 (Subtarget->hasSSE2() || 14999 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) { 15000 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15001 15002 unsigned Opcode = 0; 15003 // Check for x CC y ? x : y. 15004 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15005 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15006 switch (CC) { 15007 default: break; 15008 case ISD::SETULT: 15009 // Converting this to a min would handle NaNs incorrectly, and swapping 15010 // the operands would cause it to handle comparisons between positive 15011 // and negative zero incorrectly. 15012 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15013 if (!DAG.getTarget().Options.UnsafeFPMath && 15014 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15015 break; 15016 std::swap(LHS, RHS); 15017 } 15018 Opcode = X86ISD::FMIN; 15019 break; 15020 case ISD::SETOLE: 15021 // Converting this to a min would handle comparisons between positive 15022 // and negative zero incorrectly. 15023 if (!DAG.getTarget().Options.UnsafeFPMath && 15024 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15025 break; 15026 Opcode = X86ISD::FMIN; 15027 break; 15028 case ISD::SETULE: 15029 // Converting this to a min would handle both negative zeros and NaNs 15030 // incorrectly, but we can swap the operands to fix both. 15031 std::swap(LHS, RHS); 15032 case ISD::SETOLT: 15033 case ISD::SETLT: 15034 case ISD::SETLE: 15035 Opcode = X86ISD::FMIN; 15036 break; 15037 15038 case ISD::SETOGE: 15039 // Converting this to a max would handle comparisons between positive 15040 // and negative zero incorrectly. 15041 if (!DAG.getTarget().Options.UnsafeFPMath && 15042 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) 15043 break; 15044 Opcode = X86ISD::FMAX; 15045 break; 15046 case ISD::SETUGT: 15047 // Converting this to a max would handle NaNs incorrectly, and swapping 15048 // the operands would cause it to handle comparisons between positive 15049 // and negative zero incorrectly. 15050 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) { 15051 if (!DAG.getTarget().Options.UnsafeFPMath && 15052 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) 15053 break; 15054 std::swap(LHS, RHS); 15055 } 15056 Opcode = X86ISD::FMAX; 15057 break; 15058 case ISD::SETUGE: 15059 // Converting this to a max would handle both negative zeros and NaNs 15060 // incorrectly, but we can swap the operands to fix both. 15061 std::swap(LHS, RHS); 15062 case ISD::SETOGT: 15063 case ISD::SETGT: 15064 case ISD::SETGE: 15065 Opcode = X86ISD::FMAX; 15066 break; 15067 } 15068 // Check for x CC y ? y : x -- a min/max with reversed arms. 15069 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) && 15070 DAG.isEqualTo(RHS, Cond.getOperand(0))) { 15071 switch (CC) { 15072 default: break; 15073 case ISD::SETOGE: 15074 // Converting this to a min would handle comparisons between positive 15075 // and negative zero incorrectly, and swapping the operands would 15076 // cause it to handle NaNs incorrectly. 15077 if (!DAG.getTarget().Options.UnsafeFPMath && 15078 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) { 15079 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15080 break; 15081 std::swap(LHS, RHS); 15082 } 15083 Opcode = X86ISD::FMIN; 15084 break; 15085 case ISD::SETUGT: 15086 // Converting this to a min would handle NaNs incorrectly. 15087 if (!DAG.getTarget().Options.UnsafeFPMath && 15088 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) 15089 break; 15090 Opcode = X86ISD::FMIN; 15091 break; 15092 case ISD::SETUGE: 15093 // Converting this to a min would handle both negative zeros and NaNs 15094 // incorrectly, but we can swap the operands to fix both. 15095 std::swap(LHS, RHS); 15096 case ISD::SETOGT: 15097 case ISD::SETGT: 15098 case ISD::SETGE: 15099 Opcode = X86ISD::FMIN; 15100 break; 15101 15102 case ISD::SETULT: 15103 // Converting this to a max would handle NaNs incorrectly. 15104 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15105 break; 15106 Opcode = X86ISD::FMAX; 15107 break; 15108 case ISD::SETOLE: 15109 // Converting this to a max would handle comparisons between positive 15110 // and negative zero incorrectly, and swapping the operands would 15111 // cause it to handle NaNs incorrectly. 15112 if (!DAG.getTarget().Options.UnsafeFPMath && 15113 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) { 15114 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) 15115 break; 15116 std::swap(LHS, RHS); 15117 } 15118 Opcode = X86ISD::FMAX; 15119 break; 15120 case ISD::SETULE: 15121 // Converting this to a max would handle both negative zeros and NaNs 15122 // incorrectly, but we can swap the operands to fix both. 15123 std::swap(LHS, RHS); 15124 case ISD::SETOLT: 15125 case ISD::SETLT: 15126 case ISD::SETLE: 15127 Opcode = X86ISD::FMAX; 15128 break; 15129 } 15130 } 15131 15132 if (Opcode) 15133 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS); 15134 } 15135 15136 // If this is a select between two integer constants, try to do some 15137 // optimizations. 15138 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) { 15139 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS)) 15140 // Don't do this for crazy integer types. 15141 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) { 15142 // If this is efficiently invertible, canonicalize the LHSC/RHSC values 15143 // so that TrueC (the true value) is larger than FalseC. 15144 bool NeedsCondInvert = false; 15145 15146 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) && 15147 // Efficiently invertible. 15148 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible. 15149 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible. 15150 isa<ConstantSDNode>(Cond.getOperand(1))))) { 15151 NeedsCondInvert = true; 15152 std::swap(TrueC, FalseC); 15153 } 15154 15155 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0. 15156 if (FalseC->getAPIntValue() == 0 && 15157 TrueC->getAPIntValue().isPowerOf2()) { 15158 if (NeedsCondInvert) // Invert the condition if needed. 15159 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15160 DAG.getConstant(1, Cond.getValueType())); 15161 15162 // Zero extend the condition if needed. 15163 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond); 15164 15165 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 15166 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond, 15167 DAG.getConstant(ShAmt, MVT::i8)); 15168 } 15169 15170 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. 15171 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 15172 if (NeedsCondInvert) // Invert the condition if needed. 15173 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15174 DAG.getConstant(1, Cond.getValueType())); 15175 15176 // Zero extend the condition if needed. 15177 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 15178 FalseC->getValueType(0), Cond); 15179 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15180 SDValue(FalseC, 0)); 15181 } 15182 15183 // Optimize cases that will turn into an LEA instruction. This requires 15184 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 15185 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 15186 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 15187 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 15188 15189 bool isFastMultiplier = false; 15190 if (Diff < 10) { 15191 switch ((unsigned char)Diff) { 15192 default: break; 15193 case 1: // result = add base, cond 15194 case 2: // result = lea base( , cond*2) 15195 case 3: // result = lea base(cond, cond*2) 15196 case 4: // result = lea base( , cond*4) 15197 case 5: // result = lea base(cond, cond*4) 15198 case 8: // result = lea base( , cond*8) 15199 case 9: // result = lea base(cond, cond*8) 15200 isFastMultiplier = true; 15201 break; 15202 } 15203 } 15204 15205 if (isFastMultiplier) { 15206 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 15207 if (NeedsCondInvert) // Invert the condition if needed. 15208 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond, 15209 DAG.getConstant(1, Cond.getValueType())); 15210 15211 // Zero extend the condition if needed. 15212 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 15213 Cond); 15214 // Scale the condition by the difference. 15215 if (Diff != 1) 15216 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 15217 DAG.getConstant(Diff, Cond.getValueType())); 15218 15219 // Add the base if non-zero. 15220 if (FalseC->getAPIntValue() != 0) 15221 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15222 SDValue(FalseC, 0)); 15223 return Cond; 15224 } 15225 } 15226 } 15227 } 15228 15229 // Canonicalize max and min: 15230 // (x > y) ? x : y -> (x >= y) ? x : y 15231 // (x < y) ? x : y -> (x <= y) ? x : y 15232 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates 15233 // the need for an extra compare 15234 // against zero. e.g. 15235 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0 15236 // subl %esi, %edi 15237 // testl %edi, %edi 15238 // movl $0, %eax 15239 // cmovgl %edi, %eax 15240 // => 15241 // xorl %eax, %eax 15242 // subl %esi, $edi 15243 // cmovsl %eax, %edi 15244 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC && 15245 DAG.isEqualTo(LHS, Cond.getOperand(0)) && 15246 DAG.isEqualTo(RHS, Cond.getOperand(1))) { 15247 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15248 switch (CC) { 15249 default: break; 15250 case ISD::SETLT: 15251 case ISD::SETGT: { 15252 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE; 15253 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(), 15254 Cond.getOperand(0), Cond.getOperand(1), NewCC); 15255 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS); 15256 } 15257 } 15258 } 15259 15260 // Match VSELECTs into subs with unsigned saturation. 15261 if (!DCI.isBeforeLegalize() && 15262 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC && 15263 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors. 15264 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) || 15265 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) { 15266 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15267 15268 // Check if one of the arms of the VSELECT is a zero vector. If it's on the 15269 // left side invert the predicate to simplify logic below. 15270 SDValue Other; 15271 if (ISD::isBuildVectorAllZeros(LHS.getNode())) { 15272 Other = RHS; 15273 CC = ISD::getSetCCInverse(CC, true); 15274 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) { 15275 Other = LHS; 15276 } 15277 15278 if (Other.getNode() && Other->getNumOperands() == 2 && 15279 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) { 15280 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1); 15281 SDValue CondRHS = Cond->getOperand(1); 15282 15283 // Look for a general sub with unsigned saturation first. 15284 // x >= y ? x-y : 0 --> subus x, y 15285 // x > y ? x-y : 0 --> subus x, y 15286 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) && 15287 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS)) 15288 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 15289 15290 // If the RHS is a constant we have to reverse the const canonicalization. 15291 // x > C-1 ? x+-C : 0 --> subus x, C 15292 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD && 15293 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) { 15294 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 15295 if (CondRHS.getConstantOperandVal(0) == -A-1) { 15296 SmallVector<SDValue, 32> V(VT.getVectorNumElements(), 15297 DAG.getConstant(-A, VT.getScalarType())); 15298 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, 15299 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 15300 V.data(), V.size())); 15301 } 15302 } 15303 15304 // Another special case: If C was a sign bit, the sub has been 15305 // canonicalized into a xor. 15306 // FIXME: Would it be better to use ComputeMaskedBits to determine whether 15307 // it's safe to decanonicalize the xor? 15308 // x s< 0 ? x^C : 0 --> subus x, C 15309 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR && 15310 ISD::isBuildVectorAllZeros(CondRHS.getNode()) && 15311 isSplatVector(OpRHS.getNode())) { 15312 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue(); 15313 if (A.isSignBit()) 15314 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS); 15315 } 15316 } 15317 } 15318 15319 // Try to match a min/max vector operation. 15320 if (!DCI.isBeforeLegalize() && 15321 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) 15322 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget)) 15323 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS); 15324 15325 // If we know that this node is legal then we know that it is going to be 15326 // matched by one of the SSE/AVX BLEND instructions. These instructions only 15327 // depend on the highest bit in each word. Try to use SimplifyDemandedBits 15328 // to simplify previous instructions. 15329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 15330 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() && 15331 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) { 15332 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits(); 15333 15334 // Don't optimize vector selects that map to mask-registers. 15335 if (BitWidth == 1) 15336 return SDValue(); 15337 15338 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size"); 15339 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1); 15340 15341 APInt KnownZero, KnownOne; 15342 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 15343 DCI.isBeforeLegalizeOps()); 15344 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) || 15345 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO)) 15346 DCI.CommitTargetLoweringOpt(TLO); 15347 } 15348 15349 return SDValue(); 15350} 15351 15352// Check whether a boolean test is testing a boolean value generated by 15353// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition 15354// code. 15355// 15356// Simplify the following patterns: 15357// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or 15358// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ) 15359// to (Op EFLAGS Cond) 15360// 15361// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or 15362// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ) 15363// to (Op EFLAGS !Cond) 15364// 15365// where Op could be BRCOND or CMOV. 15366// 15367static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) { 15368 // Quit if not CMP and SUB with its value result used. 15369 if (Cmp.getOpcode() != X86ISD::CMP && 15370 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0))) 15371 return SDValue(); 15372 15373 // Quit if not used as a boolean value. 15374 if (CC != X86::COND_E && CC != X86::COND_NE) 15375 return SDValue(); 15376 15377 // Check CMP operands. One of them should be 0 or 1 and the other should be 15378 // an SetCC or extended from it. 15379 SDValue Op1 = Cmp.getOperand(0); 15380 SDValue Op2 = Cmp.getOperand(1); 15381 15382 SDValue SetCC; 15383 const ConstantSDNode* C = 0; 15384 bool needOppositeCond = (CC == X86::COND_E); 15385 15386 if ((C = dyn_cast<ConstantSDNode>(Op1))) 15387 SetCC = Op2; 15388 else if ((C = dyn_cast<ConstantSDNode>(Op2))) 15389 SetCC = Op1; 15390 else // Quit if all operands are not constants. 15391 return SDValue(); 15392 15393 if (C->getZExtValue() == 1) 15394 needOppositeCond = !needOppositeCond; 15395 else if (C->getZExtValue() != 0) 15396 // Quit if the constant is neither 0 or 1. 15397 return SDValue(); 15398 15399 // Skip 'zext' node. 15400 if (SetCC.getOpcode() == ISD::ZERO_EXTEND) 15401 SetCC = SetCC.getOperand(0); 15402 15403 switch (SetCC.getOpcode()) { 15404 case X86ISD::SETCC: 15405 // Set the condition code or opposite one if necessary. 15406 CC = X86::CondCode(SetCC.getConstantOperandVal(0)); 15407 if (needOppositeCond) 15408 CC = X86::GetOppositeBranchCondition(CC); 15409 return SetCC.getOperand(1); 15410 case X86ISD::CMOV: { 15411 // Check whether false/true value has canonical one, i.e. 0 or 1. 15412 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0)); 15413 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1)); 15414 // Quit if true value is not a constant. 15415 if (!TVal) 15416 return SDValue(); 15417 // Quit if false value is not a constant. 15418 if (!FVal) { 15419 // A special case for rdrand, where 0 is set if false cond is found. 15420 SDValue Op = SetCC.getOperand(0); 15421 if (Op.getOpcode() != X86ISD::RDRAND) 15422 return SDValue(); 15423 } 15424 // Quit if false value is not the constant 0 or 1. 15425 bool FValIsFalse = true; 15426 if (FVal && FVal->getZExtValue() != 0) { 15427 if (FVal->getZExtValue() != 1) 15428 return SDValue(); 15429 // If FVal is 1, opposite cond is needed. 15430 needOppositeCond = !needOppositeCond; 15431 FValIsFalse = false; 15432 } 15433 // Quit if TVal is not the constant opposite of FVal. 15434 if (FValIsFalse && TVal->getZExtValue() != 1) 15435 return SDValue(); 15436 if (!FValIsFalse && TVal->getZExtValue() != 0) 15437 return SDValue(); 15438 CC = X86::CondCode(SetCC.getConstantOperandVal(2)); 15439 if (needOppositeCond) 15440 CC = X86::GetOppositeBranchCondition(CC); 15441 return SetCC.getOperand(3); 15442 } 15443 } 15444 15445 return SDValue(); 15446} 15447 15448/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL] 15449static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG, 15450 TargetLowering::DAGCombinerInfo &DCI, 15451 const X86Subtarget *Subtarget) { 15452 DebugLoc DL = N->getDebugLoc(); 15453 15454 // If the flag operand isn't dead, don't touch this CMOV. 15455 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty()) 15456 return SDValue(); 15457 15458 SDValue FalseOp = N->getOperand(0); 15459 SDValue TrueOp = N->getOperand(1); 15460 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2); 15461 SDValue Cond = N->getOperand(3); 15462 15463 if (CC == X86::COND_E || CC == X86::COND_NE) { 15464 switch (Cond.getOpcode()) { 15465 default: break; 15466 case X86ISD::BSR: 15467 case X86ISD::BSF: 15468 // If operand of BSR / BSF are proven never zero, then ZF cannot be set. 15469 if (DAG.isKnownNeverZero(Cond.getOperand(0))) 15470 return (CC == X86::COND_E) ? FalseOp : TrueOp; 15471 } 15472 } 15473 15474 SDValue Flags; 15475 15476 Flags = checkBoolTestSetCCCombine(Cond, CC); 15477 if (Flags.getNode() && 15478 // Extra check as FCMOV only supports a subset of X86 cond. 15479 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) { 15480 SDValue Ops[] = { FalseOp, TrueOp, 15481 DAG.getConstant(CC, MVT::i8), Flags }; 15482 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), 15483 Ops, array_lengthof(Ops)); 15484 } 15485 15486 // If this is a select between two integer constants, try to do some 15487 // optimizations. Note that the operands are ordered the opposite of SELECT 15488 // operands. 15489 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) { 15490 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) { 15491 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is 15492 // larger than FalseC (the false value). 15493 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) { 15494 CC = X86::GetOppositeBranchCondition(CC); 15495 std::swap(TrueC, FalseC); 15496 std::swap(TrueOp, FalseOp); 15497 } 15498 15499 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0. 15500 // This is efficient for any integer data type (including i8/i16) and 15501 // shift amount. 15502 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) { 15503 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 15504 DAG.getConstant(CC, MVT::i8), Cond); 15505 15506 // Zero extend the condition if needed. 15507 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond); 15508 15509 unsigned ShAmt = TrueC->getAPIntValue().logBase2(); 15510 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond, 15511 DAG.getConstant(ShAmt, MVT::i8)); 15512 if (N->getNumValues() == 2) // Dead flag value? 15513 return DCI.CombineTo(N, Cond, SDValue()); 15514 return Cond; 15515 } 15516 15517 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient 15518 // for any integer data type, including i8/i16. 15519 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) { 15520 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 15521 DAG.getConstant(CC, MVT::i8), Cond); 15522 15523 // Zero extend the condition if needed. 15524 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, 15525 FalseC->getValueType(0), Cond); 15526 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15527 SDValue(FalseC, 0)); 15528 15529 if (N->getNumValues() == 2) // Dead flag value? 15530 return DCI.CombineTo(N, Cond, SDValue()); 15531 return Cond; 15532 } 15533 15534 // Optimize cases that will turn into an LEA instruction. This requires 15535 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9). 15536 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) { 15537 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue(); 15538 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff; 15539 15540 bool isFastMultiplier = false; 15541 if (Diff < 10) { 15542 switch ((unsigned char)Diff) { 15543 default: break; 15544 case 1: // result = add base, cond 15545 case 2: // result = lea base( , cond*2) 15546 case 3: // result = lea base(cond, cond*2) 15547 case 4: // result = lea base( , cond*4) 15548 case 5: // result = lea base(cond, cond*4) 15549 case 8: // result = lea base( , cond*8) 15550 case 9: // result = lea base(cond, cond*8) 15551 isFastMultiplier = true; 15552 break; 15553 } 15554 } 15555 15556 if (isFastMultiplier) { 15557 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue(); 15558 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8, 15559 DAG.getConstant(CC, MVT::i8), Cond); 15560 // Zero extend the condition if needed. 15561 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0), 15562 Cond); 15563 // Scale the condition by the difference. 15564 if (Diff != 1) 15565 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond, 15566 DAG.getConstant(Diff, Cond.getValueType())); 15567 15568 // Add the base if non-zero. 15569 if (FalseC->getAPIntValue() != 0) 15570 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond, 15571 SDValue(FalseC, 0)); 15572 if (N->getNumValues() == 2) // Dead flag value? 15573 return DCI.CombineTo(N, Cond, SDValue()); 15574 return Cond; 15575 } 15576 } 15577 } 15578 } 15579 15580 // Handle these cases: 15581 // (select (x != c), e, c) -> select (x != c), e, x), 15582 // (select (x == c), c, e) -> select (x == c), x, e) 15583 // where the c is an integer constant, and the "select" is the combination 15584 // of CMOV and CMP. 15585 // 15586 // The rationale for this change is that the conditional-move from a constant 15587 // needs two instructions, however, conditional-move from a register needs 15588 // only one instruction. 15589 // 15590 // CAVEAT: By replacing a constant with a symbolic value, it may obscure 15591 // some instruction-combining opportunities. This opt needs to be 15592 // postponed as late as possible. 15593 // 15594 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) { 15595 // the DCI.xxxx conditions are provided to postpone the optimization as 15596 // late as possible. 15597 15598 ConstantSDNode *CmpAgainst = 0; 15599 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) && 15600 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) && 15601 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) { 15602 15603 if (CC == X86::COND_NE && 15604 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) { 15605 CC = X86::GetOppositeBranchCondition(CC); 15606 std::swap(TrueOp, FalseOp); 15607 } 15608 15609 if (CC == X86::COND_E && 15610 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) { 15611 SDValue Ops[] = { FalseOp, Cond.getOperand(0), 15612 DAG.getConstant(CC, MVT::i8), Cond }; 15613 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops, 15614 array_lengthof(Ops)); 15615 } 15616 } 15617 } 15618 15619 return SDValue(); 15620} 15621 15622/// PerformMulCombine - Optimize a single multiply with constant into two 15623/// in order to implement it with two cheaper instructions, e.g. 15624/// LEA + SHL, LEA + LEA. 15625static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG, 15626 TargetLowering::DAGCombinerInfo &DCI) { 15627 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 15628 return SDValue(); 15629 15630 EVT VT = N->getValueType(0); 15631 if (VT != MVT::i64) 15632 return SDValue(); 15633 15634 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15635 if (!C) 15636 return SDValue(); 15637 uint64_t MulAmt = C->getZExtValue(); 15638 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9) 15639 return SDValue(); 15640 15641 uint64_t MulAmt1 = 0; 15642 uint64_t MulAmt2 = 0; 15643 if ((MulAmt % 9) == 0) { 15644 MulAmt1 = 9; 15645 MulAmt2 = MulAmt / 9; 15646 } else if ((MulAmt % 5) == 0) { 15647 MulAmt1 = 5; 15648 MulAmt2 = MulAmt / 5; 15649 } else if ((MulAmt % 3) == 0) { 15650 MulAmt1 = 3; 15651 MulAmt2 = MulAmt / 3; 15652 } 15653 if (MulAmt2 && 15654 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){ 15655 DebugLoc DL = N->getDebugLoc(); 15656 15657 if (isPowerOf2_64(MulAmt2) && 15658 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD)) 15659 // If second multiplifer is pow2, issue it first. We want the multiply by 15660 // 3, 5, or 9 to be folded into the addressing mode unless the lone use 15661 // is an add. 15662 std::swap(MulAmt1, MulAmt2); 15663 15664 SDValue NewMul; 15665 if (isPowerOf2_64(MulAmt1)) 15666 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15667 DAG.getConstant(Log2_64(MulAmt1), MVT::i8)); 15668 else 15669 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0), 15670 DAG.getConstant(MulAmt1, VT)); 15671 15672 if (isPowerOf2_64(MulAmt2)) 15673 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul, 15674 DAG.getConstant(Log2_64(MulAmt2), MVT::i8)); 15675 else 15676 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul, 15677 DAG.getConstant(MulAmt2, VT)); 15678 15679 // Do not add new nodes to DAG combiner worklist. 15680 DCI.CombineTo(N, NewMul, false); 15681 } 15682 return SDValue(); 15683} 15684 15685static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) { 15686 SDValue N0 = N->getOperand(0); 15687 SDValue N1 = N->getOperand(1); 15688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 15689 EVT VT = N0.getValueType(); 15690 15691 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2)) 15692 // since the result of setcc_c is all zero's or all ones. 15693 if (VT.isInteger() && !VT.isVector() && 15694 N1C && N0.getOpcode() == ISD::AND && 15695 N0.getOperand(1).getOpcode() == ISD::Constant) { 15696 SDValue N00 = N0.getOperand(0); 15697 if (N00.getOpcode() == X86ISD::SETCC_CARRY || 15698 ((N00.getOpcode() == ISD::ANY_EXTEND || 15699 N00.getOpcode() == ISD::ZERO_EXTEND) && 15700 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) { 15701 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 15702 APInt ShAmt = N1C->getAPIntValue(); 15703 Mask = Mask.shl(ShAmt); 15704 if (Mask != 0) 15705 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, 15706 N00, DAG.getConstant(Mask, VT)); 15707 } 15708 } 15709 15710 // Hardware support for vector shifts is sparse which makes us scalarize the 15711 // vector operations in many cases. Also, on sandybridge ADD is faster than 15712 // shl. 15713 // (shl V, 1) -> add V,V 15714 if (isSplatVector(N1.getNode())) { 15715 assert(N0.getValueType().isVector() && "Invalid vector shift type"); 15716 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0)); 15717 // We shift all of the values by one. In many cases we do not have 15718 // hardware support for this operation. This is better expressed as an ADD 15719 // of two values. 15720 if (N1C && (1 == N1C->getZExtValue())) { 15721 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0); 15722 } 15723 } 15724 15725 return SDValue(); 15726} 15727 15728/// PerformShiftCombine - Transforms vector shift nodes to use vector shifts 15729/// when possible. 15730static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG, 15731 TargetLowering::DAGCombinerInfo &DCI, 15732 const X86Subtarget *Subtarget) { 15733 EVT VT = N->getValueType(0); 15734 if (N->getOpcode() == ISD::SHL) { 15735 SDValue V = PerformSHLCombine(N, DAG); 15736 if (V.getNode()) return V; 15737 } 15738 15739 // On X86 with SSE2 support, we can transform this to a vector shift if 15740 // all elements are shifted by the same amount. We can't do this in legalize 15741 // because the a constant vector is typically transformed to a constant pool 15742 // so we have no knowledge of the shift amount. 15743 if (!Subtarget->hasSSE2()) 15744 return SDValue(); 15745 15746 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 && 15747 (!Subtarget->hasInt256() || 15748 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16))) 15749 return SDValue(); 15750 15751 SDValue ShAmtOp = N->getOperand(1); 15752 EVT EltVT = VT.getVectorElementType(); 15753 DebugLoc DL = N->getDebugLoc(); 15754 SDValue BaseShAmt = SDValue(); 15755 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) { 15756 unsigned NumElts = VT.getVectorNumElements(); 15757 unsigned i = 0; 15758 for (; i != NumElts; ++i) { 15759 SDValue Arg = ShAmtOp.getOperand(i); 15760 if (Arg.getOpcode() == ISD::UNDEF) continue; 15761 BaseShAmt = Arg; 15762 break; 15763 } 15764 // Handle the case where the build_vector is all undef 15765 // FIXME: Should DAG allow this? 15766 if (i == NumElts) 15767 return SDValue(); 15768 15769 for (; i != NumElts; ++i) { 15770 SDValue Arg = ShAmtOp.getOperand(i); 15771 if (Arg.getOpcode() == ISD::UNDEF) continue; 15772 if (Arg != BaseShAmt) { 15773 return SDValue(); 15774 } 15775 } 15776 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE && 15777 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) { 15778 SDValue InVec = ShAmtOp.getOperand(0); 15779 if (InVec.getOpcode() == ISD::BUILD_VECTOR) { 15780 unsigned NumElts = InVec.getValueType().getVectorNumElements(); 15781 unsigned i = 0; 15782 for (; i != NumElts; ++i) { 15783 SDValue Arg = InVec.getOperand(i); 15784 if (Arg.getOpcode() == ISD::UNDEF) continue; 15785 BaseShAmt = Arg; 15786 break; 15787 } 15788 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) { 15789 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) { 15790 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex(); 15791 if (C->getZExtValue() == SplatIdx) 15792 BaseShAmt = InVec.getOperand(1); 15793 } 15794 } 15795 if (BaseShAmt.getNode() == 0) { 15796 // Don't create instructions with illegal types after legalize 15797 // types has run. 15798 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) && 15799 !DCI.isBeforeLegalize()) 15800 return SDValue(); 15801 15802 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp, 15803 DAG.getIntPtrConstant(0)); 15804 } 15805 } else 15806 return SDValue(); 15807 15808 // The shift amount is an i32. 15809 if (EltVT.bitsGT(MVT::i32)) 15810 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt); 15811 else if (EltVT.bitsLT(MVT::i32)) 15812 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt); 15813 15814 // The shift amount is identical so we can do a vector shift. 15815 SDValue ValOp = N->getOperand(0); 15816 switch (N->getOpcode()) { 15817 default: 15818 llvm_unreachable("Unknown shift opcode!"); 15819 case ISD::SHL: 15820 switch (VT.getSimpleVT().SimpleTy) { 15821 default: return SDValue(); 15822 case MVT::v2i64: 15823 case MVT::v4i32: 15824 case MVT::v8i16: 15825 case MVT::v4i64: 15826 case MVT::v8i32: 15827 case MVT::v16i16: 15828 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG); 15829 } 15830 case ISD::SRA: 15831 switch (VT.getSimpleVT().SimpleTy) { 15832 default: return SDValue(); 15833 case MVT::v4i32: 15834 case MVT::v8i16: 15835 case MVT::v8i32: 15836 case MVT::v16i16: 15837 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG); 15838 } 15839 case ISD::SRL: 15840 switch (VT.getSimpleVT().SimpleTy) { 15841 default: return SDValue(); 15842 case MVT::v2i64: 15843 case MVT::v4i32: 15844 case MVT::v8i16: 15845 case MVT::v4i64: 15846 case MVT::v8i32: 15847 case MVT::v16i16: 15848 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG); 15849 } 15850 } 15851} 15852 15853// CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..)) 15854// where both setccs reference the same FP CMP, and rewrite for CMPEQSS 15855// and friends. Likewise for OR -> CMPNEQSS. 15856static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG, 15857 TargetLowering::DAGCombinerInfo &DCI, 15858 const X86Subtarget *Subtarget) { 15859 unsigned opcode; 15860 15861 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but 15862 // we're requiring SSE2 for both. 15863 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) { 15864 SDValue N0 = N->getOperand(0); 15865 SDValue N1 = N->getOperand(1); 15866 SDValue CMP0 = N0->getOperand(1); 15867 SDValue CMP1 = N1->getOperand(1); 15868 DebugLoc DL = N->getDebugLoc(); 15869 15870 // The SETCCs should both refer to the same CMP. 15871 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1) 15872 return SDValue(); 15873 15874 SDValue CMP00 = CMP0->getOperand(0); 15875 SDValue CMP01 = CMP0->getOperand(1); 15876 EVT VT = CMP00.getValueType(); 15877 15878 if (VT == MVT::f32 || VT == MVT::f64) { 15879 bool ExpectingFlags = false; 15880 // Check for any users that want flags: 15881 for (SDNode::use_iterator UI = N->use_begin(), 15882 UE = N->use_end(); 15883 !ExpectingFlags && UI != UE; ++UI) 15884 switch (UI->getOpcode()) { 15885 default: 15886 case ISD::BR_CC: 15887 case ISD::BRCOND: 15888 case ISD::SELECT: 15889 ExpectingFlags = true; 15890 break; 15891 case ISD::CopyToReg: 15892 case ISD::SIGN_EXTEND: 15893 case ISD::ZERO_EXTEND: 15894 case ISD::ANY_EXTEND: 15895 break; 15896 } 15897 15898 if (!ExpectingFlags) { 15899 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0); 15900 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0); 15901 15902 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) { 15903 X86::CondCode tmp = cc0; 15904 cc0 = cc1; 15905 cc1 = tmp; 15906 } 15907 15908 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) || 15909 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) { 15910 bool is64BitFP = (CMP00.getValueType() == MVT::f64); 15911 X86ISD::NodeType NTOperator = is64BitFP ? 15912 X86ISD::FSETCCsd : X86ISD::FSETCCss; 15913 // FIXME: need symbolic constants for these magic numbers. 15914 // See X86ATTInstPrinter.cpp:printSSECC(). 15915 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4; 15916 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01, 15917 DAG.getConstant(x86cc, MVT::i8)); 15918 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32, 15919 OnesOrZeroesF); 15920 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI, 15921 DAG.getConstant(1, MVT::i32)); 15922 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed); 15923 return OneBitOfTruth; 15924 } 15925 } 15926 } 15927 } 15928 return SDValue(); 15929} 15930 15931/// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector 15932/// so it can be folded inside ANDNP. 15933static bool CanFoldXORWithAllOnes(const SDNode *N) { 15934 EVT VT = N->getValueType(0); 15935 15936 // Match direct AllOnes for 128 and 256-bit vectors 15937 if (ISD::isBuildVectorAllOnes(N)) 15938 return true; 15939 15940 // Look through a bit convert. 15941 if (N->getOpcode() == ISD::BITCAST) 15942 N = N->getOperand(0).getNode(); 15943 15944 // Sometimes the operand may come from a insert_subvector building a 256-bit 15945 // allones vector 15946 if (VT.is256BitVector() && 15947 N->getOpcode() == ISD::INSERT_SUBVECTOR) { 15948 SDValue V1 = N->getOperand(0); 15949 SDValue V2 = N->getOperand(1); 15950 15951 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR && 15952 V1.getOperand(0).getOpcode() == ISD::UNDEF && 15953 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) && 15954 ISD::isBuildVectorAllOnes(V2.getNode())) 15955 return true; 15956 } 15957 15958 return false; 15959} 15960 15961// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized 15962// register. In most cases we actually compare or select YMM-sized registers 15963// and mixing the two types creates horrible code. This method optimizes 15964// some of the transition sequences. 15965static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG, 15966 TargetLowering::DAGCombinerInfo &DCI, 15967 const X86Subtarget *Subtarget) { 15968 EVT VT = N->getValueType(0); 15969 if (!VT.is256BitVector()) 15970 return SDValue(); 15971 15972 assert((N->getOpcode() == ISD::ANY_EXTEND || 15973 N->getOpcode() == ISD::ZERO_EXTEND || 15974 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node"); 15975 15976 SDValue Narrow = N->getOperand(0); 15977 EVT NarrowVT = Narrow->getValueType(0); 15978 if (!NarrowVT.is128BitVector()) 15979 return SDValue(); 15980 15981 if (Narrow->getOpcode() != ISD::XOR && 15982 Narrow->getOpcode() != ISD::AND && 15983 Narrow->getOpcode() != ISD::OR) 15984 return SDValue(); 15985 15986 SDValue N0 = Narrow->getOperand(0); 15987 SDValue N1 = Narrow->getOperand(1); 15988 DebugLoc DL = Narrow->getDebugLoc(); 15989 15990 // The Left side has to be a trunc. 15991 if (N0.getOpcode() != ISD::TRUNCATE) 15992 return SDValue(); 15993 15994 // The type of the truncated inputs. 15995 EVT WideVT = N0->getOperand(0)->getValueType(0); 15996 if (WideVT != VT) 15997 return SDValue(); 15998 15999 // The right side has to be a 'trunc' or a constant vector. 16000 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE; 16001 bool RHSConst = (isSplatVector(N1.getNode()) && 16002 isa<ConstantSDNode>(N1->getOperand(0))); 16003 if (!RHSTrunc && !RHSConst) 16004 return SDValue(); 16005 16006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16007 16008 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT)) 16009 return SDValue(); 16010 16011 // Set N0 and N1 to hold the inputs to the new wide operation. 16012 N0 = N0->getOperand(0); 16013 if (RHSConst) { 16014 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(), 16015 N1->getOperand(0)); 16016 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1); 16017 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size()); 16018 } else if (RHSTrunc) { 16019 N1 = N1->getOperand(0); 16020 } 16021 16022 // Generate the wide operation. 16023 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1); 16024 unsigned Opcode = N->getOpcode(); 16025 switch (Opcode) { 16026 case ISD::ANY_EXTEND: 16027 return Op; 16028 case ISD::ZERO_EXTEND: { 16029 unsigned InBits = NarrowVT.getScalarType().getSizeInBits(); 16030 APInt Mask = APInt::getAllOnesValue(InBits); 16031 Mask = Mask.zext(VT.getScalarType().getSizeInBits()); 16032 return DAG.getNode(ISD::AND, DL, VT, 16033 Op, DAG.getConstant(Mask, VT)); 16034 } 16035 case ISD::SIGN_EXTEND: 16036 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, 16037 Op, DAG.getValueType(NarrowVT)); 16038 default: 16039 llvm_unreachable("Unexpected opcode"); 16040 } 16041} 16042 16043static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG, 16044 TargetLowering::DAGCombinerInfo &DCI, 16045 const X86Subtarget *Subtarget) { 16046 EVT VT = N->getValueType(0); 16047 if (DCI.isBeforeLegalizeOps()) 16048 return SDValue(); 16049 16050 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 16051 if (R.getNode()) 16052 return R; 16053 16054 // Create BLSI, and BLSR instructions 16055 // BLSI is X & (-X) 16056 // BLSR is X & (X-1) 16057 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) { 16058 SDValue N0 = N->getOperand(0); 16059 SDValue N1 = N->getOperand(1); 16060 DebugLoc DL = N->getDebugLoc(); 16061 16062 // Check LHS for neg 16063 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 && 16064 isZero(N0.getOperand(0))) 16065 return DAG.getNode(X86ISD::BLSI, DL, VT, N1); 16066 16067 // Check RHS for neg 16068 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 && 16069 isZero(N1.getOperand(0))) 16070 return DAG.getNode(X86ISD::BLSI, DL, VT, N0); 16071 16072 // Check LHS for X-1 16073 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 16074 isAllOnes(N0.getOperand(1))) 16075 return DAG.getNode(X86ISD::BLSR, DL, VT, N1); 16076 16077 // Check RHS for X-1 16078 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 16079 isAllOnes(N1.getOperand(1))) 16080 return DAG.getNode(X86ISD::BLSR, DL, VT, N0); 16081 16082 return SDValue(); 16083 } 16084 16085 // Want to form ANDNP nodes: 16086 // 1) In the hopes of then easily combining them with OR and AND nodes 16087 // to form PBLEND/PSIGN. 16088 // 2) To match ANDN packed intrinsics 16089 if (VT != MVT::v2i64 && VT != MVT::v4i64) 16090 return SDValue(); 16091 16092 SDValue N0 = N->getOperand(0); 16093 SDValue N1 = N->getOperand(1); 16094 DebugLoc DL = N->getDebugLoc(); 16095 16096 // Check LHS for vnot 16097 if (N0.getOpcode() == ISD::XOR && 16098 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode())) 16099 CanFoldXORWithAllOnes(N0.getOperand(1).getNode())) 16100 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1); 16101 16102 // Check RHS for vnot 16103 if (N1.getOpcode() == ISD::XOR && 16104 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode())) 16105 CanFoldXORWithAllOnes(N1.getOperand(1).getNode())) 16106 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0); 16107 16108 return SDValue(); 16109} 16110 16111static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG, 16112 TargetLowering::DAGCombinerInfo &DCI, 16113 const X86Subtarget *Subtarget) { 16114 EVT VT = N->getValueType(0); 16115 if (DCI.isBeforeLegalizeOps()) 16116 return SDValue(); 16117 16118 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget); 16119 if (R.getNode()) 16120 return R; 16121 16122 SDValue N0 = N->getOperand(0); 16123 SDValue N1 = N->getOperand(1); 16124 16125 // look for psign/blend 16126 if (VT == MVT::v2i64 || VT == MVT::v4i64) { 16127 if (!Subtarget->hasSSSE3() || 16128 (VT == MVT::v4i64 && !Subtarget->hasInt256())) 16129 return SDValue(); 16130 16131 // Canonicalize pandn to RHS 16132 if (N0.getOpcode() == X86ISD::ANDNP) 16133 std::swap(N0, N1); 16134 // or (and (m, y), (pandn m, x)) 16135 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) { 16136 SDValue Mask = N1.getOperand(0); 16137 SDValue X = N1.getOperand(1); 16138 SDValue Y; 16139 if (N0.getOperand(0) == Mask) 16140 Y = N0.getOperand(1); 16141 if (N0.getOperand(1) == Mask) 16142 Y = N0.getOperand(0); 16143 16144 // Check to see if the mask appeared in both the AND and ANDNP and 16145 if (!Y.getNode()) 16146 return SDValue(); 16147 16148 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them. 16149 // Look through mask bitcast. 16150 if (Mask.getOpcode() == ISD::BITCAST) 16151 Mask = Mask.getOperand(0); 16152 if (X.getOpcode() == ISD::BITCAST) 16153 X = X.getOperand(0); 16154 if (Y.getOpcode() == ISD::BITCAST) 16155 Y = Y.getOperand(0); 16156 16157 EVT MaskVT = Mask.getValueType(); 16158 16159 // Validate that the Mask operand is a vector sra node. 16160 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but 16161 // there is no psrai.b 16162 if (Mask.getOpcode() != X86ISD::VSRAI) 16163 return SDValue(); 16164 16165 // Check that the SRA is all signbits. 16166 SDValue SraC = Mask.getOperand(1); 16167 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue(); 16168 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits(); 16169 if ((SraAmt + 1) != EltBits) 16170 return SDValue(); 16171 16172 DebugLoc DL = N->getDebugLoc(); 16173 16174 // We are going to replace the AND, OR, NAND with either BLEND 16175 // or PSIGN, which only look at the MSB. The VSRAI instruction 16176 // does not affect the highest bit, so we can get rid of it. 16177 Mask = Mask.getOperand(0); 16178 16179 // Now we know we at least have a plendvb with the mask val. See if 16180 // we can form a psignb/w/d. 16181 // psign = x.type == y.type == mask.type && y = sub(0, x); 16182 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X && 16183 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) && 16184 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) { 16185 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) && 16186 "Unsupported VT for PSIGN"); 16187 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask); 16188 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 16189 } 16190 // PBLENDVB only available on SSE 4.1 16191 if (!Subtarget->hasSSE41()) 16192 return SDValue(); 16193 16194 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8; 16195 16196 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X); 16197 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y); 16198 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask); 16199 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X); 16200 return DAG.getNode(ISD::BITCAST, DL, VT, Mask); 16201 } 16202 } 16203 16204 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 16205 return SDValue(); 16206 16207 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c) 16208 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 16209 std::swap(N0, N1); 16210 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 16211 return SDValue(); 16212 if (!N0.hasOneUse() || !N1.hasOneUse()) 16213 return SDValue(); 16214 16215 SDValue ShAmt0 = N0.getOperand(1); 16216 if (ShAmt0.getValueType() != MVT::i8) 16217 return SDValue(); 16218 SDValue ShAmt1 = N1.getOperand(1); 16219 if (ShAmt1.getValueType() != MVT::i8) 16220 return SDValue(); 16221 if (ShAmt0.getOpcode() == ISD::TRUNCATE) 16222 ShAmt0 = ShAmt0.getOperand(0); 16223 if (ShAmt1.getOpcode() == ISD::TRUNCATE) 16224 ShAmt1 = ShAmt1.getOperand(0); 16225 16226 DebugLoc DL = N->getDebugLoc(); 16227 unsigned Opc = X86ISD::SHLD; 16228 SDValue Op0 = N0.getOperand(0); 16229 SDValue Op1 = N1.getOperand(0); 16230 if (ShAmt0.getOpcode() == ISD::SUB) { 16231 Opc = X86ISD::SHRD; 16232 std::swap(Op0, Op1); 16233 std::swap(ShAmt0, ShAmt1); 16234 } 16235 16236 unsigned Bits = VT.getSizeInBits(); 16237 if (ShAmt1.getOpcode() == ISD::SUB) { 16238 SDValue Sum = ShAmt1.getOperand(0); 16239 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) { 16240 SDValue ShAmt1Op1 = ShAmt1.getOperand(1); 16241 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE) 16242 ShAmt1Op1 = ShAmt1Op1.getOperand(0); 16243 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0) 16244 return DAG.getNode(Opc, DL, VT, 16245 Op0, Op1, 16246 DAG.getNode(ISD::TRUNCATE, DL, 16247 MVT::i8, ShAmt0)); 16248 } 16249 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) { 16250 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0); 16251 if (ShAmt0C && 16252 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits) 16253 return DAG.getNode(Opc, DL, VT, 16254 N0.getOperand(0), N1.getOperand(0), 16255 DAG.getNode(ISD::TRUNCATE, DL, 16256 MVT::i8, ShAmt0)); 16257 } 16258 16259 return SDValue(); 16260} 16261 16262// Generate NEG and CMOV for integer abs. 16263static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 16264 EVT VT = N->getValueType(0); 16265 16266 // Since X86 does not have CMOV for 8-bit integer, we don't convert 16267 // 8-bit integer abs to NEG and CMOV. 16268 if (VT.isInteger() && VT.getSizeInBits() == 8) 16269 return SDValue(); 16270 16271 SDValue N0 = N->getOperand(0); 16272 SDValue N1 = N->getOperand(1); 16273 DebugLoc DL = N->getDebugLoc(); 16274 16275 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 16276 // and change it to SUB and CMOV. 16277 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 16278 N0.getOpcode() == ISD::ADD && 16279 N0.getOperand(1) == N1 && 16280 N1.getOpcode() == ISD::SRA && 16281 N1.getOperand(0) == N0.getOperand(0)) 16282 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 16283 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) { 16284 // Generate SUB & CMOV. 16285 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32), 16286 DAG.getConstant(0, VT), N0.getOperand(0)); 16287 16288 SDValue Ops[] = { N0.getOperand(0), Neg, 16289 DAG.getConstant(X86::COND_GE, MVT::i8), 16290 SDValue(Neg.getNode(), 1) }; 16291 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), 16292 Ops, array_lengthof(Ops)); 16293 } 16294 return SDValue(); 16295} 16296 16297// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes 16298static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG, 16299 TargetLowering::DAGCombinerInfo &DCI, 16300 const X86Subtarget *Subtarget) { 16301 EVT VT = N->getValueType(0); 16302 if (DCI.isBeforeLegalizeOps()) 16303 return SDValue(); 16304 16305 if (Subtarget->hasCMov()) { 16306 SDValue RV = performIntegerAbsCombine(N, DAG); 16307 if (RV.getNode()) 16308 return RV; 16309 } 16310 16311 // Try forming BMI if it is available. 16312 if (!Subtarget->hasBMI()) 16313 return SDValue(); 16314 16315 if (VT != MVT::i32 && VT != MVT::i64) 16316 return SDValue(); 16317 16318 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions"); 16319 16320 // Create BLSMSK instructions by finding X ^ (X-1) 16321 SDValue N0 = N->getOperand(0); 16322 SDValue N1 = N->getOperand(1); 16323 DebugLoc DL = N->getDebugLoc(); 16324 16325 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 && 16326 isAllOnes(N0.getOperand(1))) 16327 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1); 16328 16329 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 && 16330 isAllOnes(N1.getOperand(1))) 16331 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0); 16332 16333 return SDValue(); 16334} 16335 16336/// PerformLOADCombine - Do target-specific dag combines on LOAD nodes. 16337static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG, 16338 TargetLowering::DAGCombinerInfo &DCI, 16339 const X86Subtarget *Subtarget) { 16340 LoadSDNode *Ld = cast<LoadSDNode>(N); 16341 EVT RegVT = Ld->getValueType(0); 16342 EVT MemVT = Ld->getMemoryVT(); 16343 DebugLoc dl = Ld->getDebugLoc(); 16344 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16345 16346 ISD::LoadExtType Ext = Ld->getExtensionType(); 16347 16348 // If this is a vector EXT Load then attempt to optimize it using a 16349 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the 16350 // expansion is still better than scalar code. 16351 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll 16352 // emit a shuffle and a arithmetic shift. 16353 // TODO: It is possible to support ZExt by zeroing the undef values 16354 // during the shuffle phase or after the shuffle. 16355 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() && 16356 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) { 16357 assert(MemVT != RegVT && "Cannot extend to the same type"); 16358 assert(MemVT.isVector() && "Must load a vector from memory"); 16359 16360 unsigned NumElems = RegVT.getVectorNumElements(); 16361 unsigned RegSz = RegVT.getSizeInBits(); 16362 unsigned MemSz = MemVT.getSizeInBits(); 16363 assert(RegSz > MemSz && "Register size must be greater than the mem size"); 16364 16365 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) 16366 return SDValue(); 16367 16368 // All sizes must be a power of two. 16369 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) 16370 return SDValue(); 16371 16372 // Attempt to load the original value using scalar loads. 16373 // Find the largest scalar type that divides the total loaded size. 16374 MVT SclrLoadTy = MVT::i8; 16375 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 16376 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 16377 MVT Tp = (MVT::SimpleValueType)tp; 16378 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) { 16379 SclrLoadTy = Tp; 16380 } 16381 } 16382 16383 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 16384 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 && 16385 (64 <= MemSz)) 16386 SclrLoadTy = MVT::f64; 16387 16388 // Calculate the number of scalar loads that we need to perform 16389 // in order to load our vector from memory. 16390 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits(); 16391 if (Ext == ISD::SEXTLOAD && NumLoads > 1) 16392 return SDValue(); 16393 16394 unsigned loadRegZize = RegSz; 16395 if (Ext == ISD::SEXTLOAD && RegSz == 256) 16396 loadRegZize /= 2; 16397 16398 // Represent our vector as a sequence of elements which are the 16399 // largest scalar that we can load. 16400 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy, 16401 loadRegZize/SclrLoadTy.getSizeInBits()); 16402 16403 // Represent the data using the same element type that is stored in 16404 // memory. In practice, we ''widen'' MemVT. 16405 EVT WideVecVT = 16406 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), 16407 loadRegZize/MemVT.getScalarType().getSizeInBits()); 16408 16409 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && 16410 "Invalid vector type"); 16411 16412 // We can't shuffle using an illegal type. 16413 if (!TLI.isTypeLegal(WideVecVT)) 16414 return SDValue(); 16415 16416 SmallVector<SDValue, 8> Chains; 16417 SDValue Ptr = Ld->getBasePtr(); 16418 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8, 16419 TLI.getPointerTy()); 16420 SDValue Res = DAG.getUNDEF(LoadUnitVecVT); 16421 16422 for (unsigned i = 0; i < NumLoads; ++i) { 16423 // Perform a single load. 16424 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), 16425 Ptr, Ld->getPointerInfo(), 16426 Ld->isVolatile(), Ld->isNonTemporal(), 16427 Ld->isInvariant(), Ld->getAlignment()); 16428 Chains.push_back(ScalarLoad.getValue(1)); 16429 // Create the first element type using SCALAR_TO_VECTOR in order to avoid 16430 // another round of DAGCombining. 16431 if (i == 0) 16432 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad); 16433 else 16434 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res, 16435 ScalarLoad, DAG.getIntPtrConstant(i)); 16436 16437 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 16438 } 16439 16440 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 16441 Chains.size()); 16442 16443 // Bitcast the loaded value to a vector of the original element type, in 16444 // the size of the target vector type. 16445 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res); 16446 unsigned SizeRatio = RegSz/MemSz; 16447 16448 if (Ext == ISD::SEXTLOAD) { 16449 // If we have SSE4.1 we can directly emit a VSEXT node. 16450 if (Subtarget->hasSSE41()) { 16451 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec); 16452 return DCI.CombineTo(N, Sext, TF, true); 16453 } 16454 16455 // Otherwise we'll shuffle the small elements in the high bits of the 16456 // larger type and perform an arithmetic shift. If the shift is not legal 16457 // it's better to scalarize. 16458 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT)) 16459 return SDValue(); 16460 16461 // Redistribute the loaded elements into the different locations. 16462 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 16463 for (unsigned i = 0; i != NumElems; ++i) 16464 ShuffleVec[i*SizeRatio + SizeRatio-1] = i; 16465 16466 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 16467 DAG.getUNDEF(WideVecVT), 16468 &ShuffleVec[0]); 16469 16470 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 16471 16472 // Build the arithmetic shift. 16473 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() - 16474 MemVT.getVectorElementType().getSizeInBits(); 16475 SmallVector<SDValue, 8> C(NumElems, 16476 DAG.getConstant(Amt, RegVT.getScalarType())); 16477 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size()); 16478 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV); 16479 16480 return DCI.CombineTo(N, Shuff, TF, true); 16481 } 16482 16483 // Redistribute the loaded elements into the different locations. 16484 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 16485 for (unsigned i = 0; i != NumElems; ++i) 16486 ShuffleVec[i*SizeRatio] = i; 16487 16488 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec, 16489 DAG.getUNDEF(WideVecVT), 16490 &ShuffleVec[0]); 16491 16492 // Bitcast to the requested type. 16493 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff); 16494 // Replace the original load with the new sequence 16495 // and return the new chain. 16496 return DCI.CombineTo(N, Shuff, TF, true); 16497 } 16498 16499 return SDValue(); 16500} 16501 16502/// PerformSTORECombine - Do target-specific dag combines on STORE nodes. 16503static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG, 16504 const X86Subtarget *Subtarget) { 16505 StoreSDNode *St = cast<StoreSDNode>(N); 16506 EVT VT = St->getValue().getValueType(); 16507 EVT StVT = St->getMemoryVT(); 16508 DebugLoc dl = St->getDebugLoc(); 16509 SDValue StoredVal = St->getOperand(1); 16510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16511 16512 // If we are saving a concatenation of two XMM registers, perform two stores. 16513 // On Sandy Bridge, 256-bit memory operations are executed by two 16514 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit 16515 // memory operation. 16516 if (VT.is256BitVector() && !Subtarget->hasInt256() && 16517 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS && 16518 StoredVal.getNumOperands() == 2) { 16519 SDValue Value0 = StoredVal.getOperand(0); 16520 SDValue Value1 = StoredVal.getOperand(1); 16521 16522 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy()); 16523 SDValue Ptr0 = St->getBasePtr(); 16524 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride); 16525 16526 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0, 16527 St->getPointerInfo(), St->isVolatile(), 16528 St->isNonTemporal(), St->getAlignment()); 16529 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1, 16530 St->getPointerInfo(), St->isVolatile(), 16531 St->isNonTemporal(), St->getAlignment()); 16532 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1); 16533 } 16534 16535 // Optimize trunc store (of multiple scalars) to shuffle and store. 16536 // First, pack all of the elements in one place. Next, store to memory 16537 // in fewer chunks. 16538 if (St->isTruncatingStore() && VT.isVector()) { 16539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16540 unsigned NumElems = VT.getVectorNumElements(); 16541 assert(StVT != VT && "Cannot truncate to the same type"); 16542 unsigned FromSz = VT.getVectorElementType().getSizeInBits(); 16543 unsigned ToSz = StVT.getVectorElementType().getSizeInBits(); 16544 16545 // From, To sizes and ElemCount must be pow of two 16546 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue(); 16547 // We are going to use the original vector elt for storing. 16548 // Accumulated smaller vector elements must be a multiple of the store size. 16549 if (0 != (NumElems * FromSz) % ToSz) return SDValue(); 16550 16551 unsigned SizeRatio = FromSz / ToSz; 16552 16553 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits()); 16554 16555 // Create a type on which we perform the shuffle 16556 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), 16557 StVT.getScalarType(), NumElems*SizeRatio); 16558 16559 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits()); 16560 16561 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue()); 16562 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1); 16563 for (unsigned i = 0; i != NumElems; ++i) 16564 ShuffleVec[i] = i * SizeRatio; 16565 16566 // Can't shuffle using an illegal type. 16567 if (!TLI.isTypeLegal(WideVecVT)) 16568 return SDValue(); 16569 16570 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec, 16571 DAG.getUNDEF(WideVecVT), 16572 &ShuffleVec[0]); 16573 // At this point all of the data is stored at the bottom of the 16574 // register. We now need to save it to mem. 16575 16576 // Find the largest store unit 16577 MVT StoreType = MVT::i8; 16578 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE; 16579 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) { 16580 MVT Tp = (MVT::SimpleValueType)tp; 16581 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz) 16582 StoreType = Tp; 16583 } 16584 16585 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64. 16586 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 && 16587 (64 <= NumElems * ToSz)) 16588 StoreType = MVT::f64; 16589 16590 // Bitcast the original vector into a vector of store-size units 16591 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(), 16592 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits()); 16593 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits()); 16594 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff); 16595 SmallVector<SDValue, 8> Chains; 16596 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, 16597 TLI.getPointerTy()); 16598 SDValue Ptr = St->getBasePtr(); 16599 16600 // Perform one or more big stores into memory. 16601 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) { 16602 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, 16603 StoreType, ShuffWide, 16604 DAG.getIntPtrConstant(i)); 16605 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr, 16606 St->getPointerInfo(), St->isVolatile(), 16607 St->isNonTemporal(), St->getAlignment()); 16608 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 16609 Chains.push_back(Ch); 16610 } 16611 16612 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], 16613 Chains.size()); 16614 } 16615 16616 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering 16617 // the FP state in cases where an emms may be missing. 16618 // A preferable solution to the general problem is to figure out the right 16619 // places to insert EMMS. This qualifies as a quick hack. 16620 16621 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode. 16622 if (VT.getSizeInBits() != 64) 16623 return SDValue(); 16624 16625 const Function *F = DAG.getMachineFunction().getFunction(); 16626 bool NoImplicitFloatOps = F->getAttributes(). 16627 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 16628 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps 16629 && Subtarget->hasSSE2(); 16630 if ((VT.isVector() || 16631 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) && 16632 isa<LoadSDNode>(St->getValue()) && 16633 !cast<LoadSDNode>(St->getValue())->isVolatile() && 16634 St->getChain().hasOneUse() && !St->isVolatile()) { 16635 SDNode* LdVal = St->getValue().getNode(); 16636 LoadSDNode *Ld = 0; 16637 int TokenFactorIndex = -1; 16638 SmallVector<SDValue, 8> Ops; 16639 SDNode* ChainVal = St->getChain().getNode(); 16640 // Must be a store of a load. We currently handle two cases: the load 16641 // is a direct child, and it's under an intervening TokenFactor. It is 16642 // possible to dig deeper under nested TokenFactors. 16643 if (ChainVal == LdVal) 16644 Ld = cast<LoadSDNode>(St->getChain()); 16645 else if (St->getValue().hasOneUse() && 16646 ChainVal->getOpcode() == ISD::TokenFactor) { 16647 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) { 16648 if (ChainVal->getOperand(i).getNode() == LdVal) { 16649 TokenFactorIndex = i; 16650 Ld = cast<LoadSDNode>(St->getValue()); 16651 } else 16652 Ops.push_back(ChainVal->getOperand(i)); 16653 } 16654 } 16655 16656 if (!Ld || !ISD::isNormalLoad(Ld)) 16657 return SDValue(); 16658 16659 // If this is not the MMX case, i.e. we are just turning i64 load/store 16660 // into f64 load/store, avoid the transformation if there are multiple 16661 // uses of the loaded value. 16662 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0)) 16663 return SDValue(); 16664 16665 DebugLoc LdDL = Ld->getDebugLoc(); 16666 DebugLoc StDL = N->getDebugLoc(); 16667 // If we are a 64-bit capable x86, lower to a single movq load/store pair. 16668 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store 16669 // pair instead. 16670 if (Subtarget->is64Bit() || F64IsLegal) { 16671 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64; 16672 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(), 16673 Ld->getPointerInfo(), Ld->isVolatile(), 16674 Ld->isNonTemporal(), Ld->isInvariant(), 16675 Ld->getAlignment()); 16676 SDValue NewChain = NewLd.getValue(1); 16677 if (TokenFactorIndex != -1) { 16678 Ops.push_back(NewChain); 16679 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 16680 Ops.size()); 16681 } 16682 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(), 16683 St->getPointerInfo(), 16684 St->isVolatile(), St->isNonTemporal(), 16685 St->getAlignment()); 16686 } 16687 16688 // Otherwise, lower to two pairs of 32-bit loads / stores. 16689 SDValue LoAddr = Ld->getBasePtr(); 16690 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr, 16691 DAG.getConstant(4, MVT::i32)); 16692 16693 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr, 16694 Ld->getPointerInfo(), 16695 Ld->isVolatile(), Ld->isNonTemporal(), 16696 Ld->isInvariant(), Ld->getAlignment()); 16697 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr, 16698 Ld->getPointerInfo().getWithOffset(4), 16699 Ld->isVolatile(), Ld->isNonTemporal(), 16700 Ld->isInvariant(), 16701 MinAlign(Ld->getAlignment(), 4)); 16702 16703 SDValue NewChain = LoLd.getValue(1); 16704 if (TokenFactorIndex != -1) { 16705 Ops.push_back(LoLd); 16706 Ops.push_back(HiLd); 16707 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0], 16708 Ops.size()); 16709 } 16710 16711 LoAddr = St->getBasePtr(); 16712 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr, 16713 DAG.getConstant(4, MVT::i32)); 16714 16715 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr, 16716 St->getPointerInfo(), 16717 St->isVolatile(), St->isNonTemporal(), 16718 St->getAlignment()); 16719 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr, 16720 St->getPointerInfo().getWithOffset(4), 16721 St->isVolatile(), 16722 St->isNonTemporal(), 16723 MinAlign(St->getAlignment(), 4)); 16724 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt); 16725 } 16726 return SDValue(); 16727} 16728 16729/// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal" 16730/// and return the operands for the horizontal operation in LHS and RHS. A 16731/// horizontal operation performs the binary operation on successive elements 16732/// of its first operand, then on successive elements of its second operand, 16733/// returning the resulting values in a vector. For example, if 16734/// A = < float a0, float a1, float a2, float a3 > 16735/// and 16736/// B = < float b0, float b1, float b2, float b3 > 16737/// then the result of doing a horizontal operation on A and B is 16738/// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >. 16739/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form 16740/// A horizontal-op B, for some already available A and B, and if so then LHS is 16741/// set to A, RHS to B, and the routine returns 'true'. 16742/// Note that the binary operation should have the property that if one of the 16743/// operands is UNDEF then the result is UNDEF. 16744static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) { 16745 // Look for the following pattern: if 16746 // A = < float a0, float a1, float a2, float a3 > 16747 // B = < float b0, float b1, float b2, float b3 > 16748 // and 16749 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6> 16750 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7> 16751 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 > 16752 // which is A horizontal-op B. 16753 16754 // At least one of the operands should be a vector shuffle. 16755 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 16756 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) 16757 return false; 16758 16759 EVT VT = LHS.getValueType(); 16760 16761 assert((VT.is128BitVector() || VT.is256BitVector()) && 16762 "Unsupported vector type for horizontal add/sub"); 16763 16764 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to 16765 // operate independently on 128-bit lanes. 16766 unsigned NumElts = VT.getVectorNumElements(); 16767 unsigned NumLanes = VT.getSizeInBits()/128; 16768 unsigned NumLaneElts = NumElts / NumLanes; 16769 assert((NumLaneElts % 2 == 0) && 16770 "Vector type should have an even number of elements in each lane"); 16771 unsigned HalfLaneElts = NumLaneElts/2; 16772 16773 // View LHS in the form 16774 // LHS = VECTOR_SHUFFLE A, B, LMask 16775 // If LHS is not a shuffle then pretend it is the shuffle 16776 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1> 16777 // NOTE: in what follows a default initialized SDValue represents an UNDEF of 16778 // type VT. 16779 SDValue A, B; 16780 SmallVector<int, 16> LMask(NumElts); 16781 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 16782 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF) 16783 A = LHS.getOperand(0); 16784 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF) 16785 B = LHS.getOperand(1); 16786 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(); 16787 std::copy(Mask.begin(), Mask.end(), LMask.begin()); 16788 } else { 16789 if (LHS.getOpcode() != ISD::UNDEF) 16790 A = LHS; 16791 for (unsigned i = 0; i != NumElts; ++i) 16792 LMask[i] = i; 16793 } 16794 16795 // Likewise, view RHS in the form 16796 // RHS = VECTOR_SHUFFLE C, D, RMask 16797 SDValue C, D; 16798 SmallVector<int, 16> RMask(NumElts); 16799 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) { 16800 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF) 16801 C = RHS.getOperand(0); 16802 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF) 16803 D = RHS.getOperand(1); 16804 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(); 16805 std::copy(Mask.begin(), Mask.end(), RMask.begin()); 16806 } else { 16807 if (RHS.getOpcode() != ISD::UNDEF) 16808 C = RHS; 16809 for (unsigned i = 0; i != NumElts; ++i) 16810 RMask[i] = i; 16811 } 16812 16813 // Check that the shuffles are both shuffling the same vectors. 16814 if (!(A == C && B == D) && !(A == D && B == C)) 16815 return false; 16816 16817 // If everything is UNDEF then bail out: it would be better to fold to UNDEF. 16818 if (!A.getNode() && !B.getNode()) 16819 return false; 16820 16821 // If A and B occur in reverse order in RHS, then "swap" them (which means 16822 // rewriting the mask). 16823 if (A != C) 16824 CommuteVectorShuffleMask(RMask, NumElts); 16825 16826 // At this point LHS and RHS are equivalent to 16827 // LHS = VECTOR_SHUFFLE A, B, LMask 16828 // RHS = VECTOR_SHUFFLE A, B, RMask 16829 // Check that the masks correspond to performing a horizontal operation. 16830 for (unsigned i = 0; i != NumElts; ++i) { 16831 int LIdx = LMask[i], RIdx = RMask[i]; 16832 16833 // Ignore any UNDEF components. 16834 if (LIdx < 0 || RIdx < 0 || 16835 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) || 16836 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts))) 16837 continue; 16838 16839 // Check that successive elements are being operated on. If not, this is 16840 // not a horizontal operation. 16841 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs 16842 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts; 16843 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart; 16844 if (!(LIdx == Index && RIdx == Index + 1) && 16845 !(IsCommutative && LIdx == Index + 1 && RIdx == Index)) 16846 return false; 16847 } 16848 16849 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it. 16850 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it. 16851 return true; 16852} 16853 16854/// PerformFADDCombine - Do target-specific dag combines on floating point adds. 16855static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG, 16856 const X86Subtarget *Subtarget) { 16857 EVT VT = N->getValueType(0); 16858 SDValue LHS = N->getOperand(0); 16859 SDValue RHS = N->getOperand(1); 16860 16861 // Try to synthesize horizontal adds from adds of shuffles. 16862 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 16863 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 16864 isHorizontalBinOp(LHS, RHS, true)) 16865 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS); 16866 return SDValue(); 16867} 16868 16869/// PerformFSUBCombine - Do target-specific dag combines on floating point subs. 16870static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG, 16871 const X86Subtarget *Subtarget) { 16872 EVT VT = N->getValueType(0); 16873 SDValue LHS = N->getOperand(0); 16874 SDValue RHS = N->getOperand(1); 16875 16876 // Try to synthesize horizontal subs from subs of shuffles. 16877 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) || 16878 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) && 16879 isHorizontalBinOp(LHS, RHS, false)) 16880 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS); 16881 return SDValue(); 16882} 16883 16884/// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and 16885/// X86ISD::FXOR nodes. 16886static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) { 16887 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR); 16888 // F[X]OR(0.0, x) -> x 16889 // F[X]OR(x, 0.0) -> x 16890 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 16891 if (C->getValueAPF().isPosZero()) 16892 return N->getOperand(1); 16893 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 16894 if (C->getValueAPF().isPosZero()) 16895 return N->getOperand(0); 16896 return SDValue(); 16897} 16898 16899/// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and 16900/// X86ISD::FMAX nodes. 16901static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) { 16902 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX); 16903 16904 // Only perform optimizations if UnsafeMath is used. 16905 if (!DAG.getTarget().Options.UnsafeFPMath) 16906 return SDValue(); 16907 16908 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes 16909 // into FMINC and FMAXC, which are Commutative operations. 16910 unsigned NewOp = 0; 16911 switch (N->getOpcode()) { 16912 default: llvm_unreachable("unknown opcode"); 16913 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break; 16914 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break; 16915 } 16916 16917 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0), 16918 N->getOperand(0), N->getOperand(1)); 16919} 16920 16921/// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes. 16922static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) { 16923 // FAND(0.0, x) -> 0.0 16924 // FAND(x, 0.0) -> 0.0 16925 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) 16926 if (C->getValueAPF().isPosZero()) 16927 return N->getOperand(0); 16928 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1))) 16929 if (C->getValueAPF().isPosZero()) 16930 return N->getOperand(1); 16931 return SDValue(); 16932} 16933 16934static SDValue PerformBTCombine(SDNode *N, 16935 SelectionDAG &DAG, 16936 TargetLowering::DAGCombinerInfo &DCI) { 16937 // BT ignores high bits in the bit index operand. 16938 SDValue Op1 = N->getOperand(1); 16939 if (Op1.hasOneUse()) { 16940 unsigned BitWidth = Op1.getValueSizeInBits(); 16941 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth)); 16942 APInt KnownZero, KnownOne; 16943 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 16944 !DCI.isBeforeLegalizeOps()); 16945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16946 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) || 16947 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO)) 16948 DCI.CommitTargetLoweringOpt(TLO); 16949 } 16950 return SDValue(); 16951} 16952 16953static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) { 16954 SDValue Op = N->getOperand(0); 16955 if (Op.getOpcode() == ISD::BITCAST) 16956 Op = Op.getOperand(0); 16957 EVT VT = N->getValueType(0), OpVT = Op.getValueType(); 16958 if (Op.getOpcode() == X86ISD::VZEXT_LOAD && 16959 VT.getVectorElementType().getSizeInBits() == 16960 OpVT.getVectorElementType().getSizeInBits()) { 16961 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op); 16962 } 16963 return SDValue(); 16964} 16965 16966static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG, 16967 TargetLowering::DAGCombinerInfo &DCI, 16968 const X86Subtarget *Subtarget) { 16969 EVT VT = N->getValueType(0); 16970 16971 if (!VT.isVector()) 16972 return SDValue(); 16973 16974 SDValue In = N->getOperand(0); 16975 EVT InVT = In.getValueType(); 16976 DebugLoc dl = N->getDebugLoc(); 16977 unsigned ExtendedEltSize = VT.getVectorElementType().getSizeInBits(); 16978 16979 // Split SIGN_EXTEND operation to use vmovsx instruction when possible 16980 if (InVT == MVT::v8i8) { 16981 if (ExtendedEltSize > 16 && !Subtarget->hasInt256()) 16982 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, In); 16983 if (ExtendedEltSize > 32) 16984 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i32, In); 16985 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, In); 16986 } 16987 16988 if ((InVT == MVT::v4i8 || InVT == MVT::v4i16) && 16989 ExtendedEltSize > 32 && !Subtarget->hasInt256()) { 16990 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In); 16991 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, In); 16992 } 16993 16994 if (!DCI.isBeforeLegalizeOps()) 16995 return SDValue(); 16996 16997 if (!Subtarget->hasFp256()) 16998 return SDValue(); 16999 17000 if (VT.is256BitVector()) { 17001 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 17002 if (R.getNode()) 17003 return R; 17004 } 17005 17006 return SDValue(); 17007} 17008 17009static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG, 17010 const X86Subtarget* Subtarget) { 17011 DebugLoc dl = N->getDebugLoc(); 17012 EVT VT = N->getValueType(0); 17013 17014 // Let legalize expand this if it isn't a legal type yet. 17015 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 17016 return SDValue(); 17017 17018 EVT ScalarVT = VT.getScalarType(); 17019 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || 17020 (!Subtarget->hasFMA() && !Subtarget->hasFMA4())) 17021 return SDValue(); 17022 17023 SDValue A = N->getOperand(0); 17024 SDValue B = N->getOperand(1); 17025 SDValue C = N->getOperand(2); 17026 17027 bool NegA = (A.getOpcode() == ISD::FNEG); 17028 bool NegB = (B.getOpcode() == ISD::FNEG); 17029 bool NegC = (C.getOpcode() == ISD::FNEG); 17030 17031 // Negative multiplication when NegA xor NegB 17032 bool NegMul = (NegA != NegB); 17033 if (NegA) 17034 A = A.getOperand(0); 17035 if (NegB) 17036 B = B.getOperand(0); 17037 if (NegC) 17038 C = C.getOperand(0); 17039 17040 unsigned Opcode; 17041 if (!NegMul) 17042 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB; 17043 else 17044 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB; 17045 17046 return DAG.getNode(Opcode, dl, VT, A, B, C); 17047} 17048 17049static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG, 17050 TargetLowering::DAGCombinerInfo &DCI, 17051 const X86Subtarget *Subtarget) { 17052 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) -> 17053 // (and (i32 x86isd::setcc_carry), 1) 17054 // This eliminates the zext. This transformation is necessary because 17055 // ISD::SETCC is always legalized to i8. 17056 DebugLoc dl = N->getDebugLoc(); 17057 SDValue N0 = N->getOperand(0); 17058 EVT VT = N->getValueType(0); 17059 17060 if (N0.getOpcode() == ISD::AND && 17061 N0.hasOneUse() && 17062 N0.getOperand(0).hasOneUse()) { 17063 SDValue N00 = N0.getOperand(0); 17064 if (N00.getOpcode() == X86ISD::SETCC_CARRY) { 17065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 17066 if (!C || C->getZExtValue() != 1) 17067 return SDValue(); 17068 return DAG.getNode(ISD::AND, dl, VT, 17069 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, 17070 N00.getOperand(0), N00.getOperand(1)), 17071 DAG.getConstant(1, VT)); 17072 } 17073 } 17074 17075 if (VT.is256BitVector()) { 17076 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget); 17077 if (R.getNode()) 17078 return R; 17079 } 17080 17081 return SDValue(); 17082} 17083 17084// Optimize x == -y --> x+y == 0 17085// x != -y --> x+y != 0 17086static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) { 17087 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 17088 SDValue LHS = N->getOperand(0); 17089 SDValue RHS = N->getOperand(1); 17090 17091 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB) 17092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0))) 17093 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) { 17094 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(), 17095 LHS.getValueType(), RHS, LHS.getOperand(1)); 17096 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0), 17097 addV, DAG.getConstant(0, addV.getValueType()), CC); 17098 } 17099 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB) 17100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0))) 17101 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) { 17102 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(), 17103 RHS.getValueType(), LHS, RHS.getOperand(1)); 17104 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0), 17105 addV, DAG.getConstant(0, addV.getValueType()), CC); 17106 } 17107 return SDValue(); 17108} 17109 17110// Helper function of PerformSETCCCombine. It is to materialize "setb reg" 17111// as "sbb reg,reg", since it can be extended without zext and produces 17112// an all-ones bit which is more useful than 0/1 in some cases. 17113static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) { 17114 return DAG.getNode(ISD::AND, DL, MVT::i8, 17115 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8, 17116 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS), 17117 DAG.getConstant(1, MVT::i8)); 17118} 17119 17120// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT 17121static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG, 17122 TargetLowering::DAGCombinerInfo &DCI, 17123 const X86Subtarget *Subtarget) { 17124 DebugLoc DL = N->getDebugLoc(); 17125 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0)); 17126 SDValue EFLAGS = N->getOperand(1); 17127 17128 if (CC == X86::COND_A) { 17129 // Try to convert COND_A into COND_B in an attempt to facilitate 17130 // materializing "setb reg". 17131 // 17132 // Do not flip "e > c", where "c" is a constant, because Cmp instruction 17133 // cannot take an immediate as its first operand. 17134 // 17135 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() && 17136 EFLAGS.getValueType().isInteger() && 17137 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) { 17138 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(), 17139 EFLAGS.getNode()->getVTList(), 17140 EFLAGS.getOperand(1), EFLAGS.getOperand(0)); 17141 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo()); 17142 return MaterializeSETB(DL, NewEFLAGS, DAG); 17143 } 17144 } 17145 17146 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without 17147 // a zext and produces an all-ones bit which is more useful than 0/1 in some 17148 // cases. 17149 if (CC == X86::COND_B) 17150 return MaterializeSETB(DL, EFLAGS, DAG); 17151 17152 SDValue Flags; 17153 17154 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 17155 if (Flags.getNode()) { 17156 SDValue Cond = DAG.getConstant(CC, MVT::i8); 17157 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags); 17158 } 17159 17160 return SDValue(); 17161} 17162 17163// Optimize branch condition evaluation. 17164// 17165static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG, 17166 TargetLowering::DAGCombinerInfo &DCI, 17167 const X86Subtarget *Subtarget) { 17168 DebugLoc DL = N->getDebugLoc(); 17169 SDValue Chain = N->getOperand(0); 17170 SDValue Dest = N->getOperand(1); 17171 SDValue EFLAGS = N->getOperand(3); 17172 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2)); 17173 17174 SDValue Flags; 17175 17176 Flags = checkBoolTestSetCCCombine(EFLAGS, CC); 17177 if (Flags.getNode()) { 17178 SDValue Cond = DAG.getConstant(CC, MVT::i8); 17179 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond, 17180 Flags); 17181 } 17182 17183 return SDValue(); 17184} 17185 17186static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG, 17187 const X86TargetLowering *XTLI) { 17188 SDValue Op0 = N->getOperand(0); 17189 EVT InVT = Op0->getValueType(0); 17190 17191 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32)) 17192 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) { 17193 DebugLoc dl = N->getDebugLoc(); 17194 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32; 17195 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0); 17196 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P); 17197 } 17198 17199 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have 17200 // a 32-bit target where SSE doesn't support i64->FP operations. 17201 if (Op0.getOpcode() == ISD::LOAD) { 17202 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode()); 17203 EVT VT = Ld->getValueType(0); 17204 if (!Ld->isVolatile() && !N->getValueType(0).isVector() && 17205 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() && 17206 !XTLI->getSubtarget()->is64Bit() && 17207 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) { 17208 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0), 17209 Ld->getChain(), Op0, DAG); 17210 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1)); 17211 return FILDChain; 17212 } 17213 } 17214 return SDValue(); 17215} 17216 17217// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS 17218static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG, 17219 X86TargetLowering::DAGCombinerInfo &DCI) { 17220 // If the LHS and RHS of the ADC node are zero, then it can't overflow and 17221 // the result is either zero or one (depending on the input carry bit). 17222 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1. 17223 if (X86::isZeroNode(N->getOperand(0)) && 17224 X86::isZeroNode(N->getOperand(1)) && 17225 // We don't have a good way to replace an EFLAGS use, so only do this when 17226 // dead right now. 17227 SDValue(N, 1).use_empty()) { 17228 DebugLoc DL = N->getDebugLoc(); 17229 EVT VT = N->getValueType(0); 17230 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1)); 17231 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT, 17232 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, 17233 DAG.getConstant(X86::COND_B,MVT::i8), 17234 N->getOperand(2)), 17235 DAG.getConstant(1, VT)); 17236 return DCI.CombineTo(N, Res1, CarryOut); 17237 } 17238 17239 return SDValue(); 17240} 17241 17242// fold (add Y, (sete X, 0)) -> adc 0, Y 17243// (add Y, (setne X, 0)) -> sbb -1, Y 17244// (sub (sete X, 0), Y) -> sbb 0, Y 17245// (sub (setne X, 0), Y) -> adc -1, Y 17246static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) { 17247 DebugLoc DL = N->getDebugLoc(); 17248 17249 // Look through ZExts. 17250 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0); 17251 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse()) 17252 return SDValue(); 17253 17254 SDValue SetCC = Ext.getOperand(0); 17255 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse()) 17256 return SDValue(); 17257 17258 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0); 17259 if (CC != X86::COND_E && CC != X86::COND_NE) 17260 return SDValue(); 17261 17262 SDValue Cmp = SetCC.getOperand(1); 17263 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() || 17264 !X86::isZeroNode(Cmp.getOperand(1)) || 17265 !Cmp.getOperand(0).getValueType().isInteger()) 17266 return SDValue(); 17267 17268 SDValue CmpOp0 = Cmp.getOperand(0); 17269 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0, 17270 DAG.getConstant(1, CmpOp0.getValueType())); 17271 17272 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1); 17273 if (CC == X86::COND_NE) 17274 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB, 17275 DL, OtherVal.getValueType(), OtherVal, 17276 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp); 17277 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC, 17278 DL, OtherVal.getValueType(), OtherVal, 17279 DAG.getConstant(0, OtherVal.getValueType()), NewCmp); 17280} 17281 17282/// PerformADDCombine - Do target-specific dag combines on integer adds. 17283static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG, 17284 const X86Subtarget *Subtarget) { 17285 EVT VT = N->getValueType(0); 17286 SDValue Op0 = N->getOperand(0); 17287 SDValue Op1 = N->getOperand(1); 17288 17289 // Try to synthesize horizontal adds from adds of shuffles. 17290 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 17291 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 17292 isHorizontalBinOp(Op0, Op1, true)) 17293 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1); 17294 17295 return OptimizeConditionalInDecrement(N, DAG); 17296} 17297 17298static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG, 17299 const X86Subtarget *Subtarget) { 17300 SDValue Op0 = N->getOperand(0); 17301 SDValue Op1 = N->getOperand(1); 17302 17303 // X86 can't encode an immediate LHS of a sub. See if we can push the 17304 // negation into a preceding instruction. 17305 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) { 17306 // If the RHS of the sub is a XOR with one use and a constant, invert the 17307 // immediate. Then add one to the LHS of the sub so we can turn 17308 // X-Y -> X+~Y+1, saving one register. 17309 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR && 17310 isa<ConstantSDNode>(Op1.getOperand(1))) { 17311 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue(); 17312 EVT VT = Op0.getValueType(); 17313 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT, 17314 Op1.getOperand(0), 17315 DAG.getConstant(~XorC, VT)); 17316 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor, 17317 DAG.getConstant(C->getAPIntValue()+1, VT)); 17318 } 17319 } 17320 17321 // Try to synthesize horizontal adds from adds of shuffles. 17322 EVT VT = N->getValueType(0); 17323 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) || 17324 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) && 17325 isHorizontalBinOp(Op0, Op1, true)) 17326 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1); 17327 17328 return OptimizeConditionalInDecrement(N, DAG); 17329} 17330 17331/// performVZEXTCombine - Performs build vector combines 17332static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG, 17333 TargetLowering::DAGCombinerInfo &DCI, 17334 const X86Subtarget *Subtarget) { 17335 // (vzext (bitcast (vzext (x)) -> (vzext x) 17336 SDValue In = N->getOperand(0); 17337 while (In.getOpcode() == ISD::BITCAST) 17338 In = In.getOperand(0); 17339 17340 if (In.getOpcode() != X86ISD::VZEXT) 17341 return SDValue(); 17342 17343 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0)); 17344} 17345 17346SDValue X86TargetLowering::PerformDAGCombine(SDNode *N, 17347 DAGCombinerInfo &DCI) const { 17348 SelectionDAG &DAG = DCI.DAG; 17349 switch (N->getOpcode()) { 17350 default: break; 17351 case ISD::EXTRACT_VECTOR_ELT: 17352 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI); 17353 case ISD::VSELECT: 17354 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget); 17355 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget); 17356 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget); 17357 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget); 17358 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI); 17359 case ISD::MUL: return PerformMulCombine(N, DAG, DCI); 17360 case ISD::SHL: 17361 case ISD::SRA: 17362 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget); 17363 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget); 17364 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget); 17365 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget); 17366 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget); 17367 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget); 17368 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this); 17369 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget); 17370 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget); 17371 case X86ISD::FXOR: 17372 case X86ISD::FOR: return PerformFORCombine(N, DAG); 17373 case X86ISD::FMIN: 17374 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG); 17375 case X86ISD::FAND: return PerformFANDCombine(N, DAG); 17376 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI); 17377 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG); 17378 case ISD::ANY_EXTEND: 17379 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget); 17380 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget); 17381 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget); 17382 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG); 17383 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget); 17384 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget); 17385 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget); 17386 case X86ISD::SHUFP: // Handle all target specific shuffles 17387 case X86ISD::PALIGN: 17388 case X86ISD::UNPCKH: 17389 case X86ISD::UNPCKL: 17390 case X86ISD::MOVHLPS: 17391 case X86ISD::MOVLHPS: 17392 case X86ISD::PSHUFD: 17393 case X86ISD::PSHUFHW: 17394 case X86ISD::PSHUFLW: 17395 case X86ISD::MOVSS: 17396 case X86ISD::MOVSD: 17397 case X86ISD::VPERMILP: 17398 case X86ISD::VPERM2X128: 17399 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget); 17400 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget); 17401 } 17402 17403 return SDValue(); 17404} 17405 17406/// isTypeDesirableForOp - Return true if the target has native support for 17407/// the specified value type and it is 'desirable' to use the type for the 17408/// given node type. e.g. On x86 i16 is legal, but undesirable since i16 17409/// instruction encodings are longer and some i16 instructions are slow. 17410bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const { 17411 if (!isTypeLegal(VT)) 17412 return false; 17413 if (VT != MVT::i16) 17414 return true; 17415 17416 switch (Opc) { 17417 default: 17418 return true; 17419 case ISD::LOAD: 17420 case ISD::SIGN_EXTEND: 17421 case ISD::ZERO_EXTEND: 17422 case ISD::ANY_EXTEND: 17423 case ISD::SHL: 17424 case ISD::SRL: 17425 case ISD::SUB: 17426 case ISD::ADD: 17427 case ISD::MUL: 17428 case ISD::AND: 17429 case ISD::OR: 17430 case ISD::XOR: 17431 return false; 17432 } 17433} 17434 17435/// IsDesirableToPromoteOp - This method query the target whether it is 17436/// beneficial for dag combiner to promote the specified node. If true, it 17437/// should return the desired promotion type by reference. 17438bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 17439 EVT VT = Op.getValueType(); 17440 if (VT != MVT::i16) 17441 return false; 17442 17443 bool Promote = false; 17444 bool Commute = false; 17445 switch (Op.getOpcode()) { 17446 default: break; 17447 case ISD::LOAD: { 17448 LoadSDNode *LD = cast<LoadSDNode>(Op); 17449 // If the non-extending load has a single use and it's not live out, then it 17450 // might be folded. 17451 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&& 17452 Op.hasOneUse()*/) { 17453 for (SDNode::use_iterator UI = Op.getNode()->use_begin(), 17454 UE = Op.getNode()->use_end(); UI != UE; ++UI) { 17455 // The only case where we'd want to promote LOAD (rather then it being 17456 // promoted as an operand is when it's only use is liveout. 17457 if (UI->getOpcode() != ISD::CopyToReg) 17458 return false; 17459 } 17460 } 17461 Promote = true; 17462 break; 17463 } 17464 case ISD::SIGN_EXTEND: 17465 case ISD::ZERO_EXTEND: 17466 case ISD::ANY_EXTEND: 17467 Promote = true; 17468 break; 17469 case ISD::SHL: 17470 case ISD::SRL: { 17471 SDValue N0 = Op.getOperand(0); 17472 // Look out for (store (shl (load), x)). 17473 if (MayFoldLoad(N0) && MayFoldIntoStore(Op)) 17474 return false; 17475 Promote = true; 17476 break; 17477 } 17478 case ISD::ADD: 17479 case ISD::MUL: 17480 case ISD::AND: 17481 case ISD::OR: 17482 case ISD::XOR: 17483 Commute = true; 17484 // fallthrough 17485 case ISD::SUB: { 17486 SDValue N0 = Op.getOperand(0); 17487 SDValue N1 = Op.getOperand(1); 17488 if (!Commute && MayFoldLoad(N1)) 17489 return false; 17490 // Avoid disabling potential load folding opportunities. 17491 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op))) 17492 return false; 17493 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op))) 17494 return false; 17495 Promote = true; 17496 } 17497 } 17498 17499 PVT = MVT::i32; 17500 return Promote; 17501} 17502 17503//===----------------------------------------------------------------------===// 17504// X86 Inline Assembly Support 17505//===----------------------------------------------------------------------===// 17506 17507namespace { 17508 // Helper to match a string separated by whitespace. 17509 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) { 17510 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace. 17511 17512 for (unsigned i = 0, e = args.size(); i != e; ++i) { 17513 StringRef piece(*args[i]); 17514 if (!s.startswith(piece)) // Check if the piece matches. 17515 return false; 17516 17517 s = s.substr(piece.size()); 17518 StringRef::size_type pos = s.find_first_not_of(" \t"); 17519 if (pos == 0) // We matched a prefix. 17520 return false; 17521 17522 s = s.substr(pos); 17523 } 17524 17525 return s.empty(); 17526 } 17527 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={}; 17528} 17529 17530bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const { 17531 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue()); 17532 17533 std::string AsmStr = IA->getAsmString(); 17534 17535 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType()); 17536 if (!Ty || Ty->getBitWidth() % 16 != 0) 17537 return false; 17538 17539 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a" 17540 SmallVector<StringRef, 4> AsmPieces; 17541 SplitString(AsmStr, AsmPieces, ";\n"); 17542 17543 switch (AsmPieces.size()) { 17544 default: return false; 17545 case 1: 17546 // FIXME: this should verify that we are targeting a 486 or better. If not, 17547 // we will turn this bswap into something that will be lowered to logical 17548 // ops instead of emitting the bswap asm. For now, we don't support 486 or 17549 // lower so don't worry about this. 17550 // bswap $0 17551 if (matchAsm(AsmPieces[0], "bswap", "$0") || 17552 matchAsm(AsmPieces[0], "bswapl", "$0") || 17553 matchAsm(AsmPieces[0], "bswapq", "$0") || 17554 matchAsm(AsmPieces[0], "bswap", "${0:q}") || 17555 matchAsm(AsmPieces[0], "bswapl", "${0:q}") || 17556 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) { 17557 // No need to check constraints, nothing other than the equivalent of 17558 // "=r,0" would be valid here. 17559 return IntrinsicLowering::LowerToByteSwap(CI); 17560 } 17561 17562 // rorw $$8, ${0:w} --> llvm.bswap.i16 17563 if (CI->getType()->isIntegerTy(16) && 17564 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 17565 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") || 17566 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) { 17567 AsmPieces.clear(); 17568 const std::string &ConstraintsStr = IA->getConstraintString(); 17569 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 17570 std::sort(AsmPieces.begin(), AsmPieces.end()); 17571 if (AsmPieces.size() == 4 && 17572 AsmPieces[0] == "~{cc}" && 17573 AsmPieces[1] == "~{dirflag}" && 17574 AsmPieces[2] == "~{flags}" && 17575 AsmPieces[3] == "~{fpsr}") 17576 return IntrinsicLowering::LowerToByteSwap(CI); 17577 } 17578 break; 17579 case 3: 17580 if (CI->getType()->isIntegerTy(32) && 17581 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 && 17582 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") && 17583 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") && 17584 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) { 17585 AsmPieces.clear(); 17586 const std::string &ConstraintsStr = IA->getConstraintString(); 17587 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ","); 17588 std::sort(AsmPieces.begin(), AsmPieces.end()); 17589 if (AsmPieces.size() == 4 && 17590 AsmPieces[0] == "~{cc}" && 17591 AsmPieces[1] == "~{dirflag}" && 17592 AsmPieces[2] == "~{flags}" && 17593 AsmPieces[3] == "~{fpsr}") 17594 return IntrinsicLowering::LowerToByteSwap(CI); 17595 } 17596 17597 if (CI->getType()->isIntegerTy(64)) { 17598 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); 17599 if (Constraints.size() >= 2 && 17600 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" && 17601 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") { 17602 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64 17603 if (matchAsm(AsmPieces[0], "bswap", "%eax") && 17604 matchAsm(AsmPieces[1], "bswap", "%edx") && 17605 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx")) 17606 return IntrinsicLowering::LowerToByteSwap(CI); 17607 } 17608 } 17609 break; 17610 } 17611 return false; 17612} 17613 17614/// getConstraintType - Given a constraint letter, return the type of 17615/// constraint it is for this target. 17616X86TargetLowering::ConstraintType 17617X86TargetLowering::getConstraintType(const std::string &Constraint) const { 17618 if (Constraint.size() == 1) { 17619 switch (Constraint[0]) { 17620 case 'R': 17621 case 'q': 17622 case 'Q': 17623 case 'f': 17624 case 't': 17625 case 'u': 17626 case 'y': 17627 case 'x': 17628 case 'Y': 17629 case 'l': 17630 return C_RegisterClass; 17631 case 'a': 17632 case 'b': 17633 case 'c': 17634 case 'd': 17635 case 'S': 17636 case 'D': 17637 case 'A': 17638 return C_Register; 17639 case 'I': 17640 case 'J': 17641 case 'K': 17642 case 'L': 17643 case 'M': 17644 case 'N': 17645 case 'G': 17646 case 'C': 17647 case 'e': 17648 case 'Z': 17649 return C_Other; 17650 default: 17651 break; 17652 } 17653 } 17654 return TargetLowering::getConstraintType(Constraint); 17655} 17656 17657/// Examine constraint type and operand type and determine a weight value. 17658/// This object must already have been set up with the operand type 17659/// and the current alternative constraint selected. 17660TargetLowering::ConstraintWeight 17661 X86TargetLowering::getSingleConstraintMatchWeight( 17662 AsmOperandInfo &info, const char *constraint) const { 17663 ConstraintWeight weight = CW_Invalid; 17664 Value *CallOperandVal = info.CallOperandVal; 17665 // If we don't have a value, we can't do a match, 17666 // but allow it at the lowest weight. 17667 if (CallOperandVal == NULL) 17668 return CW_Default; 17669 Type *type = CallOperandVal->getType(); 17670 // Look at the constraint type. 17671 switch (*constraint) { 17672 default: 17673 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 17674 case 'R': 17675 case 'q': 17676 case 'Q': 17677 case 'a': 17678 case 'b': 17679 case 'c': 17680 case 'd': 17681 case 'S': 17682 case 'D': 17683 case 'A': 17684 if (CallOperandVal->getType()->isIntegerTy()) 17685 weight = CW_SpecificReg; 17686 break; 17687 case 'f': 17688 case 't': 17689 case 'u': 17690 if (type->isFloatingPointTy()) 17691 weight = CW_SpecificReg; 17692 break; 17693 case 'y': 17694 if (type->isX86_MMXTy() && Subtarget->hasMMX()) 17695 weight = CW_SpecificReg; 17696 break; 17697 case 'x': 17698 case 'Y': 17699 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) || 17700 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256())) 17701 weight = CW_Register; 17702 break; 17703 case 'I': 17704 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) { 17705 if (C->getZExtValue() <= 31) 17706 weight = CW_Constant; 17707 } 17708 break; 17709 case 'J': 17710 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17711 if (C->getZExtValue() <= 63) 17712 weight = CW_Constant; 17713 } 17714 break; 17715 case 'K': 17716 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17717 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f)) 17718 weight = CW_Constant; 17719 } 17720 break; 17721 case 'L': 17722 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17723 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff)) 17724 weight = CW_Constant; 17725 } 17726 break; 17727 case 'M': 17728 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17729 if (C->getZExtValue() <= 3) 17730 weight = CW_Constant; 17731 } 17732 break; 17733 case 'N': 17734 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17735 if (C->getZExtValue() <= 0xff) 17736 weight = CW_Constant; 17737 } 17738 break; 17739 case 'G': 17740 case 'C': 17741 if (dyn_cast<ConstantFP>(CallOperandVal)) { 17742 weight = CW_Constant; 17743 } 17744 break; 17745 case 'e': 17746 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17747 if ((C->getSExtValue() >= -0x80000000LL) && 17748 (C->getSExtValue() <= 0x7fffffffLL)) 17749 weight = CW_Constant; 17750 } 17751 break; 17752 case 'Z': 17753 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) { 17754 if (C->getZExtValue() <= 0xffffffff) 17755 weight = CW_Constant; 17756 } 17757 break; 17758 } 17759 return weight; 17760} 17761 17762/// LowerXConstraint - try to replace an X constraint, which matches anything, 17763/// with another that has more specific requirements based on the type of the 17764/// corresponding operand. 17765const char *X86TargetLowering:: 17766LowerXConstraint(EVT ConstraintVT) const { 17767 // FP X constraints get lowered to SSE1/2 registers if available, otherwise 17768 // 'f' like normal targets. 17769 if (ConstraintVT.isFloatingPoint()) { 17770 if (Subtarget->hasSSE2()) 17771 return "Y"; 17772 if (Subtarget->hasSSE1()) 17773 return "x"; 17774 } 17775 17776 return TargetLowering::LowerXConstraint(ConstraintVT); 17777} 17778 17779/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 17780/// vector. If it is invalid, don't add anything to Ops. 17781void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 17782 std::string &Constraint, 17783 std::vector<SDValue>&Ops, 17784 SelectionDAG &DAG) const { 17785 SDValue Result(0, 0); 17786 17787 // Only support length 1 constraints for now. 17788 if (Constraint.length() > 1) return; 17789 17790 char ConstraintLetter = Constraint[0]; 17791 switch (ConstraintLetter) { 17792 default: break; 17793 case 'I': 17794 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17795 if (C->getZExtValue() <= 31) { 17796 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 17797 break; 17798 } 17799 } 17800 return; 17801 case 'J': 17802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17803 if (C->getZExtValue() <= 63) { 17804 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 17805 break; 17806 } 17807 } 17808 return; 17809 case 'K': 17810 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17811 if (isInt<8>(C->getSExtValue())) { 17812 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 17813 break; 17814 } 17815 } 17816 return; 17817 case 'N': 17818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17819 if (C->getZExtValue() <= 255) { 17820 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 17821 break; 17822 } 17823 } 17824 return; 17825 case 'e': { 17826 // 32-bit signed value 17827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17828 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 17829 C->getSExtValue())) { 17830 // Widen to 64 bits here to get it sign extended. 17831 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64); 17832 break; 17833 } 17834 // FIXME gcc accepts some relocatable values here too, but only in certain 17835 // memory models; it's complicated. 17836 } 17837 return; 17838 } 17839 case 'Z': { 17840 // 32-bit unsigned value 17841 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 17842 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()), 17843 C->getZExtValue())) { 17844 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType()); 17845 break; 17846 } 17847 } 17848 // FIXME gcc accepts some relocatable values here too, but only in certain 17849 // memory models; it's complicated. 17850 return; 17851 } 17852 case 'i': { 17853 // Literal immediates are always ok. 17854 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) { 17855 // Widen to 64 bits here to get it sign extended. 17856 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64); 17857 break; 17858 } 17859 17860 // In any sort of PIC mode addresses need to be computed at runtime by 17861 // adding in a register or some sort of table lookup. These can't 17862 // be used as immediates. 17863 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC()) 17864 return; 17865 17866 // If we are in non-pic codegen mode, we allow the address of a global (with 17867 // an optional displacement) to be used with 'i'. 17868 GlobalAddressSDNode *GA = 0; 17869 int64_t Offset = 0; 17870 17871 // Match either (GA), (GA+C), (GA+C1+C2), etc. 17872 while (1) { 17873 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) { 17874 Offset += GA->getOffset(); 17875 break; 17876 } else if (Op.getOpcode() == ISD::ADD) { 17877 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 17878 Offset += C->getZExtValue(); 17879 Op = Op.getOperand(0); 17880 continue; 17881 } 17882 } else if (Op.getOpcode() == ISD::SUB) { 17883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 17884 Offset += -C->getZExtValue(); 17885 Op = Op.getOperand(0); 17886 continue; 17887 } 17888 } 17889 17890 // Otherwise, this isn't something we can handle, reject it. 17891 return; 17892 } 17893 17894 const GlobalValue *GV = GA->getGlobal(); 17895 // If we require an extra load to get this address, as in PIC mode, we 17896 // can't accept it. 17897 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV, 17898 getTargetMachine()))) 17899 return; 17900 17901 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), 17902 GA->getValueType(0), Offset); 17903 break; 17904 } 17905 } 17906 17907 if (Result.getNode()) { 17908 Ops.push_back(Result); 17909 return; 17910 } 17911 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 17912} 17913 17914std::pair<unsigned, const TargetRegisterClass*> 17915X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint, 17916 EVT VT) const { 17917 // First, see if this is a constraint that directly corresponds to an LLVM 17918 // register class. 17919 if (Constraint.size() == 1) { 17920 // GCC Constraint Letters 17921 switch (Constraint[0]) { 17922 default: break; 17923 // TODO: Slight differences here in allocation order and leaving 17924 // RIP in the class. Do they matter any more here than they do 17925 // in the normal allocation? 17926 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode. 17927 if (Subtarget->is64Bit()) { 17928 if (VT == MVT::i32 || VT == MVT::f32) 17929 return std::make_pair(0U, &X86::GR32RegClass); 17930 if (VT == MVT::i16) 17931 return std::make_pair(0U, &X86::GR16RegClass); 17932 if (VT == MVT::i8 || VT == MVT::i1) 17933 return std::make_pair(0U, &X86::GR8RegClass); 17934 if (VT == MVT::i64 || VT == MVT::f64) 17935 return std::make_pair(0U, &X86::GR64RegClass); 17936 break; 17937 } 17938 // 32-bit fallthrough 17939 case 'Q': // Q_REGS 17940 if (VT == MVT::i32 || VT == MVT::f32) 17941 return std::make_pair(0U, &X86::GR32_ABCDRegClass); 17942 if (VT == MVT::i16) 17943 return std::make_pair(0U, &X86::GR16_ABCDRegClass); 17944 if (VT == MVT::i8 || VT == MVT::i1) 17945 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass); 17946 if (VT == MVT::i64) 17947 return std::make_pair(0U, &X86::GR64_ABCDRegClass); 17948 break; 17949 case 'r': // GENERAL_REGS 17950 case 'l': // INDEX_REGS 17951 if (VT == MVT::i8 || VT == MVT::i1) 17952 return std::make_pair(0U, &X86::GR8RegClass); 17953 if (VT == MVT::i16) 17954 return std::make_pair(0U, &X86::GR16RegClass); 17955 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit()) 17956 return std::make_pair(0U, &X86::GR32RegClass); 17957 return std::make_pair(0U, &X86::GR64RegClass); 17958 case 'R': // LEGACY_REGS 17959 if (VT == MVT::i8 || VT == MVT::i1) 17960 return std::make_pair(0U, &X86::GR8_NOREXRegClass); 17961 if (VT == MVT::i16) 17962 return std::make_pair(0U, &X86::GR16_NOREXRegClass); 17963 if (VT == MVT::i32 || !Subtarget->is64Bit()) 17964 return std::make_pair(0U, &X86::GR32_NOREXRegClass); 17965 return std::make_pair(0U, &X86::GR64_NOREXRegClass); 17966 case 'f': // FP Stack registers. 17967 // If SSE is enabled for this VT, use f80 to ensure the isel moves the 17968 // value to the correct fpstack register class. 17969 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT)) 17970 return std::make_pair(0U, &X86::RFP32RegClass); 17971 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT)) 17972 return std::make_pair(0U, &X86::RFP64RegClass); 17973 return std::make_pair(0U, &X86::RFP80RegClass); 17974 case 'y': // MMX_REGS if MMX allowed. 17975 if (!Subtarget->hasMMX()) break; 17976 return std::make_pair(0U, &X86::VR64RegClass); 17977 case 'Y': // SSE_REGS if SSE2 allowed 17978 if (!Subtarget->hasSSE2()) break; 17979 // FALL THROUGH. 17980 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed 17981 if (!Subtarget->hasSSE1()) break; 17982 17983 switch (VT.getSimpleVT().SimpleTy) { 17984 default: break; 17985 // Scalar SSE types. 17986 case MVT::f32: 17987 case MVT::i32: 17988 return std::make_pair(0U, &X86::FR32RegClass); 17989 case MVT::f64: 17990 case MVT::i64: 17991 return std::make_pair(0U, &X86::FR64RegClass); 17992 // Vector types. 17993 case MVT::v16i8: 17994 case MVT::v8i16: 17995 case MVT::v4i32: 17996 case MVT::v2i64: 17997 case MVT::v4f32: 17998 case MVT::v2f64: 17999 return std::make_pair(0U, &X86::VR128RegClass); 18000 // AVX types. 18001 case MVT::v32i8: 18002 case MVT::v16i16: 18003 case MVT::v8i32: 18004 case MVT::v4i64: 18005 case MVT::v8f32: 18006 case MVT::v4f64: 18007 return std::make_pair(0U, &X86::VR256RegClass); 18008 } 18009 break; 18010 } 18011 } 18012 18013 // Use the default implementation in TargetLowering to convert the register 18014 // constraint into a member of a register class. 18015 std::pair<unsigned, const TargetRegisterClass*> Res; 18016 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT); 18017 18018 // Not found as a standard register? 18019 if (Res.second == 0) { 18020 // Map st(0) -> st(7) -> ST0 18021 if (Constraint.size() == 7 && Constraint[0] == '{' && 18022 tolower(Constraint[1]) == 's' && 18023 tolower(Constraint[2]) == 't' && 18024 Constraint[3] == '(' && 18025 (Constraint[4] >= '0' && Constraint[4] <= '7') && 18026 Constraint[5] == ')' && 18027 Constraint[6] == '}') { 18028 18029 Res.first = X86::ST0+Constraint[4]-'0'; 18030 Res.second = &X86::RFP80RegClass; 18031 return Res; 18032 } 18033 18034 // GCC allows "st(0)" to be called just plain "st". 18035 if (StringRef("{st}").equals_lower(Constraint)) { 18036 Res.first = X86::ST0; 18037 Res.second = &X86::RFP80RegClass; 18038 return Res; 18039 } 18040 18041 // flags -> EFLAGS 18042 if (StringRef("{flags}").equals_lower(Constraint)) { 18043 Res.first = X86::EFLAGS; 18044 Res.second = &X86::CCRRegClass; 18045 return Res; 18046 } 18047 18048 // 'A' means EAX + EDX. 18049 if (Constraint == "A") { 18050 Res.first = X86::EAX; 18051 Res.second = &X86::GR32_ADRegClass; 18052 return Res; 18053 } 18054 return Res; 18055 } 18056 18057 // Otherwise, check to see if this is a register class of the wrong value 18058 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to 18059 // turn into {ax},{dx}. 18060 if (Res.second->hasType(VT)) 18061 return Res; // Correct type already, nothing to do. 18062 18063 // All of the single-register GCC register classes map their values onto 18064 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we 18065 // really want an 8-bit or 32-bit register, map to the appropriate register 18066 // class and return the appropriate register. 18067 if (Res.second == &X86::GR16RegClass) { 18068 if (VT == MVT::i8) { 18069 unsigned DestReg = 0; 18070 switch (Res.first) { 18071 default: break; 18072 case X86::AX: DestReg = X86::AL; break; 18073 case X86::DX: DestReg = X86::DL; break; 18074 case X86::CX: DestReg = X86::CL; break; 18075 case X86::BX: DestReg = X86::BL; break; 18076 } 18077 if (DestReg) { 18078 Res.first = DestReg; 18079 Res.second = &X86::GR8RegClass; 18080 } 18081 } else if (VT == MVT::i32) { 18082 unsigned DestReg = 0; 18083 switch (Res.first) { 18084 default: break; 18085 case X86::AX: DestReg = X86::EAX; break; 18086 case X86::DX: DestReg = X86::EDX; break; 18087 case X86::CX: DestReg = X86::ECX; break; 18088 case X86::BX: DestReg = X86::EBX; break; 18089 case X86::SI: DestReg = X86::ESI; break; 18090 case X86::DI: DestReg = X86::EDI; break; 18091 case X86::BP: DestReg = X86::EBP; break; 18092 case X86::SP: DestReg = X86::ESP; break; 18093 } 18094 if (DestReg) { 18095 Res.first = DestReg; 18096 Res.second = &X86::GR32RegClass; 18097 } 18098 } else if (VT == MVT::i64) { 18099 unsigned DestReg = 0; 18100 switch (Res.first) { 18101 default: break; 18102 case X86::AX: DestReg = X86::RAX; break; 18103 case X86::DX: DestReg = X86::RDX; break; 18104 case X86::CX: DestReg = X86::RCX; break; 18105 case X86::BX: DestReg = X86::RBX; break; 18106 case X86::SI: DestReg = X86::RSI; break; 18107 case X86::DI: DestReg = X86::RDI; break; 18108 case X86::BP: DestReg = X86::RBP; break; 18109 case X86::SP: DestReg = X86::RSP; break; 18110 } 18111 if (DestReg) { 18112 Res.first = DestReg; 18113 Res.second = &X86::GR64RegClass; 18114 } 18115 } 18116 } else if (Res.second == &X86::FR32RegClass || 18117 Res.second == &X86::FR64RegClass || 18118 Res.second == &X86::VR128RegClass) { 18119 // Handle references to XMM physical registers that got mapped into the 18120 // wrong class. This can happen with constraints like {xmm0} where the 18121 // target independent register mapper will just pick the first match it can 18122 // find, ignoring the required type. 18123 18124 if (VT == MVT::f32 || VT == MVT::i32) 18125 Res.second = &X86::FR32RegClass; 18126 else if (VT == MVT::f64 || VT == MVT::i64) 18127 Res.second = &X86::FR64RegClass; 18128 else if (X86::VR128RegClass.hasType(VT)) 18129 Res.second = &X86::VR128RegClass; 18130 else if (X86::VR256RegClass.hasType(VT)) 18131 Res.second = &X86::VR256RegClass; 18132 } 18133 18134 return Res; 18135} 18136