1 //===-- PPCISelLowering.cpp - PPC 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 implements the PPCISelLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCISelLowering.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCCCState.h" 18 #include "PPCCallingConv.h" 19 #include "PPCFrameLowering.h" 20 #include "PPCInstrInfo.h" 21 #include "PPCMachineFunctionInfo.h" 22 #include "PPCPerfectShuffle.h" 23 #include "PPCRegisterInfo.h" 24 #include "PPCSubtarget.h" 25 #include "PPCTargetMachine.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/ADT/APInt.h" 28 #include "llvm/ADT/ArrayRef.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/None.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/CodeGen/CallingConvLower.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineLoopInfo.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/MachineValueType.h" 51 #include "llvm/CodeGen/RuntimeLibcalls.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/TargetInstrInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/CallSite.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/Module.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/MC/MCExpr.h" 73 #include "llvm/MC/MCRegisterInfo.h" 74 #include "llvm/Support/AtomicOrdering.h" 75 #include "llvm/Support/BranchProbability.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CodeGen.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/Format.h" 83 #include "llvm/Support/KnownBits.h" 84 #include "llvm/Support/MathExtras.h" 85 #include "llvm/Support/raw_ostream.h" 86 #include "llvm/Target/TargetLowering.h" 87 #include "llvm/Target/TargetMachine.h" 88 #include "llvm/Target/TargetOptions.h" 89 #include "llvm/Target/TargetRegisterInfo.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <list> 95 #include <utility> 96 #include <vector> 97 98 using namespace llvm; 99 100 #define DEBUG_TYPE "ppc-lowering" 101 102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 104 105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 107 108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 110 111 static cl::opt<bool> DisableSCO("disable-ppc-sco", 112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 113 114 STATISTIC(NumTailCalls, "Number of tail calls"); 115 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 116 117 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 118 119 // FIXME: Remove this once the bug has been fixed! 120 extern cl::opt<bool> ANDIGlueBug; 121 122 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 123 const PPCSubtarget &STI) 124 : TargetLowering(TM), Subtarget(STI) { 125 // Use _setjmp/_longjmp instead of setjmp/longjmp. 126 setUseUnderscoreSetJmp(true); 127 setUseUnderscoreLongJmp(true); 128 129 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 130 // arguments are at least 4/8 bytes aligned. 131 bool isPPC64 = Subtarget.isPPC64(); 132 setMinStackArgumentAlignment(isPPC64 ? 8:4); 133 134 // Set up the register classes. 135 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 136 if (!useSoftFloat()) { 137 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 138 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 139 } 140 141 // Match BITREVERSE to customized fast code sequence in the td file. 142 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 143 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 144 145 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 146 for (MVT VT : MVT::integer_valuetypes()) { 147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 148 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 149 } 150 151 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 152 153 // PowerPC has pre-inc load and store's. 154 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 155 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 156 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 157 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 158 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 159 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 160 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 161 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 162 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 163 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 164 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 165 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 166 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 167 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 168 169 if (Subtarget.useCRBits()) { 170 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 171 172 if (isPPC64 || Subtarget.hasFPCVT()) { 173 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 174 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 175 isPPC64 ? MVT::i64 : MVT::i32); 176 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 177 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 178 isPPC64 ? MVT::i64 : MVT::i32); 179 } else { 180 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 181 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 182 } 183 184 // PowerPC does not support direct load/store of condition registers. 185 setOperationAction(ISD::LOAD, MVT::i1, Custom); 186 setOperationAction(ISD::STORE, MVT::i1, Custom); 187 188 // FIXME: Remove this once the ANDI glue bug is fixed: 189 if (ANDIGlueBug) 190 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 191 192 for (MVT VT : MVT::integer_valuetypes()) { 193 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 194 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 195 setTruncStoreAction(VT, MVT::i1, Expand); 196 } 197 198 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 199 } 200 201 // This is used in the ppcf128->int sequence. Note it has different semantics 202 // from FP_ROUND: that rounds to nearest, this rounds to zero. 203 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); 204 205 // We do not currently implement these libm ops for PowerPC. 206 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 207 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 208 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 209 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 210 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 211 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 212 213 // PowerPC has no SREM/UREM instructions unless we are on P9 214 // On P9 we may use a hardware instruction to compute the remainder. 215 // The instructions are not legalized directly because in the cases where the 216 // result of both the remainder and the division is required it is more 217 // efficient to compute the remainder from the result of the division rather 218 // than use the remainder instruction. 219 if (Subtarget.isISA3_0()) { 220 setOperationAction(ISD::SREM, MVT::i32, Custom); 221 setOperationAction(ISD::UREM, MVT::i32, Custom); 222 setOperationAction(ISD::SREM, MVT::i64, Custom); 223 setOperationAction(ISD::UREM, MVT::i64, Custom); 224 } else { 225 setOperationAction(ISD::SREM, MVT::i32, Expand); 226 setOperationAction(ISD::UREM, MVT::i32, Expand); 227 setOperationAction(ISD::SREM, MVT::i64, Expand); 228 setOperationAction(ISD::UREM, MVT::i64, Expand); 229 } 230 231 if (Subtarget.hasP9Vector()) { 232 setOperationAction(ISD::ABS, MVT::v4i32, Legal); 233 setOperationAction(ISD::ABS, MVT::v8i16, Legal); 234 setOperationAction(ISD::ABS, MVT::v16i8, Legal); 235 } 236 237 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 238 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 239 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 240 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 241 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 242 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 243 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 245 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 246 247 // We don't support sin/cos/sqrt/fmod/pow 248 setOperationAction(ISD::FSIN , MVT::f64, Expand); 249 setOperationAction(ISD::FCOS , MVT::f64, Expand); 250 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 251 setOperationAction(ISD::FREM , MVT::f64, Expand); 252 setOperationAction(ISD::FPOW , MVT::f64, Expand); 253 setOperationAction(ISD::FMA , MVT::f64, Legal); 254 setOperationAction(ISD::FSIN , MVT::f32, Expand); 255 setOperationAction(ISD::FCOS , MVT::f32, Expand); 256 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 257 setOperationAction(ISD::FREM , MVT::f32, Expand); 258 setOperationAction(ISD::FPOW , MVT::f32, Expand); 259 setOperationAction(ISD::FMA , MVT::f32, Legal); 260 261 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 262 263 // If we're enabling GP optimizations, use hardware square root 264 if (!Subtarget.hasFSQRT() && 265 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 266 Subtarget.hasFRE())) 267 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 268 269 if (!Subtarget.hasFSQRT() && 270 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 271 Subtarget.hasFRES())) 272 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 273 274 if (Subtarget.hasFCPSGN()) { 275 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 276 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 277 } else { 278 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 279 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 280 } 281 282 if (Subtarget.hasFPRND()) { 283 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 284 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 285 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 286 setOperationAction(ISD::FROUND, MVT::f64, Legal); 287 288 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 289 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 290 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 291 setOperationAction(ISD::FROUND, MVT::f32, Legal); 292 } 293 294 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 295 // to speed up scalar BSWAP64. 296 // CTPOP or CTTZ were introduced in P8/P9 respectivelly 297 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 298 if (Subtarget.isISA3_0()) { 299 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 300 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 301 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 302 } else { 303 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 304 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 305 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 306 } 307 308 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 309 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 310 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 311 } else { 312 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 313 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 314 } 315 316 // PowerPC does not have ROTR 317 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 318 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 319 320 if (!Subtarget.useCRBits()) { 321 // PowerPC does not have Select 322 setOperationAction(ISD::SELECT, MVT::i32, Expand); 323 setOperationAction(ISD::SELECT, MVT::i64, Expand); 324 setOperationAction(ISD::SELECT, MVT::f32, Expand); 325 setOperationAction(ISD::SELECT, MVT::f64, Expand); 326 } 327 328 // PowerPC wants to turn select_cc of FP into fsel when possible. 329 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 330 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 331 332 // PowerPC wants to optimize integer setcc a bit 333 if (!Subtarget.useCRBits()) 334 setOperationAction(ISD::SETCC, MVT::i32, Custom); 335 336 // PowerPC does not have BRCOND which requires SetCC 337 if (!Subtarget.useCRBits()) 338 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 339 340 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 341 342 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 343 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 344 345 // PowerPC does not have [U|S]INT_TO_FP 346 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 347 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 348 349 if (Subtarget.hasDirectMove() && isPPC64) { 350 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 351 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 352 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 353 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 354 } else { 355 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 356 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 357 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 358 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 359 } 360 361 // We cannot sextinreg(i1). Expand to shifts. 362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 363 364 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 365 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 366 // support continuation, user-level threading, and etc.. As a result, no 367 // other SjLj exception interfaces are implemented and please don't build 368 // your own exception handling based on them. 369 // LLVM/Clang supports zero-cost DWARF exception handling. 370 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 371 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 372 373 // We want to legalize GlobalAddress and ConstantPool nodes into the 374 // appropriate instructions to materialize the address. 375 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 376 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 377 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 378 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 379 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 380 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 381 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 382 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 383 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 384 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 385 386 // TRAP is legal. 387 setOperationAction(ISD::TRAP, MVT::Other, Legal); 388 389 // TRAMPOLINE is custom lowered. 390 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 391 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 392 393 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 394 setOperationAction(ISD::VASTART , MVT::Other, Custom); 395 396 if (Subtarget.isSVR4ABI()) { 397 if (isPPC64) { 398 // VAARG always uses double-word chunks, so promote anything smaller. 399 setOperationAction(ISD::VAARG, MVT::i1, Promote); 400 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 401 setOperationAction(ISD::VAARG, MVT::i8, Promote); 402 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 403 setOperationAction(ISD::VAARG, MVT::i16, Promote); 404 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 405 setOperationAction(ISD::VAARG, MVT::i32, Promote); 406 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 407 setOperationAction(ISD::VAARG, MVT::Other, Expand); 408 } else { 409 // VAARG is custom lowered with the 32-bit SVR4 ABI. 410 setOperationAction(ISD::VAARG, MVT::Other, Custom); 411 setOperationAction(ISD::VAARG, MVT::i64, Custom); 412 } 413 } else 414 setOperationAction(ISD::VAARG, MVT::Other, Expand); 415 416 if (Subtarget.isSVR4ABI() && !isPPC64) 417 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 418 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 419 else 420 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 421 422 // Use the default implementation. 423 setOperationAction(ISD::VAEND , MVT::Other, Expand); 424 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 425 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 427 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 428 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 429 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 430 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 431 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 432 433 // We want to custom lower some of our intrinsics. 434 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 435 436 // To handle counter-based loop conditions. 437 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 438 439 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 440 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 441 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 442 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 443 444 // Comparisons that require checking two conditions. 445 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 446 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 447 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 448 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 449 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 450 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 451 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 452 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 453 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 454 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 455 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 456 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 457 458 if (Subtarget.has64BitSupport()) { 459 // They also have instructions for converting between i64 and fp. 460 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 461 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 462 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 463 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 464 // This is just the low 32 bits of a (signed) fp->i64 conversion. 465 // We cannot do this with Promote because i64 is not a legal type. 466 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 467 468 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 469 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 470 } else { 471 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 472 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 473 } 474 475 // With the instructions enabled under FPCVT, we can do everything. 476 if (Subtarget.hasFPCVT()) { 477 if (Subtarget.has64BitSupport()) { 478 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 479 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 480 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 481 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 482 } 483 484 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 485 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 486 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 487 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 488 } 489 490 if (Subtarget.use64BitRegs()) { 491 // 64-bit PowerPC implementations can support i64 types directly 492 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 493 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 494 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 495 // 64-bit PowerPC wants to expand i128 shifts itself. 496 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 497 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 498 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 499 } else { 500 // 32-bit PowerPC wants to expand i64 shifts itself. 501 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 502 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 503 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 504 } 505 506 if (Subtarget.hasAltivec()) { 507 // First set operation action for all vector types to expand. Then we 508 // will selectively turn on ones that can be effectively codegen'd. 509 for (MVT VT : MVT::vector_valuetypes()) { 510 // add/sub are legal for all supported vector VT's. 511 setOperationAction(ISD::ADD, VT, Legal); 512 setOperationAction(ISD::SUB, VT, Legal); 513 514 // Vector instructions introduced in P8 515 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 516 setOperationAction(ISD::CTPOP, VT, Legal); 517 setOperationAction(ISD::CTLZ, VT, Legal); 518 } 519 else { 520 setOperationAction(ISD::CTPOP, VT, Expand); 521 setOperationAction(ISD::CTLZ, VT, Expand); 522 } 523 524 // Vector instructions introduced in P9 525 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 526 setOperationAction(ISD::CTTZ, VT, Legal); 527 else 528 setOperationAction(ISD::CTTZ, VT, Expand); 529 530 // We promote all shuffles to v16i8. 531 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 532 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 533 534 // We promote all non-typed operations to v4i32. 535 setOperationAction(ISD::AND , VT, Promote); 536 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 537 setOperationAction(ISD::OR , VT, Promote); 538 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 539 setOperationAction(ISD::XOR , VT, Promote); 540 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 541 setOperationAction(ISD::LOAD , VT, Promote); 542 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 543 setOperationAction(ISD::SELECT, VT, Promote); 544 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 545 setOperationAction(ISD::SELECT_CC, VT, Promote); 546 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 547 setOperationAction(ISD::STORE, VT, Promote); 548 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 549 550 // No other operations are legal. 551 setOperationAction(ISD::MUL , VT, Expand); 552 setOperationAction(ISD::SDIV, VT, Expand); 553 setOperationAction(ISD::SREM, VT, Expand); 554 setOperationAction(ISD::UDIV, VT, Expand); 555 setOperationAction(ISD::UREM, VT, Expand); 556 setOperationAction(ISD::FDIV, VT, Expand); 557 setOperationAction(ISD::FREM, VT, Expand); 558 setOperationAction(ISD::FNEG, VT, Expand); 559 setOperationAction(ISD::FSQRT, VT, Expand); 560 setOperationAction(ISD::FLOG, VT, Expand); 561 setOperationAction(ISD::FLOG10, VT, Expand); 562 setOperationAction(ISD::FLOG2, VT, Expand); 563 setOperationAction(ISD::FEXP, VT, Expand); 564 setOperationAction(ISD::FEXP2, VT, Expand); 565 setOperationAction(ISD::FSIN, VT, Expand); 566 setOperationAction(ISD::FCOS, VT, Expand); 567 setOperationAction(ISD::FABS, VT, Expand); 568 setOperationAction(ISD::FFLOOR, VT, Expand); 569 setOperationAction(ISD::FCEIL, VT, Expand); 570 setOperationAction(ISD::FTRUNC, VT, Expand); 571 setOperationAction(ISD::FRINT, VT, Expand); 572 setOperationAction(ISD::FNEARBYINT, VT, Expand); 573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 574 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 575 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 576 setOperationAction(ISD::MULHU, VT, Expand); 577 setOperationAction(ISD::MULHS, VT, Expand); 578 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 579 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 580 setOperationAction(ISD::UDIVREM, VT, Expand); 581 setOperationAction(ISD::SDIVREM, VT, Expand); 582 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 583 setOperationAction(ISD::FPOW, VT, Expand); 584 setOperationAction(ISD::BSWAP, VT, Expand); 585 setOperationAction(ISD::VSELECT, VT, Expand); 586 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 587 setOperationAction(ISD::ROTL, VT, Expand); 588 setOperationAction(ISD::ROTR, VT, Expand); 589 590 for (MVT InnerVT : MVT::vector_valuetypes()) { 591 setTruncStoreAction(VT, InnerVT, Expand); 592 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 593 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 594 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 595 } 596 } 597 598 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 599 // with merges, splats, etc. 600 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 601 602 setOperationAction(ISD::AND , MVT::v4i32, Legal); 603 setOperationAction(ISD::OR , MVT::v4i32, Legal); 604 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 605 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 606 setOperationAction(ISD::SELECT, MVT::v4i32, 607 Subtarget.useCRBits() ? Legal : Expand); 608 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 609 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 610 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 611 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 612 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 613 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 614 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 615 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 616 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 617 618 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 619 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 620 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 621 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 622 623 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 624 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 625 626 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 627 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 628 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 629 } 630 631 if (Subtarget.hasP8Altivec()) 632 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 633 else 634 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 635 636 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 637 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 638 639 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 640 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 641 642 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 643 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 644 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 645 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 646 647 // Altivec does not contain unordered floating-point compare instructions 648 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 649 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 650 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 651 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 652 653 if (Subtarget.hasVSX()) { 654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 656 if (Subtarget.hasP8Vector()) { 657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 658 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 659 } 660 if (Subtarget.hasDirectMove() && isPPC64) { 661 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 662 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 663 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 664 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 666 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 667 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 668 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 669 } 670 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 671 672 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 673 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 674 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 675 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 676 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 677 678 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 679 680 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 681 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 682 683 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 684 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 685 686 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); 687 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); 688 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); 689 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 690 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); 691 692 // Share the Altivec comparison restrictions. 693 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 694 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 695 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 696 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 697 698 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 699 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 700 701 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 702 703 if (Subtarget.hasP8Vector()) 704 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 705 706 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 707 708 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 709 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 710 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 711 712 if (Subtarget.hasP8Altivec()) { 713 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 714 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 716 717 // 128 bit shifts can be accomplished via 3 instructions for SHL and 718 // SRL, but not for SRA because of the instructions available: 719 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 720 // doing 721 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 722 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 723 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 724 725 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 726 } 727 else { 728 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 729 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 730 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 731 732 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 733 734 // VSX v2i64 only supports non-arithmetic operations. 735 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 736 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 737 } 738 739 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 740 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 741 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 742 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 743 744 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 745 746 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 747 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 748 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 749 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 750 751 // Vector operation legalization checks the result type of 752 // SIGN_EXTEND_INREG, overall legalization checks the inner type. 753 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 754 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 755 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 756 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 757 758 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 759 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 760 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 761 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 762 763 if (Subtarget.hasDirectMove()) 764 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 765 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 766 767 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 768 } 769 770 if (Subtarget.hasP8Altivec()) { 771 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 772 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 773 } 774 775 if (Subtarget.hasP9Vector()) { 776 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 777 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 778 779 // 128 bit shifts can be accomplished via 3 instructions for SHL and 780 // SRL, but not for SRA because of the instructions available: 781 // VS{RL} and VS{RL}O. 782 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 783 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 784 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 785 } 786 787 if (Subtarget.hasP9Altivec()) { 788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 789 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 790 } 791 } 792 793 if (Subtarget.hasQPX()) { 794 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 795 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 796 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 797 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 798 799 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 800 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 801 802 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 803 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 804 805 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 806 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 807 808 if (!Subtarget.useCRBits()) 809 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 810 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 811 812 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 813 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 814 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 815 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 816 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 819 820 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 821 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 822 823 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 824 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 825 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 826 827 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 828 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 829 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 830 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 831 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 832 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 833 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 834 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 835 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 836 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 837 838 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 839 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 840 841 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 842 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 843 844 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 845 846 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 847 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 848 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 849 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 850 851 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 852 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 853 854 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 855 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 856 857 if (!Subtarget.useCRBits()) 858 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 859 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 860 861 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 862 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 863 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 864 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 865 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 866 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 867 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 868 869 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 870 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 871 872 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 873 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 874 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 875 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 876 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 877 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 878 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 879 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 880 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 881 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 882 883 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 884 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 885 886 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 887 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 888 889 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 890 891 setOperationAction(ISD::AND , MVT::v4i1, Legal); 892 setOperationAction(ISD::OR , MVT::v4i1, Legal); 893 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 894 895 if (!Subtarget.useCRBits()) 896 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 897 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 898 899 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 900 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 901 902 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 903 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 904 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 905 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 906 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 907 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 908 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 909 910 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 911 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 912 913 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 914 915 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 916 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 917 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 918 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 919 920 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 921 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 922 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 923 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 924 925 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 926 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 927 928 // These need to set FE_INEXACT, and so cannot be vectorized here. 929 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 930 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 931 932 if (TM.Options.UnsafeFPMath) { 933 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 934 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 935 936 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 937 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 938 } else { 939 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 940 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 941 942 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 943 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 944 } 945 } 946 947 if (Subtarget.has64BitSupport()) 948 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 949 950 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 951 952 if (!isPPC64) { 953 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 954 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 955 } 956 957 setBooleanContents(ZeroOrOneBooleanContent); 958 959 if (Subtarget.hasAltivec()) { 960 // Altivec instructions set fields to all zeros or all ones. 961 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 962 } 963 964 if (!isPPC64) { 965 // These libcalls are not available in 32-bit. 966 setLibcallName(RTLIB::SHL_I128, nullptr); 967 setLibcallName(RTLIB::SRL_I128, nullptr); 968 setLibcallName(RTLIB::SRA_I128, nullptr); 969 } 970 971 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 972 973 // We have target-specific dag combine patterns for the following nodes: 974 setTargetDAGCombine(ISD::SHL); 975 setTargetDAGCombine(ISD::SRA); 976 setTargetDAGCombine(ISD::SRL); 977 setTargetDAGCombine(ISD::SINT_TO_FP); 978 setTargetDAGCombine(ISD::BUILD_VECTOR); 979 if (Subtarget.hasFPCVT()) 980 setTargetDAGCombine(ISD::UINT_TO_FP); 981 setTargetDAGCombine(ISD::LOAD); 982 setTargetDAGCombine(ISD::STORE); 983 setTargetDAGCombine(ISD::BR_CC); 984 if (Subtarget.useCRBits()) 985 setTargetDAGCombine(ISD::BRCOND); 986 setTargetDAGCombine(ISD::BSWAP); 987 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 988 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 989 setTargetDAGCombine(ISD::INTRINSIC_VOID); 990 991 setTargetDAGCombine(ISD::SIGN_EXTEND); 992 setTargetDAGCombine(ISD::ZERO_EXTEND); 993 setTargetDAGCombine(ISD::ANY_EXTEND); 994 995 if (Subtarget.useCRBits()) { 996 setTargetDAGCombine(ISD::TRUNCATE); 997 setTargetDAGCombine(ISD::SETCC); 998 setTargetDAGCombine(ISD::SELECT_CC); 999 } 1000 1001 // Use reciprocal estimates. 1002 if (TM.Options.UnsafeFPMath) { 1003 setTargetDAGCombine(ISD::FDIV); 1004 setTargetDAGCombine(ISD::FSQRT); 1005 } 1006 1007 // Darwin long double math library functions have $LDBL128 appended. 1008 if (Subtarget.isDarwin()) { 1009 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1010 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1011 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1012 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1013 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1014 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1015 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1016 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1017 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1018 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1019 } 1020 1021 // With 32 condition bits, we don't need to sink (and duplicate) compares 1022 // aggressively in CodeGenPrep. 1023 if (Subtarget.useCRBits()) { 1024 setHasMultipleConditionRegisters(); 1025 setJumpIsExpensive(); 1026 } 1027 1028 setMinFunctionAlignment(2); 1029 if (Subtarget.isDarwin()) 1030 setPrefFunctionAlignment(4); 1031 1032 switch (Subtarget.getDarwinDirective()) { 1033 default: break; 1034 case PPC::DIR_970: 1035 case PPC::DIR_A2: 1036 case PPC::DIR_E500mc: 1037 case PPC::DIR_E5500: 1038 case PPC::DIR_PWR4: 1039 case PPC::DIR_PWR5: 1040 case PPC::DIR_PWR5X: 1041 case PPC::DIR_PWR6: 1042 case PPC::DIR_PWR6X: 1043 case PPC::DIR_PWR7: 1044 case PPC::DIR_PWR8: 1045 case PPC::DIR_PWR9: 1046 setPrefFunctionAlignment(4); 1047 setPrefLoopAlignment(4); 1048 break; 1049 } 1050 1051 if (Subtarget.enableMachineScheduler()) 1052 setSchedulingPreference(Sched::Source); 1053 else 1054 setSchedulingPreference(Sched::Hybrid); 1055 1056 computeRegisterProperties(STI.getRegisterInfo()); 1057 1058 // The Freescale cores do better with aggressive inlining of memcpy and 1059 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1060 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1061 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1062 MaxStoresPerMemset = 32; 1063 MaxStoresPerMemsetOptSize = 16; 1064 MaxStoresPerMemcpy = 32; 1065 MaxStoresPerMemcpyOptSize = 8; 1066 MaxStoresPerMemmove = 32; 1067 MaxStoresPerMemmoveOptSize = 8; 1068 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1069 // The A2 also benefits from (very) aggressive inlining of memcpy and 1070 // friends. The overhead of a the function call, even when warm, can be 1071 // over one hundred cycles. 1072 MaxStoresPerMemset = 128; 1073 MaxStoresPerMemcpy = 128; 1074 MaxStoresPerMemmove = 128; 1075 MaxLoadsPerMemcmp = 128; 1076 } else { 1077 MaxLoadsPerMemcmp = 8; 1078 MaxLoadsPerMemcmpOptSize = 4; 1079 } 1080 } 1081 1082 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1083 /// the desired ByVal argument alignment. 1084 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1085 unsigned MaxMaxAlign) { 1086 if (MaxAlign == MaxMaxAlign) 1087 return; 1088 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1089 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1090 MaxAlign = 32; 1091 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1092 MaxAlign = 16; 1093 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1094 unsigned EltAlign = 0; 1095 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1096 if (EltAlign > MaxAlign) 1097 MaxAlign = EltAlign; 1098 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1099 for (auto *EltTy : STy->elements()) { 1100 unsigned EltAlign = 0; 1101 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1102 if (EltAlign > MaxAlign) 1103 MaxAlign = EltAlign; 1104 if (MaxAlign == MaxMaxAlign) 1105 break; 1106 } 1107 } 1108 } 1109 1110 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1111 /// function arguments in the caller parameter area. 1112 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1113 const DataLayout &DL) const { 1114 // Darwin passes everything on 4 byte boundary. 1115 if (Subtarget.isDarwin()) 1116 return 4; 1117 1118 // 16byte and wider vectors are passed on 16byte boundary. 1119 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1120 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1121 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1122 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1123 return Align; 1124 } 1125 1126 bool PPCTargetLowering::useSoftFloat() const { 1127 return Subtarget.useSoftFloat(); 1128 } 1129 1130 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1131 switch ((PPCISD::NodeType)Opcode) { 1132 case PPCISD::FIRST_NUMBER: break; 1133 case PPCISD::FSEL: return "PPCISD::FSEL"; 1134 case PPCISD::FCFID: return "PPCISD::FCFID"; 1135 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1136 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1137 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1138 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1139 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1140 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1141 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1142 case PPCISD::FRE: return "PPCISD::FRE"; 1143 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1144 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1145 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1146 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1147 case PPCISD::VPERM: return "PPCISD::VPERM"; 1148 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1149 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1150 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1151 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1152 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1153 case PPCISD::CMPB: return "PPCISD::CMPB"; 1154 case PPCISD::Hi: return "PPCISD::Hi"; 1155 case PPCISD::Lo: return "PPCISD::Lo"; 1156 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1157 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1158 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1159 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1160 case PPCISD::SRL: return "PPCISD::SRL"; 1161 case PPCISD::SRA: return "PPCISD::SRA"; 1162 case PPCISD::SHL: return "PPCISD::SHL"; 1163 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1164 case PPCISD::CALL: return "PPCISD::CALL"; 1165 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1166 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1167 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1168 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1169 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1170 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1171 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1172 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1173 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1174 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1175 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1176 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1177 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1178 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1179 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1180 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1181 case PPCISD::VCMP: return "PPCISD::VCMP"; 1182 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1183 case PPCISD::LBRX: return "PPCISD::LBRX"; 1184 case PPCISD::STBRX: return "PPCISD::STBRX"; 1185 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1186 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1187 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1188 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1189 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1190 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1191 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1192 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1193 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1194 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1195 case PPCISD::BDZ: return "PPCISD::BDZ"; 1196 case PPCISD::MFFS: return "PPCISD::MFFS"; 1197 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1198 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1199 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1200 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1201 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1202 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1203 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1204 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1205 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1206 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1207 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1208 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1209 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1210 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1211 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1212 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1213 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1214 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1215 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1216 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1217 case PPCISD::SC: return "PPCISD::SC"; 1218 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1219 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1220 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1221 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1222 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1223 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1224 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1225 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1226 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1227 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1228 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1229 } 1230 return nullptr; 1231 } 1232 1233 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1234 EVT VT) const { 1235 if (!VT.isVector()) 1236 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1237 1238 if (Subtarget.hasQPX()) 1239 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1240 1241 return VT.changeVectorElementTypeToInteger(); 1242 } 1243 1244 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1245 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1246 return true; 1247 } 1248 1249 //===----------------------------------------------------------------------===// 1250 // Node matching predicates, for use by the tblgen matching code. 1251 //===----------------------------------------------------------------------===// 1252 1253 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1254 static bool isFloatingPointZero(SDValue Op) { 1255 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1256 return CFP->getValueAPF().isZero(); 1257 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1258 // Maybe this has already been legalized into the constant pool? 1259 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1260 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1261 return CFP->getValueAPF().isZero(); 1262 } 1263 return false; 1264 } 1265 1266 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1267 /// true if Op is undef or if it matches the specified value. 1268 static bool isConstantOrUndef(int Op, int Val) { 1269 return Op < 0 || Op == Val; 1270 } 1271 1272 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1273 /// VPKUHUM instruction. 1274 /// The ShuffleKind distinguishes between big-endian operations with 1275 /// two different inputs (0), either-endian operations with two identical 1276 /// inputs (1), and little-endian operations with two different inputs (2). 1277 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1278 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1279 SelectionDAG &DAG) { 1280 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1281 if (ShuffleKind == 0) { 1282 if (IsLE) 1283 return false; 1284 for (unsigned i = 0; i != 16; ++i) 1285 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1286 return false; 1287 } else if (ShuffleKind == 2) { 1288 if (!IsLE) 1289 return false; 1290 for (unsigned i = 0; i != 16; ++i) 1291 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1292 return false; 1293 } else if (ShuffleKind == 1) { 1294 unsigned j = IsLE ? 0 : 1; 1295 for (unsigned i = 0; i != 8; ++i) 1296 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1297 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1298 return false; 1299 } 1300 return true; 1301 } 1302 1303 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1304 /// VPKUWUM instruction. 1305 /// The ShuffleKind distinguishes between big-endian operations with 1306 /// two different inputs (0), either-endian operations with two identical 1307 /// inputs (1), and little-endian operations with two different inputs (2). 1308 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1309 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1310 SelectionDAG &DAG) { 1311 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1312 if (ShuffleKind == 0) { 1313 if (IsLE) 1314 return false; 1315 for (unsigned i = 0; i != 16; i += 2) 1316 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1317 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1318 return false; 1319 } else if (ShuffleKind == 2) { 1320 if (!IsLE) 1321 return false; 1322 for (unsigned i = 0; i != 16; i += 2) 1323 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1324 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1325 return false; 1326 } else if (ShuffleKind == 1) { 1327 unsigned j = IsLE ? 0 : 2; 1328 for (unsigned i = 0; i != 8; i += 2) 1329 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1330 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1331 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1332 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1333 return false; 1334 } 1335 return true; 1336 } 1337 1338 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1339 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1340 /// current subtarget. 1341 /// 1342 /// The ShuffleKind distinguishes between big-endian operations with 1343 /// two different inputs (0), either-endian operations with two identical 1344 /// inputs (1), and little-endian operations with two different inputs (2). 1345 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1346 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1347 SelectionDAG &DAG) { 1348 const PPCSubtarget& Subtarget = 1349 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1350 if (!Subtarget.hasP8Vector()) 1351 return false; 1352 1353 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1354 if (ShuffleKind == 0) { 1355 if (IsLE) 1356 return false; 1357 for (unsigned i = 0; i != 16; i += 4) 1358 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1359 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1360 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1361 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1362 return false; 1363 } else if (ShuffleKind == 2) { 1364 if (!IsLE) 1365 return false; 1366 for (unsigned i = 0; i != 16; i += 4) 1367 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1368 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1369 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1370 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1371 return false; 1372 } else if (ShuffleKind == 1) { 1373 unsigned j = IsLE ? 0 : 4; 1374 for (unsigned i = 0; i != 8; i += 4) 1375 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1376 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1377 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1378 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1379 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1380 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1381 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1382 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1383 return false; 1384 } 1385 return true; 1386 } 1387 1388 /// isVMerge - Common function, used to match vmrg* shuffles. 1389 /// 1390 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1391 unsigned LHSStart, unsigned RHSStart) { 1392 if (N->getValueType(0) != MVT::v16i8) 1393 return false; 1394 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1395 "Unsupported merge size!"); 1396 1397 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1398 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1399 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1400 LHSStart+j+i*UnitSize) || 1401 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1402 RHSStart+j+i*UnitSize)) 1403 return false; 1404 } 1405 return true; 1406 } 1407 1408 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1409 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1410 /// The ShuffleKind distinguishes between big-endian merges with two 1411 /// different inputs (0), either-endian merges with two identical inputs (1), 1412 /// and little-endian merges with two different inputs (2). For the latter, 1413 /// the input operands are swapped (see PPCInstrAltivec.td). 1414 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1415 unsigned ShuffleKind, SelectionDAG &DAG) { 1416 if (DAG.getDataLayout().isLittleEndian()) { 1417 if (ShuffleKind == 1) // unary 1418 return isVMerge(N, UnitSize, 0, 0); 1419 else if (ShuffleKind == 2) // swapped 1420 return isVMerge(N, UnitSize, 0, 16); 1421 else 1422 return false; 1423 } else { 1424 if (ShuffleKind == 1) // unary 1425 return isVMerge(N, UnitSize, 8, 8); 1426 else if (ShuffleKind == 0) // normal 1427 return isVMerge(N, UnitSize, 8, 24); 1428 else 1429 return false; 1430 } 1431 } 1432 1433 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1434 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1435 /// The ShuffleKind distinguishes between big-endian merges with two 1436 /// different inputs (0), either-endian merges with two identical inputs (1), 1437 /// and little-endian merges with two different inputs (2). For the latter, 1438 /// the input operands are swapped (see PPCInstrAltivec.td). 1439 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1440 unsigned ShuffleKind, SelectionDAG &DAG) { 1441 if (DAG.getDataLayout().isLittleEndian()) { 1442 if (ShuffleKind == 1) // unary 1443 return isVMerge(N, UnitSize, 8, 8); 1444 else if (ShuffleKind == 2) // swapped 1445 return isVMerge(N, UnitSize, 8, 24); 1446 else 1447 return false; 1448 } else { 1449 if (ShuffleKind == 1) // unary 1450 return isVMerge(N, UnitSize, 0, 0); 1451 else if (ShuffleKind == 0) // normal 1452 return isVMerge(N, UnitSize, 0, 16); 1453 else 1454 return false; 1455 } 1456 } 1457 1458 /** 1459 * \brief Common function used to match vmrgew and vmrgow shuffles 1460 * 1461 * The indexOffset determines whether to look for even or odd words in 1462 * the shuffle mask. This is based on the of the endianness of the target 1463 * machine. 1464 * - Little Endian: 1465 * - Use offset of 0 to check for odd elements 1466 * - Use offset of 4 to check for even elements 1467 * - Big Endian: 1468 * - Use offset of 0 to check for even elements 1469 * - Use offset of 4 to check for odd elements 1470 * A detailed description of the vector element ordering for little endian and 1471 * big endian can be found at 1472 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1473 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1474 * compiler differences mean to you 1475 * 1476 * The mask to the shuffle vector instruction specifies the indices of the 1477 * elements from the two input vectors to place in the result. The elements are 1478 * numbered in array-access order, starting with the first vector. These vectors 1479 * are always of type v16i8, thus each vector will contain 16 elements of size 1480 * 8. More info on the shuffle vector can be found in the 1481 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1482 * Language Reference. 1483 * 1484 * The RHSStartValue indicates whether the same input vectors are used (unary) 1485 * or two different input vectors are used, based on the following: 1486 * - If the instruction uses the same vector for both inputs, the range of the 1487 * indices will be 0 to 15. In this case, the RHSStart value passed should 1488 * be 0. 1489 * - If the instruction has two different vectors then the range of the 1490 * indices will be 0 to 31. In this case, the RHSStart value passed should 1491 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1492 * to 31 specify elements in the second vector). 1493 * 1494 * \param[in] N The shuffle vector SD Node to analyze 1495 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1496 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1497 * vector to the shuffle_vector instruction 1498 * \return true iff this shuffle vector represents an even or odd word merge 1499 */ 1500 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1501 unsigned RHSStartValue) { 1502 if (N->getValueType(0) != MVT::v16i8) 1503 return false; 1504 1505 for (unsigned i = 0; i < 2; ++i) 1506 for (unsigned j = 0; j < 4; ++j) 1507 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1508 i*RHSStartValue+j+IndexOffset) || 1509 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1510 i*RHSStartValue+j+IndexOffset+8)) 1511 return false; 1512 return true; 1513 } 1514 1515 /** 1516 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or 1517 * vmrgow instructions. 1518 * 1519 * \param[in] N The shuffle vector SD Node to analyze 1520 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1521 * \param[in] ShuffleKind Identify the type of merge: 1522 * - 0 = big-endian merge with two different inputs; 1523 * - 1 = either-endian merge with two identical inputs; 1524 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1525 * little-endian merges). 1526 * \param[in] DAG The current SelectionDAG 1527 * \return true iff this shuffle mask 1528 */ 1529 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1530 unsigned ShuffleKind, SelectionDAG &DAG) { 1531 if (DAG.getDataLayout().isLittleEndian()) { 1532 unsigned indexOffset = CheckEven ? 4 : 0; 1533 if (ShuffleKind == 1) // Unary 1534 return isVMerge(N, indexOffset, 0); 1535 else if (ShuffleKind == 2) // swapped 1536 return isVMerge(N, indexOffset, 16); 1537 else 1538 return false; 1539 } 1540 else { 1541 unsigned indexOffset = CheckEven ? 0 : 4; 1542 if (ShuffleKind == 1) // Unary 1543 return isVMerge(N, indexOffset, 0); 1544 else if (ShuffleKind == 0) // Normal 1545 return isVMerge(N, indexOffset, 16); 1546 else 1547 return false; 1548 } 1549 return false; 1550 } 1551 1552 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1553 /// amount, otherwise return -1. 1554 /// The ShuffleKind distinguishes between big-endian operations with two 1555 /// different inputs (0), either-endian operations with two identical inputs 1556 /// (1), and little-endian operations with two different inputs (2). For the 1557 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1558 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1559 SelectionDAG &DAG) { 1560 if (N->getValueType(0) != MVT::v16i8) 1561 return -1; 1562 1563 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1564 1565 // Find the first non-undef value in the shuffle mask. 1566 unsigned i; 1567 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1568 /*search*/; 1569 1570 if (i == 16) return -1; // all undef. 1571 1572 // Otherwise, check to see if the rest of the elements are consecutively 1573 // numbered from this value. 1574 unsigned ShiftAmt = SVOp->getMaskElt(i); 1575 if (ShiftAmt < i) return -1; 1576 1577 ShiftAmt -= i; 1578 bool isLE = DAG.getDataLayout().isLittleEndian(); 1579 1580 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1581 // Check the rest of the elements to see if they are consecutive. 1582 for (++i; i != 16; ++i) 1583 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1584 return -1; 1585 } else if (ShuffleKind == 1) { 1586 // Check the rest of the elements to see if they are consecutive. 1587 for (++i; i != 16; ++i) 1588 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1589 return -1; 1590 } else 1591 return -1; 1592 1593 if (isLE) 1594 ShiftAmt = 16 - ShiftAmt; 1595 1596 return ShiftAmt; 1597 } 1598 1599 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1600 /// specifies a splat of a single element that is suitable for input to 1601 /// VSPLTB/VSPLTH/VSPLTW. 1602 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1603 assert(N->getValueType(0) == MVT::v16i8 && 1604 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1605 1606 // The consecutive indices need to specify an element, not part of two 1607 // different elements. So abandon ship early if this isn't the case. 1608 if (N->getMaskElt(0) % EltSize != 0) 1609 return false; 1610 1611 // This is a splat operation if each element of the permute is the same, and 1612 // if the value doesn't reference the second vector. 1613 unsigned ElementBase = N->getMaskElt(0); 1614 1615 // FIXME: Handle UNDEF elements too! 1616 if (ElementBase >= 16) 1617 return false; 1618 1619 // Check that the indices are consecutive, in the case of a multi-byte element 1620 // splatted with a v16i8 mask. 1621 for (unsigned i = 1; i != EltSize; ++i) 1622 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1623 return false; 1624 1625 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1626 if (N->getMaskElt(i) < 0) continue; 1627 for (unsigned j = 0; j != EltSize; ++j) 1628 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1629 return false; 1630 } 1631 return true; 1632 } 1633 1634 /// Check that the mask is shuffling N byte elements. Within each N byte 1635 /// element of the mask, the indices could be either in increasing or 1636 /// decreasing order as long as they are consecutive. 1637 /// \param[in] N the shuffle vector SD Node to analyze 1638 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1639 /// Word/DoubleWord/QuadWord). 1640 /// \param[in] StepLen the delta indices number among the N byte element, if 1641 /// the mask is in increasing/decreasing order then it is 1/-1. 1642 /// \return true iff the mask is shuffling N byte elements. 1643 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1644 int StepLen) { 1645 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1646 "Unexpected element width."); 1647 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1648 1649 unsigned NumOfElem = 16 / Width; 1650 unsigned MaskVal[16]; // Width is never greater than 16 1651 for (unsigned i = 0; i < NumOfElem; ++i) { 1652 MaskVal[0] = N->getMaskElt(i * Width); 1653 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1654 return false; 1655 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1656 return false; 1657 } 1658 1659 for (unsigned int j = 1; j < Width; ++j) { 1660 MaskVal[j] = N->getMaskElt(i * Width + j); 1661 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1662 return false; 1663 } 1664 } 1665 } 1666 1667 return true; 1668 } 1669 1670 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1671 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1672 if (!isNByteElemShuffleMask(N, 4, 1)) 1673 return false; 1674 1675 // Now we look at mask elements 0,4,8,12 1676 unsigned M0 = N->getMaskElt(0) / 4; 1677 unsigned M1 = N->getMaskElt(4) / 4; 1678 unsigned M2 = N->getMaskElt(8) / 4; 1679 unsigned M3 = N->getMaskElt(12) / 4; 1680 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1681 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1682 1683 // Below, let H and L be arbitrary elements of the shuffle mask 1684 // where H is in the range [4,7] and L is in the range [0,3]. 1685 // H, 1, 2, 3 or L, 5, 6, 7 1686 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1687 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1688 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1689 InsertAtByte = IsLE ? 12 : 0; 1690 Swap = M0 < 4; 1691 return true; 1692 } 1693 // 0, H, 2, 3 or 4, L, 6, 7 1694 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1695 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1696 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1697 InsertAtByte = IsLE ? 8 : 4; 1698 Swap = M1 < 4; 1699 return true; 1700 } 1701 // 0, 1, H, 3 or 4, 5, L, 7 1702 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1703 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1704 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1705 InsertAtByte = IsLE ? 4 : 8; 1706 Swap = M2 < 4; 1707 return true; 1708 } 1709 // 0, 1, 2, H or 4, 5, 6, L 1710 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1711 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1712 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1713 InsertAtByte = IsLE ? 0 : 12; 1714 Swap = M3 < 4; 1715 return true; 1716 } 1717 1718 // If both vector operands for the shuffle are the same vector, the mask will 1719 // contain only elements from the first one and the second one will be undef. 1720 if (N->getOperand(1).isUndef()) { 1721 ShiftElts = 0; 1722 Swap = true; 1723 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1724 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1725 InsertAtByte = IsLE ? 12 : 0; 1726 return true; 1727 } 1728 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1729 InsertAtByte = IsLE ? 8 : 4; 1730 return true; 1731 } 1732 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1733 InsertAtByte = IsLE ? 4 : 8; 1734 return true; 1735 } 1736 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1737 InsertAtByte = IsLE ? 0 : 12; 1738 return true; 1739 } 1740 } 1741 1742 return false; 1743 } 1744 1745 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1746 bool &Swap, bool IsLE) { 1747 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1748 // Ensure each byte index of the word is consecutive. 1749 if (!isNByteElemShuffleMask(N, 4, 1)) 1750 return false; 1751 1752 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1753 unsigned M0 = N->getMaskElt(0) / 4; 1754 unsigned M1 = N->getMaskElt(4) / 4; 1755 unsigned M2 = N->getMaskElt(8) / 4; 1756 unsigned M3 = N->getMaskElt(12) / 4; 1757 1758 // If both vector operands for the shuffle are the same vector, the mask will 1759 // contain only elements from the first one and the second one will be undef. 1760 if (N->getOperand(1).isUndef()) { 1761 assert(M0 < 4 && "Indexing into an undef vector?"); 1762 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1763 return false; 1764 1765 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1766 Swap = false; 1767 return true; 1768 } 1769 1770 // Ensure each word index of the ShuffleVector Mask is consecutive. 1771 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1772 return false; 1773 1774 if (IsLE) { 1775 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1776 // Input vectors don't need to be swapped if the leading element 1777 // of the result is one of the 3 left elements of the second vector 1778 // (or if there is no shift to be done at all). 1779 Swap = false; 1780 ShiftElts = (8 - M0) % 8; 1781 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1782 // Input vectors need to be swapped if the leading element 1783 // of the result is one of the 3 left elements of the first vector 1784 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1785 Swap = true; 1786 ShiftElts = (4 - M0) % 4; 1787 } 1788 1789 return true; 1790 } else { // BE 1791 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1792 // Input vectors don't need to be swapped if the leading element 1793 // of the result is one of the 4 elements of the first vector. 1794 Swap = false; 1795 ShiftElts = M0; 1796 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1797 // Input vectors need to be swapped if the leading element 1798 // of the result is one of the 4 elements of the right vector. 1799 Swap = true; 1800 ShiftElts = M0 - 4; 1801 } 1802 1803 return true; 1804 } 1805 } 1806 1807 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1808 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1809 1810 if (!isNByteElemShuffleMask(N, Width, -1)) 1811 return false; 1812 1813 for (int i = 0; i < 16; i += Width) 1814 if (N->getMaskElt(i) != i + Width - 1) 1815 return false; 1816 1817 return true; 1818 } 1819 1820 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1821 return isXXBRShuffleMaskHelper(N, 2); 1822 } 1823 1824 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 1825 return isXXBRShuffleMaskHelper(N, 4); 1826 } 1827 1828 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 1829 return isXXBRShuffleMaskHelper(N, 8); 1830 } 1831 1832 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 1833 return isXXBRShuffleMaskHelper(N, 16); 1834 } 1835 1836 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 1837 /// if the inputs to the instruction should be swapped and set \p DM to the 1838 /// value for the immediate. 1839 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 1840 /// AND element 0 of the result comes from the first input (LE) or second input 1841 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 1842 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 1843 /// mask. 1844 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 1845 bool &Swap, bool IsLE) { 1846 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1847 1848 // Ensure each byte index of the double word is consecutive. 1849 if (!isNByteElemShuffleMask(N, 8, 1)) 1850 return false; 1851 1852 unsigned M0 = N->getMaskElt(0) / 8; 1853 unsigned M1 = N->getMaskElt(8) / 8; 1854 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 1855 1856 // If both vector operands for the shuffle are the same vector, the mask will 1857 // contain only elements from the first one and the second one will be undef. 1858 if (N->getOperand(1).isUndef()) { 1859 if ((M0 | M1) < 2) { 1860 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 1861 Swap = false; 1862 return true; 1863 } else 1864 return false; 1865 } 1866 1867 if (IsLE) { 1868 if (M0 > 1 && M1 < 2) { 1869 Swap = false; 1870 } else if (M0 < 2 && M1 > 1) { 1871 M0 = (M0 + 2) % 4; 1872 M1 = (M1 + 2) % 4; 1873 Swap = true; 1874 } else 1875 return false; 1876 1877 // Note: if control flow comes here that means Swap is already set above 1878 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 1879 return true; 1880 } else { // BE 1881 if (M0 < 2 && M1 > 1) { 1882 Swap = false; 1883 } else if (M0 > 1 && M1 < 2) { 1884 M0 = (M0 + 2) % 4; 1885 M1 = (M1 + 2) % 4; 1886 Swap = true; 1887 } else 1888 return false; 1889 1890 // Note: if control flow comes here that means Swap is already set above 1891 DM = (M0 << 1) + (M1 & 1); 1892 return true; 1893 } 1894 } 1895 1896 1897 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 1898 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 1899 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 1900 SelectionDAG &DAG) { 1901 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1902 assert(isSplatShuffleMask(SVOp, EltSize)); 1903 if (DAG.getDataLayout().isLittleEndian()) 1904 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 1905 else 1906 return SVOp->getMaskElt(0) / EltSize; 1907 } 1908 1909 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 1910 /// by using a vspltis[bhw] instruction of the specified element size, return 1911 /// the constant being splatted. The ByteSize field indicates the number of 1912 /// bytes of each element [124] -> [bhw]. 1913 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 1914 SDValue OpVal(nullptr, 0); 1915 1916 // If ByteSize of the splat is bigger than the element size of the 1917 // build_vector, then we have a case where we are checking for a splat where 1918 // multiple elements of the buildvector are folded together into a single 1919 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 1920 unsigned EltSize = 16/N->getNumOperands(); 1921 if (EltSize < ByteSize) { 1922 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 1923 SDValue UniquedVals[4]; 1924 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 1925 1926 // See if all of the elements in the buildvector agree across. 1927 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1928 if (N->getOperand(i).isUndef()) continue; 1929 // If the element isn't a constant, bail fully out. 1930 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 1931 1932 if (!UniquedVals[i&(Multiple-1)].getNode()) 1933 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 1934 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 1935 return SDValue(); // no match. 1936 } 1937 1938 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 1939 // either constant or undef values that are identical for each chunk. See 1940 // if these chunks can form into a larger vspltis*. 1941 1942 // Check to see if all of the leading entries are either 0 or -1. If 1943 // neither, then this won't fit into the immediate field. 1944 bool LeadingZero = true; 1945 bool LeadingOnes = true; 1946 for (unsigned i = 0; i != Multiple-1; ++i) { 1947 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 1948 1949 LeadingZero &= isNullConstant(UniquedVals[i]); 1950 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 1951 } 1952 // Finally, check the least significant entry. 1953 if (LeadingZero) { 1954 if (!UniquedVals[Multiple-1].getNode()) 1955 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 1956 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 1957 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 1958 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1959 } 1960 if (LeadingOnes) { 1961 if (!UniquedVals[Multiple-1].getNode()) 1962 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 1963 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 1964 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 1965 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 1966 } 1967 1968 return SDValue(); 1969 } 1970 1971 // Check to see if this buildvec has a single non-undef value in its elements. 1972 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 1973 if (N->getOperand(i).isUndef()) continue; 1974 if (!OpVal.getNode()) 1975 OpVal = N->getOperand(i); 1976 else if (OpVal != N->getOperand(i)) 1977 return SDValue(); 1978 } 1979 1980 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 1981 1982 unsigned ValSizeInBytes = EltSize; 1983 uint64_t Value = 0; 1984 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 1985 Value = CN->getZExtValue(); 1986 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 1987 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 1988 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 1989 } 1990 1991 // If the splat value is larger than the element value, then we can never do 1992 // this splat. The only case that we could fit the replicated bits into our 1993 // immediate field for would be zero, and we prefer to use vxor for it. 1994 if (ValSizeInBytes < ByteSize) return SDValue(); 1995 1996 // If the element value is larger than the splat value, check if it consists 1997 // of a repeated bit pattern of size ByteSize. 1998 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 1999 return SDValue(); 2000 2001 // Properly sign extend the value. 2002 int MaskVal = SignExtend32(Value, ByteSize * 8); 2003 2004 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2005 if (MaskVal == 0) return SDValue(); 2006 2007 // Finally, if this value fits in a 5 bit sext field, return it 2008 if (SignExtend32<5>(MaskVal) == MaskVal) 2009 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2010 return SDValue(); 2011 } 2012 2013 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2014 /// amount, otherwise return -1. 2015 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2016 EVT VT = N->getValueType(0); 2017 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2018 return -1; 2019 2020 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2021 2022 // Find the first non-undef value in the shuffle mask. 2023 unsigned i; 2024 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2025 /*search*/; 2026 2027 if (i == 4) return -1; // all undef. 2028 2029 // Otherwise, check to see if the rest of the elements are consecutively 2030 // numbered from this value. 2031 unsigned ShiftAmt = SVOp->getMaskElt(i); 2032 if (ShiftAmt < i) return -1; 2033 ShiftAmt -= i; 2034 2035 // Check the rest of the elements to see if they are consecutive. 2036 for (++i; i != 4; ++i) 2037 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2038 return -1; 2039 2040 return ShiftAmt; 2041 } 2042 2043 //===----------------------------------------------------------------------===// 2044 // Addressing Mode Selection 2045 //===----------------------------------------------------------------------===// 2046 2047 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2048 /// or 64-bit immediate, and if the value can be accurately represented as a 2049 /// sign extension from a 16-bit value. If so, this returns true and the 2050 /// immediate. 2051 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2052 if (!isa<ConstantSDNode>(N)) 2053 return false; 2054 2055 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2056 if (N->getValueType(0) == MVT::i32) 2057 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2058 else 2059 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2060 } 2061 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2062 return isIntS16Immediate(Op.getNode(), Imm); 2063 } 2064 2065 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2066 /// can be represented as an indexed [r+r] operation. Returns false if it 2067 /// can be more efficiently represented with [r+imm]. 2068 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2069 SDValue &Index, 2070 SelectionDAG &DAG) const { 2071 int16_t imm = 0; 2072 if (N.getOpcode() == ISD::ADD) { 2073 if (isIntS16Immediate(N.getOperand(1), imm)) 2074 return false; // r+i 2075 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2076 return false; // r+i 2077 2078 Base = N.getOperand(0); 2079 Index = N.getOperand(1); 2080 return true; 2081 } else if (N.getOpcode() == ISD::OR) { 2082 if (isIntS16Immediate(N.getOperand(1), imm)) 2083 return false; // r+i can fold it if we can. 2084 2085 // If this is an or of disjoint bitfields, we can codegen this as an add 2086 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2087 // disjoint. 2088 KnownBits LHSKnown, RHSKnown; 2089 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2090 2091 if (LHSKnown.Zero.getBoolValue()) { 2092 DAG.computeKnownBits(N.getOperand(1), RHSKnown); 2093 // If all of the bits are known zero on the LHS or RHS, the add won't 2094 // carry. 2095 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2096 Base = N.getOperand(0); 2097 Index = N.getOperand(1); 2098 return true; 2099 } 2100 } 2101 } 2102 2103 return false; 2104 } 2105 2106 // If we happen to be doing an i64 load or store into a stack slot that has 2107 // less than a 4-byte alignment, then the frame-index elimination may need to 2108 // use an indexed load or store instruction (because the offset may not be a 2109 // multiple of 4). The extra register needed to hold the offset comes from the 2110 // register scavenger, and it is possible that the scavenger will need to use 2111 // an emergency spill slot. As a result, we need to make sure that a spill slot 2112 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2113 // stack slot. 2114 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2115 // FIXME: This does not handle the LWA case. 2116 if (VT != MVT::i64) 2117 return; 2118 2119 // NOTE: We'll exclude negative FIs here, which come from argument 2120 // lowering, because there are no known test cases triggering this problem 2121 // using packed structures (or similar). We can remove this exclusion if 2122 // we find such a test case. The reason why this is so test-case driven is 2123 // because this entire 'fixup' is only to prevent crashes (from the 2124 // register scavenger) on not-really-valid inputs. For example, if we have: 2125 // %a = alloca i1 2126 // %b = bitcast i1* %a to i64* 2127 // store i64* a, i64 b 2128 // then the store should really be marked as 'align 1', but is not. If it 2129 // were marked as 'align 1' then the indexed form would have been 2130 // instruction-selected initially, and the problem this 'fixup' is preventing 2131 // won't happen regardless. 2132 if (FrameIdx < 0) 2133 return; 2134 2135 MachineFunction &MF = DAG.getMachineFunction(); 2136 MachineFrameInfo &MFI = MF.getFrameInfo(); 2137 2138 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2139 if (Align >= 4) 2140 return; 2141 2142 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2143 FuncInfo->setHasNonRISpills(); 2144 } 2145 2146 /// Returns true if the address N can be represented by a base register plus 2147 /// a signed 16-bit displacement [r+imm], and if it is not better 2148 /// represented as reg+reg. If \p Alignment is non-zero, only accept 2149 /// displacements that are multiples of that value. 2150 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2151 SDValue &Base, 2152 SelectionDAG &DAG, 2153 unsigned Alignment) const { 2154 // FIXME dl should come from parent load or store, not from address 2155 SDLoc dl(N); 2156 // If this can be more profitably realized as r+r, fail. 2157 if (SelectAddressRegReg(N, Disp, Base, DAG)) 2158 return false; 2159 2160 if (N.getOpcode() == ISD::ADD) { 2161 int16_t imm = 0; 2162 if (isIntS16Immediate(N.getOperand(1), imm) && 2163 (!Alignment || (imm % Alignment) == 0)) { 2164 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2165 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2166 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2167 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2168 } else { 2169 Base = N.getOperand(0); 2170 } 2171 return true; // [r+i] 2172 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2173 // Match LOAD (ADD (X, Lo(G))). 2174 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2175 && "Cannot handle constant offsets yet!"); 2176 Disp = N.getOperand(1).getOperand(0); // The global address. 2177 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2178 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2179 Disp.getOpcode() == ISD::TargetConstantPool || 2180 Disp.getOpcode() == ISD::TargetJumpTable); 2181 Base = N.getOperand(0); 2182 return true; // [&g+r] 2183 } 2184 } else if (N.getOpcode() == ISD::OR) { 2185 int16_t imm = 0; 2186 if (isIntS16Immediate(N.getOperand(1), imm) && 2187 (!Alignment || (imm % Alignment) == 0)) { 2188 // If this is an or of disjoint bitfields, we can codegen this as an add 2189 // (for better address arithmetic) if the LHS and RHS of the OR are 2190 // provably disjoint. 2191 KnownBits LHSKnown; 2192 DAG.computeKnownBits(N.getOperand(0), LHSKnown); 2193 2194 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2195 // If all of the bits are known zero on the LHS or RHS, the add won't 2196 // carry. 2197 if (FrameIndexSDNode *FI = 2198 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2199 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2200 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2201 } else { 2202 Base = N.getOperand(0); 2203 } 2204 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2205 return true; 2206 } 2207 } 2208 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2209 // Loading from a constant address. 2210 2211 // If this address fits entirely in a 16-bit sext immediate field, codegen 2212 // this as "d, 0" 2213 int16_t Imm; 2214 if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) { 2215 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2216 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2217 CN->getValueType(0)); 2218 return true; 2219 } 2220 2221 // Handle 32-bit sext immediates with LIS + addr mode. 2222 if ((CN->getValueType(0) == MVT::i32 || 2223 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2224 (!Alignment || (CN->getZExtValue() % Alignment) == 0)) { 2225 int Addr = (int)CN->getZExtValue(); 2226 2227 // Otherwise, break this down into an LIS + disp. 2228 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2229 2230 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2231 MVT::i32); 2232 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2233 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2234 return true; 2235 } 2236 } 2237 2238 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2239 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2240 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2241 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2242 } else 2243 Base = N; 2244 return true; // [r+0] 2245 } 2246 2247 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2248 /// represented as an indexed [r+r] operation. 2249 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2250 SDValue &Index, 2251 SelectionDAG &DAG) const { 2252 // Check to see if we can easily represent this as an [r+r] address. This 2253 // will fail if it thinks that the address is more profitably represented as 2254 // reg+imm, e.g. where imm = 0. 2255 if (SelectAddressRegReg(N, Base, Index, DAG)) 2256 return true; 2257 2258 // If the address is the result of an add, we will utilize the fact that the 2259 // address calculation includes an implicit add. However, we can reduce 2260 // register pressure if we do not materialize a constant just for use as the 2261 // index register. We only get rid of the add if it is not an add of a 2262 // value and a 16-bit signed constant and both have a single use. 2263 int16_t imm = 0; 2264 if (N.getOpcode() == ISD::ADD && 2265 (!isIntS16Immediate(N.getOperand(1), imm) || 2266 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2267 Base = N.getOperand(0); 2268 Index = N.getOperand(1); 2269 return true; 2270 } 2271 2272 // Otherwise, do it the hard way, using R0 as the base register. 2273 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2274 N.getValueType()); 2275 Index = N; 2276 return true; 2277 } 2278 2279 /// getPreIndexedAddressParts - returns true by value, base pointer and 2280 /// offset pointer and addressing mode by reference if the node's address 2281 /// can be legally represented as pre-indexed load / store address. 2282 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2283 SDValue &Offset, 2284 ISD::MemIndexedMode &AM, 2285 SelectionDAG &DAG) const { 2286 if (DisablePPCPreinc) return false; 2287 2288 bool isLoad = true; 2289 SDValue Ptr; 2290 EVT VT; 2291 unsigned Alignment; 2292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2293 Ptr = LD->getBasePtr(); 2294 VT = LD->getMemoryVT(); 2295 Alignment = LD->getAlignment(); 2296 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2297 Ptr = ST->getBasePtr(); 2298 VT = ST->getMemoryVT(); 2299 Alignment = ST->getAlignment(); 2300 isLoad = false; 2301 } else 2302 return false; 2303 2304 // PowerPC doesn't have preinc load/store instructions for vectors (except 2305 // for QPX, which does have preinc r+r forms). 2306 if (VT.isVector()) { 2307 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2308 return false; 2309 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2310 AM = ISD::PRE_INC; 2311 return true; 2312 } 2313 } 2314 2315 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2316 // Common code will reject creating a pre-inc form if the base pointer 2317 // is a frame index, or if N is a store and the base pointer is either 2318 // the same as or a predecessor of the value being stored. Check for 2319 // those situations here, and try with swapped Base/Offset instead. 2320 bool Swap = false; 2321 2322 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2323 Swap = true; 2324 else if (!isLoad) { 2325 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2326 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2327 Swap = true; 2328 } 2329 2330 if (Swap) 2331 std::swap(Base, Offset); 2332 2333 AM = ISD::PRE_INC; 2334 return true; 2335 } 2336 2337 // LDU/STU can only handle immediates that are a multiple of 4. 2338 if (VT != MVT::i64) { 2339 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2340 return false; 2341 } else { 2342 // LDU/STU need an address with at least 4-byte alignment. 2343 if (Alignment < 4) 2344 return false; 2345 2346 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2347 return false; 2348 } 2349 2350 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2351 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2352 // sext i32 to i64 when addr mode is r+i. 2353 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2354 LD->getExtensionType() == ISD::SEXTLOAD && 2355 isa<ConstantSDNode>(Offset)) 2356 return false; 2357 } 2358 2359 AM = ISD::PRE_INC; 2360 return true; 2361 } 2362 2363 //===----------------------------------------------------------------------===// 2364 // LowerOperation implementation 2365 //===----------------------------------------------------------------------===// 2366 2367 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2368 /// and LoOpFlags to the target MO flags. 2369 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2370 unsigned &HiOpFlags, unsigned &LoOpFlags, 2371 const GlobalValue *GV = nullptr) { 2372 HiOpFlags = PPCII::MO_HA; 2373 LoOpFlags = PPCII::MO_LO; 2374 2375 // Don't use the pic base if not in PIC relocation model. 2376 if (IsPIC) { 2377 HiOpFlags |= PPCII::MO_PIC_FLAG; 2378 LoOpFlags |= PPCII::MO_PIC_FLAG; 2379 } 2380 2381 // If this is a reference to a global value that requires a non-lazy-ptr, make 2382 // sure that instruction lowering adds it. 2383 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2384 HiOpFlags |= PPCII::MO_NLP_FLAG; 2385 LoOpFlags |= PPCII::MO_NLP_FLAG; 2386 2387 if (GV->hasHiddenVisibility()) { 2388 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2389 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2390 } 2391 } 2392 } 2393 2394 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2395 SelectionDAG &DAG) { 2396 SDLoc DL(HiPart); 2397 EVT PtrVT = HiPart.getValueType(); 2398 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2399 2400 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2401 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2402 2403 // With PIC, the first instruction is actually "GR+hi(&G)". 2404 if (isPIC) 2405 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2406 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2407 2408 // Generate non-pic code that has direct accesses to the constant pool. 2409 // The address of the global is just (hi(&g)+lo(&g)). 2410 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2411 } 2412 2413 static void setUsesTOCBasePtr(MachineFunction &MF) { 2414 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2415 FuncInfo->setUsesTOCBasePtr(); 2416 } 2417 2418 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2419 setUsesTOCBasePtr(DAG.getMachineFunction()); 2420 } 2421 2422 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2423 SDValue GA) { 2424 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2425 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2426 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2427 2428 SDValue Ops[] = { GA, Reg }; 2429 return DAG.getMemIntrinsicNode( 2430 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2431 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, 2432 false, 0); 2433 } 2434 2435 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2436 SelectionDAG &DAG) const { 2437 EVT PtrVT = Op.getValueType(); 2438 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2439 const Constant *C = CP->getConstVal(); 2440 2441 // 64-bit SVR4 ABI code is always position-independent. 2442 // The actual address of the GlobalValue is stored in the TOC. 2443 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2444 setUsesTOCBasePtr(DAG); 2445 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2446 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2447 } 2448 2449 unsigned MOHiFlag, MOLoFlag; 2450 bool IsPIC = isPositionIndependent(); 2451 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2452 2453 if (IsPIC && Subtarget.isSVR4ABI()) { 2454 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2455 PPCII::MO_PIC_FLAG); 2456 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2457 } 2458 2459 SDValue CPIHi = 2460 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2461 SDValue CPILo = 2462 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2463 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2464 } 2465 2466 // For 64-bit PowerPC, prefer the more compact relative encodings. 2467 // This trades 32 bits per jump table entry for one or two instructions 2468 // on the jump site. 2469 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2470 if (isJumpTableRelative()) 2471 return MachineJumpTableInfo::EK_LabelDifference32; 2472 2473 return TargetLowering::getJumpTableEncoding(); 2474 } 2475 2476 bool PPCTargetLowering::isJumpTableRelative() const { 2477 if (Subtarget.isPPC64()) 2478 return true; 2479 return TargetLowering::isJumpTableRelative(); 2480 } 2481 2482 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2483 SelectionDAG &DAG) const { 2484 if (!Subtarget.isPPC64()) 2485 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2486 2487 switch (getTargetMachine().getCodeModel()) { 2488 case CodeModel::Small: 2489 case CodeModel::Medium: 2490 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2491 default: 2492 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2493 getPointerTy(DAG.getDataLayout())); 2494 } 2495 } 2496 2497 const MCExpr * 2498 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2499 unsigned JTI, 2500 MCContext &Ctx) const { 2501 if (!Subtarget.isPPC64()) 2502 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2503 2504 switch (getTargetMachine().getCodeModel()) { 2505 case CodeModel::Small: 2506 case CodeModel::Medium: 2507 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2508 default: 2509 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2510 } 2511 } 2512 2513 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2514 EVT PtrVT = Op.getValueType(); 2515 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2516 2517 // 64-bit SVR4 ABI code is always position-independent. 2518 // The actual address of the GlobalValue is stored in the TOC. 2519 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2520 setUsesTOCBasePtr(DAG); 2521 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2522 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2523 } 2524 2525 unsigned MOHiFlag, MOLoFlag; 2526 bool IsPIC = isPositionIndependent(); 2527 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2528 2529 if (IsPIC && Subtarget.isSVR4ABI()) { 2530 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2531 PPCII::MO_PIC_FLAG); 2532 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2533 } 2534 2535 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2536 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2537 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2538 } 2539 2540 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2541 SelectionDAG &DAG) const { 2542 EVT PtrVT = Op.getValueType(); 2543 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2544 const BlockAddress *BA = BASDN->getBlockAddress(); 2545 2546 // 64-bit SVR4 ABI code is always position-independent. 2547 // The actual BlockAddress is stored in the TOC. 2548 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2549 setUsesTOCBasePtr(DAG); 2550 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2551 return getTOCEntry(DAG, SDLoc(BASDN), true, GA); 2552 } 2553 2554 unsigned MOHiFlag, MOLoFlag; 2555 bool IsPIC = isPositionIndependent(); 2556 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2557 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2558 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2559 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2560 } 2561 2562 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2563 SelectionDAG &DAG) const { 2564 // FIXME: TLS addresses currently use medium model code sequences, 2565 // which is the most useful form. Eventually support for small and 2566 // large models could be added if users need it, at the cost of 2567 // additional complexity. 2568 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2569 if (DAG.getTarget().Options.EmulatedTLS) 2570 return LowerToTLSEmulatedModel(GA, DAG); 2571 2572 SDLoc dl(GA); 2573 const GlobalValue *GV = GA->getGlobal(); 2574 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2575 bool is64bit = Subtarget.isPPC64(); 2576 const Module *M = DAG.getMachineFunction().getFunction()->getParent(); 2577 PICLevel::Level picLevel = M->getPICLevel(); 2578 2579 TLSModel::Model Model = getTargetMachine().getTLSModel(GV); 2580 2581 if (Model == TLSModel::LocalExec) { 2582 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2583 PPCII::MO_TPREL_HA); 2584 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2585 PPCII::MO_TPREL_LO); 2586 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2587 : DAG.getRegister(PPC::R2, MVT::i32); 2588 2589 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2590 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2591 } 2592 2593 if (Model == TLSModel::InitialExec) { 2594 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2595 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2596 PPCII::MO_TLS); 2597 SDValue GOTPtr; 2598 if (is64bit) { 2599 setUsesTOCBasePtr(DAG); 2600 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2601 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2602 PtrVT, GOTReg, TGA); 2603 } else 2604 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2605 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2606 PtrVT, TGA, GOTPtr); 2607 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2608 } 2609 2610 if (Model == TLSModel::GeneralDynamic) { 2611 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2612 SDValue GOTPtr; 2613 if (is64bit) { 2614 setUsesTOCBasePtr(DAG); 2615 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2616 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2617 GOTReg, TGA); 2618 } else { 2619 if (picLevel == PICLevel::SmallPIC) 2620 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2621 else 2622 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2623 } 2624 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2625 GOTPtr, TGA, TGA); 2626 } 2627 2628 if (Model == TLSModel::LocalDynamic) { 2629 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2630 SDValue GOTPtr; 2631 if (is64bit) { 2632 setUsesTOCBasePtr(DAG); 2633 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2634 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2635 GOTReg, TGA); 2636 } else { 2637 if (picLevel == PICLevel::SmallPIC) 2638 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2639 else 2640 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2641 } 2642 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2643 PtrVT, GOTPtr, TGA, TGA); 2644 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2645 PtrVT, TLSAddr, TGA); 2646 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2647 } 2648 2649 llvm_unreachable("Unknown TLS model!"); 2650 } 2651 2652 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2653 SelectionDAG &DAG) const { 2654 EVT PtrVT = Op.getValueType(); 2655 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2656 SDLoc DL(GSDN); 2657 const GlobalValue *GV = GSDN->getGlobal(); 2658 2659 // 64-bit SVR4 ABI code is always position-independent. 2660 // The actual address of the GlobalValue is stored in the TOC. 2661 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2662 setUsesTOCBasePtr(DAG); 2663 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2664 return getTOCEntry(DAG, DL, true, GA); 2665 } 2666 2667 unsigned MOHiFlag, MOLoFlag; 2668 bool IsPIC = isPositionIndependent(); 2669 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2670 2671 if (IsPIC && Subtarget.isSVR4ABI()) { 2672 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2673 GSDN->getOffset(), 2674 PPCII::MO_PIC_FLAG); 2675 return getTOCEntry(DAG, DL, false, GA); 2676 } 2677 2678 SDValue GAHi = 2679 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2680 SDValue GALo = 2681 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2682 2683 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2684 2685 // If the global reference is actually to a non-lazy-pointer, we have to do an 2686 // extra load to get the address of the global. 2687 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2688 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2689 return Ptr; 2690 } 2691 2692 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2693 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2694 SDLoc dl(Op); 2695 2696 if (Op.getValueType() == MVT::v2i64) { 2697 // When the operands themselves are v2i64 values, we need to do something 2698 // special because VSX has no underlying comparison operations for these. 2699 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2700 // Equality can be handled by casting to the legal type for Altivec 2701 // comparisons, everything else needs to be expanded. 2702 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2703 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2704 DAG.getSetCC(dl, MVT::v4i32, 2705 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2706 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2707 CC)); 2708 } 2709 2710 return SDValue(); 2711 } 2712 2713 // We handle most of these in the usual way. 2714 return Op; 2715 } 2716 2717 // If we're comparing for equality to zero, expose the fact that this is 2718 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2719 // fold the new nodes. 2720 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2721 return V; 2722 2723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2724 // Leave comparisons against 0 and -1 alone for now, since they're usually 2725 // optimized. FIXME: revisit this when we can custom lower all setcc 2726 // optimizations. 2727 if (C->isAllOnesValue() || C->isNullValue()) 2728 return SDValue(); 2729 } 2730 2731 // If we have an integer seteq/setne, turn it into a compare against zero 2732 // by xor'ing the rhs with the lhs, which is faster than setting a 2733 // condition register, reading it back out, and masking the correct bit. The 2734 // normal approach here uses sub to do this instead of xor. Using xor exposes 2735 // the result to other bit-twiddling opportunities. 2736 EVT LHSVT = Op.getOperand(0).getValueType(); 2737 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2738 EVT VT = Op.getValueType(); 2739 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 2740 Op.getOperand(1)); 2741 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 2742 } 2743 return SDValue(); 2744 } 2745 2746 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 2747 SDNode *Node = Op.getNode(); 2748 EVT VT = Node->getValueType(0); 2749 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2750 SDValue InChain = Node->getOperand(0); 2751 SDValue VAListPtr = Node->getOperand(1); 2752 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2753 SDLoc dl(Node); 2754 2755 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 2756 2757 // gpr_index 2758 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2759 VAListPtr, MachinePointerInfo(SV), MVT::i8); 2760 InChain = GprIndex.getValue(1); 2761 2762 if (VT == MVT::i64) { 2763 // Check if GprIndex is even 2764 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 2765 DAG.getConstant(1, dl, MVT::i32)); 2766 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 2767 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 2768 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 2769 DAG.getConstant(1, dl, MVT::i32)); 2770 // Align GprIndex to be even if it isn't 2771 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 2772 GprIndex); 2773 } 2774 2775 // fpr index is 1 byte after gpr 2776 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2777 DAG.getConstant(1, dl, MVT::i32)); 2778 2779 // fpr 2780 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 2781 FprPtr, MachinePointerInfo(SV), MVT::i8); 2782 InChain = FprIndex.getValue(1); 2783 2784 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2785 DAG.getConstant(8, dl, MVT::i32)); 2786 2787 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 2788 DAG.getConstant(4, dl, MVT::i32)); 2789 2790 // areas 2791 SDValue OverflowArea = 2792 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 2793 InChain = OverflowArea.getValue(1); 2794 2795 SDValue RegSaveArea = 2796 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 2797 InChain = RegSaveArea.getValue(1); 2798 2799 // select overflow_area if index > 8 2800 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 2801 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 2802 2803 // adjustment constant gpr_index * 4/8 2804 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 2805 VT.isInteger() ? GprIndex : FprIndex, 2806 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 2807 MVT::i32)); 2808 2809 // OurReg = RegSaveArea + RegConstant 2810 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 2811 RegConstant); 2812 2813 // Floating types are 32 bytes into RegSaveArea 2814 if (VT.isFloatingPoint()) 2815 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 2816 DAG.getConstant(32, dl, MVT::i32)); 2817 2818 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 2819 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 2820 VT.isInteger() ? GprIndex : FprIndex, 2821 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 2822 MVT::i32)); 2823 2824 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 2825 VT.isInteger() ? VAListPtr : FprPtr, 2826 MachinePointerInfo(SV), MVT::i8); 2827 2828 // determine if we should load from reg_save_area or overflow_area 2829 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 2830 2831 // increase overflow_area by 4/8 if gpr/fpr > 8 2832 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 2833 DAG.getConstant(VT.isInteger() ? 4 : 8, 2834 dl, MVT::i32)); 2835 2836 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 2837 OverflowAreaPlusN); 2838 2839 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 2840 MachinePointerInfo(), MVT::i32); 2841 2842 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 2843 } 2844 2845 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 2846 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 2847 2848 // We have to copy the entire va_list struct: 2849 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 2850 return DAG.getMemcpy(Op.getOperand(0), Op, 2851 Op.getOperand(1), Op.getOperand(2), 2852 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 2853 false, MachinePointerInfo(), MachinePointerInfo()); 2854 } 2855 2856 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 2857 SelectionDAG &DAG) const { 2858 return Op.getOperand(0); 2859 } 2860 2861 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 2862 SelectionDAG &DAG) const { 2863 SDValue Chain = Op.getOperand(0); 2864 SDValue Trmp = Op.getOperand(1); // trampoline 2865 SDValue FPtr = Op.getOperand(2); // nested function 2866 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 2867 SDLoc dl(Op); 2868 2869 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2870 bool isPPC64 = (PtrVT == MVT::i64); 2871 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 2872 2873 TargetLowering::ArgListTy Args; 2874 TargetLowering::ArgListEntry Entry; 2875 2876 Entry.Ty = IntPtrTy; 2877 Entry.Node = Trmp; Args.push_back(Entry); 2878 2879 // TrampSize == (isPPC64 ? 48 : 40); 2880 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 2881 isPPC64 ? MVT::i64 : MVT::i32); 2882 Args.push_back(Entry); 2883 2884 Entry.Node = FPtr; Args.push_back(Entry); 2885 Entry.Node = Nest; Args.push_back(Entry); 2886 2887 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 2888 TargetLowering::CallLoweringInfo CLI(DAG); 2889 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 2890 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 2891 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 2892 2893 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2894 return CallResult.second; 2895 } 2896 2897 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 2898 MachineFunction &MF = DAG.getMachineFunction(); 2899 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2900 EVT PtrVT = getPointerTy(MF.getDataLayout()); 2901 2902 SDLoc dl(Op); 2903 2904 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 2905 // vastart just stores the address of the VarArgsFrameIndex slot into the 2906 // memory location argument. 2907 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 2908 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2909 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 2910 MachinePointerInfo(SV)); 2911 } 2912 2913 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 2914 // We suppose the given va_list is already allocated. 2915 // 2916 // typedef struct { 2917 // char gpr; /* index into the array of 8 GPRs 2918 // * stored in the register save area 2919 // * gpr=0 corresponds to r3, 2920 // * gpr=1 to r4, etc. 2921 // */ 2922 // char fpr; /* index into the array of 8 FPRs 2923 // * stored in the register save area 2924 // * fpr=0 corresponds to f1, 2925 // * fpr=1 to f2, etc. 2926 // */ 2927 // char *overflow_arg_area; 2928 // /* location on stack that holds 2929 // * the next overflow argument 2930 // */ 2931 // char *reg_save_area; 2932 // /* where r3:r10 and f1:f8 (if saved) 2933 // * are stored 2934 // */ 2935 // } va_list[1]; 2936 2937 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 2938 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 2939 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 2940 PtrVT); 2941 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 2942 PtrVT); 2943 2944 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 2945 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 2946 2947 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 2948 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 2949 2950 uint64_t FPROffset = 1; 2951 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 2952 2953 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 2954 2955 // Store first byte : number of int regs 2956 SDValue firstStore = 2957 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 2958 MachinePointerInfo(SV), MVT::i8); 2959 uint64_t nextOffset = FPROffset; 2960 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 2961 ConstFPROffset); 2962 2963 // Store second byte : number of float regs 2964 SDValue secondStore = 2965 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 2966 MachinePointerInfo(SV, nextOffset), MVT::i8); 2967 nextOffset += StackOffset; 2968 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 2969 2970 // Store second word : arguments given on stack 2971 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 2972 MachinePointerInfo(SV, nextOffset)); 2973 nextOffset += FrameOffset; 2974 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 2975 2976 // Store third word : arguments given in registers 2977 return DAG.getStore(thirdStore, dl, FR, nextPtr, 2978 MachinePointerInfo(SV, nextOffset)); 2979 } 2980 2981 #include "PPCGenCallingConv.inc" 2982 2983 // Function whose sole purpose is to kill compiler warnings 2984 // stemming from unused functions included from PPCGenCallingConv.inc. 2985 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { 2986 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; 2987 } 2988 2989 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, 2990 CCValAssign::LocInfo &LocInfo, 2991 ISD::ArgFlagsTy &ArgFlags, 2992 CCState &State) { 2993 return true; 2994 } 2995 2996 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, 2997 MVT &LocVT, 2998 CCValAssign::LocInfo &LocInfo, 2999 ISD::ArgFlagsTy &ArgFlags, 3000 CCState &State) { 3001 static const MCPhysReg ArgRegs[] = { 3002 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3003 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3004 }; 3005 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3006 3007 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3008 3009 // Skip one register if the first unallocated register has an even register 3010 // number and there are still argument registers available which have not been 3011 // allocated yet. RegNum is actually an index into ArgRegs, which means we 3012 // need to skip a register if RegNum is odd. 3013 if (RegNum != NumArgRegs && RegNum % 2 == 1) { 3014 State.AllocateReg(ArgRegs[RegNum]); 3015 } 3016 3017 // Always return false here, as this function only makes sure that the first 3018 // unallocated register has an odd register number and does not actually 3019 // allocate a register for the current argument. 3020 return false; 3021 } 3022 3023 bool 3024 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT, 3025 MVT &LocVT, 3026 CCValAssign::LocInfo &LocInfo, 3027 ISD::ArgFlagsTy &ArgFlags, 3028 CCState &State) { 3029 static const MCPhysReg ArgRegs[] = { 3030 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3031 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3032 }; 3033 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3034 3035 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3036 int RegsLeft = NumArgRegs - RegNum; 3037 3038 // Skip if there is not enough registers left for long double type (4 gpr regs 3039 // in soft float mode) and put long double argument on the stack. 3040 if (RegNum != NumArgRegs && RegsLeft < 4) { 3041 for (int i = 0; i < RegsLeft; i++) { 3042 State.AllocateReg(ArgRegs[RegNum + i]); 3043 } 3044 } 3045 3046 return false; 3047 } 3048 3049 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, 3050 MVT &LocVT, 3051 CCValAssign::LocInfo &LocInfo, 3052 ISD::ArgFlagsTy &ArgFlags, 3053 CCState &State) { 3054 static const MCPhysReg ArgRegs[] = { 3055 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3056 PPC::F8 3057 }; 3058 3059 const unsigned NumArgRegs = array_lengthof(ArgRegs); 3060 3061 unsigned RegNum = State.getFirstUnallocated(ArgRegs); 3062 3063 // If there is only one Floating-point register left we need to put both f64 3064 // values of a split ppc_fp128 value on the stack. 3065 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { 3066 State.AllocateReg(ArgRegs[RegNum]); 3067 } 3068 3069 // Always return false here, as this function only makes sure that the two f64 3070 // values a ppc_fp128 value is split into are both passed in registers or both 3071 // passed on the stack and does not actually allocate a register for the 3072 // current argument. 3073 return false; 3074 } 3075 3076 /// FPR - The set of FP registers that should be allocated for arguments, 3077 /// on Darwin. 3078 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3079 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3080 PPC::F11, PPC::F12, PPC::F13}; 3081 3082 /// QFPR - The set of QPX registers that should be allocated for arguments. 3083 static const MCPhysReg QFPR[] = { 3084 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3085 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3086 3087 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3088 /// the stack. 3089 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3090 unsigned PtrByteSize) { 3091 unsigned ArgSize = ArgVT.getStoreSize(); 3092 if (Flags.isByVal()) 3093 ArgSize = Flags.getByValSize(); 3094 3095 // Round up to multiples of the pointer size, except for array members, 3096 // which are always packed. 3097 if (!Flags.isInConsecutiveRegs()) 3098 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3099 3100 return ArgSize; 3101 } 3102 3103 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3104 /// on the stack. 3105 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3106 ISD::ArgFlagsTy Flags, 3107 unsigned PtrByteSize) { 3108 unsigned Align = PtrByteSize; 3109 3110 // Altivec parameters are padded to a 16 byte boundary. 3111 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3112 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3113 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3114 ArgVT == MVT::v1i128) 3115 Align = 16; 3116 // QPX vector types stored in double-precision are padded to a 32 byte 3117 // boundary. 3118 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3119 Align = 32; 3120 3121 // ByVal parameters are aligned as requested. 3122 if (Flags.isByVal()) { 3123 unsigned BVAlign = Flags.getByValAlign(); 3124 if (BVAlign > PtrByteSize) { 3125 if (BVAlign % PtrByteSize != 0) 3126 llvm_unreachable( 3127 "ByVal alignment is not a multiple of the pointer size"); 3128 3129 Align = BVAlign; 3130 } 3131 } 3132 3133 // Array members are always packed to their original alignment. 3134 if (Flags.isInConsecutiveRegs()) { 3135 // If the array member was split into multiple registers, the first 3136 // needs to be aligned to the size of the full type. (Except for 3137 // ppcf128, which is only aligned as its f64 components.) 3138 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3139 Align = OrigVT.getStoreSize(); 3140 else 3141 Align = ArgVT.getStoreSize(); 3142 } 3143 3144 return Align; 3145 } 3146 3147 /// CalculateStackSlotUsed - Return whether this argument will use its 3148 /// stack slot (instead of being passed in registers). ArgOffset, 3149 /// AvailableFPRs, and AvailableVRs must hold the current argument 3150 /// position, and will be updated to account for this argument. 3151 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3152 ISD::ArgFlagsTy Flags, 3153 unsigned PtrByteSize, 3154 unsigned LinkageSize, 3155 unsigned ParamAreaSize, 3156 unsigned &ArgOffset, 3157 unsigned &AvailableFPRs, 3158 unsigned &AvailableVRs, bool HasQPX) { 3159 bool UseMemory = false; 3160 3161 // Respect alignment of argument on the stack. 3162 unsigned Align = 3163 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3164 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3165 // If there's no space left in the argument save area, we must 3166 // use memory (this check also catches zero-sized arguments). 3167 if (ArgOffset >= LinkageSize + ParamAreaSize) 3168 UseMemory = true; 3169 3170 // Allocate argument on the stack. 3171 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3172 if (Flags.isInConsecutiveRegsLast()) 3173 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3174 // If we overran the argument save area, we must use memory 3175 // (this check catches arguments passed partially in memory) 3176 if (ArgOffset > LinkageSize + ParamAreaSize) 3177 UseMemory = true; 3178 3179 // However, if the argument is actually passed in an FPR or a VR, 3180 // we don't use memory after all. 3181 if (!Flags.isByVal()) { 3182 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3183 // QPX registers overlap with the scalar FP registers. 3184 (HasQPX && (ArgVT == MVT::v4f32 || 3185 ArgVT == MVT::v4f64 || 3186 ArgVT == MVT::v4i1))) 3187 if (AvailableFPRs > 0) { 3188 --AvailableFPRs; 3189 return false; 3190 } 3191 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3192 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3193 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3194 ArgVT == MVT::v1i128) 3195 if (AvailableVRs > 0) { 3196 --AvailableVRs; 3197 return false; 3198 } 3199 } 3200 3201 return UseMemory; 3202 } 3203 3204 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3205 /// ensure minimum alignment required for target. 3206 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3207 unsigned NumBytes) { 3208 unsigned TargetAlign = Lowering->getStackAlignment(); 3209 unsigned AlignMask = TargetAlign - 1; 3210 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3211 return NumBytes; 3212 } 3213 3214 SDValue PPCTargetLowering::LowerFormalArguments( 3215 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3216 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3217 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3218 if (Subtarget.isSVR4ABI()) { 3219 if (Subtarget.isPPC64()) 3220 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3221 dl, DAG, InVals); 3222 else 3223 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3224 dl, DAG, InVals); 3225 } else { 3226 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3227 dl, DAG, InVals); 3228 } 3229 } 3230 3231 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3232 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3233 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3234 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3235 3236 // 32-bit SVR4 ABI Stack Frame Layout: 3237 // +-----------------------------------+ 3238 // +--> | Back chain | 3239 // | +-----------------------------------+ 3240 // | | Floating-point register save area | 3241 // | +-----------------------------------+ 3242 // | | General register save area | 3243 // | +-----------------------------------+ 3244 // | | CR save word | 3245 // | +-----------------------------------+ 3246 // | | VRSAVE save word | 3247 // | +-----------------------------------+ 3248 // | | Alignment padding | 3249 // | +-----------------------------------+ 3250 // | | Vector register save area | 3251 // | +-----------------------------------+ 3252 // | | Local variable space | 3253 // | +-----------------------------------+ 3254 // | | Parameter list area | 3255 // | +-----------------------------------+ 3256 // | | LR save word | 3257 // | +-----------------------------------+ 3258 // SP--> +--- | Back chain | 3259 // +-----------------------------------+ 3260 // 3261 // Specifications: 3262 // System V Application Binary Interface PowerPC Processor Supplement 3263 // AltiVec Technology Programming Interface Manual 3264 3265 MachineFunction &MF = DAG.getMachineFunction(); 3266 MachineFrameInfo &MFI = MF.getFrameInfo(); 3267 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3268 3269 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3270 // Potential tail calls could cause overwriting of argument stack slots. 3271 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3272 (CallConv == CallingConv::Fast)); 3273 unsigned PtrByteSize = 4; 3274 3275 // Assign locations to all of the incoming arguments. 3276 SmallVector<CCValAssign, 16> ArgLocs; 3277 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3278 *DAG.getContext()); 3279 3280 // Reserve space for the linkage area on the stack. 3281 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3282 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3283 if (useSoftFloat()) 3284 CCInfo.PreAnalyzeFormalArguments(Ins); 3285 3286 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3287 CCInfo.clearWasPPCF128(); 3288 3289 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3290 CCValAssign &VA = ArgLocs[i]; 3291 3292 // Arguments stored in registers. 3293 if (VA.isRegLoc()) { 3294 const TargetRegisterClass *RC; 3295 EVT ValVT = VA.getValVT(); 3296 3297 switch (ValVT.getSimpleVT().SimpleTy) { 3298 default: 3299 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3300 case MVT::i1: 3301 case MVT::i32: 3302 RC = &PPC::GPRCRegClass; 3303 break; 3304 case MVT::f32: 3305 if (Subtarget.hasP8Vector()) 3306 RC = &PPC::VSSRCRegClass; 3307 else 3308 RC = &PPC::F4RCRegClass; 3309 break; 3310 case MVT::f64: 3311 if (Subtarget.hasVSX()) 3312 RC = &PPC::VSFRCRegClass; 3313 else 3314 RC = &PPC::F8RCRegClass; 3315 break; 3316 case MVT::v16i8: 3317 case MVT::v8i16: 3318 case MVT::v4i32: 3319 RC = &PPC::VRRCRegClass; 3320 break; 3321 case MVT::v4f32: 3322 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3323 break; 3324 case MVT::v2f64: 3325 case MVT::v2i64: 3326 RC = &PPC::VRRCRegClass; 3327 break; 3328 case MVT::v4f64: 3329 RC = &PPC::QFRCRegClass; 3330 break; 3331 case MVT::v4i1: 3332 RC = &PPC::QBRCRegClass; 3333 break; 3334 } 3335 3336 // Transform the arguments stored in physical registers into virtual ones. 3337 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3338 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3339 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3340 3341 if (ValVT == MVT::i1) 3342 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3343 3344 InVals.push_back(ArgValue); 3345 } else { 3346 // Argument stored in memory. 3347 assert(VA.isMemLoc()); 3348 3349 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3350 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(), 3351 isImmutable); 3352 3353 // Create load nodes to retrieve arguments from the stack. 3354 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3355 InVals.push_back( 3356 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3357 } 3358 } 3359 3360 // Assign locations to all of the incoming aggregate by value arguments. 3361 // Aggregates passed by value are stored in the local variable space of the 3362 // caller's stack frame, right above the parameter list area. 3363 SmallVector<CCValAssign, 16> ByValArgLocs; 3364 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3365 ByValArgLocs, *DAG.getContext()); 3366 3367 // Reserve stack space for the allocations in CCInfo. 3368 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3369 3370 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3371 3372 // Area that is at least reserved in the caller of this function. 3373 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3374 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3375 3376 // Set the size that is at least reserved in caller of this function. Tail 3377 // call optimized function's reserved stack space needs to be aligned so that 3378 // taking the difference between two stack areas will result in an aligned 3379 // stack. 3380 MinReservedArea = 3381 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3382 FuncInfo->setMinReservedArea(MinReservedArea); 3383 3384 SmallVector<SDValue, 8> MemOps; 3385 3386 // If the function takes variable number of arguments, make a frame index for 3387 // the start of the first vararg value... for expansion of llvm.va_start. 3388 if (isVarArg) { 3389 static const MCPhysReg GPArgRegs[] = { 3390 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3391 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3392 }; 3393 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3394 3395 static const MCPhysReg FPArgRegs[] = { 3396 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3397 PPC::F8 3398 }; 3399 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3400 3401 if (useSoftFloat()) 3402 NumFPArgRegs = 0; 3403 3404 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3405 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3406 3407 // Make room for NumGPArgRegs and NumFPArgRegs. 3408 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3409 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3410 3411 FuncInfo->setVarArgsStackOffset( 3412 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3413 CCInfo.getNextStackOffset(), true)); 3414 3415 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3416 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3417 3418 // The fixed integer arguments of a variadic function are stored to the 3419 // VarArgsFrameIndex on the stack so that they may be loaded by 3420 // dereferencing the result of va_next. 3421 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3422 // Get an existing live-in vreg, or add a new one. 3423 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3424 if (!VReg) 3425 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3426 3427 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3428 SDValue Store = 3429 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3430 MemOps.push_back(Store); 3431 // Increment the address by four for the next argument to store 3432 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3433 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3434 } 3435 3436 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3437 // is set. 3438 // The double arguments are stored to the VarArgsFrameIndex 3439 // on the stack. 3440 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3441 // Get an existing live-in vreg, or add a new one. 3442 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3443 if (!VReg) 3444 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3445 3446 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3447 SDValue Store = 3448 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3449 MemOps.push_back(Store); 3450 // Increment the address by eight for the next argument to store 3451 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3452 PtrVT); 3453 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3454 } 3455 } 3456 3457 if (!MemOps.empty()) 3458 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3459 3460 return Chain; 3461 } 3462 3463 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3464 // value to MVT::i64 and then truncate to the correct register size. 3465 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3466 EVT ObjectVT, SelectionDAG &DAG, 3467 SDValue ArgVal, 3468 const SDLoc &dl) const { 3469 if (Flags.isSExt()) 3470 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3471 DAG.getValueType(ObjectVT)); 3472 else if (Flags.isZExt()) 3473 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3474 DAG.getValueType(ObjectVT)); 3475 3476 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3477 } 3478 3479 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3480 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3481 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3482 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3483 // TODO: add description of PPC stack frame format, or at least some docs. 3484 // 3485 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3486 bool isLittleEndian = Subtarget.isLittleEndian(); 3487 MachineFunction &MF = DAG.getMachineFunction(); 3488 MachineFrameInfo &MFI = MF.getFrameInfo(); 3489 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3490 3491 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3492 "fastcc not supported on varargs functions"); 3493 3494 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3495 // Potential tail calls could cause overwriting of argument stack slots. 3496 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3497 (CallConv == CallingConv::Fast)); 3498 unsigned PtrByteSize = 8; 3499 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3500 3501 static const MCPhysReg GPR[] = { 3502 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3503 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3504 }; 3505 static const MCPhysReg VR[] = { 3506 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3507 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3508 }; 3509 3510 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3511 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3512 const unsigned Num_VR_Regs = array_lengthof(VR); 3513 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3514 3515 // Do a first pass over the arguments to determine whether the ABI 3516 // guarantees that our caller has allocated the parameter save area 3517 // on its stack frame. In the ELFv1 ABI, this is always the case; 3518 // in the ELFv2 ABI, it is true if this is a vararg function or if 3519 // any parameter is located in a stack slot. 3520 3521 bool HasParameterArea = !isELFv2ABI || isVarArg; 3522 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3523 unsigned NumBytes = LinkageSize; 3524 unsigned AvailableFPRs = Num_FPR_Regs; 3525 unsigned AvailableVRs = Num_VR_Regs; 3526 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3527 if (Ins[i].Flags.isNest()) 3528 continue; 3529 3530 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3531 PtrByteSize, LinkageSize, ParamAreaSize, 3532 NumBytes, AvailableFPRs, AvailableVRs, 3533 Subtarget.hasQPX())) 3534 HasParameterArea = true; 3535 } 3536 3537 // Add DAG nodes to load the arguments or copy them out of registers. On 3538 // entry to a function on PPC, the arguments start after the linkage area, 3539 // although the first ones are often in registers. 3540 3541 unsigned ArgOffset = LinkageSize; 3542 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3543 unsigned &QFPR_idx = FPR_idx; 3544 SmallVector<SDValue, 8> MemOps; 3545 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3546 unsigned CurArgIdx = 0; 3547 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3548 SDValue ArgVal; 3549 bool needsLoad = false; 3550 EVT ObjectVT = Ins[ArgNo].VT; 3551 EVT OrigVT = Ins[ArgNo].ArgVT; 3552 unsigned ObjSize = ObjectVT.getStoreSize(); 3553 unsigned ArgSize = ObjSize; 3554 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3555 if (Ins[ArgNo].isOrigArg()) { 3556 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3557 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3558 } 3559 // We re-align the argument offset for each argument, except when using the 3560 // fast calling convention, when we need to make sure we do that only when 3561 // we'll actually use a stack slot. 3562 unsigned CurArgOffset, Align; 3563 auto ComputeArgOffset = [&]() { 3564 /* Respect alignment of argument on the stack. */ 3565 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3566 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3567 CurArgOffset = ArgOffset; 3568 }; 3569 3570 if (CallConv != CallingConv::Fast) { 3571 ComputeArgOffset(); 3572 3573 /* Compute GPR index associated with argument offset. */ 3574 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3575 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3576 } 3577 3578 // FIXME the codegen can be much improved in some cases. 3579 // We do not have to keep everything in memory. 3580 if (Flags.isByVal()) { 3581 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3582 3583 if (CallConv == CallingConv::Fast) 3584 ComputeArgOffset(); 3585 3586 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3587 ObjSize = Flags.getByValSize(); 3588 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3589 // Empty aggregate parameters do not take up registers. Examples: 3590 // struct { } a; 3591 // union { } b; 3592 // int c[0]; 3593 // etc. However, we have to provide a place-holder in InVals, so 3594 // pretend we have an 8-byte item at the current address for that 3595 // purpose. 3596 if (!ObjSize) { 3597 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3598 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3599 InVals.push_back(FIN); 3600 continue; 3601 } 3602 3603 // Create a stack object covering all stack doublewords occupied 3604 // by the argument. If the argument is (fully or partially) on 3605 // the stack, or if the argument is fully in registers but the 3606 // caller has allocated the parameter save anyway, we can refer 3607 // directly to the caller's stack frame. Otherwise, create a 3608 // local copy in our own frame. 3609 int FI; 3610 if (HasParameterArea || 3611 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3612 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3613 else 3614 FI = MFI.CreateStackObject(ArgSize, Align, false); 3615 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3616 3617 // Handle aggregates smaller than 8 bytes. 3618 if (ObjSize < PtrByteSize) { 3619 // The value of the object is its address, which differs from the 3620 // address of the enclosing doubleword on big-endian systems. 3621 SDValue Arg = FIN; 3622 if (!isLittleEndian) { 3623 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3624 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3625 } 3626 InVals.push_back(Arg); 3627 3628 if (GPR_idx != Num_GPR_Regs) { 3629 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3630 FuncInfo->addLiveInAttr(VReg, Flags); 3631 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3632 SDValue Store; 3633 3634 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3635 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3636 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3637 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3638 MachinePointerInfo(&*FuncArg), ObjType); 3639 } else { 3640 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3641 // store the whole register as-is to the parameter save area 3642 // slot. 3643 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3644 MachinePointerInfo(&*FuncArg)); 3645 } 3646 3647 MemOps.push_back(Store); 3648 } 3649 // Whether we copied from a register or not, advance the offset 3650 // into the parameter save area by a full doubleword. 3651 ArgOffset += PtrByteSize; 3652 continue; 3653 } 3654 3655 // The value of the object is its address, which is the address of 3656 // its first stack doubleword. 3657 InVals.push_back(FIN); 3658 3659 // Store whatever pieces of the object are in registers to memory. 3660 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3661 if (GPR_idx == Num_GPR_Regs) 3662 break; 3663 3664 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3665 FuncInfo->addLiveInAttr(VReg, Flags); 3666 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3667 SDValue Addr = FIN; 3668 if (j) { 3669 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3670 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3671 } 3672 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3673 MachinePointerInfo(&*FuncArg, j)); 3674 MemOps.push_back(Store); 3675 ++GPR_idx; 3676 } 3677 ArgOffset += ArgSize; 3678 continue; 3679 } 3680 3681 switch (ObjectVT.getSimpleVT().SimpleTy) { 3682 default: llvm_unreachable("Unhandled argument type!"); 3683 case MVT::i1: 3684 case MVT::i32: 3685 case MVT::i64: 3686 if (Flags.isNest()) { 3687 // The 'nest' parameter, if any, is passed in R11. 3688 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3689 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3690 3691 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3692 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3693 3694 break; 3695 } 3696 3697 // These can be scalar arguments or elements of an integer array type 3698 // passed directly. Clang may use those instead of "byval" aggregate 3699 // types to avoid forcing arguments to memory unnecessarily. 3700 if (GPR_idx != Num_GPR_Regs) { 3701 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3702 FuncInfo->addLiveInAttr(VReg, Flags); 3703 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3704 3705 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3706 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3707 // value to MVT::i64 and then truncate to the correct register size. 3708 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3709 } else { 3710 if (CallConv == CallingConv::Fast) 3711 ComputeArgOffset(); 3712 3713 needsLoad = true; 3714 ArgSize = PtrByteSize; 3715 } 3716 if (CallConv != CallingConv::Fast || needsLoad) 3717 ArgOffset += 8; 3718 break; 3719 3720 case MVT::f32: 3721 case MVT::f64: 3722 // These can be scalar arguments or elements of a float array type 3723 // passed directly. The latter are used to implement ELFv2 homogenous 3724 // float aggregates. 3725 if (FPR_idx != Num_FPR_Regs) { 3726 unsigned VReg; 3727 3728 if (ObjectVT == MVT::f32) 3729 VReg = MF.addLiveIn(FPR[FPR_idx], 3730 Subtarget.hasP8Vector() 3731 ? &PPC::VSSRCRegClass 3732 : &PPC::F4RCRegClass); 3733 else 3734 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3735 ? &PPC::VSFRCRegClass 3736 : &PPC::F8RCRegClass); 3737 3738 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3739 ++FPR_idx; 3740 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3741 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3742 // once we support fp <-> gpr moves. 3743 3744 // This can only ever happen in the presence of f32 array types, 3745 // since otherwise we never run out of FPRs before running out 3746 // of GPRs. 3747 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3748 FuncInfo->addLiveInAttr(VReg, Flags); 3749 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3750 3751 if (ObjectVT == MVT::f32) { 3752 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3753 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3754 DAG.getConstant(32, dl, MVT::i32)); 3755 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3756 } 3757 3758 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3759 } else { 3760 if (CallConv == CallingConv::Fast) 3761 ComputeArgOffset(); 3762 3763 needsLoad = true; 3764 } 3765 3766 // When passing an array of floats, the array occupies consecutive 3767 // space in the argument area; only round up to the next doubleword 3768 // at the end of the array. Otherwise, each float takes 8 bytes. 3769 if (CallConv != CallingConv::Fast || needsLoad) { 3770 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3771 ArgOffset += ArgSize; 3772 if (Flags.isInConsecutiveRegsLast()) 3773 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3774 } 3775 break; 3776 case MVT::v4f32: 3777 case MVT::v4i32: 3778 case MVT::v8i16: 3779 case MVT::v16i8: 3780 case MVT::v2f64: 3781 case MVT::v2i64: 3782 case MVT::v1i128: 3783 if (!Subtarget.hasQPX()) { 3784 // These can be scalar arguments or elements of a vector array type 3785 // passed directly. The latter are used to implement ELFv2 homogenous 3786 // vector aggregates. 3787 if (VR_idx != Num_VR_Regs) { 3788 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3789 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3790 ++VR_idx; 3791 } else { 3792 if (CallConv == CallingConv::Fast) 3793 ComputeArgOffset(); 3794 3795 needsLoad = true; 3796 } 3797 if (CallConv != CallingConv::Fast || needsLoad) 3798 ArgOffset += 16; 3799 break; 3800 } // not QPX 3801 3802 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3803 "Invalid QPX parameter type"); 3804 /* fall through */ 3805 3806 case MVT::v4f64: 3807 case MVT::v4i1: 3808 // QPX vectors are treated like their scalar floating-point subregisters 3809 // (except that they're larger). 3810 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 3811 if (QFPR_idx != Num_QFPR_Regs) { 3812 const TargetRegisterClass *RC; 3813 switch (ObjectVT.getSimpleVT().SimpleTy) { 3814 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 3815 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 3816 default: RC = &PPC::QBRCRegClass; break; 3817 } 3818 3819 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 3820 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3821 ++QFPR_idx; 3822 } else { 3823 if (CallConv == CallingConv::Fast) 3824 ComputeArgOffset(); 3825 needsLoad = true; 3826 } 3827 if (CallConv != CallingConv::Fast || needsLoad) 3828 ArgOffset += Sz; 3829 break; 3830 } 3831 3832 // We need to load the argument to a virtual register if we determined 3833 // above that we ran out of physical registers of the appropriate type. 3834 if (needsLoad) { 3835 if (ObjSize < ArgSize && !isLittleEndian) 3836 CurArgOffset += ArgSize - ObjSize; 3837 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 3838 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3839 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 3840 } 3841 3842 InVals.push_back(ArgVal); 3843 } 3844 3845 // Area that is at least reserved in the caller of this function. 3846 unsigned MinReservedArea; 3847 if (HasParameterArea) 3848 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 3849 else 3850 MinReservedArea = LinkageSize; 3851 3852 // Set the size that is at least reserved in caller of this function. Tail 3853 // call optimized functions' reserved stack space needs to be aligned so that 3854 // taking the difference between two stack areas will result in an aligned 3855 // stack. 3856 MinReservedArea = 3857 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3858 FuncInfo->setMinReservedArea(MinReservedArea); 3859 3860 // If the function takes variable number of arguments, make a frame index for 3861 // the start of the first vararg value... for expansion of llvm.va_start. 3862 if (isVarArg) { 3863 int Depth = ArgOffset; 3864 3865 FuncInfo->setVarArgsFrameIndex( 3866 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 3867 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3868 3869 // If this function is vararg, store any remaining integer argument regs 3870 // to their spots on the stack so that they may be loaded by dereferencing 3871 // the result of va_next. 3872 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3873 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 3874 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3875 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3876 SDValue Store = 3877 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3878 MemOps.push_back(Store); 3879 // Increment the address by four for the next argument to store 3880 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 3881 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3882 } 3883 } 3884 3885 if (!MemOps.empty()) 3886 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3887 3888 return Chain; 3889 } 3890 3891 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 3892 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3893 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3894 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3895 // TODO: add description of PPC stack frame format, or at least some docs. 3896 // 3897 MachineFunction &MF = DAG.getMachineFunction(); 3898 MachineFrameInfo &MFI = MF.getFrameInfo(); 3899 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3900 3901 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3902 bool isPPC64 = PtrVT == MVT::i64; 3903 // Potential tail calls could cause overwriting of argument stack slots. 3904 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3905 (CallConv == CallingConv::Fast)); 3906 unsigned PtrByteSize = isPPC64 ? 8 : 4; 3907 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3908 unsigned ArgOffset = LinkageSize; 3909 // Area that is at least reserved in caller of this function. 3910 unsigned MinReservedArea = ArgOffset; 3911 3912 static const MCPhysReg GPR_32[] = { // 32-bit registers. 3913 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3914 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3915 }; 3916 static const MCPhysReg GPR_64[] = { // 64-bit registers. 3917 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3918 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3919 }; 3920 static const MCPhysReg VR[] = { 3921 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3922 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3923 }; 3924 3925 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 3926 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3927 const unsigned Num_VR_Regs = array_lengthof( VR); 3928 3929 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3930 3931 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 3932 3933 // In 32-bit non-varargs functions, the stack space for vectors is after the 3934 // stack space for non-vectors. We do not use this space unless we have 3935 // too many vectors to fit in registers, something that only occurs in 3936 // constructed examples:), but we have to walk the arglist to figure 3937 // that out...for the pathological case, compute VecArgOffset as the 3938 // start of the vector parameter area. Computing VecArgOffset is the 3939 // entire point of the following loop. 3940 unsigned VecArgOffset = ArgOffset; 3941 if (!isVarArg && !isPPC64) { 3942 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 3943 ++ArgNo) { 3944 EVT ObjectVT = Ins[ArgNo].VT; 3945 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3946 3947 if (Flags.isByVal()) { 3948 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 3949 unsigned ObjSize = Flags.getByValSize(); 3950 unsigned ArgSize = 3951 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3952 VecArgOffset += ArgSize; 3953 continue; 3954 } 3955 3956 switch(ObjectVT.getSimpleVT().SimpleTy) { 3957 default: llvm_unreachable("Unhandled argument type!"); 3958 case MVT::i1: 3959 case MVT::i32: 3960 case MVT::f32: 3961 VecArgOffset += 4; 3962 break; 3963 case MVT::i64: // PPC64 3964 case MVT::f64: 3965 // FIXME: We are guaranteed to be !isPPC64 at this point. 3966 // Does MVT::i64 apply? 3967 VecArgOffset += 8; 3968 break; 3969 case MVT::v4f32: 3970 case MVT::v4i32: 3971 case MVT::v8i16: 3972 case MVT::v16i8: 3973 // Nothing to do, we're only looking at Nonvector args here. 3974 break; 3975 } 3976 } 3977 } 3978 // We've found where the vector parameter area in memory is. Skip the 3979 // first 12 parameters; these don't use that memory. 3980 VecArgOffset = ((VecArgOffset+15)/16)*16; 3981 VecArgOffset += 12*16; 3982 3983 // Add DAG nodes to load the arguments or copy them out of registers. On 3984 // entry to a function on PPC, the arguments start after the linkage area, 3985 // although the first ones are often in registers. 3986 3987 SmallVector<SDValue, 8> MemOps; 3988 unsigned nAltivecParamsAtEnd = 0; 3989 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); 3990 unsigned CurArgIdx = 0; 3991 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3992 SDValue ArgVal; 3993 bool needsLoad = false; 3994 EVT ObjectVT = Ins[ArgNo].VT; 3995 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 3996 unsigned ArgSize = ObjSize; 3997 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3998 if (Ins[ArgNo].isOrigArg()) { 3999 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4000 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4001 } 4002 unsigned CurArgOffset = ArgOffset; 4003 4004 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4005 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4006 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4007 if (isVarArg || isPPC64) { 4008 MinReservedArea = ((MinReservedArea+15)/16)*16; 4009 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4010 Flags, 4011 PtrByteSize); 4012 } else nAltivecParamsAtEnd++; 4013 } else 4014 // Calculate min reserved area. 4015 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4016 Flags, 4017 PtrByteSize); 4018 4019 // FIXME the codegen can be much improved in some cases. 4020 // We do not have to keep everything in memory. 4021 if (Flags.isByVal()) { 4022 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4023 4024 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4025 ObjSize = Flags.getByValSize(); 4026 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4027 // Objects of size 1 and 2 are right justified, everything else is 4028 // left justified. This means the memory address is adjusted forwards. 4029 if (ObjSize==1 || ObjSize==2) { 4030 CurArgOffset = CurArgOffset + (4 - ObjSize); 4031 } 4032 // The value of the object is its address. 4033 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4034 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4035 InVals.push_back(FIN); 4036 if (ObjSize==1 || ObjSize==2) { 4037 if (GPR_idx != Num_GPR_Regs) { 4038 unsigned VReg; 4039 if (isPPC64) 4040 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4041 else 4042 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4043 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4044 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4045 SDValue Store = 4046 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4047 MachinePointerInfo(&*FuncArg), ObjType); 4048 MemOps.push_back(Store); 4049 ++GPR_idx; 4050 } 4051 4052 ArgOffset += PtrByteSize; 4053 4054 continue; 4055 } 4056 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4057 // Store whatever pieces of the object are in registers 4058 // to memory. ArgOffset will be the address of the beginning 4059 // of the object. 4060 if (GPR_idx != Num_GPR_Regs) { 4061 unsigned VReg; 4062 if (isPPC64) 4063 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4064 else 4065 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4066 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4067 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4068 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4069 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4070 MachinePointerInfo(&*FuncArg, j)); 4071 MemOps.push_back(Store); 4072 ++GPR_idx; 4073 ArgOffset += PtrByteSize; 4074 } else { 4075 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4076 break; 4077 } 4078 } 4079 continue; 4080 } 4081 4082 switch (ObjectVT.getSimpleVT().SimpleTy) { 4083 default: llvm_unreachable("Unhandled argument type!"); 4084 case MVT::i1: 4085 case MVT::i32: 4086 if (!isPPC64) { 4087 if (GPR_idx != Num_GPR_Regs) { 4088 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4089 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4090 4091 if (ObjectVT == MVT::i1) 4092 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4093 4094 ++GPR_idx; 4095 } else { 4096 needsLoad = true; 4097 ArgSize = PtrByteSize; 4098 } 4099 // All int arguments reserve stack space in the Darwin ABI. 4100 ArgOffset += PtrByteSize; 4101 break; 4102 } 4103 LLVM_FALLTHROUGH; 4104 case MVT::i64: // PPC64 4105 if (GPR_idx != Num_GPR_Regs) { 4106 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4107 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4108 4109 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4110 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4111 // value to MVT::i64 and then truncate to the correct register size. 4112 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4113 4114 ++GPR_idx; 4115 } else { 4116 needsLoad = true; 4117 ArgSize = PtrByteSize; 4118 } 4119 // All int arguments reserve stack space in the Darwin ABI. 4120 ArgOffset += 8; 4121 break; 4122 4123 case MVT::f32: 4124 case MVT::f64: 4125 // Every 4 bytes of argument space consumes one of the GPRs available for 4126 // argument passing. 4127 if (GPR_idx != Num_GPR_Regs) { 4128 ++GPR_idx; 4129 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4130 ++GPR_idx; 4131 } 4132 if (FPR_idx != Num_FPR_Regs) { 4133 unsigned VReg; 4134 4135 if (ObjectVT == MVT::f32) 4136 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4137 else 4138 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4139 4140 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4141 ++FPR_idx; 4142 } else { 4143 needsLoad = true; 4144 } 4145 4146 // All FP arguments reserve stack space in the Darwin ABI. 4147 ArgOffset += isPPC64 ? 8 : ObjSize; 4148 break; 4149 case MVT::v4f32: 4150 case MVT::v4i32: 4151 case MVT::v8i16: 4152 case MVT::v16i8: 4153 // Note that vector arguments in registers don't reserve stack space, 4154 // except in varargs functions. 4155 if (VR_idx != Num_VR_Regs) { 4156 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4157 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4158 if (isVarArg) { 4159 while ((ArgOffset % 16) != 0) { 4160 ArgOffset += PtrByteSize; 4161 if (GPR_idx != Num_GPR_Regs) 4162 GPR_idx++; 4163 } 4164 ArgOffset += 16; 4165 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4166 } 4167 ++VR_idx; 4168 } else { 4169 if (!isVarArg && !isPPC64) { 4170 // Vectors go after all the nonvectors. 4171 CurArgOffset = VecArgOffset; 4172 VecArgOffset += 16; 4173 } else { 4174 // Vectors are aligned. 4175 ArgOffset = ((ArgOffset+15)/16)*16; 4176 CurArgOffset = ArgOffset; 4177 ArgOffset += 16; 4178 } 4179 needsLoad = true; 4180 } 4181 break; 4182 } 4183 4184 // We need to load the argument to a virtual register if we determined above 4185 // that we ran out of physical registers of the appropriate type. 4186 if (needsLoad) { 4187 int FI = MFI.CreateFixedObject(ObjSize, 4188 CurArgOffset + (ArgSize - ObjSize), 4189 isImmutable); 4190 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4191 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4192 } 4193 4194 InVals.push_back(ArgVal); 4195 } 4196 4197 // Allow for Altivec parameters at the end, if needed. 4198 if (nAltivecParamsAtEnd) { 4199 MinReservedArea = ((MinReservedArea+15)/16)*16; 4200 MinReservedArea += 16*nAltivecParamsAtEnd; 4201 } 4202 4203 // Area that is at least reserved in the caller of this function. 4204 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4205 4206 // Set the size that is at least reserved in caller of this function. Tail 4207 // call optimized functions' reserved stack space needs to be aligned so that 4208 // taking the difference between two stack areas will result in an aligned 4209 // stack. 4210 MinReservedArea = 4211 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4212 FuncInfo->setMinReservedArea(MinReservedArea); 4213 4214 // If the function takes variable number of arguments, make a frame index for 4215 // the start of the first vararg value... for expansion of llvm.va_start. 4216 if (isVarArg) { 4217 int Depth = ArgOffset; 4218 4219 FuncInfo->setVarArgsFrameIndex( 4220 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4221 Depth, true)); 4222 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4223 4224 // If this function is vararg, store any remaining integer argument regs 4225 // to their spots on the stack so that they may be loaded by dereferencing 4226 // the result of va_next. 4227 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4228 unsigned VReg; 4229 4230 if (isPPC64) 4231 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4232 else 4233 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4234 4235 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4236 SDValue Store = 4237 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4238 MemOps.push_back(Store); 4239 // Increment the address by four for the next argument to store 4240 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4241 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4242 } 4243 } 4244 4245 if (!MemOps.empty()) 4246 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4247 4248 return Chain; 4249 } 4250 4251 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4252 /// adjusted to accommodate the arguments for the tailcall. 4253 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4254 unsigned ParamSize) { 4255 4256 if (!isTailCall) return 0; 4257 4258 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4259 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4260 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4261 // Remember only if the new adjustement is bigger. 4262 if (SPDiff < FI->getTailCallSPDelta()) 4263 FI->setTailCallSPDelta(SPDiff); 4264 4265 return SPDiff; 4266 } 4267 4268 static bool isFunctionGlobalAddress(SDValue Callee); 4269 4270 static bool 4271 callsShareTOCBase(const Function *Caller, SDValue Callee, 4272 const TargetMachine &TM) { 4273 // If !G, Callee can be an external symbol. 4274 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4275 if (!G) 4276 return false; 4277 4278 // The medium and large code models are expected to provide a sufficiently 4279 // large TOC to provide all data addressing needs of a module with a 4280 // single TOC. Since each module will be addressed with a single TOC then we 4281 // only need to check that caller and callee don't cross dso boundaries. 4282 if (CodeModel::Medium == TM.getCodeModel() || 4283 CodeModel::Large == TM.getCodeModel()) 4284 return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal()); 4285 4286 // Otherwise we need to ensure callee and caller are in the same section, 4287 // since the linker may allocate multiple TOCs, and we don't know which 4288 // sections will belong to the same TOC base. 4289 4290 const GlobalValue *GV = G->getGlobal(); 4291 if (!GV->isStrongDefinitionForLinker()) 4292 return false; 4293 4294 // Any explicitly-specified sections and section prefixes must also match. 4295 // Also, if we're using -ffunction-sections, then each function is always in 4296 // a different section (the same is true for COMDAT functions). 4297 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4298 GV->getSection() != Caller->getSection()) 4299 return false; 4300 if (const auto *F = dyn_cast<Function>(GV)) { 4301 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4302 return false; 4303 } 4304 4305 // If the callee might be interposed, then we can't assume the ultimate call 4306 // target will be in the same section. Even in cases where we can assume that 4307 // interposition won't happen, in any case where the linker might insert a 4308 // stub to allow for interposition, we must generate code as though 4309 // interposition might occur. To understand why this matters, consider a 4310 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4311 // in the same section, but a is in a different module (i.e. has a different 4312 // TOC base pointer). If the linker allows for interposition between b and c, 4313 // then it will generate a stub for the call edge between b and c which will 4314 // save the TOC pointer into the designated stack slot allocated by b. If we 4315 // return true here, and therefore allow a tail call between b and c, that 4316 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4317 // pointer into the stack slot allocated by a (where the a -> b stub saved 4318 // a's TOC base pointer). If we're not considering a tail call, but rather, 4319 // whether a nop is needed after the call instruction in b, because the linker 4320 // will insert a stub, it might complain about a missing nop if we omit it 4321 // (although many don't complain in this case). 4322 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4323 return false; 4324 4325 return true; 4326 } 4327 4328 static bool 4329 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4330 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4331 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4332 4333 const unsigned PtrByteSize = 8; 4334 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4335 4336 static const MCPhysReg GPR[] = { 4337 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4338 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4339 }; 4340 static const MCPhysReg VR[] = { 4341 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4342 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4343 }; 4344 4345 const unsigned NumGPRs = array_lengthof(GPR); 4346 const unsigned NumFPRs = 13; 4347 const unsigned NumVRs = array_lengthof(VR); 4348 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4349 4350 unsigned NumBytes = LinkageSize; 4351 unsigned AvailableFPRs = NumFPRs; 4352 unsigned AvailableVRs = NumVRs; 4353 4354 for (const ISD::OutputArg& Param : Outs) { 4355 if (Param.Flags.isNest()) continue; 4356 4357 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4358 PtrByteSize, LinkageSize, ParamAreaSize, 4359 NumBytes, AvailableFPRs, AvailableVRs, 4360 Subtarget.hasQPX())) 4361 return true; 4362 } 4363 return false; 4364 } 4365 4366 static bool 4367 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4368 if (CS.arg_size() != CallerFn->arg_size()) 4369 return false; 4370 4371 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4372 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4373 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4374 4375 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4376 const Value* CalleeArg = *CalleeArgIter; 4377 const Value* CallerArg = &(*CallerArgIter); 4378 if (CalleeArg == CallerArg) 4379 continue; 4380 4381 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4382 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4383 // } 4384 // 1st argument of callee is undef and has the same type as caller. 4385 if (CalleeArg->getType() == CallerArg->getType() && 4386 isa<UndefValue>(CalleeArg)) 4387 continue; 4388 4389 return false; 4390 } 4391 4392 return true; 4393 } 4394 4395 bool 4396 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4397 SDValue Callee, 4398 CallingConv::ID CalleeCC, 4399 ImmutableCallSite CS, 4400 bool isVarArg, 4401 const SmallVectorImpl<ISD::OutputArg> &Outs, 4402 const SmallVectorImpl<ISD::InputArg> &Ins, 4403 SelectionDAG& DAG) const { 4404 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4405 4406 if (DisableSCO && !TailCallOpt) return false; 4407 4408 // Variadic argument functions are not supported. 4409 if (isVarArg) return false; 4410 4411 MachineFunction &MF = DAG.getMachineFunction(); 4412 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4413 4414 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has 4415 // the same calling convention 4416 if (CallerCC != CalleeCC) return false; 4417 4418 // SCO support C calling convention 4419 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C) 4420 return false; 4421 4422 // Caller contains any byval parameter is not supported. 4423 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4424 return false; 4425 4426 // Callee contains any byval parameter is not supported, too. 4427 // Note: This is a quick work around, because in some cases, e.g. 4428 // caller's stack size > callee's stack size, we are still able to apply 4429 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574 4430 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4431 return false; 4432 4433 // No TCO/SCO on indirect call because Caller have to restore its TOC 4434 if (!isFunctionGlobalAddress(Callee) && 4435 !isa<ExternalSymbolSDNode>(Callee)) 4436 return false; 4437 4438 // If the caller and callee potentially have different TOC bases then we 4439 // cannot tail call since we need to restore the TOC pointer after the call. 4440 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4441 if (!callsShareTOCBase(MF.getFunction(), Callee, getTargetMachine())) 4442 return false; 4443 4444 // TCO allows altering callee ABI, so we don't have to check further. 4445 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4446 return true; 4447 4448 if (DisableSCO) return false; 4449 4450 // If callee use the same argument list that caller is using, then we can 4451 // apply SCO on this case. If it is not, then we need to check if callee needs 4452 // stack for passing arguments. 4453 if (!hasSameArgumentList(MF.getFunction(), CS) && 4454 needStackSlotPassParameters(Subtarget, Outs)) { 4455 return false; 4456 } 4457 4458 return true; 4459 } 4460 4461 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4462 /// for tail call optimization. Targets which want to do tail call 4463 /// optimization should implement this function. 4464 bool 4465 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4466 CallingConv::ID CalleeCC, 4467 bool isVarArg, 4468 const SmallVectorImpl<ISD::InputArg> &Ins, 4469 SelectionDAG& DAG) const { 4470 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4471 return false; 4472 4473 // Variable argument functions are not supported. 4474 if (isVarArg) 4475 return false; 4476 4477 MachineFunction &MF = DAG.getMachineFunction(); 4478 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); 4479 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4480 // Functions containing by val parameters are not supported. 4481 for (unsigned i = 0; i != Ins.size(); i++) { 4482 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4483 if (Flags.isByVal()) return false; 4484 } 4485 4486 // Non-PIC/GOT tail calls are supported. 4487 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4488 return true; 4489 4490 // At the moment we can only do local tail calls (in same module, hidden 4491 // or protected) if we are generating PIC. 4492 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4493 return G->getGlobal()->hasHiddenVisibility() 4494 || G->getGlobal()->hasProtectedVisibility(); 4495 } 4496 4497 return false; 4498 } 4499 4500 /// isCallCompatibleAddress - Return the immediate to use if the specified 4501 /// 32-bit value is representable in the immediate field of a BxA instruction. 4502 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4504 if (!C) return nullptr; 4505 4506 int Addr = C->getZExtValue(); 4507 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4508 SignExtend32<26>(Addr) != Addr) 4509 return nullptr; // Top 6 bits have to be sext of immediate. 4510 4511 return DAG 4512 .getConstant( 4513 (int)C->getZExtValue() >> 2, SDLoc(Op), 4514 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4515 .getNode(); 4516 } 4517 4518 namespace { 4519 4520 struct TailCallArgumentInfo { 4521 SDValue Arg; 4522 SDValue FrameIdxOp; 4523 int FrameIdx = 0; 4524 4525 TailCallArgumentInfo() = default; 4526 }; 4527 4528 } // end anonymous namespace 4529 4530 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4531 static void StoreTailCallArgumentsToStackSlot( 4532 SelectionDAG &DAG, SDValue Chain, 4533 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4534 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4535 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4536 SDValue Arg = TailCallArgs[i].Arg; 4537 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4538 int FI = TailCallArgs[i].FrameIdx; 4539 // Store relative to framepointer. 4540 MemOpChains.push_back(DAG.getStore( 4541 Chain, dl, Arg, FIN, 4542 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4543 } 4544 } 4545 4546 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4547 /// the appropriate stack slot for the tail call optimized function call. 4548 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4549 SDValue OldRetAddr, SDValue OldFP, 4550 int SPDiff, const SDLoc &dl) { 4551 if (SPDiff) { 4552 // Calculate the new stack slot for the return address. 4553 MachineFunction &MF = DAG.getMachineFunction(); 4554 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4555 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4556 bool isPPC64 = Subtarget.isPPC64(); 4557 int SlotSize = isPPC64 ? 8 : 4; 4558 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4559 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4560 NewRetAddrLoc, true); 4561 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4562 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4563 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4564 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4565 4566 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4567 // slot as the FP is never overwritten. 4568 if (Subtarget.isDarwinABI()) { 4569 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4570 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4571 true); 4572 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4573 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4574 MachinePointerInfo::getFixedStack( 4575 DAG.getMachineFunction(), NewFPIdx)); 4576 } 4577 } 4578 return Chain; 4579 } 4580 4581 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4582 /// the position of the argument. 4583 static void 4584 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4585 SDValue Arg, int SPDiff, unsigned ArgOffset, 4586 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4587 int Offset = ArgOffset + SPDiff; 4588 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4589 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4590 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4591 SDValue FIN = DAG.getFrameIndex(FI, VT); 4592 TailCallArgumentInfo Info; 4593 Info.Arg = Arg; 4594 Info.FrameIdxOp = FIN; 4595 Info.FrameIdx = FI; 4596 TailCallArguments.push_back(Info); 4597 } 4598 4599 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4600 /// stack slot. Returns the chain as result and the loaded frame pointers in 4601 /// LROpOut/FPOpout. Used when tail calling. 4602 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4603 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4604 SDValue &FPOpOut, const SDLoc &dl) const { 4605 if (SPDiff) { 4606 // Load the LR and FP stack slot for later adjusting. 4607 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4608 LROpOut = getReturnAddrFrameIndex(DAG); 4609 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4610 Chain = SDValue(LROpOut.getNode(), 1); 4611 4612 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4613 // slot as the FP is never overwritten. 4614 if (Subtarget.isDarwinABI()) { 4615 FPOpOut = getFramePointerFrameIndex(DAG); 4616 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4617 Chain = SDValue(FPOpOut.getNode(), 1); 4618 } 4619 } 4620 return Chain; 4621 } 4622 4623 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4624 /// by "Src" to address "Dst" of size "Size". Alignment information is 4625 /// specified by the specific parameter attribute. The copy will be passed as 4626 /// a byval function parameter. 4627 /// Sometimes what we are copying is the end of a larger object, the part that 4628 /// does not fit in registers. 4629 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4630 SDValue Chain, ISD::ArgFlagsTy Flags, 4631 SelectionDAG &DAG, const SDLoc &dl) { 4632 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4633 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4634 false, false, false, MachinePointerInfo(), 4635 MachinePointerInfo()); 4636 } 4637 4638 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4639 /// tail calls. 4640 static void LowerMemOpCallTo( 4641 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4642 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4643 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4644 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4645 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4646 if (!isTailCall) { 4647 if (isVector) { 4648 SDValue StackPtr; 4649 if (isPPC64) 4650 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4651 else 4652 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4653 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4654 DAG.getConstant(ArgOffset, dl, PtrVT)); 4655 } 4656 MemOpChains.push_back( 4657 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4658 // Calculate and remember argument location. 4659 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4660 TailCallArguments); 4661 } 4662 4663 static void 4664 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4665 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4666 SDValue FPOp, 4667 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4668 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4669 // might overwrite each other in case of tail call optimization. 4670 SmallVector<SDValue, 8> MemOpChains2; 4671 // Do not flag preceding copytoreg stuff together with the following stuff. 4672 InFlag = SDValue(); 4673 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4674 MemOpChains2, dl); 4675 if (!MemOpChains2.empty()) 4676 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4677 4678 // Store the return address to the appropriate stack slot. 4679 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4680 4681 // Emit callseq_end just before tailcall node. 4682 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4683 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4684 InFlag = Chain.getValue(1); 4685 } 4686 4687 // Is this global address that of a function that can be called by name? (as 4688 // opposed to something that must hold a descriptor for an indirect call). 4689 static bool isFunctionGlobalAddress(SDValue Callee) { 4690 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4691 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4692 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4693 return false; 4694 4695 return G->getGlobal()->getValueType()->isFunctionTy(); 4696 } 4697 4698 return false; 4699 } 4700 4701 static unsigned 4702 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4703 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4704 bool isPatchPoint, bool hasNest, 4705 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4706 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4707 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4708 bool isPPC64 = Subtarget.isPPC64(); 4709 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4710 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4711 4712 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4713 NodeTys.push_back(MVT::Other); // Returns a chain 4714 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4715 4716 unsigned CallOpc = PPCISD::CALL; 4717 4718 bool needIndirectCall = true; 4719 if (!isSVR4ABI || !isPPC64) 4720 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4721 // If this is an absolute destination address, use the munged value. 4722 Callee = SDValue(Dest, 0); 4723 needIndirectCall = false; 4724 } 4725 4726 // PC-relative references to external symbols should go through $stub, unless 4727 // we're building with the leopard linker or later, which automatically 4728 // synthesizes these stubs. 4729 const TargetMachine &TM = DAG.getTarget(); 4730 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent(); 4731 const GlobalValue *GV = nullptr; 4732 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4733 GV = G->getGlobal(); 4734 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4735 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4736 4737 if (isFunctionGlobalAddress(Callee)) { 4738 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4739 // A call to a TLS address is actually an indirect call to a 4740 // thread-specific pointer. 4741 unsigned OpFlags = 0; 4742 if (UsePlt) 4743 OpFlags = PPCII::MO_PLT; 4744 4745 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4746 // every direct call is) turn it into a TargetGlobalAddress / 4747 // TargetExternalSymbol node so that legalize doesn't hack it. 4748 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4749 Callee.getValueType(), 0, OpFlags); 4750 needIndirectCall = false; 4751 } 4752 4753 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4754 unsigned char OpFlags = 0; 4755 4756 if (UsePlt) 4757 OpFlags = PPCII::MO_PLT; 4758 4759 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4760 OpFlags); 4761 needIndirectCall = false; 4762 } 4763 4764 if (isPatchPoint) { 4765 // We'll form an invalid direct call when lowering a patchpoint; the full 4766 // sequence for an indirect call is complicated, and many of the 4767 // instructions introduced might have side effects (and, thus, can't be 4768 // removed later). The call itself will be removed as soon as the 4769 // argument/return lowering is complete, so the fact that it has the wrong 4770 // kind of operands should not really matter. 4771 needIndirectCall = false; 4772 } 4773 4774 if (needIndirectCall) { 4775 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 4776 // to do the call, we can't use PPCISD::CALL. 4777 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 4778 4779 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 4780 // Function pointers in the 64-bit SVR4 ABI do not point to the function 4781 // entry point, but to the function descriptor (the function entry point 4782 // address is part of the function descriptor though). 4783 // The function descriptor is a three doubleword structure with the 4784 // following fields: function entry point, TOC base address and 4785 // environment pointer. 4786 // Thus for a call through a function pointer, the following actions need 4787 // to be performed: 4788 // 1. Save the TOC of the caller in the TOC save area of its stack 4789 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 4790 // 2. Load the address of the function entry point from the function 4791 // descriptor. 4792 // 3. Load the TOC of the callee from the function descriptor into r2. 4793 // 4. Load the environment pointer from the function descriptor into 4794 // r11. 4795 // 5. Branch to the function entry point address. 4796 // 6. On return of the callee, the TOC of the caller needs to be 4797 // restored (this is done in FinishCall()). 4798 // 4799 // The loads are scheduled at the beginning of the call sequence, and the 4800 // register copies are flagged together to ensure that no other 4801 // operations can be scheduled in between. E.g. without flagging the 4802 // copies together, a TOC access in the caller could be scheduled between 4803 // the assignment of the callee TOC and the branch to the callee, which 4804 // results in the TOC access going through the TOC of the callee instead 4805 // of going through the TOC of the caller, which leads to incorrect code. 4806 4807 // Load the address of the function entry point from the function 4808 // descriptor. 4809 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 4810 if (LDChain.getValueType() == MVT::Glue) 4811 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 4812 4813 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 4814 ? (MachineMemOperand::MODereferenceable | 4815 MachineMemOperand::MOInvariant) 4816 : MachineMemOperand::MONone; 4817 4818 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 4819 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 4820 /* Alignment = */ 8, MMOFlags); 4821 4822 // Load environment pointer into r11. 4823 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 4824 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 4825 SDValue LoadEnvPtr = 4826 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 4827 /* Alignment = */ 8, MMOFlags); 4828 4829 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 4830 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 4831 SDValue TOCPtr = 4832 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 4833 /* Alignment = */ 8, MMOFlags); 4834 4835 setUsesTOCBasePtr(DAG); 4836 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 4837 InFlag); 4838 Chain = TOCVal.getValue(0); 4839 InFlag = TOCVal.getValue(1); 4840 4841 // If the function call has an explicit 'nest' parameter, it takes the 4842 // place of the environment pointer. 4843 if (!hasNest) { 4844 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 4845 InFlag); 4846 4847 Chain = EnvVal.getValue(0); 4848 InFlag = EnvVal.getValue(1); 4849 } 4850 4851 MTCTROps[0] = Chain; 4852 MTCTROps[1] = LoadFuncPtr; 4853 MTCTROps[2] = InFlag; 4854 } 4855 4856 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 4857 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 4858 InFlag = Chain.getValue(1); 4859 4860 NodeTys.clear(); 4861 NodeTys.push_back(MVT::Other); 4862 NodeTys.push_back(MVT::Glue); 4863 Ops.push_back(Chain); 4864 CallOpc = PPCISD::BCTRL; 4865 Callee.setNode(nullptr); 4866 // Add use of X11 (holding environment pointer) 4867 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 4868 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 4869 // Add CTR register as callee so a bctr can be emitted later. 4870 if (isTailCall) 4871 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 4872 } 4873 4874 // If this is a direct call, pass the chain and the callee. 4875 if (Callee.getNode()) { 4876 Ops.push_back(Chain); 4877 Ops.push_back(Callee); 4878 } 4879 // If this is a tail call add stack pointer delta. 4880 if (isTailCall) 4881 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 4882 4883 // Add argument registers to the end of the list so that they are known live 4884 // into the call. 4885 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 4886 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 4887 RegsToPass[i].second.getValueType())); 4888 4889 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live 4890 // into the call. 4891 if (isSVR4ABI && isPPC64 && !isPatchPoint) { 4892 setUsesTOCBasePtr(DAG); 4893 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); 4894 } 4895 4896 return CallOpc; 4897 } 4898 4899 SDValue PPCTargetLowering::LowerCallResult( 4900 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4901 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4902 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4903 SmallVector<CCValAssign, 16> RVLocs; 4904 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4905 *DAG.getContext()); 4906 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); 4907 4908 // Copy all of the result registers out of their specified physreg. 4909 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4910 CCValAssign &VA = RVLocs[i]; 4911 assert(VA.isRegLoc() && "Can only return in registers!"); 4912 4913 SDValue Val = DAG.getCopyFromReg(Chain, dl, 4914 VA.getLocReg(), VA.getLocVT(), InFlag); 4915 Chain = Val.getValue(1); 4916 InFlag = Val.getValue(2); 4917 4918 switch (VA.getLocInfo()) { 4919 default: llvm_unreachable("Unknown loc info!"); 4920 case CCValAssign::Full: break; 4921 case CCValAssign::AExt: 4922 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4923 break; 4924 case CCValAssign::ZExt: 4925 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4926 DAG.getValueType(VA.getValVT())); 4927 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4928 break; 4929 case CCValAssign::SExt: 4930 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 4931 DAG.getValueType(VA.getValVT())); 4932 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4933 break; 4934 } 4935 4936 InVals.push_back(Val); 4937 } 4938 4939 return Chain; 4940 } 4941 4942 SDValue PPCTargetLowering::FinishCall( 4943 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 4944 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 4945 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 4946 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 4947 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 4948 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 4949 std::vector<EVT> NodeTys; 4950 SmallVector<SDValue, 8> Ops; 4951 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 4952 SPDiff, isTailCall, isPatchPoint, hasNest, 4953 RegsToPass, Ops, NodeTys, CS, Subtarget); 4954 4955 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 4956 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 4957 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 4958 4959 // When performing tail call optimization the callee pops its arguments off 4960 // the stack. Account for this here so these bytes can be pushed back on in 4961 // PPCFrameLowering::eliminateCallFramePseudoInstr. 4962 int BytesCalleePops = 4963 (CallConv == CallingConv::Fast && 4964 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 4965 4966 // Add a register mask operand representing the call-preserved registers. 4967 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 4968 const uint32_t *Mask = 4969 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 4970 assert(Mask && "Missing call preserved mask for calling convention"); 4971 Ops.push_back(DAG.getRegisterMask(Mask)); 4972 4973 if (InFlag.getNode()) 4974 Ops.push_back(InFlag); 4975 4976 // Emit tail call. 4977 if (isTailCall) { 4978 assert(((Callee.getOpcode() == ISD::Register && 4979 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 4980 Callee.getOpcode() == ISD::TargetExternalSymbol || 4981 Callee.getOpcode() == ISD::TargetGlobalAddress || 4982 isa<ConstantSDNode>(Callee)) && 4983 "Expecting an global address, external symbol, absolute value or register"); 4984 4985 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 4986 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 4987 } 4988 4989 // Add a NOP immediately after the branch instruction when using the 64-bit 4990 // SVR4 ABI. At link time, if caller and callee are in a different module and 4991 // thus have a different TOC, the call will be replaced with a call to a stub 4992 // function which saves the current TOC, loads the TOC of the callee and 4993 // branches to the callee. The NOP will be replaced with a load instruction 4994 // which restores the TOC of the caller from the TOC save slot of the current 4995 // stack frame. If caller and callee belong to the same module (and have the 4996 // same TOC), the NOP will remain unchanged. 4997 4998 MachineFunction &MF = DAG.getMachineFunction(); 4999 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && 5000 !isPatchPoint) { 5001 if (CallOpc == PPCISD::BCTRL) { 5002 // This is a call through a function pointer. 5003 // Restore the caller TOC from the save area into R2. 5004 // See PrepareCall() for more information about calls through function 5005 // pointers in the 64-bit SVR4 ABI. 5006 // We are using a target-specific load with r2 hard coded, because the 5007 // result of a target-independent load would never go directly into r2, 5008 // since r2 is a reserved register (which prevents the register allocator 5009 // from allocating it), resulting in an additional register being 5010 // allocated and an unnecessary move instruction being generated. 5011 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5012 5013 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5014 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5015 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5016 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5017 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5018 5019 // The address needs to go after the chain input but before the flag (or 5020 // any other variadic arguments). 5021 Ops.insert(std::next(Ops.begin()), AddTOC); 5022 } else if (CallOpc == PPCISD::CALL && 5023 !callsShareTOCBase(MF.getFunction(), Callee, DAG.getTarget())) { 5024 // Otherwise insert NOP for non-local calls. 5025 CallOpc = PPCISD::CALL_NOP; 5026 } 5027 } 5028 5029 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5030 InFlag = Chain.getValue(1); 5031 5032 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5033 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5034 InFlag, dl); 5035 if (!Ins.empty()) 5036 InFlag = Chain.getValue(1); 5037 5038 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5039 Ins, dl, DAG, InVals); 5040 } 5041 5042 SDValue 5043 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5044 SmallVectorImpl<SDValue> &InVals) const { 5045 SelectionDAG &DAG = CLI.DAG; 5046 SDLoc &dl = CLI.DL; 5047 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5048 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5049 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5050 SDValue Chain = CLI.Chain; 5051 SDValue Callee = CLI.Callee; 5052 bool &isTailCall = CLI.IsTailCall; 5053 CallingConv::ID CallConv = CLI.CallConv; 5054 bool isVarArg = CLI.IsVarArg; 5055 bool isPatchPoint = CLI.IsPatchPoint; 5056 ImmutableCallSite CS = CLI.CS; 5057 5058 if (isTailCall) { 5059 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5060 isTailCall = false; 5061 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5062 isTailCall = 5063 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5064 isVarArg, Outs, Ins, DAG); 5065 else 5066 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5067 Ins, DAG); 5068 if (isTailCall) { 5069 ++NumTailCalls; 5070 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5071 ++NumSiblingCalls; 5072 5073 assert(isa<GlobalAddressSDNode>(Callee) && 5074 "Callee should be an llvm::Function object."); 5075 DEBUG( 5076 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5077 const unsigned Width = 80 - strlen("TCO caller: ") 5078 - strlen(", callee linkage: 0, 0"); 5079 dbgs() << "TCO caller: " 5080 << left_justify(DAG.getMachineFunction().getName(), Width) 5081 << ", callee linkage: " 5082 << GV->getVisibility() << ", " << GV->getLinkage() << "\n" 5083 ); 5084 } 5085 } 5086 5087 if (!isTailCall && CS && CS.isMustTailCall()) 5088 report_fatal_error("failed to perform tail call elimination on a call " 5089 "site marked musttail"); 5090 5091 // When long calls (i.e. indirect calls) are always used, calls are always 5092 // made via function pointer. If we have a function name, first translate it 5093 // into a pointer. 5094 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5095 !isTailCall) 5096 Callee = LowerGlobalAddress(Callee, DAG); 5097 5098 if (Subtarget.isSVR4ABI()) { 5099 if (Subtarget.isPPC64()) 5100 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5101 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5102 dl, DAG, InVals, CS); 5103 else 5104 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5105 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5106 dl, DAG, InVals, CS); 5107 } 5108 5109 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5110 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5111 dl, DAG, InVals, CS); 5112 } 5113 5114 SDValue PPCTargetLowering::LowerCall_32SVR4( 5115 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5116 bool isTailCall, bool isPatchPoint, 5117 const SmallVectorImpl<ISD::OutputArg> &Outs, 5118 const SmallVectorImpl<SDValue> &OutVals, 5119 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5120 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5121 ImmutableCallSite CS) const { 5122 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5123 // of the 32-bit SVR4 ABI stack frame layout. 5124 5125 assert((CallConv == CallingConv::C || 5126 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5127 5128 unsigned PtrByteSize = 4; 5129 5130 MachineFunction &MF = DAG.getMachineFunction(); 5131 5132 // Mark this function as potentially containing a function that contains a 5133 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5134 // and restoring the callers stack pointer in this functions epilog. This is 5135 // done because by tail calling the called function might overwrite the value 5136 // in this function's (MF) stack pointer stack slot 0(SP). 5137 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5138 CallConv == CallingConv::Fast) 5139 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5140 5141 // Count how many bytes are to be pushed on the stack, including the linkage 5142 // area, parameter list area and the part of the local variable space which 5143 // contains copies of aggregates which are passed by value. 5144 5145 // Assign locations to all of the outgoing arguments. 5146 SmallVector<CCValAssign, 16> ArgLocs; 5147 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5148 5149 // Reserve space for the linkage area on the stack. 5150 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5151 PtrByteSize); 5152 if (useSoftFloat()) 5153 CCInfo.PreAnalyzeCallOperands(Outs); 5154 5155 if (isVarArg) { 5156 // Handle fixed and variable vector arguments differently. 5157 // Fixed vector arguments go into registers as long as registers are 5158 // available. Variable vector arguments always go into memory. 5159 unsigned NumArgs = Outs.size(); 5160 5161 for (unsigned i = 0; i != NumArgs; ++i) { 5162 MVT ArgVT = Outs[i].VT; 5163 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5164 bool Result; 5165 5166 if (Outs[i].IsFixed) { 5167 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5168 CCInfo); 5169 } else { 5170 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5171 ArgFlags, CCInfo); 5172 } 5173 5174 if (Result) { 5175 #ifndef NDEBUG 5176 errs() << "Call operand #" << i << " has unhandled type " 5177 << EVT(ArgVT).getEVTString() << "\n"; 5178 #endif 5179 llvm_unreachable(nullptr); 5180 } 5181 } 5182 } else { 5183 // All arguments are treated the same. 5184 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5185 } 5186 CCInfo.clearWasPPCF128(); 5187 5188 // Assign locations to all of the outgoing aggregate by value arguments. 5189 SmallVector<CCValAssign, 16> ByValArgLocs; 5190 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5191 5192 // Reserve stack space for the allocations in CCInfo. 5193 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5194 5195 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5196 5197 // Size of the linkage area, parameter list area and the part of the local 5198 // space variable where copies of aggregates which are passed by value are 5199 // stored. 5200 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5201 5202 // Calculate by how many bytes the stack has to be adjusted in case of tail 5203 // call optimization. 5204 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5205 5206 // Adjust the stack pointer for the new arguments... 5207 // These operations are automatically eliminated by the prolog/epilog pass 5208 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5209 SDValue CallSeqStart = Chain; 5210 5211 // Load the return address and frame pointer so it can be moved somewhere else 5212 // later. 5213 SDValue LROp, FPOp; 5214 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5215 5216 // Set up a copy of the stack pointer for use loading and storing any 5217 // arguments that may not fit in the registers available for argument 5218 // passing. 5219 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5220 5221 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5222 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5223 SmallVector<SDValue, 8> MemOpChains; 5224 5225 bool seenFloatArg = false; 5226 // Walk the register/memloc assignments, inserting copies/loads. 5227 for (unsigned i = 0, j = 0, e = ArgLocs.size(); 5228 i != e; 5229 ++i) { 5230 CCValAssign &VA = ArgLocs[i]; 5231 SDValue Arg = OutVals[i]; 5232 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5233 5234 if (Flags.isByVal()) { 5235 // Argument is an aggregate which is passed by value, thus we need to 5236 // create a copy of it in the local variable space of the current stack 5237 // frame (which is the stack frame of the caller) and pass the address of 5238 // this copy to the callee. 5239 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5240 CCValAssign &ByValVA = ByValArgLocs[j++]; 5241 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5242 5243 // Memory reserved in the local variable space of the callers stack frame. 5244 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5245 5246 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5247 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5248 StackPtr, PtrOff); 5249 5250 // Create a copy of the argument in the local area of the current 5251 // stack frame. 5252 SDValue MemcpyCall = 5253 CreateCopyOfByValArgument(Arg, PtrOff, 5254 CallSeqStart.getNode()->getOperand(0), 5255 Flags, DAG, dl); 5256 5257 // This must go outside the CALLSEQ_START..END. 5258 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5259 SDLoc(MemcpyCall)); 5260 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5261 NewCallSeqStart.getNode()); 5262 Chain = CallSeqStart = NewCallSeqStart; 5263 5264 // Pass the address of the aggregate copy on the stack either in a 5265 // physical register or in the parameter list area of the current stack 5266 // frame to the callee. 5267 Arg = PtrOff; 5268 } 5269 5270 if (VA.isRegLoc()) { 5271 if (Arg.getValueType() == MVT::i1) 5272 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); 5273 5274 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5275 // Put argument in a physical register. 5276 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5277 } else { 5278 // Put argument in the parameter list area of the current stack frame. 5279 assert(VA.isMemLoc()); 5280 unsigned LocMemOffset = VA.getLocMemOffset(); 5281 5282 if (!isTailCall) { 5283 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5284 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5285 StackPtr, PtrOff); 5286 5287 MemOpChains.push_back( 5288 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5289 } else { 5290 // Calculate and remember argument location. 5291 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5292 TailCallArguments); 5293 } 5294 } 5295 } 5296 5297 if (!MemOpChains.empty()) 5298 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5299 5300 // Build a sequence of copy-to-reg nodes chained together with token chain 5301 // and flag operands which copy the outgoing args into the appropriate regs. 5302 SDValue InFlag; 5303 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5304 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5305 RegsToPass[i].second, InFlag); 5306 InFlag = Chain.getValue(1); 5307 } 5308 5309 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5310 // registers. 5311 if (isVarArg) { 5312 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5313 SDValue Ops[] = { Chain, InFlag }; 5314 5315 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5316 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5317 5318 InFlag = Chain.getValue(1); 5319 } 5320 5321 if (isTailCall) 5322 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5323 TailCallArguments); 5324 5325 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5326 /* unused except on PPC64 ELFv1 */ false, DAG, 5327 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5328 NumBytes, Ins, InVals, CS); 5329 } 5330 5331 // Copy an argument into memory, being careful to do this outside the 5332 // call sequence for the call to which the argument belongs. 5333 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5334 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5335 SelectionDAG &DAG, const SDLoc &dl) const { 5336 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5337 CallSeqStart.getNode()->getOperand(0), 5338 Flags, DAG, dl); 5339 // The MEMCPY must go outside the CALLSEQ_START..END. 5340 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5341 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5342 SDLoc(MemcpyCall)); 5343 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5344 NewCallSeqStart.getNode()); 5345 return NewCallSeqStart; 5346 } 5347 5348 SDValue PPCTargetLowering::LowerCall_64SVR4( 5349 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5350 bool isTailCall, bool isPatchPoint, 5351 const SmallVectorImpl<ISD::OutputArg> &Outs, 5352 const SmallVectorImpl<SDValue> &OutVals, 5353 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5354 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5355 ImmutableCallSite CS) const { 5356 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5357 bool isLittleEndian = Subtarget.isLittleEndian(); 5358 unsigned NumOps = Outs.size(); 5359 bool hasNest = false; 5360 bool IsSibCall = false; 5361 5362 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5363 unsigned PtrByteSize = 8; 5364 5365 MachineFunction &MF = DAG.getMachineFunction(); 5366 5367 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5368 IsSibCall = true; 5369 5370 // Mark this function as potentially containing a function that contains a 5371 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5372 // and restoring the callers stack pointer in this functions epilog. This is 5373 // done because by tail calling the called function might overwrite the value 5374 // in this function's (MF) stack pointer stack slot 0(SP). 5375 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5376 CallConv == CallingConv::Fast) 5377 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5378 5379 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5380 "fastcc not supported on varargs functions"); 5381 5382 // Count how many bytes are to be pushed on the stack, including the linkage 5383 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5384 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5385 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5386 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5387 unsigned NumBytes = LinkageSize; 5388 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5389 unsigned &QFPR_idx = FPR_idx; 5390 5391 static const MCPhysReg GPR[] = { 5392 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5393 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5394 }; 5395 static const MCPhysReg VR[] = { 5396 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5397 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5398 }; 5399 5400 const unsigned NumGPRs = array_lengthof(GPR); 5401 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5402 const unsigned NumVRs = array_lengthof(VR); 5403 const unsigned NumQFPRs = NumFPRs; 5404 5405 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5406 // can be passed to the callee in registers. 5407 // For the fast calling convention, there is another check below. 5408 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5409 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5410 if (!HasParameterArea) { 5411 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5412 unsigned AvailableFPRs = NumFPRs; 5413 unsigned AvailableVRs = NumVRs; 5414 unsigned NumBytesTmp = NumBytes; 5415 for (unsigned i = 0; i != NumOps; ++i) { 5416 if (Outs[i].Flags.isNest()) continue; 5417 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5418 PtrByteSize, LinkageSize, ParamAreaSize, 5419 NumBytesTmp, AvailableFPRs, AvailableVRs, 5420 Subtarget.hasQPX())) 5421 HasParameterArea = true; 5422 } 5423 } 5424 5425 // When using the fast calling convention, we don't provide backing for 5426 // arguments that will be in registers. 5427 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5428 5429 // Add up all the space actually used. 5430 for (unsigned i = 0; i != NumOps; ++i) { 5431 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5432 EVT ArgVT = Outs[i].VT; 5433 EVT OrigVT = Outs[i].ArgVT; 5434 5435 if (Flags.isNest()) 5436 continue; 5437 5438 if (CallConv == CallingConv::Fast) { 5439 if (Flags.isByVal()) 5440 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5441 else 5442 switch (ArgVT.getSimpleVT().SimpleTy) { 5443 default: llvm_unreachable("Unexpected ValueType for argument!"); 5444 case MVT::i1: 5445 case MVT::i32: 5446 case MVT::i64: 5447 if (++NumGPRsUsed <= NumGPRs) 5448 continue; 5449 break; 5450 case MVT::v4i32: 5451 case MVT::v8i16: 5452 case MVT::v16i8: 5453 case MVT::v2f64: 5454 case MVT::v2i64: 5455 case MVT::v1i128: 5456 if (++NumVRsUsed <= NumVRs) 5457 continue; 5458 break; 5459 case MVT::v4f32: 5460 // When using QPX, this is handled like a FP register, otherwise, it 5461 // is an Altivec register. 5462 if (Subtarget.hasQPX()) { 5463 if (++NumFPRsUsed <= NumFPRs) 5464 continue; 5465 } else { 5466 if (++NumVRsUsed <= NumVRs) 5467 continue; 5468 } 5469 break; 5470 case MVT::f32: 5471 case MVT::f64: 5472 case MVT::v4f64: // QPX 5473 case MVT::v4i1: // QPX 5474 if (++NumFPRsUsed <= NumFPRs) 5475 continue; 5476 break; 5477 } 5478 } 5479 5480 /* Respect alignment of argument on the stack. */ 5481 unsigned Align = 5482 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5483 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5484 5485 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5486 if (Flags.isInConsecutiveRegsLast()) 5487 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5488 } 5489 5490 unsigned NumBytesActuallyUsed = NumBytes; 5491 5492 // In the old ELFv1 ABI, 5493 // the prolog code of the callee may store up to 8 GPR argument registers to 5494 // the stack, allowing va_start to index over them in memory if its varargs. 5495 // Because we cannot tell if this is needed on the caller side, we have to 5496 // conservatively assume that it is needed. As such, make sure we have at 5497 // least enough stack space for the caller to store the 8 GPRs. 5498 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5499 // really requires memory operands, e.g. a vararg function. 5500 if (HasParameterArea) 5501 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5502 else 5503 NumBytes = LinkageSize; 5504 5505 // Tail call needs the stack to be aligned. 5506 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5507 CallConv == CallingConv::Fast) 5508 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5509 5510 int SPDiff = 0; 5511 5512 // Calculate by how many bytes the stack has to be adjusted in case of tail 5513 // call optimization. 5514 if (!IsSibCall) 5515 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5516 5517 // To protect arguments on the stack from being clobbered in a tail call, 5518 // force all the loads to happen before doing any other lowering. 5519 if (isTailCall) 5520 Chain = DAG.getStackArgumentTokenFactor(Chain); 5521 5522 // Adjust the stack pointer for the new arguments... 5523 // These operations are automatically eliminated by the prolog/epilog pass 5524 if (!IsSibCall) 5525 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5526 SDValue CallSeqStart = Chain; 5527 5528 // Load the return address and frame pointer so it can be move somewhere else 5529 // later. 5530 SDValue LROp, FPOp; 5531 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5532 5533 // Set up a copy of the stack pointer for use loading and storing any 5534 // arguments that may not fit in the registers available for argument 5535 // passing. 5536 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5537 5538 // Figure out which arguments are going to go in registers, and which in 5539 // memory. Also, if this is a vararg function, floating point operations 5540 // must be stored to our stack, and loaded into integer regs as well, if 5541 // any integer regs are available for argument passing. 5542 unsigned ArgOffset = LinkageSize; 5543 5544 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5545 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5546 5547 SmallVector<SDValue, 8> MemOpChains; 5548 for (unsigned i = 0; i != NumOps; ++i) { 5549 SDValue Arg = OutVals[i]; 5550 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5551 EVT ArgVT = Outs[i].VT; 5552 EVT OrigVT = Outs[i].ArgVT; 5553 5554 // PtrOff will be used to store the current argument to the stack if a 5555 // register cannot be found for it. 5556 SDValue PtrOff; 5557 5558 // We re-align the argument offset for each argument, except when using the 5559 // fast calling convention, when we need to make sure we do that only when 5560 // we'll actually use a stack slot. 5561 auto ComputePtrOff = [&]() { 5562 /* Respect alignment of argument on the stack. */ 5563 unsigned Align = 5564 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5565 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5566 5567 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5568 5569 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5570 }; 5571 5572 if (CallConv != CallingConv::Fast) { 5573 ComputePtrOff(); 5574 5575 /* Compute GPR index associated with argument offset. */ 5576 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5577 GPR_idx = std::min(GPR_idx, NumGPRs); 5578 } 5579 5580 // Promote integers to 64-bit values. 5581 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5582 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5583 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5584 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5585 } 5586 5587 // FIXME memcpy is used way more than necessary. Correctness first. 5588 // Note: "by value" is code for passing a structure by value, not 5589 // basic types. 5590 if (Flags.isByVal()) { 5591 // Note: Size includes alignment padding, so 5592 // struct x { short a; char b; } 5593 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5594 // These are the proper values we need for right-justifying the 5595 // aggregate in a parameter register. 5596 unsigned Size = Flags.getByValSize(); 5597 5598 // An empty aggregate parameter takes up no storage and no 5599 // registers. 5600 if (Size == 0) 5601 continue; 5602 5603 if (CallConv == CallingConv::Fast) 5604 ComputePtrOff(); 5605 5606 // All aggregates smaller than 8 bytes must be passed right-justified. 5607 if (Size==1 || Size==2 || Size==4) { 5608 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5609 if (GPR_idx != NumGPRs) { 5610 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5611 MachinePointerInfo(), VT); 5612 MemOpChains.push_back(Load.getValue(1)); 5613 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5614 5615 ArgOffset += PtrByteSize; 5616 continue; 5617 } 5618 } 5619 5620 if (GPR_idx == NumGPRs && Size < 8) { 5621 SDValue AddPtr = PtrOff; 5622 if (!isLittleEndian) { 5623 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5624 PtrOff.getValueType()); 5625 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5626 } 5627 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5628 CallSeqStart, 5629 Flags, DAG, dl); 5630 ArgOffset += PtrByteSize; 5631 continue; 5632 } 5633 // Copy entire object into memory. There are cases where gcc-generated 5634 // code assumes it is there, even if it could be put entirely into 5635 // registers. (This is not what the doc says.) 5636 5637 // FIXME: The above statement is likely due to a misunderstanding of the 5638 // documents. All arguments must be copied into the parameter area BY 5639 // THE CALLEE in the event that the callee takes the address of any 5640 // formal argument. That has not yet been implemented. However, it is 5641 // reasonable to use the stack area as a staging area for the register 5642 // load. 5643 5644 // Skip this for small aggregates, as we will use the same slot for a 5645 // right-justified copy, below. 5646 if (Size >= 8) 5647 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5648 CallSeqStart, 5649 Flags, DAG, dl); 5650 5651 // When a register is available, pass a small aggregate right-justified. 5652 if (Size < 8 && GPR_idx != NumGPRs) { 5653 // The easiest way to get this right-justified in a register 5654 // is to copy the structure into the rightmost portion of a 5655 // local variable slot, then load the whole slot into the 5656 // register. 5657 // FIXME: The memcpy seems to produce pretty awful code for 5658 // small aggregates, particularly for packed ones. 5659 // FIXME: It would be preferable to use the slot in the 5660 // parameter save area instead of a new local variable. 5661 SDValue AddPtr = PtrOff; 5662 if (!isLittleEndian) { 5663 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5664 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5665 } 5666 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5667 CallSeqStart, 5668 Flags, DAG, dl); 5669 5670 // Load the slot into the register. 5671 SDValue Load = 5672 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5673 MemOpChains.push_back(Load.getValue(1)); 5674 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5675 5676 // Done with this argument. 5677 ArgOffset += PtrByteSize; 5678 continue; 5679 } 5680 5681 // For aggregates larger than PtrByteSize, copy the pieces of the 5682 // object that fit into registers from the parameter save area. 5683 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5684 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5685 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5686 if (GPR_idx != NumGPRs) { 5687 SDValue Load = 5688 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5689 MemOpChains.push_back(Load.getValue(1)); 5690 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5691 ArgOffset += PtrByteSize; 5692 } else { 5693 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5694 break; 5695 } 5696 } 5697 continue; 5698 } 5699 5700 switch (Arg.getSimpleValueType().SimpleTy) { 5701 default: llvm_unreachable("Unexpected ValueType for argument!"); 5702 case MVT::i1: 5703 case MVT::i32: 5704 case MVT::i64: 5705 if (Flags.isNest()) { 5706 // The 'nest' parameter, if any, is passed in R11. 5707 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 5708 hasNest = true; 5709 break; 5710 } 5711 5712 // These can be scalar arguments or elements of an integer array type 5713 // passed directly. Clang may use those instead of "byval" aggregate 5714 // types to avoid forcing arguments to memory unnecessarily. 5715 if (GPR_idx != NumGPRs) { 5716 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 5717 } else { 5718 if (CallConv == CallingConv::Fast) 5719 ComputePtrOff(); 5720 5721 assert(HasParameterArea && 5722 "Parameter area must exist to pass an argument in memory."); 5723 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5724 true, isTailCall, false, MemOpChains, 5725 TailCallArguments, dl); 5726 if (CallConv == CallingConv::Fast) 5727 ArgOffset += PtrByteSize; 5728 } 5729 if (CallConv != CallingConv::Fast) 5730 ArgOffset += PtrByteSize; 5731 break; 5732 case MVT::f32: 5733 case MVT::f64: { 5734 // These can be scalar arguments or elements of a float array type 5735 // passed directly. The latter are used to implement ELFv2 homogenous 5736 // float aggregates. 5737 5738 // Named arguments go into FPRs first, and once they overflow, the 5739 // remaining arguments go into GPRs and then the parameter save area. 5740 // Unnamed arguments for vararg functions always go to GPRs and 5741 // then the parameter save area. For now, put all arguments to vararg 5742 // routines always in both locations (FPR *and* GPR or stack slot). 5743 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 5744 bool NeededLoad = false; 5745 5746 // First load the argument into the next available FPR. 5747 if (FPR_idx != NumFPRs) 5748 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 5749 5750 // Next, load the argument into GPR or stack slot if needed. 5751 if (!NeedGPROrStack) 5752 ; 5753 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 5754 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 5755 // once we support fp <-> gpr moves. 5756 5757 // In the non-vararg case, this can only ever happen in the 5758 // presence of f32 array types, since otherwise we never run 5759 // out of FPRs before running out of GPRs. 5760 SDValue ArgVal; 5761 5762 // Double values are always passed in a single GPR. 5763 if (Arg.getValueType() != MVT::f32) { 5764 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 5765 5766 // Non-array float values are extended and passed in a GPR. 5767 } else if (!Flags.isInConsecutiveRegs()) { 5768 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5769 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5770 5771 // If we have an array of floats, we collect every odd element 5772 // together with its predecessor into one GPR. 5773 } else if (ArgOffset % PtrByteSize != 0) { 5774 SDValue Lo, Hi; 5775 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 5776 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5777 if (!isLittleEndian) 5778 std::swap(Lo, Hi); 5779 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 5780 5781 // The final element, if even, goes into the first half of a GPR. 5782 } else if (Flags.isInConsecutiveRegsLast()) { 5783 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 5784 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 5785 if (!isLittleEndian) 5786 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 5787 DAG.getConstant(32, dl, MVT::i32)); 5788 5789 // Non-final even elements are skipped; they will be handled 5790 // together the with subsequent argument on the next go-around. 5791 } else 5792 ArgVal = SDValue(); 5793 5794 if (ArgVal.getNode()) 5795 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 5796 } else { 5797 if (CallConv == CallingConv::Fast) 5798 ComputePtrOff(); 5799 5800 // Single-precision floating-point values are mapped to the 5801 // second (rightmost) word of the stack doubleword. 5802 if (Arg.getValueType() == MVT::f32 && 5803 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 5804 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 5805 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 5806 } 5807 5808 assert(HasParameterArea && 5809 "Parameter area must exist to pass an argument in memory."); 5810 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5811 true, isTailCall, false, MemOpChains, 5812 TailCallArguments, dl); 5813 5814 NeededLoad = true; 5815 } 5816 // When passing an array of floats, the array occupies consecutive 5817 // space in the argument area; only round up to the next doubleword 5818 // at the end of the array. Otherwise, each float takes 8 bytes. 5819 if (CallConv != CallingConv::Fast || NeededLoad) { 5820 ArgOffset += (Arg.getValueType() == MVT::f32 && 5821 Flags.isInConsecutiveRegs()) ? 4 : 8; 5822 if (Flags.isInConsecutiveRegsLast()) 5823 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5824 } 5825 break; 5826 } 5827 case MVT::v4f32: 5828 case MVT::v4i32: 5829 case MVT::v8i16: 5830 case MVT::v16i8: 5831 case MVT::v2f64: 5832 case MVT::v2i64: 5833 case MVT::v1i128: 5834 if (!Subtarget.hasQPX()) { 5835 // These can be scalar arguments or elements of a vector array type 5836 // passed directly. The latter are used to implement ELFv2 homogenous 5837 // vector aggregates. 5838 5839 // For a varargs call, named arguments go into VRs or on the stack as 5840 // usual; unnamed arguments always go to the stack or the corresponding 5841 // GPRs when within range. For now, we always put the value in both 5842 // locations (or even all three). 5843 if (isVarArg) { 5844 assert(HasParameterArea && 5845 "Parameter area must exist if we have a varargs call."); 5846 // We could elide this store in the case where the object fits 5847 // entirely in R registers. Maybe later. 5848 SDValue Store = 5849 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5850 MemOpChains.push_back(Store); 5851 if (VR_idx != NumVRs) { 5852 SDValue Load = 5853 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 5854 MemOpChains.push_back(Load.getValue(1)); 5855 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 5856 } 5857 ArgOffset += 16; 5858 for (unsigned i=0; i<16; i+=PtrByteSize) { 5859 if (GPR_idx == NumGPRs) 5860 break; 5861 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5862 DAG.getConstant(i, dl, PtrVT)); 5863 SDValue Load = 5864 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5865 MemOpChains.push_back(Load.getValue(1)); 5866 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5867 } 5868 break; 5869 } 5870 5871 // Non-varargs Altivec params go into VRs or on the stack. 5872 if (VR_idx != NumVRs) { 5873 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 5874 } else { 5875 if (CallConv == CallingConv::Fast) 5876 ComputePtrOff(); 5877 5878 assert(HasParameterArea && 5879 "Parameter area must exist to pass an argument in memory."); 5880 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5881 true, isTailCall, true, MemOpChains, 5882 TailCallArguments, dl); 5883 if (CallConv == CallingConv::Fast) 5884 ArgOffset += 16; 5885 } 5886 5887 if (CallConv != CallingConv::Fast) 5888 ArgOffset += 16; 5889 break; 5890 } // not QPX 5891 5892 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 5893 "Invalid QPX parameter type"); 5894 5895 /* fall through */ 5896 case MVT::v4f64: 5897 case MVT::v4i1: { 5898 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 5899 if (isVarArg) { 5900 assert(HasParameterArea && 5901 "Parameter area must exist if we have a varargs call."); 5902 // We could elide this store in the case where the object fits 5903 // entirely in R registers. Maybe later. 5904 SDValue Store = 5905 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 5906 MemOpChains.push_back(Store); 5907 if (QFPR_idx != NumQFPRs) { 5908 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 5909 PtrOff, MachinePointerInfo()); 5910 MemOpChains.push_back(Load.getValue(1)); 5911 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 5912 } 5913 ArgOffset += (IsF32 ? 16 : 32); 5914 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 5915 if (GPR_idx == NumGPRs) 5916 break; 5917 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 5918 DAG.getConstant(i, dl, PtrVT)); 5919 SDValue Load = 5920 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 5921 MemOpChains.push_back(Load.getValue(1)); 5922 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5923 } 5924 break; 5925 } 5926 5927 // Non-varargs QPX params go into registers or on the stack. 5928 if (QFPR_idx != NumQFPRs) { 5929 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 5930 } else { 5931 if (CallConv == CallingConv::Fast) 5932 ComputePtrOff(); 5933 5934 assert(HasParameterArea && 5935 "Parameter area must exist to pass an argument in memory."); 5936 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 5937 true, isTailCall, true, MemOpChains, 5938 TailCallArguments, dl); 5939 if (CallConv == CallingConv::Fast) 5940 ArgOffset += (IsF32 ? 16 : 32); 5941 } 5942 5943 if (CallConv != CallingConv::Fast) 5944 ArgOffset += (IsF32 ? 16 : 32); 5945 break; 5946 } 5947 } 5948 } 5949 5950 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 5951 "mismatch in size of parameter area"); 5952 (void)NumBytesActuallyUsed; 5953 5954 if (!MemOpChains.empty()) 5955 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5956 5957 // Check if this is an indirect call (MTCTR/BCTRL). 5958 // See PrepareCall() for more information about calls through function 5959 // pointers in the 64-bit SVR4 ABI. 5960 if (!isTailCall && !isPatchPoint && 5961 !isFunctionGlobalAddress(Callee) && 5962 !isa<ExternalSymbolSDNode>(Callee)) { 5963 // Load r2 into a virtual register and store it to the TOC save area. 5964 setUsesTOCBasePtr(DAG); 5965 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 5966 // TOC save area offset. 5967 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5968 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5969 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5970 Chain = DAG.getStore( 5971 Val.getValue(1), dl, Val, AddPtr, 5972 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 5973 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 5974 // This does not mean the MTCTR instruction must use R12; it's easier 5975 // to model this as an extra parameter, so do that. 5976 if (isELFv2ABI && !isPatchPoint) 5977 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 5978 } 5979 5980 // Build a sequence of copy-to-reg nodes chained together with token chain 5981 // and flag operands which copy the outgoing args into the appropriate regs. 5982 SDValue InFlag; 5983 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5984 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5985 RegsToPass[i].second, InFlag); 5986 InFlag = Chain.getValue(1); 5987 } 5988 5989 if (isTailCall && !IsSibCall) 5990 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5991 TailCallArguments); 5992 5993 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 5994 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 5995 SPDiff, NumBytes, Ins, InVals, CS); 5996 } 5997 5998 SDValue PPCTargetLowering::LowerCall_Darwin( 5999 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6000 bool isTailCall, bool isPatchPoint, 6001 const SmallVectorImpl<ISD::OutputArg> &Outs, 6002 const SmallVectorImpl<SDValue> &OutVals, 6003 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6004 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6005 ImmutableCallSite CS) const { 6006 unsigned NumOps = Outs.size(); 6007 6008 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6009 bool isPPC64 = PtrVT == MVT::i64; 6010 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6011 6012 MachineFunction &MF = DAG.getMachineFunction(); 6013 6014 // Mark this function as potentially containing a function that contains a 6015 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6016 // and restoring the callers stack pointer in this functions epilog. This is 6017 // done because by tail calling the called function might overwrite the value 6018 // in this function's (MF) stack pointer stack slot 0(SP). 6019 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6020 CallConv == CallingConv::Fast) 6021 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6022 6023 // Count how many bytes are to be pushed on the stack, including the linkage 6024 // area, and parameter passing area. We start with 24/48 bytes, which is 6025 // prereserved space for [SP][CR][LR][3 x unused]. 6026 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6027 unsigned NumBytes = LinkageSize; 6028 6029 // Add up all the space actually used. 6030 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6031 // they all go in registers, but we must reserve stack space for them for 6032 // possible use by the caller. In varargs or 64-bit calls, parameters are 6033 // assigned stack space in order, with padding so Altivec parameters are 6034 // 16-byte aligned. 6035 unsigned nAltivecParamsAtEnd = 0; 6036 for (unsigned i = 0; i != NumOps; ++i) { 6037 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6038 EVT ArgVT = Outs[i].VT; 6039 // Varargs Altivec parameters are padded to a 16 byte boundary. 6040 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6041 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6042 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6043 if (!isVarArg && !isPPC64) { 6044 // Non-varargs Altivec parameters go after all the non-Altivec 6045 // parameters; handle those later so we know how much padding we need. 6046 nAltivecParamsAtEnd++; 6047 continue; 6048 } 6049 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6050 NumBytes = ((NumBytes+15)/16)*16; 6051 } 6052 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6053 } 6054 6055 // Allow for Altivec parameters at the end, if needed. 6056 if (nAltivecParamsAtEnd) { 6057 NumBytes = ((NumBytes+15)/16)*16; 6058 NumBytes += 16*nAltivecParamsAtEnd; 6059 } 6060 6061 // The prolog code of the callee may store up to 8 GPR argument registers to 6062 // the stack, allowing va_start to index over them in memory if its varargs. 6063 // Because we cannot tell if this is needed on the caller side, we have to 6064 // conservatively assume that it is needed. As such, make sure we have at 6065 // least enough stack space for the caller to store the 8 GPRs. 6066 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6067 6068 // Tail call needs the stack to be aligned. 6069 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6070 CallConv == CallingConv::Fast) 6071 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6072 6073 // Calculate by how many bytes the stack has to be adjusted in case of tail 6074 // call optimization. 6075 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6076 6077 // To protect arguments on the stack from being clobbered in a tail call, 6078 // force all the loads to happen before doing any other lowering. 6079 if (isTailCall) 6080 Chain = DAG.getStackArgumentTokenFactor(Chain); 6081 6082 // Adjust the stack pointer for the new arguments... 6083 // These operations are automatically eliminated by the prolog/epilog pass 6084 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6085 SDValue CallSeqStart = Chain; 6086 6087 // Load the return address and frame pointer so it can be move somewhere else 6088 // later. 6089 SDValue LROp, FPOp; 6090 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6091 6092 // Set up a copy of the stack pointer for use loading and storing any 6093 // arguments that may not fit in the registers available for argument 6094 // passing. 6095 SDValue StackPtr; 6096 if (isPPC64) 6097 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6098 else 6099 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6100 6101 // Figure out which arguments are going to go in registers, and which in 6102 // memory. Also, if this is a vararg function, floating point operations 6103 // must be stored to our stack, and loaded into integer regs as well, if 6104 // any integer regs are available for argument passing. 6105 unsigned ArgOffset = LinkageSize; 6106 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6107 6108 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6109 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6110 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6111 }; 6112 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6113 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6114 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6115 }; 6116 static const MCPhysReg VR[] = { 6117 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6118 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6119 }; 6120 const unsigned NumGPRs = array_lengthof(GPR_32); 6121 const unsigned NumFPRs = 13; 6122 const unsigned NumVRs = array_lengthof(VR); 6123 6124 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6125 6126 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6127 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6128 6129 SmallVector<SDValue, 8> MemOpChains; 6130 for (unsigned i = 0; i != NumOps; ++i) { 6131 SDValue Arg = OutVals[i]; 6132 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6133 6134 // PtrOff will be used to store the current argument to the stack if a 6135 // register cannot be found for it. 6136 SDValue PtrOff; 6137 6138 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6139 6140 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6141 6142 // On PPC64, promote integers to 64-bit values. 6143 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6144 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6145 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6146 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6147 } 6148 6149 // FIXME memcpy is used way more than necessary. Correctness first. 6150 // Note: "by value" is code for passing a structure by value, not 6151 // basic types. 6152 if (Flags.isByVal()) { 6153 unsigned Size = Flags.getByValSize(); 6154 // Very small objects are passed right-justified. Everything else is 6155 // passed left-justified. 6156 if (Size==1 || Size==2) { 6157 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6158 if (GPR_idx != NumGPRs) { 6159 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6160 MachinePointerInfo(), VT); 6161 MemOpChains.push_back(Load.getValue(1)); 6162 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6163 6164 ArgOffset += PtrByteSize; 6165 } else { 6166 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6167 PtrOff.getValueType()); 6168 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6169 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6170 CallSeqStart, 6171 Flags, DAG, dl); 6172 ArgOffset += PtrByteSize; 6173 } 6174 continue; 6175 } 6176 // Copy entire object into memory. There are cases where gcc-generated 6177 // code assumes it is there, even if it could be put entirely into 6178 // registers. (This is not what the doc says.) 6179 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6180 CallSeqStart, 6181 Flags, DAG, dl); 6182 6183 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6184 // copy the pieces of the object that fit into registers from the 6185 // parameter save area. 6186 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6187 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6188 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6189 if (GPR_idx != NumGPRs) { 6190 SDValue Load = 6191 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6192 MemOpChains.push_back(Load.getValue(1)); 6193 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6194 ArgOffset += PtrByteSize; 6195 } else { 6196 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6197 break; 6198 } 6199 } 6200 continue; 6201 } 6202 6203 switch (Arg.getSimpleValueType().SimpleTy) { 6204 default: llvm_unreachable("Unexpected ValueType for argument!"); 6205 case MVT::i1: 6206 case MVT::i32: 6207 case MVT::i64: 6208 if (GPR_idx != NumGPRs) { 6209 if (Arg.getValueType() == MVT::i1) 6210 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6211 6212 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6213 } else { 6214 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6215 isPPC64, isTailCall, false, MemOpChains, 6216 TailCallArguments, dl); 6217 } 6218 ArgOffset += PtrByteSize; 6219 break; 6220 case MVT::f32: 6221 case MVT::f64: 6222 if (FPR_idx != NumFPRs) { 6223 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6224 6225 if (isVarArg) { 6226 SDValue Store = 6227 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6228 MemOpChains.push_back(Store); 6229 6230 // Float varargs are always shadowed in available integer registers 6231 if (GPR_idx != NumGPRs) { 6232 SDValue Load = 6233 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6234 MemOpChains.push_back(Load.getValue(1)); 6235 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6236 } 6237 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6238 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6239 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6240 SDValue Load = 6241 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6242 MemOpChains.push_back(Load.getValue(1)); 6243 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6244 } 6245 } else { 6246 // If we have any FPRs remaining, we may also have GPRs remaining. 6247 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6248 // GPRs. 6249 if (GPR_idx != NumGPRs) 6250 ++GPR_idx; 6251 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6252 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6253 ++GPR_idx; 6254 } 6255 } else 6256 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6257 isPPC64, isTailCall, false, MemOpChains, 6258 TailCallArguments, dl); 6259 if (isPPC64) 6260 ArgOffset += 8; 6261 else 6262 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6263 break; 6264 case MVT::v4f32: 6265 case MVT::v4i32: 6266 case MVT::v8i16: 6267 case MVT::v16i8: 6268 if (isVarArg) { 6269 // These go aligned on the stack, or in the corresponding R registers 6270 // when within range. The Darwin PPC ABI doc claims they also go in 6271 // V registers; in fact gcc does this only for arguments that are 6272 // prototyped, not for those that match the ... We do it for all 6273 // arguments, seems to work. 6274 while (ArgOffset % 16 !=0) { 6275 ArgOffset += PtrByteSize; 6276 if (GPR_idx != NumGPRs) 6277 GPR_idx++; 6278 } 6279 // We could elide this store in the case where the object fits 6280 // entirely in R registers. Maybe later. 6281 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6282 DAG.getConstant(ArgOffset, dl, PtrVT)); 6283 SDValue Store = 6284 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6285 MemOpChains.push_back(Store); 6286 if (VR_idx != NumVRs) { 6287 SDValue Load = 6288 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6289 MemOpChains.push_back(Load.getValue(1)); 6290 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6291 } 6292 ArgOffset += 16; 6293 for (unsigned i=0; i<16; i+=PtrByteSize) { 6294 if (GPR_idx == NumGPRs) 6295 break; 6296 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6297 DAG.getConstant(i, dl, PtrVT)); 6298 SDValue Load = 6299 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6300 MemOpChains.push_back(Load.getValue(1)); 6301 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6302 } 6303 break; 6304 } 6305 6306 // Non-varargs Altivec params generally go in registers, but have 6307 // stack space allocated at the end. 6308 if (VR_idx != NumVRs) { 6309 // Doesn't have GPR space allocated. 6310 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6311 } else if (nAltivecParamsAtEnd==0) { 6312 // We are emitting Altivec params in order. 6313 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6314 isPPC64, isTailCall, true, MemOpChains, 6315 TailCallArguments, dl); 6316 ArgOffset += 16; 6317 } 6318 break; 6319 } 6320 } 6321 // If all Altivec parameters fit in registers, as they usually do, 6322 // they get stack space following the non-Altivec parameters. We 6323 // don't track this here because nobody below needs it. 6324 // If there are more Altivec parameters than fit in registers emit 6325 // the stores here. 6326 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6327 unsigned j = 0; 6328 // Offset is aligned; skip 1st 12 params which go in V registers. 6329 ArgOffset = ((ArgOffset+15)/16)*16; 6330 ArgOffset += 12*16; 6331 for (unsigned i = 0; i != NumOps; ++i) { 6332 SDValue Arg = OutVals[i]; 6333 EVT ArgType = Outs[i].VT; 6334 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6335 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6336 if (++j > NumVRs) { 6337 SDValue PtrOff; 6338 // We are emitting Altivec params in order. 6339 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6340 isPPC64, isTailCall, true, MemOpChains, 6341 TailCallArguments, dl); 6342 ArgOffset += 16; 6343 } 6344 } 6345 } 6346 } 6347 6348 if (!MemOpChains.empty()) 6349 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6350 6351 // On Darwin, R12 must contain the address of an indirect callee. This does 6352 // not mean the MTCTR instruction must use R12; it's easier to model this as 6353 // an extra parameter, so do that. 6354 if (!isTailCall && 6355 !isFunctionGlobalAddress(Callee) && 6356 !isa<ExternalSymbolSDNode>(Callee) && 6357 !isBLACompatibleAddress(Callee, DAG)) 6358 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6359 PPC::R12), Callee)); 6360 6361 // Build a sequence of copy-to-reg nodes chained together with token chain 6362 // and flag operands which copy the outgoing args into the appropriate regs. 6363 SDValue InFlag; 6364 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6365 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6366 RegsToPass[i].second, InFlag); 6367 InFlag = Chain.getValue(1); 6368 } 6369 6370 if (isTailCall) 6371 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6372 TailCallArguments); 6373 6374 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6375 /* unused except on PPC64 ELFv1 */ false, DAG, 6376 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6377 NumBytes, Ins, InVals, CS); 6378 } 6379 6380 bool 6381 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6382 MachineFunction &MF, bool isVarArg, 6383 const SmallVectorImpl<ISD::OutputArg> &Outs, 6384 LLVMContext &Context) const { 6385 SmallVector<CCValAssign, 16> RVLocs; 6386 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6387 return CCInfo.CheckReturn(Outs, RetCC_PPC); 6388 } 6389 6390 SDValue 6391 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6392 bool isVarArg, 6393 const SmallVectorImpl<ISD::OutputArg> &Outs, 6394 const SmallVectorImpl<SDValue> &OutVals, 6395 const SDLoc &dl, SelectionDAG &DAG) const { 6396 SmallVector<CCValAssign, 16> RVLocs; 6397 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6398 *DAG.getContext()); 6399 CCInfo.AnalyzeReturn(Outs, RetCC_PPC); 6400 6401 SDValue Flag; 6402 SmallVector<SDValue, 4> RetOps(1, Chain); 6403 6404 // Copy the result values into the output registers. 6405 for (unsigned i = 0; i != RVLocs.size(); ++i) { 6406 CCValAssign &VA = RVLocs[i]; 6407 assert(VA.isRegLoc() && "Can only return in registers!"); 6408 6409 SDValue Arg = OutVals[i]; 6410 6411 switch (VA.getLocInfo()) { 6412 default: llvm_unreachable("Unknown loc info!"); 6413 case CCValAssign::Full: break; 6414 case CCValAssign::AExt: 6415 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6416 break; 6417 case CCValAssign::ZExt: 6418 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6419 break; 6420 case CCValAssign::SExt: 6421 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6422 break; 6423 } 6424 6425 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6426 Flag = Chain.getValue(1); 6427 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6428 } 6429 6430 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6431 const MCPhysReg *I = 6432 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6433 if (I) { 6434 for (; *I; ++I) { 6435 6436 if (PPC::G8RCRegClass.contains(*I)) 6437 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6438 else if (PPC::F8RCRegClass.contains(*I)) 6439 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6440 else if (PPC::CRRCRegClass.contains(*I)) 6441 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6442 else if (PPC::VRRCRegClass.contains(*I)) 6443 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6444 else 6445 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6446 } 6447 } 6448 6449 RetOps[0] = Chain; // Update chain. 6450 6451 // Add the flag if we have it. 6452 if (Flag.getNode()) 6453 RetOps.push_back(Flag); 6454 6455 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6456 } 6457 6458 SDValue 6459 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6460 SelectionDAG &DAG) const { 6461 SDLoc dl(Op); 6462 6463 // Get the correct type for integers. 6464 EVT IntVT = Op.getValueType(); 6465 6466 // Get the inputs. 6467 SDValue Chain = Op.getOperand(0); 6468 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6469 // Build a DYNAREAOFFSET node. 6470 SDValue Ops[2] = {Chain, FPSIdx}; 6471 SDVTList VTs = DAG.getVTList(IntVT); 6472 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6473 } 6474 6475 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6476 SelectionDAG &DAG) const { 6477 // When we pop the dynamic allocation we need to restore the SP link. 6478 SDLoc dl(Op); 6479 6480 // Get the correct type for pointers. 6481 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6482 6483 // Construct the stack pointer operand. 6484 bool isPPC64 = Subtarget.isPPC64(); 6485 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6486 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6487 6488 // Get the operands for the STACKRESTORE. 6489 SDValue Chain = Op.getOperand(0); 6490 SDValue SaveSP = Op.getOperand(1); 6491 6492 // Load the old link SP. 6493 SDValue LoadLinkSP = 6494 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6495 6496 // Restore the stack pointer. 6497 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6498 6499 // Store the old link SP. 6500 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6501 } 6502 6503 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6504 MachineFunction &MF = DAG.getMachineFunction(); 6505 bool isPPC64 = Subtarget.isPPC64(); 6506 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6507 6508 // Get current frame pointer save index. The users of this index will be 6509 // primarily DYNALLOC instructions. 6510 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6511 int RASI = FI->getReturnAddrSaveIndex(); 6512 6513 // If the frame pointer save index hasn't been defined yet. 6514 if (!RASI) { 6515 // Find out what the fix offset of the frame pointer save area. 6516 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6517 // Allocate the frame index for frame pointer save area. 6518 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6519 // Save the result. 6520 FI->setReturnAddrSaveIndex(RASI); 6521 } 6522 return DAG.getFrameIndex(RASI, PtrVT); 6523 } 6524 6525 SDValue 6526 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6527 MachineFunction &MF = DAG.getMachineFunction(); 6528 bool isPPC64 = Subtarget.isPPC64(); 6529 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6530 6531 // Get current frame pointer save index. The users of this index will be 6532 // primarily DYNALLOC instructions. 6533 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6534 int FPSI = FI->getFramePointerSaveIndex(); 6535 6536 // If the frame pointer save index hasn't been defined yet. 6537 if (!FPSI) { 6538 // Find out what the fix offset of the frame pointer save area. 6539 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6540 // Allocate the frame index for frame pointer save area. 6541 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6542 // Save the result. 6543 FI->setFramePointerSaveIndex(FPSI); 6544 } 6545 return DAG.getFrameIndex(FPSI, PtrVT); 6546 } 6547 6548 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6549 SelectionDAG &DAG) const { 6550 // Get the inputs. 6551 SDValue Chain = Op.getOperand(0); 6552 SDValue Size = Op.getOperand(1); 6553 SDLoc dl(Op); 6554 6555 // Get the correct type for pointers. 6556 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6557 // Negate the size. 6558 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 6559 DAG.getConstant(0, dl, PtrVT), Size); 6560 // Construct a node for the frame pointer save index. 6561 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6562 // Build a DYNALLOC node. 6563 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 6564 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 6565 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 6566 } 6567 6568 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 6569 SelectionDAG &DAG) const { 6570 MachineFunction &MF = DAG.getMachineFunction(); 6571 6572 bool isPPC64 = Subtarget.isPPC64(); 6573 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6574 6575 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 6576 return DAG.getFrameIndex(FI, PtrVT); 6577 } 6578 6579 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 6580 SelectionDAG &DAG) const { 6581 SDLoc DL(Op); 6582 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 6583 DAG.getVTList(MVT::i32, MVT::Other), 6584 Op.getOperand(0), Op.getOperand(1)); 6585 } 6586 6587 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 6588 SelectionDAG &DAG) const { 6589 SDLoc DL(Op); 6590 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 6591 Op.getOperand(0), Op.getOperand(1)); 6592 } 6593 6594 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 6595 if (Op.getValueType().isVector()) 6596 return LowerVectorLoad(Op, DAG); 6597 6598 assert(Op.getValueType() == MVT::i1 && 6599 "Custom lowering only for i1 loads"); 6600 6601 // First, load 8 bits into 32 bits, then truncate to 1 bit. 6602 6603 SDLoc dl(Op); 6604 LoadSDNode *LD = cast<LoadSDNode>(Op); 6605 6606 SDValue Chain = LD->getChain(); 6607 SDValue BasePtr = LD->getBasePtr(); 6608 MachineMemOperand *MMO = LD->getMemOperand(); 6609 6610 SDValue NewLD = 6611 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 6612 BasePtr, MVT::i8, MMO); 6613 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 6614 6615 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 6616 return DAG.getMergeValues(Ops, dl); 6617 } 6618 6619 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 6620 if (Op.getOperand(1).getValueType().isVector()) 6621 return LowerVectorStore(Op, DAG); 6622 6623 assert(Op.getOperand(1).getValueType() == MVT::i1 && 6624 "Custom lowering only for i1 stores"); 6625 6626 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 6627 6628 SDLoc dl(Op); 6629 StoreSDNode *ST = cast<StoreSDNode>(Op); 6630 6631 SDValue Chain = ST->getChain(); 6632 SDValue BasePtr = ST->getBasePtr(); 6633 SDValue Value = ST->getValue(); 6634 MachineMemOperand *MMO = ST->getMemOperand(); 6635 6636 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 6637 Value); 6638 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 6639 } 6640 6641 // FIXME: Remove this once the ANDI glue bug is fixed: 6642 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 6643 assert(Op.getValueType() == MVT::i1 && 6644 "Custom lowering only for i1 results"); 6645 6646 SDLoc DL(Op); 6647 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 6648 Op.getOperand(0)); 6649 } 6650 6651 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 6652 /// possible. 6653 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 6654 // Not FP? Not a fsel. 6655 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 6656 !Op.getOperand(2).getValueType().isFloatingPoint()) 6657 return Op; 6658 6659 // We might be able to do better than this under some circumstances, but in 6660 // general, fsel-based lowering of select is a finite-math-only optimization. 6661 // For more information, see section F.3 of the 2.06 ISA specification. 6662 if (!DAG.getTarget().Options.NoInfsFPMath || 6663 !DAG.getTarget().Options.NoNaNsFPMath) 6664 return Op; 6665 // TODO: Propagate flags from the select rather than global settings. 6666 SDNodeFlags Flags; 6667 Flags.setNoInfs(true); 6668 Flags.setNoNaNs(true); 6669 6670 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 6671 6672 EVT ResVT = Op.getValueType(); 6673 EVT CmpVT = Op.getOperand(0).getValueType(); 6674 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 6675 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 6676 SDLoc dl(Op); 6677 6678 // If the RHS of the comparison is a 0.0, we don't need to do the 6679 // subtraction at all. 6680 SDValue Sel1; 6681 if (isFloatingPointZero(RHS)) 6682 switch (CC) { 6683 default: break; // SETUO etc aren't handled by fsel. 6684 case ISD::SETNE: 6685 std::swap(TV, FV); 6686 LLVM_FALLTHROUGH; 6687 case ISD::SETEQ: 6688 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6689 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6690 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6691 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6692 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6693 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6694 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 6695 case ISD::SETULT: 6696 case ISD::SETLT: 6697 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6698 LLVM_FALLTHROUGH; 6699 case ISD::SETOGE: 6700 case ISD::SETGE: 6701 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6702 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6703 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 6704 case ISD::SETUGT: 6705 case ISD::SETGT: 6706 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 6707 LLVM_FALLTHROUGH; 6708 case ISD::SETOLE: 6709 case ISD::SETLE: 6710 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 6711 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 6712 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6713 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 6714 } 6715 6716 SDValue Cmp; 6717 switch (CC) { 6718 default: break; // SETUO etc aren't handled by fsel. 6719 case ISD::SETNE: 6720 std::swap(TV, FV); 6721 LLVM_FALLTHROUGH; 6722 case ISD::SETEQ: 6723 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6724 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6725 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6726 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6727 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 6728 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 6729 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 6730 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 6731 case ISD::SETULT: 6732 case ISD::SETLT: 6733 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6734 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6735 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6736 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6737 case ISD::SETOGE: 6738 case ISD::SETGE: 6739 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 6740 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6741 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6742 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6743 case ISD::SETUGT: 6744 case ISD::SETGT: 6745 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6746 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6747 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6748 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 6749 case ISD::SETOLE: 6750 case ISD::SETLE: 6751 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 6752 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 6753 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 6754 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 6755 } 6756 return Op; 6757 } 6758 6759 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 6760 SelectionDAG &DAG, 6761 const SDLoc &dl) const { 6762 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6763 SDValue Src = Op.getOperand(0); 6764 if (Src.getValueType() == MVT::f32) 6765 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6766 6767 SDValue Tmp; 6768 switch (Op.getSimpleValueType().SimpleTy) { 6769 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6770 case MVT::i32: 6771 Tmp = DAG.getNode( 6772 Op.getOpcode() == ISD::FP_TO_SINT 6773 ? PPCISD::FCTIWZ 6774 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6775 dl, MVT::f64, Src); 6776 break; 6777 case MVT::i64: 6778 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6779 "i64 FP_TO_UINT is supported only with FPCVT"); 6780 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6781 PPCISD::FCTIDUZ, 6782 dl, MVT::f64, Src); 6783 break; 6784 } 6785 6786 // Convert the FP value to an int value through memory. 6787 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 6788 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 6789 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 6790 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 6791 MachinePointerInfo MPI = 6792 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 6793 6794 // Emit a store to the stack slot. 6795 SDValue Chain; 6796 if (i32Stack) { 6797 MachineFunction &MF = DAG.getMachineFunction(); 6798 MachineMemOperand *MMO = 6799 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 6800 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 6801 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 6802 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 6803 } else 6804 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 6805 6806 // Result is a load from the stack slot. If loading 4 bytes, make sure to 6807 // add in a bias on big endian. 6808 if (Op.getValueType() == MVT::i32 && !i32Stack) { 6809 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 6810 DAG.getConstant(4, dl, FIPtr.getValueType())); 6811 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 6812 } 6813 6814 RLI.Chain = Chain; 6815 RLI.Ptr = FIPtr; 6816 RLI.MPI = MPI; 6817 } 6818 6819 /// \brief Custom lowers floating point to integer conversions to use 6820 /// the direct move instructions available in ISA 2.07 to avoid the 6821 /// need for load/store combinations. 6822 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 6823 SelectionDAG &DAG, 6824 const SDLoc &dl) const { 6825 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 6826 SDValue Src = Op.getOperand(0); 6827 6828 if (Src.getValueType() == MVT::f32) 6829 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 6830 6831 SDValue Tmp; 6832 switch (Op.getSimpleValueType().SimpleTy) { 6833 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 6834 case MVT::i32: 6835 Tmp = DAG.getNode( 6836 Op.getOpcode() == ISD::FP_TO_SINT 6837 ? PPCISD::FCTIWZ 6838 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 6839 dl, MVT::f64, Src); 6840 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 6841 break; 6842 case MVT::i64: 6843 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 6844 "i64 FP_TO_UINT is supported only with FPCVT"); 6845 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 6846 PPCISD::FCTIDUZ, 6847 dl, MVT::f64, Src); 6848 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 6849 break; 6850 } 6851 return Tmp; 6852 } 6853 6854 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 6855 const SDLoc &dl) const { 6856 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 6857 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 6858 6859 ReuseLoadInfo RLI; 6860 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6861 6862 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 6863 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 6864 } 6865 6866 // We're trying to insert a regular store, S, and then a load, L. If the 6867 // incoming value, O, is a load, we might just be able to have our load use the 6868 // address used by O. However, we don't know if anything else will store to 6869 // that address before we can load from it. To prevent this situation, we need 6870 // to insert our load, L, into the chain as a peer of O. To do this, we give L 6871 // the same chain operand as O, we create a token factor from the chain results 6872 // of O and L, and we replace all uses of O's chain result with that token 6873 // factor (see spliceIntoChain below for this last part). 6874 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 6875 ReuseLoadInfo &RLI, 6876 SelectionDAG &DAG, 6877 ISD::LoadExtType ET) const { 6878 SDLoc dl(Op); 6879 if (ET == ISD::NON_EXTLOAD && 6880 (Op.getOpcode() == ISD::FP_TO_UINT || 6881 Op.getOpcode() == ISD::FP_TO_SINT) && 6882 isOperationLegalOrCustom(Op.getOpcode(), 6883 Op.getOperand(0).getValueType())) { 6884 6885 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 6886 return true; 6887 } 6888 6889 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 6890 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 6891 LD->isNonTemporal()) 6892 return false; 6893 if (LD->getMemoryVT() != MemVT) 6894 return false; 6895 6896 RLI.Ptr = LD->getBasePtr(); 6897 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 6898 assert(LD->getAddressingMode() == ISD::PRE_INC && 6899 "Non-pre-inc AM on PPC?"); 6900 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 6901 LD->getOffset()); 6902 } 6903 6904 RLI.Chain = LD->getChain(); 6905 RLI.MPI = LD->getPointerInfo(); 6906 RLI.IsDereferenceable = LD->isDereferenceable(); 6907 RLI.IsInvariant = LD->isInvariant(); 6908 RLI.Alignment = LD->getAlignment(); 6909 RLI.AAInfo = LD->getAAInfo(); 6910 RLI.Ranges = LD->getRanges(); 6911 6912 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 6913 return true; 6914 } 6915 6916 // Given the head of the old chain, ResChain, insert a token factor containing 6917 // it and NewResChain, and make users of ResChain now be users of that token 6918 // factor. 6919 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 6920 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 6921 SDValue NewResChain, 6922 SelectionDAG &DAG) const { 6923 if (!ResChain) 6924 return; 6925 6926 SDLoc dl(NewResChain); 6927 6928 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6929 NewResChain, DAG.getUNDEF(MVT::Other)); 6930 assert(TF.getNode() != NewResChain.getNode() && 6931 "A new TF really is required here"); 6932 6933 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 6934 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 6935 } 6936 6937 /// \brief Analyze profitability of direct move 6938 /// prefer float load to int load plus direct move 6939 /// when there is no integer use of int load 6940 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 6941 SDNode *Origin = Op.getOperand(0).getNode(); 6942 if (Origin->getOpcode() != ISD::LOAD) 6943 return true; 6944 6945 // If there is no LXSIBZX/LXSIHZX, like Power8, 6946 // prefer direct move if the memory size is 1 or 2 bytes. 6947 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 6948 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 6949 return true; 6950 6951 for (SDNode::use_iterator UI = Origin->use_begin(), 6952 UE = Origin->use_end(); 6953 UI != UE; ++UI) { 6954 6955 // Only look at the users of the loaded value. 6956 if (UI.getUse().get().getResNo() != 0) 6957 continue; 6958 6959 if (UI->getOpcode() != ISD::SINT_TO_FP && 6960 UI->getOpcode() != ISD::UINT_TO_FP) 6961 return true; 6962 } 6963 6964 return false; 6965 } 6966 6967 /// \brief Custom lowers integer to floating point conversions to use 6968 /// the direct move instructions available in ISA 2.07 to avoid the 6969 /// need for load/store combinations. 6970 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 6971 SelectionDAG &DAG, 6972 const SDLoc &dl) const { 6973 assert((Op.getValueType() == MVT::f32 || 6974 Op.getValueType() == MVT::f64) && 6975 "Invalid floating point type as target of conversion"); 6976 assert(Subtarget.hasFPCVT() && 6977 "Int to FP conversions with direct moves require FPCVT"); 6978 SDValue FP; 6979 SDValue Src = Op.getOperand(0); 6980 bool SinglePrec = Op.getValueType() == MVT::f32; 6981 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 6982 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 6983 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 6984 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 6985 6986 if (WordInt) { 6987 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 6988 dl, MVT::f64, Src); 6989 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6990 } 6991 else { 6992 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 6993 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 6994 } 6995 6996 return FP; 6997 } 6998 6999 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7000 SelectionDAG &DAG) const { 7001 SDLoc dl(Op); 7002 7003 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7004 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7005 return SDValue(); 7006 7007 SDValue Value = Op.getOperand(0); 7008 // The values are now known to be -1 (false) or 1 (true). To convert this 7009 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7010 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7011 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7012 7013 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7014 7015 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7016 7017 if (Op.getValueType() != MVT::v4f64) 7018 Value = DAG.getNode(ISD::FP_ROUND, dl, 7019 Op.getValueType(), Value, 7020 DAG.getIntPtrConstant(1, dl)); 7021 return Value; 7022 } 7023 7024 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7025 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7026 return SDValue(); 7027 7028 if (Op.getOperand(0).getValueType() == MVT::i1) 7029 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7030 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7031 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7032 7033 // If we have direct moves, we can do all the conversion, skip the store/load 7034 // however, without FPCVT we can't do most conversions. 7035 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7036 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7037 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7038 7039 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7040 "UINT_TO_FP is supported only with FPCVT"); 7041 7042 // If we have FCFIDS, then use it when converting to single-precision. 7043 // Otherwise, convert to double-precision and then round. 7044 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7045 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7046 : PPCISD::FCFIDS) 7047 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7048 : PPCISD::FCFID); 7049 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7050 ? MVT::f32 7051 : MVT::f64; 7052 7053 if (Op.getOperand(0).getValueType() == MVT::i64) { 7054 SDValue SINT = Op.getOperand(0); 7055 // When converting to single-precision, we actually need to convert 7056 // to double-precision first and then round to single-precision. 7057 // To avoid double-rounding effects during that operation, we have 7058 // to prepare the input operand. Bits that might be truncated when 7059 // converting to double-precision are replaced by a bit that won't 7060 // be lost at this stage, but is below the single-precision rounding 7061 // position. 7062 // 7063 // However, if -enable-unsafe-fp-math is in effect, accept double 7064 // rounding to avoid the extra overhead. 7065 if (Op.getValueType() == MVT::f32 && 7066 !Subtarget.hasFPCVT() && 7067 !DAG.getTarget().Options.UnsafeFPMath) { 7068 7069 // Twiddle input to make sure the low 11 bits are zero. (If this 7070 // is the case, we are guaranteed the value will fit into the 53 bit 7071 // mantissa of an IEEE double-precision value without rounding.) 7072 // If any of those low 11 bits were not zero originally, make sure 7073 // bit 12 (value 2048) is set instead, so that the final rounding 7074 // to single-precision gets the correct result. 7075 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7076 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7077 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7078 Round, DAG.getConstant(2047, dl, MVT::i64)); 7079 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7080 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7081 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7082 7083 // However, we cannot use that value unconditionally: if the magnitude 7084 // of the input value is small, the bit-twiddling we did above might 7085 // end up visibly changing the output. Fortunately, in that case, we 7086 // don't need to twiddle bits since the original input will convert 7087 // exactly to double-precision floating-point already. Therefore, 7088 // construct a conditional to use the original value if the top 11 7089 // bits are all sign-bit copies, and use the rounded value computed 7090 // above otherwise. 7091 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7092 SINT, DAG.getConstant(53, dl, MVT::i32)); 7093 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7094 Cond, DAG.getConstant(1, dl, MVT::i64)); 7095 Cond = DAG.getSetCC(dl, MVT::i32, 7096 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7097 7098 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7099 } 7100 7101 ReuseLoadInfo RLI; 7102 SDValue Bits; 7103 7104 MachineFunction &MF = DAG.getMachineFunction(); 7105 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7106 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7107 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7108 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7109 } else if (Subtarget.hasLFIWAX() && 7110 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7111 MachineMemOperand *MMO = 7112 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7113 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7114 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7115 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7116 DAG.getVTList(MVT::f64, MVT::Other), 7117 Ops, MVT::i32, MMO); 7118 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7119 } else if (Subtarget.hasFPCVT() && 7120 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7121 MachineMemOperand *MMO = 7122 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7123 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7124 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7125 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7126 DAG.getVTList(MVT::f64, MVT::Other), 7127 Ops, MVT::i32, MMO); 7128 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7129 } else if (((Subtarget.hasLFIWAX() && 7130 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7131 (Subtarget.hasFPCVT() && 7132 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7133 SINT.getOperand(0).getValueType() == MVT::i32) { 7134 MachineFrameInfo &MFI = MF.getFrameInfo(); 7135 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7136 7137 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7138 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7139 7140 SDValue Store = 7141 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7142 MachinePointerInfo::getFixedStack( 7143 DAG.getMachineFunction(), FrameIdx)); 7144 7145 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7146 "Expected an i32 store"); 7147 7148 RLI.Ptr = FIdx; 7149 RLI.Chain = Store; 7150 RLI.MPI = 7151 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7152 RLI.Alignment = 4; 7153 7154 MachineMemOperand *MMO = 7155 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7156 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7157 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7158 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7159 PPCISD::LFIWZX : PPCISD::LFIWAX, 7160 dl, DAG.getVTList(MVT::f64, MVT::Other), 7161 Ops, MVT::i32, MMO); 7162 } else 7163 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7164 7165 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7166 7167 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7168 FP = DAG.getNode(ISD::FP_ROUND, dl, 7169 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7170 return FP; 7171 } 7172 7173 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7174 "Unhandled INT_TO_FP type in custom expander!"); 7175 // Since we only generate this in 64-bit mode, we can take advantage of 7176 // 64-bit registers. In particular, sign extend the input value into the 7177 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7178 // then lfd it and fcfid it. 7179 MachineFunction &MF = DAG.getMachineFunction(); 7180 MachineFrameInfo &MFI = MF.getFrameInfo(); 7181 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7182 7183 SDValue Ld; 7184 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7185 ReuseLoadInfo RLI; 7186 bool ReusingLoad; 7187 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7188 DAG))) { 7189 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7190 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7191 7192 SDValue Store = 7193 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7194 MachinePointerInfo::getFixedStack( 7195 DAG.getMachineFunction(), FrameIdx)); 7196 7197 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7198 "Expected an i32 store"); 7199 7200 RLI.Ptr = FIdx; 7201 RLI.Chain = Store; 7202 RLI.MPI = 7203 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7204 RLI.Alignment = 4; 7205 } 7206 7207 MachineMemOperand *MMO = 7208 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7209 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7210 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7211 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7212 PPCISD::LFIWZX : PPCISD::LFIWAX, 7213 dl, DAG.getVTList(MVT::f64, MVT::Other), 7214 Ops, MVT::i32, MMO); 7215 if (ReusingLoad) 7216 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7217 } else { 7218 assert(Subtarget.isPPC64() && 7219 "i32->FP without LFIWAX supported only on PPC64"); 7220 7221 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7222 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7223 7224 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7225 Op.getOperand(0)); 7226 7227 // STD the extended value into the stack slot. 7228 SDValue Store = DAG.getStore( 7229 DAG.getEntryNode(), dl, Ext64, FIdx, 7230 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7231 7232 // Load the value as a double. 7233 Ld = DAG.getLoad( 7234 MVT::f64, dl, Store, FIdx, 7235 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7236 } 7237 7238 // FCFID it and return it. 7239 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7240 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7241 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7242 DAG.getIntPtrConstant(0, dl)); 7243 return FP; 7244 } 7245 7246 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7247 SelectionDAG &DAG) const { 7248 SDLoc dl(Op); 7249 /* 7250 The rounding mode is in bits 30:31 of FPSR, and has the following 7251 settings: 7252 00 Round to nearest 7253 01 Round to 0 7254 10 Round to +inf 7255 11 Round to -inf 7256 7257 FLT_ROUNDS, on the other hand, expects the following: 7258 -1 Undefined 7259 0 Round to 0 7260 1 Round to nearest 7261 2 Round to +inf 7262 3 Round to -inf 7263 7264 To perform the conversion, we do: 7265 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7266 */ 7267 7268 MachineFunction &MF = DAG.getMachineFunction(); 7269 EVT VT = Op.getValueType(); 7270 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7271 7272 // Save FP Control Word to register 7273 EVT NodeTys[] = { 7274 MVT::f64, // return register 7275 MVT::Glue // unused in this context 7276 }; 7277 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7278 7279 // Save FP register to stack slot 7280 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7281 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7282 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7283 MachinePointerInfo()); 7284 7285 // Load FP Control Word from low 32 bits of stack slot. 7286 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7287 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7288 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7289 7290 // Transform as necessary 7291 SDValue CWD1 = 7292 DAG.getNode(ISD::AND, dl, MVT::i32, 7293 CWD, DAG.getConstant(3, dl, MVT::i32)); 7294 SDValue CWD2 = 7295 DAG.getNode(ISD::SRL, dl, MVT::i32, 7296 DAG.getNode(ISD::AND, dl, MVT::i32, 7297 DAG.getNode(ISD::XOR, dl, MVT::i32, 7298 CWD, DAG.getConstant(3, dl, MVT::i32)), 7299 DAG.getConstant(3, dl, MVT::i32)), 7300 DAG.getConstant(1, dl, MVT::i32)); 7301 7302 SDValue RetVal = 7303 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7304 7305 return DAG.getNode((VT.getSizeInBits() < 16 ? 7306 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7307 } 7308 7309 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7310 EVT VT = Op.getValueType(); 7311 unsigned BitWidth = VT.getSizeInBits(); 7312 SDLoc dl(Op); 7313 assert(Op.getNumOperands() == 3 && 7314 VT == Op.getOperand(1).getValueType() && 7315 "Unexpected SHL!"); 7316 7317 // Expand into a bunch of logical ops. Note that these ops 7318 // depend on the PPC behavior for oversized shift amounts. 7319 SDValue Lo = Op.getOperand(0); 7320 SDValue Hi = Op.getOperand(1); 7321 SDValue Amt = Op.getOperand(2); 7322 EVT AmtVT = Amt.getValueType(); 7323 7324 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7325 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7326 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7327 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7328 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7329 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7330 DAG.getConstant(-BitWidth, dl, AmtVT)); 7331 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7332 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7333 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7334 SDValue OutOps[] = { OutLo, OutHi }; 7335 return DAG.getMergeValues(OutOps, dl); 7336 } 7337 7338 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7339 EVT VT = Op.getValueType(); 7340 SDLoc dl(Op); 7341 unsigned BitWidth = VT.getSizeInBits(); 7342 assert(Op.getNumOperands() == 3 && 7343 VT == Op.getOperand(1).getValueType() && 7344 "Unexpected SRL!"); 7345 7346 // Expand into a bunch of logical ops. Note that these ops 7347 // depend on the PPC behavior for oversized shift amounts. 7348 SDValue Lo = Op.getOperand(0); 7349 SDValue Hi = Op.getOperand(1); 7350 SDValue Amt = Op.getOperand(2); 7351 EVT AmtVT = Amt.getValueType(); 7352 7353 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7354 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7355 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7356 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7357 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7358 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7359 DAG.getConstant(-BitWidth, dl, AmtVT)); 7360 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7361 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7362 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7363 SDValue OutOps[] = { OutLo, OutHi }; 7364 return DAG.getMergeValues(OutOps, dl); 7365 } 7366 7367 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7368 SDLoc dl(Op); 7369 EVT VT = Op.getValueType(); 7370 unsigned BitWidth = VT.getSizeInBits(); 7371 assert(Op.getNumOperands() == 3 && 7372 VT == Op.getOperand(1).getValueType() && 7373 "Unexpected SRA!"); 7374 7375 // Expand into a bunch of logical ops, followed by a select_cc. 7376 SDValue Lo = Op.getOperand(0); 7377 SDValue Hi = Op.getOperand(1); 7378 SDValue Amt = Op.getOperand(2); 7379 EVT AmtVT = Amt.getValueType(); 7380 7381 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7382 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7383 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7384 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7385 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7386 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7387 DAG.getConstant(-BitWidth, dl, AmtVT)); 7388 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 7389 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 7390 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 7391 Tmp4, Tmp6, ISD::SETLE); 7392 SDValue OutOps[] = { OutLo, OutHi }; 7393 return DAG.getMergeValues(OutOps, dl); 7394 } 7395 7396 //===----------------------------------------------------------------------===// 7397 // Vector related lowering. 7398 // 7399 7400 /// BuildSplatI - Build a canonical splati of Val with an element size of 7401 /// SplatSize. Cast the result to VT. 7402 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 7403 SelectionDAG &DAG, const SDLoc &dl) { 7404 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 7405 7406 static const MVT VTys[] = { // canonical VT to use for each size. 7407 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 7408 }; 7409 7410 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 7411 7412 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 7413 if (Val == -1) 7414 SplatSize = 1; 7415 7416 EVT CanonicalVT = VTys[SplatSize-1]; 7417 7418 // Build a canonical splat for this value. 7419 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 7420 } 7421 7422 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 7423 /// specified intrinsic ID. 7424 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 7425 const SDLoc &dl, EVT DestVT = MVT::Other) { 7426 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 7427 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7428 DAG.getConstant(IID, dl, MVT::i32), Op); 7429 } 7430 7431 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 7432 /// specified intrinsic ID. 7433 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 7434 SelectionDAG &DAG, const SDLoc &dl, 7435 EVT DestVT = MVT::Other) { 7436 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 7437 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7438 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 7439 } 7440 7441 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 7442 /// specified intrinsic ID. 7443 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 7444 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 7445 EVT DestVT = MVT::Other) { 7446 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 7447 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 7448 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 7449 } 7450 7451 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 7452 /// amount. The result has the specified value type. 7453 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 7454 SelectionDAG &DAG, const SDLoc &dl) { 7455 // Force LHS/RHS to be the right type. 7456 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 7457 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 7458 7459 int Ops[16]; 7460 for (unsigned i = 0; i != 16; ++i) 7461 Ops[i] = i + Amt; 7462 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 7463 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7464 } 7465 7466 /// Do we have an efficient pattern in a .td file for this node? 7467 /// 7468 /// \param V - pointer to the BuildVectorSDNode being matched 7469 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 7470 /// 7471 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 7472 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 7473 /// the opposite is true (expansion is beneficial) are: 7474 /// - The node builds a vector out of integers that are not 32 or 64-bits 7475 /// - The node builds a vector out of constants 7476 /// - The node is a "load-and-splat" 7477 /// In all other cases, we will choose to keep the BUILD_VECTOR. 7478 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 7479 bool HasDirectMove, 7480 bool HasP8Vector) { 7481 EVT VecVT = V->getValueType(0); 7482 bool RightType = VecVT == MVT::v2f64 || 7483 (HasP8Vector && VecVT == MVT::v4f32) || 7484 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 7485 if (!RightType) 7486 return false; 7487 7488 bool IsSplat = true; 7489 bool IsLoad = false; 7490 SDValue Op0 = V->getOperand(0); 7491 7492 // This function is called in a block that confirms the node is not a constant 7493 // splat. So a constant BUILD_VECTOR here means the vector is built out of 7494 // different constants. 7495 if (V->isConstant()) 7496 return false; 7497 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 7498 if (V->getOperand(i).isUndef()) 7499 return false; 7500 // We want to expand nodes that represent load-and-splat even if the 7501 // loaded value is a floating point truncation or conversion to int. 7502 if (V->getOperand(i).getOpcode() == ISD::LOAD || 7503 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 7504 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7505 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 7506 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 7507 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 7508 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 7509 IsLoad = true; 7510 // If the operands are different or the input is not a load and has more 7511 // uses than just this BV node, then it isn't a splat. 7512 if (V->getOperand(i) != Op0 || 7513 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 7514 IsSplat = false; 7515 } 7516 return !(IsSplat && IsLoad); 7517 } 7518 7519 // If this is a case we can't handle, return null and let the default 7520 // expansion code take care of it. If we CAN select this case, and if it 7521 // selects to a single instruction, return Op. Otherwise, if we can codegen 7522 // this case more efficiently than a constant pool load, lower it to the 7523 // sequence of ops that should be used. 7524 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 7525 SelectionDAG &DAG) const { 7526 SDLoc dl(Op); 7527 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7528 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 7529 7530 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 7531 // We first build an i32 vector, load it into a QPX register, 7532 // then convert it to a floating-point vector and compare it 7533 // to a zero vector to get the boolean result. 7534 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 7535 int FrameIdx = MFI.CreateStackObject(16, 16, false); 7536 MachinePointerInfo PtrInfo = 7537 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7538 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7539 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7540 7541 assert(BVN->getNumOperands() == 4 && 7542 "BUILD_VECTOR for v4i1 does not have 4 operands"); 7543 7544 bool IsConst = true; 7545 for (unsigned i = 0; i < 4; ++i) { 7546 if (BVN->getOperand(i).isUndef()) continue; 7547 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 7548 IsConst = false; 7549 break; 7550 } 7551 } 7552 7553 if (IsConst) { 7554 Constant *One = 7555 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 7556 Constant *NegOne = 7557 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 7558 7559 Constant *CV[4]; 7560 for (unsigned i = 0; i < 4; ++i) { 7561 if (BVN->getOperand(i).isUndef()) 7562 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 7563 else if (isNullConstant(BVN->getOperand(i))) 7564 CV[i] = NegOne; 7565 else 7566 CV[i] = One; 7567 } 7568 7569 Constant *CP = ConstantVector::get(CV); 7570 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 7571 16 /* alignment */); 7572 7573 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 7574 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 7575 return DAG.getMemIntrinsicNode( 7576 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 7577 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 7578 } 7579 7580 SmallVector<SDValue, 4> Stores; 7581 for (unsigned i = 0; i < 4; ++i) { 7582 if (BVN->getOperand(i).isUndef()) continue; 7583 7584 unsigned Offset = 4*i; 7585 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 7586 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 7587 7588 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 7589 if (StoreSize > 4) { 7590 Stores.push_back( 7591 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 7592 PtrInfo.getWithOffset(Offset), MVT::i32)); 7593 } else { 7594 SDValue StoreValue = BVN->getOperand(i); 7595 if (StoreSize < 4) 7596 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 7597 7598 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 7599 PtrInfo.getWithOffset(Offset))); 7600 } 7601 } 7602 7603 SDValue StoreChain; 7604 if (!Stores.empty()) 7605 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 7606 else 7607 StoreChain = DAG.getEntryNode(); 7608 7609 // Now load from v4i32 into the QPX register; this will extend it to 7610 // v4i64 but not yet convert it to a floating point. Nevertheless, this 7611 // is typed as v4f64 because the QPX register integer states are not 7612 // explicitly represented. 7613 7614 SDValue Ops[] = {StoreChain, 7615 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 7616 FIdx}; 7617 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 7618 7619 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 7620 dl, VTs, Ops, MVT::v4i32, PtrInfo); 7621 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 7622 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 7623 LoadedVect); 7624 7625 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 7626 7627 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 7628 } 7629 7630 // All other QPX vectors are handled by generic code. 7631 if (Subtarget.hasQPX()) 7632 return SDValue(); 7633 7634 // Check if this is a splat of a constant value. 7635 APInt APSplatBits, APSplatUndef; 7636 unsigned SplatBitSize; 7637 bool HasAnyUndefs; 7638 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 7639 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 7640 SplatBitSize > 32) { 7641 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 7642 // lowered to VSX instructions under certain conditions. 7643 // Without VSX, there is no pattern more efficient than expanding the node. 7644 if (Subtarget.hasVSX() && 7645 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 7646 Subtarget.hasP8Vector())) 7647 return Op; 7648 return SDValue(); 7649 } 7650 7651 unsigned SplatBits = APSplatBits.getZExtValue(); 7652 unsigned SplatUndef = APSplatUndef.getZExtValue(); 7653 unsigned SplatSize = SplatBitSize / 8; 7654 7655 // First, handle single instruction cases. 7656 7657 // All zeros? 7658 if (SplatBits == 0) { 7659 // Canonicalize all zero vectors to be v4i32. 7660 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 7661 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 7662 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 7663 } 7664 return Op; 7665 } 7666 7667 // We have XXSPLTIB for constant splats one byte wide 7668 if (Subtarget.hasP9Vector() && SplatSize == 1) { 7669 // This is a splat of 1-byte elements with some elements potentially undef. 7670 // Rather than trying to match undef in the SDAG patterns, ensure that all 7671 // elements are the same constant. 7672 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 7673 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 7674 dl, MVT::i32)); 7675 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 7676 if (Op.getValueType() != MVT::v16i8) 7677 return DAG.getBitcast(Op.getValueType(), NewBV); 7678 return NewBV; 7679 } 7680 7681 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 7682 // detect that constant splats like v8i16: 0xABAB are really just splats 7683 // of a 1-byte constant. In this case, we need to convert the node to a 7684 // splat of v16i8 and a bitcast. 7685 if (Op.getValueType() != MVT::v16i8) 7686 return DAG.getBitcast(Op.getValueType(), 7687 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 7688 7689 return Op; 7690 } 7691 7692 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 7693 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 7694 (32-SplatBitSize)); 7695 if (SextVal >= -16 && SextVal <= 15) 7696 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 7697 7698 // Two instruction sequences. 7699 7700 // If this value is in the range [-32,30] and is even, use: 7701 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 7702 // If this value is in the range [17,31] and is odd, use: 7703 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 7704 // If this value is in the range [-31,-17] and is odd, use: 7705 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 7706 // Note the last two are three-instruction sequences. 7707 if (SextVal >= -32 && SextVal <= 31) { 7708 // To avoid having these optimizations undone by constant folding, 7709 // we convert to a pseudo that will be expanded later into one of 7710 // the above forms. 7711 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 7712 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 7713 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 7714 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 7715 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 7716 if (VT == Op.getValueType()) 7717 return RetVal; 7718 else 7719 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 7720 } 7721 7722 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 7723 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 7724 // for fneg/fabs. 7725 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 7726 // Make -1 and vspltisw -1: 7727 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 7728 7729 // Make the VSLW intrinsic, computing 0x8000_0000. 7730 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 7731 OnesV, DAG, dl); 7732 7733 // xor by OnesV to invert it. 7734 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 7735 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7736 } 7737 7738 // Check to see if this is a wide variety of vsplti*, binop self cases. 7739 static const signed char SplatCsts[] = { 7740 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 7741 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 7742 }; 7743 7744 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 7745 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 7746 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 7747 int i = SplatCsts[idx]; 7748 7749 // Figure out what shift amount will be used by altivec if shifted by i in 7750 // this splat size. 7751 unsigned TypeShiftAmt = i & (SplatBitSize-1); 7752 7753 // vsplti + shl self. 7754 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 7755 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7756 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7757 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 7758 Intrinsic::ppc_altivec_vslw 7759 }; 7760 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7761 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7762 } 7763 7764 // vsplti + srl self. 7765 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7766 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7767 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7768 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 7769 Intrinsic::ppc_altivec_vsrw 7770 }; 7771 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7772 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7773 } 7774 7775 // vsplti + sra self. 7776 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 7777 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7778 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7779 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 7780 Intrinsic::ppc_altivec_vsraw 7781 }; 7782 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7783 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7784 } 7785 7786 // vsplti + rol self. 7787 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 7788 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 7789 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 7790 static const unsigned IIDs[] = { // Intrinsic to use for each size. 7791 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 7792 Intrinsic::ppc_altivec_vrlw 7793 }; 7794 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 7795 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 7796 } 7797 7798 // t = vsplti c, result = vsldoi t, t, 1 7799 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 7800 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7801 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 7802 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7803 } 7804 // t = vsplti c, result = vsldoi t, t, 2 7805 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 7806 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7807 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 7808 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7809 } 7810 // t = vsplti c, result = vsldoi t, t, 3 7811 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 7812 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 7813 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 7814 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 7815 } 7816 } 7817 7818 return SDValue(); 7819 } 7820 7821 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7822 /// the specified operations to build the shuffle. 7823 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7824 SDValue RHS, SelectionDAG &DAG, 7825 const SDLoc &dl) { 7826 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7827 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 7828 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 7829 7830 enum { 7831 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7832 OP_VMRGHW, 7833 OP_VMRGLW, 7834 OP_VSPLTISW0, 7835 OP_VSPLTISW1, 7836 OP_VSPLTISW2, 7837 OP_VSPLTISW3, 7838 OP_VSLDOI4, 7839 OP_VSLDOI8, 7840 OP_VSLDOI12 7841 }; 7842 7843 if (OpNum == OP_COPY) { 7844 if (LHSID == (1*9+2)*9+3) return LHS; 7845 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 7846 return RHS; 7847 } 7848 7849 SDValue OpLHS, OpRHS; 7850 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7851 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7852 7853 int ShufIdxs[16]; 7854 switch (OpNum) { 7855 default: llvm_unreachable("Unknown i32 permute!"); 7856 case OP_VMRGHW: 7857 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 7858 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 7859 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 7860 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 7861 break; 7862 case OP_VMRGLW: 7863 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 7864 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 7865 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 7866 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 7867 break; 7868 case OP_VSPLTISW0: 7869 for (unsigned i = 0; i != 16; ++i) 7870 ShufIdxs[i] = (i&3)+0; 7871 break; 7872 case OP_VSPLTISW1: 7873 for (unsigned i = 0; i != 16; ++i) 7874 ShufIdxs[i] = (i&3)+4; 7875 break; 7876 case OP_VSPLTISW2: 7877 for (unsigned i = 0; i != 16; ++i) 7878 ShufIdxs[i] = (i&3)+8; 7879 break; 7880 case OP_VSPLTISW3: 7881 for (unsigned i = 0; i != 16; ++i) 7882 ShufIdxs[i] = (i&3)+12; 7883 break; 7884 case OP_VSLDOI4: 7885 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 7886 case OP_VSLDOI8: 7887 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 7888 case OP_VSLDOI12: 7889 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 7890 } 7891 EVT VT = OpLHS.getValueType(); 7892 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 7893 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 7894 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 7895 return DAG.getNode(ISD::BITCAST, dl, VT, T); 7896 } 7897 7898 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 7899 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 7900 /// SDValue. 7901 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 7902 SelectionDAG &DAG) const { 7903 const unsigned BytesInVector = 16; 7904 bool IsLE = Subtarget.isLittleEndian(); 7905 SDLoc dl(N); 7906 SDValue V1 = N->getOperand(0); 7907 SDValue V2 = N->getOperand(1); 7908 unsigned ShiftElts = 0, InsertAtByte = 0; 7909 bool Swap = false; 7910 7911 // Shifts required to get the byte we want at element 7. 7912 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 7913 0, 15, 14, 13, 12, 11, 10, 9}; 7914 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 7915 1, 2, 3, 4, 5, 6, 7, 8}; 7916 7917 ArrayRef<int> Mask = N->getMask(); 7918 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 7919 7920 // For each mask element, find out if we're just inserting something 7921 // from V2 into V1 or vice versa. 7922 // Possible permutations inserting an element from V2 into V1: 7923 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 7924 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 7925 // ... 7926 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 7927 // Inserting from V1 into V2 will be similar, except mask range will be 7928 // [16,31]. 7929 7930 bool FoundCandidate = false; 7931 // If both vector operands for the shuffle are the same vector, the mask 7932 // will contain only elements from the first one and the second one will be 7933 // undef. 7934 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 7935 // Go through the mask of half-words to find an element that's being moved 7936 // from one vector to the other. 7937 for (unsigned i = 0; i < BytesInVector; ++i) { 7938 unsigned CurrentElement = Mask[i]; 7939 // If 2nd operand is undefined, we should only look for element 7 in the 7940 // Mask. 7941 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 7942 continue; 7943 7944 bool OtherElementsInOrder = true; 7945 // Examine the other elements in the Mask to see if they're in original 7946 // order. 7947 for (unsigned j = 0; j < BytesInVector; ++j) { 7948 if (j == i) 7949 continue; 7950 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 7951 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 7952 // in which we always assume we're always picking from the 1st operand. 7953 int MaskOffset = 7954 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 7955 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 7956 OtherElementsInOrder = false; 7957 break; 7958 } 7959 } 7960 // If other elements are in original order, we record the number of shifts 7961 // we need to get the element we want into element 7. Also record which byte 7962 // in the vector we should insert into. 7963 if (OtherElementsInOrder) { 7964 // If 2nd operand is undefined, we assume no shifts and no swapping. 7965 if (V2.isUndef()) { 7966 ShiftElts = 0; 7967 Swap = false; 7968 } else { 7969 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 7970 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 7971 : BigEndianShifts[CurrentElement & 0xF]; 7972 Swap = CurrentElement < BytesInVector; 7973 } 7974 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 7975 FoundCandidate = true; 7976 break; 7977 } 7978 } 7979 7980 if (!FoundCandidate) 7981 return SDValue(); 7982 7983 // Candidate found, construct the proper SDAG sequence with VINSERTB, 7984 // optionally with VECSHL if shift is required. 7985 if (Swap) 7986 std::swap(V1, V2); 7987 if (V2.isUndef()) 7988 V2 = V1; 7989 if (ShiftElts) { 7990 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 7991 DAG.getConstant(ShiftElts, dl, MVT::i32)); 7992 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 7993 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7994 } 7995 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 7996 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 7997 } 7998 7999 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8000 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8001 /// SDValue. 8002 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8003 SelectionDAG &DAG) const { 8004 const unsigned NumHalfWords = 8; 8005 const unsigned BytesInVector = NumHalfWords * 2; 8006 // Check that the shuffle is on half-words. 8007 if (!isNByteElemShuffleMask(N, 2, 1)) 8008 return SDValue(); 8009 8010 bool IsLE = Subtarget.isLittleEndian(); 8011 SDLoc dl(N); 8012 SDValue V1 = N->getOperand(0); 8013 SDValue V2 = N->getOperand(1); 8014 unsigned ShiftElts = 0, InsertAtByte = 0; 8015 bool Swap = false; 8016 8017 // Shifts required to get the half-word we want at element 3. 8018 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8019 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8020 8021 uint32_t Mask = 0; 8022 uint32_t OriginalOrderLow = 0x1234567; 8023 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8024 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8025 // 32-bit space, only need 4-bit nibbles per element. 8026 for (unsigned i = 0; i < NumHalfWords; ++i) { 8027 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8028 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8029 } 8030 8031 // For each mask element, find out if we're just inserting something 8032 // from V2 into V1 or vice versa. Possible permutations inserting an element 8033 // from V2 into V1: 8034 // X, 1, 2, 3, 4, 5, 6, 7 8035 // 0, X, 2, 3, 4, 5, 6, 7 8036 // 0, 1, X, 3, 4, 5, 6, 7 8037 // 0, 1, 2, X, 4, 5, 6, 7 8038 // 0, 1, 2, 3, X, 5, 6, 7 8039 // 0, 1, 2, 3, 4, X, 6, 7 8040 // 0, 1, 2, 3, 4, 5, X, 7 8041 // 0, 1, 2, 3, 4, 5, 6, X 8042 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8043 8044 bool FoundCandidate = false; 8045 // Go through the mask of half-words to find an element that's being moved 8046 // from one vector to the other. 8047 for (unsigned i = 0; i < NumHalfWords; ++i) { 8048 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8049 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8050 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8051 uint32_t TargetOrder = 0x0; 8052 8053 // If both vector operands for the shuffle are the same vector, the mask 8054 // will contain only elements from the first one and the second one will be 8055 // undef. 8056 if (V2.isUndef()) { 8057 ShiftElts = 0; 8058 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8059 TargetOrder = OriginalOrderLow; 8060 Swap = false; 8061 // Skip if not the correct element or mask of other elements don't equal 8062 // to our expected order. 8063 if (MaskOneElt == VINSERTHSrcElem && 8064 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8065 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8066 FoundCandidate = true; 8067 break; 8068 } 8069 } else { // If both operands are defined. 8070 // Target order is [8,15] if the current mask is between [0,7]. 8071 TargetOrder = 8072 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8073 // Skip if mask of other elements don't equal our expected order. 8074 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8075 // We only need the last 3 bits for the number of shifts. 8076 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8077 : BigEndianShifts[MaskOneElt & 0x7]; 8078 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8079 Swap = MaskOneElt < NumHalfWords; 8080 FoundCandidate = true; 8081 break; 8082 } 8083 } 8084 } 8085 8086 if (!FoundCandidate) 8087 return SDValue(); 8088 8089 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8090 // optionally with VECSHL if shift is required. 8091 if (Swap) 8092 std::swap(V1, V2); 8093 if (V2.isUndef()) 8094 V2 = V1; 8095 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8096 if (ShiftElts) { 8097 // Double ShiftElts because we're left shifting on v16i8 type. 8098 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8099 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8100 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8101 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8102 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8103 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8104 } 8105 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8106 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8107 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8108 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8109 } 8110 8111 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8112 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8113 /// return the code it can be lowered into. Worst case, it can always be 8114 /// lowered into a vperm. 8115 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8116 SelectionDAG &DAG) const { 8117 SDLoc dl(Op); 8118 SDValue V1 = Op.getOperand(0); 8119 SDValue V2 = Op.getOperand(1); 8120 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8121 EVT VT = Op.getValueType(); 8122 bool isLittleEndian = Subtarget.isLittleEndian(); 8123 8124 unsigned ShiftElts, InsertAtByte; 8125 bool Swap = false; 8126 if (Subtarget.hasP9Vector() && 8127 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8128 isLittleEndian)) { 8129 if (Swap) 8130 std::swap(V1, V2); 8131 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8132 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8133 if (ShiftElts) { 8134 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8135 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8136 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8137 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8138 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8139 } 8140 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8141 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8142 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8143 } 8144 8145 if (Subtarget.hasP9Altivec()) { 8146 SDValue NewISDNode; 8147 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8148 return NewISDNode; 8149 8150 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8151 return NewISDNode; 8152 } 8153 8154 if (Subtarget.hasVSX() && 8155 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8156 if (Swap) 8157 std::swap(V1, V2); 8158 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8159 SDValue Conv2 = 8160 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8161 8162 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8163 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8164 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8165 } 8166 8167 if (Subtarget.hasVSX() && 8168 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8169 if (Swap) 8170 std::swap(V1, V2); 8171 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8172 SDValue Conv2 = 8173 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8174 8175 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8176 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8177 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8178 } 8179 8180 if (Subtarget.hasP9Vector()) { 8181 if (PPC::isXXBRHShuffleMask(SVOp)) { 8182 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8183 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8184 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8185 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8186 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8187 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8188 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8189 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8190 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8191 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8192 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8193 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8194 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8195 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8196 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8197 } 8198 } 8199 8200 if (Subtarget.hasVSX()) { 8201 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8202 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8203 8204 // If the source for the shuffle is a scalar_to_vector that came from a 8205 // 32-bit load, it will have used LXVWSX so we don't need to splat again. 8206 if (Subtarget.hasP9Vector() && 8207 ((isLittleEndian && SplatIdx == 3) || 8208 (!isLittleEndian && SplatIdx == 0))) { 8209 SDValue Src = V1.getOperand(0); 8210 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR && 8211 Src.getOperand(0).getOpcode() == ISD::LOAD && 8212 Src.getOperand(0).hasOneUse()) 8213 return V1; 8214 } 8215 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8216 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8217 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8218 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8219 } 8220 8221 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8222 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8223 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8224 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8225 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8226 } 8227 } 8228 8229 if (Subtarget.hasQPX()) { 8230 if (VT.getVectorNumElements() != 4) 8231 return SDValue(); 8232 8233 if (V2.isUndef()) V2 = V1; 8234 8235 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8236 if (AlignIdx != -1) { 8237 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8238 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8239 } else if (SVOp->isSplat()) { 8240 int SplatIdx = SVOp->getSplatIndex(); 8241 if (SplatIdx >= 4) { 8242 std::swap(V1, V2); 8243 SplatIdx -= 4; 8244 } 8245 8246 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8247 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8248 } 8249 8250 // Lower this into a qvgpci/qvfperm pair. 8251 8252 // Compute the qvgpci literal 8253 unsigned idx = 0; 8254 for (unsigned i = 0; i < 4; ++i) { 8255 int m = SVOp->getMaskElt(i); 8256 unsigned mm = m >= 0 ? (unsigned) m : i; 8257 idx |= mm << (3-i)*3; 8258 } 8259 8260 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8261 DAG.getConstant(idx, dl, MVT::i32)); 8262 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8263 } 8264 8265 // Cases that are handled by instructions that take permute immediates 8266 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8267 // selected by the instruction selector. 8268 if (V2.isUndef()) { 8269 if (PPC::isSplatShuffleMask(SVOp, 1) || 8270 PPC::isSplatShuffleMask(SVOp, 2) || 8271 PPC::isSplatShuffleMask(SVOp, 4) || 8272 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8273 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8274 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8275 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8276 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8277 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8278 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8279 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8280 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8281 (Subtarget.hasP8Altivec() && ( 8282 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8283 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8284 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8285 return Op; 8286 } 8287 } 8288 8289 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8290 // and produce a fixed permutation. If any of these match, do not lower to 8291 // VPERM. 8292 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8293 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8294 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8295 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8296 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8297 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8298 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8299 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8300 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8301 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8302 (Subtarget.hasP8Altivec() && ( 8303 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8304 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8305 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8306 return Op; 8307 8308 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8309 // perfect shuffle table to emit an optimal matching sequence. 8310 ArrayRef<int> PermMask = SVOp->getMask(); 8311 8312 unsigned PFIndexes[4]; 8313 bool isFourElementShuffle = true; 8314 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8315 unsigned EltNo = 8; // Start out undef. 8316 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8317 if (PermMask[i*4+j] < 0) 8318 continue; // Undef, ignore it. 8319 8320 unsigned ByteSource = PermMask[i*4+j]; 8321 if ((ByteSource & 3) != j) { 8322 isFourElementShuffle = false; 8323 break; 8324 } 8325 8326 if (EltNo == 8) { 8327 EltNo = ByteSource/4; 8328 } else if (EltNo != ByteSource/4) { 8329 isFourElementShuffle = false; 8330 break; 8331 } 8332 } 8333 PFIndexes[i] = EltNo; 8334 } 8335 8336 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8337 // perfect shuffle vector to determine if it is cost effective to do this as 8338 // discrete instructions, or whether we should use a vperm. 8339 // For now, we skip this for little endian until such time as we have a 8340 // little-endian perfect shuffle table. 8341 if (isFourElementShuffle && !isLittleEndian) { 8342 // Compute the index in the perfect shuffle table. 8343 unsigned PFTableIndex = 8344 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8345 8346 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8347 unsigned Cost = (PFEntry >> 30); 8348 8349 // Determining when to avoid vperm is tricky. Many things affect the cost 8350 // of vperm, particularly how many times the perm mask needs to be computed. 8351 // For example, if the perm mask can be hoisted out of a loop or is already 8352 // used (perhaps because there are multiple permutes with the same shuffle 8353 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8354 // the loop requires an extra register. 8355 // 8356 // As a compromise, we only emit discrete instructions if the shuffle can be 8357 // generated in 3 or fewer operations. When we have loop information 8358 // available, if this block is within a loop, we should avoid using vperm 8359 // for 3-operation perms and use a constant pool load instead. 8360 if (Cost < 3) 8361 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8362 } 8363 8364 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8365 // vector that will get spilled to the constant pool. 8366 if (V2.isUndef()) V2 = V1; 8367 8368 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8369 // that it is in input element units, not in bytes. Convert now. 8370 8371 // For little endian, the order of the input vectors is reversed, and 8372 // the permutation mask is complemented with respect to 31. This is 8373 // necessary to produce proper semantics with the big-endian-biased vperm 8374 // instruction. 8375 EVT EltVT = V1.getValueType().getVectorElementType(); 8376 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 8377 8378 SmallVector<SDValue, 16> ResultMask; 8379 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 8380 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 8381 8382 for (unsigned j = 0; j != BytesPerElement; ++j) 8383 if (isLittleEndian) 8384 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 8385 dl, MVT::i32)); 8386 else 8387 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 8388 MVT::i32)); 8389 } 8390 8391 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 8392 if (isLittleEndian) 8393 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8394 V2, V1, VPermMask); 8395 else 8396 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 8397 V1, V2, VPermMask); 8398 } 8399 8400 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 8401 /// vector comparison. If it is, return true and fill in Opc/isDot with 8402 /// information about the intrinsic. 8403 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 8404 bool &isDot, const PPCSubtarget &Subtarget) { 8405 unsigned IntrinsicID = 8406 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 8407 CompareOpc = -1; 8408 isDot = false; 8409 switch (IntrinsicID) { 8410 default: 8411 return false; 8412 // Comparison predicates. 8413 case Intrinsic::ppc_altivec_vcmpbfp_p: 8414 CompareOpc = 966; 8415 isDot = true; 8416 break; 8417 case Intrinsic::ppc_altivec_vcmpeqfp_p: 8418 CompareOpc = 198; 8419 isDot = true; 8420 break; 8421 case Intrinsic::ppc_altivec_vcmpequb_p: 8422 CompareOpc = 6; 8423 isDot = true; 8424 break; 8425 case Intrinsic::ppc_altivec_vcmpequh_p: 8426 CompareOpc = 70; 8427 isDot = true; 8428 break; 8429 case Intrinsic::ppc_altivec_vcmpequw_p: 8430 CompareOpc = 134; 8431 isDot = true; 8432 break; 8433 case Intrinsic::ppc_altivec_vcmpequd_p: 8434 if (Subtarget.hasP8Altivec()) { 8435 CompareOpc = 199; 8436 isDot = true; 8437 } else 8438 return false; 8439 break; 8440 case Intrinsic::ppc_altivec_vcmpneb_p: 8441 case Intrinsic::ppc_altivec_vcmpneh_p: 8442 case Intrinsic::ppc_altivec_vcmpnew_p: 8443 case Intrinsic::ppc_altivec_vcmpnezb_p: 8444 case Intrinsic::ppc_altivec_vcmpnezh_p: 8445 case Intrinsic::ppc_altivec_vcmpnezw_p: 8446 if (Subtarget.hasP9Altivec()) { 8447 switch (IntrinsicID) { 8448 default: 8449 llvm_unreachable("Unknown comparison intrinsic."); 8450 case Intrinsic::ppc_altivec_vcmpneb_p: 8451 CompareOpc = 7; 8452 break; 8453 case Intrinsic::ppc_altivec_vcmpneh_p: 8454 CompareOpc = 71; 8455 break; 8456 case Intrinsic::ppc_altivec_vcmpnew_p: 8457 CompareOpc = 135; 8458 break; 8459 case Intrinsic::ppc_altivec_vcmpnezb_p: 8460 CompareOpc = 263; 8461 break; 8462 case Intrinsic::ppc_altivec_vcmpnezh_p: 8463 CompareOpc = 327; 8464 break; 8465 case Intrinsic::ppc_altivec_vcmpnezw_p: 8466 CompareOpc = 391; 8467 break; 8468 } 8469 isDot = true; 8470 } else 8471 return false; 8472 break; 8473 case Intrinsic::ppc_altivec_vcmpgefp_p: 8474 CompareOpc = 454; 8475 isDot = true; 8476 break; 8477 case Intrinsic::ppc_altivec_vcmpgtfp_p: 8478 CompareOpc = 710; 8479 isDot = true; 8480 break; 8481 case Intrinsic::ppc_altivec_vcmpgtsb_p: 8482 CompareOpc = 774; 8483 isDot = true; 8484 break; 8485 case Intrinsic::ppc_altivec_vcmpgtsh_p: 8486 CompareOpc = 838; 8487 isDot = true; 8488 break; 8489 case Intrinsic::ppc_altivec_vcmpgtsw_p: 8490 CompareOpc = 902; 8491 isDot = true; 8492 break; 8493 case Intrinsic::ppc_altivec_vcmpgtsd_p: 8494 if (Subtarget.hasP8Altivec()) { 8495 CompareOpc = 967; 8496 isDot = true; 8497 } else 8498 return false; 8499 break; 8500 case Intrinsic::ppc_altivec_vcmpgtub_p: 8501 CompareOpc = 518; 8502 isDot = true; 8503 break; 8504 case Intrinsic::ppc_altivec_vcmpgtuh_p: 8505 CompareOpc = 582; 8506 isDot = true; 8507 break; 8508 case Intrinsic::ppc_altivec_vcmpgtuw_p: 8509 CompareOpc = 646; 8510 isDot = true; 8511 break; 8512 case Intrinsic::ppc_altivec_vcmpgtud_p: 8513 if (Subtarget.hasP8Altivec()) { 8514 CompareOpc = 711; 8515 isDot = true; 8516 } else 8517 return false; 8518 break; 8519 8520 // VSX predicate comparisons use the same infrastructure 8521 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8522 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8523 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8524 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8525 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8526 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8527 if (Subtarget.hasVSX()) { 8528 switch (IntrinsicID) { 8529 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 8530 CompareOpc = 99; 8531 break; 8532 case Intrinsic::ppc_vsx_xvcmpgedp_p: 8533 CompareOpc = 115; 8534 break; 8535 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 8536 CompareOpc = 107; 8537 break; 8538 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 8539 CompareOpc = 67; 8540 break; 8541 case Intrinsic::ppc_vsx_xvcmpgesp_p: 8542 CompareOpc = 83; 8543 break; 8544 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 8545 CompareOpc = 75; 8546 break; 8547 } 8548 isDot = true; 8549 } else 8550 return false; 8551 break; 8552 8553 // Normal Comparisons. 8554 case Intrinsic::ppc_altivec_vcmpbfp: 8555 CompareOpc = 966; 8556 break; 8557 case Intrinsic::ppc_altivec_vcmpeqfp: 8558 CompareOpc = 198; 8559 break; 8560 case Intrinsic::ppc_altivec_vcmpequb: 8561 CompareOpc = 6; 8562 break; 8563 case Intrinsic::ppc_altivec_vcmpequh: 8564 CompareOpc = 70; 8565 break; 8566 case Intrinsic::ppc_altivec_vcmpequw: 8567 CompareOpc = 134; 8568 break; 8569 case Intrinsic::ppc_altivec_vcmpequd: 8570 if (Subtarget.hasP8Altivec()) 8571 CompareOpc = 199; 8572 else 8573 return false; 8574 break; 8575 case Intrinsic::ppc_altivec_vcmpneb: 8576 case Intrinsic::ppc_altivec_vcmpneh: 8577 case Intrinsic::ppc_altivec_vcmpnew: 8578 case Intrinsic::ppc_altivec_vcmpnezb: 8579 case Intrinsic::ppc_altivec_vcmpnezh: 8580 case Intrinsic::ppc_altivec_vcmpnezw: 8581 if (Subtarget.hasP9Altivec()) 8582 switch (IntrinsicID) { 8583 default: 8584 llvm_unreachable("Unknown comparison intrinsic."); 8585 case Intrinsic::ppc_altivec_vcmpneb: 8586 CompareOpc = 7; 8587 break; 8588 case Intrinsic::ppc_altivec_vcmpneh: 8589 CompareOpc = 71; 8590 break; 8591 case Intrinsic::ppc_altivec_vcmpnew: 8592 CompareOpc = 135; 8593 break; 8594 case Intrinsic::ppc_altivec_vcmpnezb: 8595 CompareOpc = 263; 8596 break; 8597 case Intrinsic::ppc_altivec_vcmpnezh: 8598 CompareOpc = 327; 8599 break; 8600 case Intrinsic::ppc_altivec_vcmpnezw: 8601 CompareOpc = 391; 8602 break; 8603 } 8604 else 8605 return false; 8606 break; 8607 case Intrinsic::ppc_altivec_vcmpgefp: 8608 CompareOpc = 454; 8609 break; 8610 case Intrinsic::ppc_altivec_vcmpgtfp: 8611 CompareOpc = 710; 8612 break; 8613 case Intrinsic::ppc_altivec_vcmpgtsb: 8614 CompareOpc = 774; 8615 break; 8616 case Intrinsic::ppc_altivec_vcmpgtsh: 8617 CompareOpc = 838; 8618 break; 8619 case Intrinsic::ppc_altivec_vcmpgtsw: 8620 CompareOpc = 902; 8621 break; 8622 case Intrinsic::ppc_altivec_vcmpgtsd: 8623 if (Subtarget.hasP8Altivec()) 8624 CompareOpc = 967; 8625 else 8626 return false; 8627 break; 8628 case Intrinsic::ppc_altivec_vcmpgtub: 8629 CompareOpc = 518; 8630 break; 8631 case Intrinsic::ppc_altivec_vcmpgtuh: 8632 CompareOpc = 582; 8633 break; 8634 case Intrinsic::ppc_altivec_vcmpgtuw: 8635 CompareOpc = 646; 8636 break; 8637 case Intrinsic::ppc_altivec_vcmpgtud: 8638 if (Subtarget.hasP8Altivec()) 8639 CompareOpc = 711; 8640 else 8641 return false; 8642 break; 8643 } 8644 return true; 8645 } 8646 8647 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 8648 /// lower, do it, otherwise return null. 8649 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 8650 SelectionDAG &DAG) const { 8651 unsigned IntrinsicID = 8652 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8653 8654 SDLoc dl(Op); 8655 8656 if (IntrinsicID == Intrinsic::thread_pointer) { 8657 // Reads the thread pointer register, used for __builtin_thread_pointer. 8658 if (Subtarget.isPPC64()) 8659 return DAG.getRegister(PPC::X13, MVT::i64); 8660 return DAG.getRegister(PPC::R2, MVT::i32); 8661 } 8662 8663 // We are looking for absolute values here. 8664 // The idea is to try to fit one of two patterns: 8665 // max (a, (0-a)) OR max ((0-a), a) 8666 if (Subtarget.hasP9Vector() && 8667 (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw || 8668 IntrinsicID == Intrinsic::ppc_altivec_vmaxsh || 8669 IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) { 8670 SDValue V1 = Op.getOperand(1); 8671 SDValue V2 = Op.getOperand(2); 8672 if (V1.getSimpleValueType() == V2.getSimpleValueType() && 8673 (V1.getSimpleValueType() == MVT::v4i32 || 8674 V1.getSimpleValueType() == MVT::v8i16 || 8675 V1.getSimpleValueType() == MVT::v16i8)) { 8676 if ( V1.getOpcode() == ISD::SUB && 8677 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 8678 V1.getOperand(1) == V2 ) { 8679 // Generate the abs instruction with the operands 8680 return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2); 8681 } 8682 8683 if ( V2.getOpcode() == ISD::SUB && 8684 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 8685 V2.getOperand(1) == V1 ) { 8686 // Generate the abs instruction with the operands 8687 return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1); 8688 } 8689 } 8690 } 8691 8692 // If this is a lowered altivec predicate compare, CompareOpc is set to the 8693 // opcode number of the comparison. 8694 int CompareOpc; 8695 bool isDot; 8696 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 8697 return SDValue(); // Don't custom lower most intrinsics. 8698 8699 // If this is a non-dot comparison, make the VCMP node and we are done. 8700 if (!isDot) { 8701 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 8702 Op.getOperand(1), Op.getOperand(2), 8703 DAG.getConstant(CompareOpc, dl, MVT::i32)); 8704 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 8705 } 8706 8707 // Create the PPCISD altivec 'dot' comparison node. 8708 SDValue Ops[] = { 8709 Op.getOperand(2), // LHS 8710 Op.getOperand(3), // RHS 8711 DAG.getConstant(CompareOpc, dl, MVT::i32) 8712 }; 8713 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 8714 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 8715 8716 // Now that we have the comparison, emit a copy from the CR to a GPR. 8717 // This is flagged to the above dot comparison. 8718 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 8719 DAG.getRegister(PPC::CR6, MVT::i32), 8720 CompNode.getValue(1)); 8721 8722 // Unpack the result based on how the target uses it. 8723 unsigned BitNo; // Bit # of CR6. 8724 bool InvertBit; // Invert result? 8725 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 8726 default: // Can't happen, don't crash on invalid number though. 8727 case 0: // Return the value of the EQ bit of CR6. 8728 BitNo = 0; InvertBit = false; 8729 break; 8730 case 1: // Return the inverted value of the EQ bit of CR6. 8731 BitNo = 0; InvertBit = true; 8732 break; 8733 case 2: // Return the value of the LT bit of CR6. 8734 BitNo = 2; InvertBit = false; 8735 break; 8736 case 3: // Return the inverted value of the LT bit of CR6. 8737 BitNo = 2; InvertBit = true; 8738 break; 8739 } 8740 8741 // Shift the bit into the low position. 8742 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 8743 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 8744 // Isolate the bit. 8745 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 8746 DAG.getConstant(1, dl, MVT::i32)); 8747 8748 // If we are supposed to, toggle the bit. 8749 if (InvertBit) 8750 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 8751 DAG.getConstant(1, dl, MVT::i32)); 8752 return Flags; 8753 } 8754 8755 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 8756 SelectionDAG &DAG) const { 8757 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 8758 // the beginning of the argument list. 8759 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 8760 SDLoc DL(Op); 8761 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 8762 case Intrinsic::ppc_cfence: { 8763 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 8764 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 8765 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 8766 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 8767 Op.getOperand(ArgStart + 1)), 8768 Op.getOperand(0)), 8769 0); 8770 } 8771 default: 8772 break; 8773 } 8774 return SDValue(); 8775 } 8776 8777 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 8778 // Check for a DIV with the same operands as this REM. 8779 for (auto UI : Op.getOperand(1)->uses()) { 8780 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 8781 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 8782 if (UI->getOperand(0) == Op.getOperand(0) && 8783 UI->getOperand(1) == Op.getOperand(1)) 8784 return SDValue(); 8785 } 8786 return Op; 8787 } 8788 8789 // Lower scalar BSWAP64 to xxbrd. 8790 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 8791 SDLoc dl(Op); 8792 // MTVSRDD 8793 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 8794 Op.getOperand(0)); 8795 // XXBRD 8796 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 8797 // MFVSRD 8798 int VectorIndex = 0; 8799 if (Subtarget.isLittleEndian()) 8800 VectorIndex = 1; 8801 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 8802 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 8803 return Op; 8804 } 8805 8806 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 8807 SelectionDAG &DAG) const { 8808 SDLoc dl(Op); 8809 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int 8810 // instructions), but for smaller types, we need to first extend up to v2i32 8811 // before doing going farther. 8812 if (Op.getValueType() == MVT::v2i64) { 8813 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 8814 if (ExtVT != MVT::v2i32) { 8815 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); 8816 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, 8817 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), 8818 ExtVT.getVectorElementType(), 4))); 8819 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); 8820 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, 8821 DAG.getValueType(MVT::v2i32)); 8822 } 8823 8824 return Op; 8825 } 8826 8827 return SDValue(); 8828 } 8829 8830 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 8831 SelectionDAG &DAG) const { 8832 SDLoc dl(Op); 8833 // Create a stack slot that is 16-byte aligned. 8834 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8835 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8836 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8837 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8838 8839 // Store the input value into Value#0 of the stack slot. 8840 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8841 MachinePointerInfo()); 8842 // Load it out. 8843 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 8844 } 8845 8846 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8847 SelectionDAG &DAG) const { 8848 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 8849 "Should only be called for ISD::INSERT_VECTOR_ELT"); 8850 8851 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8852 // We have legal lowering for constant indices but not for variable ones. 8853 if (!C) 8854 return SDValue(); 8855 8856 EVT VT = Op.getValueType(); 8857 SDLoc dl(Op); 8858 SDValue V1 = Op.getOperand(0); 8859 SDValue V2 = Op.getOperand(1); 8860 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 8861 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 8862 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 8863 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 8864 unsigned InsertAtElement = C->getZExtValue(); 8865 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 8866 if (Subtarget.isLittleEndian()) { 8867 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 8868 } 8869 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 8870 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8871 } 8872 return Op; 8873 } 8874 8875 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8876 SelectionDAG &DAG) const { 8877 SDLoc dl(Op); 8878 SDNode *N = Op.getNode(); 8879 8880 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 8881 "Unknown extract_vector_elt type"); 8882 8883 SDValue Value = N->getOperand(0); 8884 8885 // The first part of this is like the store lowering except that we don't 8886 // need to track the chain. 8887 8888 // The values are now known to be -1 (false) or 1 (true). To convert this 8889 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8890 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8891 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8892 8893 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 8894 // understand how to form the extending load. 8895 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8896 8897 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8898 8899 // Now convert to an integer and store. 8900 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8901 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 8902 Value); 8903 8904 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8905 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8906 MachinePointerInfo PtrInfo = 8907 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8908 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8909 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8910 8911 SDValue StoreChain = DAG.getEntryNode(); 8912 SDValue Ops[] = {StoreChain, 8913 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 8914 Value, FIdx}; 8915 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 8916 8917 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 8918 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8919 8920 // Extract the value requested. 8921 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 8922 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8923 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8924 8925 SDValue IntVal = 8926 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 8927 8928 if (!Subtarget.useCRBits()) 8929 return IntVal; 8930 8931 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 8932 } 8933 8934 /// Lowering for QPX v4i1 loads 8935 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 8936 SelectionDAG &DAG) const { 8937 SDLoc dl(Op); 8938 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 8939 SDValue LoadChain = LN->getChain(); 8940 SDValue BasePtr = LN->getBasePtr(); 8941 8942 if (Op.getValueType() == MVT::v4f64 || 8943 Op.getValueType() == MVT::v4f32) { 8944 EVT MemVT = LN->getMemoryVT(); 8945 unsigned Alignment = LN->getAlignment(); 8946 8947 // If this load is properly aligned, then it is legal. 8948 if (Alignment >= MemVT.getStoreSize()) 8949 return Op; 8950 8951 EVT ScalarVT = Op.getValueType().getScalarType(), 8952 ScalarMemVT = MemVT.getScalarType(); 8953 unsigned Stride = ScalarMemVT.getStoreSize(); 8954 8955 SDValue Vals[4], LoadChains[4]; 8956 for (unsigned Idx = 0; Idx < 4; ++Idx) { 8957 SDValue Load; 8958 if (ScalarVT != ScalarMemVT) 8959 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 8960 BasePtr, 8961 LN->getPointerInfo().getWithOffset(Idx * Stride), 8962 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 8963 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8964 else 8965 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 8966 LN->getPointerInfo().getWithOffset(Idx * Stride), 8967 MinAlign(Alignment, Idx * Stride), 8968 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 8969 8970 if (Idx == 0 && LN->isIndexed()) { 8971 assert(LN->getAddressingMode() == ISD::PRE_INC && 8972 "Unknown addressing mode on vector load"); 8973 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 8974 LN->getAddressingMode()); 8975 } 8976 8977 Vals[Idx] = Load; 8978 LoadChains[Idx] = Load.getValue(1); 8979 8980 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 8981 DAG.getConstant(Stride, dl, 8982 BasePtr.getValueType())); 8983 } 8984 8985 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 8986 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 8987 8988 if (LN->isIndexed()) { 8989 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 8990 return DAG.getMergeValues(RetOps, dl); 8991 } 8992 8993 SDValue RetOps[] = { Value, TF }; 8994 return DAG.getMergeValues(RetOps, dl); 8995 } 8996 8997 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 8998 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 8999 9000 // To lower v4i1 from a byte array, we load the byte elements of the 9001 // vector and then reuse the BUILD_VECTOR logic. 9002 9003 SDValue VectElmts[4], VectElmtChains[4]; 9004 for (unsigned i = 0; i < 4; ++i) { 9005 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9006 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9007 9008 VectElmts[i] = DAG.getExtLoad( 9009 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9010 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9011 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9012 VectElmtChains[i] = VectElmts[i].getValue(1); 9013 } 9014 9015 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9016 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9017 9018 SDValue RVals[] = { Value, LoadChain }; 9019 return DAG.getMergeValues(RVals, dl); 9020 } 9021 9022 /// Lowering for QPX v4i1 stores 9023 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9024 SelectionDAG &DAG) const { 9025 SDLoc dl(Op); 9026 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9027 SDValue StoreChain = SN->getChain(); 9028 SDValue BasePtr = SN->getBasePtr(); 9029 SDValue Value = SN->getValue(); 9030 9031 if (Value.getValueType() == MVT::v4f64 || 9032 Value.getValueType() == MVT::v4f32) { 9033 EVT MemVT = SN->getMemoryVT(); 9034 unsigned Alignment = SN->getAlignment(); 9035 9036 // If this store is properly aligned, then it is legal. 9037 if (Alignment >= MemVT.getStoreSize()) 9038 return Op; 9039 9040 EVT ScalarVT = Value.getValueType().getScalarType(), 9041 ScalarMemVT = MemVT.getScalarType(); 9042 unsigned Stride = ScalarMemVT.getStoreSize(); 9043 9044 SDValue Stores[4]; 9045 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9046 SDValue Ex = DAG.getNode( 9047 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9048 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9049 SDValue Store; 9050 if (ScalarVT != ScalarMemVT) 9051 Store = 9052 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9053 SN->getPointerInfo().getWithOffset(Idx * Stride), 9054 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9055 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9056 else 9057 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9058 SN->getPointerInfo().getWithOffset(Idx * Stride), 9059 MinAlign(Alignment, Idx * Stride), 9060 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9061 9062 if (Idx == 0 && SN->isIndexed()) { 9063 assert(SN->getAddressingMode() == ISD::PRE_INC && 9064 "Unknown addressing mode on vector store"); 9065 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9066 SN->getAddressingMode()); 9067 } 9068 9069 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9070 DAG.getConstant(Stride, dl, 9071 BasePtr.getValueType())); 9072 Stores[Idx] = Store; 9073 } 9074 9075 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9076 9077 if (SN->isIndexed()) { 9078 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9079 return DAG.getMergeValues(RetOps, dl); 9080 } 9081 9082 return TF; 9083 } 9084 9085 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9086 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9087 9088 // The values are now known to be -1 (false) or 1 (true). To convert this 9089 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9090 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9091 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9092 9093 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9094 // understand how to form the extending load. 9095 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9096 9097 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9098 9099 // Now convert to an integer and store. 9100 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9101 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9102 Value); 9103 9104 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9105 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9106 MachinePointerInfo PtrInfo = 9107 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9108 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9109 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9110 9111 SDValue Ops[] = {StoreChain, 9112 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9113 Value, FIdx}; 9114 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9115 9116 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9117 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9118 9119 // Move data into the byte array. 9120 SDValue Loads[4], LoadChains[4]; 9121 for (unsigned i = 0; i < 4; ++i) { 9122 unsigned Offset = 4*i; 9123 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9124 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9125 9126 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9127 PtrInfo.getWithOffset(Offset)); 9128 LoadChains[i] = Loads[i].getValue(1); 9129 } 9130 9131 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9132 9133 SDValue Stores[4]; 9134 for (unsigned i = 0; i < 4; ++i) { 9135 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9136 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9137 9138 Stores[i] = DAG.getTruncStore( 9139 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9140 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9141 SN->getAAInfo()); 9142 } 9143 9144 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9145 9146 return StoreChain; 9147 } 9148 9149 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9150 SDLoc dl(Op); 9151 if (Op.getValueType() == MVT::v4i32) { 9152 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9153 9154 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9155 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9156 9157 SDValue RHSSwap = // = vrlw RHS, 16 9158 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9159 9160 // Shrinkify inputs to v8i16. 9161 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9162 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9163 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9164 9165 // Low parts multiplied together, generating 32-bit results (we ignore the 9166 // top parts). 9167 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9168 LHS, RHS, DAG, dl, MVT::v4i32); 9169 9170 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9171 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9172 // Shift the high parts up 16 bits. 9173 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9174 Neg16, DAG, dl); 9175 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9176 } else if (Op.getValueType() == MVT::v8i16) { 9177 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9178 9179 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9180 9181 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9182 LHS, RHS, Zero, DAG, dl); 9183 } else if (Op.getValueType() == MVT::v16i8) { 9184 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9185 bool isLittleEndian = Subtarget.isLittleEndian(); 9186 9187 // Multiply the even 8-bit parts, producing 16-bit sums. 9188 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9189 LHS, RHS, DAG, dl, MVT::v8i16); 9190 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9191 9192 // Multiply the odd 8-bit parts, producing 16-bit sums. 9193 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9194 LHS, RHS, DAG, dl, MVT::v8i16); 9195 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9196 9197 // Merge the results together. Because vmuleub and vmuloub are 9198 // instructions with a big-endian bias, we must reverse the 9199 // element numbering and reverse the meaning of "odd" and "even" 9200 // when generating little endian code. 9201 int Ops[16]; 9202 for (unsigned i = 0; i != 8; ++i) { 9203 if (isLittleEndian) { 9204 Ops[i*2 ] = 2*i; 9205 Ops[i*2+1] = 2*i+16; 9206 } else { 9207 Ops[i*2 ] = 2*i+1; 9208 Ops[i*2+1] = 2*i+1+16; 9209 } 9210 } 9211 if (isLittleEndian) 9212 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9213 else 9214 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9215 } else { 9216 llvm_unreachable("Unknown mul to lower!"); 9217 } 9218 } 9219 9220 /// LowerOperation - Provide custom lowering hooks for some operations. 9221 /// 9222 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9223 switch (Op.getOpcode()) { 9224 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9225 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9226 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9227 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9228 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9229 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9230 case ISD::SETCC: return LowerSETCC(Op, DAG); 9231 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9232 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9233 case ISD::VASTART: 9234 return LowerVASTART(Op, DAG); 9235 9236 case ISD::VAARG: 9237 return LowerVAARG(Op, DAG); 9238 9239 case ISD::VACOPY: 9240 return LowerVACOPY(Op, DAG); 9241 9242 case ISD::STACKRESTORE: 9243 return LowerSTACKRESTORE(Op, DAG); 9244 9245 case ISD::DYNAMIC_STACKALLOC: 9246 return LowerDYNAMIC_STACKALLOC(Op, DAG); 9247 9248 case ISD::GET_DYNAMIC_AREA_OFFSET: 9249 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9250 9251 case ISD::EH_DWARF_CFA: 9252 return LowerEH_DWARF_CFA(Op, DAG); 9253 9254 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9255 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9256 9257 case ISD::LOAD: return LowerLOAD(Op, DAG); 9258 case ISD::STORE: return LowerSTORE(Op, DAG); 9259 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9260 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9261 case ISD::FP_TO_UINT: 9262 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, 9263 SDLoc(Op)); 9264 case ISD::UINT_TO_FP: 9265 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9266 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9267 9268 // Lower 64-bit shifts. 9269 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9270 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9271 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9272 9273 // Vector-related lowering. 9274 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9275 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9276 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9277 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9278 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); 9279 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9280 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9281 case ISD::MUL: return LowerMUL(Op, DAG); 9282 9283 // For counter-based loop handling. 9284 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9285 9286 // Frame & Return address. 9287 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9288 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9289 9290 case ISD::INTRINSIC_VOID: 9291 return LowerINTRINSIC_VOID(Op, DAG); 9292 case ISD::SREM: 9293 case ISD::UREM: 9294 return LowerREM(Op, DAG); 9295 case ISD::BSWAP: 9296 return LowerBSWAP(Op, DAG); 9297 } 9298 } 9299 9300 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 9301 SmallVectorImpl<SDValue>&Results, 9302 SelectionDAG &DAG) const { 9303 SDLoc dl(N); 9304 switch (N->getOpcode()) { 9305 default: 9306 llvm_unreachable("Do not know how to custom type legalize this operation!"); 9307 case ISD::READCYCLECOUNTER: { 9308 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 9309 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 9310 9311 Results.push_back(RTB); 9312 Results.push_back(RTB.getValue(1)); 9313 Results.push_back(RTB.getValue(2)); 9314 break; 9315 } 9316 case ISD::INTRINSIC_W_CHAIN: { 9317 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 9318 Intrinsic::ppc_is_decremented_ctr_nonzero) 9319 break; 9320 9321 assert(N->getValueType(0) == MVT::i1 && 9322 "Unexpected result type for CTR decrement intrinsic"); 9323 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 9324 N->getValueType(0)); 9325 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 9326 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 9327 N->getOperand(1)); 9328 9329 Results.push_back(NewInt); 9330 Results.push_back(NewInt.getValue(1)); 9331 break; 9332 } 9333 case ISD::VAARG: { 9334 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 9335 return; 9336 9337 EVT VT = N->getValueType(0); 9338 9339 if (VT == MVT::i64) { 9340 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 9341 9342 Results.push_back(NewNode); 9343 Results.push_back(NewNode.getValue(1)); 9344 } 9345 return; 9346 } 9347 case ISD::FP_ROUND_INREG: { 9348 assert(N->getValueType(0) == MVT::ppcf128); 9349 assert(N->getOperand(0).getValueType() == MVT::ppcf128); 9350 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9351 MVT::f64, N->getOperand(0), 9352 DAG.getIntPtrConstant(0, dl)); 9353 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 9354 MVT::f64, N->getOperand(0), 9355 DAG.getIntPtrConstant(1, dl)); 9356 9357 // Add the two halves of the long double in round-to-zero mode. 9358 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 9359 9360 // We know the low half is about to be thrown away, so just use something 9361 // convenient. 9362 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 9363 FPreg, FPreg)); 9364 return; 9365 } 9366 case ISD::FP_TO_SINT: 9367 case ISD::FP_TO_UINT: 9368 // LowerFP_TO_INT() can only handle f32 and f64. 9369 if (N->getOperand(0).getValueType() == MVT::ppcf128) 9370 return; 9371 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 9372 return; 9373 } 9374 } 9375 9376 //===----------------------------------------------------------------------===// 9377 // Other Lowering Code 9378 //===----------------------------------------------------------------------===// 9379 9380 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 9381 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 9382 Function *Func = Intrinsic::getDeclaration(M, Id); 9383 return Builder.CreateCall(Func, {}); 9384 } 9385 9386 // The mappings for emitLeading/TrailingFence is taken from 9387 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 9388 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 9389 Instruction *Inst, 9390 AtomicOrdering Ord) const { 9391 if (Ord == AtomicOrdering::SequentiallyConsistent) 9392 return callIntrinsic(Builder, Intrinsic::ppc_sync); 9393 if (isReleaseOrStronger(Ord)) 9394 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9395 return nullptr; 9396 } 9397 9398 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 9399 Instruction *Inst, 9400 AtomicOrdering Ord) const { 9401 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 9402 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 9403 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 9404 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 9405 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 9406 return Builder.CreateCall( 9407 Intrinsic::getDeclaration( 9408 Builder.GetInsertBlock()->getParent()->getParent(), 9409 Intrinsic::ppc_cfence, {Inst->getType()}), 9410 {Inst}); 9411 // FIXME: Can use isync for rmw operation. 9412 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 9413 } 9414 return nullptr; 9415 } 9416 9417 MachineBasicBlock * 9418 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 9419 unsigned AtomicSize, 9420 unsigned BinOpcode, 9421 unsigned CmpOpcode, 9422 unsigned CmpPred) const { 9423 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9424 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9425 9426 auto LoadMnemonic = PPC::LDARX; 9427 auto StoreMnemonic = PPC::STDCX; 9428 switch (AtomicSize) { 9429 default: 9430 llvm_unreachable("Unexpected size of atomic entity"); 9431 case 1: 9432 LoadMnemonic = PPC::LBARX; 9433 StoreMnemonic = PPC::STBCX; 9434 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9435 break; 9436 case 2: 9437 LoadMnemonic = PPC::LHARX; 9438 StoreMnemonic = PPC::STHCX; 9439 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 9440 break; 9441 case 4: 9442 LoadMnemonic = PPC::LWARX; 9443 StoreMnemonic = PPC::STWCX; 9444 break; 9445 case 8: 9446 LoadMnemonic = PPC::LDARX; 9447 StoreMnemonic = PPC::STDCX; 9448 break; 9449 } 9450 9451 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9452 MachineFunction *F = BB->getParent(); 9453 MachineFunction::iterator It = ++BB->getIterator(); 9454 9455 unsigned dest = MI.getOperand(0).getReg(); 9456 unsigned ptrA = MI.getOperand(1).getReg(); 9457 unsigned ptrB = MI.getOperand(2).getReg(); 9458 unsigned incr = MI.getOperand(3).getReg(); 9459 DebugLoc dl = MI.getDebugLoc(); 9460 9461 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9462 MachineBasicBlock *loop2MBB = 9463 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9464 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9465 F->insert(It, loopMBB); 9466 if (CmpOpcode) 9467 F->insert(It, loop2MBB); 9468 F->insert(It, exitMBB); 9469 exitMBB->splice(exitMBB->begin(), BB, 9470 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9471 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9472 9473 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9474 unsigned TmpReg = (!BinOpcode) ? incr : 9475 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 9476 : &PPC::GPRCRegClass); 9477 9478 // thisMBB: 9479 // ... 9480 // fallthrough --> loopMBB 9481 BB->addSuccessor(loopMBB); 9482 9483 // loopMBB: 9484 // l[wd]arx dest, ptr 9485 // add r0, dest, incr 9486 // st[wd]cx. r0, ptr 9487 // bne- loopMBB 9488 // fallthrough --> exitMBB 9489 9490 // For max/min... 9491 // loopMBB: 9492 // l[wd]arx dest, ptr 9493 // cmpl?[wd] incr, dest 9494 // bgt exitMBB 9495 // loop2MBB: 9496 // st[wd]cx. dest, ptr 9497 // bne- loopMBB 9498 // fallthrough --> exitMBB 9499 9500 BB = loopMBB; 9501 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 9502 .addReg(ptrA).addReg(ptrB); 9503 if (BinOpcode) 9504 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 9505 if (CmpOpcode) { 9506 // Signed comparisons of byte or halfword values must be sign-extended. 9507 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 9508 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 9509 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 9510 ExtReg).addReg(dest); 9511 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9512 .addReg(incr).addReg(ExtReg); 9513 } else 9514 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9515 .addReg(incr).addReg(dest); 9516 9517 BuildMI(BB, dl, TII->get(PPC::BCC)) 9518 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9519 BB->addSuccessor(loop2MBB); 9520 BB->addSuccessor(exitMBB); 9521 BB = loop2MBB; 9522 } 9523 BuildMI(BB, dl, TII->get(StoreMnemonic)) 9524 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 9525 BuildMI(BB, dl, TII->get(PPC::BCC)) 9526 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9527 BB->addSuccessor(loopMBB); 9528 BB->addSuccessor(exitMBB); 9529 9530 // exitMBB: 9531 // ... 9532 BB = exitMBB; 9533 return BB; 9534 } 9535 9536 MachineBasicBlock * 9537 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI, 9538 MachineBasicBlock *BB, 9539 bool is8bit, // operation 9540 unsigned BinOpcode, 9541 unsigned CmpOpcode, 9542 unsigned CmpPred) const { 9543 // If we support part-word atomic mnemonics, just use them 9544 if (Subtarget.hasPartwordAtomics()) 9545 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, 9546 CmpOpcode, CmpPred); 9547 9548 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 9549 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9550 // In 64 bit mode we have to use 64 bits for addresses, even though the 9551 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 9552 // registers without caring whether they're 32 or 64, but here we're 9553 // doing actual arithmetic on the addresses. 9554 bool is64bit = Subtarget.isPPC64(); 9555 bool isLittleEndian = Subtarget.isLittleEndian(); 9556 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 9557 9558 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9559 MachineFunction *F = BB->getParent(); 9560 MachineFunction::iterator It = ++BB->getIterator(); 9561 9562 unsigned dest = MI.getOperand(0).getReg(); 9563 unsigned ptrA = MI.getOperand(1).getReg(); 9564 unsigned ptrB = MI.getOperand(2).getReg(); 9565 unsigned incr = MI.getOperand(3).getReg(); 9566 DebugLoc dl = MI.getDebugLoc(); 9567 9568 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 9569 MachineBasicBlock *loop2MBB = 9570 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 9571 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 9572 F->insert(It, loopMBB); 9573 if (CmpOpcode) 9574 F->insert(It, loop2MBB); 9575 F->insert(It, exitMBB); 9576 exitMBB->splice(exitMBB->begin(), BB, 9577 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9578 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 9579 9580 MachineRegisterInfo &RegInfo = F->getRegInfo(); 9581 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 9582 : &PPC::GPRCRegClass; 9583 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 9584 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 9585 unsigned ShiftReg = 9586 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 9587 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); 9588 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 9589 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 9590 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 9591 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 9592 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); 9593 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 9594 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 9595 unsigned Ptr1Reg; 9596 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); 9597 9598 // thisMBB: 9599 // ... 9600 // fallthrough --> loopMBB 9601 BB->addSuccessor(loopMBB); 9602 9603 // The 4-byte load must be aligned, while a char or short may be 9604 // anywhere in the word. Hence all this nasty bookkeeping code. 9605 // add ptr1, ptrA, ptrB [copy if ptrA==0] 9606 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 9607 // xori shift, shift1, 24 [16] 9608 // rlwinm ptr, ptr1, 0, 0, 29 9609 // slw incr2, incr, shift 9610 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 9611 // slw mask, mask2, shift 9612 // loopMBB: 9613 // lwarx tmpDest, ptr 9614 // add tmp, tmpDest, incr2 9615 // andc tmp2, tmpDest, mask 9616 // and tmp3, tmp, mask 9617 // or tmp4, tmp3, tmp2 9618 // stwcx. tmp4, ptr 9619 // bne- loopMBB 9620 // fallthrough --> exitMBB 9621 // srw dest, tmpDest, shift 9622 if (ptrA != ZeroReg) { 9623 Ptr1Reg = RegInfo.createVirtualRegister(RC); 9624 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 9625 .addReg(ptrA).addReg(ptrB); 9626 } else { 9627 Ptr1Reg = ptrB; 9628 } 9629 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 9630 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 9631 if (!isLittleEndian) 9632 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 9633 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 9634 if (is64bit) 9635 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 9636 .addReg(Ptr1Reg).addImm(0).addImm(61); 9637 else 9638 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 9639 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 9640 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) 9641 .addReg(incr).addReg(ShiftReg); 9642 if (is8bit) 9643 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 9644 else { 9645 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 9646 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); 9647 } 9648 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 9649 .addReg(Mask2Reg).addReg(ShiftReg); 9650 9651 BB = loopMBB; 9652 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 9653 .addReg(ZeroReg).addReg(PtrReg); 9654 if (BinOpcode) 9655 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 9656 .addReg(Incr2Reg).addReg(TmpDestReg); 9657 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) 9658 .addReg(TmpDestReg).addReg(MaskReg); 9659 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) 9660 .addReg(TmpReg).addReg(MaskReg); 9661 if (CmpOpcode) { 9662 // For unsigned comparisons, we can directly compare the shifted values. 9663 // For signed comparisons we shift and sign extend. 9664 unsigned SReg = RegInfo.createVirtualRegister(RC); 9665 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg) 9666 .addReg(TmpDestReg).addReg(MaskReg); 9667 unsigned ValueReg = SReg; 9668 unsigned CmpReg = Incr2Reg; 9669 if (CmpOpcode == PPC::CMPW) { 9670 ValueReg = RegInfo.createVirtualRegister(RC); 9671 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 9672 .addReg(SReg).addReg(ShiftReg); 9673 unsigned ValueSReg = RegInfo.createVirtualRegister(RC); 9674 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 9675 .addReg(ValueReg); 9676 ValueReg = ValueSReg; 9677 CmpReg = incr; 9678 } 9679 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 9680 .addReg(CmpReg).addReg(ValueReg); 9681 BuildMI(BB, dl, TII->get(PPC::BCC)) 9682 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 9683 BB->addSuccessor(loop2MBB); 9684 BB->addSuccessor(exitMBB); 9685 BB = loop2MBB; 9686 } 9687 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) 9688 .addReg(Tmp3Reg).addReg(Tmp2Reg); 9689 BuildMI(BB, dl, TII->get(PPC::STWCX)) 9690 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); 9691 BuildMI(BB, dl, TII->get(PPC::BCC)) 9692 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 9693 BB->addSuccessor(loopMBB); 9694 BB->addSuccessor(exitMBB); 9695 9696 // exitMBB: 9697 // ... 9698 BB = exitMBB; 9699 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) 9700 .addReg(ShiftReg); 9701 return BB; 9702 } 9703 9704 llvm::MachineBasicBlock * 9705 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 9706 MachineBasicBlock *MBB) const { 9707 DebugLoc DL = MI.getDebugLoc(); 9708 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9709 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 9710 9711 MachineFunction *MF = MBB->getParent(); 9712 MachineRegisterInfo &MRI = MF->getRegInfo(); 9713 9714 const BasicBlock *BB = MBB->getBasicBlock(); 9715 MachineFunction::iterator I = ++MBB->getIterator(); 9716 9717 // Memory Reference 9718 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9719 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9720 9721 unsigned DstReg = MI.getOperand(0).getReg(); 9722 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 9723 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 9724 unsigned mainDstReg = MRI.createVirtualRegister(RC); 9725 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 9726 9727 MVT PVT = getPointerTy(MF->getDataLayout()); 9728 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9729 "Invalid Pointer Size!"); 9730 // For v = setjmp(buf), we generate 9731 // 9732 // thisMBB: 9733 // SjLjSetup mainMBB 9734 // bl mainMBB 9735 // v_restore = 1 9736 // b sinkMBB 9737 // 9738 // mainMBB: 9739 // buf[LabelOffset] = LR 9740 // v_main = 0 9741 // 9742 // sinkMBB: 9743 // v = phi(main, restore) 9744 // 9745 9746 MachineBasicBlock *thisMBB = MBB; 9747 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 9748 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 9749 MF->insert(I, mainMBB); 9750 MF->insert(I, sinkMBB); 9751 9752 MachineInstrBuilder MIB; 9753 9754 // Transfer the remainder of BB and its successor edges to sinkMBB. 9755 sinkMBB->splice(sinkMBB->begin(), MBB, 9756 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 9757 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 9758 9759 // Note that the structure of the jmp_buf used here is not compatible 9760 // with that used by libc, and is not designed to be. Specifically, it 9761 // stores only those 'reserved' registers that LLVM does not otherwise 9762 // understand how to spill. Also, by convention, by the time this 9763 // intrinsic is called, Clang has already stored the frame address in the 9764 // first slot of the buffer and stack address in the third. Following the 9765 // X86 target code, we'll store the jump address in the second slot. We also 9766 // need to save the TOC pointer (R2) to handle jumps between shared 9767 // libraries, and that will be stored in the fourth slot. The thread 9768 // identifier (R13) is not affected. 9769 9770 // thisMBB: 9771 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9772 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9773 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9774 9775 // Prepare IP either in reg. 9776 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 9777 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 9778 unsigned BufReg = MI.getOperand(1).getReg(); 9779 9780 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 9781 setUsesTOCBasePtr(*MBB->getParent()); 9782 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 9783 .addReg(PPC::X2) 9784 .addImm(TOCOffset) 9785 .addReg(BufReg); 9786 MIB.setMemRefs(MMOBegin, MMOEnd); 9787 } 9788 9789 // Naked functions never have a base pointer, and so we use r1. For all 9790 // other functions, this decision must be delayed until during PEI. 9791 unsigned BaseReg; 9792 if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) 9793 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 9794 else 9795 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 9796 9797 MIB = BuildMI(*thisMBB, MI, DL, 9798 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 9799 .addReg(BaseReg) 9800 .addImm(BPOffset) 9801 .addReg(BufReg); 9802 MIB.setMemRefs(MMOBegin, MMOEnd); 9803 9804 // Setup 9805 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 9806 MIB.addRegMask(TRI->getNoPreservedMask()); 9807 9808 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 9809 9810 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 9811 .addMBB(mainMBB); 9812 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 9813 9814 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 9815 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 9816 9817 // mainMBB: 9818 // mainDstReg = 0 9819 MIB = 9820 BuildMI(mainMBB, DL, 9821 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 9822 9823 // Store IP 9824 if (Subtarget.isPPC64()) { 9825 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 9826 .addReg(LabelReg) 9827 .addImm(LabelOffset) 9828 .addReg(BufReg); 9829 } else { 9830 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 9831 .addReg(LabelReg) 9832 .addImm(LabelOffset) 9833 .addReg(BufReg); 9834 } 9835 9836 MIB.setMemRefs(MMOBegin, MMOEnd); 9837 9838 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 9839 mainMBB->addSuccessor(sinkMBB); 9840 9841 // sinkMBB: 9842 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 9843 TII->get(PPC::PHI), DstReg) 9844 .addReg(mainDstReg).addMBB(mainMBB) 9845 .addReg(restoreDstReg).addMBB(thisMBB); 9846 9847 MI.eraseFromParent(); 9848 return sinkMBB; 9849 } 9850 9851 MachineBasicBlock * 9852 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 9853 MachineBasicBlock *MBB) const { 9854 DebugLoc DL = MI.getDebugLoc(); 9855 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9856 9857 MachineFunction *MF = MBB->getParent(); 9858 MachineRegisterInfo &MRI = MF->getRegInfo(); 9859 9860 // Memory Reference 9861 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin(); 9862 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end(); 9863 9864 MVT PVT = getPointerTy(MF->getDataLayout()); 9865 assert((PVT == MVT::i64 || PVT == MVT::i32) && 9866 "Invalid Pointer Size!"); 9867 9868 const TargetRegisterClass *RC = 9869 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 9870 unsigned Tmp = MRI.createVirtualRegister(RC); 9871 // Since FP is only updated here but NOT referenced, it's treated as GPR. 9872 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 9873 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 9874 unsigned BP = 9875 (PVT == MVT::i64) 9876 ? PPC::X30 9877 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 9878 : PPC::R30); 9879 9880 MachineInstrBuilder MIB; 9881 9882 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 9883 const int64_t SPOffset = 2 * PVT.getStoreSize(); 9884 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 9885 const int64_t BPOffset = 4 * PVT.getStoreSize(); 9886 9887 unsigned BufReg = MI.getOperand(0).getReg(); 9888 9889 // Reload FP (the jumped-to function may not have had a 9890 // frame pointer, and if so, then its r31 will be restored 9891 // as necessary). 9892 if (PVT == MVT::i64) { 9893 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 9894 .addImm(0) 9895 .addReg(BufReg); 9896 } else { 9897 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 9898 .addImm(0) 9899 .addReg(BufReg); 9900 } 9901 MIB.setMemRefs(MMOBegin, MMOEnd); 9902 9903 // Reload IP 9904 if (PVT == MVT::i64) { 9905 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 9906 .addImm(LabelOffset) 9907 .addReg(BufReg); 9908 } else { 9909 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 9910 .addImm(LabelOffset) 9911 .addReg(BufReg); 9912 } 9913 MIB.setMemRefs(MMOBegin, MMOEnd); 9914 9915 // Reload SP 9916 if (PVT == MVT::i64) { 9917 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 9918 .addImm(SPOffset) 9919 .addReg(BufReg); 9920 } else { 9921 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 9922 .addImm(SPOffset) 9923 .addReg(BufReg); 9924 } 9925 MIB.setMemRefs(MMOBegin, MMOEnd); 9926 9927 // Reload BP 9928 if (PVT == MVT::i64) { 9929 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 9930 .addImm(BPOffset) 9931 .addReg(BufReg); 9932 } else { 9933 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 9934 .addImm(BPOffset) 9935 .addReg(BufReg); 9936 } 9937 MIB.setMemRefs(MMOBegin, MMOEnd); 9938 9939 // Reload TOC 9940 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 9941 setUsesTOCBasePtr(*MBB->getParent()); 9942 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 9943 .addImm(TOCOffset) 9944 .addReg(BufReg); 9945 9946 MIB.setMemRefs(MMOBegin, MMOEnd); 9947 } 9948 9949 // Jump 9950 BuildMI(*MBB, MI, DL, 9951 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 9952 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 9953 9954 MI.eraseFromParent(); 9955 return MBB; 9956 } 9957 9958 MachineBasicBlock * 9959 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9960 MachineBasicBlock *BB) const { 9961 if (MI.getOpcode() == TargetOpcode::STACKMAP || 9962 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9963 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 9964 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 9965 // Call lowering should have added an r2 operand to indicate a dependence 9966 // on the TOC base pointer value. It can't however, because there is no 9967 // way to mark the dependence as implicit there, and so the stackmap code 9968 // will confuse it with a regular operand. Instead, add the dependence 9969 // here. 9970 setUsesTOCBasePtr(*BB->getParent()); 9971 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 9972 } 9973 9974 return emitPatchPoint(MI, BB); 9975 } 9976 9977 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 9978 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 9979 return emitEHSjLjSetJmp(MI, BB); 9980 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 9981 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 9982 return emitEHSjLjLongJmp(MI, BB); 9983 } 9984 9985 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 9986 9987 // To "insert" these instructions we actually have to insert their 9988 // control-flow patterns. 9989 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9990 MachineFunction::iterator It = ++BB->getIterator(); 9991 9992 MachineFunction *F = BB->getParent(); 9993 9994 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9995 MI.getOpcode() == PPC::SELECT_CC_I8 || 9996 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) { 9997 SmallVector<MachineOperand, 2> Cond; 9998 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 9999 MI.getOpcode() == PPC::SELECT_CC_I8) 10000 Cond.push_back(MI.getOperand(4)); 10001 else 10002 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10003 Cond.push_back(MI.getOperand(1)); 10004 10005 DebugLoc dl = MI.getDebugLoc(); 10006 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10007 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10008 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10009 MI.getOpcode() == PPC::SELECT_CC_I8 || 10010 MI.getOpcode() == PPC::SELECT_CC_F4 || 10011 MI.getOpcode() == PPC::SELECT_CC_F8 || 10012 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10013 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10014 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10015 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10016 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10017 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10018 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10019 MI.getOpcode() == PPC::SELECT_I4 || 10020 MI.getOpcode() == PPC::SELECT_I8 || 10021 MI.getOpcode() == PPC::SELECT_F4 || 10022 MI.getOpcode() == PPC::SELECT_F8 || 10023 MI.getOpcode() == PPC::SELECT_QFRC || 10024 MI.getOpcode() == PPC::SELECT_QSRC || 10025 MI.getOpcode() == PPC::SELECT_QBRC || 10026 MI.getOpcode() == PPC::SELECT_VRRC || 10027 MI.getOpcode() == PPC::SELECT_VSFRC || 10028 MI.getOpcode() == PPC::SELECT_VSSRC || 10029 MI.getOpcode() == PPC::SELECT_VSRC) { 10030 // The incoming instruction knows the destination vreg to set, the 10031 // condition code register to branch on, the true/false values to 10032 // select between, and a branch opcode to use. 10033 10034 // thisMBB: 10035 // ... 10036 // TrueVal = ... 10037 // cmpTY ccX, r1, r2 10038 // bCC copy1MBB 10039 // fallthrough --> copy0MBB 10040 MachineBasicBlock *thisMBB = BB; 10041 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10042 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10043 DebugLoc dl = MI.getDebugLoc(); 10044 F->insert(It, copy0MBB); 10045 F->insert(It, sinkMBB); 10046 10047 // Transfer the remainder of BB and its successor edges to sinkMBB. 10048 sinkMBB->splice(sinkMBB->begin(), BB, 10049 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10050 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10051 10052 // Next, add the true and fallthrough blocks as its successors. 10053 BB->addSuccessor(copy0MBB); 10054 BB->addSuccessor(sinkMBB); 10055 10056 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10057 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10058 MI.getOpcode() == PPC::SELECT_QFRC || 10059 MI.getOpcode() == PPC::SELECT_QSRC || 10060 MI.getOpcode() == PPC::SELECT_QBRC || 10061 MI.getOpcode() == PPC::SELECT_VRRC || 10062 MI.getOpcode() == PPC::SELECT_VSFRC || 10063 MI.getOpcode() == PPC::SELECT_VSSRC || 10064 MI.getOpcode() == PPC::SELECT_VSRC) { 10065 BuildMI(BB, dl, TII->get(PPC::BC)) 10066 .addReg(MI.getOperand(1).getReg()) 10067 .addMBB(sinkMBB); 10068 } else { 10069 unsigned SelectPred = MI.getOperand(4).getImm(); 10070 BuildMI(BB, dl, TII->get(PPC::BCC)) 10071 .addImm(SelectPred) 10072 .addReg(MI.getOperand(1).getReg()) 10073 .addMBB(sinkMBB); 10074 } 10075 10076 // copy0MBB: 10077 // %FalseValue = ... 10078 // # fallthrough to sinkMBB 10079 BB = copy0MBB; 10080 10081 // Update machine-CFG edges 10082 BB->addSuccessor(sinkMBB); 10083 10084 // sinkMBB: 10085 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10086 // ... 10087 BB = sinkMBB; 10088 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10089 .addReg(MI.getOperand(3).getReg()) 10090 .addMBB(copy0MBB) 10091 .addReg(MI.getOperand(2).getReg()) 10092 .addMBB(thisMBB); 10093 } else if (MI.getOpcode() == PPC::ReadTB) { 10094 // To read the 64-bit time-base register on a 32-bit target, we read the 10095 // two halves. Should the counter have wrapped while it was being read, we 10096 // need to try again. 10097 // ... 10098 // readLoop: 10099 // mfspr Rx,TBU # load from TBU 10100 // mfspr Ry,TB # load from TB 10101 // mfspr Rz,TBU # load from TBU 10102 // cmpw crX,Rx,Rz # check if 'old'='new' 10103 // bne readLoop # branch if they're not equal 10104 // ... 10105 10106 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10107 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10108 DebugLoc dl = MI.getDebugLoc(); 10109 F->insert(It, readMBB); 10110 F->insert(It, sinkMBB); 10111 10112 // Transfer the remainder of BB and its successor edges to sinkMBB. 10113 sinkMBB->splice(sinkMBB->begin(), BB, 10114 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10115 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10116 10117 BB->addSuccessor(readMBB); 10118 BB = readMBB; 10119 10120 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10121 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10122 unsigned LoReg = MI.getOperand(0).getReg(); 10123 unsigned HiReg = MI.getOperand(1).getReg(); 10124 10125 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10126 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10127 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10128 10129 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10130 10131 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10132 .addReg(HiReg).addReg(ReadAgainReg); 10133 BuildMI(BB, dl, TII->get(PPC::BCC)) 10134 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); 10135 10136 BB->addSuccessor(readMBB); 10137 BB->addSuccessor(sinkMBB); 10138 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10139 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10140 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10141 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10142 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10143 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10144 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10145 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10146 10147 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10148 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10149 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10150 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10151 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10152 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10153 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10154 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10155 10156 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10157 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10158 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10159 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10160 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10161 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10162 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10163 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10164 10165 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10166 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10167 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10168 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10169 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10170 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10171 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10172 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10173 10174 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10175 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10176 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10177 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10178 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10179 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10180 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10181 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10182 10183 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10184 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10185 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10186 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10187 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10188 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10189 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10190 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10191 10192 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10193 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10194 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10195 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10196 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10197 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10198 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10199 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10200 10201 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10202 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10203 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10204 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10205 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10206 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10207 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10208 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10209 10210 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10211 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10212 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10213 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10214 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10215 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10216 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10217 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10218 10219 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10220 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10221 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10222 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10223 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10224 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10225 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10226 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10227 10228 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10229 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10230 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10231 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10232 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10233 BB = EmitAtomicBinary(MI, BB, 4, 0); 10234 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10235 BB = EmitAtomicBinary(MI, BB, 8, 0); 10236 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10237 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10238 (Subtarget.hasPartwordAtomics() && 10239 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10240 (Subtarget.hasPartwordAtomics() && 10241 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10242 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10243 10244 auto LoadMnemonic = PPC::LDARX; 10245 auto StoreMnemonic = PPC::STDCX; 10246 switch (MI.getOpcode()) { 10247 default: 10248 llvm_unreachable("Compare and swap of unknown size"); 10249 case PPC::ATOMIC_CMP_SWAP_I8: 10250 LoadMnemonic = PPC::LBARX; 10251 StoreMnemonic = PPC::STBCX; 10252 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10253 break; 10254 case PPC::ATOMIC_CMP_SWAP_I16: 10255 LoadMnemonic = PPC::LHARX; 10256 StoreMnemonic = PPC::STHCX; 10257 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10258 break; 10259 case PPC::ATOMIC_CMP_SWAP_I32: 10260 LoadMnemonic = PPC::LWARX; 10261 StoreMnemonic = PPC::STWCX; 10262 break; 10263 case PPC::ATOMIC_CMP_SWAP_I64: 10264 LoadMnemonic = PPC::LDARX; 10265 StoreMnemonic = PPC::STDCX; 10266 break; 10267 } 10268 unsigned dest = MI.getOperand(0).getReg(); 10269 unsigned ptrA = MI.getOperand(1).getReg(); 10270 unsigned ptrB = MI.getOperand(2).getReg(); 10271 unsigned oldval = MI.getOperand(3).getReg(); 10272 unsigned newval = MI.getOperand(4).getReg(); 10273 DebugLoc dl = MI.getDebugLoc(); 10274 10275 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10276 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10277 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10278 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10279 F->insert(It, loop1MBB); 10280 F->insert(It, loop2MBB); 10281 F->insert(It, midMBB); 10282 F->insert(It, exitMBB); 10283 exitMBB->splice(exitMBB->begin(), BB, 10284 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10285 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10286 10287 // thisMBB: 10288 // ... 10289 // fallthrough --> loopMBB 10290 BB->addSuccessor(loop1MBB); 10291 10292 // loop1MBB: 10293 // l[bhwd]arx dest, ptr 10294 // cmp[wd] dest, oldval 10295 // bne- midMBB 10296 // loop2MBB: 10297 // st[bhwd]cx. newval, ptr 10298 // bne- loopMBB 10299 // b exitBB 10300 // midMBB: 10301 // st[bhwd]cx. dest, ptr 10302 // exitBB: 10303 BB = loop1MBB; 10304 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10305 .addReg(ptrA).addReg(ptrB); 10306 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 10307 .addReg(oldval).addReg(dest); 10308 BuildMI(BB, dl, TII->get(PPC::BCC)) 10309 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10310 BB->addSuccessor(loop2MBB); 10311 BB->addSuccessor(midMBB); 10312 10313 BB = loop2MBB; 10314 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10315 .addReg(newval).addReg(ptrA).addReg(ptrB); 10316 BuildMI(BB, dl, TII->get(PPC::BCC)) 10317 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10318 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10319 BB->addSuccessor(loop1MBB); 10320 BB->addSuccessor(exitMBB); 10321 10322 BB = midMBB; 10323 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10324 .addReg(dest).addReg(ptrA).addReg(ptrB); 10325 BB->addSuccessor(exitMBB); 10326 10327 // exitMBB: 10328 // ... 10329 BB = exitMBB; 10330 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 10331 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 10332 // We must use 64-bit registers for addresses when targeting 64-bit, 10333 // since we're actually doing arithmetic on them. Other registers 10334 // can be 32-bit. 10335 bool is64bit = Subtarget.isPPC64(); 10336 bool isLittleEndian = Subtarget.isLittleEndian(); 10337 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 10338 10339 unsigned dest = MI.getOperand(0).getReg(); 10340 unsigned ptrA = MI.getOperand(1).getReg(); 10341 unsigned ptrB = MI.getOperand(2).getReg(); 10342 unsigned oldval = MI.getOperand(3).getReg(); 10343 unsigned newval = MI.getOperand(4).getReg(); 10344 DebugLoc dl = MI.getDebugLoc(); 10345 10346 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10347 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10348 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10349 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10350 F->insert(It, loop1MBB); 10351 F->insert(It, loop2MBB); 10352 F->insert(It, midMBB); 10353 F->insert(It, exitMBB); 10354 exitMBB->splice(exitMBB->begin(), BB, 10355 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10356 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10357 10358 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10359 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass 10360 : &PPC::GPRCRegClass; 10361 unsigned PtrReg = RegInfo.createVirtualRegister(RC); 10362 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); 10363 unsigned ShiftReg = 10364 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC); 10365 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); 10366 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); 10367 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); 10368 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); 10369 unsigned MaskReg = RegInfo.createVirtualRegister(RC); 10370 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); 10371 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); 10372 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); 10373 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); 10374 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); 10375 unsigned Ptr1Reg; 10376 unsigned TmpReg = RegInfo.createVirtualRegister(RC); 10377 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10378 // thisMBB: 10379 // ... 10380 // fallthrough --> loopMBB 10381 BB->addSuccessor(loop1MBB); 10382 10383 // The 4-byte load must be aligned, while a char or short may be 10384 // anywhere in the word. Hence all this nasty bookkeeping code. 10385 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10386 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10387 // xori shift, shift1, 24 [16] 10388 // rlwinm ptr, ptr1, 0, 0, 29 10389 // slw newval2, newval, shift 10390 // slw oldval2, oldval,shift 10391 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10392 // slw mask, mask2, shift 10393 // and newval3, newval2, mask 10394 // and oldval3, oldval2, mask 10395 // loop1MBB: 10396 // lwarx tmpDest, ptr 10397 // and tmp, tmpDest, mask 10398 // cmpw tmp, oldval3 10399 // bne- midMBB 10400 // loop2MBB: 10401 // andc tmp2, tmpDest, mask 10402 // or tmp4, tmp2, newval3 10403 // stwcx. tmp4, ptr 10404 // bne- loop1MBB 10405 // b exitBB 10406 // midMBB: 10407 // stwcx. tmpDest, ptr 10408 // exitBB: 10409 // srw dest, tmpDest, shift 10410 if (ptrA != ZeroReg) { 10411 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10412 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10413 .addReg(ptrA).addReg(ptrB); 10414 } else { 10415 Ptr1Reg = ptrB; 10416 } 10417 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) 10418 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); 10419 if (!isLittleEndian) 10420 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) 10421 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); 10422 if (is64bit) 10423 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10424 .addReg(Ptr1Reg).addImm(0).addImm(61); 10425 else 10426 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10427 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); 10428 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 10429 .addReg(newval).addReg(ShiftReg); 10430 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 10431 .addReg(oldval).addReg(ShiftReg); 10432 if (is8bit) 10433 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10434 else { 10435 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10436 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10437 .addReg(Mask3Reg).addImm(65535); 10438 } 10439 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10440 .addReg(Mask2Reg).addReg(ShiftReg); 10441 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 10442 .addReg(NewVal2Reg).addReg(MaskReg); 10443 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 10444 .addReg(OldVal2Reg).addReg(MaskReg); 10445 10446 BB = loop1MBB; 10447 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10448 .addReg(ZeroReg).addReg(PtrReg); 10449 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) 10450 .addReg(TmpDestReg).addReg(MaskReg); 10451 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 10452 .addReg(TmpReg).addReg(OldVal3Reg); 10453 BuildMI(BB, dl, TII->get(PPC::BCC)) 10454 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); 10455 BB->addSuccessor(loop2MBB); 10456 BB->addSuccessor(midMBB); 10457 10458 BB = loop2MBB; 10459 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) 10460 .addReg(TmpDestReg).addReg(MaskReg); 10461 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) 10462 .addReg(Tmp2Reg).addReg(NewVal3Reg); 10463 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) 10464 .addReg(ZeroReg).addReg(PtrReg); 10465 BuildMI(BB, dl, TII->get(PPC::BCC)) 10466 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); 10467 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 10468 BB->addSuccessor(loop1MBB); 10469 BB->addSuccessor(exitMBB); 10470 10471 BB = midMBB; 10472 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) 10473 .addReg(ZeroReg).addReg(PtrReg); 10474 BB->addSuccessor(exitMBB); 10475 10476 // exitMBB: 10477 // ... 10478 BB = exitMBB; 10479 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) 10480 .addReg(ShiftReg); 10481 } else if (MI.getOpcode() == PPC::FADDrtz) { 10482 // This pseudo performs an FADD with rounding mode temporarily forced 10483 // to round-to-zero. We emit this via custom inserter since the FPSCR 10484 // is not modeled at the SelectionDAG level. 10485 unsigned Dest = MI.getOperand(0).getReg(); 10486 unsigned Src1 = MI.getOperand(1).getReg(); 10487 unsigned Src2 = MI.getOperand(2).getReg(); 10488 DebugLoc dl = MI.getDebugLoc(); 10489 10490 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10491 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 10492 10493 // Save FPSCR value. 10494 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 10495 10496 // Set rounding mode to round-to-zero. 10497 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 10498 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 10499 10500 // Perform addition. 10501 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 10502 10503 // Restore FPSCR value. 10504 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 10505 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10506 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 10507 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10508 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 10509 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 10510 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 10511 ? PPC::ANDIo8 10512 : PPC::ANDIo; 10513 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 10514 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 10515 10516 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10517 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? 10518 &PPC::GPRCRegClass : 10519 &PPC::G8RCRegClass); 10520 10521 DebugLoc dl = MI.getDebugLoc(); 10522 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 10523 .addReg(MI.getOperand(1).getReg()) 10524 .addImm(1); 10525 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 10526 MI.getOperand(0).getReg()) 10527 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 10528 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 10529 DebugLoc Dl = MI.getDebugLoc(); 10530 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10531 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10532 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 10533 return BB; 10534 } else { 10535 llvm_unreachable("Unexpected instr type to insert"); 10536 } 10537 10538 MI.eraseFromParent(); // The pseudo instruction is gone now. 10539 return BB; 10540 } 10541 10542 //===----------------------------------------------------------------------===// 10543 // Target Optimization Hooks 10544 //===----------------------------------------------------------------------===// 10545 10546 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 10547 // For the estimates, convergence is quadratic, so we essentially double the 10548 // number of digits correct after every iteration. For both FRE and FRSQRTE, 10549 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 10550 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 10551 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 10552 if (VT.getScalarType() == MVT::f64) 10553 RefinementSteps++; 10554 return RefinementSteps; 10555 } 10556 10557 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 10558 int Enabled, int &RefinementSteps, 10559 bool &UseOneConstNR, 10560 bool Reciprocal) const { 10561 EVT VT = Operand.getValueType(); 10562 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 10563 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 10564 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10565 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10566 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10567 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10568 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10569 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10570 10571 UseOneConstNR = true; 10572 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 10573 } 10574 return SDValue(); 10575 } 10576 10577 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 10578 int Enabled, 10579 int &RefinementSteps) const { 10580 EVT VT = Operand.getValueType(); 10581 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 10582 (VT == MVT::f64 && Subtarget.hasFRE()) || 10583 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 10584 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 10585 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 10586 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 10587 if (RefinementSteps == ReciprocalEstimate::Unspecified) 10588 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 10589 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 10590 } 10591 return SDValue(); 10592 } 10593 10594 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 10595 // Note: This functionality is used only when unsafe-fp-math is enabled, and 10596 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 10597 // enabled for division), this functionality is redundant with the default 10598 // combiner logic (once the division -> reciprocal/multiply transformation 10599 // has taken place). As a result, this matters more for older cores than for 10600 // newer ones. 10601 10602 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10603 // reciprocal if there are two or more FDIVs (for embedded cores with only 10604 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 10605 switch (Subtarget.getDarwinDirective()) { 10606 default: 10607 return 3; 10608 case PPC::DIR_440: 10609 case PPC::DIR_A2: 10610 case PPC::DIR_E500mc: 10611 case PPC::DIR_E5500: 10612 return 2; 10613 } 10614 } 10615 10616 // isConsecutiveLSLoc needs to work even if all adds have not yet been 10617 // collapsed, and so we need to look through chains of them. 10618 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 10619 int64_t& Offset, SelectionDAG &DAG) { 10620 if (DAG.isBaseWithConstantOffset(Loc)) { 10621 Base = Loc.getOperand(0); 10622 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 10623 10624 // The base might itself be a base plus an offset, and if so, accumulate 10625 // that as well. 10626 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 10627 } 10628 } 10629 10630 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 10631 unsigned Bytes, int Dist, 10632 SelectionDAG &DAG) { 10633 if (VT.getSizeInBits() / 8 != Bytes) 10634 return false; 10635 10636 SDValue BaseLoc = Base->getBasePtr(); 10637 if (Loc.getOpcode() == ISD::FrameIndex) { 10638 if (BaseLoc.getOpcode() != ISD::FrameIndex) 10639 return false; 10640 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10641 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 10642 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 10643 int FS = MFI.getObjectSize(FI); 10644 int BFS = MFI.getObjectSize(BFI); 10645 if (FS != BFS || FS != (int)Bytes) return false; 10646 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 10647 } 10648 10649 SDValue Base1 = Loc, Base2 = BaseLoc; 10650 int64_t Offset1 = 0, Offset2 = 0; 10651 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 10652 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 10653 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 10654 return true; 10655 10656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10657 const GlobalValue *GV1 = nullptr; 10658 const GlobalValue *GV2 = nullptr; 10659 Offset1 = 0; 10660 Offset2 = 0; 10661 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 10662 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 10663 if (isGA1 && isGA2 && GV1 == GV2) 10664 return Offset1 == (Offset2 + Dist*Bytes); 10665 return false; 10666 } 10667 10668 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 10669 // not enforce equality of the chain operands. 10670 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 10671 unsigned Bytes, int Dist, 10672 SelectionDAG &DAG) { 10673 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 10674 EVT VT = LS->getMemoryVT(); 10675 SDValue Loc = LS->getBasePtr(); 10676 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 10677 } 10678 10679 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 10680 EVT VT; 10681 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10682 default: return false; 10683 case Intrinsic::ppc_qpx_qvlfd: 10684 case Intrinsic::ppc_qpx_qvlfda: 10685 VT = MVT::v4f64; 10686 break; 10687 case Intrinsic::ppc_qpx_qvlfs: 10688 case Intrinsic::ppc_qpx_qvlfsa: 10689 VT = MVT::v4f32; 10690 break; 10691 case Intrinsic::ppc_qpx_qvlfcd: 10692 case Intrinsic::ppc_qpx_qvlfcda: 10693 VT = MVT::v2f64; 10694 break; 10695 case Intrinsic::ppc_qpx_qvlfcs: 10696 case Intrinsic::ppc_qpx_qvlfcsa: 10697 VT = MVT::v2f32; 10698 break; 10699 case Intrinsic::ppc_qpx_qvlfiwa: 10700 case Intrinsic::ppc_qpx_qvlfiwz: 10701 case Intrinsic::ppc_altivec_lvx: 10702 case Intrinsic::ppc_altivec_lvxl: 10703 case Intrinsic::ppc_vsx_lxvw4x: 10704 case Intrinsic::ppc_vsx_lxvw4x_be: 10705 VT = MVT::v4i32; 10706 break; 10707 case Intrinsic::ppc_vsx_lxvd2x: 10708 case Intrinsic::ppc_vsx_lxvd2x_be: 10709 VT = MVT::v2f64; 10710 break; 10711 case Intrinsic::ppc_altivec_lvebx: 10712 VT = MVT::i8; 10713 break; 10714 case Intrinsic::ppc_altivec_lvehx: 10715 VT = MVT::i16; 10716 break; 10717 case Intrinsic::ppc_altivec_lvewx: 10718 VT = MVT::i32; 10719 break; 10720 } 10721 10722 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 10723 } 10724 10725 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 10726 EVT VT; 10727 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10728 default: return false; 10729 case Intrinsic::ppc_qpx_qvstfd: 10730 case Intrinsic::ppc_qpx_qvstfda: 10731 VT = MVT::v4f64; 10732 break; 10733 case Intrinsic::ppc_qpx_qvstfs: 10734 case Intrinsic::ppc_qpx_qvstfsa: 10735 VT = MVT::v4f32; 10736 break; 10737 case Intrinsic::ppc_qpx_qvstfcd: 10738 case Intrinsic::ppc_qpx_qvstfcda: 10739 VT = MVT::v2f64; 10740 break; 10741 case Intrinsic::ppc_qpx_qvstfcs: 10742 case Intrinsic::ppc_qpx_qvstfcsa: 10743 VT = MVT::v2f32; 10744 break; 10745 case Intrinsic::ppc_qpx_qvstfiw: 10746 case Intrinsic::ppc_qpx_qvstfiwa: 10747 case Intrinsic::ppc_altivec_stvx: 10748 case Intrinsic::ppc_altivec_stvxl: 10749 case Intrinsic::ppc_vsx_stxvw4x: 10750 VT = MVT::v4i32; 10751 break; 10752 case Intrinsic::ppc_vsx_stxvd2x: 10753 VT = MVT::v2f64; 10754 break; 10755 case Intrinsic::ppc_vsx_stxvw4x_be: 10756 VT = MVT::v4i32; 10757 break; 10758 case Intrinsic::ppc_vsx_stxvd2x_be: 10759 VT = MVT::v2f64; 10760 break; 10761 case Intrinsic::ppc_altivec_stvebx: 10762 VT = MVT::i8; 10763 break; 10764 case Intrinsic::ppc_altivec_stvehx: 10765 VT = MVT::i16; 10766 break; 10767 case Intrinsic::ppc_altivec_stvewx: 10768 VT = MVT::i32; 10769 break; 10770 } 10771 10772 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 10773 } 10774 10775 return false; 10776 } 10777 10778 // Return true is there is a nearyby consecutive load to the one provided 10779 // (regardless of alignment). We search up and down the chain, looking though 10780 // token factors and other loads (but nothing else). As a result, a true result 10781 // indicates that it is safe to create a new consecutive load adjacent to the 10782 // load provided. 10783 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 10784 SDValue Chain = LD->getChain(); 10785 EVT VT = LD->getMemoryVT(); 10786 10787 SmallSet<SDNode *, 16> LoadRoots; 10788 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 10789 SmallSet<SDNode *, 16> Visited; 10790 10791 // First, search up the chain, branching to follow all token-factor operands. 10792 // If we find a consecutive load, then we're done, otherwise, record all 10793 // nodes just above the top-level loads and token factors. 10794 while (!Queue.empty()) { 10795 SDNode *ChainNext = Queue.pop_back_val(); 10796 if (!Visited.insert(ChainNext).second) 10797 continue; 10798 10799 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 10800 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10801 return true; 10802 10803 if (!Visited.count(ChainLD->getChain().getNode())) 10804 Queue.push_back(ChainLD->getChain().getNode()); 10805 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 10806 for (const SDUse &O : ChainNext->ops()) 10807 if (!Visited.count(O.getNode())) 10808 Queue.push_back(O.getNode()); 10809 } else 10810 LoadRoots.insert(ChainNext); 10811 } 10812 10813 // Second, search down the chain, starting from the top-level nodes recorded 10814 // in the first phase. These top-level nodes are the nodes just above all 10815 // loads and token factors. Starting with their uses, recursively look though 10816 // all loads (just the chain uses) and token factors to find a consecutive 10817 // load. 10818 Visited.clear(); 10819 Queue.clear(); 10820 10821 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 10822 IE = LoadRoots.end(); I != IE; ++I) { 10823 Queue.push_back(*I); 10824 10825 while (!Queue.empty()) { 10826 SDNode *LoadRoot = Queue.pop_back_val(); 10827 if (!Visited.insert(LoadRoot).second) 10828 continue; 10829 10830 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 10831 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 10832 return true; 10833 10834 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 10835 UE = LoadRoot->use_end(); UI != UE; ++UI) 10836 if (((isa<MemSDNode>(*UI) && 10837 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 10838 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 10839 Queue.push_back(*UI); 10840 } 10841 } 10842 10843 return false; 10844 } 10845 10846 /// This function is called when we have proved that a SETCC node can be replaced 10847 /// by subtraction (and other supporting instructions) so that the result of 10848 /// comparison is kept in a GPR instead of CR. This function is purely for 10849 /// codegen purposes and has some flags to guide the codegen process. 10850 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 10851 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 10852 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10853 10854 // Zero extend the operands to the largest legal integer. Originally, they 10855 // must be of a strictly smaller size. 10856 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 10857 DAG.getConstant(Size, DL, MVT::i32)); 10858 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 10859 DAG.getConstant(Size, DL, MVT::i32)); 10860 10861 // Swap if needed. Depends on the condition code. 10862 if (Swap) 10863 std::swap(Op0, Op1); 10864 10865 // Subtract extended integers. 10866 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 10867 10868 // Move the sign bit to the least significant position and zero out the rest. 10869 // Now the least significant bit carries the result of original comparison. 10870 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 10871 DAG.getConstant(Size - 1, DL, MVT::i32)); 10872 auto Final = Shifted; 10873 10874 // Complement the result if needed. Based on the condition code. 10875 if (Complement) 10876 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 10877 DAG.getConstant(1, DL, MVT::i64)); 10878 10879 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 10880 } 10881 10882 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 10883 DAGCombinerInfo &DCI) const { 10884 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 10885 10886 SelectionDAG &DAG = DCI.DAG; 10887 SDLoc DL(N); 10888 10889 // Size of integers being compared has a critical role in the following 10890 // analysis, so we prefer to do this when all types are legal. 10891 if (!DCI.isAfterLegalizeVectorOps()) 10892 return SDValue(); 10893 10894 // If all users of SETCC extend its value to a legal integer type 10895 // then we replace SETCC with a subtraction 10896 for (SDNode::use_iterator UI = N->use_begin(), 10897 UE = N->use_end(); UI != UE; ++UI) { 10898 if (UI->getOpcode() != ISD::ZERO_EXTEND) 10899 return SDValue(); 10900 } 10901 10902 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10903 auto OpSize = N->getOperand(0).getValueSizeInBits(); 10904 10905 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 10906 10907 if (OpSize < Size) { 10908 switch (CC) { 10909 default: break; 10910 case ISD::SETULT: 10911 return generateEquivalentSub(N, Size, false, false, DL, DAG); 10912 case ISD::SETULE: 10913 return generateEquivalentSub(N, Size, true, true, DL, DAG); 10914 case ISD::SETUGT: 10915 return generateEquivalentSub(N, Size, false, true, DL, DAG); 10916 case ISD::SETUGE: 10917 return generateEquivalentSub(N, Size, true, false, DL, DAG); 10918 } 10919 } 10920 10921 return SDValue(); 10922 } 10923 10924 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 10925 DAGCombinerInfo &DCI) const { 10926 SelectionDAG &DAG = DCI.DAG; 10927 SDLoc dl(N); 10928 10929 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 10930 // If we're tracking CR bits, we need to be careful that we don't have: 10931 // trunc(binary-ops(zext(x), zext(y))) 10932 // or 10933 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 10934 // such that we're unnecessarily moving things into GPRs when it would be 10935 // better to keep them in CR bits. 10936 10937 // Note that trunc here can be an actual i1 trunc, or can be the effective 10938 // truncation that comes from a setcc or select_cc. 10939 if (N->getOpcode() == ISD::TRUNCATE && 10940 N->getValueType(0) != MVT::i1) 10941 return SDValue(); 10942 10943 if (N->getOperand(0).getValueType() != MVT::i32 && 10944 N->getOperand(0).getValueType() != MVT::i64) 10945 return SDValue(); 10946 10947 if (N->getOpcode() == ISD::SETCC || 10948 N->getOpcode() == ISD::SELECT_CC) { 10949 // If we're looking at a comparison, then we need to make sure that the 10950 // high bits (all except for the first) don't matter the result. 10951 ISD::CondCode CC = 10952 cast<CondCodeSDNode>(N->getOperand( 10953 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 10954 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 10955 10956 if (ISD::isSignedIntSetCC(CC)) { 10957 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 10958 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 10959 return SDValue(); 10960 } else if (ISD::isUnsignedIntSetCC(CC)) { 10961 if (!DAG.MaskedValueIsZero(N->getOperand(0), 10962 APInt::getHighBitsSet(OpBits, OpBits-1)) || 10963 !DAG.MaskedValueIsZero(N->getOperand(1), 10964 APInt::getHighBitsSet(OpBits, OpBits-1))) 10965 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 10966 : SDValue()); 10967 } else { 10968 // This is neither a signed nor an unsigned comparison, just make sure 10969 // that the high bits are equal. 10970 KnownBits Op1Known, Op2Known; 10971 DAG.computeKnownBits(N->getOperand(0), Op1Known); 10972 DAG.computeKnownBits(N->getOperand(1), Op2Known); 10973 10974 // We don't really care about what is known about the first bit (if 10975 // anything), so clear it in all masks prior to comparing them. 10976 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 10977 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 10978 10979 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 10980 return SDValue(); 10981 } 10982 } 10983 10984 // We now know that the higher-order bits are irrelevant, we just need to 10985 // make sure that all of the intermediate operations are bit operations, and 10986 // all inputs are extensions. 10987 if (N->getOperand(0).getOpcode() != ISD::AND && 10988 N->getOperand(0).getOpcode() != ISD::OR && 10989 N->getOperand(0).getOpcode() != ISD::XOR && 10990 N->getOperand(0).getOpcode() != ISD::SELECT && 10991 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 10992 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 10993 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 10994 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 10995 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 10996 return SDValue(); 10997 10998 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 10999 N->getOperand(1).getOpcode() != ISD::AND && 11000 N->getOperand(1).getOpcode() != ISD::OR && 11001 N->getOperand(1).getOpcode() != ISD::XOR && 11002 N->getOperand(1).getOpcode() != ISD::SELECT && 11003 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11004 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11005 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11006 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11007 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11008 return SDValue(); 11009 11010 SmallVector<SDValue, 4> Inputs; 11011 SmallVector<SDValue, 8> BinOps, PromOps; 11012 SmallPtrSet<SDNode *, 16> Visited; 11013 11014 for (unsigned i = 0; i < 2; ++i) { 11015 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11016 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11017 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11018 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11019 isa<ConstantSDNode>(N->getOperand(i))) 11020 Inputs.push_back(N->getOperand(i)); 11021 else 11022 BinOps.push_back(N->getOperand(i)); 11023 11024 if (N->getOpcode() == ISD::TRUNCATE) 11025 break; 11026 } 11027 11028 // Visit all inputs, collect all binary operations (and, or, xor and 11029 // select) that are all fed by extensions. 11030 while (!BinOps.empty()) { 11031 SDValue BinOp = BinOps.back(); 11032 BinOps.pop_back(); 11033 11034 if (!Visited.insert(BinOp.getNode()).second) 11035 continue; 11036 11037 PromOps.push_back(BinOp); 11038 11039 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11040 // The condition of the select is not promoted. 11041 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11042 continue; 11043 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11044 continue; 11045 11046 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11047 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11048 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11049 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11050 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11051 Inputs.push_back(BinOp.getOperand(i)); 11052 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11053 BinOp.getOperand(i).getOpcode() == ISD::OR || 11054 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11055 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11056 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11057 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11058 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11059 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11060 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11061 BinOps.push_back(BinOp.getOperand(i)); 11062 } else { 11063 // We have an input that is not an extension or another binary 11064 // operation; we'll abort this transformation. 11065 return SDValue(); 11066 } 11067 } 11068 } 11069 11070 // Make sure that this is a self-contained cluster of operations (which 11071 // is not quite the same thing as saying that everything has only one 11072 // use). 11073 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11074 if (isa<ConstantSDNode>(Inputs[i])) 11075 continue; 11076 11077 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11078 UE = Inputs[i].getNode()->use_end(); 11079 UI != UE; ++UI) { 11080 SDNode *User = *UI; 11081 if (User != N && !Visited.count(User)) 11082 return SDValue(); 11083 11084 // Make sure that we're not going to promote the non-output-value 11085 // operand(s) or SELECT or SELECT_CC. 11086 // FIXME: Although we could sometimes handle this, and it does occur in 11087 // practice that one of the condition inputs to the select is also one of 11088 // the outputs, we currently can't deal with this. 11089 if (User->getOpcode() == ISD::SELECT) { 11090 if (User->getOperand(0) == Inputs[i]) 11091 return SDValue(); 11092 } else if (User->getOpcode() == ISD::SELECT_CC) { 11093 if (User->getOperand(0) == Inputs[i] || 11094 User->getOperand(1) == Inputs[i]) 11095 return SDValue(); 11096 } 11097 } 11098 } 11099 11100 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11101 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11102 UE = PromOps[i].getNode()->use_end(); 11103 UI != UE; ++UI) { 11104 SDNode *User = *UI; 11105 if (User != N && !Visited.count(User)) 11106 return SDValue(); 11107 11108 // Make sure that we're not going to promote the non-output-value 11109 // operand(s) or SELECT or SELECT_CC. 11110 // FIXME: Although we could sometimes handle this, and it does occur in 11111 // practice that one of the condition inputs to the select is also one of 11112 // the outputs, we currently can't deal with this. 11113 if (User->getOpcode() == ISD::SELECT) { 11114 if (User->getOperand(0) == PromOps[i]) 11115 return SDValue(); 11116 } else if (User->getOpcode() == ISD::SELECT_CC) { 11117 if (User->getOperand(0) == PromOps[i] || 11118 User->getOperand(1) == PromOps[i]) 11119 return SDValue(); 11120 } 11121 } 11122 } 11123 11124 // Replace all inputs with the extension operand. 11125 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11126 // Constants may have users outside the cluster of to-be-promoted nodes, 11127 // and so we need to replace those as we do the promotions. 11128 if (isa<ConstantSDNode>(Inputs[i])) 11129 continue; 11130 else 11131 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 11132 } 11133 11134 std::list<HandleSDNode> PromOpHandles; 11135 for (auto &PromOp : PromOps) 11136 PromOpHandles.emplace_back(PromOp); 11137 11138 // Replace all operations (these are all the same, but have a different 11139 // (i1) return type). DAG.getNode will validate that the types of 11140 // a binary operator match, so go through the list in reverse so that 11141 // we've likely promoted both operands first. Any intermediate truncations or 11142 // extensions disappear. 11143 while (!PromOpHandles.empty()) { 11144 SDValue PromOp = PromOpHandles.back().getValue(); 11145 PromOpHandles.pop_back(); 11146 11147 if (PromOp.getOpcode() == ISD::TRUNCATE || 11148 PromOp.getOpcode() == ISD::SIGN_EXTEND || 11149 PromOp.getOpcode() == ISD::ZERO_EXTEND || 11150 PromOp.getOpcode() == ISD::ANY_EXTEND) { 11151 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 11152 PromOp.getOperand(0).getValueType() != MVT::i1) { 11153 // The operand is not yet ready (see comment below). 11154 PromOpHandles.emplace_front(PromOp); 11155 continue; 11156 } 11157 11158 SDValue RepValue = PromOp.getOperand(0); 11159 if (isa<ConstantSDNode>(RepValue)) 11160 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 11161 11162 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 11163 continue; 11164 } 11165 11166 unsigned C; 11167 switch (PromOp.getOpcode()) { 11168 default: C = 0; break; 11169 case ISD::SELECT: C = 1; break; 11170 case ISD::SELECT_CC: C = 2; break; 11171 } 11172 11173 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11174 PromOp.getOperand(C).getValueType() != MVT::i1) || 11175 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11176 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 11177 // The to-be-promoted operands of this node have not yet been 11178 // promoted (this should be rare because we're going through the 11179 // list backward, but if one of the operands has several users in 11180 // this cluster of to-be-promoted nodes, it is possible). 11181 PromOpHandles.emplace_front(PromOp); 11182 continue; 11183 } 11184 11185 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11186 PromOp.getNode()->op_end()); 11187 11188 // If there are any constant inputs, make sure they're replaced now. 11189 for (unsigned i = 0; i < 2; ++i) 11190 if (isa<ConstantSDNode>(Ops[C+i])) 11191 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 11192 11193 DAG.ReplaceAllUsesOfValueWith(PromOp, 11194 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 11195 } 11196 11197 // Now we're left with the initial truncation itself. 11198 if (N->getOpcode() == ISD::TRUNCATE) 11199 return N->getOperand(0); 11200 11201 // Otherwise, this is a comparison. The operands to be compared have just 11202 // changed type (to i1), but everything else is the same. 11203 return SDValue(N, 0); 11204 } 11205 11206 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 11207 DAGCombinerInfo &DCI) const { 11208 SelectionDAG &DAG = DCI.DAG; 11209 SDLoc dl(N); 11210 11211 // If we're tracking CR bits, we need to be careful that we don't have: 11212 // zext(binary-ops(trunc(x), trunc(y))) 11213 // or 11214 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 11215 // such that we're unnecessarily moving things into CR bits that can more 11216 // efficiently stay in GPRs. Note that if we're not certain that the high 11217 // bits are set as required by the final extension, we still may need to do 11218 // some masking to get the proper behavior. 11219 11220 // This same functionality is important on PPC64 when dealing with 11221 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 11222 // the return values of functions. Because it is so similar, it is handled 11223 // here as well. 11224 11225 if (N->getValueType(0) != MVT::i32 && 11226 N->getValueType(0) != MVT::i64) 11227 return SDValue(); 11228 11229 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 11230 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 11231 return SDValue(); 11232 11233 if (N->getOperand(0).getOpcode() != ISD::AND && 11234 N->getOperand(0).getOpcode() != ISD::OR && 11235 N->getOperand(0).getOpcode() != ISD::XOR && 11236 N->getOperand(0).getOpcode() != ISD::SELECT && 11237 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 11238 return SDValue(); 11239 11240 SmallVector<SDValue, 4> Inputs; 11241 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 11242 SmallPtrSet<SDNode *, 16> Visited; 11243 11244 // Visit all inputs, collect all binary operations (and, or, xor and 11245 // select) that are all fed by truncations. 11246 while (!BinOps.empty()) { 11247 SDValue BinOp = BinOps.back(); 11248 BinOps.pop_back(); 11249 11250 if (!Visited.insert(BinOp.getNode()).second) 11251 continue; 11252 11253 PromOps.push_back(BinOp); 11254 11255 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11256 // The condition of the select is not promoted. 11257 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11258 continue; 11259 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11260 continue; 11261 11262 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11263 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11264 Inputs.push_back(BinOp.getOperand(i)); 11265 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11266 BinOp.getOperand(i).getOpcode() == ISD::OR || 11267 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11268 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11269 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 11270 BinOps.push_back(BinOp.getOperand(i)); 11271 } else { 11272 // We have an input that is not a truncation or another binary 11273 // operation; we'll abort this transformation. 11274 return SDValue(); 11275 } 11276 } 11277 } 11278 11279 // The operands of a select that must be truncated when the select is 11280 // promoted because the operand is actually part of the to-be-promoted set. 11281 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 11282 11283 // Make sure that this is a self-contained cluster of operations (which 11284 // is not quite the same thing as saying that everything has only one 11285 // use). 11286 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11287 if (isa<ConstantSDNode>(Inputs[i])) 11288 continue; 11289 11290 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11291 UE = Inputs[i].getNode()->use_end(); 11292 UI != UE; ++UI) { 11293 SDNode *User = *UI; 11294 if (User != N && !Visited.count(User)) 11295 return SDValue(); 11296 11297 // If we're going to promote the non-output-value operand(s) or SELECT or 11298 // SELECT_CC, record them for truncation. 11299 if (User->getOpcode() == ISD::SELECT) { 11300 if (User->getOperand(0) == Inputs[i]) 11301 SelectTruncOp[0].insert(std::make_pair(User, 11302 User->getOperand(0).getValueType())); 11303 } else if (User->getOpcode() == ISD::SELECT_CC) { 11304 if (User->getOperand(0) == Inputs[i]) 11305 SelectTruncOp[0].insert(std::make_pair(User, 11306 User->getOperand(0).getValueType())); 11307 if (User->getOperand(1) == Inputs[i]) 11308 SelectTruncOp[1].insert(std::make_pair(User, 11309 User->getOperand(1).getValueType())); 11310 } 11311 } 11312 } 11313 11314 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 11315 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 11316 UE = PromOps[i].getNode()->use_end(); 11317 UI != UE; ++UI) { 11318 SDNode *User = *UI; 11319 if (User != N && !Visited.count(User)) 11320 return SDValue(); 11321 11322 // If we're going to promote the non-output-value operand(s) or SELECT or 11323 // SELECT_CC, record them for truncation. 11324 if (User->getOpcode() == ISD::SELECT) { 11325 if (User->getOperand(0) == PromOps[i]) 11326 SelectTruncOp[0].insert(std::make_pair(User, 11327 User->getOperand(0).getValueType())); 11328 } else if (User->getOpcode() == ISD::SELECT_CC) { 11329 if (User->getOperand(0) == PromOps[i]) 11330 SelectTruncOp[0].insert(std::make_pair(User, 11331 User->getOperand(0).getValueType())); 11332 if (User->getOperand(1) == PromOps[i]) 11333 SelectTruncOp[1].insert(std::make_pair(User, 11334 User->getOperand(1).getValueType())); 11335 } 11336 } 11337 } 11338 11339 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 11340 bool ReallyNeedsExt = false; 11341 if (N->getOpcode() != ISD::ANY_EXTEND) { 11342 // If all of the inputs are not already sign/zero extended, then 11343 // we'll still need to do that at the end. 11344 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11345 if (isa<ConstantSDNode>(Inputs[i])) 11346 continue; 11347 11348 unsigned OpBits = 11349 Inputs[i].getOperand(0).getValueSizeInBits(); 11350 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 11351 11352 if ((N->getOpcode() == ISD::ZERO_EXTEND && 11353 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 11354 APInt::getHighBitsSet(OpBits, 11355 OpBits-PromBits))) || 11356 (N->getOpcode() == ISD::SIGN_EXTEND && 11357 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 11358 (OpBits-(PromBits-1)))) { 11359 ReallyNeedsExt = true; 11360 break; 11361 } 11362 } 11363 } 11364 11365 // Replace all inputs, either with the truncation operand, or a 11366 // truncation or extension to the final output type. 11367 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11368 // Constant inputs need to be replaced with the to-be-promoted nodes that 11369 // use them because they might have users outside of the cluster of 11370 // promoted nodes. 11371 if (isa<ConstantSDNode>(Inputs[i])) 11372 continue; 11373 11374 SDValue InSrc = Inputs[i].getOperand(0); 11375 if (Inputs[i].getValueType() == N->getValueType(0)) 11376 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 11377 else if (N->getOpcode() == ISD::SIGN_EXTEND) 11378 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11379 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 11380 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11381 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11382 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 11383 else 11384 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 11385 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 11386 } 11387 11388 std::list<HandleSDNode> PromOpHandles; 11389 for (auto &PromOp : PromOps) 11390 PromOpHandles.emplace_back(PromOp); 11391 11392 // Replace all operations (these are all the same, but have a different 11393 // (promoted) return type). DAG.getNode will validate that the types of 11394 // a binary operator match, so go through the list in reverse so that 11395 // we've likely promoted both operands first. 11396 while (!PromOpHandles.empty()) { 11397 SDValue PromOp = PromOpHandles.back().getValue(); 11398 PromOpHandles.pop_back(); 11399 11400 unsigned C; 11401 switch (PromOp.getOpcode()) { 11402 default: C = 0; break; 11403 case ISD::SELECT: C = 1; break; 11404 case ISD::SELECT_CC: C = 2; break; 11405 } 11406 11407 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 11408 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 11409 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 11410 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 11411 // The to-be-promoted operands of this node have not yet been 11412 // promoted (this should be rare because we're going through the 11413 // list backward, but if one of the operands has several users in 11414 // this cluster of to-be-promoted nodes, it is possible). 11415 PromOpHandles.emplace_front(PromOp); 11416 continue; 11417 } 11418 11419 // For SELECT and SELECT_CC nodes, we do a similar check for any 11420 // to-be-promoted comparison inputs. 11421 if (PromOp.getOpcode() == ISD::SELECT || 11422 PromOp.getOpcode() == ISD::SELECT_CC) { 11423 if ((SelectTruncOp[0].count(PromOp.getNode()) && 11424 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 11425 (SelectTruncOp[1].count(PromOp.getNode()) && 11426 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 11427 PromOpHandles.emplace_front(PromOp); 11428 continue; 11429 } 11430 } 11431 11432 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 11433 PromOp.getNode()->op_end()); 11434 11435 // If this node has constant inputs, then they'll need to be promoted here. 11436 for (unsigned i = 0; i < 2; ++i) { 11437 if (!isa<ConstantSDNode>(Ops[C+i])) 11438 continue; 11439 if (Ops[C+i].getValueType() == N->getValueType(0)) 11440 continue; 11441 11442 if (N->getOpcode() == ISD::SIGN_EXTEND) 11443 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11444 else if (N->getOpcode() == ISD::ZERO_EXTEND) 11445 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11446 else 11447 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 11448 } 11449 11450 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 11451 // truncate them again to the original value type. 11452 if (PromOp.getOpcode() == ISD::SELECT || 11453 PromOp.getOpcode() == ISD::SELECT_CC) { 11454 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 11455 if (SI0 != SelectTruncOp[0].end()) 11456 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 11457 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 11458 if (SI1 != SelectTruncOp[1].end()) 11459 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 11460 } 11461 11462 DAG.ReplaceAllUsesOfValueWith(PromOp, 11463 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 11464 } 11465 11466 // Now we're left with the initial extension itself. 11467 if (!ReallyNeedsExt) 11468 return N->getOperand(0); 11469 11470 // To zero extend, just mask off everything except for the first bit (in the 11471 // i1 case). 11472 if (N->getOpcode() == ISD::ZERO_EXTEND) 11473 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 11474 DAG.getConstant(APInt::getLowBitsSet( 11475 N->getValueSizeInBits(0), PromBits), 11476 dl, N->getValueType(0))); 11477 11478 assert(N->getOpcode() == ISD::SIGN_EXTEND && 11479 "Invalid extension type"); 11480 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 11481 SDValue ShiftCst = 11482 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 11483 return DAG.getNode( 11484 ISD::SRA, dl, N->getValueType(0), 11485 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 11486 ShiftCst); 11487 } 11488 11489 /// \brief Reduces the number of fp-to-int conversion when building a vector. 11490 /// 11491 /// If this vector is built out of floating to integer conversions, 11492 /// transform it to a vector built out of floating point values followed by a 11493 /// single floating to integer conversion of the vector. 11494 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 11495 /// becomes (fptosi (build_vector ($A, $B, ...))) 11496 SDValue PPCTargetLowering:: 11497 combineElementTruncationToVectorTruncation(SDNode *N, 11498 DAGCombinerInfo &DCI) const { 11499 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11500 "Should be called with a BUILD_VECTOR node"); 11501 11502 SelectionDAG &DAG = DCI.DAG; 11503 SDLoc dl(N); 11504 11505 SDValue FirstInput = N->getOperand(0); 11506 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 11507 "The input operand must be an fp-to-int conversion."); 11508 11509 // This combine happens after legalization so the fp_to_[su]i nodes are 11510 // already converted to PPCSISD nodes. 11511 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 11512 if (FirstConversion == PPCISD::FCTIDZ || 11513 FirstConversion == PPCISD::FCTIDUZ || 11514 FirstConversion == PPCISD::FCTIWZ || 11515 FirstConversion == PPCISD::FCTIWUZ) { 11516 bool IsSplat = true; 11517 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 11518 FirstConversion == PPCISD::FCTIWUZ; 11519 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 11520 SmallVector<SDValue, 4> Ops; 11521 EVT TargetVT = N->getValueType(0); 11522 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11523 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR) 11524 return SDValue(); 11525 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode(); 11526 if (NextConversion != FirstConversion) 11527 return SDValue(); 11528 if (N->getOperand(i) != FirstInput) 11529 IsSplat = false; 11530 } 11531 11532 // If this is a splat, we leave it as-is since there will be only a single 11533 // fp-to-int conversion followed by a splat of the integer. This is better 11534 // for 32-bit and smaller ints and neutral for 64-bit ints. 11535 if (IsSplat) 11536 return SDValue(); 11537 11538 // Now that we know we have the right type of node, get its operands 11539 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 11540 SDValue In = N->getOperand(i).getOperand(0); 11541 // For 32-bit values, we need to add an FP_ROUND node. 11542 if (Is32Bit) { 11543 if (In.isUndef()) 11544 Ops.push_back(DAG.getUNDEF(SrcVT)); 11545 else { 11546 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 11547 MVT::f32, In.getOperand(0), 11548 DAG.getIntPtrConstant(1, dl)); 11549 Ops.push_back(Trunc); 11550 } 11551 } else 11552 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 11553 } 11554 11555 unsigned Opcode; 11556 if (FirstConversion == PPCISD::FCTIDZ || 11557 FirstConversion == PPCISD::FCTIWZ) 11558 Opcode = ISD::FP_TO_SINT; 11559 else 11560 Opcode = ISD::FP_TO_UINT; 11561 11562 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 11563 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 11564 return DAG.getNode(Opcode, dl, TargetVT, BV); 11565 } 11566 return SDValue(); 11567 } 11568 11569 /// \brief Reduce the number of loads when building a vector. 11570 /// 11571 /// Building a vector out of multiple loads can be converted to a load 11572 /// of the vector type if the loads are consecutive. If the loads are 11573 /// consecutive but in descending order, a shuffle is added at the end 11574 /// to reorder the vector. 11575 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 11576 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11577 "Should be called with a BUILD_VECTOR node"); 11578 11579 SDLoc dl(N); 11580 bool InputsAreConsecutiveLoads = true; 11581 bool InputsAreReverseConsecutive = true; 11582 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8; 11583 SDValue FirstInput = N->getOperand(0); 11584 bool IsRoundOfExtLoad = false; 11585 11586 if (FirstInput.getOpcode() == ISD::FP_ROUND && 11587 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 11588 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 11589 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 11590 } 11591 // Not a build vector of (possibly fp_rounded) loads. 11592 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) 11593 return SDValue(); 11594 11595 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 11596 // If any inputs are fp_round(extload), they all must be. 11597 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 11598 return SDValue(); 11599 11600 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 11601 N->getOperand(i); 11602 if (NextInput.getOpcode() != ISD::LOAD) 11603 return SDValue(); 11604 11605 SDValue PreviousInput = 11606 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 11607 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 11608 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 11609 11610 // If any inputs are fp_round(extload), they all must be. 11611 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 11612 return SDValue(); 11613 11614 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 11615 InputsAreConsecutiveLoads = false; 11616 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 11617 InputsAreReverseConsecutive = false; 11618 11619 // Exit early if the loads are neither consecutive nor reverse consecutive. 11620 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 11621 return SDValue(); 11622 } 11623 11624 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 11625 "The loads cannot be both consecutive and reverse consecutive."); 11626 11627 SDValue FirstLoadOp = 11628 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 11629 SDValue LastLoadOp = 11630 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 11631 N->getOperand(N->getNumOperands()-1); 11632 11633 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 11634 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 11635 if (InputsAreConsecutiveLoads) { 11636 assert(LD1 && "Input needs to be a LoadSDNode."); 11637 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 11638 LD1->getBasePtr(), LD1->getPointerInfo(), 11639 LD1->getAlignment()); 11640 } 11641 if (InputsAreReverseConsecutive) { 11642 assert(LDL && "Input needs to be a LoadSDNode."); 11643 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 11644 LDL->getBasePtr(), LDL->getPointerInfo(), 11645 LDL->getAlignment()); 11646 SmallVector<int, 16> Ops; 11647 for (int i = N->getNumOperands() - 1; i >= 0; i--) 11648 Ops.push_back(i); 11649 11650 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 11651 DAG.getUNDEF(N->getValueType(0)), Ops); 11652 } 11653 return SDValue(); 11654 } 11655 11656 // This function adds the required vector_shuffle needed to get 11657 // the elements of the vector extract in the correct position 11658 // as specified by the CorrectElems encoding. 11659 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 11660 SDValue Input, uint64_t Elems, 11661 uint64_t CorrectElems) { 11662 SDLoc dl(N); 11663 11664 unsigned NumElems = Input.getValueType().getVectorNumElements(); 11665 SmallVector<int, 16> ShuffleMask(NumElems, -1); 11666 11667 // Knowing the element indices being extracted from the original 11668 // vector and the order in which they're being inserted, just put 11669 // them at element indices required for the instruction. 11670 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11671 if (DAG.getDataLayout().isLittleEndian()) 11672 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 11673 else 11674 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 11675 CorrectElems = CorrectElems >> 8; 11676 Elems = Elems >> 8; 11677 } 11678 11679 SDValue Shuffle = 11680 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 11681 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 11682 11683 EVT Ty = N->getValueType(0); 11684 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 11685 return BV; 11686 } 11687 11688 // Look for build vector patterns where input operands come from sign 11689 // extended vector_extract elements of specific indices. If the correct indices 11690 // aren't used, add a vector shuffle to fix up the indices and create a new 11691 // PPCISD:SExtVElems node which selects the vector sign extend instructions 11692 // during instruction selection. 11693 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 11694 // This array encodes the indices that the vector sign extend instructions 11695 // extract from when extending from one type to another for both BE and LE. 11696 // The right nibble of each byte corresponds to the LE incides. 11697 // and the left nibble of each byte corresponds to the BE incides. 11698 // For example: 0x3074B8FC byte->word 11699 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 11700 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 11701 // For example: 0x000070F8 byte->double word 11702 // For LE: the allowed indices are: 0x0,0x8 11703 // For BE: the allowed indices are: 0x7,0xF 11704 uint64_t TargetElems[] = { 11705 0x3074B8FC, // b->w 11706 0x000070F8, // b->d 11707 0x10325476, // h->w 11708 0x00003074, // h->d 11709 0x00001032, // w->d 11710 }; 11711 11712 uint64_t Elems = 0; 11713 int Index; 11714 SDValue Input; 11715 11716 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 11717 if (!Op) 11718 return false; 11719 if (Op.getOpcode() != ISD::SIGN_EXTEND) 11720 return false; 11721 11722 SDValue Extract = Op.getOperand(0); 11723 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11724 return false; 11725 11726 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 11727 if (!ExtOp) 11728 return false; 11729 11730 Index = ExtOp->getZExtValue(); 11731 if (Input && Input != Extract.getOperand(0)) 11732 return false; 11733 11734 if (!Input) 11735 Input = Extract.getOperand(0); 11736 11737 Elems = Elems << 8; 11738 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 11739 Elems |= Index; 11740 11741 return true; 11742 }; 11743 11744 // If the build vector operands aren't sign extended vector extracts, 11745 // of the same input vector, then return. 11746 for (unsigned i = 0; i < N->getNumOperands(); i++) { 11747 if (!isSExtOfVecExtract(N->getOperand(i))) { 11748 return SDValue(); 11749 } 11750 } 11751 11752 // If the vector extract indicies are not correct, add the appropriate 11753 // vector_shuffle. 11754 int TgtElemArrayIdx; 11755 int InputSize = Input.getValueType().getScalarSizeInBits(); 11756 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 11757 if (InputSize + OutputSize == 40) 11758 TgtElemArrayIdx = 0; 11759 else if (InputSize + OutputSize == 72) 11760 TgtElemArrayIdx = 1; 11761 else if (InputSize + OutputSize == 48) 11762 TgtElemArrayIdx = 2; 11763 else if (InputSize + OutputSize == 80) 11764 TgtElemArrayIdx = 3; 11765 else if (InputSize + OutputSize == 96) 11766 TgtElemArrayIdx = 4; 11767 else 11768 return SDValue(); 11769 11770 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 11771 CorrectElems = DAG.getDataLayout().isLittleEndian() 11772 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 11773 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 11774 if (Elems != CorrectElems) { 11775 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 11776 } 11777 11778 // Regular lowering will catch cases where a shuffle is not needed. 11779 return SDValue(); 11780 } 11781 11782 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 11783 DAGCombinerInfo &DCI) const { 11784 assert(N->getOpcode() == ISD::BUILD_VECTOR && 11785 "Should be called with a BUILD_VECTOR node"); 11786 11787 SelectionDAG &DAG = DCI.DAG; 11788 SDLoc dl(N); 11789 11790 if (!Subtarget.hasVSX()) 11791 return SDValue(); 11792 11793 // The target independent DAG combiner will leave a build_vector of 11794 // float-to-int conversions intact. We can generate MUCH better code for 11795 // a float-to-int conversion of a vector of floats. 11796 SDValue FirstInput = N->getOperand(0); 11797 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 11798 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 11799 if (Reduced) 11800 return Reduced; 11801 } 11802 11803 // If we're building a vector out of consecutive loads, just load that 11804 // vector type. 11805 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 11806 if (Reduced) 11807 return Reduced; 11808 11809 // If we're building a vector out of extended elements from another vector 11810 // we have P9 vector integer extend instructions. 11811 if (Subtarget.hasP9Altivec()) { 11812 Reduced = combineBVOfVecSExt(N, DAG); 11813 if (Reduced) 11814 return Reduced; 11815 } 11816 11817 11818 if (N->getValueType(0) != MVT::v2f64) 11819 return SDValue(); 11820 11821 // Looking for: 11822 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 11823 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 11824 FirstInput.getOpcode() != ISD::UINT_TO_FP) 11825 return SDValue(); 11826 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 11827 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 11828 return SDValue(); 11829 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 11830 return SDValue(); 11831 11832 SDValue Ext1 = FirstInput.getOperand(0); 11833 SDValue Ext2 = N->getOperand(1).getOperand(0); 11834 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11835 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11836 return SDValue(); 11837 11838 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 11839 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 11840 if (!Ext1Op || !Ext2Op) 11841 return SDValue(); 11842 if (Ext1.getValueType() != MVT::i32 || 11843 Ext2.getValueType() != MVT::i32) 11844 if (Ext1.getOperand(0) != Ext2.getOperand(0)) 11845 return SDValue(); 11846 11847 int FirstElem = Ext1Op->getZExtValue(); 11848 int SecondElem = Ext2Op->getZExtValue(); 11849 int SubvecIdx; 11850 if (FirstElem == 0 && SecondElem == 1) 11851 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 11852 else if (FirstElem == 2 && SecondElem == 3) 11853 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 11854 else 11855 return SDValue(); 11856 11857 SDValue SrcVec = Ext1.getOperand(0); 11858 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 11859 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 11860 return DAG.getNode(NodeType, dl, MVT::v2f64, 11861 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 11862 } 11863 11864 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 11865 DAGCombinerInfo &DCI) const { 11866 assert((N->getOpcode() == ISD::SINT_TO_FP || 11867 N->getOpcode() == ISD::UINT_TO_FP) && 11868 "Need an int -> FP conversion node here"); 11869 11870 if (useSoftFloat() || !Subtarget.has64BitSupport()) 11871 return SDValue(); 11872 11873 SelectionDAG &DAG = DCI.DAG; 11874 SDLoc dl(N); 11875 SDValue Op(N, 0); 11876 11877 SDValue FirstOperand(Op.getOperand(0)); 11878 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 11879 (FirstOperand.getValueType() == MVT::i8 || 11880 FirstOperand.getValueType() == MVT::i16); 11881 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 11882 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 11883 bool DstDouble = Op.getValueType() == MVT::f64; 11884 unsigned ConvOp = Signed ? 11885 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 11886 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 11887 SDValue WidthConst = 11888 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 11889 dl, false); 11890 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 11891 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 11892 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 11893 DAG.getVTList(MVT::f64, MVT::Other), 11894 Ops, MVT::i8, LDN->getMemOperand()); 11895 11896 // For signed conversion, we need to sign-extend the value in the VSR 11897 if (Signed) { 11898 SDValue ExtOps[] = { Ld, WidthConst }; 11899 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 11900 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 11901 } else 11902 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 11903 } 11904 11905 // Don't handle ppc_fp128 here or i1 conversions. 11906 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 11907 return SDValue(); 11908 if (Op.getOperand(0).getValueType() == MVT::i1) 11909 return SDValue(); 11910 11911 // For i32 intermediate values, unfortunately, the conversion functions 11912 // leave the upper 32 bits of the value are undefined. Within the set of 11913 // scalar instructions, we have no method for zero- or sign-extending the 11914 // value. Thus, we cannot handle i32 intermediate values here. 11915 if (Op.getOperand(0).getValueType() == MVT::i32) 11916 return SDValue(); 11917 11918 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 11919 "UINT_TO_FP is supported only with FPCVT"); 11920 11921 // If we have FCFIDS, then use it when converting to single-precision. 11922 // Otherwise, convert to double-precision and then round. 11923 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11924 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 11925 : PPCISD::FCFIDS) 11926 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 11927 : PPCISD::FCFID); 11928 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 11929 ? MVT::f32 11930 : MVT::f64; 11931 11932 // If we're converting from a float, to an int, and back to a float again, 11933 // then we don't need the store/load pair at all. 11934 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 11935 Subtarget.hasFPCVT()) || 11936 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 11937 SDValue Src = Op.getOperand(0).getOperand(0); 11938 if (Src.getValueType() == MVT::f32) { 11939 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 11940 DCI.AddToWorklist(Src.getNode()); 11941 } else if (Src.getValueType() != MVT::f64) { 11942 // Make sure that we don't pick up a ppc_fp128 source value. 11943 return SDValue(); 11944 } 11945 11946 unsigned FCTOp = 11947 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 11948 PPCISD::FCTIDUZ; 11949 11950 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 11951 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 11952 11953 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 11954 FP = DAG.getNode(ISD::FP_ROUND, dl, 11955 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 11956 DCI.AddToWorklist(FP.getNode()); 11957 } 11958 11959 return FP; 11960 } 11961 11962 return SDValue(); 11963 } 11964 11965 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 11966 // builtins) into loads with swaps. 11967 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 11968 DAGCombinerInfo &DCI) const { 11969 SelectionDAG &DAG = DCI.DAG; 11970 SDLoc dl(N); 11971 SDValue Chain; 11972 SDValue Base; 11973 MachineMemOperand *MMO; 11974 11975 switch (N->getOpcode()) { 11976 default: 11977 llvm_unreachable("Unexpected opcode for little endian VSX load"); 11978 case ISD::LOAD: { 11979 LoadSDNode *LD = cast<LoadSDNode>(N); 11980 Chain = LD->getChain(); 11981 Base = LD->getBasePtr(); 11982 MMO = LD->getMemOperand(); 11983 // If the MMO suggests this isn't a load of a full vector, leave 11984 // things alone. For a built-in, we have to make the change for 11985 // correctness, so if there is a size problem that will be a bug. 11986 if (MMO->getSize() < 16) 11987 return SDValue(); 11988 break; 11989 } 11990 case ISD::INTRINSIC_W_CHAIN: { 11991 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 11992 Chain = Intrin->getChain(); 11993 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 11994 // us what we want. Get operand 2 instead. 11995 Base = Intrin->getOperand(2); 11996 MMO = Intrin->getMemOperand(); 11997 break; 11998 } 11999 } 12000 12001 MVT VecTy = N->getValueType(0).getSimpleVT(); 12002 12003 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12004 // aligned and the type is a vector with elements up to 4 bytes 12005 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12006 && VecTy.getScalarSizeInBits() <= 32 ) { 12007 return SDValue(); 12008 } 12009 12010 SDValue LoadOps[] = { Chain, Base }; 12011 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12012 DAG.getVTList(MVT::v2f64, MVT::Other), 12013 LoadOps, MVT::v2f64, MMO); 12014 12015 DCI.AddToWorklist(Load.getNode()); 12016 Chain = Load.getValue(1); 12017 SDValue Swap = DAG.getNode( 12018 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12019 DCI.AddToWorklist(Swap.getNode()); 12020 12021 // Add a bitcast if the resulting load type doesn't match v2f64. 12022 if (VecTy != MVT::v2f64) { 12023 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12024 DCI.AddToWorklist(N.getNode()); 12025 // Package {bitcast value, swap's chain} to match Load's shape. 12026 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12027 N, Swap.getValue(1)); 12028 } 12029 12030 return Swap; 12031 } 12032 12033 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12034 // builtins) into stores with swaps. 12035 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12036 DAGCombinerInfo &DCI) const { 12037 SelectionDAG &DAG = DCI.DAG; 12038 SDLoc dl(N); 12039 SDValue Chain; 12040 SDValue Base; 12041 unsigned SrcOpnd; 12042 MachineMemOperand *MMO; 12043 12044 switch (N->getOpcode()) { 12045 default: 12046 llvm_unreachable("Unexpected opcode for little endian VSX store"); 12047 case ISD::STORE: { 12048 StoreSDNode *ST = cast<StoreSDNode>(N); 12049 Chain = ST->getChain(); 12050 Base = ST->getBasePtr(); 12051 MMO = ST->getMemOperand(); 12052 SrcOpnd = 1; 12053 // If the MMO suggests this isn't a store of a full vector, leave 12054 // things alone. For a built-in, we have to make the change for 12055 // correctness, so if there is a size problem that will be a bug. 12056 if (MMO->getSize() < 16) 12057 return SDValue(); 12058 break; 12059 } 12060 case ISD::INTRINSIC_VOID: { 12061 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12062 Chain = Intrin->getChain(); 12063 // Intrin->getBasePtr() oddly does not get what we want. 12064 Base = Intrin->getOperand(3); 12065 MMO = Intrin->getMemOperand(); 12066 SrcOpnd = 2; 12067 break; 12068 } 12069 } 12070 12071 SDValue Src = N->getOperand(SrcOpnd); 12072 MVT VecTy = Src.getValueType().getSimpleVT(); 12073 12074 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 12075 // aligned and the type is a vector with elements up to 4 bytes 12076 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12077 && VecTy.getScalarSizeInBits() <= 32 ) { 12078 return SDValue(); 12079 } 12080 12081 // All stores are done as v2f64 and possible bit cast. 12082 if (VecTy != MVT::v2f64) { 12083 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 12084 DCI.AddToWorklist(Src.getNode()); 12085 } 12086 12087 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 12088 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 12089 DCI.AddToWorklist(Swap.getNode()); 12090 Chain = Swap.getValue(1); 12091 SDValue StoreOps[] = { Chain, Swap, Base }; 12092 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 12093 DAG.getVTList(MVT::Other), 12094 StoreOps, VecTy, MMO); 12095 DCI.AddToWorklist(Store.getNode()); 12096 return Store; 12097 } 12098 12099 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 12100 DAGCombinerInfo &DCI) const { 12101 SelectionDAG &DAG = DCI.DAG; 12102 SDLoc dl(N); 12103 switch (N->getOpcode()) { 12104 default: break; 12105 case ISD::SHL: 12106 return combineSHL(N, DCI); 12107 case ISD::SRA: 12108 return combineSRA(N, DCI); 12109 case ISD::SRL: 12110 return combineSRL(N, DCI); 12111 case PPCISD::SHL: 12112 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 12113 return N->getOperand(0); 12114 break; 12115 case PPCISD::SRL: 12116 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 12117 return N->getOperand(0); 12118 break; 12119 case PPCISD::SRA: 12120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 12121 if (C->isNullValue() || // 0 >>s V -> 0. 12122 C->isAllOnesValue()) // -1 >>s V -> -1. 12123 return N->getOperand(0); 12124 } 12125 break; 12126 case ISD::SIGN_EXTEND: 12127 case ISD::ZERO_EXTEND: 12128 case ISD::ANY_EXTEND: 12129 return DAGCombineExtBoolTrunc(N, DCI); 12130 case ISD::TRUNCATE: 12131 case ISD::SETCC: 12132 case ISD::SELECT_CC: 12133 return DAGCombineTruncBoolExt(N, DCI); 12134 case ISD::SINT_TO_FP: 12135 case ISD::UINT_TO_FP: 12136 return combineFPToIntToFP(N, DCI); 12137 case ISD::STORE: { 12138 EVT Op1VT = N->getOperand(1).getValueType(); 12139 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) || 12140 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16)); 12141 12142 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). 12143 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && 12144 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && 12145 ValidTypeForStoreFltAsInt && 12146 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { 12147 SDValue Val = N->getOperand(1).getOperand(0); 12148 if (Val.getValueType() == MVT::f32) { 12149 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 12150 DCI.AddToWorklist(Val.getNode()); 12151 } 12152 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); 12153 DCI.AddToWorklist(Val.getNode()); 12154 12155 if (Op1VT == MVT::i32) { 12156 SDValue Ops[] = { 12157 N->getOperand(0), Val, N->getOperand(2), 12158 DAG.getValueType(N->getOperand(1).getValueType()) 12159 }; 12160 12161 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 12162 DAG.getVTList(MVT::Other), Ops, 12163 cast<StoreSDNode>(N)->getMemoryVT(), 12164 cast<StoreSDNode>(N)->getMemOperand()); 12165 } else { 12166 unsigned WidthInBytes = 12167 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2; 12168 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false); 12169 12170 SDValue Ops[] = { 12171 N->getOperand(0), Val, N->getOperand(2), WidthConst, 12172 DAG.getValueType(N->getOperand(1).getValueType()) 12173 }; 12174 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl, 12175 DAG.getVTList(MVT::Other), Ops, 12176 cast<StoreSDNode>(N)->getMemoryVT(), 12177 cast<StoreSDNode>(N)->getMemOperand()); 12178 } 12179 12180 DCI.AddToWorklist(Val.getNode()); 12181 return Val; 12182 } 12183 12184 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 12185 if (cast<StoreSDNode>(N)->isUnindexed() && 12186 N->getOperand(1).getOpcode() == ISD::BSWAP && 12187 N->getOperand(1).getNode()->hasOneUse() && 12188 (N->getOperand(1).getValueType() == MVT::i32 || 12189 N->getOperand(1).getValueType() == MVT::i16 || 12190 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12191 N->getOperand(1).getValueType() == MVT::i64))) { 12192 SDValue BSwapOp = N->getOperand(1).getOperand(0); 12193 // Do an any-extend to 32-bits if this is a half-word input. 12194 if (BSwapOp.getValueType() == MVT::i16) 12195 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 12196 12197 // If the type of BSWAP operand is wider than stored memory width 12198 // it need to be shifted to the right side before STBRX. 12199 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 12200 if (Op1VT.bitsGT(mVT)) { 12201 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 12202 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 12203 DAG.getConstant(Shift, dl, MVT::i32)); 12204 // Need to truncate if this is a bswap of i64 stored as i32/i16. 12205 if (Op1VT == MVT::i64) 12206 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 12207 } 12208 12209 SDValue Ops[] = { 12210 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 12211 }; 12212 return 12213 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 12214 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 12215 cast<StoreSDNode>(N)->getMemOperand()); 12216 } 12217 12218 // For little endian, VSX stores require generating xxswapd/lxvd2x. 12219 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12220 EVT VT = N->getOperand(1).getValueType(); 12221 if (VT.isSimple()) { 12222 MVT StoreVT = VT.getSimpleVT(); 12223 if (Subtarget.needsSwapsForVSXMemOps() && 12224 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 12225 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 12226 return expandVSXStoreForLE(N, DCI); 12227 } 12228 break; 12229 } 12230 case ISD::LOAD: { 12231 LoadSDNode *LD = cast<LoadSDNode>(N); 12232 EVT VT = LD->getValueType(0); 12233 12234 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12235 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12236 if (VT.isSimple()) { 12237 MVT LoadVT = VT.getSimpleVT(); 12238 if (Subtarget.needsSwapsForVSXMemOps() && 12239 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 12240 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 12241 return expandVSXLoadForLE(N, DCI); 12242 } 12243 12244 // We sometimes end up with a 64-bit integer load, from which we extract 12245 // two single-precision floating-point numbers. This happens with 12246 // std::complex<float>, and other similar structures, because of the way we 12247 // canonicalize structure copies. However, if we lack direct moves, 12248 // then the final bitcasts from the extracted integer values to the 12249 // floating-point numbers turn into store/load pairs. Even with direct moves, 12250 // just loading the two floating-point numbers is likely better. 12251 auto ReplaceTwoFloatLoad = [&]() { 12252 if (VT != MVT::i64) 12253 return false; 12254 12255 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 12256 LD->isVolatile()) 12257 return false; 12258 12259 // We're looking for a sequence like this: 12260 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 12261 // t16: i64 = srl t13, Constant:i32<32> 12262 // t17: i32 = truncate t16 12263 // t18: f32 = bitcast t17 12264 // t19: i32 = truncate t13 12265 // t20: f32 = bitcast t19 12266 12267 if (!LD->hasNUsesOfValue(2, 0)) 12268 return false; 12269 12270 auto UI = LD->use_begin(); 12271 while (UI.getUse().getResNo() != 0) ++UI; 12272 SDNode *Trunc = *UI++; 12273 while (UI.getUse().getResNo() != 0) ++UI; 12274 SDNode *RightShift = *UI; 12275 if (Trunc->getOpcode() != ISD::TRUNCATE) 12276 std::swap(Trunc, RightShift); 12277 12278 if (Trunc->getOpcode() != ISD::TRUNCATE || 12279 Trunc->getValueType(0) != MVT::i32 || 12280 !Trunc->hasOneUse()) 12281 return false; 12282 if (RightShift->getOpcode() != ISD::SRL || 12283 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 12284 RightShift->getConstantOperandVal(1) != 32 || 12285 !RightShift->hasOneUse()) 12286 return false; 12287 12288 SDNode *Trunc2 = *RightShift->use_begin(); 12289 if (Trunc2->getOpcode() != ISD::TRUNCATE || 12290 Trunc2->getValueType(0) != MVT::i32 || 12291 !Trunc2->hasOneUse()) 12292 return false; 12293 12294 SDNode *Bitcast = *Trunc->use_begin(); 12295 SDNode *Bitcast2 = *Trunc2->use_begin(); 12296 12297 if (Bitcast->getOpcode() != ISD::BITCAST || 12298 Bitcast->getValueType(0) != MVT::f32) 12299 return false; 12300 if (Bitcast2->getOpcode() != ISD::BITCAST || 12301 Bitcast2->getValueType(0) != MVT::f32) 12302 return false; 12303 12304 if (Subtarget.isLittleEndian()) 12305 std::swap(Bitcast, Bitcast2); 12306 12307 // Bitcast has the second float (in memory-layout order) and Bitcast2 12308 // has the first one. 12309 12310 SDValue BasePtr = LD->getBasePtr(); 12311 if (LD->isIndexed()) { 12312 assert(LD->getAddressingMode() == ISD::PRE_INC && 12313 "Non-pre-inc AM on PPC?"); 12314 BasePtr = 12315 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 12316 LD->getOffset()); 12317 } 12318 12319 auto MMOFlags = 12320 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 12321 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 12322 LD->getPointerInfo(), LD->getAlignment(), 12323 MMOFlags, LD->getAAInfo()); 12324 SDValue AddPtr = 12325 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 12326 BasePtr, DAG.getIntPtrConstant(4, dl)); 12327 SDValue FloatLoad2 = DAG.getLoad( 12328 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 12329 LD->getPointerInfo().getWithOffset(4), 12330 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 12331 12332 if (LD->isIndexed()) { 12333 // Note that DAGCombine should re-form any pre-increment load(s) from 12334 // what is produced here if that makes sense. 12335 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 12336 } 12337 12338 DCI.CombineTo(Bitcast2, FloatLoad); 12339 DCI.CombineTo(Bitcast, FloatLoad2); 12340 12341 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 12342 SDValue(FloatLoad2.getNode(), 1)); 12343 return true; 12344 }; 12345 12346 if (ReplaceTwoFloatLoad()) 12347 return SDValue(N, 0); 12348 12349 EVT MemVT = LD->getMemoryVT(); 12350 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 12351 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 12352 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 12353 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 12354 if (LD->isUnindexed() && VT.isVector() && 12355 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 12356 // P8 and later hardware should just use LOAD. 12357 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 12358 VT == MVT::v4i32 || VT == MVT::v4f32)) || 12359 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 12360 LD->getAlignment() >= ScalarABIAlignment)) && 12361 LD->getAlignment() < ABIAlignment) { 12362 // This is a type-legal unaligned Altivec or QPX load. 12363 SDValue Chain = LD->getChain(); 12364 SDValue Ptr = LD->getBasePtr(); 12365 bool isLittleEndian = Subtarget.isLittleEndian(); 12366 12367 // This implements the loading of unaligned vectors as described in 12368 // the venerable Apple Velocity Engine overview. Specifically: 12369 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 12370 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 12371 // 12372 // The general idea is to expand a sequence of one or more unaligned 12373 // loads into an alignment-based permutation-control instruction (lvsl 12374 // or lvsr), a series of regular vector loads (which always truncate 12375 // their input address to an aligned address), and a series of 12376 // permutations. The results of these permutations are the requested 12377 // loaded values. The trick is that the last "extra" load is not taken 12378 // from the address you might suspect (sizeof(vector) bytes after the 12379 // last requested load), but rather sizeof(vector) - 1 bytes after the 12380 // last requested vector. The point of this is to avoid a page fault if 12381 // the base address happened to be aligned. This works because if the 12382 // base address is aligned, then adding less than a full vector length 12383 // will cause the last vector in the sequence to be (re)loaded. 12384 // Otherwise, the next vector will be fetched as you might suspect was 12385 // necessary. 12386 12387 // We might be able to reuse the permutation generation from 12388 // a different base address offset from this one by an aligned amount. 12389 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 12390 // optimization later. 12391 Intrinsic::ID Intr, IntrLD, IntrPerm; 12392 MVT PermCntlTy, PermTy, LDTy; 12393 if (Subtarget.hasAltivec()) { 12394 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 12395 Intrinsic::ppc_altivec_lvsl; 12396 IntrLD = Intrinsic::ppc_altivec_lvx; 12397 IntrPerm = Intrinsic::ppc_altivec_vperm; 12398 PermCntlTy = MVT::v16i8; 12399 PermTy = MVT::v4i32; 12400 LDTy = MVT::v4i32; 12401 } else { 12402 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 12403 Intrinsic::ppc_qpx_qvlpcls; 12404 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 12405 Intrinsic::ppc_qpx_qvlfs; 12406 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 12407 PermCntlTy = MVT::v4f64; 12408 PermTy = MVT::v4f64; 12409 LDTy = MemVT.getSimpleVT(); 12410 } 12411 12412 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 12413 12414 // Create the new MMO for the new base load. It is like the original MMO, 12415 // but represents an area in memory almost twice the vector size centered 12416 // on the original address. If the address is unaligned, we might start 12417 // reading up to (sizeof(vector)-1) bytes below the address of the 12418 // original unaligned load. 12419 MachineFunction &MF = DAG.getMachineFunction(); 12420 MachineMemOperand *BaseMMO = 12421 MF.getMachineMemOperand(LD->getMemOperand(), 12422 -(long)MemVT.getStoreSize()+1, 12423 2*MemVT.getStoreSize()-1); 12424 12425 // Create the new base load. 12426 SDValue LDXIntID = 12427 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 12428 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 12429 SDValue BaseLoad = 12430 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12431 DAG.getVTList(PermTy, MVT::Other), 12432 BaseLoadOps, LDTy, BaseMMO); 12433 12434 // Note that the value of IncOffset (which is provided to the next 12435 // load's pointer info offset value, and thus used to calculate the 12436 // alignment), and the value of IncValue (which is actually used to 12437 // increment the pointer value) are different! This is because we 12438 // require the next load to appear to be aligned, even though it 12439 // is actually offset from the base pointer by a lesser amount. 12440 int IncOffset = VT.getSizeInBits() / 8; 12441 int IncValue = IncOffset; 12442 12443 // Walk (both up and down) the chain looking for another load at the real 12444 // (aligned) offset (the alignment of the other load does not matter in 12445 // this case). If found, then do not use the offset reduction trick, as 12446 // that will prevent the loads from being later combined (as they would 12447 // otherwise be duplicates). 12448 if (!findConsecutiveLoad(LD, DAG)) 12449 --IncValue; 12450 12451 SDValue Increment = 12452 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 12453 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 12454 12455 MachineMemOperand *ExtraMMO = 12456 MF.getMachineMemOperand(LD->getMemOperand(), 12457 1, 2*MemVT.getStoreSize()-1); 12458 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 12459 SDValue ExtraLoad = 12460 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 12461 DAG.getVTList(PermTy, MVT::Other), 12462 ExtraLoadOps, LDTy, ExtraMMO); 12463 12464 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 12465 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 12466 12467 // Because vperm has a big-endian bias, we must reverse the order 12468 // of the input vectors and complement the permute control vector 12469 // when generating little endian code. We have already handled the 12470 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 12471 // and ExtraLoad here. 12472 SDValue Perm; 12473 if (isLittleEndian) 12474 Perm = BuildIntrinsicOp(IntrPerm, 12475 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 12476 else 12477 Perm = BuildIntrinsicOp(IntrPerm, 12478 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 12479 12480 if (VT != PermTy) 12481 Perm = Subtarget.hasAltivec() ? 12482 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 12483 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 12484 DAG.getTargetConstant(1, dl, MVT::i64)); 12485 // second argument is 1 because this rounding 12486 // is always exact. 12487 12488 // The output of the permutation is our loaded result, the TokenFactor is 12489 // our new chain. 12490 DCI.CombineTo(N, Perm, TF); 12491 return SDValue(N, 0); 12492 } 12493 } 12494 break; 12495 case ISD::INTRINSIC_WO_CHAIN: { 12496 bool isLittleEndian = Subtarget.isLittleEndian(); 12497 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 12498 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 12499 : Intrinsic::ppc_altivec_lvsl); 12500 if ((IID == Intr || 12501 IID == Intrinsic::ppc_qpx_qvlpcld || 12502 IID == Intrinsic::ppc_qpx_qvlpcls) && 12503 N->getOperand(1)->getOpcode() == ISD::ADD) { 12504 SDValue Add = N->getOperand(1); 12505 12506 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 12507 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 12508 12509 if (DAG.MaskedValueIsZero(Add->getOperand(1), 12510 APInt::getAllOnesValue(Bits /* alignment */) 12511 .zext(Add.getScalarValueSizeInBits()))) { 12512 SDNode *BasePtr = Add->getOperand(0).getNode(); 12513 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12514 UE = BasePtr->use_end(); 12515 UI != UE; ++UI) { 12516 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12517 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 12518 // We've found another LVSL/LVSR, and this address is an aligned 12519 // multiple of that one. The results will be the same, so use the 12520 // one we've just found instead. 12521 12522 return SDValue(*UI, 0); 12523 } 12524 } 12525 } 12526 12527 if (isa<ConstantSDNode>(Add->getOperand(1))) { 12528 SDNode *BasePtr = Add->getOperand(0).getNode(); 12529 for (SDNode::use_iterator UI = BasePtr->use_begin(), 12530 UE = BasePtr->use_end(); UI != UE; ++UI) { 12531 if (UI->getOpcode() == ISD::ADD && 12532 isa<ConstantSDNode>(UI->getOperand(1)) && 12533 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 12534 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 12535 (1ULL << Bits) == 0) { 12536 SDNode *OtherAdd = *UI; 12537 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 12538 VE = OtherAdd->use_end(); VI != VE; ++VI) { 12539 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12540 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 12541 return SDValue(*VI, 0); 12542 } 12543 } 12544 } 12545 } 12546 } 12547 } 12548 } 12549 12550 break; 12551 case ISD::INTRINSIC_W_CHAIN: 12552 // For little endian, VSX loads require generating lxvd2x/xxswapd. 12553 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 12554 if (Subtarget.needsSwapsForVSXMemOps()) { 12555 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12556 default: 12557 break; 12558 case Intrinsic::ppc_vsx_lxvw4x: 12559 case Intrinsic::ppc_vsx_lxvd2x: 12560 return expandVSXLoadForLE(N, DCI); 12561 } 12562 } 12563 break; 12564 case ISD::INTRINSIC_VOID: 12565 // For little endian, VSX stores require generating xxswapd/stxvd2x. 12566 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 12567 if (Subtarget.needsSwapsForVSXMemOps()) { 12568 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12569 default: 12570 break; 12571 case Intrinsic::ppc_vsx_stxvw4x: 12572 case Intrinsic::ppc_vsx_stxvd2x: 12573 return expandVSXStoreForLE(N, DCI); 12574 } 12575 } 12576 break; 12577 case ISD::BSWAP: 12578 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 12579 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 12580 N->getOperand(0).hasOneUse() && 12581 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 12582 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 12583 N->getValueType(0) == MVT::i64))) { 12584 SDValue Load = N->getOperand(0); 12585 LoadSDNode *LD = cast<LoadSDNode>(Load); 12586 // Create the byte-swapping load. 12587 SDValue Ops[] = { 12588 LD->getChain(), // Chain 12589 LD->getBasePtr(), // Ptr 12590 DAG.getValueType(N->getValueType(0)) // VT 12591 }; 12592 SDValue BSLoad = 12593 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 12594 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 12595 MVT::i64 : MVT::i32, MVT::Other), 12596 Ops, LD->getMemoryVT(), LD->getMemOperand()); 12597 12598 // If this is an i16 load, insert the truncate. 12599 SDValue ResVal = BSLoad; 12600 if (N->getValueType(0) == MVT::i16) 12601 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 12602 12603 // First, combine the bswap away. This makes the value produced by the 12604 // load dead. 12605 DCI.CombineTo(N, ResVal); 12606 12607 // Next, combine the load away, we give it a bogus result value but a real 12608 // chain result. The result value is dead because the bswap is dead. 12609 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 12610 12611 // Return N so it doesn't get rechecked! 12612 return SDValue(N, 0); 12613 } 12614 break; 12615 case PPCISD::VCMP: 12616 // If a VCMPo node already exists with exactly the same operands as this 12617 // node, use its result instead of this node (VCMPo computes both a CR6 and 12618 // a normal output). 12619 // 12620 if (!N->getOperand(0).hasOneUse() && 12621 !N->getOperand(1).hasOneUse() && 12622 !N->getOperand(2).hasOneUse()) { 12623 12624 // Scan all of the users of the LHS, looking for VCMPo's that match. 12625 SDNode *VCMPoNode = nullptr; 12626 12627 SDNode *LHSN = N->getOperand(0).getNode(); 12628 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 12629 UI != E; ++UI) 12630 if (UI->getOpcode() == PPCISD::VCMPo && 12631 UI->getOperand(1) == N->getOperand(1) && 12632 UI->getOperand(2) == N->getOperand(2) && 12633 UI->getOperand(0) == N->getOperand(0)) { 12634 VCMPoNode = *UI; 12635 break; 12636 } 12637 12638 // If there is no VCMPo node, or if the flag value has a single use, don't 12639 // transform this. 12640 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 12641 break; 12642 12643 // Look at the (necessarily single) use of the flag value. If it has a 12644 // chain, this transformation is more complex. Note that multiple things 12645 // could use the value result, which we should ignore. 12646 SDNode *FlagUser = nullptr; 12647 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 12648 FlagUser == nullptr; ++UI) { 12649 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 12650 SDNode *User = *UI; 12651 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 12652 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 12653 FlagUser = User; 12654 break; 12655 } 12656 } 12657 } 12658 12659 // If the user is a MFOCRF instruction, we know this is safe. 12660 // Otherwise we give up for right now. 12661 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 12662 return SDValue(VCMPoNode, 0); 12663 } 12664 break; 12665 case ISD::BRCOND: { 12666 SDValue Cond = N->getOperand(1); 12667 SDValue Target = N->getOperand(2); 12668 12669 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12670 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 12671 Intrinsic::ppc_is_decremented_ctr_nonzero) { 12672 12673 // We now need to make the intrinsic dead (it cannot be instruction 12674 // selected). 12675 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 12676 assert(Cond.getNode()->hasOneUse() && 12677 "Counter decrement has more than one use"); 12678 12679 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 12680 N->getOperand(0), Target); 12681 } 12682 } 12683 break; 12684 case ISD::BR_CC: { 12685 // If this is a branch on an altivec predicate comparison, lower this so 12686 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 12687 // lowering is done pre-legalize, because the legalizer lowers the predicate 12688 // compare down to code that is difficult to reassemble. 12689 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 12690 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 12691 12692 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 12693 // value. If so, pass-through the AND to get to the intrinsic. 12694 if (LHS.getOpcode() == ISD::AND && 12695 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 12696 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 12697 Intrinsic::ppc_is_decremented_ctr_nonzero && 12698 isa<ConstantSDNode>(LHS.getOperand(1)) && 12699 !isNullConstant(LHS.getOperand(1))) 12700 LHS = LHS.getOperand(0); 12701 12702 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 12703 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 12704 Intrinsic::ppc_is_decremented_ctr_nonzero && 12705 isa<ConstantSDNode>(RHS)) { 12706 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 12707 "Counter decrement comparison is not EQ or NE"); 12708 12709 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12710 bool isBDNZ = (CC == ISD::SETEQ && Val) || 12711 (CC == ISD::SETNE && !Val); 12712 12713 // We now need to make the intrinsic dead (it cannot be instruction 12714 // selected). 12715 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 12716 assert(LHS.getNode()->hasOneUse() && 12717 "Counter decrement has more than one use"); 12718 12719 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 12720 N->getOperand(0), N->getOperand(4)); 12721 } 12722 12723 int CompareOpc; 12724 bool isDot; 12725 12726 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 12727 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 12728 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 12729 assert(isDot && "Can't compare against a vector result!"); 12730 12731 // If this is a comparison against something other than 0/1, then we know 12732 // that the condition is never/always true. 12733 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 12734 if (Val != 0 && Val != 1) { 12735 if (CC == ISD::SETEQ) // Cond never true, remove branch. 12736 return N->getOperand(0); 12737 // Always !=, turn it into an unconditional branch. 12738 return DAG.getNode(ISD::BR, dl, MVT::Other, 12739 N->getOperand(0), N->getOperand(4)); 12740 } 12741 12742 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 12743 12744 // Create the PPCISD altivec 'dot' comparison node. 12745 SDValue Ops[] = { 12746 LHS.getOperand(2), // LHS of compare 12747 LHS.getOperand(3), // RHS of compare 12748 DAG.getConstant(CompareOpc, dl, MVT::i32) 12749 }; 12750 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 12751 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 12752 12753 // Unpack the result based on how the target uses it. 12754 PPC::Predicate CompOpc; 12755 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 12756 default: // Can't happen, don't crash on invalid number though. 12757 case 0: // Branch on the value of the EQ bit of CR6. 12758 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 12759 break; 12760 case 1: // Branch on the inverted value of the EQ bit of CR6. 12761 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 12762 break; 12763 case 2: // Branch on the value of the LT bit of CR6. 12764 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 12765 break; 12766 case 3: // Branch on the inverted value of the LT bit of CR6. 12767 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 12768 break; 12769 } 12770 12771 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 12772 DAG.getConstant(CompOpc, dl, MVT::i32), 12773 DAG.getRegister(PPC::CR6, MVT::i32), 12774 N->getOperand(4), CompNode.getValue(1)); 12775 } 12776 break; 12777 } 12778 case ISD::BUILD_VECTOR: 12779 return DAGCombineBuildVector(N, DCI); 12780 } 12781 12782 return SDValue(); 12783 } 12784 12785 SDValue 12786 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12787 SelectionDAG &DAG, 12788 std::vector<SDNode *> *Created) const { 12789 // fold (sdiv X, pow2) 12790 EVT VT = N->getValueType(0); 12791 if (VT == MVT::i64 && !Subtarget.isPPC64()) 12792 return SDValue(); 12793 if ((VT != MVT::i32 && VT != MVT::i64) || 12794 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 12795 return SDValue(); 12796 12797 SDLoc DL(N); 12798 SDValue N0 = N->getOperand(0); 12799 12800 bool IsNegPow2 = (-Divisor).isPowerOf2(); 12801 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 12802 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 12803 12804 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 12805 if (Created) 12806 Created->push_back(Op.getNode()); 12807 12808 if (IsNegPow2) { 12809 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 12810 if (Created) 12811 Created->push_back(Op.getNode()); 12812 } 12813 12814 return Op; 12815 } 12816 12817 //===----------------------------------------------------------------------===// 12818 // Inline Assembly Support 12819 //===----------------------------------------------------------------------===// 12820 12821 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 12822 KnownBits &Known, 12823 const APInt &DemandedElts, 12824 const SelectionDAG &DAG, 12825 unsigned Depth) const { 12826 Known.resetAll(); 12827 switch (Op.getOpcode()) { 12828 default: break; 12829 case PPCISD::LBRX: { 12830 // lhbrx is known to have the top bits cleared out. 12831 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 12832 Known.Zero = 0xFFFF0000; 12833 break; 12834 } 12835 case ISD::INTRINSIC_WO_CHAIN: { 12836 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 12837 default: break; 12838 case Intrinsic::ppc_altivec_vcmpbfp_p: 12839 case Intrinsic::ppc_altivec_vcmpeqfp_p: 12840 case Intrinsic::ppc_altivec_vcmpequb_p: 12841 case Intrinsic::ppc_altivec_vcmpequh_p: 12842 case Intrinsic::ppc_altivec_vcmpequw_p: 12843 case Intrinsic::ppc_altivec_vcmpequd_p: 12844 case Intrinsic::ppc_altivec_vcmpgefp_p: 12845 case Intrinsic::ppc_altivec_vcmpgtfp_p: 12846 case Intrinsic::ppc_altivec_vcmpgtsb_p: 12847 case Intrinsic::ppc_altivec_vcmpgtsh_p: 12848 case Intrinsic::ppc_altivec_vcmpgtsw_p: 12849 case Intrinsic::ppc_altivec_vcmpgtsd_p: 12850 case Intrinsic::ppc_altivec_vcmpgtub_p: 12851 case Intrinsic::ppc_altivec_vcmpgtuh_p: 12852 case Intrinsic::ppc_altivec_vcmpgtuw_p: 12853 case Intrinsic::ppc_altivec_vcmpgtud_p: 12854 Known.Zero = ~1U; // All bits but the low one are known to be zero. 12855 break; 12856 } 12857 } 12858 } 12859 } 12860 12861 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12862 switch (Subtarget.getDarwinDirective()) { 12863 default: break; 12864 case PPC::DIR_970: 12865 case PPC::DIR_PWR4: 12866 case PPC::DIR_PWR5: 12867 case PPC::DIR_PWR5X: 12868 case PPC::DIR_PWR6: 12869 case PPC::DIR_PWR6X: 12870 case PPC::DIR_PWR7: 12871 case PPC::DIR_PWR8: 12872 case PPC::DIR_PWR9: { 12873 if (!ML) 12874 break; 12875 12876 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 12877 12878 // For small loops (between 5 and 8 instructions), align to a 32-byte 12879 // boundary so that the entire loop fits in one instruction-cache line. 12880 uint64_t LoopSize = 0; 12881 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 12882 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 12883 LoopSize += TII->getInstSizeInBytes(*J); 12884 if (LoopSize > 32) 12885 break; 12886 } 12887 12888 if (LoopSize > 16 && LoopSize <= 32) 12889 return 5; 12890 12891 break; 12892 } 12893 } 12894 12895 return TargetLowering::getPrefLoopAlignment(ML); 12896 } 12897 12898 /// getConstraintType - Given a constraint, return the type of 12899 /// constraint it is for this target. 12900 PPCTargetLowering::ConstraintType 12901 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 12902 if (Constraint.size() == 1) { 12903 switch (Constraint[0]) { 12904 default: break; 12905 case 'b': 12906 case 'r': 12907 case 'f': 12908 case 'd': 12909 case 'v': 12910 case 'y': 12911 return C_RegisterClass; 12912 case 'Z': 12913 // FIXME: While Z does indicate a memory constraint, it specifically 12914 // indicates an r+r address (used in conjunction with the 'y' modifier 12915 // in the replacement string). Currently, we're forcing the base 12916 // register to be r0 in the asm printer (which is interpreted as zero) 12917 // and forming the complete address in the second register. This is 12918 // suboptimal. 12919 return C_Memory; 12920 } 12921 } else if (Constraint == "wc") { // individual CR bits. 12922 return C_RegisterClass; 12923 } else if (Constraint == "wa" || Constraint == "wd" || 12924 Constraint == "wf" || Constraint == "ws") { 12925 return C_RegisterClass; // VSX registers. 12926 } 12927 return TargetLowering::getConstraintType(Constraint); 12928 } 12929 12930 /// Examine constraint type and operand type and determine a weight value. 12931 /// This object must already have been set up with the operand type 12932 /// and the current alternative constraint selected. 12933 TargetLowering::ConstraintWeight 12934 PPCTargetLowering::getSingleConstraintMatchWeight( 12935 AsmOperandInfo &info, const char *constraint) const { 12936 ConstraintWeight weight = CW_Invalid; 12937 Value *CallOperandVal = info.CallOperandVal; 12938 // If we don't have a value, we can't do a match, 12939 // but allow it at the lowest weight. 12940 if (!CallOperandVal) 12941 return CW_Default; 12942 Type *type = CallOperandVal->getType(); 12943 12944 // Look at the constraint type. 12945 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 12946 return CW_Register; // an individual CR bit. 12947 else if ((StringRef(constraint) == "wa" || 12948 StringRef(constraint) == "wd" || 12949 StringRef(constraint) == "wf") && 12950 type->isVectorTy()) 12951 return CW_Register; 12952 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 12953 return CW_Register; 12954 12955 switch (*constraint) { 12956 default: 12957 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 12958 break; 12959 case 'b': 12960 if (type->isIntegerTy()) 12961 weight = CW_Register; 12962 break; 12963 case 'f': 12964 if (type->isFloatTy()) 12965 weight = CW_Register; 12966 break; 12967 case 'd': 12968 if (type->isDoubleTy()) 12969 weight = CW_Register; 12970 break; 12971 case 'v': 12972 if (type->isVectorTy()) 12973 weight = CW_Register; 12974 break; 12975 case 'y': 12976 weight = CW_Register; 12977 break; 12978 case 'Z': 12979 weight = CW_Memory; 12980 break; 12981 } 12982 return weight; 12983 } 12984 12985 std::pair<unsigned, const TargetRegisterClass *> 12986 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 12987 StringRef Constraint, 12988 MVT VT) const { 12989 if (Constraint.size() == 1) { 12990 // GCC RS6000 Constraint Letters 12991 switch (Constraint[0]) { 12992 case 'b': // R1-R31 12993 if (VT == MVT::i64 && Subtarget.isPPC64()) 12994 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 12995 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 12996 case 'r': // R0-R31 12997 if (VT == MVT::i64 && Subtarget.isPPC64()) 12998 return std::make_pair(0U, &PPC::G8RCRegClass); 12999 return std::make_pair(0U, &PPC::GPRCRegClass); 13000 // 'd' and 'f' constraints are both defined to be "the floating point 13001 // registers", where one is for 32-bit and the other for 64-bit. We don't 13002 // really care overly much here so just give them all the same reg classes. 13003 case 'd': 13004 case 'f': 13005 if (VT == MVT::f32 || VT == MVT::i32) 13006 return std::make_pair(0U, &PPC::F4RCRegClass); 13007 if (VT == MVT::f64 || VT == MVT::i64) 13008 return std::make_pair(0U, &PPC::F8RCRegClass); 13009 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13010 return std::make_pair(0U, &PPC::QFRCRegClass); 13011 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13012 return std::make_pair(0U, &PPC::QSRCRegClass); 13013 break; 13014 case 'v': 13015 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 13016 return std::make_pair(0U, &PPC::QFRCRegClass); 13017 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 13018 return std::make_pair(0U, &PPC::QSRCRegClass); 13019 if (Subtarget.hasAltivec()) 13020 return std::make_pair(0U, &PPC::VRRCRegClass); 13021 case 'y': // crrc 13022 return std::make_pair(0U, &PPC::CRRCRegClass); 13023 } 13024 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 13025 // An individual CR bit. 13026 return std::make_pair(0U, &PPC::CRBITRCRegClass); 13027 } else if ((Constraint == "wa" || Constraint == "wd" || 13028 Constraint == "wf") && Subtarget.hasVSX()) { 13029 return std::make_pair(0U, &PPC::VSRCRegClass); 13030 } else if (Constraint == "ws" && Subtarget.hasVSX()) { 13031 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 13032 return std::make_pair(0U, &PPC::VSSRCRegClass); 13033 else 13034 return std::make_pair(0U, &PPC::VSFRCRegClass); 13035 } 13036 13037 std::pair<unsigned, const TargetRegisterClass *> R = 13038 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 13039 13040 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 13041 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 13042 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 13043 // register. 13044 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 13045 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 13046 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 13047 PPC::GPRCRegClass.contains(R.first)) 13048 return std::make_pair(TRI->getMatchingSuperReg(R.first, 13049 PPC::sub_32, &PPC::G8RCRegClass), 13050 &PPC::G8RCRegClass); 13051 13052 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 13053 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 13054 R.first = PPC::CR0; 13055 R.second = &PPC::CRRCRegClass; 13056 } 13057 13058 return R; 13059 } 13060 13061 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 13062 /// vector. If it is invalid, don't add anything to Ops. 13063 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 13064 std::string &Constraint, 13065 std::vector<SDValue>&Ops, 13066 SelectionDAG &DAG) const { 13067 SDValue Result; 13068 13069 // Only support length 1 constraints. 13070 if (Constraint.length() > 1) return; 13071 13072 char Letter = Constraint[0]; 13073 switch (Letter) { 13074 default: break; 13075 case 'I': 13076 case 'J': 13077 case 'K': 13078 case 'L': 13079 case 'M': 13080 case 'N': 13081 case 'O': 13082 case 'P': { 13083 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 13084 if (!CST) return; // Must be an immediate to match. 13085 SDLoc dl(Op); 13086 int64_t Value = CST->getSExtValue(); 13087 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 13088 // numbers are printed as such. 13089 switch (Letter) { 13090 default: llvm_unreachable("Unknown constraint letter!"); 13091 case 'I': // "I" is a signed 16-bit constant. 13092 if (isInt<16>(Value)) 13093 Result = DAG.getTargetConstant(Value, dl, TCVT); 13094 break; 13095 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 13096 if (isShiftedUInt<16, 16>(Value)) 13097 Result = DAG.getTargetConstant(Value, dl, TCVT); 13098 break; 13099 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 13100 if (isShiftedInt<16, 16>(Value)) 13101 Result = DAG.getTargetConstant(Value, dl, TCVT); 13102 break; 13103 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 13104 if (isUInt<16>(Value)) 13105 Result = DAG.getTargetConstant(Value, dl, TCVT); 13106 break; 13107 case 'M': // "M" is a constant that is greater than 31. 13108 if (Value > 31) 13109 Result = DAG.getTargetConstant(Value, dl, TCVT); 13110 break; 13111 case 'N': // "N" is a positive constant that is an exact power of two. 13112 if (Value > 0 && isPowerOf2_64(Value)) 13113 Result = DAG.getTargetConstant(Value, dl, TCVT); 13114 break; 13115 case 'O': // "O" is the constant zero. 13116 if (Value == 0) 13117 Result = DAG.getTargetConstant(Value, dl, TCVT); 13118 break; 13119 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 13120 if (isInt<16>(-Value)) 13121 Result = DAG.getTargetConstant(Value, dl, TCVT); 13122 break; 13123 } 13124 break; 13125 } 13126 } 13127 13128 if (Result.getNode()) { 13129 Ops.push_back(Result); 13130 return; 13131 } 13132 13133 // Handle standard constraint letters. 13134 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 13135 } 13136 13137 // isLegalAddressingMode - Return true if the addressing mode represented 13138 // by AM is legal for this target, for a load/store of the specified type. 13139 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 13140 const AddrMode &AM, Type *Ty, 13141 unsigned AS, Instruction *I) const { 13142 // PPC does not allow r+i addressing modes for vectors! 13143 if (Ty->isVectorTy() && AM.BaseOffs != 0) 13144 return false; 13145 13146 // PPC allows a sign-extended 16-bit immediate field. 13147 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 13148 return false; 13149 13150 // No global is ever allowed as a base. 13151 if (AM.BaseGV) 13152 return false; 13153 13154 // PPC only support r+r, 13155 switch (AM.Scale) { 13156 case 0: // "r+i" or just "i", depending on HasBaseReg. 13157 break; 13158 case 1: 13159 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 13160 return false; 13161 // Otherwise we have r+r or r+i. 13162 break; 13163 case 2: 13164 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 13165 return false; 13166 // Allow 2*r as r+r. 13167 break; 13168 default: 13169 // No other scales are supported. 13170 return false; 13171 } 13172 13173 return true; 13174 } 13175 13176 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 13177 SelectionDAG &DAG) const { 13178 MachineFunction &MF = DAG.getMachineFunction(); 13179 MachineFrameInfo &MFI = MF.getFrameInfo(); 13180 MFI.setReturnAddressIsTaken(true); 13181 13182 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 13183 return SDValue(); 13184 13185 SDLoc dl(Op); 13186 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13187 13188 // Make sure the function does not optimize away the store of the RA to 13189 // the stack. 13190 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 13191 FuncInfo->setLRStoreRequired(); 13192 bool isPPC64 = Subtarget.isPPC64(); 13193 auto PtrVT = getPointerTy(MF.getDataLayout()); 13194 13195 if (Depth > 0) { 13196 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 13197 SDValue Offset = 13198 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 13199 isPPC64 ? MVT::i64 : MVT::i32); 13200 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 13201 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 13202 MachinePointerInfo()); 13203 } 13204 13205 // Just load the return address off the stack. 13206 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 13207 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 13208 MachinePointerInfo()); 13209 } 13210 13211 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 13212 SelectionDAG &DAG) const { 13213 SDLoc dl(Op); 13214 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 13215 13216 MachineFunction &MF = DAG.getMachineFunction(); 13217 MachineFrameInfo &MFI = MF.getFrameInfo(); 13218 MFI.setFrameAddressIsTaken(true); 13219 13220 EVT PtrVT = getPointerTy(MF.getDataLayout()); 13221 bool isPPC64 = PtrVT == MVT::i64; 13222 13223 // Naked functions never have a frame pointer, and so we use r1. For all 13224 // other functions, this decision must be delayed until during PEI. 13225 unsigned FrameReg; 13226 if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) 13227 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 13228 else 13229 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 13230 13231 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 13232 PtrVT); 13233 while (Depth--) 13234 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 13235 FrameAddr, MachinePointerInfo()); 13236 return FrameAddr; 13237 } 13238 13239 // FIXME? Maybe this could be a TableGen attribute on some registers and 13240 // this table could be generated automatically from RegInfo. 13241 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 13242 SelectionDAG &DAG) const { 13243 bool isPPC64 = Subtarget.isPPC64(); 13244 bool isDarwinABI = Subtarget.isDarwinABI(); 13245 13246 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 13247 (!isPPC64 && VT != MVT::i32)) 13248 report_fatal_error("Invalid register global variable type"); 13249 13250 bool is64Bit = isPPC64 && VT == MVT::i64; 13251 unsigned Reg = StringSwitch<unsigned>(RegName) 13252 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 13253 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 13254 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 13255 (is64Bit ? PPC::X13 : PPC::R13)) 13256 .Default(0); 13257 13258 if (Reg) 13259 return Reg; 13260 report_fatal_error("Invalid register name global variable"); 13261 } 13262 13263 bool 13264 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 13265 // The PowerPC target isn't yet aware of offsets. 13266 return false; 13267 } 13268 13269 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 13270 const CallInst &I, 13271 unsigned Intrinsic) const { 13272 switch (Intrinsic) { 13273 case Intrinsic::ppc_qpx_qvlfd: 13274 case Intrinsic::ppc_qpx_qvlfs: 13275 case Intrinsic::ppc_qpx_qvlfcd: 13276 case Intrinsic::ppc_qpx_qvlfcs: 13277 case Intrinsic::ppc_qpx_qvlfiwa: 13278 case Intrinsic::ppc_qpx_qvlfiwz: 13279 case Intrinsic::ppc_altivec_lvx: 13280 case Intrinsic::ppc_altivec_lvxl: 13281 case Intrinsic::ppc_altivec_lvebx: 13282 case Intrinsic::ppc_altivec_lvehx: 13283 case Intrinsic::ppc_altivec_lvewx: 13284 case Intrinsic::ppc_vsx_lxvd2x: 13285 case Intrinsic::ppc_vsx_lxvw4x: { 13286 EVT VT; 13287 switch (Intrinsic) { 13288 case Intrinsic::ppc_altivec_lvebx: 13289 VT = MVT::i8; 13290 break; 13291 case Intrinsic::ppc_altivec_lvehx: 13292 VT = MVT::i16; 13293 break; 13294 case Intrinsic::ppc_altivec_lvewx: 13295 VT = MVT::i32; 13296 break; 13297 case Intrinsic::ppc_vsx_lxvd2x: 13298 VT = MVT::v2f64; 13299 break; 13300 case Intrinsic::ppc_qpx_qvlfd: 13301 VT = MVT::v4f64; 13302 break; 13303 case Intrinsic::ppc_qpx_qvlfs: 13304 VT = MVT::v4f32; 13305 break; 13306 case Intrinsic::ppc_qpx_qvlfcd: 13307 VT = MVT::v2f64; 13308 break; 13309 case Intrinsic::ppc_qpx_qvlfcs: 13310 VT = MVT::v2f32; 13311 break; 13312 default: 13313 VT = MVT::v4i32; 13314 break; 13315 } 13316 13317 Info.opc = ISD::INTRINSIC_W_CHAIN; 13318 Info.memVT = VT; 13319 Info.ptrVal = I.getArgOperand(0); 13320 Info.offset = -VT.getStoreSize()+1; 13321 Info.size = 2*VT.getStoreSize()-1; 13322 Info.align = 1; 13323 Info.vol = false; 13324 Info.readMem = true; 13325 Info.writeMem = false; 13326 return true; 13327 } 13328 case Intrinsic::ppc_qpx_qvlfda: 13329 case Intrinsic::ppc_qpx_qvlfsa: 13330 case Intrinsic::ppc_qpx_qvlfcda: 13331 case Intrinsic::ppc_qpx_qvlfcsa: 13332 case Intrinsic::ppc_qpx_qvlfiwaa: 13333 case Intrinsic::ppc_qpx_qvlfiwza: { 13334 EVT VT; 13335 switch (Intrinsic) { 13336 case Intrinsic::ppc_qpx_qvlfda: 13337 VT = MVT::v4f64; 13338 break; 13339 case Intrinsic::ppc_qpx_qvlfsa: 13340 VT = MVT::v4f32; 13341 break; 13342 case Intrinsic::ppc_qpx_qvlfcda: 13343 VT = MVT::v2f64; 13344 break; 13345 case Intrinsic::ppc_qpx_qvlfcsa: 13346 VT = MVT::v2f32; 13347 break; 13348 default: 13349 VT = MVT::v4i32; 13350 break; 13351 } 13352 13353 Info.opc = ISD::INTRINSIC_W_CHAIN; 13354 Info.memVT = VT; 13355 Info.ptrVal = I.getArgOperand(0); 13356 Info.offset = 0; 13357 Info.size = VT.getStoreSize(); 13358 Info.align = 1; 13359 Info.vol = false; 13360 Info.readMem = true; 13361 Info.writeMem = false; 13362 return true; 13363 } 13364 case Intrinsic::ppc_qpx_qvstfd: 13365 case Intrinsic::ppc_qpx_qvstfs: 13366 case Intrinsic::ppc_qpx_qvstfcd: 13367 case Intrinsic::ppc_qpx_qvstfcs: 13368 case Intrinsic::ppc_qpx_qvstfiw: 13369 case Intrinsic::ppc_altivec_stvx: 13370 case Intrinsic::ppc_altivec_stvxl: 13371 case Intrinsic::ppc_altivec_stvebx: 13372 case Intrinsic::ppc_altivec_stvehx: 13373 case Intrinsic::ppc_altivec_stvewx: 13374 case Intrinsic::ppc_vsx_stxvd2x: 13375 case Intrinsic::ppc_vsx_stxvw4x: { 13376 EVT VT; 13377 switch (Intrinsic) { 13378 case Intrinsic::ppc_altivec_stvebx: 13379 VT = MVT::i8; 13380 break; 13381 case Intrinsic::ppc_altivec_stvehx: 13382 VT = MVT::i16; 13383 break; 13384 case Intrinsic::ppc_altivec_stvewx: 13385 VT = MVT::i32; 13386 break; 13387 case Intrinsic::ppc_vsx_stxvd2x: 13388 VT = MVT::v2f64; 13389 break; 13390 case Intrinsic::ppc_qpx_qvstfd: 13391 VT = MVT::v4f64; 13392 break; 13393 case Intrinsic::ppc_qpx_qvstfs: 13394 VT = MVT::v4f32; 13395 break; 13396 case Intrinsic::ppc_qpx_qvstfcd: 13397 VT = MVT::v2f64; 13398 break; 13399 case Intrinsic::ppc_qpx_qvstfcs: 13400 VT = MVT::v2f32; 13401 break; 13402 default: 13403 VT = MVT::v4i32; 13404 break; 13405 } 13406 13407 Info.opc = ISD::INTRINSIC_VOID; 13408 Info.memVT = VT; 13409 Info.ptrVal = I.getArgOperand(1); 13410 Info.offset = -VT.getStoreSize()+1; 13411 Info.size = 2*VT.getStoreSize()-1; 13412 Info.align = 1; 13413 Info.vol = false; 13414 Info.readMem = false; 13415 Info.writeMem = true; 13416 return true; 13417 } 13418 case Intrinsic::ppc_qpx_qvstfda: 13419 case Intrinsic::ppc_qpx_qvstfsa: 13420 case Intrinsic::ppc_qpx_qvstfcda: 13421 case Intrinsic::ppc_qpx_qvstfcsa: 13422 case Intrinsic::ppc_qpx_qvstfiwa: { 13423 EVT VT; 13424 switch (Intrinsic) { 13425 case Intrinsic::ppc_qpx_qvstfda: 13426 VT = MVT::v4f64; 13427 break; 13428 case Intrinsic::ppc_qpx_qvstfsa: 13429 VT = MVT::v4f32; 13430 break; 13431 case Intrinsic::ppc_qpx_qvstfcda: 13432 VT = MVT::v2f64; 13433 break; 13434 case Intrinsic::ppc_qpx_qvstfcsa: 13435 VT = MVT::v2f32; 13436 break; 13437 default: 13438 VT = MVT::v4i32; 13439 break; 13440 } 13441 13442 Info.opc = ISD::INTRINSIC_VOID; 13443 Info.memVT = VT; 13444 Info.ptrVal = I.getArgOperand(1); 13445 Info.offset = 0; 13446 Info.size = VT.getStoreSize(); 13447 Info.align = 1; 13448 Info.vol = false; 13449 Info.readMem = false; 13450 Info.writeMem = true; 13451 return true; 13452 } 13453 default: 13454 break; 13455 } 13456 13457 return false; 13458 } 13459 13460 /// getOptimalMemOpType - Returns the target specific optimal type for load 13461 /// and store operations as a result of memset, memcpy, and memmove 13462 /// lowering. If DstAlign is zero that means it's safe to destination 13463 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 13464 /// means there isn't a need to check it against alignment requirement, 13465 /// probably because the source does not need to be loaded. If 'IsMemset' is 13466 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 13467 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 13468 /// source is constant so it does not need to be loaded. 13469 /// It returns EVT::Other if the type should be determined using generic 13470 /// target-independent logic. 13471 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, 13472 unsigned DstAlign, unsigned SrcAlign, 13473 bool IsMemset, bool ZeroMemset, 13474 bool MemcpyStrSrc, 13475 MachineFunction &MF) const { 13476 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 13477 const Function *F = MF.getFunction(); 13478 // When expanding a memset, require at least two QPX instructions to cover 13479 // the cost of loading the value to be stored from the constant pool. 13480 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 13481 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 13482 !F->hasFnAttribute(Attribute::NoImplicitFloat)) { 13483 return MVT::v4f64; 13484 } 13485 13486 // We should use Altivec/VSX loads and stores when available. For unaligned 13487 // addresses, unaligned VSX loads are only fast starting with the P8. 13488 if (Subtarget.hasAltivec() && Size >= 16 && 13489 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 13490 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 13491 return MVT::v4i32; 13492 } 13493 13494 if (Subtarget.isPPC64()) { 13495 return MVT::i64; 13496 } 13497 13498 return MVT::i32; 13499 } 13500 13501 /// \brief Returns true if it is beneficial to convert a load of a constant 13502 /// to just the constant itself. 13503 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 13504 Type *Ty) const { 13505 assert(Ty->isIntegerTy()); 13506 13507 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 13508 return !(BitSize == 0 || BitSize > 64); 13509 } 13510 13511 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 13512 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 13513 return false; 13514 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 13515 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 13516 return NumBits1 == 64 && NumBits2 == 32; 13517 } 13518 13519 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 13520 if (!VT1.isInteger() || !VT2.isInteger()) 13521 return false; 13522 unsigned NumBits1 = VT1.getSizeInBits(); 13523 unsigned NumBits2 = VT2.getSizeInBits(); 13524 return NumBits1 == 64 && NumBits2 == 32; 13525 } 13526 13527 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 13528 // Generally speaking, zexts are not free, but they are free when they can be 13529 // folded with other operations. 13530 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 13531 EVT MemVT = LD->getMemoryVT(); 13532 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 13533 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 13534 (LD->getExtensionType() == ISD::NON_EXTLOAD || 13535 LD->getExtensionType() == ISD::ZEXTLOAD)) 13536 return true; 13537 } 13538 13539 // FIXME: Add other cases... 13540 // - 32-bit shifts with a zext to i64 13541 // - zext after ctlz, bswap, etc. 13542 // - zext after and by a constant mask 13543 13544 return TargetLowering::isZExtFree(Val, VT2); 13545 } 13546 13547 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 13548 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 13549 "invalid fpext types"); 13550 return true; 13551 } 13552 13553 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 13554 return isInt<16>(Imm) || isUInt<16>(Imm); 13555 } 13556 13557 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 13558 return isInt<16>(Imm) || isUInt<16>(Imm); 13559 } 13560 13561 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 13562 unsigned, 13563 unsigned, 13564 bool *Fast) const { 13565 if (DisablePPCUnaligned) 13566 return false; 13567 13568 // PowerPC supports unaligned memory access for simple non-vector types. 13569 // Although accessing unaligned addresses is not as efficient as accessing 13570 // aligned addresses, it is generally more efficient than manual expansion, 13571 // and generally only traps for software emulation when crossing page 13572 // boundaries. 13573 13574 if (!VT.isSimple()) 13575 return false; 13576 13577 if (VT.getSimpleVT().isVector()) { 13578 if (Subtarget.hasVSX()) { 13579 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 13580 VT != MVT::v4f32 && VT != MVT::v4i32) 13581 return false; 13582 } else { 13583 return false; 13584 } 13585 } 13586 13587 if (VT == MVT::ppcf128) 13588 return false; 13589 13590 if (Fast) 13591 *Fast = true; 13592 13593 return true; 13594 } 13595 13596 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 13597 VT = VT.getScalarType(); 13598 13599 if (!VT.isSimple()) 13600 return false; 13601 13602 switch (VT.getSimpleVT().SimpleTy) { 13603 case MVT::f32: 13604 case MVT::f64: 13605 return true; 13606 default: 13607 break; 13608 } 13609 13610 return false; 13611 } 13612 13613 const MCPhysReg * 13614 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 13615 // LR is a callee-save register, but we must treat it as clobbered by any call 13616 // site. Hence we include LR in the scratch registers, which are in turn added 13617 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 13618 // to CTR, which is used by any indirect call. 13619 static const MCPhysReg ScratchRegs[] = { 13620 PPC::X12, PPC::LR8, PPC::CTR8, 0 13621 }; 13622 13623 return ScratchRegs; 13624 } 13625 13626 unsigned PPCTargetLowering::getExceptionPointerRegister( 13627 const Constant *PersonalityFn) const { 13628 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 13629 } 13630 13631 unsigned PPCTargetLowering::getExceptionSelectorRegister( 13632 const Constant *PersonalityFn) const { 13633 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 13634 } 13635 13636 bool 13637 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 13638 EVT VT , unsigned DefinedValues) const { 13639 if (VT == MVT::v2i64) 13640 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 13641 13642 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 13643 return true; 13644 13645 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 13646 } 13647 13648 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 13649 if (DisableILPPref || Subtarget.enableMachineScheduler()) 13650 return TargetLowering::getSchedulingPreference(N); 13651 13652 return Sched::ILP; 13653 } 13654 13655 // Create a fast isel object. 13656 FastISel * 13657 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 13658 const TargetLibraryInfo *LibInfo) const { 13659 return PPC::createFastISel(FuncInfo, LibInfo); 13660 } 13661 13662 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13663 if (Subtarget.isDarwinABI()) return; 13664 if (!Subtarget.isPPC64()) return; 13665 13666 // Update IsSplitCSR in PPCFunctionInfo 13667 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 13668 PFI->setIsSplitCSR(true); 13669 } 13670 13671 void PPCTargetLowering::insertCopiesSplitCSR( 13672 MachineBasicBlock *Entry, 13673 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13674 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 13675 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13676 if (!IStart) 13677 return; 13678 13679 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 13680 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13681 MachineBasicBlock::iterator MBBI = Entry->begin(); 13682 for (const MCPhysReg *I = IStart; *I; ++I) { 13683 const TargetRegisterClass *RC = nullptr; 13684 if (PPC::G8RCRegClass.contains(*I)) 13685 RC = &PPC::G8RCRegClass; 13686 else if (PPC::F8RCRegClass.contains(*I)) 13687 RC = &PPC::F8RCRegClass; 13688 else if (PPC::CRRCRegClass.contains(*I)) 13689 RC = &PPC::CRRCRegClass; 13690 else if (PPC::VRRCRegClass.contains(*I)) 13691 RC = &PPC::VRRCRegClass; 13692 else 13693 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13694 13695 unsigned NewVR = MRI->createVirtualRegister(RC); 13696 // Create copy from CSR to a virtual register. 13697 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13698 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13699 // nounwind. If we want to generalize this later, we may need to emit 13700 // CFI pseudo-instructions. 13701 assert(Entry->getParent()->getFunction()->hasFnAttribute( 13702 Attribute::NoUnwind) && 13703 "Function should be nounwind in insertCopiesSplitCSR!"); 13704 Entry->addLiveIn(*I); 13705 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13706 .addReg(*I); 13707 13708 // Insert the copy-back instructions right before the terminator 13709 for (auto *Exit : Exits) 13710 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13711 TII->get(TargetOpcode::COPY), *I) 13712 .addReg(NewVR); 13713 } 13714 } 13715 13716 // Override to enable LOAD_STACK_GUARD lowering on Linux. 13717 bool PPCTargetLowering::useLoadStackGuardNode() const { 13718 if (!Subtarget.isTargetLinux()) 13719 return TargetLowering::useLoadStackGuardNode(); 13720 return true; 13721 } 13722 13723 // Override to disable global variable loading on Linux. 13724 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 13725 if (!Subtarget.isTargetLinux()) 13726 return TargetLowering::insertSSPDeclarations(M); 13727 } 13728 13729 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 13730 if (!VT.isSimple() || !Subtarget.hasVSX()) 13731 return false; 13732 13733 switch(VT.getSimpleVT().SimpleTy) { 13734 default: 13735 // For FP types that are currently not supported by PPC backend, return 13736 // false. Examples: f16, f80. 13737 return false; 13738 case MVT::f32: 13739 case MVT::f64: 13740 case MVT::ppcf128: 13741 return Imm.isPosZero(); 13742 } 13743 } 13744 13745 // For vector shift operation op, fold 13746 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 13747 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 13748 SelectionDAG &DAG) { 13749 SDValue N0 = N->getOperand(0); 13750 SDValue N1 = N->getOperand(1); 13751 EVT VT = N0.getValueType(); 13752 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 13753 unsigned Opcode = N->getOpcode(); 13754 unsigned TargetOpcode; 13755 13756 switch (Opcode) { 13757 default: 13758 llvm_unreachable("Unexpected shift operation"); 13759 case ISD::SHL: 13760 TargetOpcode = PPCISD::SHL; 13761 break; 13762 case ISD::SRL: 13763 TargetOpcode = PPCISD::SRL; 13764 break; 13765 case ISD::SRA: 13766 TargetOpcode = PPCISD::SRA; 13767 break; 13768 } 13769 13770 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 13771 N1->getOpcode() == ISD::AND) 13772 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 13773 if (Mask->getZExtValue() == OpSizeInBits - 1) 13774 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 13775 13776 return SDValue(); 13777 } 13778 13779 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 13780 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13781 return Value; 13782 13783 return SDValue(); 13784 } 13785 13786 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 13787 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13788 return Value; 13789 13790 return SDValue(); 13791 } 13792 13793 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 13794 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 13795 return Value; 13796 13797 return SDValue(); 13798 } 13799