1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PPCISelLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCISelLowering.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCCCState.h" 17 #include "PPCCallingConv.h" 18 #include "PPCFrameLowering.h" 19 #include "PPCInstrInfo.h" 20 #include "PPCMachineFunctionInfo.h" 21 #include "PPCPerfectShuffle.h" 22 #include "PPCRegisterInfo.h" 23 #include "PPCSubtarget.h" 24 #include "PPCTargetMachine.h" 25 #include "llvm/ADT/APFloat.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/None.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallPtrSet.h" 32 #include "llvm/ADT/SmallSet.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/CodeGen/CallingConvLower.h" 38 #include "llvm/CodeGen/ISDOpcodes.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetInstrInfo.h" 54 #include "llvm/CodeGen/TargetLowering.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/Constant.h" 60 #include "llvm/IR/Constants.h" 61 #include "llvm/IR/DataLayout.h" 62 #include "llvm/IR/DebugLoc.h" 63 #include "llvm/IR/DerivedTypes.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/GlobalValue.h" 66 #include "llvm/IR/IRBuilder.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/Intrinsics.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSymbolXCOFF.h" 77 #include "llvm/Support/AtomicOrdering.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CodeGen.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MachineValueType.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include "llvm/Target/TargetMachine.h" 91 #include "llvm/Target/TargetOptions.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <list> 97 #include <utility> 98 #include <vector> 99 100 using namespace llvm; 101 102 #define DEBUG_TYPE "ppc-lowering" 103 104 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 105 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 106 107 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 108 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 109 110 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 111 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 112 113 static cl::opt<bool> DisableSCO("disable-ppc-sco", 114 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 115 116 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 117 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 118 119 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 120 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 121 122 STATISTIC(NumTailCalls, "Number of tail calls"); 123 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 124 125 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 126 127 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 128 129 // FIXME: Remove this once the bug has been fixed! 130 extern cl::opt<bool> ANDIGlueBug; 131 132 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 133 const PPCSubtarget &STI) 134 : TargetLowering(TM), Subtarget(STI) { 135 // Use _setjmp/_longjmp instead of setjmp/longjmp. 136 setUseUnderscoreSetJmp(true); 137 setUseUnderscoreLongJmp(true); 138 139 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 140 // arguments are at least 4/8 bytes aligned. 141 bool isPPC64 = Subtarget.isPPC64(); 142 setMinStackArgumentAlignment(isPPC64 ? 8:4); 143 144 // Set up the register classes. 145 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 146 if (!useSoftFloat()) { 147 if (hasSPE()) { 148 addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass); 149 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 150 } else { 151 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 152 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 153 } 154 } 155 156 // Match BITREVERSE to customized fast code sequence in the td file. 157 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 158 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 159 160 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 161 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 162 163 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 164 for (MVT VT : MVT::integer_valuetypes()) { 165 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 167 } 168 169 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 170 171 // PowerPC has pre-inc load and store's. 172 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 177 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 182 if (!Subtarget.hasSPE()) { 183 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 185 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 187 } 188 189 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 190 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 191 for (MVT VT : ScalarIntVTs) { 192 setOperationAction(ISD::ADDC, VT, Legal); 193 setOperationAction(ISD::ADDE, VT, Legal); 194 setOperationAction(ISD::SUBC, VT, Legal); 195 setOperationAction(ISD::SUBE, VT, Legal); 196 } 197 198 if (Subtarget.useCRBits()) { 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 200 201 if (isPPC64 || Subtarget.hasFPCVT()) { 202 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 203 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 204 isPPC64 ? MVT::i64 : MVT::i32); 205 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 206 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 207 isPPC64 ? MVT::i64 : MVT::i32); 208 } else { 209 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 211 } 212 213 // PowerPC does not support direct load/store of condition registers. 214 setOperationAction(ISD::LOAD, MVT::i1, Custom); 215 setOperationAction(ISD::STORE, MVT::i1, Custom); 216 217 // FIXME: Remove this once the ANDI glue bug is fixed: 218 if (ANDIGlueBug) 219 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 220 221 for (MVT VT : MVT::integer_valuetypes()) { 222 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 223 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 224 setTruncStoreAction(VT, MVT::i1, Expand); 225 } 226 227 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 228 } 229 230 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 231 // PPC (the libcall is not available). 232 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 233 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 234 235 // We do not currently implement these libm ops for PowerPC. 236 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 237 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 242 243 // PowerPC has no SREM/UREM instructions unless we are on P9 244 // On P9 we may use a hardware instruction to compute the remainder. 245 // The instructions are not legalized directly because in the cases where the 246 // result of both the remainder and the division is required it is more 247 // efficient to compute the remainder from the result of the division rather 248 // than use the remainder instruction. 249 if (Subtarget.isISA3_0()) { 250 setOperationAction(ISD::SREM, MVT::i32, Custom); 251 setOperationAction(ISD::UREM, MVT::i32, Custom); 252 setOperationAction(ISD::SREM, MVT::i64, Custom); 253 setOperationAction(ISD::UREM, MVT::i64, Custom); 254 } else { 255 setOperationAction(ISD::SREM, MVT::i32, Expand); 256 setOperationAction(ISD::UREM, MVT::i32, Expand); 257 setOperationAction(ISD::SREM, MVT::i64, Expand); 258 setOperationAction(ISD::UREM, MVT::i64, Expand); 259 } 260 261 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 262 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 263 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 265 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 267 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 269 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 270 271 // We don't support sin/cos/sqrt/fmod/pow 272 setOperationAction(ISD::FSIN , MVT::f64, Expand); 273 setOperationAction(ISD::FCOS , MVT::f64, Expand); 274 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 275 setOperationAction(ISD::FREM , MVT::f64, Expand); 276 setOperationAction(ISD::FPOW , MVT::f64, Expand); 277 setOperationAction(ISD::FSIN , MVT::f32, Expand); 278 setOperationAction(ISD::FCOS , MVT::f32, Expand); 279 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 280 setOperationAction(ISD::FREM , MVT::f32, Expand); 281 setOperationAction(ISD::FPOW , MVT::f32, Expand); 282 if (Subtarget.hasSPE()) { 283 setOperationAction(ISD::FMA , MVT::f64, Expand); 284 setOperationAction(ISD::FMA , MVT::f32, Expand); 285 } else { 286 setOperationAction(ISD::FMA , MVT::f64, Legal); 287 setOperationAction(ISD::FMA , MVT::f32, Legal); 288 } 289 290 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 291 292 // If we're enabling GP optimizations, use hardware square root 293 if (!Subtarget.hasFSQRT() && 294 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 295 Subtarget.hasFRE())) 296 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 297 298 if (!Subtarget.hasFSQRT() && 299 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 300 Subtarget.hasFRES())) 301 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 302 303 if (Subtarget.hasFCPSGN()) { 304 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 305 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 306 } else { 307 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 308 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 309 } 310 311 if (Subtarget.hasFPRND()) { 312 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 313 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 314 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 315 setOperationAction(ISD::FROUND, MVT::f64, Legal); 316 317 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 318 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 319 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 320 setOperationAction(ISD::FROUND, MVT::f32, Legal); 321 } 322 323 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 324 // to speed up scalar BSWAP64. 325 // CTPOP or CTTZ were introduced in P8/P9 respectively 326 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 327 if (Subtarget.hasP9Vector()) 328 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 329 else 330 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 331 if (Subtarget.isISA3_0()) { 332 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 333 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 334 } else { 335 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 336 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 337 } 338 339 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 340 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 341 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 342 } else { 343 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 344 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 345 } 346 347 // PowerPC does not have ROTR 348 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 349 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 350 351 if (!Subtarget.useCRBits()) { 352 // PowerPC does not have Select 353 setOperationAction(ISD::SELECT, MVT::i32, Expand); 354 setOperationAction(ISD::SELECT, MVT::i64, Expand); 355 setOperationAction(ISD::SELECT, MVT::f32, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Expand); 357 } 358 359 // PowerPC wants to turn select_cc of FP into fsel when possible. 360 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 361 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 362 363 // PowerPC wants to optimize integer setcc a bit 364 if (!Subtarget.useCRBits()) 365 setOperationAction(ISD::SETCC, MVT::i32, Custom); 366 367 // PowerPC does not have BRCOND which requires SetCC 368 if (!Subtarget.useCRBits()) 369 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 370 371 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 372 373 if (Subtarget.hasSPE()) { 374 // SPE has built-in conversions 375 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 378 } else { 379 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 380 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 381 382 // PowerPC does not have [U|S]INT_TO_FP 383 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 384 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 385 } 386 387 if (Subtarget.hasDirectMove() && isPPC64) { 388 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 389 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 391 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 392 } else { 393 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 394 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 395 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 396 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 397 } 398 399 // We cannot sextinreg(i1). Expand to shifts. 400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 401 402 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 403 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 404 // support continuation, user-level threading, and etc.. As a result, no 405 // other SjLj exception interfaces are implemented and please don't build 406 // your own exception handling based on them. 407 // LLVM/Clang supports zero-cost DWARF exception handling. 408 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 409 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 410 411 // We want to legalize GlobalAddress and ConstantPool nodes into the 412 // appropriate instructions to materialize the address. 413 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 414 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 415 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 416 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 417 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 418 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 419 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 420 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 421 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 422 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 423 424 // TRAP is legal. 425 setOperationAction(ISD::TRAP, MVT::Other, Legal); 426 427 // TRAMPOLINE is custom lowered. 428 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 429 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 430 431 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 432 setOperationAction(ISD::VASTART , MVT::Other, Custom); 433 434 if (Subtarget.isSVR4ABI()) { 435 if (isPPC64) { 436 // VAARG always uses double-word chunks, so promote anything smaller. 437 setOperationAction(ISD::VAARG, MVT::i1, Promote); 438 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); 439 setOperationAction(ISD::VAARG, MVT::i8, Promote); 440 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); 441 setOperationAction(ISD::VAARG, MVT::i16, Promote); 442 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); 443 setOperationAction(ISD::VAARG, MVT::i32, Promote); 444 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); 445 setOperationAction(ISD::VAARG, MVT::Other, Expand); 446 } else { 447 // VAARG is custom lowered with the 32-bit SVR4 ABI. 448 setOperationAction(ISD::VAARG, MVT::Other, Custom); 449 setOperationAction(ISD::VAARG, MVT::i64, Custom); 450 } 451 } else 452 setOperationAction(ISD::VAARG, MVT::Other, Expand); 453 454 if (Subtarget.isSVR4ABI() && !isPPC64) 455 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 456 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 457 else 458 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 459 460 // Use the default implementation. 461 setOperationAction(ISD::VAEND , MVT::Other, Expand); 462 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 463 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 464 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 465 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 466 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 467 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 468 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 469 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 470 471 // We want to custom lower some of our intrinsics. 472 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 473 474 // To handle counter-based loop conditions. 475 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 476 477 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 478 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 479 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 480 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 481 482 // Comparisons that require checking two conditions. 483 if (Subtarget.hasSPE()) { 484 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 485 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 486 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 487 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 488 } 489 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 490 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 491 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 492 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 493 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 497 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 498 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 499 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 500 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 501 502 if (Subtarget.has64BitSupport()) { 503 // They also have instructions for converting between i64 and fp. 504 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 505 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 506 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 507 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 508 // This is just the low 32 bits of a (signed) fp->i64 conversion. 509 // We cannot do this with Promote because i64 is not a legal type. 510 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 511 512 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 513 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 514 } else { 515 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 516 if (Subtarget.hasSPE()) 517 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 518 else 519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 520 } 521 522 // With the instructions enabled under FPCVT, we can do everything. 523 if (Subtarget.hasFPCVT()) { 524 if (Subtarget.has64BitSupport()) { 525 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 526 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 527 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 528 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 529 } 530 531 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 532 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 533 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 534 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 535 } 536 537 if (Subtarget.use64BitRegs()) { 538 // 64-bit PowerPC implementations can support i64 types directly 539 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 540 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 541 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 542 // 64-bit PowerPC wants to expand i128 shifts itself. 543 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 544 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 545 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 546 } else { 547 // 32-bit PowerPC wants to expand i64 shifts itself. 548 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 549 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 550 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 551 } 552 553 if (Subtarget.hasAltivec()) { 554 // First set operation action for all vector types to expand. Then we 555 // will selectively turn on ones that can be effectively codegen'd. 556 for (MVT VT : MVT::vector_valuetypes()) { 557 // add/sub are legal for all supported vector VT's. 558 setOperationAction(ISD::ADD, VT, Legal); 559 setOperationAction(ISD::SUB, VT, Legal); 560 561 // For v2i64, these are only valid with P8Vector. This is corrected after 562 // the loop. 563 setOperationAction(ISD::SMAX, VT, Legal); 564 setOperationAction(ISD::SMIN, VT, Legal); 565 setOperationAction(ISD::UMAX, VT, Legal); 566 setOperationAction(ISD::UMIN, VT, Legal); 567 568 if (Subtarget.hasVSX()) { 569 setOperationAction(ISD::FMAXNUM, VT, Legal); 570 setOperationAction(ISD::FMINNUM, VT, Legal); 571 } 572 573 // Vector instructions introduced in P8 574 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 575 setOperationAction(ISD::CTPOP, VT, Legal); 576 setOperationAction(ISD::CTLZ, VT, Legal); 577 } 578 else { 579 setOperationAction(ISD::CTPOP, VT, Expand); 580 setOperationAction(ISD::CTLZ, VT, Expand); 581 } 582 583 // Vector instructions introduced in P9 584 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 585 setOperationAction(ISD::CTTZ, VT, Legal); 586 else 587 setOperationAction(ISD::CTTZ, VT, Expand); 588 589 // We promote all shuffles to v16i8. 590 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 591 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 592 593 // We promote all non-typed operations to v4i32. 594 setOperationAction(ISD::AND , VT, Promote); 595 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 596 setOperationAction(ISD::OR , VT, Promote); 597 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 598 setOperationAction(ISD::XOR , VT, Promote); 599 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 600 setOperationAction(ISD::LOAD , VT, Promote); 601 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 602 setOperationAction(ISD::SELECT, VT, Promote); 603 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 604 setOperationAction(ISD::VSELECT, VT, Legal); 605 setOperationAction(ISD::SELECT_CC, VT, Promote); 606 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 607 setOperationAction(ISD::STORE, VT, Promote); 608 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 609 610 // No other operations are legal. 611 setOperationAction(ISD::MUL , VT, Expand); 612 setOperationAction(ISD::SDIV, VT, Expand); 613 setOperationAction(ISD::SREM, VT, Expand); 614 setOperationAction(ISD::UDIV, VT, Expand); 615 setOperationAction(ISD::UREM, VT, Expand); 616 setOperationAction(ISD::FDIV, VT, Expand); 617 setOperationAction(ISD::FREM, VT, Expand); 618 setOperationAction(ISD::FNEG, VT, Expand); 619 setOperationAction(ISD::FSQRT, VT, Expand); 620 setOperationAction(ISD::FLOG, VT, Expand); 621 setOperationAction(ISD::FLOG10, VT, Expand); 622 setOperationAction(ISD::FLOG2, VT, Expand); 623 setOperationAction(ISD::FEXP, VT, Expand); 624 setOperationAction(ISD::FEXP2, VT, Expand); 625 setOperationAction(ISD::FSIN, VT, Expand); 626 setOperationAction(ISD::FCOS, VT, Expand); 627 setOperationAction(ISD::FABS, VT, Expand); 628 setOperationAction(ISD::FFLOOR, VT, Expand); 629 setOperationAction(ISD::FCEIL, VT, Expand); 630 setOperationAction(ISD::FTRUNC, VT, Expand); 631 setOperationAction(ISD::FRINT, VT, Expand); 632 setOperationAction(ISD::FNEARBYINT, VT, Expand); 633 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 634 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 635 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 636 setOperationAction(ISD::MULHU, VT, Expand); 637 setOperationAction(ISD::MULHS, VT, Expand); 638 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 639 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 640 setOperationAction(ISD::UDIVREM, VT, Expand); 641 setOperationAction(ISD::SDIVREM, VT, Expand); 642 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 643 setOperationAction(ISD::FPOW, VT, Expand); 644 setOperationAction(ISD::BSWAP, VT, Expand); 645 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 646 setOperationAction(ISD::ROTL, VT, Expand); 647 setOperationAction(ISD::ROTR, VT, Expand); 648 649 for (MVT InnerVT : MVT::vector_valuetypes()) { 650 setTruncStoreAction(VT, InnerVT, Expand); 651 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 652 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 653 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 654 } 655 } 656 if (!Subtarget.hasP8Vector()) { 657 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 658 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 659 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 660 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 661 } 662 663 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 664 setOperationAction(ISD::ABS, VT, Custom); 665 666 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 667 // with merges, splats, etc. 668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 669 670 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 671 // are cheap, so handle them before they get expanded to scalar. 672 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 673 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 674 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 675 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 676 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 677 678 setOperationAction(ISD::AND , MVT::v4i32, Legal); 679 setOperationAction(ISD::OR , MVT::v4i32, Legal); 680 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 681 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 682 setOperationAction(ISD::SELECT, MVT::v4i32, 683 Subtarget.useCRBits() ? Legal : Expand); 684 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 685 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 686 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 687 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 688 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 689 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 690 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 691 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 692 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 693 694 // Without hasP8Altivec set, v2i64 SMAX isn't available. 695 // But ABS custom lowering requires SMAX support. 696 if (!Subtarget.hasP8Altivec()) 697 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 698 699 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 700 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 701 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 702 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 703 704 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 705 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 706 707 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 708 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 709 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 710 } 711 712 if (Subtarget.hasP8Altivec()) 713 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 714 else 715 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 716 717 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 718 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 719 720 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 721 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 722 723 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 724 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 725 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 726 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 727 728 // Altivec does not contain unordered floating-point compare instructions 729 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 730 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 731 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 732 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 733 734 if (Subtarget.hasVSX()) { 735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 737 if (Subtarget.hasP8Vector()) { 738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 739 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 740 } 741 if (Subtarget.hasDirectMove() && isPPC64) { 742 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 743 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 744 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 745 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 746 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 747 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 748 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 749 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 750 } 751 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 752 753 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 754 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 755 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 756 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 757 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 758 759 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 760 761 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 762 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 763 764 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 765 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 766 767 // Share the Altivec comparison restrictions. 768 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 769 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 770 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 771 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 772 773 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 774 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 775 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 777 778 if (Subtarget.hasP8Vector()) 779 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 780 781 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 782 783 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 784 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 785 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 786 787 if (Subtarget.hasP8Altivec()) { 788 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 789 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 790 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 791 792 // 128 bit shifts can be accomplished via 3 instructions for SHL and 793 // SRL, but not for SRA because of the instructions available: 794 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 795 // doing 796 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 797 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 798 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 799 800 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 801 } 802 else { 803 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 804 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 805 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 806 807 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 808 809 // VSX v2i64 only supports non-arithmetic operations. 810 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 811 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 812 } 813 814 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 815 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 816 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 817 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 818 819 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 820 821 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 822 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 823 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 824 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 825 826 // Custom handling for partial vectors of integers converted to 827 // floating point. We already have optimal handling for v2i32 through 828 // the DAG combine, so those aren't necessary. 829 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 830 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 831 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 832 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 833 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 834 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 835 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 836 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 837 838 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 839 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 840 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 841 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 842 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 843 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 844 845 if (Subtarget.hasDirectMove()) 846 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 847 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 848 849 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 850 } 851 852 if (Subtarget.hasP8Altivec()) { 853 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 854 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 855 } 856 857 if (Subtarget.hasP9Vector()) { 858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 860 861 // 128 bit shifts can be accomplished via 3 instructions for SHL and 862 // SRL, but not for SRA because of the instructions available: 863 // VS{RL} and VS{RL}O. 864 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 865 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 866 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 867 868 if (EnableQuadPrecision) { 869 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 870 setOperationAction(ISD::FADD, MVT::f128, Legal); 871 setOperationAction(ISD::FSUB, MVT::f128, Legal); 872 setOperationAction(ISD::FDIV, MVT::f128, Legal); 873 setOperationAction(ISD::FMUL, MVT::f128, Legal); 874 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 875 // No extending loads to f128 on PPC. 876 for (MVT FPT : MVT::fp_valuetypes()) 877 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 878 setOperationAction(ISD::FMA, MVT::f128, Legal); 879 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 880 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 881 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 882 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 883 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 884 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 885 886 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 887 setOperationAction(ISD::FRINT, MVT::f128, Legal); 888 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 889 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 890 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 891 setOperationAction(ISD::FROUND, MVT::f128, Legal); 892 893 setOperationAction(ISD::SELECT, MVT::f128, Expand); 894 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 895 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 896 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 897 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 898 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 899 // No implementation for these ops for PowerPC. 900 setOperationAction(ISD::FSIN , MVT::f128, Expand); 901 setOperationAction(ISD::FCOS , MVT::f128, Expand); 902 setOperationAction(ISD::FPOW, MVT::f128, Expand); 903 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 904 setOperationAction(ISD::FREM, MVT::f128, Expand); 905 } 906 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 907 908 } 909 910 if (Subtarget.hasP9Altivec()) { 911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 913 } 914 } 915 916 if (Subtarget.hasQPX()) { 917 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 918 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 919 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 920 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 921 922 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 923 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 924 925 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 926 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 927 928 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 929 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 930 931 if (!Subtarget.useCRBits()) 932 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 933 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 934 935 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 936 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 937 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 938 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 939 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 940 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 941 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 942 943 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 944 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 945 946 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 947 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); 948 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 949 950 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 951 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 952 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 953 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 954 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 955 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 956 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 957 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 958 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 959 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 960 961 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 962 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 963 964 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 965 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 966 967 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 968 969 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 970 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 971 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 972 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 973 974 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 975 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 976 977 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 978 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 979 980 if (!Subtarget.useCRBits()) 981 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 982 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 983 984 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 985 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 986 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 987 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 988 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 989 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 990 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 991 992 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 993 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 994 995 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 996 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 997 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 998 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 999 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1000 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1001 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1002 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1003 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1004 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1005 1006 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1007 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1008 1009 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1010 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1011 1012 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1013 1014 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1015 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1016 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1017 1018 if (!Subtarget.useCRBits()) 1019 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1020 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1021 1022 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1023 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1024 1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1026 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1027 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1028 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1029 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1030 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1032 1033 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1034 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1035 1036 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1037 1038 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1039 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1040 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1041 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1042 1043 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1044 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1045 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1046 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1047 1048 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1049 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1050 1051 // These need to set FE_INEXACT, and so cannot be vectorized here. 1052 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1053 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1054 1055 if (TM.Options.UnsafeFPMath) { 1056 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1057 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1058 1059 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1060 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1061 } else { 1062 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1063 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1064 1065 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1066 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1067 } 1068 } 1069 1070 if (Subtarget.has64BitSupport()) 1071 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1072 1073 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1074 1075 if (!isPPC64) { 1076 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1077 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1078 } 1079 1080 setBooleanContents(ZeroOrOneBooleanContent); 1081 1082 if (Subtarget.hasAltivec()) { 1083 // Altivec instructions set fields to all zeros or all ones. 1084 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1085 } 1086 1087 if (!isPPC64) { 1088 // These libcalls are not available in 32-bit. 1089 setLibcallName(RTLIB::SHL_I128, nullptr); 1090 setLibcallName(RTLIB::SRL_I128, nullptr); 1091 setLibcallName(RTLIB::SRA_I128, nullptr); 1092 } 1093 1094 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1095 1096 // We have target-specific dag combine patterns for the following nodes: 1097 setTargetDAGCombine(ISD::ADD); 1098 setTargetDAGCombine(ISD::SHL); 1099 setTargetDAGCombine(ISD::SRA); 1100 setTargetDAGCombine(ISD::SRL); 1101 setTargetDAGCombine(ISD::MUL); 1102 setTargetDAGCombine(ISD::SINT_TO_FP); 1103 setTargetDAGCombine(ISD::BUILD_VECTOR); 1104 if (Subtarget.hasFPCVT()) 1105 setTargetDAGCombine(ISD::UINT_TO_FP); 1106 setTargetDAGCombine(ISD::LOAD); 1107 setTargetDAGCombine(ISD::STORE); 1108 setTargetDAGCombine(ISD::BR_CC); 1109 if (Subtarget.useCRBits()) 1110 setTargetDAGCombine(ISD::BRCOND); 1111 setTargetDAGCombine(ISD::BSWAP); 1112 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1113 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1114 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1115 1116 setTargetDAGCombine(ISD::SIGN_EXTEND); 1117 setTargetDAGCombine(ISD::ZERO_EXTEND); 1118 setTargetDAGCombine(ISD::ANY_EXTEND); 1119 1120 setTargetDAGCombine(ISD::TRUNCATE); 1121 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1122 1123 1124 if (Subtarget.useCRBits()) { 1125 setTargetDAGCombine(ISD::TRUNCATE); 1126 setTargetDAGCombine(ISD::SETCC); 1127 setTargetDAGCombine(ISD::SELECT_CC); 1128 } 1129 1130 // Use reciprocal estimates. 1131 if (TM.Options.UnsafeFPMath) { 1132 setTargetDAGCombine(ISD::FDIV); 1133 setTargetDAGCombine(ISD::FSQRT); 1134 } 1135 1136 if (Subtarget.hasP9Altivec()) { 1137 setTargetDAGCombine(ISD::ABS); 1138 setTargetDAGCombine(ISD::VSELECT); 1139 } 1140 1141 // Darwin long double math library functions have $LDBL128 appended. 1142 if (Subtarget.isDarwin()) { 1143 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); 1144 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); 1145 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); 1146 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); 1147 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); 1148 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); 1149 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); 1150 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); 1151 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); 1152 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); 1153 } 1154 1155 if (EnableQuadPrecision) { 1156 setLibcallName(RTLIB::LOG_F128, "logf128"); 1157 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1158 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1159 setLibcallName(RTLIB::EXP_F128, "expf128"); 1160 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1161 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1162 setLibcallName(RTLIB::COS_F128, "cosf128"); 1163 setLibcallName(RTLIB::POW_F128, "powf128"); 1164 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1165 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1166 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1167 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1168 } 1169 1170 // With 32 condition bits, we don't need to sink (and duplicate) compares 1171 // aggressively in CodeGenPrep. 1172 if (Subtarget.useCRBits()) { 1173 setHasMultipleConditionRegisters(); 1174 setJumpIsExpensive(); 1175 } 1176 1177 setMinFunctionAlignment(2); 1178 if (Subtarget.isDarwin()) 1179 setPrefFunctionAlignment(4); 1180 1181 switch (Subtarget.getDarwinDirective()) { 1182 default: break; 1183 case PPC::DIR_970: 1184 case PPC::DIR_A2: 1185 case PPC::DIR_E500: 1186 case PPC::DIR_E500mc: 1187 case PPC::DIR_E5500: 1188 case PPC::DIR_PWR4: 1189 case PPC::DIR_PWR5: 1190 case PPC::DIR_PWR5X: 1191 case PPC::DIR_PWR6: 1192 case PPC::DIR_PWR6X: 1193 case PPC::DIR_PWR7: 1194 case PPC::DIR_PWR8: 1195 case PPC::DIR_PWR9: 1196 setPrefFunctionAlignment(4); 1197 setPrefLoopAlignment(4); 1198 break; 1199 } 1200 1201 if (Subtarget.enableMachineScheduler()) 1202 setSchedulingPreference(Sched::Source); 1203 else 1204 setSchedulingPreference(Sched::Hybrid); 1205 1206 computeRegisterProperties(STI.getRegisterInfo()); 1207 1208 // The Freescale cores do better with aggressive inlining of memcpy and 1209 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1210 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || 1211 Subtarget.getDarwinDirective() == PPC::DIR_E5500) { 1212 MaxStoresPerMemset = 32; 1213 MaxStoresPerMemsetOptSize = 16; 1214 MaxStoresPerMemcpy = 32; 1215 MaxStoresPerMemcpyOptSize = 8; 1216 MaxStoresPerMemmove = 32; 1217 MaxStoresPerMemmoveOptSize = 8; 1218 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { 1219 // The A2 also benefits from (very) aggressive inlining of memcpy and 1220 // friends. The overhead of a the function call, even when warm, can be 1221 // over one hundred cycles. 1222 MaxStoresPerMemset = 128; 1223 MaxStoresPerMemcpy = 128; 1224 MaxStoresPerMemmove = 128; 1225 MaxLoadsPerMemcmp = 128; 1226 } else { 1227 MaxLoadsPerMemcmp = 8; 1228 MaxLoadsPerMemcmpOptSize = 4; 1229 } 1230 } 1231 1232 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1233 /// the desired ByVal argument alignment. 1234 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1235 unsigned MaxMaxAlign) { 1236 if (MaxAlign == MaxMaxAlign) 1237 return; 1238 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1239 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1240 MaxAlign = 32; 1241 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1242 MaxAlign = 16; 1243 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1244 unsigned EltAlign = 0; 1245 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1246 if (EltAlign > MaxAlign) 1247 MaxAlign = EltAlign; 1248 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1249 for (auto *EltTy : STy->elements()) { 1250 unsigned EltAlign = 0; 1251 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1252 if (EltAlign > MaxAlign) 1253 MaxAlign = EltAlign; 1254 if (MaxAlign == MaxMaxAlign) 1255 break; 1256 } 1257 } 1258 } 1259 1260 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1261 /// function arguments in the caller parameter area. 1262 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1263 const DataLayout &DL) const { 1264 // Darwin passes everything on 4 byte boundary. 1265 if (Subtarget.isDarwin()) 1266 return 4; 1267 1268 // 16byte and wider vectors are passed on 16byte boundary. 1269 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1270 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1271 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1272 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1273 return Align; 1274 } 1275 1276 bool PPCTargetLowering::useSoftFloat() const { 1277 return Subtarget.useSoftFloat(); 1278 } 1279 1280 bool PPCTargetLowering::hasSPE() const { 1281 return Subtarget.hasSPE(); 1282 } 1283 1284 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1285 return VT.isScalarInteger(); 1286 } 1287 1288 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1289 switch ((PPCISD::NodeType)Opcode) { 1290 case PPCISD::FIRST_NUMBER: break; 1291 case PPCISD::FSEL: return "PPCISD::FSEL"; 1292 case PPCISD::FCFID: return "PPCISD::FCFID"; 1293 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1294 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1295 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1296 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1297 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1298 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1299 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1300 case PPCISD::FP_TO_UINT_IN_VSR: 1301 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1302 case PPCISD::FP_TO_SINT_IN_VSR: 1303 return "PPCISD::FP_TO_SINT_IN_VSR"; 1304 case PPCISD::FRE: return "PPCISD::FRE"; 1305 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1306 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1307 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1308 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1309 case PPCISD::VPERM: return "PPCISD::VPERM"; 1310 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1311 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1312 case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE"; 1313 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1314 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1315 case PPCISD::CMPB: return "PPCISD::CMPB"; 1316 case PPCISD::Hi: return "PPCISD::Hi"; 1317 case PPCISD::Lo: return "PPCISD::Lo"; 1318 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1319 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1320 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1321 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1322 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1323 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1324 case PPCISD::SRL: return "PPCISD::SRL"; 1325 case PPCISD::SRA: return "PPCISD::SRA"; 1326 case PPCISD::SHL: return "PPCISD::SHL"; 1327 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1328 case PPCISD::CALL: return "PPCISD::CALL"; 1329 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1330 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1331 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1332 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1333 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1334 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1335 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1336 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1337 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1338 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1339 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1340 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1341 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1342 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1343 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; 1344 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; 1345 case PPCISD::VCMP: return "PPCISD::VCMP"; 1346 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1347 case PPCISD::LBRX: return "PPCISD::LBRX"; 1348 case PPCISD::STBRX: return "PPCISD::STBRX"; 1349 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1350 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1351 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1352 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1353 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1354 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1355 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1356 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1357 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1358 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1359 case PPCISD::ST_VSR_SCAL_INT: 1360 return "PPCISD::ST_VSR_SCAL_INT"; 1361 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1362 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1363 case PPCISD::BDZ: return "PPCISD::BDZ"; 1364 case PPCISD::MFFS: return "PPCISD::MFFS"; 1365 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1366 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1367 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1368 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1369 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1370 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1371 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1372 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1373 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1374 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1375 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1376 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1377 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1378 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1379 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1380 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1381 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1382 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1383 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1384 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1385 case PPCISD::SC: return "PPCISD::SC"; 1386 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1387 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1388 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1389 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1390 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1391 case PPCISD::VABSD: return "PPCISD::VABSD"; 1392 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1393 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1394 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1395 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1396 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1397 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1398 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1399 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1400 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1401 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1402 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1403 case PPCISD::FP_EXTEND_LH: return "PPCISD::FP_EXTEND_LH"; 1404 } 1405 return nullptr; 1406 } 1407 1408 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1409 EVT VT) const { 1410 if (!VT.isVector()) 1411 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1412 1413 if (Subtarget.hasQPX()) 1414 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1415 1416 return VT.changeVectorElementTypeToInteger(); 1417 } 1418 1419 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1420 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1421 return true; 1422 } 1423 1424 //===----------------------------------------------------------------------===// 1425 // Node matching predicates, for use by the tblgen matching code. 1426 //===----------------------------------------------------------------------===// 1427 1428 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1429 static bool isFloatingPointZero(SDValue Op) { 1430 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1431 return CFP->getValueAPF().isZero(); 1432 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1433 // Maybe this has already been legalized into the constant pool? 1434 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1435 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1436 return CFP->getValueAPF().isZero(); 1437 } 1438 return false; 1439 } 1440 1441 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1442 /// true if Op is undef or if it matches the specified value. 1443 static bool isConstantOrUndef(int Op, int Val) { 1444 return Op < 0 || Op == Val; 1445 } 1446 1447 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1448 /// VPKUHUM instruction. 1449 /// The ShuffleKind distinguishes between big-endian operations with 1450 /// two different inputs (0), either-endian operations with two identical 1451 /// inputs (1), and little-endian operations with two different inputs (2). 1452 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1453 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1454 SelectionDAG &DAG) { 1455 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1456 if (ShuffleKind == 0) { 1457 if (IsLE) 1458 return false; 1459 for (unsigned i = 0; i != 16; ++i) 1460 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1461 return false; 1462 } else if (ShuffleKind == 2) { 1463 if (!IsLE) 1464 return false; 1465 for (unsigned i = 0; i != 16; ++i) 1466 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1467 return false; 1468 } else if (ShuffleKind == 1) { 1469 unsigned j = IsLE ? 0 : 1; 1470 for (unsigned i = 0; i != 8; ++i) 1471 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1472 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1473 return false; 1474 } 1475 return true; 1476 } 1477 1478 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1479 /// VPKUWUM instruction. 1480 /// The ShuffleKind distinguishes between big-endian operations with 1481 /// two different inputs (0), either-endian operations with two identical 1482 /// inputs (1), and little-endian operations with two different inputs (2). 1483 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1484 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1485 SelectionDAG &DAG) { 1486 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1487 if (ShuffleKind == 0) { 1488 if (IsLE) 1489 return false; 1490 for (unsigned i = 0; i != 16; i += 2) 1491 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1492 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1493 return false; 1494 } else if (ShuffleKind == 2) { 1495 if (!IsLE) 1496 return false; 1497 for (unsigned i = 0; i != 16; i += 2) 1498 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1499 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1500 return false; 1501 } else if (ShuffleKind == 1) { 1502 unsigned j = IsLE ? 0 : 2; 1503 for (unsigned i = 0; i != 8; i += 2) 1504 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1505 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1506 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1507 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1508 return false; 1509 } 1510 return true; 1511 } 1512 1513 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1514 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1515 /// current subtarget. 1516 /// 1517 /// The ShuffleKind distinguishes between big-endian operations with 1518 /// two different inputs (0), either-endian operations with two identical 1519 /// inputs (1), and little-endian operations with two different inputs (2). 1520 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1521 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1522 SelectionDAG &DAG) { 1523 const PPCSubtarget& Subtarget = 1524 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1525 if (!Subtarget.hasP8Vector()) 1526 return false; 1527 1528 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1529 if (ShuffleKind == 0) { 1530 if (IsLE) 1531 return false; 1532 for (unsigned i = 0; i != 16; i += 4) 1533 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1534 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1535 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1536 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1537 return false; 1538 } else if (ShuffleKind == 2) { 1539 if (!IsLE) 1540 return false; 1541 for (unsigned i = 0; i != 16; i += 4) 1542 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1543 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1544 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1545 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1546 return false; 1547 } else if (ShuffleKind == 1) { 1548 unsigned j = IsLE ? 0 : 4; 1549 for (unsigned i = 0; i != 8; i += 4) 1550 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1551 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1552 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1553 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1554 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1555 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1556 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1557 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1558 return false; 1559 } 1560 return true; 1561 } 1562 1563 /// isVMerge - Common function, used to match vmrg* shuffles. 1564 /// 1565 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1566 unsigned LHSStart, unsigned RHSStart) { 1567 if (N->getValueType(0) != MVT::v16i8) 1568 return false; 1569 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1570 "Unsupported merge size!"); 1571 1572 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1573 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1574 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1575 LHSStart+j+i*UnitSize) || 1576 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1577 RHSStart+j+i*UnitSize)) 1578 return false; 1579 } 1580 return true; 1581 } 1582 1583 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1584 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1585 /// The ShuffleKind distinguishes between big-endian merges with two 1586 /// different inputs (0), either-endian merges with two identical inputs (1), 1587 /// and little-endian merges with two different inputs (2). For the latter, 1588 /// the input operands are swapped (see PPCInstrAltivec.td). 1589 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1590 unsigned ShuffleKind, SelectionDAG &DAG) { 1591 if (DAG.getDataLayout().isLittleEndian()) { 1592 if (ShuffleKind == 1) // unary 1593 return isVMerge(N, UnitSize, 0, 0); 1594 else if (ShuffleKind == 2) // swapped 1595 return isVMerge(N, UnitSize, 0, 16); 1596 else 1597 return false; 1598 } else { 1599 if (ShuffleKind == 1) // unary 1600 return isVMerge(N, UnitSize, 8, 8); 1601 else if (ShuffleKind == 0) // normal 1602 return isVMerge(N, UnitSize, 8, 24); 1603 else 1604 return false; 1605 } 1606 } 1607 1608 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1609 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1610 /// The ShuffleKind distinguishes between big-endian merges with two 1611 /// different inputs (0), either-endian merges with two identical inputs (1), 1612 /// and little-endian merges with two different inputs (2). For the latter, 1613 /// the input operands are swapped (see PPCInstrAltivec.td). 1614 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1615 unsigned ShuffleKind, SelectionDAG &DAG) { 1616 if (DAG.getDataLayout().isLittleEndian()) { 1617 if (ShuffleKind == 1) // unary 1618 return isVMerge(N, UnitSize, 8, 8); 1619 else if (ShuffleKind == 2) // swapped 1620 return isVMerge(N, UnitSize, 8, 24); 1621 else 1622 return false; 1623 } else { 1624 if (ShuffleKind == 1) // unary 1625 return isVMerge(N, UnitSize, 0, 0); 1626 else if (ShuffleKind == 0) // normal 1627 return isVMerge(N, UnitSize, 0, 16); 1628 else 1629 return false; 1630 } 1631 } 1632 1633 /** 1634 * Common function used to match vmrgew and vmrgow shuffles 1635 * 1636 * The indexOffset determines whether to look for even or odd words in 1637 * the shuffle mask. This is based on the of the endianness of the target 1638 * machine. 1639 * - Little Endian: 1640 * - Use offset of 0 to check for odd elements 1641 * - Use offset of 4 to check for even elements 1642 * - Big Endian: 1643 * - Use offset of 0 to check for even elements 1644 * - Use offset of 4 to check for odd elements 1645 * A detailed description of the vector element ordering for little endian and 1646 * big endian can be found at 1647 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1648 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1649 * compiler differences mean to you 1650 * 1651 * The mask to the shuffle vector instruction specifies the indices of the 1652 * elements from the two input vectors to place in the result. The elements are 1653 * numbered in array-access order, starting with the first vector. These vectors 1654 * are always of type v16i8, thus each vector will contain 16 elements of size 1655 * 8. More info on the shuffle vector can be found in the 1656 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1657 * Language Reference. 1658 * 1659 * The RHSStartValue indicates whether the same input vectors are used (unary) 1660 * or two different input vectors are used, based on the following: 1661 * - If the instruction uses the same vector for both inputs, the range of the 1662 * indices will be 0 to 15. In this case, the RHSStart value passed should 1663 * be 0. 1664 * - If the instruction has two different vectors then the range of the 1665 * indices will be 0 to 31. In this case, the RHSStart value passed should 1666 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1667 * to 31 specify elements in the second vector). 1668 * 1669 * \param[in] N The shuffle vector SD Node to analyze 1670 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1671 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1672 * vector to the shuffle_vector instruction 1673 * \return true iff this shuffle vector represents an even or odd word merge 1674 */ 1675 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1676 unsigned RHSStartValue) { 1677 if (N->getValueType(0) != MVT::v16i8) 1678 return false; 1679 1680 for (unsigned i = 0; i < 2; ++i) 1681 for (unsigned j = 0; j < 4; ++j) 1682 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1683 i*RHSStartValue+j+IndexOffset) || 1684 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1685 i*RHSStartValue+j+IndexOffset+8)) 1686 return false; 1687 return true; 1688 } 1689 1690 /** 1691 * Determine if the specified shuffle mask is suitable for the vmrgew or 1692 * vmrgow instructions. 1693 * 1694 * \param[in] N The shuffle vector SD Node to analyze 1695 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1696 * \param[in] ShuffleKind Identify the type of merge: 1697 * - 0 = big-endian merge with two different inputs; 1698 * - 1 = either-endian merge with two identical inputs; 1699 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1700 * little-endian merges). 1701 * \param[in] DAG The current SelectionDAG 1702 * \return true iff this shuffle mask 1703 */ 1704 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1705 unsigned ShuffleKind, SelectionDAG &DAG) { 1706 if (DAG.getDataLayout().isLittleEndian()) { 1707 unsigned indexOffset = CheckEven ? 4 : 0; 1708 if (ShuffleKind == 1) // Unary 1709 return isVMerge(N, indexOffset, 0); 1710 else if (ShuffleKind == 2) // swapped 1711 return isVMerge(N, indexOffset, 16); 1712 else 1713 return false; 1714 } 1715 else { 1716 unsigned indexOffset = CheckEven ? 0 : 4; 1717 if (ShuffleKind == 1) // Unary 1718 return isVMerge(N, indexOffset, 0); 1719 else if (ShuffleKind == 0) // Normal 1720 return isVMerge(N, indexOffset, 16); 1721 else 1722 return false; 1723 } 1724 return false; 1725 } 1726 1727 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1728 /// amount, otherwise return -1. 1729 /// The ShuffleKind distinguishes between big-endian operations with two 1730 /// different inputs (0), either-endian operations with two identical inputs 1731 /// (1), and little-endian operations with two different inputs (2). For the 1732 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1733 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1734 SelectionDAG &DAG) { 1735 if (N->getValueType(0) != MVT::v16i8) 1736 return -1; 1737 1738 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1739 1740 // Find the first non-undef value in the shuffle mask. 1741 unsigned i; 1742 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1743 /*search*/; 1744 1745 if (i == 16) return -1; // all undef. 1746 1747 // Otherwise, check to see if the rest of the elements are consecutively 1748 // numbered from this value. 1749 unsigned ShiftAmt = SVOp->getMaskElt(i); 1750 if (ShiftAmt < i) return -1; 1751 1752 ShiftAmt -= i; 1753 bool isLE = DAG.getDataLayout().isLittleEndian(); 1754 1755 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1756 // Check the rest of the elements to see if they are consecutive. 1757 for (++i; i != 16; ++i) 1758 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1759 return -1; 1760 } else if (ShuffleKind == 1) { 1761 // Check the rest of the elements to see if they are consecutive. 1762 for (++i; i != 16; ++i) 1763 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1764 return -1; 1765 } else 1766 return -1; 1767 1768 if (isLE) 1769 ShiftAmt = 16 - ShiftAmt; 1770 1771 return ShiftAmt; 1772 } 1773 1774 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1775 /// specifies a splat of a single element that is suitable for input to 1776 /// VSPLTB/VSPLTH/VSPLTW. 1777 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1778 assert(N->getValueType(0) == MVT::v16i8 && 1779 (EltSize == 1 || EltSize == 2 || EltSize == 4)); 1780 1781 // The consecutive indices need to specify an element, not part of two 1782 // different elements. So abandon ship early if this isn't the case. 1783 if (N->getMaskElt(0) % EltSize != 0) 1784 return false; 1785 1786 // This is a splat operation if each element of the permute is the same, and 1787 // if the value doesn't reference the second vector. 1788 unsigned ElementBase = N->getMaskElt(0); 1789 1790 // FIXME: Handle UNDEF elements too! 1791 if (ElementBase >= 16) 1792 return false; 1793 1794 // Check that the indices are consecutive, in the case of a multi-byte element 1795 // splatted with a v16i8 mask. 1796 for (unsigned i = 1; i != EltSize; ++i) 1797 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1798 return false; 1799 1800 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1801 if (N->getMaskElt(i) < 0) continue; 1802 for (unsigned j = 0; j != EltSize; ++j) 1803 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1804 return false; 1805 } 1806 return true; 1807 } 1808 1809 /// Check that the mask is shuffling N byte elements. Within each N byte 1810 /// element of the mask, the indices could be either in increasing or 1811 /// decreasing order as long as they are consecutive. 1812 /// \param[in] N the shuffle vector SD Node to analyze 1813 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1814 /// Word/DoubleWord/QuadWord). 1815 /// \param[in] StepLen the delta indices number among the N byte element, if 1816 /// the mask is in increasing/decreasing order then it is 1/-1. 1817 /// \return true iff the mask is shuffling N byte elements. 1818 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1819 int StepLen) { 1820 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1821 "Unexpected element width."); 1822 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1823 1824 unsigned NumOfElem = 16 / Width; 1825 unsigned MaskVal[16]; // Width is never greater than 16 1826 for (unsigned i = 0; i < NumOfElem; ++i) { 1827 MaskVal[0] = N->getMaskElt(i * Width); 1828 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1829 return false; 1830 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1831 return false; 1832 } 1833 1834 for (unsigned int j = 1; j < Width; ++j) { 1835 MaskVal[j] = N->getMaskElt(i * Width + j); 1836 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1837 return false; 1838 } 1839 } 1840 } 1841 1842 return true; 1843 } 1844 1845 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1846 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1847 if (!isNByteElemShuffleMask(N, 4, 1)) 1848 return false; 1849 1850 // Now we look at mask elements 0,4,8,12 1851 unsigned M0 = N->getMaskElt(0) / 4; 1852 unsigned M1 = N->getMaskElt(4) / 4; 1853 unsigned M2 = N->getMaskElt(8) / 4; 1854 unsigned M3 = N->getMaskElt(12) / 4; 1855 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1856 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1857 1858 // Below, let H and L be arbitrary elements of the shuffle mask 1859 // where H is in the range [4,7] and L is in the range [0,3]. 1860 // H, 1, 2, 3 or L, 5, 6, 7 1861 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1862 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1863 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1864 InsertAtByte = IsLE ? 12 : 0; 1865 Swap = M0 < 4; 1866 return true; 1867 } 1868 // 0, H, 2, 3 or 4, L, 6, 7 1869 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1870 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1871 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1872 InsertAtByte = IsLE ? 8 : 4; 1873 Swap = M1 < 4; 1874 return true; 1875 } 1876 // 0, 1, H, 3 or 4, 5, L, 7 1877 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1878 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1879 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1880 InsertAtByte = IsLE ? 4 : 8; 1881 Swap = M2 < 4; 1882 return true; 1883 } 1884 // 0, 1, 2, H or 4, 5, 6, L 1885 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1886 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1887 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1888 InsertAtByte = IsLE ? 0 : 12; 1889 Swap = M3 < 4; 1890 return true; 1891 } 1892 1893 // If both vector operands for the shuffle are the same vector, the mask will 1894 // contain only elements from the first one and the second one will be undef. 1895 if (N->getOperand(1).isUndef()) { 1896 ShiftElts = 0; 1897 Swap = true; 1898 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1899 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1900 InsertAtByte = IsLE ? 12 : 0; 1901 return true; 1902 } 1903 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1904 InsertAtByte = IsLE ? 8 : 4; 1905 return true; 1906 } 1907 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1908 InsertAtByte = IsLE ? 4 : 8; 1909 return true; 1910 } 1911 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1912 InsertAtByte = IsLE ? 0 : 12; 1913 return true; 1914 } 1915 } 1916 1917 return false; 1918 } 1919 1920 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1921 bool &Swap, bool IsLE) { 1922 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1923 // Ensure each byte index of the word is consecutive. 1924 if (!isNByteElemShuffleMask(N, 4, 1)) 1925 return false; 1926 1927 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1928 unsigned M0 = N->getMaskElt(0) / 4; 1929 unsigned M1 = N->getMaskElt(4) / 4; 1930 unsigned M2 = N->getMaskElt(8) / 4; 1931 unsigned M3 = N->getMaskElt(12) / 4; 1932 1933 // If both vector operands for the shuffle are the same vector, the mask will 1934 // contain only elements from the first one and the second one will be undef. 1935 if (N->getOperand(1).isUndef()) { 1936 assert(M0 < 4 && "Indexing into an undef vector?"); 1937 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1938 return false; 1939 1940 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1941 Swap = false; 1942 return true; 1943 } 1944 1945 // Ensure each word index of the ShuffleVector Mask is consecutive. 1946 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1947 return false; 1948 1949 if (IsLE) { 1950 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1951 // Input vectors don't need to be swapped if the leading element 1952 // of the result is one of the 3 left elements of the second vector 1953 // (or if there is no shift to be done at all). 1954 Swap = false; 1955 ShiftElts = (8 - M0) % 8; 1956 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 1957 // Input vectors need to be swapped if the leading element 1958 // of the result is one of the 3 left elements of the first vector 1959 // (or if we're shifting by 4 - thereby simply swapping the vectors). 1960 Swap = true; 1961 ShiftElts = (4 - M0) % 4; 1962 } 1963 1964 return true; 1965 } else { // BE 1966 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 1967 // Input vectors don't need to be swapped if the leading element 1968 // of the result is one of the 4 elements of the first vector. 1969 Swap = false; 1970 ShiftElts = M0; 1971 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 1972 // Input vectors need to be swapped if the leading element 1973 // of the result is one of the 4 elements of the right vector. 1974 Swap = true; 1975 ShiftElts = M0 - 4; 1976 } 1977 1978 return true; 1979 } 1980 } 1981 1982 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 1983 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1984 1985 if (!isNByteElemShuffleMask(N, Width, -1)) 1986 return false; 1987 1988 for (int i = 0; i < 16; i += Width) 1989 if (N->getMaskElt(i) != i + Width - 1) 1990 return false; 1991 1992 return true; 1993 } 1994 1995 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 1996 return isXXBRShuffleMaskHelper(N, 2); 1997 } 1998 1999 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2000 return isXXBRShuffleMaskHelper(N, 4); 2001 } 2002 2003 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2004 return isXXBRShuffleMaskHelper(N, 8); 2005 } 2006 2007 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2008 return isXXBRShuffleMaskHelper(N, 16); 2009 } 2010 2011 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2012 /// if the inputs to the instruction should be swapped and set \p DM to the 2013 /// value for the immediate. 2014 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2015 /// AND element 0 of the result comes from the first input (LE) or second input 2016 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2017 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2018 /// mask. 2019 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2020 bool &Swap, bool IsLE) { 2021 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2022 2023 // Ensure each byte index of the double word is consecutive. 2024 if (!isNByteElemShuffleMask(N, 8, 1)) 2025 return false; 2026 2027 unsigned M0 = N->getMaskElt(0) / 8; 2028 unsigned M1 = N->getMaskElt(8) / 8; 2029 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2030 2031 // If both vector operands for the shuffle are the same vector, the mask will 2032 // contain only elements from the first one and the second one will be undef. 2033 if (N->getOperand(1).isUndef()) { 2034 if ((M0 | M1) < 2) { 2035 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2036 Swap = false; 2037 return true; 2038 } else 2039 return false; 2040 } 2041 2042 if (IsLE) { 2043 if (M0 > 1 && M1 < 2) { 2044 Swap = false; 2045 } else if (M0 < 2 && M1 > 1) { 2046 M0 = (M0 + 2) % 4; 2047 M1 = (M1 + 2) % 4; 2048 Swap = true; 2049 } else 2050 return false; 2051 2052 // Note: if control flow comes here that means Swap is already set above 2053 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2054 return true; 2055 } else { // BE 2056 if (M0 < 2 && M1 > 1) { 2057 Swap = false; 2058 } else if (M0 > 1 && M1 < 2) { 2059 M0 = (M0 + 2) % 4; 2060 M1 = (M1 + 2) % 4; 2061 Swap = true; 2062 } else 2063 return false; 2064 2065 // Note: if control flow comes here that means Swap is already set above 2066 DM = (M0 << 1) + (M1 & 1); 2067 return true; 2068 } 2069 } 2070 2071 2072 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the 2073 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. 2074 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, 2075 SelectionDAG &DAG) { 2076 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2077 assert(isSplatShuffleMask(SVOp, EltSize)); 2078 if (DAG.getDataLayout().isLittleEndian()) 2079 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2080 else 2081 return SVOp->getMaskElt(0) / EltSize; 2082 } 2083 2084 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2085 /// by using a vspltis[bhw] instruction of the specified element size, return 2086 /// the constant being splatted. The ByteSize field indicates the number of 2087 /// bytes of each element [124] -> [bhw]. 2088 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2089 SDValue OpVal(nullptr, 0); 2090 2091 // If ByteSize of the splat is bigger than the element size of the 2092 // build_vector, then we have a case where we are checking for a splat where 2093 // multiple elements of the buildvector are folded together into a single 2094 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2095 unsigned EltSize = 16/N->getNumOperands(); 2096 if (EltSize < ByteSize) { 2097 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2098 SDValue UniquedVals[4]; 2099 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2100 2101 // See if all of the elements in the buildvector agree across. 2102 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2103 if (N->getOperand(i).isUndef()) continue; 2104 // If the element isn't a constant, bail fully out. 2105 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2106 2107 if (!UniquedVals[i&(Multiple-1)].getNode()) 2108 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2109 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2110 return SDValue(); // no match. 2111 } 2112 2113 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2114 // either constant or undef values that are identical for each chunk. See 2115 // if these chunks can form into a larger vspltis*. 2116 2117 // Check to see if all of the leading entries are either 0 or -1. If 2118 // neither, then this won't fit into the immediate field. 2119 bool LeadingZero = true; 2120 bool LeadingOnes = true; 2121 for (unsigned i = 0; i != Multiple-1; ++i) { 2122 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2123 2124 LeadingZero &= isNullConstant(UniquedVals[i]); 2125 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2126 } 2127 // Finally, check the least significant entry. 2128 if (LeadingZero) { 2129 if (!UniquedVals[Multiple-1].getNode()) 2130 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2131 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2132 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2133 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2134 } 2135 if (LeadingOnes) { 2136 if (!UniquedVals[Multiple-1].getNode()) 2137 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2138 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2139 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2140 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2141 } 2142 2143 return SDValue(); 2144 } 2145 2146 // Check to see if this buildvec has a single non-undef value in its elements. 2147 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2148 if (N->getOperand(i).isUndef()) continue; 2149 if (!OpVal.getNode()) 2150 OpVal = N->getOperand(i); 2151 else if (OpVal != N->getOperand(i)) 2152 return SDValue(); 2153 } 2154 2155 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2156 2157 unsigned ValSizeInBytes = EltSize; 2158 uint64_t Value = 0; 2159 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2160 Value = CN->getZExtValue(); 2161 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2162 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2163 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2164 } 2165 2166 // If the splat value is larger than the element value, then we can never do 2167 // this splat. The only case that we could fit the replicated bits into our 2168 // immediate field for would be zero, and we prefer to use vxor for it. 2169 if (ValSizeInBytes < ByteSize) return SDValue(); 2170 2171 // If the element value is larger than the splat value, check if it consists 2172 // of a repeated bit pattern of size ByteSize. 2173 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2174 return SDValue(); 2175 2176 // Properly sign extend the value. 2177 int MaskVal = SignExtend32(Value, ByteSize * 8); 2178 2179 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2180 if (MaskVal == 0) return SDValue(); 2181 2182 // Finally, if this value fits in a 5 bit sext field, return it 2183 if (SignExtend32<5>(MaskVal) == MaskVal) 2184 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2185 return SDValue(); 2186 } 2187 2188 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2189 /// amount, otherwise return -1. 2190 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2191 EVT VT = N->getValueType(0); 2192 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2193 return -1; 2194 2195 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2196 2197 // Find the first non-undef value in the shuffle mask. 2198 unsigned i; 2199 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2200 /*search*/; 2201 2202 if (i == 4) return -1; // all undef. 2203 2204 // Otherwise, check to see if the rest of the elements are consecutively 2205 // numbered from this value. 2206 unsigned ShiftAmt = SVOp->getMaskElt(i); 2207 if (ShiftAmt < i) return -1; 2208 ShiftAmt -= i; 2209 2210 // Check the rest of the elements to see if they are consecutive. 2211 for (++i; i != 4; ++i) 2212 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2213 return -1; 2214 2215 return ShiftAmt; 2216 } 2217 2218 //===----------------------------------------------------------------------===// 2219 // Addressing Mode Selection 2220 //===----------------------------------------------------------------------===// 2221 2222 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2223 /// or 64-bit immediate, and if the value can be accurately represented as a 2224 /// sign extension from a 16-bit value. If so, this returns true and the 2225 /// immediate. 2226 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2227 if (!isa<ConstantSDNode>(N)) 2228 return false; 2229 2230 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2231 if (N->getValueType(0) == MVT::i32) 2232 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2233 else 2234 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2235 } 2236 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2237 return isIntS16Immediate(Op.getNode(), Imm); 2238 } 2239 2240 2241 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2242 /// be represented as an indexed [r+r] operation. 2243 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2244 SDValue &Index, 2245 SelectionDAG &DAG) const { 2246 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2247 UI != E; ++UI) { 2248 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2249 if (Memop->getMemoryVT() == MVT::f64) { 2250 Base = N.getOperand(0); 2251 Index = N.getOperand(1); 2252 return true; 2253 } 2254 } 2255 } 2256 return false; 2257 } 2258 2259 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2260 /// can be represented as an indexed [r+r] operation. Returns false if it 2261 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2262 /// non-zero and N can be represented by a base register plus a signed 16-bit 2263 /// displacement, make a more precise judgement by checking (displacement % \p 2264 /// EncodingAlignment). 2265 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2266 SDValue &Index, SelectionDAG &DAG, 2267 unsigned EncodingAlignment) const { 2268 int16_t imm = 0; 2269 if (N.getOpcode() == ISD::ADD) { 2270 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2271 // SPE load/store can only handle 8-bit offsets. 2272 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2273 return true; 2274 if (isIntS16Immediate(N.getOperand(1), imm) && 2275 (!EncodingAlignment || !(imm % EncodingAlignment))) 2276 return false; // r+i 2277 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2278 return false; // r+i 2279 2280 Base = N.getOperand(0); 2281 Index = N.getOperand(1); 2282 return true; 2283 } else if (N.getOpcode() == ISD::OR) { 2284 if (isIntS16Immediate(N.getOperand(1), imm) && 2285 (!EncodingAlignment || !(imm % EncodingAlignment))) 2286 return false; // r+i can fold it if we can. 2287 2288 // If this is an or of disjoint bitfields, we can codegen this as an add 2289 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2290 // disjoint. 2291 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2292 2293 if (LHSKnown.Zero.getBoolValue()) { 2294 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2295 // If all of the bits are known zero on the LHS or RHS, the add won't 2296 // carry. 2297 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2298 Base = N.getOperand(0); 2299 Index = N.getOperand(1); 2300 return true; 2301 } 2302 } 2303 } 2304 2305 return false; 2306 } 2307 2308 // If we happen to be doing an i64 load or store into a stack slot that has 2309 // less than a 4-byte alignment, then the frame-index elimination may need to 2310 // use an indexed load or store instruction (because the offset may not be a 2311 // multiple of 4). The extra register needed to hold the offset comes from the 2312 // register scavenger, and it is possible that the scavenger will need to use 2313 // an emergency spill slot. As a result, we need to make sure that a spill slot 2314 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2315 // stack slot. 2316 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2317 // FIXME: This does not handle the LWA case. 2318 if (VT != MVT::i64) 2319 return; 2320 2321 // NOTE: We'll exclude negative FIs here, which come from argument 2322 // lowering, because there are no known test cases triggering this problem 2323 // using packed structures (or similar). We can remove this exclusion if 2324 // we find such a test case. The reason why this is so test-case driven is 2325 // because this entire 'fixup' is only to prevent crashes (from the 2326 // register scavenger) on not-really-valid inputs. For example, if we have: 2327 // %a = alloca i1 2328 // %b = bitcast i1* %a to i64* 2329 // store i64* a, i64 b 2330 // then the store should really be marked as 'align 1', but is not. If it 2331 // were marked as 'align 1' then the indexed form would have been 2332 // instruction-selected initially, and the problem this 'fixup' is preventing 2333 // won't happen regardless. 2334 if (FrameIdx < 0) 2335 return; 2336 2337 MachineFunction &MF = DAG.getMachineFunction(); 2338 MachineFrameInfo &MFI = MF.getFrameInfo(); 2339 2340 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2341 if (Align >= 4) 2342 return; 2343 2344 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2345 FuncInfo->setHasNonRISpills(); 2346 } 2347 2348 /// Returns true if the address N can be represented by a base register plus 2349 /// a signed 16-bit displacement [r+imm], and if it is not better 2350 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2351 /// displacements that are multiples of that value. 2352 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2353 SDValue &Base, 2354 SelectionDAG &DAG, 2355 unsigned EncodingAlignment) const { 2356 // FIXME dl should come from parent load or store, not from address 2357 SDLoc dl(N); 2358 // If this can be more profitably realized as r+r, fail. 2359 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2360 return false; 2361 2362 if (N.getOpcode() == ISD::ADD) { 2363 int16_t imm = 0; 2364 if (isIntS16Immediate(N.getOperand(1), imm) && 2365 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2366 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2367 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2368 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2369 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2370 } else { 2371 Base = N.getOperand(0); 2372 } 2373 return true; // [r+i] 2374 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2375 // Match LOAD (ADD (X, Lo(G))). 2376 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2377 && "Cannot handle constant offsets yet!"); 2378 Disp = N.getOperand(1).getOperand(0); // The global address. 2379 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2380 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2381 Disp.getOpcode() == ISD::TargetConstantPool || 2382 Disp.getOpcode() == ISD::TargetJumpTable); 2383 Base = N.getOperand(0); 2384 return true; // [&g+r] 2385 } 2386 } else if (N.getOpcode() == ISD::OR) { 2387 int16_t imm = 0; 2388 if (isIntS16Immediate(N.getOperand(1), imm) && 2389 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2390 // If this is an or of disjoint bitfields, we can codegen this as an add 2391 // (for better address arithmetic) if the LHS and RHS of the OR are 2392 // provably disjoint. 2393 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2394 2395 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2396 // If all of the bits are known zero on the LHS or RHS, the add won't 2397 // carry. 2398 if (FrameIndexSDNode *FI = 2399 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2400 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2401 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2402 } else { 2403 Base = N.getOperand(0); 2404 } 2405 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2406 return true; 2407 } 2408 } 2409 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2410 // Loading from a constant address. 2411 2412 // If this address fits entirely in a 16-bit sext immediate field, codegen 2413 // this as "d, 0" 2414 int16_t Imm; 2415 if (isIntS16Immediate(CN, Imm) && 2416 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2417 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2418 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2419 CN->getValueType(0)); 2420 return true; 2421 } 2422 2423 // Handle 32-bit sext immediates with LIS + addr mode. 2424 if ((CN->getValueType(0) == MVT::i32 || 2425 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2426 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2427 int Addr = (int)CN->getZExtValue(); 2428 2429 // Otherwise, break this down into an LIS + disp. 2430 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2431 2432 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2433 MVT::i32); 2434 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2435 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2436 return true; 2437 } 2438 } 2439 2440 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2441 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2442 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2443 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2444 } else 2445 Base = N; 2446 return true; // [r+0] 2447 } 2448 2449 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2450 /// represented as an indexed [r+r] operation. 2451 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2452 SDValue &Index, 2453 SelectionDAG &DAG) const { 2454 // Check to see if we can easily represent this as an [r+r] address. This 2455 // will fail if it thinks that the address is more profitably represented as 2456 // reg+imm, e.g. where imm = 0. 2457 if (SelectAddressRegReg(N, Base, Index, DAG)) 2458 return true; 2459 2460 // If the address is the result of an add, we will utilize the fact that the 2461 // address calculation includes an implicit add. However, we can reduce 2462 // register pressure if we do not materialize a constant just for use as the 2463 // index register. We only get rid of the add if it is not an add of a 2464 // value and a 16-bit signed constant and both have a single use. 2465 int16_t imm = 0; 2466 if (N.getOpcode() == ISD::ADD && 2467 (!isIntS16Immediate(N.getOperand(1), imm) || 2468 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2469 Base = N.getOperand(0); 2470 Index = N.getOperand(1); 2471 return true; 2472 } 2473 2474 // Otherwise, do it the hard way, using R0 as the base register. 2475 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2476 N.getValueType()); 2477 Index = N; 2478 return true; 2479 } 2480 2481 /// Returns true if we should use a direct load into vector instruction 2482 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2483 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2484 2485 // If there are any other uses other than scalar to vector, then we should 2486 // keep it as a scalar load -> direct move pattern to prevent multiple 2487 // loads. 2488 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2489 if (!LD) 2490 return false; 2491 2492 EVT MemVT = LD->getMemoryVT(); 2493 if (!MemVT.isSimple()) 2494 return false; 2495 switch(MemVT.getSimpleVT().SimpleTy) { 2496 case MVT::i64: 2497 break; 2498 case MVT::i32: 2499 if (!ST.hasP8Vector()) 2500 return false; 2501 break; 2502 case MVT::i16: 2503 case MVT::i8: 2504 if (!ST.hasP9Vector()) 2505 return false; 2506 break; 2507 default: 2508 return false; 2509 } 2510 2511 SDValue LoadedVal(N, 0); 2512 if (!LoadedVal.hasOneUse()) 2513 return false; 2514 2515 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2516 UI != UE; ++UI) 2517 if (UI.getUse().get().getResNo() == 0 && 2518 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2519 return false; 2520 2521 return true; 2522 } 2523 2524 /// getPreIndexedAddressParts - returns true by value, base pointer and 2525 /// offset pointer and addressing mode by reference if the node's address 2526 /// can be legally represented as pre-indexed load / store address. 2527 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2528 SDValue &Offset, 2529 ISD::MemIndexedMode &AM, 2530 SelectionDAG &DAG) const { 2531 if (DisablePPCPreinc) return false; 2532 2533 bool isLoad = true; 2534 SDValue Ptr; 2535 EVT VT; 2536 unsigned Alignment; 2537 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2538 Ptr = LD->getBasePtr(); 2539 VT = LD->getMemoryVT(); 2540 Alignment = LD->getAlignment(); 2541 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2542 Ptr = ST->getBasePtr(); 2543 VT = ST->getMemoryVT(); 2544 Alignment = ST->getAlignment(); 2545 isLoad = false; 2546 } else 2547 return false; 2548 2549 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2550 // instructions because we can fold these into a more efficient instruction 2551 // instead, (such as LXSD). 2552 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2553 return false; 2554 } 2555 2556 // PowerPC doesn't have preinc load/store instructions for vectors (except 2557 // for QPX, which does have preinc r+r forms). 2558 if (VT.isVector()) { 2559 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2560 return false; 2561 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2562 AM = ISD::PRE_INC; 2563 return true; 2564 } 2565 } 2566 2567 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2568 // Common code will reject creating a pre-inc form if the base pointer 2569 // is a frame index, or if N is a store and the base pointer is either 2570 // the same as or a predecessor of the value being stored. Check for 2571 // those situations here, and try with swapped Base/Offset instead. 2572 bool Swap = false; 2573 2574 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2575 Swap = true; 2576 else if (!isLoad) { 2577 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2578 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2579 Swap = true; 2580 } 2581 2582 if (Swap) 2583 std::swap(Base, Offset); 2584 2585 AM = ISD::PRE_INC; 2586 return true; 2587 } 2588 2589 // LDU/STU can only handle immediates that are a multiple of 4. 2590 if (VT != MVT::i64) { 2591 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2592 return false; 2593 } else { 2594 // LDU/STU need an address with at least 4-byte alignment. 2595 if (Alignment < 4) 2596 return false; 2597 2598 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2599 return false; 2600 } 2601 2602 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2603 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2604 // sext i32 to i64 when addr mode is r+i. 2605 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2606 LD->getExtensionType() == ISD::SEXTLOAD && 2607 isa<ConstantSDNode>(Offset)) 2608 return false; 2609 } 2610 2611 AM = ISD::PRE_INC; 2612 return true; 2613 } 2614 2615 //===----------------------------------------------------------------------===// 2616 // LowerOperation implementation 2617 //===----------------------------------------------------------------------===// 2618 2619 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2620 /// and LoOpFlags to the target MO flags. 2621 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2622 unsigned &HiOpFlags, unsigned &LoOpFlags, 2623 const GlobalValue *GV = nullptr) { 2624 HiOpFlags = PPCII::MO_HA; 2625 LoOpFlags = PPCII::MO_LO; 2626 2627 // Don't use the pic base if not in PIC relocation model. 2628 if (IsPIC) { 2629 HiOpFlags |= PPCII::MO_PIC_FLAG; 2630 LoOpFlags |= PPCII::MO_PIC_FLAG; 2631 } 2632 2633 // If this is a reference to a global value that requires a non-lazy-ptr, make 2634 // sure that instruction lowering adds it. 2635 if (GV && Subtarget.hasLazyResolverStub(GV)) { 2636 HiOpFlags |= PPCII::MO_NLP_FLAG; 2637 LoOpFlags |= PPCII::MO_NLP_FLAG; 2638 2639 if (GV->hasHiddenVisibility()) { 2640 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2641 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; 2642 } 2643 } 2644 } 2645 2646 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2647 SelectionDAG &DAG) { 2648 SDLoc DL(HiPart); 2649 EVT PtrVT = HiPart.getValueType(); 2650 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2651 2652 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2653 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2654 2655 // With PIC, the first instruction is actually "GR+hi(&G)". 2656 if (isPIC) 2657 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2658 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2659 2660 // Generate non-pic code that has direct accesses to the constant pool. 2661 // The address of the global is just (hi(&g)+lo(&g)). 2662 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2663 } 2664 2665 static void setUsesTOCBasePtr(MachineFunction &MF) { 2666 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2667 FuncInfo->setUsesTOCBasePtr(); 2668 } 2669 2670 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2671 setUsesTOCBasePtr(DAG.getMachineFunction()); 2672 } 2673 2674 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit, 2675 SDValue GA) { 2676 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2677 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : 2678 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2679 2680 SDValue Ops[] = { GA, Reg }; 2681 return DAG.getMemIntrinsicNode( 2682 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2683 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2684 MachineMemOperand::MOLoad); 2685 } 2686 2687 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2688 SelectionDAG &DAG) const { 2689 EVT PtrVT = Op.getValueType(); 2690 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2691 const Constant *C = CP->getConstVal(); 2692 2693 // 64-bit SVR4 ABI code is always position-independent. 2694 // The actual address of the GlobalValue is stored in the TOC. 2695 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2696 setUsesTOCBasePtr(DAG); 2697 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2698 return getTOCEntry(DAG, SDLoc(CP), true, GA); 2699 } 2700 2701 unsigned MOHiFlag, MOLoFlag; 2702 bool IsPIC = isPositionIndependent(); 2703 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2704 2705 if (IsPIC && Subtarget.isSVR4ABI()) { 2706 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2707 PPCII::MO_PIC_FLAG); 2708 return getTOCEntry(DAG, SDLoc(CP), false, GA); 2709 } 2710 2711 SDValue CPIHi = 2712 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2713 SDValue CPILo = 2714 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2715 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2716 } 2717 2718 // For 64-bit PowerPC, prefer the more compact relative encodings. 2719 // This trades 32 bits per jump table entry for one or two instructions 2720 // on the jump site. 2721 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2722 if (isJumpTableRelative()) 2723 return MachineJumpTableInfo::EK_LabelDifference32; 2724 2725 return TargetLowering::getJumpTableEncoding(); 2726 } 2727 2728 bool PPCTargetLowering::isJumpTableRelative() const { 2729 if (Subtarget.isPPC64()) 2730 return true; 2731 return TargetLowering::isJumpTableRelative(); 2732 } 2733 2734 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2735 SelectionDAG &DAG) const { 2736 if (!Subtarget.isPPC64()) 2737 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2738 2739 switch (getTargetMachine().getCodeModel()) { 2740 case CodeModel::Small: 2741 case CodeModel::Medium: 2742 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2743 default: 2744 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2745 getPointerTy(DAG.getDataLayout())); 2746 } 2747 } 2748 2749 const MCExpr * 2750 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2751 unsigned JTI, 2752 MCContext &Ctx) const { 2753 if (!Subtarget.isPPC64()) 2754 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2755 2756 switch (getTargetMachine().getCodeModel()) { 2757 case CodeModel::Small: 2758 case CodeModel::Medium: 2759 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2760 default: 2761 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2762 } 2763 } 2764 2765 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2766 EVT PtrVT = Op.getValueType(); 2767 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2768 2769 // 64-bit SVR4 ABI code is always position-independent. 2770 // The actual address of the GlobalValue is stored in the TOC. 2771 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2772 setUsesTOCBasePtr(DAG); 2773 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2774 return getTOCEntry(DAG, SDLoc(JT), true, GA); 2775 } 2776 2777 unsigned MOHiFlag, MOLoFlag; 2778 bool IsPIC = isPositionIndependent(); 2779 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2780 2781 if (IsPIC && Subtarget.isSVR4ABI()) { 2782 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2783 PPCII::MO_PIC_FLAG); 2784 return getTOCEntry(DAG, SDLoc(GA), false, GA); 2785 } 2786 2787 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2788 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2789 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2790 } 2791 2792 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2793 SelectionDAG &DAG) const { 2794 EVT PtrVT = Op.getValueType(); 2795 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2796 const BlockAddress *BA = BASDN->getBlockAddress(); 2797 2798 // 64-bit SVR4 ABI code is always position-independent. 2799 // The actual BlockAddress is stored in the TOC. 2800 if (Subtarget.isSVR4ABI() && 2801 (Subtarget.isPPC64() || isPositionIndependent())) { 2802 if (Subtarget.isPPC64()) 2803 setUsesTOCBasePtr(DAG); 2804 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2805 return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA); 2806 } 2807 2808 unsigned MOHiFlag, MOLoFlag; 2809 bool IsPIC = isPositionIndependent(); 2810 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2811 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2812 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2813 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2814 } 2815 2816 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2817 SelectionDAG &DAG) const { 2818 // FIXME: TLS addresses currently use medium model code sequences, 2819 // which is the most useful form. Eventually support for small and 2820 // large models could be added if users need it, at the cost of 2821 // additional complexity. 2822 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2823 if (DAG.getTarget().useEmulatedTLS()) 2824 return LowerToTLSEmulatedModel(GA, DAG); 2825 2826 SDLoc dl(GA); 2827 const GlobalValue *GV = GA->getGlobal(); 2828 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2829 bool is64bit = Subtarget.isPPC64(); 2830 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2831 PICLevel::Level picLevel = M->getPICLevel(); 2832 2833 const TargetMachine &TM = getTargetMachine(); 2834 TLSModel::Model Model = TM.getTLSModel(GV); 2835 2836 if (Model == TLSModel::LocalExec) { 2837 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2838 PPCII::MO_TPREL_HA); 2839 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2840 PPCII::MO_TPREL_LO); 2841 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2842 : DAG.getRegister(PPC::R2, MVT::i32); 2843 2844 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2845 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2846 } 2847 2848 if (Model == TLSModel::InitialExec) { 2849 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2850 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2851 PPCII::MO_TLS); 2852 SDValue GOTPtr; 2853 if (is64bit) { 2854 setUsesTOCBasePtr(DAG); 2855 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2856 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2857 PtrVT, GOTReg, TGA); 2858 } else { 2859 if (!TM.isPositionIndependent()) 2860 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2861 else if (picLevel == PICLevel::SmallPIC) 2862 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2863 else 2864 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2865 } 2866 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2867 PtrVT, TGA, GOTPtr); 2868 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2869 } 2870 2871 if (Model == TLSModel::GeneralDynamic) { 2872 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2873 SDValue GOTPtr; 2874 if (is64bit) { 2875 setUsesTOCBasePtr(DAG); 2876 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2877 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2878 GOTReg, TGA); 2879 } else { 2880 if (picLevel == PICLevel::SmallPIC) 2881 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2882 else 2883 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2884 } 2885 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2886 GOTPtr, TGA, TGA); 2887 } 2888 2889 if (Model == TLSModel::LocalDynamic) { 2890 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2891 SDValue GOTPtr; 2892 if (is64bit) { 2893 setUsesTOCBasePtr(DAG); 2894 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2895 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2896 GOTReg, TGA); 2897 } else { 2898 if (picLevel == PICLevel::SmallPIC) 2899 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2900 else 2901 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2902 } 2903 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2904 PtrVT, GOTPtr, TGA, TGA); 2905 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2906 PtrVT, TLSAddr, TGA); 2907 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2908 } 2909 2910 llvm_unreachable("Unknown TLS model!"); 2911 } 2912 2913 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2914 SelectionDAG &DAG) const { 2915 EVT PtrVT = Op.getValueType(); 2916 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2917 SDLoc DL(GSDN); 2918 const GlobalValue *GV = GSDN->getGlobal(); 2919 2920 // 64-bit SVR4 ABI code is always position-independent. 2921 // The actual address of the GlobalValue is stored in the TOC. 2922 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { 2923 setUsesTOCBasePtr(DAG); 2924 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2925 return getTOCEntry(DAG, DL, true, GA); 2926 } 2927 2928 unsigned MOHiFlag, MOLoFlag; 2929 bool IsPIC = isPositionIndependent(); 2930 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2931 2932 if (IsPIC && Subtarget.isSVR4ABI()) { 2933 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2934 GSDN->getOffset(), 2935 PPCII::MO_PIC_FLAG); 2936 return getTOCEntry(DAG, DL, false, GA); 2937 } 2938 2939 SDValue GAHi = 2940 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2941 SDValue GALo = 2942 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2943 2944 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2945 2946 // If the global reference is actually to a non-lazy-pointer, we have to do an 2947 // extra load to get the address of the global. 2948 if (MOHiFlag & PPCII::MO_NLP_FLAG) 2949 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 2950 return Ptr; 2951 } 2952 2953 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2954 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2955 SDLoc dl(Op); 2956 2957 if (Op.getValueType() == MVT::v2i64) { 2958 // When the operands themselves are v2i64 values, we need to do something 2959 // special because VSX has no underlying comparison operations for these. 2960 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2961 // Equality can be handled by casting to the legal type for Altivec 2962 // comparisons, everything else needs to be expanded. 2963 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2964 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2965 DAG.getSetCC(dl, MVT::v4i32, 2966 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 2967 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 2968 CC)); 2969 } 2970 2971 return SDValue(); 2972 } 2973 2974 // We handle most of these in the usual way. 2975 return Op; 2976 } 2977 2978 // If we're comparing for equality to zero, expose the fact that this is 2979 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 2980 // fold the new nodes. 2981 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 2982 return V; 2983 2984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2985 // Leave comparisons against 0 and -1 alone for now, since they're usually 2986 // optimized. FIXME: revisit this when we can custom lower all setcc 2987 // optimizations. 2988 if (C->isAllOnesValue() || C->isNullValue()) 2989 return SDValue(); 2990 } 2991 2992 // If we have an integer seteq/setne, turn it into a compare against zero 2993 // by xor'ing the rhs with the lhs, which is faster than setting a 2994 // condition register, reading it back out, and masking the correct bit. The 2995 // normal approach here uses sub to do this instead of xor. Using xor exposes 2996 // the result to other bit-twiddling opportunities. 2997 EVT LHSVT = Op.getOperand(0).getValueType(); 2998 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 2999 EVT VT = Op.getValueType(); 3000 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3001 Op.getOperand(1)); 3002 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3003 } 3004 return SDValue(); 3005 } 3006 3007 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3008 SDNode *Node = Op.getNode(); 3009 EVT VT = Node->getValueType(0); 3010 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3011 SDValue InChain = Node->getOperand(0); 3012 SDValue VAListPtr = Node->getOperand(1); 3013 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3014 SDLoc dl(Node); 3015 3016 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3017 3018 // gpr_index 3019 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3020 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3021 InChain = GprIndex.getValue(1); 3022 3023 if (VT == MVT::i64) { 3024 // Check if GprIndex is even 3025 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3026 DAG.getConstant(1, dl, MVT::i32)); 3027 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3028 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3029 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3030 DAG.getConstant(1, dl, MVT::i32)); 3031 // Align GprIndex to be even if it isn't 3032 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3033 GprIndex); 3034 } 3035 3036 // fpr index is 1 byte after gpr 3037 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3038 DAG.getConstant(1, dl, MVT::i32)); 3039 3040 // fpr 3041 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3042 FprPtr, MachinePointerInfo(SV), MVT::i8); 3043 InChain = FprIndex.getValue(1); 3044 3045 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3046 DAG.getConstant(8, dl, MVT::i32)); 3047 3048 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3049 DAG.getConstant(4, dl, MVT::i32)); 3050 3051 // areas 3052 SDValue OverflowArea = 3053 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3054 InChain = OverflowArea.getValue(1); 3055 3056 SDValue RegSaveArea = 3057 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3058 InChain = RegSaveArea.getValue(1); 3059 3060 // select overflow_area if index > 8 3061 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3062 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3063 3064 // adjustment constant gpr_index * 4/8 3065 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3066 VT.isInteger() ? GprIndex : FprIndex, 3067 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3068 MVT::i32)); 3069 3070 // OurReg = RegSaveArea + RegConstant 3071 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3072 RegConstant); 3073 3074 // Floating types are 32 bytes into RegSaveArea 3075 if (VT.isFloatingPoint()) 3076 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3077 DAG.getConstant(32, dl, MVT::i32)); 3078 3079 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3080 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3081 VT.isInteger() ? GprIndex : FprIndex, 3082 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3083 MVT::i32)); 3084 3085 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3086 VT.isInteger() ? VAListPtr : FprPtr, 3087 MachinePointerInfo(SV), MVT::i8); 3088 3089 // determine if we should load from reg_save_area or overflow_area 3090 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3091 3092 // increase overflow_area by 4/8 if gpr/fpr > 8 3093 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3094 DAG.getConstant(VT.isInteger() ? 4 : 8, 3095 dl, MVT::i32)); 3096 3097 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3098 OverflowAreaPlusN); 3099 3100 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3101 MachinePointerInfo(), MVT::i32); 3102 3103 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3104 } 3105 3106 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3107 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3108 3109 // We have to copy the entire va_list struct: 3110 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3111 return DAG.getMemcpy(Op.getOperand(0), Op, 3112 Op.getOperand(1), Op.getOperand(2), 3113 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, 3114 false, MachinePointerInfo(), MachinePointerInfo()); 3115 } 3116 3117 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3118 SelectionDAG &DAG) const { 3119 return Op.getOperand(0); 3120 } 3121 3122 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3123 SelectionDAG &DAG) const { 3124 SDValue Chain = Op.getOperand(0); 3125 SDValue Trmp = Op.getOperand(1); // trampoline 3126 SDValue FPtr = Op.getOperand(2); // nested function 3127 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3128 SDLoc dl(Op); 3129 3130 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3131 bool isPPC64 = (PtrVT == MVT::i64); 3132 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3133 3134 TargetLowering::ArgListTy Args; 3135 TargetLowering::ArgListEntry Entry; 3136 3137 Entry.Ty = IntPtrTy; 3138 Entry.Node = Trmp; Args.push_back(Entry); 3139 3140 // TrampSize == (isPPC64 ? 48 : 40); 3141 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3142 isPPC64 ? MVT::i64 : MVT::i32); 3143 Args.push_back(Entry); 3144 3145 Entry.Node = FPtr; Args.push_back(Entry); 3146 Entry.Node = Nest; Args.push_back(Entry); 3147 3148 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3149 TargetLowering::CallLoweringInfo CLI(DAG); 3150 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3151 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3152 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3153 3154 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3155 return CallResult.second; 3156 } 3157 3158 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3159 MachineFunction &MF = DAG.getMachineFunction(); 3160 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3161 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3162 3163 SDLoc dl(Op); 3164 3165 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { 3166 // vastart just stores the address of the VarArgsFrameIndex slot into the 3167 // memory location argument. 3168 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3169 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3170 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3171 MachinePointerInfo(SV)); 3172 } 3173 3174 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3175 // We suppose the given va_list is already allocated. 3176 // 3177 // typedef struct { 3178 // char gpr; /* index into the array of 8 GPRs 3179 // * stored in the register save area 3180 // * gpr=0 corresponds to r3, 3181 // * gpr=1 to r4, etc. 3182 // */ 3183 // char fpr; /* index into the array of 8 FPRs 3184 // * stored in the register save area 3185 // * fpr=0 corresponds to f1, 3186 // * fpr=1 to f2, etc. 3187 // */ 3188 // char *overflow_arg_area; 3189 // /* location on stack that holds 3190 // * the next overflow argument 3191 // */ 3192 // char *reg_save_area; 3193 // /* where r3:r10 and f1:f8 (if saved) 3194 // * are stored 3195 // */ 3196 // } va_list[1]; 3197 3198 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3199 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3200 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3201 PtrVT); 3202 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3203 PtrVT); 3204 3205 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3206 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3207 3208 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3209 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3210 3211 uint64_t FPROffset = 1; 3212 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3213 3214 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3215 3216 // Store first byte : number of int regs 3217 SDValue firstStore = 3218 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3219 MachinePointerInfo(SV), MVT::i8); 3220 uint64_t nextOffset = FPROffset; 3221 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3222 ConstFPROffset); 3223 3224 // Store second byte : number of float regs 3225 SDValue secondStore = 3226 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3227 MachinePointerInfo(SV, nextOffset), MVT::i8); 3228 nextOffset += StackOffset; 3229 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3230 3231 // Store second word : arguments given on stack 3232 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3233 MachinePointerInfo(SV, nextOffset)); 3234 nextOffset += FrameOffset; 3235 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3236 3237 // Store third word : arguments given in registers 3238 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3239 MachinePointerInfo(SV, nextOffset)); 3240 } 3241 3242 /// FPR - The set of FP registers that should be allocated for arguments, 3243 /// on Darwin. 3244 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3245 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3246 PPC::F11, PPC::F12, PPC::F13}; 3247 3248 /// QFPR - The set of QPX registers that should be allocated for arguments. 3249 static const MCPhysReg QFPR[] = { 3250 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3251 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3252 3253 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3254 /// the stack. 3255 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3256 unsigned PtrByteSize) { 3257 unsigned ArgSize = ArgVT.getStoreSize(); 3258 if (Flags.isByVal()) 3259 ArgSize = Flags.getByValSize(); 3260 3261 // Round up to multiples of the pointer size, except for array members, 3262 // which are always packed. 3263 if (!Flags.isInConsecutiveRegs()) 3264 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3265 3266 return ArgSize; 3267 } 3268 3269 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3270 /// on the stack. 3271 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3272 ISD::ArgFlagsTy Flags, 3273 unsigned PtrByteSize) { 3274 unsigned Align = PtrByteSize; 3275 3276 // Altivec parameters are padded to a 16 byte boundary. 3277 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3278 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3279 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3280 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3281 Align = 16; 3282 // QPX vector types stored in double-precision are padded to a 32 byte 3283 // boundary. 3284 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3285 Align = 32; 3286 3287 // ByVal parameters are aligned as requested. 3288 if (Flags.isByVal()) { 3289 unsigned BVAlign = Flags.getByValAlign(); 3290 if (BVAlign > PtrByteSize) { 3291 if (BVAlign % PtrByteSize != 0) 3292 llvm_unreachable( 3293 "ByVal alignment is not a multiple of the pointer size"); 3294 3295 Align = BVAlign; 3296 } 3297 } 3298 3299 // Array members are always packed to their original alignment. 3300 if (Flags.isInConsecutiveRegs()) { 3301 // If the array member was split into multiple registers, the first 3302 // needs to be aligned to the size of the full type. (Except for 3303 // ppcf128, which is only aligned as its f64 components.) 3304 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3305 Align = OrigVT.getStoreSize(); 3306 else 3307 Align = ArgVT.getStoreSize(); 3308 } 3309 3310 return Align; 3311 } 3312 3313 /// CalculateStackSlotUsed - Return whether this argument will use its 3314 /// stack slot (instead of being passed in registers). ArgOffset, 3315 /// AvailableFPRs, and AvailableVRs must hold the current argument 3316 /// position, and will be updated to account for this argument. 3317 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3318 ISD::ArgFlagsTy Flags, 3319 unsigned PtrByteSize, 3320 unsigned LinkageSize, 3321 unsigned ParamAreaSize, 3322 unsigned &ArgOffset, 3323 unsigned &AvailableFPRs, 3324 unsigned &AvailableVRs, bool HasQPX) { 3325 bool UseMemory = false; 3326 3327 // Respect alignment of argument on the stack. 3328 unsigned Align = 3329 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3330 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3331 // If there's no space left in the argument save area, we must 3332 // use memory (this check also catches zero-sized arguments). 3333 if (ArgOffset >= LinkageSize + ParamAreaSize) 3334 UseMemory = true; 3335 3336 // Allocate argument on the stack. 3337 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3338 if (Flags.isInConsecutiveRegsLast()) 3339 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3340 // If we overran the argument save area, we must use memory 3341 // (this check catches arguments passed partially in memory) 3342 if (ArgOffset > LinkageSize + ParamAreaSize) 3343 UseMemory = true; 3344 3345 // However, if the argument is actually passed in an FPR or a VR, 3346 // we don't use memory after all. 3347 if (!Flags.isByVal()) { 3348 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3349 // QPX registers overlap with the scalar FP registers. 3350 (HasQPX && (ArgVT == MVT::v4f32 || 3351 ArgVT == MVT::v4f64 || 3352 ArgVT == MVT::v4i1))) 3353 if (AvailableFPRs > 0) { 3354 --AvailableFPRs; 3355 return false; 3356 } 3357 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3358 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3359 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3360 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3361 if (AvailableVRs > 0) { 3362 --AvailableVRs; 3363 return false; 3364 } 3365 } 3366 3367 return UseMemory; 3368 } 3369 3370 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3371 /// ensure minimum alignment required for target. 3372 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3373 unsigned NumBytes) { 3374 unsigned TargetAlign = Lowering->getStackAlignment(); 3375 unsigned AlignMask = TargetAlign - 1; 3376 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3377 return NumBytes; 3378 } 3379 3380 SDValue PPCTargetLowering::LowerFormalArguments( 3381 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3382 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3383 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3384 if (Subtarget.isSVR4ABI()) { 3385 if (Subtarget.isPPC64()) 3386 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, 3387 dl, DAG, InVals); 3388 else 3389 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, 3390 dl, DAG, InVals); 3391 } else { 3392 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, 3393 dl, DAG, InVals); 3394 } 3395 } 3396 3397 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3398 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3399 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3400 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3401 3402 // 32-bit SVR4 ABI Stack Frame Layout: 3403 // +-----------------------------------+ 3404 // +--> | Back chain | 3405 // | +-----------------------------------+ 3406 // | | Floating-point register save area | 3407 // | +-----------------------------------+ 3408 // | | General register save area | 3409 // | +-----------------------------------+ 3410 // | | CR save word | 3411 // | +-----------------------------------+ 3412 // | | VRSAVE save word | 3413 // | +-----------------------------------+ 3414 // | | Alignment padding | 3415 // | +-----------------------------------+ 3416 // | | Vector register save area | 3417 // | +-----------------------------------+ 3418 // | | Local variable space | 3419 // | +-----------------------------------+ 3420 // | | Parameter list area | 3421 // | +-----------------------------------+ 3422 // | | LR save word | 3423 // | +-----------------------------------+ 3424 // SP--> +--- | Back chain | 3425 // +-----------------------------------+ 3426 // 3427 // Specifications: 3428 // System V Application Binary Interface PowerPC Processor Supplement 3429 // AltiVec Technology Programming Interface Manual 3430 3431 MachineFunction &MF = DAG.getMachineFunction(); 3432 MachineFrameInfo &MFI = MF.getFrameInfo(); 3433 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3434 3435 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3436 // Potential tail calls could cause overwriting of argument stack slots. 3437 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3438 (CallConv == CallingConv::Fast)); 3439 unsigned PtrByteSize = 4; 3440 3441 // Assign locations to all of the incoming arguments. 3442 SmallVector<CCValAssign, 16> ArgLocs; 3443 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3444 *DAG.getContext()); 3445 3446 // Reserve space for the linkage area on the stack. 3447 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3448 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3449 if (useSoftFloat()) 3450 CCInfo.PreAnalyzeFormalArguments(Ins); 3451 3452 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3453 CCInfo.clearWasPPCF128(); 3454 3455 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3456 CCValAssign &VA = ArgLocs[i]; 3457 3458 // Arguments stored in registers. 3459 if (VA.isRegLoc()) { 3460 const TargetRegisterClass *RC; 3461 EVT ValVT = VA.getValVT(); 3462 3463 switch (ValVT.getSimpleVT().SimpleTy) { 3464 default: 3465 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3466 case MVT::i1: 3467 case MVT::i32: 3468 RC = &PPC::GPRCRegClass; 3469 break; 3470 case MVT::f32: 3471 if (Subtarget.hasP8Vector()) 3472 RC = &PPC::VSSRCRegClass; 3473 else if (Subtarget.hasSPE()) 3474 RC = &PPC::SPE4RCRegClass; 3475 else 3476 RC = &PPC::F4RCRegClass; 3477 break; 3478 case MVT::f64: 3479 if (Subtarget.hasVSX()) 3480 RC = &PPC::VSFRCRegClass; 3481 else if (Subtarget.hasSPE()) 3482 // SPE passes doubles in GPR pairs. 3483 RC = &PPC::GPRCRegClass; 3484 else 3485 RC = &PPC::F8RCRegClass; 3486 break; 3487 case MVT::v16i8: 3488 case MVT::v8i16: 3489 case MVT::v4i32: 3490 RC = &PPC::VRRCRegClass; 3491 break; 3492 case MVT::v4f32: 3493 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3494 break; 3495 case MVT::v2f64: 3496 case MVT::v2i64: 3497 RC = &PPC::VRRCRegClass; 3498 break; 3499 case MVT::v4f64: 3500 RC = &PPC::QFRCRegClass; 3501 break; 3502 case MVT::v4i1: 3503 RC = &PPC::QBRCRegClass; 3504 break; 3505 } 3506 3507 SDValue ArgValue; 3508 // Transform the arguments stored in physical registers into 3509 // virtual ones. 3510 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3511 assert(i + 1 < e && "No second half of double precision argument"); 3512 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3513 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3514 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3515 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3516 if (!Subtarget.isLittleEndian()) 3517 std::swap (ArgValueLo, ArgValueHi); 3518 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3519 ArgValueHi); 3520 } else { 3521 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3522 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3523 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3524 if (ValVT == MVT::i1) 3525 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3526 } 3527 3528 InVals.push_back(ArgValue); 3529 } else { 3530 // Argument stored in memory. 3531 assert(VA.isMemLoc()); 3532 3533 // Get the extended size of the argument type in stack 3534 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3535 // Get the actual size of the argument type 3536 unsigned ObjSize = VA.getValVT().getStoreSize(); 3537 unsigned ArgOffset = VA.getLocMemOffset(); 3538 // Stack objects in PPC32 are right justified. 3539 ArgOffset += ArgSize - ObjSize; 3540 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3541 3542 // Create load nodes to retrieve arguments from the stack. 3543 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3544 InVals.push_back( 3545 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3546 } 3547 } 3548 3549 // Assign locations to all of the incoming aggregate by value arguments. 3550 // Aggregates passed by value are stored in the local variable space of the 3551 // caller's stack frame, right above the parameter list area. 3552 SmallVector<CCValAssign, 16> ByValArgLocs; 3553 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3554 ByValArgLocs, *DAG.getContext()); 3555 3556 // Reserve stack space for the allocations in CCInfo. 3557 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3558 3559 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3560 3561 // Area that is at least reserved in the caller of this function. 3562 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3563 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3564 3565 // Set the size that is at least reserved in caller of this function. Tail 3566 // call optimized function's reserved stack space needs to be aligned so that 3567 // taking the difference between two stack areas will result in an aligned 3568 // stack. 3569 MinReservedArea = 3570 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3571 FuncInfo->setMinReservedArea(MinReservedArea); 3572 3573 SmallVector<SDValue, 8> MemOps; 3574 3575 // If the function takes variable number of arguments, make a frame index for 3576 // the start of the first vararg value... for expansion of llvm.va_start. 3577 if (isVarArg) { 3578 static const MCPhysReg GPArgRegs[] = { 3579 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3580 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3581 }; 3582 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3583 3584 static const MCPhysReg FPArgRegs[] = { 3585 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3586 PPC::F8 3587 }; 3588 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3589 3590 if (useSoftFloat() || hasSPE()) 3591 NumFPArgRegs = 0; 3592 3593 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3594 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3595 3596 // Make room for NumGPArgRegs and NumFPArgRegs. 3597 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3598 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3599 3600 FuncInfo->setVarArgsStackOffset( 3601 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3602 CCInfo.getNextStackOffset(), true)); 3603 3604 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3605 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3606 3607 // The fixed integer arguments of a variadic function are stored to the 3608 // VarArgsFrameIndex on the stack so that they may be loaded by 3609 // dereferencing the result of va_next. 3610 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3611 // Get an existing live-in vreg, or add a new one. 3612 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3613 if (!VReg) 3614 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3615 3616 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3617 SDValue Store = 3618 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3619 MemOps.push_back(Store); 3620 // Increment the address by four for the next argument to store 3621 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3622 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3623 } 3624 3625 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3626 // is set. 3627 // The double arguments are stored to the VarArgsFrameIndex 3628 // on the stack. 3629 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3630 // Get an existing live-in vreg, or add a new one. 3631 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3632 if (!VReg) 3633 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3634 3635 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3636 SDValue Store = 3637 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3638 MemOps.push_back(Store); 3639 // Increment the address by eight for the next argument to store 3640 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3641 PtrVT); 3642 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3643 } 3644 } 3645 3646 if (!MemOps.empty()) 3647 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3648 3649 return Chain; 3650 } 3651 3652 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3653 // value to MVT::i64 and then truncate to the correct register size. 3654 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3655 EVT ObjectVT, SelectionDAG &DAG, 3656 SDValue ArgVal, 3657 const SDLoc &dl) const { 3658 if (Flags.isSExt()) 3659 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3660 DAG.getValueType(ObjectVT)); 3661 else if (Flags.isZExt()) 3662 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3663 DAG.getValueType(ObjectVT)); 3664 3665 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3666 } 3667 3668 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3669 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3670 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3671 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3672 // TODO: add description of PPC stack frame format, or at least some docs. 3673 // 3674 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3675 bool isLittleEndian = Subtarget.isLittleEndian(); 3676 MachineFunction &MF = DAG.getMachineFunction(); 3677 MachineFrameInfo &MFI = MF.getFrameInfo(); 3678 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3679 3680 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3681 "fastcc not supported on varargs functions"); 3682 3683 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3684 // Potential tail calls could cause overwriting of argument stack slots. 3685 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3686 (CallConv == CallingConv::Fast)); 3687 unsigned PtrByteSize = 8; 3688 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3689 3690 static const MCPhysReg GPR[] = { 3691 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3692 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3693 }; 3694 static const MCPhysReg VR[] = { 3695 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3696 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3697 }; 3698 3699 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3700 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3701 const unsigned Num_VR_Regs = array_lengthof(VR); 3702 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3703 3704 // Do a first pass over the arguments to determine whether the ABI 3705 // guarantees that our caller has allocated the parameter save area 3706 // on its stack frame. In the ELFv1 ABI, this is always the case; 3707 // in the ELFv2 ABI, it is true if this is a vararg function or if 3708 // any parameter is located in a stack slot. 3709 3710 bool HasParameterArea = !isELFv2ABI || isVarArg; 3711 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3712 unsigned NumBytes = LinkageSize; 3713 unsigned AvailableFPRs = Num_FPR_Regs; 3714 unsigned AvailableVRs = Num_VR_Regs; 3715 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3716 if (Ins[i].Flags.isNest()) 3717 continue; 3718 3719 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3720 PtrByteSize, LinkageSize, ParamAreaSize, 3721 NumBytes, AvailableFPRs, AvailableVRs, 3722 Subtarget.hasQPX())) 3723 HasParameterArea = true; 3724 } 3725 3726 // Add DAG nodes to load the arguments or copy them out of registers. On 3727 // entry to a function on PPC, the arguments start after the linkage area, 3728 // although the first ones are often in registers. 3729 3730 unsigned ArgOffset = LinkageSize; 3731 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3732 unsigned &QFPR_idx = FPR_idx; 3733 SmallVector<SDValue, 8> MemOps; 3734 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3735 unsigned CurArgIdx = 0; 3736 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3737 SDValue ArgVal; 3738 bool needsLoad = false; 3739 EVT ObjectVT = Ins[ArgNo].VT; 3740 EVT OrigVT = Ins[ArgNo].ArgVT; 3741 unsigned ObjSize = ObjectVT.getStoreSize(); 3742 unsigned ArgSize = ObjSize; 3743 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3744 if (Ins[ArgNo].isOrigArg()) { 3745 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3746 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3747 } 3748 // We re-align the argument offset for each argument, except when using the 3749 // fast calling convention, when we need to make sure we do that only when 3750 // we'll actually use a stack slot. 3751 unsigned CurArgOffset, Align; 3752 auto ComputeArgOffset = [&]() { 3753 /* Respect alignment of argument on the stack. */ 3754 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3755 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 3756 CurArgOffset = ArgOffset; 3757 }; 3758 3759 if (CallConv != CallingConv::Fast) { 3760 ComputeArgOffset(); 3761 3762 /* Compute GPR index associated with argument offset. */ 3763 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3764 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3765 } 3766 3767 // FIXME the codegen can be much improved in some cases. 3768 // We do not have to keep everything in memory. 3769 if (Flags.isByVal()) { 3770 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3771 3772 if (CallConv == CallingConv::Fast) 3773 ComputeArgOffset(); 3774 3775 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3776 ObjSize = Flags.getByValSize(); 3777 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3778 // Empty aggregate parameters do not take up registers. Examples: 3779 // struct { } a; 3780 // union { } b; 3781 // int c[0]; 3782 // etc. However, we have to provide a place-holder in InVals, so 3783 // pretend we have an 8-byte item at the current address for that 3784 // purpose. 3785 if (!ObjSize) { 3786 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3787 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3788 InVals.push_back(FIN); 3789 continue; 3790 } 3791 3792 // Create a stack object covering all stack doublewords occupied 3793 // by the argument. If the argument is (fully or partially) on 3794 // the stack, or if the argument is fully in registers but the 3795 // caller has allocated the parameter save anyway, we can refer 3796 // directly to the caller's stack frame. Otherwise, create a 3797 // local copy in our own frame. 3798 int FI; 3799 if (HasParameterArea || 3800 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3801 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3802 else 3803 FI = MFI.CreateStackObject(ArgSize, Align, false); 3804 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3805 3806 // Handle aggregates smaller than 8 bytes. 3807 if (ObjSize < PtrByteSize) { 3808 // The value of the object is its address, which differs from the 3809 // address of the enclosing doubleword on big-endian systems. 3810 SDValue Arg = FIN; 3811 if (!isLittleEndian) { 3812 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3813 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3814 } 3815 InVals.push_back(Arg); 3816 3817 if (GPR_idx != Num_GPR_Regs) { 3818 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3819 FuncInfo->addLiveInAttr(VReg, Flags); 3820 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3821 SDValue Store; 3822 3823 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3824 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3825 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3826 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3827 MachinePointerInfo(&*FuncArg), ObjType); 3828 } else { 3829 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3830 // store the whole register as-is to the parameter save area 3831 // slot. 3832 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3833 MachinePointerInfo(&*FuncArg)); 3834 } 3835 3836 MemOps.push_back(Store); 3837 } 3838 // Whether we copied from a register or not, advance the offset 3839 // into the parameter save area by a full doubleword. 3840 ArgOffset += PtrByteSize; 3841 continue; 3842 } 3843 3844 // The value of the object is its address, which is the address of 3845 // its first stack doubleword. 3846 InVals.push_back(FIN); 3847 3848 // Store whatever pieces of the object are in registers to memory. 3849 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3850 if (GPR_idx == Num_GPR_Regs) 3851 break; 3852 3853 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3854 FuncInfo->addLiveInAttr(VReg, Flags); 3855 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3856 SDValue Addr = FIN; 3857 if (j) { 3858 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3859 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3860 } 3861 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3862 MachinePointerInfo(&*FuncArg, j)); 3863 MemOps.push_back(Store); 3864 ++GPR_idx; 3865 } 3866 ArgOffset += ArgSize; 3867 continue; 3868 } 3869 3870 switch (ObjectVT.getSimpleVT().SimpleTy) { 3871 default: llvm_unreachable("Unhandled argument type!"); 3872 case MVT::i1: 3873 case MVT::i32: 3874 case MVT::i64: 3875 if (Flags.isNest()) { 3876 // The 'nest' parameter, if any, is passed in R11. 3877 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3878 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3879 3880 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3881 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3882 3883 break; 3884 } 3885 3886 // These can be scalar arguments or elements of an integer array type 3887 // passed directly. Clang may use those instead of "byval" aggregate 3888 // types to avoid forcing arguments to memory unnecessarily. 3889 if (GPR_idx != Num_GPR_Regs) { 3890 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3891 FuncInfo->addLiveInAttr(VReg, Flags); 3892 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3893 3894 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3895 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3896 // value to MVT::i64 and then truncate to the correct register size. 3897 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3898 } else { 3899 if (CallConv == CallingConv::Fast) 3900 ComputeArgOffset(); 3901 3902 needsLoad = true; 3903 ArgSize = PtrByteSize; 3904 } 3905 if (CallConv != CallingConv::Fast || needsLoad) 3906 ArgOffset += 8; 3907 break; 3908 3909 case MVT::f32: 3910 case MVT::f64: 3911 // These can be scalar arguments or elements of a float array type 3912 // passed directly. The latter are used to implement ELFv2 homogenous 3913 // float aggregates. 3914 if (FPR_idx != Num_FPR_Regs) { 3915 unsigned VReg; 3916 3917 if (ObjectVT == MVT::f32) 3918 VReg = MF.addLiveIn(FPR[FPR_idx], 3919 Subtarget.hasP8Vector() 3920 ? &PPC::VSSRCRegClass 3921 : &PPC::F4RCRegClass); 3922 else 3923 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3924 ? &PPC::VSFRCRegClass 3925 : &PPC::F8RCRegClass); 3926 3927 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3928 ++FPR_idx; 3929 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3930 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3931 // once we support fp <-> gpr moves. 3932 3933 // This can only ever happen in the presence of f32 array types, 3934 // since otherwise we never run out of FPRs before running out 3935 // of GPRs. 3936 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3937 FuncInfo->addLiveInAttr(VReg, Flags); 3938 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3939 3940 if (ObjectVT == MVT::f32) { 3941 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3942 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3943 DAG.getConstant(32, dl, MVT::i32)); 3944 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3945 } 3946 3947 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3948 } else { 3949 if (CallConv == CallingConv::Fast) 3950 ComputeArgOffset(); 3951 3952 needsLoad = true; 3953 } 3954 3955 // When passing an array of floats, the array occupies consecutive 3956 // space in the argument area; only round up to the next doubleword 3957 // at the end of the array. Otherwise, each float takes 8 bytes. 3958 if (CallConv != CallingConv::Fast || needsLoad) { 3959 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 3960 ArgOffset += ArgSize; 3961 if (Flags.isInConsecutiveRegsLast()) 3962 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3963 } 3964 break; 3965 case MVT::v4f32: 3966 case MVT::v4i32: 3967 case MVT::v8i16: 3968 case MVT::v16i8: 3969 case MVT::v2f64: 3970 case MVT::v2i64: 3971 case MVT::v1i128: 3972 case MVT::f128: 3973 if (!Subtarget.hasQPX()) { 3974 // These can be scalar arguments or elements of a vector array type 3975 // passed directly. The latter are used to implement ELFv2 homogenous 3976 // vector aggregates. 3977 if (VR_idx != Num_VR_Regs) { 3978 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 3979 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3980 ++VR_idx; 3981 } else { 3982 if (CallConv == CallingConv::Fast) 3983 ComputeArgOffset(); 3984 needsLoad = true; 3985 } 3986 if (CallConv != CallingConv::Fast || needsLoad) 3987 ArgOffset += 16; 3988 break; 3989 } // not QPX 3990 3991 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 3992 "Invalid QPX parameter type"); 3993 LLVM_FALLTHROUGH; 3994 3995 case MVT::v4f64: 3996 case MVT::v4i1: 3997 // QPX vectors are treated like their scalar floating-point subregisters 3998 // (except that they're larger). 3999 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4000 if (QFPR_idx != Num_QFPR_Regs) { 4001 const TargetRegisterClass *RC; 4002 switch (ObjectVT.getSimpleVT().SimpleTy) { 4003 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4004 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4005 default: RC = &PPC::QBRCRegClass; break; 4006 } 4007 4008 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4009 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4010 ++QFPR_idx; 4011 } else { 4012 if (CallConv == CallingConv::Fast) 4013 ComputeArgOffset(); 4014 needsLoad = true; 4015 } 4016 if (CallConv != CallingConv::Fast || needsLoad) 4017 ArgOffset += Sz; 4018 break; 4019 } 4020 4021 // We need to load the argument to a virtual register if we determined 4022 // above that we ran out of physical registers of the appropriate type. 4023 if (needsLoad) { 4024 if (ObjSize < ArgSize && !isLittleEndian) 4025 CurArgOffset += ArgSize - ObjSize; 4026 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4027 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4028 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4029 } 4030 4031 InVals.push_back(ArgVal); 4032 } 4033 4034 // Area that is at least reserved in the caller of this function. 4035 unsigned MinReservedArea; 4036 if (HasParameterArea) 4037 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4038 else 4039 MinReservedArea = LinkageSize; 4040 4041 // Set the size that is at least reserved in caller of this function. Tail 4042 // call optimized functions' reserved stack space needs to be aligned so that 4043 // taking the difference between two stack areas will result in an aligned 4044 // stack. 4045 MinReservedArea = 4046 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4047 FuncInfo->setMinReservedArea(MinReservedArea); 4048 4049 // If the function takes variable number of arguments, make a frame index for 4050 // the start of the first vararg value... for expansion of llvm.va_start. 4051 if (isVarArg) { 4052 int Depth = ArgOffset; 4053 4054 FuncInfo->setVarArgsFrameIndex( 4055 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4056 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4057 4058 // If this function is vararg, store any remaining integer argument regs 4059 // to their spots on the stack so that they may be loaded by dereferencing 4060 // the result of va_next. 4061 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4062 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4063 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4064 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4065 SDValue Store = 4066 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4067 MemOps.push_back(Store); 4068 // Increment the address by four for the next argument to store 4069 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4070 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4071 } 4072 } 4073 4074 if (!MemOps.empty()) 4075 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4076 4077 return Chain; 4078 } 4079 4080 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4081 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4082 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4083 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4084 // TODO: add description of PPC stack frame format, or at least some docs. 4085 // 4086 MachineFunction &MF = DAG.getMachineFunction(); 4087 MachineFrameInfo &MFI = MF.getFrameInfo(); 4088 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4089 4090 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4091 bool isPPC64 = PtrVT == MVT::i64; 4092 // Potential tail calls could cause overwriting of argument stack slots. 4093 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4094 (CallConv == CallingConv::Fast)); 4095 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4096 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4097 unsigned ArgOffset = LinkageSize; 4098 // Area that is at least reserved in caller of this function. 4099 unsigned MinReservedArea = ArgOffset; 4100 4101 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4102 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4103 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4104 }; 4105 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4106 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4107 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4108 }; 4109 static const MCPhysReg VR[] = { 4110 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4111 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4112 }; 4113 4114 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4115 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4116 const unsigned Num_VR_Regs = array_lengthof( VR); 4117 4118 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4119 4120 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4121 4122 // In 32-bit non-varargs functions, the stack space for vectors is after the 4123 // stack space for non-vectors. We do not use this space unless we have 4124 // too many vectors to fit in registers, something that only occurs in 4125 // constructed examples:), but we have to walk the arglist to figure 4126 // that out...for the pathological case, compute VecArgOffset as the 4127 // start of the vector parameter area. Computing VecArgOffset is the 4128 // entire point of the following loop. 4129 unsigned VecArgOffset = ArgOffset; 4130 if (!isVarArg && !isPPC64) { 4131 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4132 ++ArgNo) { 4133 EVT ObjectVT = Ins[ArgNo].VT; 4134 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4135 4136 if (Flags.isByVal()) { 4137 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4138 unsigned ObjSize = Flags.getByValSize(); 4139 unsigned ArgSize = 4140 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4141 VecArgOffset += ArgSize; 4142 continue; 4143 } 4144 4145 switch(ObjectVT.getSimpleVT().SimpleTy) { 4146 default: llvm_unreachable("Unhandled argument type!"); 4147 case MVT::i1: 4148 case MVT::i32: 4149 case MVT::f32: 4150 VecArgOffset += 4; 4151 break; 4152 case MVT::i64: // PPC64 4153 case MVT::f64: 4154 // FIXME: We are guaranteed to be !isPPC64 at this point. 4155 // Does MVT::i64 apply? 4156 VecArgOffset += 8; 4157 break; 4158 case MVT::v4f32: 4159 case MVT::v4i32: 4160 case MVT::v8i16: 4161 case MVT::v16i8: 4162 // Nothing to do, we're only looking at Nonvector args here. 4163 break; 4164 } 4165 } 4166 } 4167 // We've found where the vector parameter area in memory is. Skip the 4168 // first 12 parameters; these don't use that memory. 4169 VecArgOffset = ((VecArgOffset+15)/16)*16; 4170 VecArgOffset += 12*16; 4171 4172 // Add DAG nodes to load the arguments or copy them out of registers. On 4173 // entry to a function on PPC, the arguments start after the linkage area, 4174 // although the first ones are often in registers. 4175 4176 SmallVector<SDValue, 8> MemOps; 4177 unsigned nAltivecParamsAtEnd = 0; 4178 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4179 unsigned CurArgIdx = 0; 4180 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4181 SDValue ArgVal; 4182 bool needsLoad = false; 4183 EVT ObjectVT = Ins[ArgNo].VT; 4184 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4185 unsigned ArgSize = ObjSize; 4186 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4187 if (Ins[ArgNo].isOrigArg()) { 4188 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4189 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4190 } 4191 unsigned CurArgOffset = ArgOffset; 4192 4193 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4194 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4195 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4196 if (isVarArg || isPPC64) { 4197 MinReservedArea = ((MinReservedArea+15)/16)*16; 4198 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4199 Flags, 4200 PtrByteSize); 4201 } else nAltivecParamsAtEnd++; 4202 } else 4203 // Calculate min reserved area. 4204 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4205 Flags, 4206 PtrByteSize); 4207 4208 // FIXME the codegen can be much improved in some cases. 4209 // We do not have to keep everything in memory. 4210 if (Flags.isByVal()) { 4211 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4212 4213 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4214 ObjSize = Flags.getByValSize(); 4215 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4216 // Objects of size 1 and 2 are right justified, everything else is 4217 // left justified. This means the memory address is adjusted forwards. 4218 if (ObjSize==1 || ObjSize==2) { 4219 CurArgOffset = CurArgOffset + (4 - ObjSize); 4220 } 4221 // The value of the object is its address. 4222 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4223 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4224 InVals.push_back(FIN); 4225 if (ObjSize==1 || ObjSize==2) { 4226 if (GPR_idx != Num_GPR_Regs) { 4227 unsigned VReg; 4228 if (isPPC64) 4229 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4230 else 4231 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4232 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4233 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4234 SDValue Store = 4235 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4236 MachinePointerInfo(&*FuncArg), ObjType); 4237 MemOps.push_back(Store); 4238 ++GPR_idx; 4239 } 4240 4241 ArgOffset += PtrByteSize; 4242 4243 continue; 4244 } 4245 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4246 // Store whatever pieces of the object are in registers 4247 // to memory. ArgOffset will be the address of the beginning 4248 // of the object. 4249 if (GPR_idx != Num_GPR_Regs) { 4250 unsigned VReg; 4251 if (isPPC64) 4252 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4253 else 4254 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4255 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4256 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4257 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4258 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4259 MachinePointerInfo(&*FuncArg, j)); 4260 MemOps.push_back(Store); 4261 ++GPR_idx; 4262 ArgOffset += PtrByteSize; 4263 } else { 4264 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4265 break; 4266 } 4267 } 4268 continue; 4269 } 4270 4271 switch (ObjectVT.getSimpleVT().SimpleTy) { 4272 default: llvm_unreachable("Unhandled argument type!"); 4273 case MVT::i1: 4274 case MVT::i32: 4275 if (!isPPC64) { 4276 if (GPR_idx != Num_GPR_Regs) { 4277 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4278 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4279 4280 if (ObjectVT == MVT::i1) 4281 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4282 4283 ++GPR_idx; 4284 } else { 4285 needsLoad = true; 4286 ArgSize = PtrByteSize; 4287 } 4288 // All int arguments reserve stack space in the Darwin ABI. 4289 ArgOffset += PtrByteSize; 4290 break; 4291 } 4292 LLVM_FALLTHROUGH; 4293 case MVT::i64: // PPC64 4294 if (GPR_idx != Num_GPR_Regs) { 4295 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4296 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4297 4298 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4299 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4300 // value to MVT::i64 and then truncate to the correct register size. 4301 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4302 4303 ++GPR_idx; 4304 } else { 4305 needsLoad = true; 4306 ArgSize = PtrByteSize; 4307 } 4308 // All int arguments reserve stack space in the Darwin ABI. 4309 ArgOffset += 8; 4310 break; 4311 4312 case MVT::f32: 4313 case MVT::f64: 4314 // Every 4 bytes of argument space consumes one of the GPRs available for 4315 // argument passing. 4316 if (GPR_idx != Num_GPR_Regs) { 4317 ++GPR_idx; 4318 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4319 ++GPR_idx; 4320 } 4321 if (FPR_idx != Num_FPR_Regs) { 4322 unsigned VReg; 4323 4324 if (ObjectVT == MVT::f32) 4325 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4326 else 4327 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4328 4329 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4330 ++FPR_idx; 4331 } else { 4332 needsLoad = true; 4333 } 4334 4335 // All FP arguments reserve stack space in the Darwin ABI. 4336 ArgOffset += isPPC64 ? 8 : ObjSize; 4337 break; 4338 case MVT::v4f32: 4339 case MVT::v4i32: 4340 case MVT::v8i16: 4341 case MVT::v16i8: 4342 // Note that vector arguments in registers don't reserve stack space, 4343 // except in varargs functions. 4344 if (VR_idx != Num_VR_Regs) { 4345 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4346 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4347 if (isVarArg) { 4348 while ((ArgOffset % 16) != 0) { 4349 ArgOffset += PtrByteSize; 4350 if (GPR_idx != Num_GPR_Regs) 4351 GPR_idx++; 4352 } 4353 ArgOffset += 16; 4354 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4355 } 4356 ++VR_idx; 4357 } else { 4358 if (!isVarArg && !isPPC64) { 4359 // Vectors go after all the nonvectors. 4360 CurArgOffset = VecArgOffset; 4361 VecArgOffset += 16; 4362 } else { 4363 // Vectors are aligned. 4364 ArgOffset = ((ArgOffset+15)/16)*16; 4365 CurArgOffset = ArgOffset; 4366 ArgOffset += 16; 4367 } 4368 needsLoad = true; 4369 } 4370 break; 4371 } 4372 4373 // We need to load the argument to a virtual register if we determined above 4374 // that we ran out of physical registers of the appropriate type. 4375 if (needsLoad) { 4376 int FI = MFI.CreateFixedObject(ObjSize, 4377 CurArgOffset + (ArgSize - ObjSize), 4378 isImmutable); 4379 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4380 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4381 } 4382 4383 InVals.push_back(ArgVal); 4384 } 4385 4386 // Allow for Altivec parameters at the end, if needed. 4387 if (nAltivecParamsAtEnd) { 4388 MinReservedArea = ((MinReservedArea+15)/16)*16; 4389 MinReservedArea += 16*nAltivecParamsAtEnd; 4390 } 4391 4392 // Area that is at least reserved in the caller of this function. 4393 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4394 4395 // Set the size that is at least reserved in caller of this function. Tail 4396 // call optimized functions' reserved stack space needs to be aligned so that 4397 // taking the difference between two stack areas will result in an aligned 4398 // stack. 4399 MinReservedArea = 4400 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4401 FuncInfo->setMinReservedArea(MinReservedArea); 4402 4403 // If the function takes variable number of arguments, make a frame index for 4404 // the start of the first vararg value... for expansion of llvm.va_start. 4405 if (isVarArg) { 4406 int Depth = ArgOffset; 4407 4408 FuncInfo->setVarArgsFrameIndex( 4409 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4410 Depth, true)); 4411 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4412 4413 // If this function is vararg, store any remaining integer argument regs 4414 // to their spots on the stack so that they may be loaded by dereferencing 4415 // the result of va_next. 4416 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4417 unsigned VReg; 4418 4419 if (isPPC64) 4420 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4421 else 4422 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4423 4424 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4425 SDValue Store = 4426 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4427 MemOps.push_back(Store); 4428 // Increment the address by four for the next argument to store 4429 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4430 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4431 } 4432 } 4433 4434 if (!MemOps.empty()) 4435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4436 4437 return Chain; 4438 } 4439 4440 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4441 /// adjusted to accommodate the arguments for the tailcall. 4442 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4443 unsigned ParamSize) { 4444 4445 if (!isTailCall) return 0; 4446 4447 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4448 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4449 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4450 // Remember only if the new adjustment is bigger. 4451 if (SPDiff < FI->getTailCallSPDelta()) 4452 FI->setTailCallSPDelta(SPDiff); 4453 4454 return SPDiff; 4455 } 4456 4457 static bool isFunctionGlobalAddress(SDValue Callee); 4458 4459 static bool 4460 callsShareTOCBase(const Function *Caller, SDValue Callee, 4461 const TargetMachine &TM) { 4462 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4463 // don't have enough information to determine if the caller and calle share 4464 // the same TOC base, so we have to pessimistically assume they don't for 4465 // correctness. 4466 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4467 if (!G) 4468 return false; 4469 4470 const GlobalValue *GV = G->getGlobal(); 4471 // The medium and large code models are expected to provide a sufficiently 4472 // large TOC to provide all data addressing needs of a module with a 4473 // single TOC. Since each module will be addressed with a single TOC then we 4474 // only need to check that caller and callee don't cross dso boundaries. 4475 if (CodeModel::Medium == TM.getCodeModel() || 4476 CodeModel::Large == TM.getCodeModel()) 4477 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4478 4479 // Otherwise we need to ensure callee and caller are in the same section, 4480 // since the linker may allocate multiple TOCs, and we don't know which 4481 // sections will belong to the same TOC base. 4482 4483 if (!GV->isStrongDefinitionForLinker()) 4484 return false; 4485 4486 // Any explicitly-specified sections and section prefixes must also match. 4487 // Also, if we're using -ffunction-sections, then each function is always in 4488 // a different section (the same is true for COMDAT functions). 4489 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4490 GV->getSection() != Caller->getSection()) 4491 return false; 4492 if (const auto *F = dyn_cast<Function>(GV)) { 4493 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4494 return false; 4495 } 4496 4497 // If the callee might be interposed, then we can't assume the ultimate call 4498 // target will be in the same section. Even in cases where we can assume that 4499 // interposition won't happen, in any case where the linker might insert a 4500 // stub to allow for interposition, we must generate code as though 4501 // interposition might occur. To understand why this matters, consider a 4502 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4503 // in the same section, but a is in a different module (i.e. has a different 4504 // TOC base pointer). If the linker allows for interposition between b and c, 4505 // then it will generate a stub for the call edge between b and c which will 4506 // save the TOC pointer into the designated stack slot allocated by b. If we 4507 // return true here, and therefore allow a tail call between b and c, that 4508 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4509 // pointer into the stack slot allocated by a (where the a -> b stub saved 4510 // a's TOC base pointer). If we're not considering a tail call, but rather, 4511 // whether a nop is needed after the call instruction in b, because the linker 4512 // will insert a stub, it might complain about a missing nop if we omit it 4513 // (although many don't complain in this case). 4514 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4515 return false; 4516 4517 return true; 4518 } 4519 4520 static bool 4521 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4522 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4523 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64()); 4524 4525 const unsigned PtrByteSize = 8; 4526 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4527 4528 static const MCPhysReg GPR[] = { 4529 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4530 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4531 }; 4532 static const MCPhysReg VR[] = { 4533 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4534 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4535 }; 4536 4537 const unsigned NumGPRs = array_lengthof(GPR); 4538 const unsigned NumFPRs = 13; 4539 const unsigned NumVRs = array_lengthof(VR); 4540 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4541 4542 unsigned NumBytes = LinkageSize; 4543 unsigned AvailableFPRs = NumFPRs; 4544 unsigned AvailableVRs = NumVRs; 4545 4546 for (const ISD::OutputArg& Param : Outs) { 4547 if (Param.Flags.isNest()) continue; 4548 4549 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4550 PtrByteSize, LinkageSize, ParamAreaSize, 4551 NumBytes, AvailableFPRs, AvailableVRs, 4552 Subtarget.hasQPX())) 4553 return true; 4554 } 4555 return false; 4556 } 4557 4558 static bool 4559 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4560 if (CS.arg_size() != CallerFn->arg_size()) 4561 return false; 4562 4563 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4564 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4565 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4566 4567 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4568 const Value* CalleeArg = *CalleeArgIter; 4569 const Value* CallerArg = &(*CallerArgIter); 4570 if (CalleeArg == CallerArg) 4571 continue; 4572 4573 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4574 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4575 // } 4576 // 1st argument of callee is undef and has the same type as caller. 4577 if (CalleeArg->getType() == CallerArg->getType() && 4578 isa<UndefValue>(CalleeArg)) 4579 continue; 4580 4581 return false; 4582 } 4583 4584 return true; 4585 } 4586 4587 // Returns true if TCO is possible between the callers and callees 4588 // calling conventions. 4589 static bool 4590 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4591 CallingConv::ID CalleeCC) { 4592 // Tail calls are possible with fastcc and ccc. 4593 auto isTailCallableCC = [] (CallingConv::ID CC){ 4594 return CC == CallingConv::C || CC == CallingConv::Fast; 4595 }; 4596 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4597 return false; 4598 4599 // We can safely tail call both fastcc and ccc callees from a c calling 4600 // convention caller. If the caller is fastcc, we may have less stack space 4601 // than a non-fastcc caller with the same signature so disable tail-calls in 4602 // that case. 4603 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4604 } 4605 4606 bool 4607 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4608 SDValue Callee, 4609 CallingConv::ID CalleeCC, 4610 ImmutableCallSite CS, 4611 bool isVarArg, 4612 const SmallVectorImpl<ISD::OutputArg> &Outs, 4613 const SmallVectorImpl<ISD::InputArg> &Ins, 4614 SelectionDAG& DAG) const { 4615 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4616 4617 if (DisableSCO && !TailCallOpt) return false; 4618 4619 // Variadic argument functions are not supported. 4620 if (isVarArg) return false; 4621 4622 auto &Caller = DAG.getMachineFunction().getFunction(); 4623 // Check that the calling conventions are compatible for tco. 4624 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4625 return false; 4626 4627 // Caller contains any byval parameter is not supported. 4628 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4629 return false; 4630 4631 // Callee contains any byval parameter is not supported, too. 4632 // Note: This is a quick work around, because in some cases, e.g. 4633 // caller's stack size > callee's stack size, we are still able to apply 4634 // sibling call optimization. For example, gcc is able to do SCO for caller1 4635 // in the following example, but not for caller2. 4636 // struct test { 4637 // long int a; 4638 // char ary[56]; 4639 // } gTest; 4640 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4641 // b->a = v.a; 4642 // return 0; 4643 // } 4644 // void caller1(struct test a, struct test c, struct test *b) { 4645 // callee(gTest, b); } 4646 // void caller2(struct test *b) { callee(gTest, b); } 4647 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4648 return false; 4649 4650 // If callee and caller use different calling conventions, we cannot pass 4651 // parameters on stack since offsets for the parameter area may be different. 4652 if (Caller.getCallingConv() != CalleeCC && 4653 needStackSlotPassParameters(Subtarget, Outs)) 4654 return false; 4655 4656 // No TCO/SCO on indirect call because Caller have to restore its TOC 4657 if (!isFunctionGlobalAddress(Callee) && 4658 !isa<ExternalSymbolSDNode>(Callee)) 4659 return false; 4660 4661 // If the caller and callee potentially have different TOC bases then we 4662 // cannot tail call since we need to restore the TOC pointer after the call. 4663 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4664 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4665 return false; 4666 4667 // TCO allows altering callee ABI, so we don't have to check further. 4668 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4669 return true; 4670 4671 if (DisableSCO) return false; 4672 4673 // If callee use the same argument list that caller is using, then we can 4674 // apply SCO on this case. If it is not, then we need to check if callee needs 4675 // stack for passing arguments. 4676 if (!hasSameArgumentList(&Caller, CS) && 4677 needStackSlotPassParameters(Subtarget, Outs)) { 4678 return false; 4679 } 4680 4681 return true; 4682 } 4683 4684 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4685 /// for tail call optimization. Targets which want to do tail call 4686 /// optimization should implement this function. 4687 bool 4688 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4689 CallingConv::ID CalleeCC, 4690 bool isVarArg, 4691 const SmallVectorImpl<ISD::InputArg> &Ins, 4692 SelectionDAG& DAG) const { 4693 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4694 return false; 4695 4696 // Variable argument functions are not supported. 4697 if (isVarArg) 4698 return false; 4699 4700 MachineFunction &MF = DAG.getMachineFunction(); 4701 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4702 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4703 // Functions containing by val parameters are not supported. 4704 for (unsigned i = 0; i != Ins.size(); i++) { 4705 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4706 if (Flags.isByVal()) return false; 4707 } 4708 4709 // Non-PIC/GOT tail calls are supported. 4710 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4711 return true; 4712 4713 // At the moment we can only do local tail calls (in same module, hidden 4714 // or protected) if we are generating PIC. 4715 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4716 return G->getGlobal()->hasHiddenVisibility() 4717 || G->getGlobal()->hasProtectedVisibility(); 4718 } 4719 4720 return false; 4721 } 4722 4723 /// isCallCompatibleAddress - Return the immediate to use if the specified 4724 /// 32-bit value is representable in the immediate field of a BxA instruction. 4725 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4726 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4727 if (!C) return nullptr; 4728 4729 int Addr = C->getZExtValue(); 4730 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4731 SignExtend32<26>(Addr) != Addr) 4732 return nullptr; // Top 6 bits have to be sext of immediate. 4733 4734 return DAG 4735 .getConstant( 4736 (int)C->getZExtValue() >> 2, SDLoc(Op), 4737 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4738 .getNode(); 4739 } 4740 4741 namespace { 4742 4743 struct TailCallArgumentInfo { 4744 SDValue Arg; 4745 SDValue FrameIdxOp; 4746 int FrameIdx = 0; 4747 4748 TailCallArgumentInfo() = default; 4749 }; 4750 4751 } // end anonymous namespace 4752 4753 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4754 static void StoreTailCallArgumentsToStackSlot( 4755 SelectionDAG &DAG, SDValue Chain, 4756 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4757 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4758 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4759 SDValue Arg = TailCallArgs[i].Arg; 4760 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4761 int FI = TailCallArgs[i].FrameIdx; 4762 // Store relative to framepointer. 4763 MemOpChains.push_back(DAG.getStore( 4764 Chain, dl, Arg, FIN, 4765 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4766 } 4767 } 4768 4769 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4770 /// the appropriate stack slot for the tail call optimized function call. 4771 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4772 SDValue OldRetAddr, SDValue OldFP, 4773 int SPDiff, const SDLoc &dl) { 4774 if (SPDiff) { 4775 // Calculate the new stack slot for the return address. 4776 MachineFunction &MF = DAG.getMachineFunction(); 4777 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4778 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4779 bool isPPC64 = Subtarget.isPPC64(); 4780 int SlotSize = isPPC64 ? 8 : 4; 4781 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4782 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4783 NewRetAddrLoc, true); 4784 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4785 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4786 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4787 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4788 4789 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack 4790 // slot as the FP is never overwritten. 4791 if (Subtarget.isDarwinABI()) { 4792 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); 4793 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc, 4794 true); 4795 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); 4796 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx, 4797 MachinePointerInfo::getFixedStack( 4798 DAG.getMachineFunction(), NewFPIdx)); 4799 } 4800 } 4801 return Chain; 4802 } 4803 4804 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4805 /// the position of the argument. 4806 static void 4807 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4808 SDValue Arg, int SPDiff, unsigned ArgOffset, 4809 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4810 int Offset = ArgOffset + SPDiff; 4811 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4812 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4813 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4814 SDValue FIN = DAG.getFrameIndex(FI, VT); 4815 TailCallArgumentInfo Info; 4816 Info.Arg = Arg; 4817 Info.FrameIdxOp = FIN; 4818 Info.FrameIdx = FI; 4819 TailCallArguments.push_back(Info); 4820 } 4821 4822 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4823 /// stack slot. Returns the chain as result and the loaded frame pointers in 4824 /// LROpOut/FPOpout. Used when tail calling. 4825 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4826 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4827 SDValue &FPOpOut, const SDLoc &dl) const { 4828 if (SPDiff) { 4829 // Load the LR and FP stack slot for later adjusting. 4830 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4831 LROpOut = getReturnAddrFrameIndex(DAG); 4832 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4833 Chain = SDValue(LROpOut.getNode(), 1); 4834 4835 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack 4836 // slot as the FP is never overwritten. 4837 if (Subtarget.isDarwinABI()) { 4838 FPOpOut = getFramePointerFrameIndex(DAG); 4839 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo()); 4840 Chain = SDValue(FPOpOut.getNode(), 1); 4841 } 4842 } 4843 return Chain; 4844 } 4845 4846 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4847 /// by "Src" to address "Dst" of size "Size". Alignment information is 4848 /// specified by the specific parameter attribute. The copy will be passed as 4849 /// a byval function parameter. 4850 /// Sometimes what we are copying is the end of a larger object, the part that 4851 /// does not fit in registers. 4852 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4853 SDValue Chain, ISD::ArgFlagsTy Flags, 4854 SelectionDAG &DAG, const SDLoc &dl) { 4855 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4856 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), 4857 false, false, false, MachinePointerInfo(), 4858 MachinePointerInfo()); 4859 } 4860 4861 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4862 /// tail calls. 4863 static void LowerMemOpCallTo( 4864 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4865 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4866 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4867 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4868 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4869 if (!isTailCall) { 4870 if (isVector) { 4871 SDValue StackPtr; 4872 if (isPPC64) 4873 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4874 else 4875 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4876 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4877 DAG.getConstant(ArgOffset, dl, PtrVT)); 4878 } 4879 MemOpChains.push_back( 4880 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4881 // Calculate and remember argument location. 4882 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4883 TailCallArguments); 4884 } 4885 4886 static void 4887 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4888 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4889 SDValue FPOp, 4890 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4891 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4892 // might overwrite each other in case of tail call optimization. 4893 SmallVector<SDValue, 8> MemOpChains2; 4894 // Do not flag preceding copytoreg stuff together with the following stuff. 4895 InFlag = SDValue(); 4896 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4897 MemOpChains2, dl); 4898 if (!MemOpChains2.empty()) 4899 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4900 4901 // Store the return address to the appropriate stack slot. 4902 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4903 4904 // Emit callseq_end just before tailcall node. 4905 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4906 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4907 InFlag = Chain.getValue(1); 4908 } 4909 4910 // Is this global address that of a function that can be called by name? (as 4911 // opposed to something that must hold a descriptor for an indirect call). 4912 static bool isFunctionGlobalAddress(SDValue Callee) { 4913 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4914 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4915 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4916 return false; 4917 4918 return G->getGlobal()->getValueType()->isFunctionTy(); 4919 } 4920 4921 return false; 4922 } 4923 4924 static unsigned 4925 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, 4926 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall, 4927 bool isPatchPoint, bool hasNest, 4928 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 4929 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, 4930 ImmutableCallSite CS, const PPCSubtarget &Subtarget) { 4931 bool isPPC64 = Subtarget.isPPC64(); 4932 bool isSVR4ABI = Subtarget.isSVR4ABI(); 4933 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4934 bool isAIXABI = Subtarget.isAIXABI(); 4935 4936 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4937 NodeTys.push_back(MVT::Other); // Returns a chain 4938 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. 4939 4940 unsigned CallOpc = PPCISD::CALL; 4941 4942 bool needIndirectCall = true; 4943 if (!isSVR4ABI || !isPPC64) 4944 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { 4945 // If this is an absolute destination address, use the munged value. 4946 Callee = SDValue(Dest, 0); 4947 needIndirectCall = false; 4948 } 4949 4950 // PC-relative references to external symbols should go through $stub, unless 4951 // we're building with the leopard linker or later, which automatically 4952 // synthesizes these stubs. 4953 const TargetMachine &TM = DAG.getTarget(); 4954 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 4955 const GlobalValue *GV = nullptr; 4956 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4957 GV = G->getGlobal(); 4958 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 4959 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64; 4960 4961 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, 4962 // every direct call is) turn it into a TargetGlobalAddress / 4963 // TargetExternalSymbol node so that legalize doesn't hack it. 4964 if (isFunctionGlobalAddress(Callee)) { 4965 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 4966 4967 // A call to a TLS address is actually an indirect call to a 4968 // thread-specific pointer. 4969 unsigned OpFlags = 0; 4970 if (UsePlt) 4971 OpFlags = PPCII::MO_PLT; 4972 4973 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, 4974 Callee.getValueType(), 0, OpFlags); 4975 needIndirectCall = false; 4976 } 4977 4978 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4979 unsigned char OpFlags = 0; 4980 4981 if (UsePlt) 4982 OpFlags = PPCII::MO_PLT; 4983 4984 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), 4985 OpFlags); 4986 needIndirectCall = false; 4987 } 4988 4989 if (isPatchPoint) { 4990 // We'll form an invalid direct call when lowering a patchpoint; the full 4991 // sequence for an indirect call is complicated, and many of the 4992 // instructions introduced might have side effects (and, thus, can't be 4993 // removed later). The call itself will be removed as soon as the 4994 // argument/return lowering is complete, so the fact that it has the wrong 4995 // kind of operands should not really matter. 4996 needIndirectCall = false; 4997 } 4998 4999 if (needIndirectCall) { 5000 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair 5001 // to do the call, we can't use PPCISD::CALL. 5002 SDValue MTCTROps[] = {Chain, Callee, InFlag}; 5003 5004 if (isSVR4ABI && isPPC64 && !isELFv2ABI) { 5005 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5006 // entry point, but to the function descriptor (the function entry point 5007 // address is part of the function descriptor though). 5008 // The function descriptor is a three doubleword structure with the 5009 // following fields: function entry point, TOC base address and 5010 // environment pointer. 5011 // Thus for a call through a function pointer, the following actions need 5012 // to be performed: 5013 // 1. Save the TOC of the caller in the TOC save area of its stack 5014 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5015 // 2. Load the address of the function entry point from the function 5016 // descriptor. 5017 // 3. Load the TOC of the callee from the function descriptor into r2. 5018 // 4. Load the environment pointer from the function descriptor into 5019 // r11. 5020 // 5. Branch to the function entry point address. 5021 // 6. On return of the callee, the TOC of the caller needs to be 5022 // restored (this is done in FinishCall()). 5023 // 5024 // The loads are scheduled at the beginning of the call sequence, and the 5025 // register copies are flagged together to ensure that no other 5026 // operations can be scheduled in between. E.g. without flagging the 5027 // copies together, a TOC access in the caller could be scheduled between 5028 // the assignment of the callee TOC and the branch to the callee, which 5029 // results in the TOC access going through the TOC of the callee instead 5030 // of going through the TOC of the caller, which leads to incorrect code. 5031 5032 // Load the address of the function entry point from the function 5033 // descriptor. 5034 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); 5035 if (LDChain.getValueType() == MVT::Glue) 5036 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); 5037 5038 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5039 ? (MachineMemOperand::MODereferenceable | 5040 MachineMemOperand::MOInvariant) 5041 : MachineMemOperand::MONone; 5042 5043 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5044 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, 5045 /* Alignment = */ 8, MMOFlags); 5046 5047 // Load environment pointer into r11. 5048 SDValue PtrOff = DAG.getIntPtrConstant(16, dl); 5049 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); 5050 SDValue LoadEnvPtr = 5051 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), 5052 /* Alignment = */ 8, MMOFlags); 5053 5054 SDValue TOCOff = DAG.getIntPtrConstant(8, dl); 5055 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); 5056 SDValue TOCPtr = 5057 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), 5058 /* Alignment = */ 8, MMOFlags); 5059 5060 setUsesTOCBasePtr(DAG); 5061 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, 5062 InFlag); 5063 Chain = TOCVal.getValue(0); 5064 InFlag = TOCVal.getValue(1); 5065 5066 // If the function call has an explicit 'nest' parameter, it takes the 5067 // place of the environment pointer. 5068 if (!hasNest) { 5069 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, 5070 InFlag); 5071 5072 Chain = EnvVal.getValue(0); 5073 InFlag = EnvVal.getValue(1); 5074 } 5075 5076 MTCTROps[0] = Chain; 5077 MTCTROps[1] = LoadFuncPtr; 5078 MTCTROps[2] = InFlag; 5079 } 5080 5081 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, 5082 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); 5083 InFlag = Chain.getValue(1); 5084 5085 NodeTys.clear(); 5086 NodeTys.push_back(MVT::Other); 5087 NodeTys.push_back(MVT::Glue); 5088 Ops.push_back(Chain); 5089 CallOpc = PPCISD::BCTRL; 5090 Callee.setNode(nullptr); 5091 // Add use of X11 (holding environment pointer) 5092 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) 5093 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); 5094 // Add CTR register as callee so a bctr can be emitted later. 5095 if (isTailCall) 5096 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); 5097 } 5098 5099 // If this is a direct call, pass the chain and the callee. 5100 if (Callee.getNode()) { 5101 Ops.push_back(Chain); 5102 Ops.push_back(Callee); 5103 } 5104 // If this is a tail call add stack pointer delta. 5105 if (isTailCall) 5106 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5107 5108 // Add argument registers to the end of the list so that they are known live 5109 // into the call. 5110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5111 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5112 RegsToPass[i].second.getValueType())); 5113 5114 // All calls, in the AIX ABI and 64-bit ELF ABIs, need the TOC register 5115 // live into the call. 5116 // We do need to reserve R2/X2 to appease the verifier for the PATCHPOINT. 5117 if ((isSVR4ABI && isPPC64) || isAIXABI) { 5118 setUsesTOCBasePtr(DAG); 5119 5120 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5121 // no way to mark dependencies as implicit here. 5122 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5123 if (!isPatchPoint) 5124 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::X2 5125 : PPC::R2, PtrVT)); 5126 } 5127 5128 return CallOpc; 5129 } 5130 5131 SDValue PPCTargetLowering::LowerCallResult( 5132 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5133 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5134 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5135 SmallVector<CCValAssign, 16> RVLocs; 5136 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5137 *DAG.getContext()); 5138 5139 CCRetInfo.AnalyzeCallResult( 5140 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5141 ? RetCC_PPC_Cold 5142 : RetCC_PPC); 5143 5144 // Copy all of the result registers out of their specified physreg. 5145 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5146 CCValAssign &VA = RVLocs[i]; 5147 assert(VA.isRegLoc() && "Can only return in registers!"); 5148 5149 SDValue Val; 5150 5151 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5152 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5153 InFlag); 5154 Chain = Lo.getValue(1); 5155 InFlag = Lo.getValue(2); 5156 VA = RVLocs[++i]; // skip ahead to next loc 5157 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5158 InFlag); 5159 Chain = Hi.getValue(1); 5160 InFlag = Hi.getValue(2); 5161 if (!Subtarget.isLittleEndian()) 5162 std::swap (Lo, Hi); 5163 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5164 } else { 5165 Val = DAG.getCopyFromReg(Chain, dl, 5166 VA.getLocReg(), VA.getLocVT(), InFlag); 5167 Chain = Val.getValue(1); 5168 InFlag = Val.getValue(2); 5169 } 5170 5171 switch (VA.getLocInfo()) { 5172 default: llvm_unreachable("Unknown loc info!"); 5173 case CCValAssign::Full: break; 5174 case CCValAssign::AExt: 5175 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5176 break; 5177 case CCValAssign::ZExt: 5178 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5179 DAG.getValueType(VA.getValVT())); 5180 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5181 break; 5182 case CCValAssign::SExt: 5183 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5184 DAG.getValueType(VA.getValVT())); 5185 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5186 break; 5187 } 5188 5189 InVals.push_back(Val); 5190 } 5191 5192 return Chain; 5193 } 5194 5195 SDValue PPCTargetLowering::FinishCall( 5196 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg, 5197 bool isPatchPoint, bool hasNest, SelectionDAG &DAG, 5198 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, 5199 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5200 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5201 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5202 std::vector<EVT> NodeTys; 5203 SmallVector<SDValue, 8> Ops; 5204 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, 5205 SPDiff, isTailCall, isPatchPoint, hasNest, 5206 RegsToPass, Ops, NodeTys, CS, Subtarget); 5207 5208 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5209 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 5210 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5211 5212 // When performing tail call optimization the callee pops its arguments off 5213 // the stack. Account for this here so these bytes can be pushed back on in 5214 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5215 int BytesCalleePops = 5216 (CallConv == CallingConv::Fast && 5217 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; 5218 5219 // Add a register mask operand representing the call-preserved registers. 5220 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5221 const uint32_t *Mask = 5222 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); 5223 assert(Mask && "Missing call preserved mask for calling convention"); 5224 Ops.push_back(DAG.getRegisterMask(Mask)); 5225 5226 if (InFlag.getNode()) 5227 Ops.push_back(InFlag); 5228 5229 // Emit tail call. 5230 if (isTailCall) { 5231 assert(((Callee.getOpcode() == ISD::Register && 5232 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5233 Callee.getOpcode() == ISD::TargetExternalSymbol || 5234 Callee.getOpcode() == ISD::TargetGlobalAddress || 5235 isa<ConstantSDNode>(Callee)) && 5236 "Expecting an global address, external symbol, absolute value or register"); 5237 5238 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5239 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); 5240 } 5241 5242 // Add a NOP immediately after the branch instruction when using the 64-bit 5243 // SVR4 or the AIX ABI. 5244 // At link time, if caller and callee are in a different module and 5245 // thus have a different TOC, the call will be replaced with a call to a stub 5246 // function which saves the current TOC, loads the TOC of the callee and 5247 // branches to the callee. The NOP will be replaced with a load instruction 5248 // which restores the TOC of the caller from the TOC save slot of the current 5249 // stack frame. If caller and callee belong to the same module (and have the 5250 // same TOC), the NOP will remain unchanged, or become some other NOP. 5251 5252 MachineFunction &MF = DAG.getMachineFunction(); 5253 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5254 if (!isTailCall && !isPatchPoint && 5255 ((Subtarget.isSVR4ABI() && Subtarget.isPPC64()) || 5256 Subtarget.isAIXABI())) { 5257 if (CallOpc == PPCISD::BCTRL) { 5258 if (Subtarget.isAIXABI()) 5259 report_fatal_error("Indirect call on AIX is not implemented."); 5260 5261 // This is a call through a function pointer. 5262 // Restore the caller TOC from the save area into R2. 5263 // See PrepareCall() for more information about calls through function 5264 // pointers in the 64-bit SVR4 ABI. 5265 // We are using a target-specific load with r2 hard coded, because the 5266 // result of a target-independent load would never go directly into r2, 5267 // since r2 is a reserved register (which prevents the register allocator 5268 // from allocating it), resulting in an additional register being 5269 // allocated and an unnecessary move instruction being generated. 5270 CallOpc = PPCISD::BCTRL_LOAD_TOC; 5271 5272 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); 5273 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5274 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5275 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); 5276 5277 // The address needs to go after the chain input but before the flag (or 5278 // any other variadic arguments). 5279 Ops.insert(std::next(Ops.begin()), AddTOC); 5280 } else if (CallOpc == PPCISD::CALL && 5281 !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) { 5282 // Otherwise insert NOP for non-local calls. 5283 CallOpc = PPCISD::CALL_NOP; 5284 } 5285 } 5286 5287 if (Subtarget.isAIXABI() && isFunctionGlobalAddress(Callee)) { 5288 // On AIX, direct function calls reference the symbol for the function's 5289 // entry point, which is named by inserting a "." before the function's 5290 // C-linkage name. 5291 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5292 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5293 MCSymbol *S = Context.getOrCreateSymbol(Twine(".") + 5294 Twine(G->getGlobal()->getName())); 5295 Callee = DAG.getMCSymbol(S, PtrVT); 5296 // Replace the GlobalAddressSDNode Callee with the MCSymbolSDNode. 5297 Ops[1] = Callee; 5298 } 5299 5300 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); 5301 InFlag = Chain.getValue(1); 5302 5303 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5304 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5305 InFlag, dl); 5306 if (!Ins.empty()) 5307 InFlag = Chain.getValue(1); 5308 5309 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, 5310 Ins, dl, DAG, InVals); 5311 } 5312 5313 SDValue 5314 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5315 SmallVectorImpl<SDValue> &InVals) const { 5316 SelectionDAG &DAG = CLI.DAG; 5317 SDLoc &dl = CLI.DL; 5318 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5319 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5320 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5321 SDValue Chain = CLI.Chain; 5322 SDValue Callee = CLI.Callee; 5323 bool &isTailCall = CLI.IsTailCall; 5324 CallingConv::ID CallConv = CLI.CallConv; 5325 bool isVarArg = CLI.IsVarArg; 5326 bool isPatchPoint = CLI.IsPatchPoint; 5327 ImmutableCallSite CS = CLI.CS; 5328 5329 if (isTailCall) { 5330 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5331 isTailCall = false; 5332 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5333 isTailCall = 5334 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5335 isVarArg, Outs, Ins, DAG); 5336 else 5337 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5338 Ins, DAG); 5339 if (isTailCall) { 5340 ++NumTailCalls; 5341 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5342 ++NumSiblingCalls; 5343 5344 assert(isa<GlobalAddressSDNode>(Callee) && 5345 "Callee should be an llvm::Function object."); 5346 LLVM_DEBUG( 5347 const GlobalValue *GV = 5348 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5349 const unsigned Width = 5350 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5351 dbgs() << "TCO caller: " 5352 << left_justify(DAG.getMachineFunction().getName(), Width) 5353 << ", callee linkage: " << GV->getVisibility() << ", " 5354 << GV->getLinkage() << "\n"); 5355 } 5356 } 5357 5358 if (!isTailCall && CS && CS.isMustTailCall()) 5359 report_fatal_error("failed to perform tail call elimination on a call " 5360 "site marked musttail"); 5361 5362 // When long calls (i.e. indirect calls) are always used, calls are always 5363 // made via function pointer. If we have a function name, first translate it 5364 // into a pointer. 5365 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5366 !isTailCall) 5367 Callee = LowerGlobalAddress(Callee, DAG); 5368 5369 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5370 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, 5371 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5372 dl, DAG, InVals, CS); 5373 5374 if (Subtarget.isSVR4ABI()) 5375 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, 5376 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5377 dl, DAG, InVals, CS); 5378 5379 if (Subtarget.isAIXABI()) 5380 return LowerCall_AIX(Chain, Callee, CallConv, isVarArg, 5381 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5382 dl, DAG, InVals, CS); 5383 5384 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, 5385 isTailCall, isPatchPoint, Outs, OutVals, Ins, 5386 dl, DAG, InVals, CS); 5387 } 5388 5389 SDValue PPCTargetLowering::LowerCall_32SVR4( 5390 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5391 bool isTailCall, bool isPatchPoint, 5392 const SmallVectorImpl<ISD::OutputArg> &Outs, 5393 const SmallVectorImpl<SDValue> &OutVals, 5394 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5395 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5396 ImmutableCallSite CS) const { 5397 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5398 // of the 32-bit SVR4 ABI stack frame layout. 5399 5400 assert((CallConv == CallingConv::C || 5401 CallConv == CallingConv::Cold || 5402 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5403 5404 unsigned PtrByteSize = 4; 5405 5406 MachineFunction &MF = DAG.getMachineFunction(); 5407 5408 // Mark this function as potentially containing a function that contains a 5409 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5410 // and restoring the callers stack pointer in this functions epilog. This is 5411 // done because by tail calling the called function might overwrite the value 5412 // in this function's (MF) stack pointer stack slot 0(SP). 5413 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5414 CallConv == CallingConv::Fast) 5415 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5416 5417 // Count how many bytes are to be pushed on the stack, including the linkage 5418 // area, parameter list area and the part of the local variable space which 5419 // contains copies of aggregates which are passed by value. 5420 5421 // Assign locations to all of the outgoing arguments. 5422 SmallVector<CCValAssign, 16> ArgLocs; 5423 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 5424 5425 // Reserve space for the linkage area on the stack. 5426 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5427 PtrByteSize); 5428 if (useSoftFloat()) 5429 CCInfo.PreAnalyzeCallOperands(Outs); 5430 5431 if (isVarArg) { 5432 // Handle fixed and variable vector arguments differently. 5433 // Fixed vector arguments go into registers as long as registers are 5434 // available. Variable vector arguments always go into memory. 5435 unsigned NumArgs = Outs.size(); 5436 5437 for (unsigned i = 0; i != NumArgs; ++i) { 5438 MVT ArgVT = Outs[i].VT; 5439 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5440 bool Result; 5441 5442 if (Outs[i].IsFixed) { 5443 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5444 CCInfo); 5445 } else { 5446 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5447 ArgFlags, CCInfo); 5448 } 5449 5450 if (Result) { 5451 #ifndef NDEBUG 5452 errs() << "Call operand #" << i << " has unhandled type " 5453 << EVT(ArgVT).getEVTString() << "\n"; 5454 #endif 5455 llvm_unreachable(nullptr); 5456 } 5457 } 5458 } else { 5459 // All arguments are treated the same. 5460 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5461 } 5462 CCInfo.clearWasPPCF128(); 5463 5464 // Assign locations to all of the outgoing aggregate by value arguments. 5465 SmallVector<CCValAssign, 16> ByValArgLocs; 5466 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext()); 5467 5468 // Reserve stack space for the allocations in CCInfo. 5469 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5470 5471 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5472 5473 // Size of the linkage area, parameter list area and the part of the local 5474 // space variable where copies of aggregates which are passed by value are 5475 // stored. 5476 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5477 5478 // Calculate by how many bytes the stack has to be adjusted in case of tail 5479 // call optimization. 5480 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5481 5482 // Adjust the stack pointer for the new arguments... 5483 // These operations are automatically eliminated by the prolog/epilog pass 5484 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5485 SDValue CallSeqStart = Chain; 5486 5487 // Load the return address and frame pointer so it can be moved somewhere else 5488 // later. 5489 SDValue LROp, FPOp; 5490 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5491 5492 // Set up a copy of the stack pointer for use loading and storing any 5493 // arguments that may not fit in the registers available for argument 5494 // passing. 5495 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5496 5497 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5498 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5499 SmallVector<SDValue, 8> MemOpChains; 5500 5501 bool seenFloatArg = false; 5502 // Walk the register/memloc assignments, inserting copies/loads. 5503 // i - Tracks the index into the list of registers allocated for the call 5504 // RealArgIdx - Tracks the index into the list of actual function arguments 5505 // j - Tracks the index into the list of byval arguments 5506 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5507 i != e; 5508 ++i, ++RealArgIdx) { 5509 CCValAssign &VA = ArgLocs[i]; 5510 SDValue Arg = OutVals[RealArgIdx]; 5511 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5512 5513 if (Flags.isByVal()) { 5514 // Argument is an aggregate which is passed by value, thus we need to 5515 // create a copy of it in the local variable space of the current stack 5516 // frame (which is the stack frame of the caller) and pass the address of 5517 // this copy to the callee. 5518 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5519 CCValAssign &ByValVA = ByValArgLocs[j++]; 5520 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5521 5522 // Memory reserved in the local variable space of the callers stack frame. 5523 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5524 5525 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5526 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5527 StackPtr, PtrOff); 5528 5529 // Create a copy of the argument in the local area of the current 5530 // stack frame. 5531 SDValue MemcpyCall = 5532 CreateCopyOfByValArgument(Arg, PtrOff, 5533 CallSeqStart.getNode()->getOperand(0), 5534 Flags, DAG, dl); 5535 5536 // This must go outside the CALLSEQ_START..END. 5537 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5538 SDLoc(MemcpyCall)); 5539 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5540 NewCallSeqStart.getNode()); 5541 Chain = CallSeqStart = NewCallSeqStart; 5542 5543 // Pass the address of the aggregate copy on the stack either in a 5544 // physical register or in the parameter list area of the current stack 5545 // frame to the callee. 5546 Arg = PtrOff; 5547 } 5548 5549 // When useCRBits() is true, there can be i1 arguments. 5550 // It is because getRegisterType(MVT::i1) => MVT::i1, 5551 // and for other integer types getRegisterType() => MVT::i32. 5552 // Extend i1 and ensure callee will get i32. 5553 if (Arg.getValueType() == MVT::i1) 5554 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5555 dl, MVT::i32, Arg); 5556 5557 if (VA.isRegLoc()) { 5558 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5559 // Put argument in a physical register. 5560 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5561 bool IsLE = Subtarget.isLittleEndian(); 5562 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5563 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5564 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5565 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5566 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5567 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5568 SVal.getValue(0))); 5569 } else 5570 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5571 } else { 5572 // Put argument in the parameter list area of the current stack frame. 5573 assert(VA.isMemLoc()); 5574 unsigned LocMemOffset = VA.getLocMemOffset(); 5575 5576 if (!isTailCall) { 5577 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5578 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5579 StackPtr, PtrOff); 5580 5581 MemOpChains.push_back( 5582 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5583 } else { 5584 // Calculate and remember argument location. 5585 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5586 TailCallArguments); 5587 } 5588 } 5589 } 5590 5591 if (!MemOpChains.empty()) 5592 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5593 5594 // Build a sequence of copy-to-reg nodes chained together with token chain 5595 // and flag operands which copy the outgoing args into the appropriate regs. 5596 SDValue InFlag; 5597 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5598 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5599 RegsToPass[i].second, InFlag); 5600 InFlag = Chain.getValue(1); 5601 } 5602 5603 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5604 // registers. 5605 if (isVarArg) { 5606 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5607 SDValue Ops[] = { Chain, InFlag }; 5608 5609 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5610 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5611 5612 InFlag = Chain.getValue(1); 5613 } 5614 5615 if (isTailCall) 5616 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5617 TailCallArguments); 5618 5619 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 5620 /* unused except on PPC64 ELFv1 */ false, DAG, 5621 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 5622 NumBytes, Ins, InVals, CS); 5623 } 5624 5625 // Copy an argument into memory, being careful to do this outside the 5626 // call sequence for the call to which the argument belongs. 5627 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5628 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5629 SelectionDAG &DAG, const SDLoc &dl) const { 5630 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5631 CallSeqStart.getNode()->getOperand(0), 5632 Flags, DAG, dl); 5633 // The MEMCPY must go outside the CALLSEQ_START..END. 5634 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5635 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5636 SDLoc(MemcpyCall)); 5637 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5638 NewCallSeqStart.getNode()); 5639 return NewCallSeqStart; 5640 } 5641 5642 SDValue PPCTargetLowering::LowerCall_64SVR4( 5643 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 5644 bool isTailCall, bool isPatchPoint, 5645 const SmallVectorImpl<ISD::OutputArg> &Outs, 5646 const SmallVectorImpl<SDValue> &OutVals, 5647 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5648 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5649 ImmutableCallSite CS) const { 5650 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5651 bool isLittleEndian = Subtarget.isLittleEndian(); 5652 unsigned NumOps = Outs.size(); 5653 bool hasNest = false; 5654 bool IsSibCall = false; 5655 5656 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5657 unsigned PtrByteSize = 8; 5658 5659 MachineFunction &MF = DAG.getMachineFunction(); 5660 5661 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5662 IsSibCall = true; 5663 5664 // Mark this function as potentially containing a function that contains a 5665 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5666 // and restoring the callers stack pointer in this functions epilog. This is 5667 // done because by tail calling the called function might overwrite the value 5668 // in this function's (MF) stack pointer stack slot 0(SP). 5669 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5670 CallConv == CallingConv::Fast) 5671 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5672 5673 assert(!(CallConv == CallingConv::Fast && isVarArg) && 5674 "fastcc not supported on varargs functions"); 5675 5676 // Count how many bytes are to be pushed on the stack, including the linkage 5677 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5678 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5679 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5680 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5681 unsigned NumBytes = LinkageSize; 5682 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5683 unsigned &QFPR_idx = FPR_idx; 5684 5685 static const MCPhysReg GPR[] = { 5686 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5687 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5688 }; 5689 static const MCPhysReg VR[] = { 5690 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5691 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5692 }; 5693 5694 const unsigned NumGPRs = array_lengthof(GPR); 5695 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5696 const unsigned NumVRs = array_lengthof(VR); 5697 const unsigned NumQFPRs = NumFPRs; 5698 5699 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5700 // can be passed to the callee in registers. 5701 // For the fast calling convention, there is another check below. 5702 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5703 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast; 5704 if (!HasParameterArea) { 5705 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5706 unsigned AvailableFPRs = NumFPRs; 5707 unsigned AvailableVRs = NumVRs; 5708 unsigned NumBytesTmp = NumBytes; 5709 for (unsigned i = 0; i != NumOps; ++i) { 5710 if (Outs[i].Flags.isNest()) continue; 5711 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5712 PtrByteSize, LinkageSize, ParamAreaSize, 5713 NumBytesTmp, AvailableFPRs, AvailableVRs, 5714 Subtarget.hasQPX())) 5715 HasParameterArea = true; 5716 } 5717 } 5718 5719 // When using the fast calling convention, we don't provide backing for 5720 // arguments that will be in registers. 5721 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5722 5723 // Avoid allocating parameter area for fastcc functions if all the arguments 5724 // can be passed in the registers. 5725 if (CallConv == CallingConv::Fast) 5726 HasParameterArea = false; 5727 5728 // Add up all the space actually used. 5729 for (unsigned i = 0; i != NumOps; ++i) { 5730 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5731 EVT ArgVT = Outs[i].VT; 5732 EVT OrigVT = Outs[i].ArgVT; 5733 5734 if (Flags.isNest()) 5735 continue; 5736 5737 if (CallConv == CallingConv::Fast) { 5738 if (Flags.isByVal()) { 5739 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5740 if (NumGPRsUsed > NumGPRs) 5741 HasParameterArea = true; 5742 } else { 5743 switch (ArgVT.getSimpleVT().SimpleTy) { 5744 default: llvm_unreachable("Unexpected ValueType for argument!"); 5745 case MVT::i1: 5746 case MVT::i32: 5747 case MVT::i64: 5748 if (++NumGPRsUsed <= NumGPRs) 5749 continue; 5750 break; 5751 case MVT::v4i32: 5752 case MVT::v8i16: 5753 case MVT::v16i8: 5754 case MVT::v2f64: 5755 case MVT::v2i64: 5756 case MVT::v1i128: 5757 case MVT::f128: 5758 if (++NumVRsUsed <= NumVRs) 5759 continue; 5760 break; 5761 case MVT::v4f32: 5762 // When using QPX, this is handled like a FP register, otherwise, it 5763 // is an Altivec register. 5764 if (Subtarget.hasQPX()) { 5765 if (++NumFPRsUsed <= NumFPRs) 5766 continue; 5767 } else { 5768 if (++NumVRsUsed <= NumVRs) 5769 continue; 5770 } 5771 break; 5772 case MVT::f32: 5773 case MVT::f64: 5774 case MVT::v4f64: // QPX 5775 case MVT::v4i1: // QPX 5776 if (++NumFPRsUsed <= NumFPRs) 5777 continue; 5778 break; 5779 } 5780 HasParameterArea = true; 5781 } 5782 } 5783 5784 /* Respect alignment of argument on the stack. */ 5785 unsigned Align = 5786 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5787 NumBytes = ((NumBytes + Align - 1) / Align) * Align; 5788 5789 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5790 if (Flags.isInConsecutiveRegsLast()) 5791 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5792 } 5793 5794 unsigned NumBytesActuallyUsed = NumBytes; 5795 5796 // In the old ELFv1 ABI, 5797 // the prolog code of the callee may store up to 8 GPR argument registers to 5798 // the stack, allowing va_start to index over them in memory if its varargs. 5799 // Because we cannot tell if this is needed on the caller side, we have to 5800 // conservatively assume that it is needed. As such, make sure we have at 5801 // least enough stack space for the caller to store the 8 GPRs. 5802 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5803 // really requires memory operands, e.g. a vararg function. 5804 if (HasParameterArea) 5805 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5806 else 5807 NumBytes = LinkageSize; 5808 5809 // Tail call needs the stack to be aligned. 5810 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5811 CallConv == CallingConv::Fast) 5812 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5813 5814 int SPDiff = 0; 5815 5816 // Calculate by how many bytes the stack has to be adjusted in case of tail 5817 // call optimization. 5818 if (!IsSibCall) 5819 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 5820 5821 // To protect arguments on the stack from being clobbered in a tail call, 5822 // force all the loads to happen before doing any other lowering. 5823 if (isTailCall) 5824 Chain = DAG.getStackArgumentTokenFactor(Chain); 5825 5826 // Adjust the stack pointer for the new arguments... 5827 // These operations are automatically eliminated by the prolog/epilog pass 5828 if (!IsSibCall) 5829 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5830 SDValue CallSeqStart = Chain; 5831 5832 // Load the return address and frame pointer so it can be move somewhere else 5833 // later. 5834 SDValue LROp, FPOp; 5835 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5836 5837 // Set up a copy of the stack pointer for use loading and storing any 5838 // arguments that may not fit in the registers available for argument 5839 // passing. 5840 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5841 5842 // Figure out which arguments are going to go in registers, and which in 5843 // memory. Also, if this is a vararg function, floating point operations 5844 // must be stored to our stack, and loaded into integer regs as well, if 5845 // any integer regs are available for argument passing. 5846 unsigned ArgOffset = LinkageSize; 5847 5848 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5849 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5850 5851 SmallVector<SDValue, 8> MemOpChains; 5852 for (unsigned i = 0; i != NumOps; ++i) { 5853 SDValue Arg = OutVals[i]; 5854 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5855 EVT ArgVT = Outs[i].VT; 5856 EVT OrigVT = Outs[i].ArgVT; 5857 5858 // PtrOff will be used to store the current argument to the stack if a 5859 // register cannot be found for it. 5860 SDValue PtrOff; 5861 5862 // We re-align the argument offset for each argument, except when using the 5863 // fast calling convention, when we need to make sure we do that only when 5864 // we'll actually use a stack slot. 5865 auto ComputePtrOff = [&]() { 5866 /* Respect alignment of argument on the stack. */ 5867 unsigned Align = 5868 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5869 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; 5870 5871 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5872 5873 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 5874 }; 5875 5876 if (CallConv != CallingConv::Fast) { 5877 ComputePtrOff(); 5878 5879 /* Compute GPR index associated with argument offset. */ 5880 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 5881 GPR_idx = std::min(GPR_idx, NumGPRs); 5882 } 5883 5884 // Promote integers to 64-bit values. 5885 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 5886 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 5887 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 5888 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 5889 } 5890 5891 // FIXME memcpy is used way more than necessary. Correctness first. 5892 // Note: "by value" is code for passing a structure by value, not 5893 // basic types. 5894 if (Flags.isByVal()) { 5895 // Note: Size includes alignment padding, so 5896 // struct x { short a; char b; } 5897 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 5898 // These are the proper values we need for right-justifying the 5899 // aggregate in a parameter register. 5900 unsigned Size = Flags.getByValSize(); 5901 5902 // An empty aggregate parameter takes up no storage and no 5903 // registers. 5904 if (Size == 0) 5905 continue; 5906 5907 if (CallConv == CallingConv::Fast) 5908 ComputePtrOff(); 5909 5910 // All aggregates smaller than 8 bytes must be passed right-justified. 5911 if (Size==1 || Size==2 || Size==4) { 5912 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 5913 if (GPR_idx != NumGPRs) { 5914 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 5915 MachinePointerInfo(), VT); 5916 MemOpChains.push_back(Load.getValue(1)); 5917 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5918 5919 ArgOffset += PtrByteSize; 5920 continue; 5921 } 5922 } 5923 5924 if (GPR_idx == NumGPRs && Size < 8) { 5925 SDValue AddPtr = PtrOff; 5926 if (!isLittleEndian) { 5927 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 5928 PtrOff.getValueType()); 5929 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5930 } 5931 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5932 CallSeqStart, 5933 Flags, DAG, dl); 5934 ArgOffset += PtrByteSize; 5935 continue; 5936 } 5937 // Copy entire object into memory. There are cases where gcc-generated 5938 // code assumes it is there, even if it could be put entirely into 5939 // registers. (This is not what the doc says.) 5940 5941 // FIXME: The above statement is likely due to a misunderstanding of the 5942 // documents. All arguments must be copied into the parameter area BY 5943 // THE CALLEE in the event that the callee takes the address of any 5944 // formal argument. That has not yet been implemented. However, it is 5945 // reasonable to use the stack area as a staging area for the register 5946 // load. 5947 5948 // Skip this for small aggregates, as we will use the same slot for a 5949 // right-justified copy, below. 5950 if (Size >= 8) 5951 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 5952 CallSeqStart, 5953 Flags, DAG, dl); 5954 5955 // When a register is available, pass a small aggregate right-justified. 5956 if (Size < 8 && GPR_idx != NumGPRs) { 5957 // The easiest way to get this right-justified in a register 5958 // is to copy the structure into the rightmost portion of a 5959 // local variable slot, then load the whole slot into the 5960 // register. 5961 // FIXME: The memcpy seems to produce pretty awful code for 5962 // small aggregates, particularly for packed ones. 5963 // FIXME: It would be preferable to use the slot in the 5964 // parameter save area instead of a new local variable. 5965 SDValue AddPtr = PtrOff; 5966 if (!isLittleEndian) { 5967 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 5968 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 5969 } 5970 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 5971 CallSeqStart, 5972 Flags, DAG, dl); 5973 5974 // Load the slot into the register. 5975 SDValue Load = 5976 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 5977 MemOpChains.push_back(Load.getValue(1)); 5978 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5979 5980 // Done with this argument. 5981 ArgOffset += PtrByteSize; 5982 continue; 5983 } 5984 5985 // For aggregates larger than PtrByteSize, copy the pieces of the 5986 // object that fit into registers from the parameter save area. 5987 for (unsigned j=0; j<Size; j+=PtrByteSize) { 5988 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 5989 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 5990 if (GPR_idx != NumGPRs) { 5991 SDValue Load = 5992 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 5993 MemOpChains.push_back(Load.getValue(1)); 5994 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 5995 ArgOffset += PtrByteSize; 5996 } else { 5997 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 5998 break; 5999 } 6000 } 6001 continue; 6002 } 6003 6004 switch (Arg.getSimpleValueType().SimpleTy) { 6005 default: llvm_unreachable("Unexpected ValueType for argument!"); 6006 case MVT::i1: 6007 case MVT::i32: 6008 case MVT::i64: 6009 if (Flags.isNest()) { 6010 // The 'nest' parameter, if any, is passed in R11. 6011 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6012 hasNest = true; 6013 break; 6014 } 6015 6016 // These can be scalar arguments or elements of an integer array type 6017 // passed directly. Clang may use those instead of "byval" aggregate 6018 // types to avoid forcing arguments to memory unnecessarily. 6019 if (GPR_idx != NumGPRs) { 6020 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6021 } else { 6022 if (CallConv == CallingConv::Fast) 6023 ComputePtrOff(); 6024 6025 assert(HasParameterArea && 6026 "Parameter area must exist to pass an argument in memory."); 6027 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6028 true, isTailCall, false, MemOpChains, 6029 TailCallArguments, dl); 6030 if (CallConv == CallingConv::Fast) 6031 ArgOffset += PtrByteSize; 6032 } 6033 if (CallConv != CallingConv::Fast) 6034 ArgOffset += PtrByteSize; 6035 break; 6036 case MVT::f32: 6037 case MVT::f64: { 6038 // These can be scalar arguments or elements of a float array type 6039 // passed directly. The latter are used to implement ELFv2 homogenous 6040 // float aggregates. 6041 6042 // Named arguments go into FPRs first, and once they overflow, the 6043 // remaining arguments go into GPRs and then the parameter save area. 6044 // Unnamed arguments for vararg functions always go to GPRs and 6045 // then the parameter save area. For now, put all arguments to vararg 6046 // routines always in both locations (FPR *and* GPR or stack slot). 6047 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; 6048 bool NeededLoad = false; 6049 6050 // First load the argument into the next available FPR. 6051 if (FPR_idx != NumFPRs) 6052 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6053 6054 // Next, load the argument into GPR or stack slot if needed. 6055 if (!NeedGPROrStack) 6056 ; 6057 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { 6058 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6059 // once we support fp <-> gpr moves. 6060 6061 // In the non-vararg case, this can only ever happen in the 6062 // presence of f32 array types, since otherwise we never run 6063 // out of FPRs before running out of GPRs. 6064 SDValue ArgVal; 6065 6066 // Double values are always passed in a single GPR. 6067 if (Arg.getValueType() != MVT::f32) { 6068 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6069 6070 // Non-array float values are extended and passed in a GPR. 6071 } else if (!Flags.isInConsecutiveRegs()) { 6072 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6073 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6074 6075 // If we have an array of floats, we collect every odd element 6076 // together with its predecessor into one GPR. 6077 } else if (ArgOffset % PtrByteSize != 0) { 6078 SDValue Lo, Hi; 6079 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6080 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6081 if (!isLittleEndian) 6082 std::swap(Lo, Hi); 6083 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6084 6085 // The final element, if even, goes into the first half of a GPR. 6086 } else if (Flags.isInConsecutiveRegsLast()) { 6087 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6088 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6089 if (!isLittleEndian) 6090 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6091 DAG.getConstant(32, dl, MVT::i32)); 6092 6093 // Non-final even elements are skipped; they will be handled 6094 // together the with subsequent argument on the next go-around. 6095 } else 6096 ArgVal = SDValue(); 6097 6098 if (ArgVal.getNode()) 6099 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6100 } else { 6101 if (CallConv == CallingConv::Fast) 6102 ComputePtrOff(); 6103 6104 // Single-precision floating-point values are mapped to the 6105 // second (rightmost) word of the stack doubleword. 6106 if (Arg.getValueType() == MVT::f32 && 6107 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6108 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6109 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6110 } 6111 6112 assert(HasParameterArea && 6113 "Parameter area must exist to pass an argument in memory."); 6114 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6115 true, isTailCall, false, MemOpChains, 6116 TailCallArguments, dl); 6117 6118 NeededLoad = true; 6119 } 6120 // When passing an array of floats, the array occupies consecutive 6121 // space in the argument area; only round up to the next doubleword 6122 // at the end of the array. Otherwise, each float takes 8 bytes. 6123 if (CallConv != CallingConv::Fast || NeededLoad) { 6124 ArgOffset += (Arg.getValueType() == MVT::f32 && 6125 Flags.isInConsecutiveRegs()) ? 4 : 8; 6126 if (Flags.isInConsecutiveRegsLast()) 6127 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6128 } 6129 break; 6130 } 6131 case MVT::v4f32: 6132 case MVT::v4i32: 6133 case MVT::v8i16: 6134 case MVT::v16i8: 6135 case MVT::v2f64: 6136 case MVT::v2i64: 6137 case MVT::v1i128: 6138 case MVT::f128: 6139 if (!Subtarget.hasQPX()) { 6140 // These can be scalar arguments or elements of a vector array type 6141 // passed directly. The latter are used to implement ELFv2 homogenous 6142 // vector aggregates. 6143 6144 // For a varargs call, named arguments go into VRs or on the stack as 6145 // usual; unnamed arguments always go to the stack or the corresponding 6146 // GPRs when within range. For now, we always put the value in both 6147 // locations (or even all three). 6148 if (isVarArg) { 6149 assert(HasParameterArea && 6150 "Parameter area must exist if we have a varargs call."); 6151 // We could elide this store in the case where the object fits 6152 // entirely in R registers. Maybe later. 6153 SDValue Store = 6154 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6155 MemOpChains.push_back(Store); 6156 if (VR_idx != NumVRs) { 6157 SDValue Load = 6158 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6159 MemOpChains.push_back(Load.getValue(1)); 6160 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6161 } 6162 ArgOffset += 16; 6163 for (unsigned i=0; i<16; i+=PtrByteSize) { 6164 if (GPR_idx == NumGPRs) 6165 break; 6166 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6167 DAG.getConstant(i, dl, PtrVT)); 6168 SDValue Load = 6169 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6170 MemOpChains.push_back(Load.getValue(1)); 6171 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6172 } 6173 break; 6174 } 6175 6176 // Non-varargs Altivec params go into VRs or on the stack. 6177 if (VR_idx != NumVRs) { 6178 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6179 } else { 6180 if (CallConv == CallingConv::Fast) 6181 ComputePtrOff(); 6182 6183 assert(HasParameterArea && 6184 "Parameter area must exist to pass an argument in memory."); 6185 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6186 true, isTailCall, true, MemOpChains, 6187 TailCallArguments, dl); 6188 if (CallConv == CallingConv::Fast) 6189 ArgOffset += 16; 6190 } 6191 6192 if (CallConv != CallingConv::Fast) 6193 ArgOffset += 16; 6194 break; 6195 } // not QPX 6196 6197 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6198 "Invalid QPX parameter type"); 6199 6200 LLVM_FALLTHROUGH; 6201 case MVT::v4f64: 6202 case MVT::v4i1: { 6203 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6204 if (isVarArg) { 6205 assert(HasParameterArea && 6206 "Parameter area must exist if we have a varargs call."); 6207 // We could elide this store in the case where the object fits 6208 // entirely in R registers. Maybe later. 6209 SDValue Store = 6210 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6211 MemOpChains.push_back(Store); 6212 if (QFPR_idx != NumQFPRs) { 6213 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6214 PtrOff, MachinePointerInfo()); 6215 MemOpChains.push_back(Load.getValue(1)); 6216 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6217 } 6218 ArgOffset += (IsF32 ? 16 : 32); 6219 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6220 if (GPR_idx == NumGPRs) 6221 break; 6222 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6223 DAG.getConstant(i, dl, PtrVT)); 6224 SDValue Load = 6225 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6226 MemOpChains.push_back(Load.getValue(1)); 6227 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6228 } 6229 break; 6230 } 6231 6232 // Non-varargs QPX params go into registers or on the stack. 6233 if (QFPR_idx != NumQFPRs) { 6234 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6235 } else { 6236 if (CallConv == CallingConv::Fast) 6237 ComputePtrOff(); 6238 6239 assert(HasParameterArea && 6240 "Parameter area must exist to pass an argument in memory."); 6241 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6242 true, isTailCall, true, MemOpChains, 6243 TailCallArguments, dl); 6244 if (CallConv == CallingConv::Fast) 6245 ArgOffset += (IsF32 ? 16 : 32); 6246 } 6247 6248 if (CallConv != CallingConv::Fast) 6249 ArgOffset += (IsF32 ? 16 : 32); 6250 break; 6251 } 6252 } 6253 } 6254 6255 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6256 "mismatch in size of parameter area"); 6257 (void)NumBytesActuallyUsed; 6258 6259 if (!MemOpChains.empty()) 6260 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6261 6262 // Check if this is an indirect call (MTCTR/BCTRL). 6263 // See PrepareCall() for more information about calls through function 6264 // pointers in the 64-bit SVR4 ABI. 6265 if (!isTailCall && !isPatchPoint && 6266 !isFunctionGlobalAddress(Callee) && 6267 !isa<ExternalSymbolSDNode>(Callee)) { 6268 // Load r2 into a virtual register and store it to the TOC save area. 6269 setUsesTOCBasePtr(DAG); 6270 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6271 // TOC save area offset. 6272 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6273 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6274 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6275 Chain = DAG.getStore( 6276 Val.getValue(1), dl, Val, AddPtr, 6277 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6278 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6279 // This does not mean the MTCTR instruction must use R12; it's easier 6280 // to model this as an extra parameter, so do that. 6281 if (isELFv2ABI && !isPatchPoint) 6282 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6283 } 6284 6285 // Build a sequence of copy-to-reg nodes chained together with token chain 6286 // and flag operands which copy the outgoing args into the appropriate regs. 6287 SDValue InFlag; 6288 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6289 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6290 RegsToPass[i].second, InFlag); 6291 InFlag = Chain.getValue(1); 6292 } 6293 6294 if (isTailCall && !IsSibCall) 6295 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6296 TailCallArguments); 6297 6298 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest, 6299 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, 6300 SPDiff, NumBytes, Ins, InVals, CS); 6301 } 6302 6303 SDValue PPCTargetLowering::LowerCall_Darwin( 6304 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6305 bool isTailCall, bool isPatchPoint, 6306 const SmallVectorImpl<ISD::OutputArg> &Outs, 6307 const SmallVectorImpl<SDValue> &OutVals, 6308 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6309 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6310 ImmutableCallSite CS) const { 6311 unsigned NumOps = Outs.size(); 6312 6313 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6314 bool isPPC64 = PtrVT == MVT::i64; 6315 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6316 6317 MachineFunction &MF = DAG.getMachineFunction(); 6318 6319 // Mark this function as potentially containing a function that contains a 6320 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6321 // and restoring the callers stack pointer in this functions epilog. This is 6322 // done because by tail calling the called function might overwrite the value 6323 // in this function's (MF) stack pointer stack slot 0(SP). 6324 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6325 CallConv == CallingConv::Fast) 6326 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6327 6328 // Count how many bytes are to be pushed on the stack, including the linkage 6329 // area, and parameter passing area. We start with 24/48 bytes, which is 6330 // prereserved space for [SP][CR][LR][3 x unused]. 6331 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6332 unsigned NumBytes = LinkageSize; 6333 6334 // Add up all the space actually used. 6335 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6336 // they all go in registers, but we must reserve stack space for them for 6337 // possible use by the caller. In varargs or 64-bit calls, parameters are 6338 // assigned stack space in order, with padding so Altivec parameters are 6339 // 16-byte aligned. 6340 unsigned nAltivecParamsAtEnd = 0; 6341 for (unsigned i = 0; i != NumOps; ++i) { 6342 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6343 EVT ArgVT = Outs[i].VT; 6344 // Varargs Altivec parameters are padded to a 16 byte boundary. 6345 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6346 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6347 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6348 if (!isVarArg && !isPPC64) { 6349 // Non-varargs Altivec parameters go after all the non-Altivec 6350 // parameters; handle those later so we know how much padding we need. 6351 nAltivecParamsAtEnd++; 6352 continue; 6353 } 6354 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6355 NumBytes = ((NumBytes+15)/16)*16; 6356 } 6357 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6358 } 6359 6360 // Allow for Altivec parameters at the end, if needed. 6361 if (nAltivecParamsAtEnd) { 6362 NumBytes = ((NumBytes+15)/16)*16; 6363 NumBytes += 16*nAltivecParamsAtEnd; 6364 } 6365 6366 // The prolog code of the callee may store up to 8 GPR argument registers to 6367 // the stack, allowing va_start to index over them in memory if its varargs. 6368 // Because we cannot tell if this is needed on the caller side, we have to 6369 // conservatively assume that it is needed. As such, make sure we have at 6370 // least enough stack space for the caller to store the 8 GPRs. 6371 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6372 6373 // Tail call needs the stack to be aligned. 6374 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6375 CallConv == CallingConv::Fast) 6376 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6377 6378 // Calculate by how many bytes the stack has to be adjusted in case of tail 6379 // call optimization. 6380 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); 6381 6382 // To protect arguments on the stack from being clobbered in a tail call, 6383 // force all the loads to happen before doing any other lowering. 6384 if (isTailCall) 6385 Chain = DAG.getStackArgumentTokenFactor(Chain); 6386 6387 // Adjust the stack pointer for the new arguments... 6388 // These operations are automatically eliminated by the prolog/epilog pass 6389 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6390 SDValue CallSeqStart = Chain; 6391 6392 // Load the return address and frame pointer so it can be move somewhere else 6393 // later. 6394 SDValue LROp, FPOp; 6395 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6396 6397 // Set up a copy of the stack pointer for use loading and storing any 6398 // arguments that may not fit in the registers available for argument 6399 // passing. 6400 SDValue StackPtr; 6401 if (isPPC64) 6402 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6403 else 6404 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6405 6406 // Figure out which arguments are going to go in registers, and which in 6407 // memory. Also, if this is a vararg function, floating point operations 6408 // must be stored to our stack, and loaded into integer regs as well, if 6409 // any integer regs are available for argument passing. 6410 unsigned ArgOffset = LinkageSize; 6411 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6412 6413 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6414 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6415 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6416 }; 6417 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6418 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6419 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6420 }; 6421 static const MCPhysReg VR[] = { 6422 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6423 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6424 }; 6425 const unsigned NumGPRs = array_lengthof(GPR_32); 6426 const unsigned NumFPRs = 13; 6427 const unsigned NumVRs = array_lengthof(VR); 6428 6429 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6430 6431 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6432 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6433 6434 SmallVector<SDValue, 8> MemOpChains; 6435 for (unsigned i = 0; i != NumOps; ++i) { 6436 SDValue Arg = OutVals[i]; 6437 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6438 6439 // PtrOff will be used to store the current argument to the stack if a 6440 // register cannot be found for it. 6441 SDValue PtrOff; 6442 6443 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6444 6445 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6446 6447 // On PPC64, promote integers to 64-bit values. 6448 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6449 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6450 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6451 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6452 } 6453 6454 // FIXME memcpy is used way more than necessary. Correctness first. 6455 // Note: "by value" is code for passing a structure by value, not 6456 // basic types. 6457 if (Flags.isByVal()) { 6458 unsigned Size = Flags.getByValSize(); 6459 // Very small objects are passed right-justified. Everything else is 6460 // passed left-justified. 6461 if (Size==1 || Size==2) { 6462 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6463 if (GPR_idx != NumGPRs) { 6464 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6465 MachinePointerInfo(), VT); 6466 MemOpChains.push_back(Load.getValue(1)); 6467 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6468 6469 ArgOffset += PtrByteSize; 6470 } else { 6471 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6472 PtrOff.getValueType()); 6473 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6474 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6475 CallSeqStart, 6476 Flags, DAG, dl); 6477 ArgOffset += PtrByteSize; 6478 } 6479 continue; 6480 } 6481 // Copy entire object into memory. There are cases where gcc-generated 6482 // code assumes it is there, even if it could be put entirely into 6483 // registers. (This is not what the doc says.) 6484 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6485 CallSeqStart, 6486 Flags, DAG, dl); 6487 6488 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6489 // copy the pieces of the object that fit into registers from the 6490 // parameter save area. 6491 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6492 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6493 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6494 if (GPR_idx != NumGPRs) { 6495 SDValue Load = 6496 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6497 MemOpChains.push_back(Load.getValue(1)); 6498 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6499 ArgOffset += PtrByteSize; 6500 } else { 6501 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6502 break; 6503 } 6504 } 6505 continue; 6506 } 6507 6508 switch (Arg.getSimpleValueType().SimpleTy) { 6509 default: llvm_unreachable("Unexpected ValueType for argument!"); 6510 case MVT::i1: 6511 case MVT::i32: 6512 case MVT::i64: 6513 if (GPR_idx != NumGPRs) { 6514 if (Arg.getValueType() == MVT::i1) 6515 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6516 6517 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6518 } else { 6519 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6520 isPPC64, isTailCall, false, MemOpChains, 6521 TailCallArguments, dl); 6522 } 6523 ArgOffset += PtrByteSize; 6524 break; 6525 case MVT::f32: 6526 case MVT::f64: 6527 if (FPR_idx != NumFPRs) { 6528 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6529 6530 if (isVarArg) { 6531 SDValue Store = 6532 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6533 MemOpChains.push_back(Store); 6534 6535 // Float varargs are always shadowed in available integer registers 6536 if (GPR_idx != NumGPRs) { 6537 SDValue Load = 6538 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6539 MemOpChains.push_back(Load.getValue(1)); 6540 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6541 } 6542 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6543 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6544 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6545 SDValue Load = 6546 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6547 MemOpChains.push_back(Load.getValue(1)); 6548 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6549 } 6550 } else { 6551 // If we have any FPRs remaining, we may also have GPRs remaining. 6552 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6553 // GPRs. 6554 if (GPR_idx != NumGPRs) 6555 ++GPR_idx; 6556 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6557 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6558 ++GPR_idx; 6559 } 6560 } else 6561 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6562 isPPC64, isTailCall, false, MemOpChains, 6563 TailCallArguments, dl); 6564 if (isPPC64) 6565 ArgOffset += 8; 6566 else 6567 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6568 break; 6569 case MVT::v4f32: 6570 case MVT::v4i32: 6571 case MVT::v8i16: 6572 case MVT::v16i8: 6573 if (isVarArg) { 6574 // These go aligned on the stack, or in the corresponding R registers 6575 // when within range. The Darwin PPC ABI doc claims they also go in 6576 // V registers; in fact gcc does this only for arguments that are 6577 // prototyped, not for those that match the ... We do it for all 6578 // arguments, seems to work. 6579 while (ArgOffset % 16 !=0) { 6580 ArgOffset += PtrByteSize; 6581 if (GPR_idx != NumGPRs) 6582 GPR_idx++; 6583 } 6584 // We could elide this store in the case where the object fits 6585 // entirely in R registers. Maybe later. 6586 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6587 DAG.getConstant(ArgOffset, dl, PtrVT)); 6588 SDValue Store = 6589 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6590 MemOpChains.push_back(Store); 6591 if (VR_idx != NumVRs) { 6592 SDValue Load = 6593 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6594 MemOpChains.push_back(Load.getValue(1)); 6595 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6596 } 6597 ArgOffset += 16; 6598 for (unsigned i=0; i<16; i+=PtrByteSize) { 6599 if (GPR_idx == NumGPRs) 6600 break; 6601 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6602 DAG.getConstant(i, dl, PtrVT)); 6603 SDValue Load = 6604 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6605 MemOpChains.push_back(Load.getValue(1)); 6606 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6607 } 6608 break; 6609 } 6610 6611 // Non-varargs Altivec params generally go in registers, but have 6612 // stack space allocated at the end. 6613 if (VR_idx != NumVRs) { 6614 // Doesn't have GPR space allocated. 6615 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6616 } else if (nAltivecParamsAtEnd==0) { 6617 // We are emitting Altivec params in order. 6618 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6619 isPPC64, isTailCall, true, MemOpChains, 6620 TailCallArguments, dl); 6621 ArgOffset += 16; 6622 } 6623 break; 6624 } 6625 } 6626 // If all Altivec parameters fit in registers, as they usually do, 6627 // they get stack space following the non-Altivec parameters. We 6628 // don't track this here because nobody below needs it. 6629 // If there are more Altivec parameters than fit in registers emit 6630 // the stores here. 6631 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { 6632 unsigned j = 0; 6633 // Offset is aligned; skip 1st 12 params which go in V registers. 6634 ArgOffset = ((ArgOffset+15)/16)*16; 6635 ArgOffset += 12*16; 6636 for (unsigned i = 0; i != NumOps; ++i) { 6637 SDValue Arg = OutVals[i]; 6638 EVT ArgType = Outs[i].VT; 6639 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6640 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6641 if (++j > NumVRs) { 6642 SDValue PtrOff; 6643 // We are emitting Altivec params in order. 6644 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6645 isPPC64, isTailCall, true, MemOpChains, 6646 TailCallArguments, dl); 6647 ArgOffset += 16; 6648 } 6649 } 6650 } 6651 } 6652 6653 if (!MemOpChains.empty()) 6654 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6655 6656 // On Darwin, R12 must contain the address of an indirect callee. This does 6657 // not mean the MTCTR instruction must use R12; it's easier to model this as 6658 // an extra parameter, so do that. 6659 if (!isTailCall && 6660 !isFunctionGlobalAddress(Callee) && 6661 !isa<ExternalSymbolSDNode>(Callee) && 6662 !isBLACompatibleAddress(Callee, DAG)) 6663 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6664 PPC::R12), Callee)); 6665 6666 // Build a sequence of copy-to-reg nodes chained together with token chain 6667 // and flag operands which copy the outgoing args into the appropriate regs. 6668 SDValue InFlag; 6669 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6670 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6671 RegsToPass[i].second, InFlag); 6672 InFlag = Chain.getValue(1); 6673 } 6674 6675 if (isTailCall) 6676 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6677 TailCallArguments); 6678 6679 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6680 /* unused except on PPC64 ELFv1 */ false, DAG, 6681 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6682 NumBytes, Ins, InVals, CS); 6683 } 6684 6685 6686 SDValue PPCTargetLowering::LowerCall_AIX( 6687 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, 6688 bool isTailCall, bool isPatchPoint, 6689 const SmallVectorImpl<ISD::OutputArg> &Outs, 6690 const SmallVectorImpl<SDValue> &OutVals, 6691 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6692 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6693 ImmutableCallSite CS) const { 6694 6695 assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) && 6696 "Unimplemented calling convention!"); 6697 if (isVarArg || isPatchPoint) 6698 report_fatal_error("This call type is unimplemented on AIX."); 6699 6700 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6701 bool isPPC64 = PtrVT == MVT::i64; 6702 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6703 unsigned NumOps = Outs.size(); 6704 6705 6706 // Count how many bytes are to be pushed on the stack, including the linkage 6707 // area, parameter list area. 6708 // On XCOFF, we start with 24/48, which is reserved space for 6709 // [SP][CR][LR][2 x reserved][TOC]. 6710 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6711 6712 // The prolog code of the callee may store up to 8 GPR argument registers to 6713 // the stack, allowing va_start to index over them in memory if the callee 6714 // is variadic. 6715 // Because we cannot tell if this is needed on the caller side, we have to 6716 // conservatively assume that it is needed. As such, make sure we have at 6717 // least enough stack space for the caller to store the 8 GPRs. 6718 unsigned NumBytes = LinkageSize + 8 * PtrByteSize; 6719 6720 // Adjust the stack pointer for the new arguments... 6721 // These operations are automatically eliminated by the prolog/epilog 6722 // inserter pass. 6723 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6724 SDValue CallSeqStart = Chain; 6725 6726 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6727 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6728 PPC::R7, PPC::R8, PPC::R9, PPC::R10 6729 }; 6730 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6731 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6732 PPC::X7, PPC::X8, PPC::X9, PPC::X10 6733 }; 6734 6735 const unsigned NumGPRs = isPPC64 ? array_lengthof(GPR_64) 6736 : array_lengthof(GPR_32); 6737 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6738 unsigned GPR_idx = 0; 6739 6740 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6741 6742 if (isTailCall) 6743 report_fatal_error("Handling of tail call is unimplemented!"); 6744 int SPDiff = 0; 6745 6746 for (unsigned i = 0; i != NumOps; ++i) { 6747 SDValue Arg = OutVals[i]; 6748 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6749 6750 // Promote integers if needed. 6751 if (Arg.getValueType() == MVT::i1 || 6752 (isPPC64 && Arg.getValueType() == MVT::i32)) { 6753 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6754 Arg = DAG.getNode(ExtOp, dl, PtrVT, Arg); 6755 } 6756 6757 // Note: "by value" is code for passing a structure by value, not 6758 // basic types. 6759 if (Flags.isByVal()) 6760 report_fatal_error("Passing structure by value is unimplemented!"); 6761 6762 switch (Arg.getSimpleValueType().SimpleTy) { 6763 default: llvm_unreachable("Unexpected ValueType for argument!"); 6764 case MVT::i1: 6765 case MVT::i32: 6766 case MVT::i64: 6767 if (GPR_idx != NumGPRs) 6768 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6769 else 6770 report_fatal_error("Handling of placing parameters on the stack is " 6771 "unimplemented!"); 6772 break; 6773 case MVT::f32: 6774 case MVT::f64: 6775 case MVT::v4f32: 6776 case MVT::v4i32: 6777 case MVT::v8i16: 6778 case MVT::v16i8: 6779 case MVT::v2f64: 6780 case MVT::v2i64: 6781 case MVT::v1i128: 6782 case MVT::f128: 6783 case MVT::v4f64: 6784 case MVT::v4i1: 6785 report_fatal_error("Handling of this parameter type is unimplemented!"); 6786 } 6787 } 6788 6789 if (!isFunctionGlobalAddress(Callee) && 6790 !isa<ExternalSymbolSDNode>(Callee)) 6791 report_fatal_error("Handling of indirect call is unimplemented!"); 6792 6793 // Build a sequence of copy-to-reg nodes chained together with token chain 6794 // and flag operands which copy the outgoing args into the appropriate regs. 6795 SDValue InFlag; 6796 for (auto Reg : RegsToPass) { 6797 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 6798 InFlag = Chain.getValue(1); 6799 } 6800 6801 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, 6802 /* unused except on PPC64 ELFv1 */ false, DAG, 6803 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, 6804 NumBytes, Ins, InVals, CS); 6805 } 6806 6807 bool 6808 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 6809 MachineFunction &MF, bool isVarArg, 6810 const SmallVectorImpl<ISD::OutputArg> &Outs, 6811 LLVMContext &Context) const { 6812 SmallVector<CCValAssign, 16> RVLocs; 6813 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 6814 return CCInfo.CheckReturn( 6815 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6816 ? RetCC_PPC_Cold 6817 : RetCC_PPC); 6818 } 6819 6820 SDValue 6821 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 6822 bool isVarArg, 6823 const SmallVectorImpl<ISD::OutputArg> &Outs, 6824 const SmallVectorImpl<SDValue> &OutVals, 6825 const SDLoc &dl, SelectionDAG &DAG) const { 6826 SmallVector<CCValAssign, 16> RVLocs; 6827 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 6828 *DAG.getContext()); 6829 CCInfo.AnalyzeReturn(Outs, 6830 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 6831 ? RetCC_PPC_Cold 6832 : RetCC_PPC); 6833 6834 SDValue Flag; 6835 SmallVector<SDValue, 4> RetOps(1, Chain); 6836 6837 // Copy the result values into the output registers. 6838 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 6839 CCValAssign &VA = RVLocs[i]; 6840 assert(VA.isRegLoc() && "Can only return in registers!"); 6841 6842 SDValue Arg = OutVals[RealResIdx]; 6843 6844 switch (VA.getLocInfo()) { 6845 default: llvm_unreachable("Unknown loc info!"); 6846 case CCValAssign::Full: break; 6847 case CCValAssign::AExt: 6848 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 6849 break; 6850 case CCValAssign::ZExt: 6851 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 6852 break; 6853 case CCValAssign::SExt: 6854 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 6855 break; 6856 } 6857 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 6858 bool isLittleEndian = Subtarget.isLittleEndian(); 6859 // Legalize ret f64 -> ret 2 x i32. 6860 SDValue SVal = 6861 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6862 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 6863 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6864 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6865 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 6866 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 6867 Flag = Chain.getValue(1); 6868 VA = RVLocs[++i]; // skip ahead to next loc 6869 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 6870 } else 6871 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 6872 Flag = Chain.getValue(1); 6873 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 6874 } 6875 6876 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 6877 const MCPhysReg *I = 6878 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 6879 if (I) { 6880 for (; *I; ++I) { 6881 6882 if (PPC::G8RCRegClass.contains(*I)) 6883 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 6884 else if (PPC::F8RCRegClass.contains(*I)) 6885 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 6886 else if (PPC::CRRCRegClass.contains(*I)) 6887 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 6888 else if (PPC::VRRCRegClass.contains(*I)) 6889 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 6890 else 6891 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 6892 } 6893 } 6894 6895 RetOps[0] = Chain; // Update chain. 6896 6897 // Add the flag if we have it. 6898 if (Flag.getNode()) 6899 RetOps.push_back(Flag); 6900 6901 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 6902 } 6903 6904 SDValue 6905 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 6906 SelectionDAG &DAG) const { 6907 SDLoc dl(Op); 6908 6909 // Get the correct type for integers. 6910 EVT IntVT = Op.getValueType(); 6911 6912 // Get the inputs. 6913 SDValue Chain = Op.getOperand(0); 6914 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 6915 // Build a DYNAREAOFFSET node. 6916 SDValue Ops[2] = {Chain, FPSIdx}; 6917 SDVTList VTs = DAG.getVTList(IntVT); 6918 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 6919 } 6920 6921 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 6922 SelectionDAG &DAG) const { 6923 // When we pop the dynamic allocation we need to restore the SP link. 6924 SDLoc dl(Op); 6925 6926 // Get the correct type for pointers. 6927 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6928 6929 // Construct the stack pointer operand. 6930 bool isPPC64 = Subtarget.isPPC64(); 6931 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 6932 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 6933 6934 // Get the operands for the STACKRESTORE. 6935 SDValue Chain = Op.getOperand(0); 6936 SDValue SaveSP = Op.getOperand(1); 6937 6938 // Load the old link SP. 6939 SDValue LoadLinkSP = 6940 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 6941 6942 // Restore the stack pointer. 6943 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 6944 6945 // Store the old link SP. 6946 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 6947 } 6948 6949 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 6950 MachineFunction &MF = DAG.getMachineFunction(); 6951 bool isPPC64 = Subtarget.isPPC64(); 6952 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6953 6954 // Get current frame pointer save index. The users of this index will be 6955 // primarily DYNALLOC instructions. 6956 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6957 int RASI = FI->getReturnAddrSaveIndex(); 6958 6959 // If the frame pointer save index hasn't been defined yet. 6960 if (!RASI) { 6961 // Find out what the fix offset of the frame pointer save area. 6962 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 6963 // Allocate the frame index for frame pointer save area. 6964 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 6965 // Save the result. 6966 FI->setReturnAddrSaveIndex(RASI); 6967 } 6968 return DAG.getFrameIndex(RASI, PtrVT); 6969 } 6970 6971 SDValue 6972 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 6973 MachineFunction &MF = DAG.getMachineFunction(); 6974 bool isPPC64 = Subtarget.isPPC64(); 6975 EVT PtrVT = getPointerTy(MF.getDataLayout()); 6976 6977 // Get current frame pointer save index. The users of this index will be 6978 // primarily DYNALLOC instructions. 6979 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 6980 int FPSI = FI->getFramePointerSaveIndex(); 6981 6982 // If the frame pointer save index hasn't been defined yet. 6983 if (!FPSI) { 6984 // Find out what the fix offset of the frame pointer save area. 6985 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 6986 // Allocate the frame index for frame pointer save area. 6987 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 6988 // Save the result. 6989 FI->setFramePointerSaveIndex(FPSI); 6990 } 6991 return DAG.getFrameIndex(FPSI, PtrVT); 6992 } 6993 6994 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 6995 SelectionDAG &DAG) const { 6996 // Get the inputs. 6997 SDValue Chain = Op.getOperand(0); 6998 SDValue Size = Op.getOperand(1); 6999 SDLoc dl(Op); 7000 7001 // Get the correct type for pointers. 7002 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7003 // Negate the size. 7004 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7005 DAG.getConstant(0, dl, PtrVT), Size); 7006 // Construct a node for the frame pointer save index. 7007 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7008 // Build a DYNALLOC node. 7009 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7010 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7011 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7012 } 7013 7014 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7015 SelectionDAG &DAG) const { 7016 MachineFunction &MF = DAG.getMachineFunction(); 7017 7018 bool isPPC64 = Subtarget.isPPC64(); 7019 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7020 7021 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7022 return DAG.getFrameIndex(FI, PtrVT); 7023 } 7024 7025 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7026 SelectionDAG &DAG) const { 7027 SDLoc DL(Op); 7028 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7029 DAG.getVTList(MVT::i32, MVT::Other), 7030 Op.getOperand(0), Op.getOperand(1)); 7031 } 7032 7033 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7034 SelectionDAG &DAG) const { 7035 SDLoc DL(Op); 7036 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7037 Op.getOperand(0), Op.getOperand(1)); 7038 } 7039 7040 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7041 if (Op.getValueType().isVector()) 7042 return LowerVectorLoad(Op, DAG); 7043 7044 assert(Op.getValueType() == MVT::i1 && 7045 "Custom lowering only for i1 loads"); 7046 7047 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7048 7049 SDLoc dl(Op); 7050 LoadSDNode *LD = cast<LoadSDNode>(Op); 7051 7052 SDValue Chain = LD->getChain(); 7053 SDValue BasePtr = LD->getBasePtr(); 7054 MachineMemOperand *MMO = LD->getMemOperand(); 7055 7056 SDValue NewLD = 7057 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7058 BasePtr, MVT::i8, MMO); 7059 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7060 7061 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7062 return DAG.getMergeValues(Ops, dl); 7063 } 7064 7065 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7066 if (Op.getOperand(1).getValueType().isVector()) 7067 return LowerVectorStore(Op, DAG); 7068 7069 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7070 "Custom lowering only for i1 stores"); 7071 7072 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7073 7074 SDLoc dl(Op); 7075 StoreSDNode *ST = cast<StoreSDNode>(Op); 7076 7077 SDValue Chain = ST->getChain(); 7078 SDValue BasePtr = ST->getBasePtr(); 7079 SDValue Value = ST->getValue(); 7080 MachineMemOperand *MMO = ST->getMemOperand(); 7081 7082 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7083 Value); 7084 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7085 } 7086 7087 // FIXME: Remove this once the ANDI glue bug is fixed: 7088 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7089 assert(Op.getValueType() == MVT::i1 && 7090 "Custom lowering only for i1 results"); 7091 7092 SDLoc DL(Op); 7093 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, 7094 Op.getOperand(0)); 7095 } 7096 7097 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7098 SelectionDAG &DAG) const { 7099 7100 // Implements a vector truncate that fits in a vector register as a shuffle. 7101 // We want to legalize vector truncates down to where the source fits in 7102 // a vector register (and target is therefore smaller than vector register 7103 // size). At that point legalization will try to custom lower the sub-legal 7104 // result and get here - where we can contain the truncate as a single target 7105 // operation. 7106 7107 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7108 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7109 // 7110 // We will implement it for big-endian ordering as this (where x denotes 7111 // undefined): 7112 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7113 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7114 // 7115 // The same operation in little-endian ordering will be: 7116 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7117 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7118 7119 assert(Op.getValueType().isVector() && "Vector type expected."); 7120 7121 SDLoc DL(Op); 7122 SDValue N1 = Op.getOperand(0); 7123 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7124 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7125 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7126 7127 EVT TrgVT = Op.getValueType(); 7128 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7129 EVT EltVT = TrgVT.getVectorElementType(); 7130 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7131 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7132 7133 // First list the elements we want to keep. 7134 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7135 SmallVector<int, 16> ShuffV; 7136 if (Subtarget.isLittleEndian()) 7137 for (unsigned i = 0; i < TrgNumElts; ++i) 7138 ShuffV.push_back(i * SizeMult); 7139 else 7140 for (unsigned i = 1; i <= TrgNumElts; ++i) 7141 ShuffV.push_back(i * SizeMult - 1); 7142 7143 // Populate the remaining elements with undefs. 7144 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7145 // ShuffV.push_back(i + WideNumElts); 7146 ShuffV.push_back(WideNumElts + 1); 7147 7148 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7149 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7150 } 7151 7152 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7153 /// possible. 7154 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7155 // Not FP? Not a fsel. 7156 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7157 !Op.getOperand(2).getValueType().isFloatingPoint()) 7158 return Op; 7159 7160 // We might be able to do better than this under some circumstances, but in 7161 // general, fsel-based lowering of select is a finite-math-only optimization. 7162 // For more information, see section F.3 of the 2.06 ISA specification. 7163 if (!DAG.getTarget().Options.NoInfsFPMath || 7164 !DAG.getTarget().Options.NoNaNsFPMath) 7165 return Op; 7166 // TODO: Propagate flags from the select rather than global settings. 7167 SDNodeFlags Flags; 7168 Flags.setNoInfs(true); 7169 Flags.setNoNaNs(true); 7170 7171 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7172 7173 EVT ResVT = Op.getValueType(); 7174 EVT CmpVT = Op.getOperand(0).getValueType(); 7175 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7176 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7177 SDLoc dl(Op); 7178 7179 // If the RHS of the comparison is a 0.0, we don't need to do the 7180 // subtraction at all. 7181 SDValue Sel1; 7182 if (isFloatingPointZero(RHS)) 7183 switch (CC) { 7184 default: break; // SETUO etc aren't handled by fsel. 7185 case ISD::SETNE: 7186 std::swap(TV, FV); 7187 LLVM_FALLTHROUGH; 7188 case ISD::SETEQ: 7189 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7190 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7191 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7192 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7193 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7194 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7195 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7196 case ISD::SETULT: 7197 case ISD::SETLT: 7198 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7199 LLVM_FALLTHROUGH; 7200 case ISD::SETOGE: 7201 case ISD::SETGE: 7202 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7203 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7204 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7205 case ISD::SETUGT: 7206 case ISD::SETGT: 7207 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7208 LLVM_FALLTHROUGH; 7209 case ISD::SETOLE: 7210 case ISD::SETLE: 7211 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7212 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7213 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7214 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7215 } 7216 7217 SDValue Cmp; 7218 switch (CC) { 7219 default: break; // SETUO etc aren't handled by fsel. 7220 case ISD::SETNE: 7221 std::swap(TV, FV); 7222 LLVM_FALLTHROUGH; 7223 case ISD::SETEQ: 7224 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7225 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7226 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7227 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7228 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7229 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7230 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7231 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7232 case ISD::SETULT: 7233 case ISD::SETLT: 7234 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7235 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7236 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7237 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7238 case ISD::SETOGE: 7239 case ISD::SETGE: 7240 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7241 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7242 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7243 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7244 case ISD::SETUGT: 7245 case ISD::SETGT: 7246 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7247 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7248 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7249 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7250 case ISD::SETOLE: 7251 case ISD::SETLE: 7252 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7253 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7254 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7255 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7256 } 7257 return Op; 7258 } 7259 7260 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7261 SelectionDAG &DAG, 7262 const SDLoc &dl) const { 7263 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7264 SDValue Src = Op.getOperand(0); 7265 if (Src.getValueType() == MVT::f32) 7266 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7267 7268 SDValue Tmp; 7269 switch (Op.getSimpleValueType().SimpleTy) { 7270 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7271 case MVT::i32: 7272 Tmp = DAG.getNode( 7273 Op.getOpcode() == ISD::FP_TO_SINT 7274 ? PPCISD::FCTIWZ 7275 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7276 dl, MVT::f64, Src); 7277 break; 7278 case MVT::i64: 7279 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7280 "i64 FP_TO_UINT is supported only with FPCVT"); 7281 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7282 PPCISD::FCTIDUZ, 7283 dl, MVT::f64, Src); 7284 break; 7285 } 7286 7287 // Convert the FP value to an int value through memory. 7288 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7289 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7290 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7291 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7292 MachinePointerInfo MPI = 7293 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7294 7295 // Emit a store to the stack slot. 7296 SDValue Chain; 7297 if (i32Stack) { 7298 MachineFunction &MF = DAG.getMachineFunction(); 7299 MachineMemOperand *MMO = 7300 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7301 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7302 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7303 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7304 } else 7305 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7306 7307 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7308 // add in a bias on big endian. 7309 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7310 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7311 DAG.getConstant(4, dl, FIPtr.getValueType())); 7312 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7313 } 7314 7315 RLI.Chain = Chain; 7316 RLI.Ptr = FIPtr; 7317 RLI.MPI = MPI; 7318 } 7319 7320 /// Custom lowers floating point to integer conversions to use 7321 /// the direct move instructions available in ISA 2.07 to avoid the 7322 /// need for load/store combinations. 7323 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7324 SelectionDAG &DAG, 7325 const SDLoc &dl) const { 7326 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7327 SDValue Src = Op.getOperand(0); 7328 7329 if (Src.getValueType() == MVT::f32) 7330 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7331 7332 SDValue Tmp; 7333 switch (Op.getSimpleValueType().SimpleTy) { 7334 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7335 case MVT::i32: 7336 Tmp = DAG.getNode( 7337 Op.getOpcode() == ISD::FP_TO_SINT 7338 ? PPCISD::FCTIWZ 7339 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7340 dl, MVT::f64, Src); 7341 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7342 break; 7343 case MVT::i64: 7344 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7345 "i64 FP_TO_UINT is supported only with FPCVT"); 7346 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7347 PPCISD::FCTIDUZ, 7348 dl, MVT::f64, Src); 7349 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7350 break; 7351 } 7352 return Tmp; 7353 } 7354 7355 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7356 const SDLoc &dl) const { 7357 7358 // FP to INT conversions are legal for f128. 7359 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7360 return Op; 7361 7362 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7363 // PPC (the libcall is not available). 7364 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7365 if (Op.getValueType() == MVT::i32) { 7366 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7367 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7368 MVT::f64, Op.getOperand(0), 7369 DAG.getIntPtrConstant(0, dl)); 7370 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7371 MVT::f64, Op.getOperand(0), 7372 DAG.getIntPtrConstant(1, dl)); 7373 7374 // Add the two halves of the long double in round-to-zero mode. 7375 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7376 7377 // Now use a smaller FP_TO_SINT. 7378 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7379 } 7380 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7381 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7382 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7383 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7384 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7385 // FIXME: generated code sucks. 7386 // TODO: Are there fast-math-flags to propagate to this FSUB? 7387 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7388 Op.getOperand(0), Tmp); 7389 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7390 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7391 DAG.getConstant(0x80000000, dl, MVT::i32)); 7392 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7393 Op.getOperand(0)); 7394 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7395 ISD::SETGE); 7396 } 7397 } 7398 7399 return SDValue(); 7400 } 7401 7402 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7403 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7404 7405 ReuseLoadInfo RLI; 7406 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7407 7408 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7409 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7410 } 7411 7412 // We're trying to insert a regular store, S, and then a load, L. If the 7413 // incoming value, O, is a load, we might just be able to have our load use the 7414 // address used by O. However, we don't know if anything else will store to 7415 // that address before we can load from it. To prevent this situation, we need 7416 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7417 // the same chain operand as O, we create a token factor from the chain results 7418 // of O and L, and we replace all uses of O's chain result with that token 7419 // factor (see spliceIntoChain below for this last part). 7420 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7421 ReuseLoadInfo &RLI, 7422 SelectionDAG &DAG, 7423 ISD::LoadExtType ET) const { 7424 SDLoc dl(Op); 7425 if (ET == ISD::NON_EXTLOAD && 7426 (Op.getOpcode() == ISD::FP_TO_UINT || 7427 Op.getOpcode() == ISD::FP_TO_SINT) && 7428 isOperationLegalOrCustom(Op.getOpcode(), 7429 Op.getOperand(0).getValueType())) { 7430 7431 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7432 return true; 7433 } 7434 7435 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7436 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7437 LD->isNonTemporal()) 7438 return false; 7439 if (LD->getMemoryVT() != MemVT) 7440 return false; 7441 7442 RLI.Ptr = LD->getBasePtr(); 7443 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7444 assert(LD->getAddressingMode() == ISD::PRE_INC && 7445 "Non-pre-inc AM on PPC?"); 7446 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7447 LD->getOffset()); 7448 } 7449 7450 RLI.Chain = LD->getChain(); 7451 RLI.MPI = LD->getPointerInfo(); 7452 RLI.IsDereferenceable = LD->isDereferenceable(); 7453 RLI.IsInvariant = LD->isInvariant(); 7454 RLI.Alignment = LD->getAlignment(); 7455 RLI.AAInfo = LD->getAAInfo(); 7456 RLI.Ranges = LD->getRanges(); 7457 7458 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7459 return true; 7460 } 7461 7462 // Given the head of the old chain, ResChain, insert a token factor containing 7463 // it and NewResChain, and make users of ResChain now be users of that token 7464 // factor. 7465 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7466 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7467 SDValue NewResChain, 7468 SelectionDAG &DAG) const { 7469 if (!ResChain) 7470 return; 7471 7472 SDLoc dl(NewResChain); 7473 7474 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7475 NewResChain, DAG.getUNDEF(MVT::Other)); 7476 assert(TF.getNode() != NewResChain.getNode() && 7477 "A new TF really is required here"); 7478 7479 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7480 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7481 } 7482 7483 /// Analyze profitability of direct move 7484 /// prefer float load to int load plus direct move 7485 /// when there is no integer use of int load 7486 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7487 SDNode *Origin = Op.getOperand(0).getNode(); 7488 if (Origin->getOpcode() != ISD::LOAD) 7489 return true; 7490 7491 // If there is no LXSIBZX/LXSIHZX, like Power8, 7492 // prefer direct move if the memory size is 1 or 2 bytes. 7493 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7494 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7495 return true; 7496 7497 for (SDNode::use_iterator UI = Origin->use_begin(), 7498 UE = Origin->use_end(); 7499 UI != UE; ++UI) { 7500 7501 // Only look at the users of the loaded value. 7502 if (UI.getUse().get().getResNo() != 0) 7503 continue; 7504 7505 if (UI->getOpcode() != ISD::SINT_TO_FP && 7506 UI->getOpcode() != ISD::UINT_TO_FP) 7507 return true; 7508 } 7509 7510 return false; 7511 } 7512 7513 /// Custom lowers integer to floating point conversions to use 7514 /// the direct move instructions available in ISA 2.07 to avoid the 7515 /// need for load/store combinations. 7516 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7517 SelectionDAG &DAG, 7518 const SDLoc &dl) const { 7519 assert((Op.getValueType() == MVT::f32 || 7520 Op.getValueType() == MVT::f64) && 7521 "Invalid floating point type as target of conversion"); 7522 assert(Subtarget.hasFPCVT() && 7523 "Int to FP conversions with direct moves require FPCVT"); 7524 SDValue FP; 7525 SDValue Src = Op.getOperand(0); 7526 bool SinglePrec = Op.getValueType() == MVT::f32; 7527 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7528 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7529 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7530 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7531 7532 if (WordInt) { 7533 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7534 dl, MVT::f64, Src); 7535 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7536 } 7537 else { 7538 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7539 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7540 } 7541 7542 return FP; 7543 } 7544 7545 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7546 7547 EVT VecVT = Vec.getValueType(); 7548 assert(VecVT.isVector() && "Expected a vector type."); 7549 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7550 7551 EVT EltVT = VecVT.getVectorElementType(); 7552 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7553 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7554 7555 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7556 SmallVector<SDValue, 16> Ops(NumConcat); 7557 Ops[0] = Vec; 7558 SDValue UndefVec = DAG.getUNDEF(VecVT); 7559 for (unsigned i = 1; i < NumConcat; ++i) 7560 Ops[i] = UndefVec; 7561 7562 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7563 } 7564 7565 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7566 const SDLoc &dl) const { 7567 7568 unsigned Opc = Op.getOpcode(); 7569 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7570 "Unexpected conversion type"); 7571 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7572 "Supports conversions to v2f64/v4f32 only."); 7573 7574 bool SignedConv = Opc == ISD::SINT_TO_FP; 7575 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7576 7577 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7578 EVT WideVT = Wide.getValueType(); 7579 unsigned WideNumElts = WideVT.getVectorNumElements(); 7580 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7581 7582 SmallVector<int, 16> ShuffV; 7583 for (unsigned i = 0; i < WideNumElts; ++i) 7584 ShuffV.push_back(i + WideNumElts); 7585 7586 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7587 int SaveElts = FourEltRes ? 4 : 2; 7588 if (Subtarget.isLittleEndian()) 7589 for (int i = 0; i < SaveElts; i++) 7590 ShuffV[i * Stride] = i; 7591 else 7592 for (int i = 1; i <= SaveElts; i++) 7593 ShuffV[i * Stride - 1] = i - 1; 7594 7595 SDValue ShuffleSrc2 = 7596 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 7597 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 7598 unsigned ExtendOp = 7599 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 7600 7601 SDValue Extend; 7602 if (!Subtarget.hasP9Altivec() && SignedConv) { 7603 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 7604 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 7605 DAG.getValueType(Op.getOperand(0).getValueType())); 7606 } else 7607 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 7608 7609 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 7610 } 7611 7612 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 7613 SelectionDAG &DAG) const { 7614 SDLoc dl(Op); 7615 7616 EVT InVT = Op.getOperand(0).getValueType(); 7617 EVT OutVT = Op.getValueType(); 7618 if (OutVT.isVector() && OutVT.isFloatingPoint() && 7619 isOperationCustom(Op.getOpcode(), InVT)) 7620 return LowerINT_TO_FPVector(Op, DAG, dl); 7621 7622 // Conversions to f128 are legal. 7623 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 7624 return Op; 7625 7626 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 7627 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 7628 return SDValue(); 7629 7630 SDValue Value = Op.getOperand(0); 7631 // The values are now known to be -1 (false) or 1 (true). To convert this 7632 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 7633 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 7634 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 7635 7636 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 7637 7638 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 7639 7640 if (Op.getValueType() != MVT::v4f64) 7641 Value = DAG.getNode(ISD::FP_ROUND, dl, 7642 Op.getValueType(), Value, 7643 DAG.getIntPtrConstant(1, dl)); 7644 return Value; 7645 } 7646 7647 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 7648 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 7649 return SDValue(); 7650 7651 if (Op.getOperand(0).getValueType() == MVT::i1) 7652 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 7653 DAG.getConstantFP(1.0, dl, Op.getValueType()), 7654 DAG.getConstantFP(0.0, dl, Op.getValueType())); 7655 7656 // If we have direct moves, we can do all the conversion, skip the store/load 7657 // however, without FPCVT we can't do most conversions. 7658 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 7659 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 7660 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 7661 7662 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 7663 "UINT_TO_FP is supported only with FPCVT"); 7664 7665 // If we have FCFIDS, then use it when converting to single-precision. 7666 // Otherwise, convert to double-precision and then round. 7667 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7668 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 7669 : PPCISD::FCFIDS) 7670 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 7671 : PPCISD::FCFID); 7672 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 7673 ? MVT::f32 7674 : MVT::f64; 7675 7676 if (Op.getOperand(0).getValueType() == MVT::i64) { 7677 SDValue SINT = Op.getOperand(0); 7678 // When converting to single-precision, we actually need to convert 7679 // to double-precision first and then round to single-precision. 7680 // To avoid double-rounding effects during that operation, we have 7681 // to prepare the input operand. Bits that might be truncated when 7682 // converting to double-precision are replaced by a bit that won't 7683 // be lost at this stage, but is below the single-precision rounding 7684 // position. 7685 // 7686 // However, if -enable-unsafe-fp-math is in effect, accept double 7687 // rounding to avoid the extra overhead. 7688 if (Op.getValueType() == MVT::f32 && 7689 !Subtarget.hasFPCVT() && 7690 !DAG.getTarget().Options.UnsafeFPMath) { 7691 7692 // Twiddle input to make sure the low 11 bits are zero. (If this 7693 // is the case, we are guaranteed the value will fit into the 53 bit 7694 // mantissa of an IEEE double-precision value without rounding.) 7695 // If any of those low 11 bits were not zero originally, make sure 7696 // bit 12 (value 2048) is set instead, so that the final rounding 7697 // to single-precision gets the correct result. 7698 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7699 SINT, DAG.getConstant(2047, dl, MVT::i64)); 7700 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 7701 Round, DAG.getConstant(2047, dl, MVT::i64)); 7702 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 7703 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 7704 Round, DAG.getConstant(-2048, dl, MVT::i64)); 7705 7706 // However, we cannot use that value unconditionally: if the magnitude 7707 // of the input value is small, the bit-twiddling we did above might 7708 // end up visibly changing the output. Fortunately, in that case, we 7709 // don't need to twiddle bits since the original input will convert 7710 // exactly to double-precision floating-point already. Therefore, 7711 // construct a conditional to use the original value if the top 11 7712 // bits are all sign-bit copies, and use the rounded value computed 7713 // above otherwise. 7714 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 7715 SINT, DAG.getConstant(53, dl, MVT::i32)); 7716 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 7717 Cond, DAG.getConstant(1, dl, MVT::i64)); 7718 Cond = DAG.getSetCC(dl, MVT::i32, 7719 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 7720 7721 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 7722 } 7723 7724 ReuseLoadInfo RLI; 7725 SDValue Bits; 7726 7727 MachineFunction &MF = DAG.getMachineFunction(); 7728 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 7729 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7730 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7731 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7732 } else if (Subtarget.hasLFIWAX() && 7733 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 7734 MachineMemOperand *MMO = 7735 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7736 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7737 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7738 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 7739 DAG.getVTList(MVT::f64, MVT::Other), 7740 Ops, MVT::i32, MMO); 7741 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7742 } else if (Subtarget.hasFPCVT() && 7743 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 7744 MachineMemOperand *MMO = 7745 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7746 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7747 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7748 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 7749 DAG.getVTList(MVT::f64, MVT::Other), 7750 Ops, MVT::i32, MMO); 7751 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 7752 } else if (((Subtarget.hasLFIWAX() && 7753 SINT.getOpcode() == ISD::SIGN_EXTEND) || 7754 (Subtarget.hasFPCVT() && 7755 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 7756 SINT.getOperand(0).getValueType() == MVT::i32) { 7757 MachineFrameInfo &MFI = MF.getFrameInfo(); 7758 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7759 7760 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7761 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7762 7763 SDValue Store = 7764 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 7765 MachinePointerInfo::getFixedStack( 7766 DAG.getMachineFunction(), FrameIdx)); 7767 7768 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7769 "Expected an i32 store"); 7770 7771 RLI.Ptr = FIdx; 7772 RLI.Chain = Store; 7773 RLI.MPI = 7774 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7775 RLI.Alignment = 4; 7776 7777 MachineMemOperand *MMO = 7778 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7779 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7780 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7781 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 7782 PPCISD::LFIWZX : PPCISD::LFIWAX, 7783 dl, DAG.getVTList(MVT::f64, MVT::Other), 7784 Ops, MVT::i32, MMO); 7785 } else 7786 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 7787 7788 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 7789 7790 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7791 FP = DAG.getNode(ISD::FP_ROUND, dl, 7792 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 7793 return FP; 7794 } 7795 7796 assert(Op.getOperand(0).getValueType() == MVT::i32 && 7797 "Unhandled INT_TO_FP type in custom expander!"); 7798 // Since we only generate this in 64-bit mode, we can take advantage of 7799 // 64-bit registers. In particular, sign extend the input value into the 7800 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 7801 // then lfd it and fcfid it. 7802 MachineFunction &MF = DAG.getMachineFunction(); 7803 MachineFrameInfo &MFI = MF.getFrameInfo(); 7804 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7805 7806 SDValue Ld; 7807 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 7808 ReuseLoadInfo RLI; 7809 bool ReusingLoad; 7810 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 7811 DAG))) { 7812 int FrameIdx = MFI.CreateStackObject(4, 4, false); 7813 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7814 7815 SDValue Store = 7816 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 7817 MachinePointerInfo::getFixedStack( 7818 DAG.getMachineFunction(), FrameIdx)); 7819 7820 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 7821 "Expected an i32 store"); 7822 7823 RLI.Ptr = FIdx; 7824 RLI.Chain = Store; 7825 RLI.MPI = 7826 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 7827 RLI.Alignment = 4; 7828 } 7829 7830 MachineMemOperand *MMO = 7831 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 7832 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 7833 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 7834 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 7835 PPCISD::LFIWZX : PPCISD::LFIWAX, 7836 dl, DAG.getVTList(MVT::f64, MVT::Other), 7837 Ops, MVT::i32, MMO); 7838 if (ReusingLoad) 7839 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 7840 } else { 7841 assert(Subtarget.isPPC64() && 7842 "i32->FP without LFIWAX supported only on PPC64"); 7843 7844 int FrameIdx = MFI.CreateStackObject(8, 8, false); 7845 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 7846 7847 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 7848 Op.getOperand(0)); 7849 7850 // STD the extended value into the stack slot. 7851 SDValue Store = DAG.getStore( 7852 DAG.getEntryNode(), dl, Ext64, FIdx, 7853 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7854 7855 // Load the value as a double. 7856 Ld = DAG.getLoad( 7857 MVT::f64, dl, Store, FIdx, 7858 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 7859 } 7860 7861 // FCFID it and return it. 7862 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 7863 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 7864 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 7865 DAG.getIntPtrConstant(0, dl)); 7866 return FP; 7867 } 7868 7869 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 7870 SelectionDAG &DAG) const { 7871 SDLoc dl(Op); 7872 /* 7873 The rounding mode is in bits 30:31 of FPSR, and has the following 7874 settings: 7875 00 Round to nearest 7876 01 Round to 0 7877 10 Round to +inf 7878 11 Round to -inf 7879 7880 FLT_ROUNDS, on the other hand, expects the following: 7881 -1 Undefined 7882 0 Round to 0 7883 1 Round to nearest 7884 2 Round to +inf 7885 3 Round to -inf 7886 7887 To perform the conversion, we do: 7888 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 7889 */ 7890 7891 MachineFunction &MF = DAG.getMachineFunction(); 7892 EVT VT = Op.getValueType(); 7893 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7894 7895 // Save FP Control Word to register 7896 EVT NodeTys[] = { 7897 MVT::f64, // return register 7898 MVT::Glue // unused in this context 7899 }; 7900 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 7901 7902 // Save FP register to stack slot 7903 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 7904 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 7905 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 7906 MachinePointerInfo()); 7907 7908 // Load FP Control Word from low 32 bits of stack slot. 7909 SDValue Four = DAG.getConstant(4, dl, PtrVT); 7910 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 7911 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 7912 7913 // Transform as necessary 7914 SDValue CWD1 = 7915 DAG.getNode(ISD::AND, dl, MVT::i32, 7916 CWD, DAG.getConstant(3, dl, MVT::i32)); 7917 SDValue CWD2 = 7918 DAG.getNode(ISD::SRL, dl, MVT::i32, 7919 DAG.getNode(ISD::AND, dl, MVT::i32, 7920 DAG.getNode(ISD::XOR, dl, MVT::i32, 7921 CWD, DAG.getConstant(3, dl, MVT::i32)), 7922 DAG.getConstant(3, dl, MVT::i32)), 7923 DAG.getConstant(1, dl, MVT::i32)); 7924 7925 SDValue RetVal = 7926 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 7927 7928 return DAG.getNode((VT.getSizeInBits() < 16 ? 7929 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 7930 } 7931 7932 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7933 EVT VT = Op.getValueType(); 7934 unsigned BitWidth = VT.getSizeInBits(); 7935 SDLoc dl(Op); 7936 assert(Op.getNumOperands() == 3 && 7937 VT == Op.getOperand(1).getValueType() && 7938 "Unexpected SHL!"); 7939 7940 // Expand into a bunch of logical ops. Note that these ops 7941 // depend on the PPC behavior for oversized shift amounts. 7942 SDValue Lo = Op.getOperand(0); 7943 SDValue Hi = Op.getOperand(1); 7944 SDValue Amt = Op.getOperand(2); 7945 EVT AmtVT = Amt.getValueType(); 7946 7947 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7948 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7949 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 7950 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 7951 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 7952 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7953 DAG.getConstant(-BitWidth, dl, AmtVT)); 7954 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 7955 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7956 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 7957 SDValue OutOps[] = { OutLo, OutHi }; 7958 return DAG.getMergeValues(OutOps, dl); 7959 } 7960 7961 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 7962 EVT VT = Op.getValueType(); 7963 SDLoc dl(Op); 7964 unsigned BitWidth = VT.getSizeInBits(); 7965 assert(Op.getNumOperands() == 3 && 7966 VT == Op.getOperand(1).getValueType() && 7967 "Unexpected SRL!"); 7968 7969 // Expand into a bunch of logical ops. Note that these ops 7970 // depend on the PPC behavior for oversized shift amounts. 7971 SDValue Lo = Op.getOperand(0); 7972 SDValue Hi = Op.getOperand(1); 7973 SDValue Amt = Op.getOperand(2); 7974 EVT AmtVT = Amt.getValueType(); 7975 7976 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 7977 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 7978 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 7979 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 7980 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 7981 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 7982 DAG.getConstant(-BitWidth, dl, AmtVT)); 7983 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 7984 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 7985 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 7986 SDValue OutOps[] = { OutLo, OutHi }; 7987 return DAG.getMergeValues(OutOps, dl); 7988 } 7989 7990 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 7991 SDLoc dl(Op); 7992 EVT VT = Op.getValueType(); 7993 unsigned BitWidth = VT.getSizeInBits(); 7994 assert(Op.getNumOperands() == 3 && 7995 VT == Op.getOperand(1).getValueType() && 7996 "Unexpected SRA!"); 7997 7998 // Expand into a bunch of logical ops, followed by a select_cc. 7999 SDValue Lo = Op.getOperand(0); 8000 SDValue Hi = Op.getOperand(1); 8001 SDValue Amt = Op.getOperand(2); 8002 EVT AmtVT = Amt.getValueType(); 8003 8004 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8005 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8006 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8007 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8008 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8009 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8010 DAG.getConstant(-BitWidth, dl, AmtVT)); 8011 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8012 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8013 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8014 Tmp4, Tmp6, ISD::SETLE); 8015 SDValue OutOps[] = { OutLo, OutHi }; 8016 return DAG.getMergeValues(OutOps, dl); 8017 } 8018 8019 //===----------------------------------------------------------------------===// 8020 // Vector related lowering. 8021 // 8022 8023 /// BuildSplatI - Build a canonical splati of Val with an element size of 8024 /// SplatSize. Cast the result to VT. 8025 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8026 SelectionDAG &DAG, const SDLoc &dl) { 8027 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); 8028 8029 static const MVT VTys[] = { // canonical VT to use for each size. 8030 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8031 }; 8032 8033 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8034 8035 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8036 if (Val == -1) 8037 SplatSize = 1; 8038 8039 EVT CanonicalVT = VTys[SplatSize-1]; 8040 8041 // Build a canonical splat for this value. 8042 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8043 } 8044 8045 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8046 /// specified intrinsic ID. 8047 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8048 const SDLoc &dl, EVT DestVT = MVT::Other) { 8049 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8050 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8051 DAG.getConstant(IID, dl, MVT::i32), Op); 8052 } 8053 8054 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8055 /// specified intrinsic ID. 8056 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8057 SelectionDAG &DAG, const SDLoc &dl, 8058 EVT DestVT = MVT::Other) { 8059 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8060 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8061 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8062 } 8063 8064 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8065 /// specified intrinsic ID. 8066 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8067 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8068 EVT DestVT = MVT::Other) { 8069 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8071 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8072 } 8073 8074 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8075 /// amount. The result has the specified value type. 8076 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8077 SelectionDAG &DAG, const SDLoc &dl) { 8078 // Force LHS/RHS to be the right type. 8079 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8080 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8081 8082 int Ops[16]; 8083 for (unsigned i = 0; i != 16; ++i) 8084 Ops[i] = i + Amt; 8085 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8086 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8087 } 8088 8089 /// Do we have an efficient pattern in a .td file for this node? 8090 /// 8091 /// \param V - pointer to the BuildVectorSDNode being matched 8092 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8093 /// 8094 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8095 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8096 /// the opposite is true (expansion is beneficial) are: 8097 /// - The node builds a vector out of integers that are not 32 or 64-bits 8098 /// - The node builds a vector out of constants 8099 /// - The node is a "load-and-splat" 8100 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8101 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8102 bool HasDirectMove, 8103 bool HasP8Vector) { 8104 EVT VecVT = V->getValueType(0); 8105 bool RightType = VecVT == MVT::v2f64 || 8106 (HasP8Vector && VecVT == MVT::v4f32) || 8107 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8108 if (!RightType) 8109 return false; 8110 8111 bool IsSplat = true; 8112 bool IsLoad = false; 8113 SDValue Op0 = V->getOperand(0); 8114 8115 // This function is called in a block that confirms the node is not a constant 8116 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8117 // different constants. 8118 if (V->isConstant()) 8119 return false; 8120 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8121 if (V->getOperand(i).isUndef()) 8122 return false; 8123 // We want to expand nodes that represent load-and-splat even if the 8124 // loaded value is a floating point truncation or conversion to int. 8125 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8126 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8127 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8128 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8129 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8130 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8131 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8132 IsLoad = true; 8133 // If the operands are different or the input is not a load and has more 8134 // uses than just this BV node, then it isn't a splat. 8135 if (V->getOperand(i) != Op0 || 8136 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8137 IsSplat = false; 8138 } 8139 return !(IsSplat && IsLoad); 8140 } 8141 8142 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8143 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8144 8145 SDLoc dl(Op); 8146 SDValue Op0 = Op->getOperand(0); 8147 8148 if (!EnableQuadPrecision || 8149 (Op.getValueType() != MVT::f128 ) || 8150 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8151 (Op0.getOperand(0).getValueType() != MVT::i64) || 8152 (Op0.getOperand(1).getValueType() != MVT::i64)) 8153 return SDValue(); 8154 8155 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8156 Op0.getOperand(1)); 8157 } 8158 8159 // If this is a case we can't handle, return null and let the default 8160 // expansion code take care of it. If we CAN select this case, and if it 8161 // selects to a single instruction, return Op. Otherwise, if we can codegen 8162 // this case more efficiently than a constant pool load, lower it to the 8163 // sequence of ops that should be used. 8164 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8165 SelectionDAG &DAG) const { 8166 SDLoc dl(Op); 8167 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8168 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8169 8170 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8171 // We first build an i32 vector, load it into a QPX register, 8172 // then convert it to a floating-point vector and compare it 8173 // to a zero vector to get the boolean result. 8174 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8175 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8176 MachinePointerInfo PtrInfo = 8177 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8178 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8179 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8180 8181 assert(BVN->getNumOperands() == 4 && 8182 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8183 8184 bool IsConst = true; 8185 for (unsigned i = 0; i < 4; ++i) { 8186 if (BVN->getOperand(i).isUndef()) continue; 8187 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8188 IsConst = false; 8189 break; 8190 } 8191 } 8192 8193 if (IsConst) { 8194 Constant *One = 8195 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8196 Constant *NegOne = 8197 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8198 8199 Constant *CV[4]; 8200 for (unsigned i = 0; i < 4; ++i) { 8201 if (BVN->getOperand(i).isUndef()) 8202 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8203 else if (isNullConstant(BVN->getOperand(i))) 8204 CV[i] = NegOne; 8205 else 8206 CV[i] = One; 8207 } 8208 8209 Constant *CP = ConstantVector::get(CV); 8210 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8211 16 /* alignment */); 8212 8213 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8214 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8215 return DAG.getMemIntrinsicNode( 8216 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8217 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8218 } 8219 8220 SmallVector<SDValue, 4> Stores; 8221 for (unsigned i = 0; i < 4; ++i) { 8222 if (BVN->getOperand(i).isUndef()) continue; 8223 8224 unsigned Offset = 4*i; 8225 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8226 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8227 8228 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8229 if (StoreSize > 4) { 8230 Stores.push_back( 8231 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8232 PtrInfo.getWithOffset(Offset), MVT::i32)); 8233 } else { 8234 SDValue StoreValue = BVN->getOperand(i); 8235 if (StoreSize < 4) 8236 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8237 8238 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8239 PtrInfo.getWithOffset(Offset))); 8240 } 8241 } 8242 8243 SDValue StoreChain; 8244 if (!Stores.empty()) 8245 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8246 else 8247 StoreChain = DAG.getEntryNode(); 8248 8249 // Now load from v4i32 into the QPX register; this will extend it to 8250 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8251 // is typed as v4f64 because the QPX register integer states are not 8252 // explicitly represented. 8253 8254 SDValue Ops[] = {StoreChain, 8255 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8256 FIdx}; 8257 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8258 8259 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8260 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8261 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8262 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8263 LoadedVect); 8264 8265 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8266 8267 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8268 } 8269 8270 // All other QPX vectors are handled by generic code. 8271 if (Subtarget.hasQPX()) 8272 return SDValue(); 8273 8274 // Check if this is a splat of a constant value. 8275 APInt APSplatBits, APSplatUndef; 8276 unsigned SplatBitSize; 8277 bool HasAnyUndefs; 8278 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8279 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8280 SplatBitSize > 32) { 8281 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8282 // lowered to VSX instructions under certain conditions. 8283 // Without VSX, there is no pattern more efficient than expanding the node. 8284 if (Subtarget.hasVSX() && 8285 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8286 Subtarget.hasP8Vector())) 8287 return Op; 8288 return SDValue(); 8289 } 8290 8291 unsigned SplatBits = APSplatBits.getZExtValue(); 8292 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8293 unsigned SplatSize = SplatBitSize / 8; 8294 8295 // First, handle single instruction cases. 8296 8297 // All zeros? 8298 if (SplatBits == 0) { 8299 // Canonicalize all zero vectors to be v4i32. 8300 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8301 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8302 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8303 } 8304 return Op; 8305 } 8306 8307 // We have XXSPLTIB for constant splats one byte wide 8308 if (Subtarget.hasP9Vector() && SplatSize == 1) { 8309 // This is a splat of 1-byte elements with some elements potentially undef. 8310 // Rather than trying to match undef in the SDAG patterns, ensure that all 8311 // elements are the same constant. 8312 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) { 8313 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits, 8314 dl, MVT::i32)); 8315 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops); 8316 if (Op.getValueType() != MVT::v16i8) 8317 return DAG.getBitcast(Op.getValueType(), NewBV); 8318 return NewBV; 8319 } 8320 8321 // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll 8322 // detect that constant splats like v8i16: 0xABAB are really just splats 8323 // of a 1-byte constant. In this case, we need to convert the node to a 8324 // splat of v16i8 and a bitcast. 8325 if (Op.getValueType() != MVT::v16i8) 8326 return DAG.getBitcast(Op.getValueType(), 8327 DAG.getConstant(SplatBits, dl, MVT::v16i8)); 8328 8329 return Op; 8330 } 8331 8332 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8333 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8334 (32-SplatBitSize)); 8335 if (SextVal >= -16 && SextVal <= 15) 8336 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8337 8338 // Two instruction sequences. 8339 8340 // If this value is in the range [-32,30] and is even, use: 8341 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8342 // If this value is in the range [17,31] and is odd, use: 8343 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8344 // If this value is in the range [-31,-17] and is odd, use: 8345 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8346 // Note the last two are three-instruction sequences. 8347 if (SextVal >= -32 && SextVal <= 31) { 8348 // To avoid having these optimizations undone by constant folding, 8349 // we convert to a pseudo that will be expanded later into one of 8350 // the above forms. 8351 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8352 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8353 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8354 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8355 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8356 if (VT == Op.getValueType()) 8357 return RetVal; 8358 else 8359 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8360 } 8361 8362 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8363 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8364 // for fneg/fabs. 8365 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8366 // Make -1 and vspltisw -1: 8367 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8368 8369 // Make the VSLW intrinsic, computing 0x8000_0000. 8370 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8371 OnesV, DAG, dl); 8372 8373 // xor by OnesV to invert it. 8374 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8375 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8376 } 8377 8378 // Check to see if this is a wide variety of vsplti*, binop self cases. 8379 static const signed char SplatCsts[] = { 8380 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8381 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8382 }; 8383 8384 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8385 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8386 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8387 int i = SplatCsts[idx]; 8388 8389 // Figure out what shift amount will be used by altivec if shifted by i in 8390 // this splat size. 8391 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8392 8393 // vsplti + shl self. 8394 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8395 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8396 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8397 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8398 Intrinsic::ppc_altivec_vslw 8399 }; 8400 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8401 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8402 } 8403 8404 // vsplti + srl self. 8405 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8406 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8407 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8408 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8409 Intrinsic::ppc_altivec_vsrw 8410 }; 8411 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8412 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8413 } 8414 8415 // vsplti + sra self. 8416 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8417 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8418 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8419 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8420 Intrinsic::ppc_altivec_vsraw 8421 }; 8422 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8423 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8424 } 8425 8426 // vsplti + rol self. 8427 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8428 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8429 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8430 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8431 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8432 Intrinsic::ppc_altivec_vrlw 8433 }; 8434 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8435 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8436 } 8437 8438 // t = vsplti c, result = vsldoi t, t, 1 8439 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8440 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8441 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8442 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8443 } 8444 // t = vsplti c, result = vsldoi t, t, 2 8445 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8446 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8447 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8448 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8449 } 8450 // t = vsplti c, result = vsldoi t, t, 3 8451 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8452 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8453 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8454 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8455 } 8456 } 8457 8458 return SDValue(); 8459 } 8460 8461 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8462 /// the specified operations to build the shuffle. 8463 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8464 SDValue RHS, SelectionDAG &DAG, 8465 const SDLoc &dl) { 8466 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8467 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8468 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8469 8470 enum { 8471 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8472 OP_VMRGHW, 8473 OP_VMRGLW, 8474 OP_VSPLTISW0, 8475 OP_VSPLTISW1, 8476 OP_VSPLTISW2, 8477 OP_VSPLTISW3, 8478 OP_VSLDOI4, 8479 OP_VSLDOI8, 8480 OP_VSLDOI12 8481 }; 8482 8483 if (OpNum == OP_COPY) { 8484 if (LHSID == (1*9+2)*9+3) return LHS; 8485 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8486 return RHS; 8487 } 8488 8489 SDValue OpLHS, OpRHS; 8490 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8491 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8492 8493 int ShufIdxs[16]; 8494 switch (OpNum) { 8495 default: llvm_unreachable("Unknown i32 permute!"); 8496 case OP_VMRGHW: 8497 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8498 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8499 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8500 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8501 break; 8502 case OP_VMRGLW: 8503 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8504 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8505 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8506 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8507 break; 8508 case OP_VSPLTISW0: 8509 for (unsigned i = 0; i != 16; ++i) 8510 ShufIdxs[i] = (i&3)+0; 8511 break; 8512 case OP_VSPLTISW1: 8513 for (unsigned i = 0; i != 16; ++i) 8514 ShufIdxs[i] = (i&3)+4; 8515 break; 8516 case OP_VSPLTISW2: 8517 for (unsigned i = 0; i != 16; ++i) 8518 ShufIdxs[i] = (i&3)+8; 8519 break; 8520 case OP_VSPLTISW3: 8521 for (unsigned i = 0; i != 16; ++i) 8522 ShufIdxs[i] = (i&3)+12; 8523 break; 8524 case OP_VSLDOI4: 8525 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8526 case OP_VSLDOI8: 8527 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8528 case OP_VSLDOI12: 8529 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8530 } 8531 EVT VT = OpLHS.getValueType(); 8532 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8533 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8534 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8535 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8536 } 8537 8538 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8539 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8540 /// SDValue. 8541 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8542 SelectionDAG &DAG) const { 8543 const unsigned BytesInVector = 16; 8544 bool IsLE = Subtarget.isLittleEndian(); 8545 SDLoc dl(N); 8546 SDValue V1 = N->getOperand(0); 8547 SDValue V2 = N->getOperand(1); 8548 unsigned ShiftElts = 0, InsertAtByte = 0; 8549 bool Swap = false; 8550 8551 // Shifts required to get the byte we want at element 7. 8552 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8553 0, 15, 14, 13, 12, 11, 10, 9}; 8554 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8555 1, 2, 3, 4, 5, 6, 7, 8}; 8556 8557 ArrayRef<int> Mask = N->getMask(); 8558 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8559 8560 // For each mask element, find out if we're just inserting something 8561 // from V2 into V1 or vice versa. 8562 // Possible permutations inserting an element from V2 into V1: 8563 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8564 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8565 // ... 8566 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8567 // Inserting from V1 into V2 will be similar, except mask range will be 8568 // [16,31]. 8569 8570 bool FoundCandidate = false; 8571 // If both vector operands for the shuffle are the same vector, the mask 8572 // will contain only elements from the first one and the second one will be 8573 // undef. 8574 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 8575 // Go through the mask of half-words to find an element that's being moved 8576 // from one vector to the other. 8577 for (unsigned i = 0; i < BytesInVector; ++i) { 8578 unsigned CurrentElement = Mask[i]; 8579 // If 2nd operand is undefined, we should only look for element 7 in the 8580 // Mask. 8581 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 8582 continue; 8583 8584 bool OtherElementsInOrder = true; 8585 // Examine the other elements in the Mask to see if they're in original 8586 // order. 8587 for (unsigned j = 0; j < BytesInVector; ++j) { 8588 if (j == i) 8589 continue; 8590 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 8591 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 8592 // in which we always assume we're always picking from the 1st operand. 8593 int MaskOffset = 8594 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 8595 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 8596 OtherElementsInOrder = false; 8597 break; 8598 } 8599 } 8600 // If other elements are in original order, we record the number of shifts 8601 // we need to get the element we want into element 7. Also record which byte 8602 // in the vector we should insert into. 8603 if (OtherElementsInOrder) { 8604 // If 2nd operand is undefined, we assume no shifts and no swapping. 8605 if (V2.isUndef()) { 8606 ShiftElts = 0; 8607 Swap = false; 8608 } else { 8609 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 8610 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 8611 : BigEndianShifts[CurrentElement & 0xF]; 8612 Swap = CurrentElement < BytesInVector; 8613 } 8614 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 8615 FoundCandidate = true; 8616 break; 8617 } 8618 } 8619 8620 if (!FoundCandidate) 8621 return SDValue(); 8622 8623 // Candidate found, construct the proper SDAG sequence with VINSERTB, 8624 // optionally with VECSHL if shift is required. 8625 if (Swap) 8626 std::swap(V1, V2); 8627 if (V2.isUndef()) 8628 V2 = V1; 8629 if (ShiftElts) { 8630 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8631 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8632 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 8633 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8634 } 8635 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 8636 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8637 } 8638 8639 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 8640 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 8641 /// SDValue. 8642 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 8643 SelectionDAG &DAG) const { 8644 const unsigned NumHalfWords = 8; 8645 const unsigned BytesInVector = NumHalfWords * 2; 8646 // Check that the shuffle is on half-words. 8647 if (!isNByteElemShuffleMask(N, 2, 1)) 8648 return SDValue(); 8649 8650 bool IsLE = Subtarget.isLittleEndian(); 8651 SDLoc dl(N); 8652 SDValue V1 = N->getOperand(0); 8653 SDValue V2 = N->getOperand(1); 8654 unsigned ShiftElts = 0, InsertAtByte = 0; 8655 bool Swap = false; 8656 8657 // Shifts required to get the half-word we want at element 3. 8658 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 8659 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 8660 8661 uint32_t Mask = 0; 8662 uint32_t OriginalOrderLow = 0x1234567; 8663 uint32_t OriginalOrderHigh = 0x89ABCDEF; 8664 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 8665 // 32-bit space, only need 4-bit nibbles per element. 8666 for (unsigned i = 0; i < NumHalfWords; ++i) { 8667 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8668 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 8669 } 8670 8671 // For each mask element, find out if we're just inserting something 8672 // from V2 into V1 or vice versa. Possible permutations inserting an element 8673 // from V2 into V1: 8674 // X, 1, 2, 3, 4, 5, 6, 7 8675 // 0, X, 2, 3, 4, 5, 6, 7 8676 // 0, 1, X, 3, 4, 5, 6, 7 8677 // 0, 1, 2, X, 4, 5, 6, 7 8678 // 0, 1, 2, 3, X, 5, 6, 7 8679 // 0, 1, 2, 3, 4, X, 6, 7 8680 // 0, 1, 2, 3, 4, 5, X, 7 8681 // 0, 1, 2, 3, 4, 5, 6, X 8682 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 8683 8684 bool FoundCandidate = false; 8685 // Go through the mask of half-words to find an element that's being moved 8686 // from one vector to the other. 8687 for (unsigned i = 0; i < NumHalfWords; ++i) { 8688 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 8689 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 8690 uint32_t MaskOtherElts = ~(0xF << MaskShift); 8691 uint32_t TargetOrder = 0x0; 8692 8693 // If both vector operands for the shuffle are the same vector, the mask 8694 // will contain only elements from the first one and the second one will be 8695 // undef. 8696 if (V2.isUndef()) { 8697 ShiftElts = 0; 8698 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 8699 TargetOrder = OriginalOrderLow; 8700 Swap = false; 8701 // Skip if not the correct element or mask of other elements don't equal 8702 // to our expected order. 8703 if (MaskOneElt == VINSERTHSrcElem && 8704 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8705 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8706 FoundCandidate = true; 8707 break; 8708 } 8709 } else { // If both operands are defined. 8710 // Target order is [8,15] if the current mask is between [0,7]. 8711 TargetOrder = 8712 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 8713 // Skip if mask of other elements don't equal our expected order. 8714 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 8715 // We only need the last 3 bits for the number of shifts. 8716 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 8717 : BigEndianShifts[MaskOneElt & 0x7]; 8718 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 8719 Swap = MaskOneElt < NumHalfWords; 8720 FoundCandidate = true; 8721 break; 8722 } 8723 } 8724 } 8725 8726 if (!FoundCandidate) 8727 return SDValue(); 8728 8729 // Candidate found, construct the proper SDAG sequence with VINSERTH, 8730 // optionally with VECSHL if shift is required. 8731 if (Swap) 8732 std::swap(V1, V2); 8733 if (V2.isUndef()) 8734 V2 = V1; 8735 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8736 if (ShiftElts) { 8737 // Double ShiftElts because we're left shifting on v16i8 type. 8738 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 8739 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 8740 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 8741 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8742 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8743 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8744 } 8745 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 8746 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 8747 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8748 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8749 } 8750 8751 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 8752 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 8753 /// return the code it can be lowered into. Worst case, it can always be 8754 /// lowered into a vperm. 8755 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 8756 SelectionDAG &DAG) const { 8757 SDLoc dl(Op); 8758 SDValue V1 = Op.getOperand(0); 8759 SDValue V2 = Op.getOperand(1); 8760 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 8761 EVT VT = Op.getValueType(); 8762 bool isLittleEndian = Subtarget.isLittleEndian(); 8763 8764 unsigned ShiftElts, InsertAtByte; 8765 bool Swap = false; 8766 if (Subtarget.hasP9Vector() && 8767 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 8768 isLittleEndian)) { 8769 if (Swap) 8770 std::swap(V1, V2); 8771 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8772 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 8773 if (ShiftElts) { 8774 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 8775 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8776 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 8777 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8778 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8779 } 8780 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 8781 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 8782 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 8783 } 8784 8785 if (Subtarget.hasP9Altivec()) { 8786 SDValue NewISDNode; 8787 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 8788 return NewISDNode; 8789 8790 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 8791 return NewISDNode; 8792 } 8793 8794 if (Subtarget.hasVSX() && 8795 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8796 if (Swap) 8797 std::swap(V1, V2); 8798 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8799 SDValue Conv2 = 8800 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 8801 8802 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 8803 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8804 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 8805 } 8806 8807 if (Subtarget.hasVSX() && 8808 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 8809 if (Swap) 8810 std::swap(V1, V2); 8811 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8812 SDValue Conv2 = 8813 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 8814 8815 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 8816 DAG.getConstant(ShiftElts, dl, MVT::i32)); 8817 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 8818 } 8819 8820 if (Subtarget.hasP9Vector()) { 8821 if (PPC::isXXBRHShuffleMask(SVOp)) { 8822 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 8823 SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv); 8824 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 8825 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 8826 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8827 SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv); 8828 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 8829 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 8830 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 8831 SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv); 8832 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 8833 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 8834 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 8835 SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv); 8836 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 8837 } 8838 } 8839 8840 if (Subtarget.hasVSX()) { 8841 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 8842 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG); 8843 8844 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 8845 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 8846 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8847 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 8848 } 8849 8850 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 8851 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 8852 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 8853 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 8854 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 8855 } 8856 } 8857 8858 if (Subtarget.hasQPX()) { 8859 if (VT.getVectorNumElements() != 4) 8860 return SDValue(); 8861 8862 if (V2.isUndef()) V2 = V1; 8863 8864 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 8865 if (AlignIdx != -1) { 8866 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 8867 DAG.getConstant(AlignIdx, dl, MVT::i32)); 8868 } else if (SVOp->isSplat()) { 8869 int SplatIdx = SVOp->getSplatIndex(); 8870 if (SplatIdx >= 4) { 8871 std::swap(V1, V2); 8872 SplatIdx -= 4; 8873 } 8874 8875 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 8876 DAG.getConstant(SplatIdx, dl, MVT::i32)); 8877 } 8878 8879 // Lower this into a qvgpci/qvfperm pair. 8880 8881 // Compute the qvgpci literal 8882 unsigned idx = 0; 8883 for (unsigned i = 0; i < 4; ++i) { 8884 int m = SVOp->getMaskElt(i); 8885 unsigned mm = m >= 0 ? (unsigned) m : i; 8886 idx |= mm << (3-i)*3; 8887 } 8888 8889 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 8890 DAG.getConstant(idx, dl, MVT::i32)); 8891 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 8892 } 8893 8894 // Cases that are handled by instructions that take permute immediates 8895 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 8896 // selected by the instruction selector. 8897 if (V2.isUndef()) { 8898 if (PPC::isSplatShuffleMask(SVOp, 1) || 8899 PPC::isSplatShuffleMask(SVOp, 2) || 8900 PPC::isSplatShuffleMask(SVOp, 4) || 8901 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 8902 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 8903 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 8904 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 8905 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 8906 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 8907 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 8908 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 8909 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 8910 (Subtarget.hasP8Altivec() && ( 8911 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 8912 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 8913 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 8914 return Op; 8915 } 8916 } 8917 8918 // Altivec has a variety of "shuffle immediates" that take two vector inputs 8919 // and produce a fixed permutation. If any of these match, do not lower to 8920 // VPERM. 8921 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 8922 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 8923 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 8924 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 8925 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8926 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8927 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8928 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 8929 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 8930 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 8931 (Subtarget.hasP8Altivec() && ( 8932 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 8933 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 8934 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 8935 return Op; 8936 8937 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 8938 // perfect shuffle table to emit an optimal matching sequence. 8939 ArrayRef<int> PermMask = SVOp->getMask(); 8940 8941 unsigned PFIndexes[4]; 8942 bool isFourElementShuffle = true; 8943 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 8944 unsigned EltNo = 8; // Start out undef. 8945 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 8946 if (PermMask[i*4+j] < 0) 8947 continue; // Undef, ignore it. 8948 8949 unsigned ByteSource = PermMask[i*4+j]; 8950 if ((ByteSource & 3) != j) { 8951 isFourElementShuffle = false; 8952 break; 8953 } 8954 8955 if (EltNo == 8) { 8956 EltNo = ByteSource/4; 8957 } else if (EltNo != ByteSource/4) { 8958 isFourElementShuffle = false; 8959 break; 8960 } 8961 } 8962 PFIndexes[i] = EltNo; 8963 } 8964 8965 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 8966 // perfect shuffle vector to determine if it is cost effective to do this as 8967 // discrete instructions, or whether we should use a vperm. 8968 // For now, we skip this for little endian until such time as we have a 8969 // little-endian perfect shuffle table. 8970 if (isFourElementShuffle && !isLittleEndian) { 8971 // Compute the index in the perfect shuffle table. 8972 unsigned PFTableIndex = 8973 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 8974 8975 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8976 unsigned Cost = (PFEntry >> 30); 8977 8978 // Determining when to avoid vperm is tricky. Many things affect the cost 8979 // of vperm, particularly how many times the perm mask needs to be computed. 8980 // For example, if the perm mask can be hoisted out of a loop or is already 8981 // used (perhaps because there are multiple permutes with the same shuffle 8982 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 8983 // the loop requires an extra register. 8984 // 8985 // As a compromise, we only emit discrete instructions if the shuffle can be 8986 // generated in 3 or fewer operations. When we have loop information 8987 // available, if this block is within a loop, we should avoid using vperm 8988 // for 3-operation perms and use a constant pool load instead. 8989 if (Cost < 3) 8990 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 8991 } 8992 8993 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 8994 // vector that will get spilled to the constant pool. 8995 if (V2.isUndef()) V2 = V1; 8996 8997 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 8998 // that it is in input element units, not in bytes. Convert now. 8999 9000 // For little endian, the order of the input vectors is reversed, and 9001 // the permutation mask is complemented with respect to 31. This is 9002 // necessary to produce proper semantics with the big-endian-biased vperm 9003 // instruction. 9004 EVT EltVT = V1.getValueType().getVectorElementType(); 9005 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9006 9007 SmallVector<SDValue, 16> ResultMask; 9008 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9009 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9010 9011 for (unsigned j = 0; j != BytesPerElement; ++j) 9012 if (isLittleEndian) 9013 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9014 dl, MVT::i32)); 9015 else 9016 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9017 MVT::i32)); 9018 } 9019 9020 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9021 if (isLittleEndian) 9022 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9023 V2, V1, VPermMask); 9024 else 9025 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9026 V1, V2, VPermMask); 9027 } 9028 9029 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9030 /// vector comparison. If it is, return true and fill in Opc/isDot with 9031 /// information about the intrinsic. 9032 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9033 bool &isDot, const PPCSubtarget &Subtarget) { 9034 unsigned IntrinsicID = 9035 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9036 CompareOpc = -1; 9037 isDot = false; 9038 switch (IntrinsicID) { 9039 default: 9040 return false; 9041 // Comparison predicates. 9042 case Intrinsic::ppc_altivec_vcmpbfp_p: 9043 CompareOpc = 966; 9044 isDot = true; 9045 break; 9046 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9047 CompareOpc = 198; 9048 isDot = true; 9049 break; 9050 case Intrinsic::ppc_altivec_vcmpequb_p: 9051 CompareOpc = 6; 9052 isDot = true; 9053 break; 9054 case Intrinsic::ppc_altivec_vcmpequh_p: 9055 CompareOpc = 70; 9056 isDot = true; 9057 break; 9058 case Intrinsic::ppc_altivec_vcmpequw_p: 9059 CompareOpc = 134; 9060 isDot = true; 9061 break; 9062 case Intrinsic::ppc_altivec_vcmpequd_p: 9063 if (Subtarget.hasP8Altivec()) { 9064 CompareOpc = 199; 9065 isDot = true; 9066 } else 9067 return false; 9068 break; 9069 case Intrinsic::ppc_altivec_vcmpneb_p: 9070 case Intrinsic::ppc_altivec_vcmpneh_p: 9071 case Intrinsic::ppc_altivec_vcmpnew_p: 9072 case Intrinsic::ppc_altivec_vcmpnezb_p: 9073 case Intrinsic::ppc_altivec_vcmpnezh_p: 9074 case Intrinsic::ppc_altivec_vcmpnezw_p: 9075 if (Subtarget.hasP9Altivec()) { 9076 switch (IntrinsicID) { 9077 default: 9078 llvm_unreachable("Unknown comparison intrinsic."); 9079 case Intrinsic::ppc_altivec_vcmpneb_p: 9080 CompareOpc = 7; 9081 break; 9082 case Intrinsic::ppc_altivec_vcmpneh_p: 9083 CompareOpc = 71; 9084 break; 9085 case Intrinsic::ppc_altivec_vcmpnew_p: 9086 CompareOpc = 135; 9087 break; 9088 case Intrinsic::ppc_altivec_vcmpnezb_p: 9089 CompareOpc = 263; 9090 break; 9091 case Intrinsic::ppc_altivec_vcmpnezh_p: 9092 CompareOpc = 327; 9093 break; 9094 case Intrinsic::ppc_altivec_vcmpnezw_p: 9095 CompareOpc = 391; 9096 break; 9097 } 9098 isDot = true; 9099 } else 9100 return false; 9101 break; 9102 case Intrinsic::ppc_altivec_vcmpgefp_p: 9103 CompareOpc = 454; 9104 isDot = true; 9105 break; 9106 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9107 CompareOpc = 710; 9108 isDot = true; 9109 break; 9110 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9111 CompareOpc = 774; 9112 isDot = true; 9113 break; 9114 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9115 CompareOpc = 838; 9116 isDot = true; 9117 break; 9118 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9119 CompareOpc = 902; 9120 isDot = true; 9121 break; 9122 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9123 if (Subtarget.hasP8Altivec()) { 9124 CompareOpc = 967; 9125 isDot = true; 9126 } else 9127 return false; 9128 break; 9129 case Intrinsic::ppc_altivec_vcmpgtub_p: 9130 CompareOpc = 518; 9131 isDot = true; 9132 break; 9133 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9134 CompareOpc = 582; 9135 isDot = true; 9136 break; 9137 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9138 CompareOpc = 646; 9139 isDot = true; 9140 break; 9141 case Intrinsic::ppc_altivec_vcmpgtud_p: 9142 if (Subtarget.hasP8Altivec()) { 9143 CompareOpc = 711; 9144 isDot = true; 9145 } else 9146 return false; 9147 break; 9148 9149 // VSX predicate comparisons use the same infrastructure 9150 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9151 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9152 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9153 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9154 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9155 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9156 if (Subtarget.hasVSX()) { 9157 switch (IntrinsicID) { 9158 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9159 CompareOpc = 99; 9160 break; 9161 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9162 CompareOpc = 115; 9163 break; 9164 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9165 CompareOpc = 107; 9166 break; 9167 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9168 CompareOpc = 67; 9169 break; 9170 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9171 CompareOpc = 83; 9172 break; 9173 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9174 CompareOpc = 75; 9175 break; 9176 } 9177 isDot = true; 9178 } else 9179 return false; 9180 break; 9181 9182 // Normal Comparisons. 9183 case Intrinsic::ppc_altivec_vcmpbfp: 9184 CompareOpc = 966; 9185 break; 9186 case Intrinsic::ppc_altivec_vcmpeqfp: 9187 CompareOpc = 198; 9188 break; 9189 case Intrinsic::ppc_altivec_vcmpequb: 9190 CompareOpc = 6; 9191 break; 9192 case Intrinsic::ppc_altivec_vcmpequh: 9193 CompareOpc = 70; 9194 break; 9195 case Intrinsic::ppc_altivec_vcmpequw: 9196 CompareOpc = 134; 9197 break; 9198 case Intrinsic::ppc_altivec_vcmpequd: 9199 if (Subtarget.hasP8Altivec()) 9200 CompareOpc = 199; 9201 else 9202 return false; 9203 break; 9204 case Intrinsic::ppc_altivec_vcmpneb: 9205 case Intrinsic::ppc_altivec_vcmpneh: 9206 case Intrinsic::ppc_altivec_vcmpnew: 9207 case Intrinsic::ppc_altivec_vcmpnezb: 9208 case Intrinsic::ppc_altivec_vcmpnezh: 9209 case Intrinsic::ppc_altivec_vcmpnezw: 9210 if (Subtarget.hasP9Altivec()) 9211 switch (IntrinsicID) { 9212 default: 9213 llvm_unreachable("Unknown comparison intrinsic."); 9214 case Intrinsic::ppc_altivec_vcmpneb: 9215 CompareOpc = 7; 9216 break; 9217 case Intrinsic::ppc_altivec_vcmpneh: 9218 CompareOpc = 71; 9219 break; 9220 case Intrinsic::ppc_altivec_vcmpnew: 9221 CompareOpc = 135; 9222 break; 9223 case Intrinsic::ppc_altivec_vcmpnezb: 9224 CompareOpc = 263; 9225 break; 9226 case Intrinsic::ppc_altivec_vcmpnezh: 9227 CompareOpc = 327; 9228 break; 9229 case Intrinsic::ppc_altivec_vcmpnezw: 9230 CompareOpc = 391; 9231 break; 9232 } 9233 else 9234 return false; 9235 break; 9236 case Intrinsic::ppc_altivec_vcmpgefp: 9237 CompareOpc = 454; 9238 break; 9239 case Intrinsic::ppc_altivec_vcmpgtfp: 9240 CompareOpc = 710; 9241 break; 9242 case Intrinsic::ppc_altivec_vcmpgtsb: 9243 CompareOpc = 774; 9244 break; 9245 case Intrinsic::ppc_altivec_vcmpgtsh: 9246 CompareOpc = 838; 9247 break; 9248 case Intrinsic::ppc_altivec_vcmpgtsw: 9249 CompareOpc = 902; 9250 break; 9251 case Intrinsic::ppc_altivec_vcmpgtsd: 9252 if (Subtarget.hasP8Altivec()) 9253 CompareOpc = 967; 9254 else 9255 return false; 9256 break; 9257 case Intrinsic::ppc_altivec_vcmpgtub: 9258 CompareOpc = 518; 9259 break; 9260 case Intrinsic::ppc_altivec_vcmpgtuh: 9261 CompareOpc = 582; 9262 break; 9263 case Intrinsic::ppc_altivec_vcmpgtuw: 9264 CompareOpc = 646; 9265 break; 9266 case Intrinsic::ppc_altivec_vcmpgtud: 9267 if (Subtarget.hasP8Altivec()) 9268 CompareOpc = 711; 9269 else 9270 return false; 9271 break; 9272 } 9273 return true; 9274 } 9275 9276 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9277 /// lower, do it, otherwise return null. 9278 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9279 SelectionDAG &DAG) const { 9280 unsigned IntrinsicID = 9281 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9282 9283 SDLoc dl(Op); 9284 9285 if (IntrinsicID == Intrinsic::thread_pointer) { 9286 // Reads the thread pointer register, used for __builtin_thread_pointer. 9287 if (Subtarget.isPPC64()) 9288 return DAG.getRegister(PPC::X13, MVT::i64); 9289 return DAG.getRegister(PPC::R2, MVT::i32); 9290 } 9291 9292 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9293 // opcode number of the comparison. 9294 int CompareOpc; 9295 bool isDot; 9296 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9297 return SDValue(); // Don't custom lower most intrinsics. 9298 9299 // If this is a non-dot comparison, make the VCMP node and we are done. 9300 if (!isDot) { 9301 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9302 Op.getOperand(1), Op.getOperand(2), 9303 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9304 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9305 } 9306 9307 // Create the PPCISD altivec 'dot' comparison node. 9308 SDValue Ops[] = { 9309 Op.getOperand(2), // LHS 9310 Op.getOperand(3), // RHS 9311 DAG.getConstant(CompareOpc, dl, MVT::i32) 9312 }; 9313 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9314 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9315 9316 // Now that we have the comparison, emit a copy from the CR to a GPR. 9317 // This is flagged to the above dot comparison. 9318 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9319 DAG.getRegister(PPC::CR6, MVT::i32), 9320 CompNode.getValue(1)); 9321 9322 // Unpack the result based on how the target uses it. 9323 unsigned BitNo; // Bit # of CR6. 9324 bool InvertBit; // Invert result? 9325 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9326 default: // Can't happen, don't crash on invalid number though. 9327 case 0: // Return the value of the EQ bit of CR6. 9328 BitNo = 0; InvertBit = false; 9329 break; 9330 case 1: // Return the inverted value of the EQ bit of CR6. 9331 BitNo = 0; InvertBit = true; 9332 break; 9333 case 2: // Return the value of the LT bit of CR6. 9334 BitNo = 2; InvertBit = false; 9335 break; 9336 case 3: // Return the inverted value of the LT bit of CR6. 9337 BitNo = 2; InvertBit = true; 9338 break; 9339 } 9340 9341 // Shift the bit into the low position. 9342 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9343 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9344 // Isolate the bit. 9345 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9346 DAG.getConstant(1, dl, MVT::i32)); 9347 9348 // If we are supposed to, toggle the bit. 9349 if (InvertBit) 9350 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9351 DAG.getConstant(1, dl, MVT::i32)); 9352 return Flags; 9353 } 9354 9355 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9356 SelectionDAG &DAG) const { 9357 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9358 // the beginning of the argument list. 9359 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9360 SDLoc DL(Op); 9361 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9362 case Intrinsic::ppc_cfence: { 9363 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9364 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9365 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9366 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9367 Op.getOperand(ArgStart + 1)), 9368 Op.getOperand(0)), 9369 0); 9370 } 9371 default: 9372 break; 9373 } 9374 return SDValue(); 9375 } 9376 9377 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9378 // Check for a DIV with the same operands as this REM. 9379 for (auto UI : Op.getOperand(1)->uses()) { 9380 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9381 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9382 if (UI->getOperand(0) == Op.getOperand(0) && 9383 UI->getOperand(1) == Op.getOperand(1)) 9384 return SDValue(); 9385 } 9386 return Op; 9387 } 9388 9389 // Lower scalar BSWAP64 to xxbrd. 9390 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9391 SDLoc dl(Op); 9392 // MTVSRDD 9393 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9394 Op.getOperand(0)); 9395 // XXBRD 9396 Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op); 9397 // MFVSRD 9398 int VectorIndex = 0; 9399 if (Subtarget.isLittleEndian()) 9400 VectorIndex = 1; 9401 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9402 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9403 return Op; 9404 } 9405 9406 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9407 // compared to a value that is atomically loaded (atomic loads zero-extend). 9408 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9409 SelectionDAG &DAG) const { 9410 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9411 "Expecting an atomic compare-and-swap here."); 9412 SDLoc dl(Op); 9413 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9414 EVT MemVT = AtomicNode->getMemoryVT(); 9415 if (MemVT.getSizeInBits() >= 32) 9416 return Op; 9417 9418 SDValue CmpOp = Op.getOperand(2); 9419 // If this is already correctly zero-extended, leave it alone. 9420 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9421 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9422 return Op; 9423 9424 // Clear the high bits of the compare operand. 9425 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9426 SDValue NewCmpOp = 9427 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9428 DAG.getConstant(MaskVal, dl, MVT::i32)); 9429 9430 // Replace the existing compare operand with the properly zero-extended one. 9431 SmallVector<SDValue, 4> Ops; 9432 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9433 Ops.push_back(AtomicNode->getOperand(i)); 9434 Ops[2] = NewCmpOp; 9435 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9436 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9437 auto NodeTy = 9438 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9439 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9440 } 9441 9442 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9443 SelectionDAG &DAG) const { 9444 SDLoc dl(Op); 9445 // Create a stack slot that is 16-byte aligned. 9446 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9447 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9448 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9449 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9450 9451 // Store the input value into Value#0 of the stack slot. 9452 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9453 MachinePointerInfo()); 9454 // Load it out. 9455 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9456 } 9457 9458 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9459 SelectionDAG &DAG) const { 9460 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9461 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9462 9463 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9464 // We have legal lowering for constant indices but not for variable ones. 9465 if (!C) 9466 return SDValue(); 9467 9468 EVT VT = Op.getValueType(); 9469 SDLoc dl(Op); 9470 SDValue V1 = Op.getOperand(0); 9471 SDValue V2 = Op.getOperand(1); 9472 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9473 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9474 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9475 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9476 unsigned InsertAtElement = C->getZExtValue(); 9477 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9478 if (Subtarget.isLittleEndian()) { 9479 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9480 } 9481 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9482 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9483 } 9484 return Op; 9485 } 9486 9487 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9488 SelectionDAG &DAG) const { 9489 SDLoc dl(Op); 9490 SDNode *N = Op.getNode(); 9491 9492 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9493 "Unknown extract_vector_elt type"); 9494 9495 SDValue Value = N->getOperand(0); 9496 9497 // The first part of this is like the store lowering except that we don't 9498 // need to track the chain. 9499 9500 // The values are now known to be -1 (false) or 1 (true). To convert this 9501 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9502 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9503 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9504 9505 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9506 // understand how to form the extending load. 9507 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9508 9509 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9510 9511 // Now convert to an integer and store. 9512 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9513 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9514 Value); 9515 9516 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9517 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9518 MachinePointerInfo PtrInfo = 9519 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9520 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9521 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9522 9523 SDValue StoreChain = DAG.getEntryNode(); 9524 SDValue Ops[] = {StoreChain, 9525 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9526 Value, FIdx}; 9527 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9528 9529 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9530 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9531 9532 // Extract the value requested. 9533 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9534 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9535 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9536 9537 SDValue IntVal = 9538 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 9539 9540 if (!Subtarget.useCRBits()) 9541 return IntVal; 9542 9543 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 9544 } 9545 9546 /// Lowering for QPX v4i1 loads 9547 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 9548 SelectionDAG &DAG) const { 9549 SDLoc dl(Op); 9550 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 9551 SDValue LoadChain = LN->getChain(); 9552 SDValue BasePtr = LN->getBasePtr(); 9553 9554 if (Op.getValueType() == MVT::v4f64 || 9555 Op.getValueType() == MVT::v4f32) { 9556 EVT MemVT = LN->getMemoryVT(); 9557 unsigned Alignment = LN->getAlignment(); 9558 9559 // If this load is properly aligned, then it is legal. 9560 if (Alignment >= MemVT.getStoreSize()) 9561 return Op; 9562 9563 EVT ScalarVT = Op.getValueType().getScalarType(), 9564 ScalarMemVT = MemVT.getScalarType(); 9565 unsigned Stride = ScalarMemVT.getStoreSize(); 9566 9567 SDValue Vals[4], LoadChains[4]; 9568 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9569 SDValue Load; 9570 if (ScalarVT != ScalarMemVT) 9571 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 9572 BasePtr, 9573 LN->getPointerInfo().getWithOffset(Idx * Stride), 9574 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9575 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9576 else 9577 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 9578 LN->getPointerInfo().getWithOffset(Idx * Stride), 9579 MinAlign(Alignment, Idx * Stride), 9580 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9581 9582 if (Idx == 0 && LN->isIndexed()) { 9583 assert(LN->getAddressingMode() == ISD::PRE_INC && 9584 "Unknown addressing mode on vector load"); 9585 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 9586 LN->getAddressingMode()); 9587 } 9588 9589 Vals[Idx] = Load; 9590 LoadChains[Idx] = Load.getValue(1); 9591 9592 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9593 DAG.getConstant(Stride, dl, 9594 BasePtr.getValueType())); 9595 } 9596 9597 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9598 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 9599 9600 if (LN->isIndexed()) { 9601 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 9602 return DAG.getMergeValues(RetOps, dl); 9603 } 9604 9605 SDValue RetOps[] = { Value, TF }; 9606 return DAG.getMergeValues(RetOps, dl); 9607 } 9608 9609 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 9610 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 9611 9612 // To lower v4i1 from a byte array, we load the byte elements of the 9613 // vector and then reuse the BUILD_VECTOR logic. 9614 9615 SDValue VectElmts[4], VectElmtChains[4]; 9616 for (unsigned i = 0; i < 4; ++i) { 9617 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9618 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9619 9620 VectElmts[i] = DAG.getExtLoad( 9621 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 9622 LN->getPointerInfo().getWithOffset(i), MVT::i8, 9623 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 9624 VectElmtChains[i] = VectElmts[i].getValue(1); 9625 } 9626 9627 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 9628 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 9629 9630 SDValue RVals[] = { Value, LoadChain }; 9631 return DAG.getMergeValues(RVals, dl); 9632 } 9633 9634 /// Lowering for QPX v4i1 stores 9635 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 9636 SelectionDAG &DAG) const { 9637 SDLoc dl(Op); 9638 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 9639 SDValue StoreChain = SN->getChain(); 9640 SDValue BasePtr = SN->getBasePtr(); 9641 SDValue Value = SN->getValue(); 9642 9643 if (Value.getValueType() == MVT::v4f64 || 9644 Value.getValueType() == MVT::v4f32) { 9645 EVT MemVT = SN->getMemoryVT(); 9646 unsigned Alignment = SN->getAlignment(); 9647 9648 // If this store is properly aligned, then it is legal. 9649 if (Alignment >= MemVT.getStoreSize()) 9650 return Op; 9651 9652 EVT ScalarVT = Value.getValueType().getScalarType(), 9653 ScalarMemVT = MemVT.getScalarType(); 9654 unsigned Stride = ScalarMemVT.getStoreSize(); 9655 9656 SDValue Stores[4]; 9657 for (unsigned Idx = 0; Idx < 4; ++Idx) { 9658 SDValue Ex = DAG.getNode( 9659 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 9660 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); 9661 SDValue Store; 9662 if (ScalarVT != ScalarMemVT) 9663 Store = 9664 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 9665 SN->getPointerInfo().getWithOffset(Idx * Stride), 9666 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 9667 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9668 else 9669 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 9670 SN->getPointerInfo().getWithOffset(Idx * Stride), 9671 MinAlign(Alignment, Idx * Stride), 9672 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 9673 9674 if (Idx == 0 && SN->isIndexed()) { 9675 assert(SN->getAddressingMode() == ISD::PRE_INC && 9676 "Unknown addressing mode on vector store"); 9677 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 9678 SN->getAddressingMode()); 9679 } 9680 9681 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 9682 DAG.getConstant(Stride, dl, 9683 BasePtr.getValueType())); 9684 Stores[Idx] = Store; 9685 } 9686 9687 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9688 9689 if (SN->isIndexed()) { 9690 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 9691 return DAG.getMergeValues(RetOps, dl); 9692 } 9693 9694 return TF; 9695 } 9696 9697 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 9698 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 9699 9700 // The values are now known to be -1 (false) or 1 (true). To convert this 9701 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9702 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9703 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9704 9705 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9706 // understand how to form the extending load. 9707 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9708 9709 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9710 9711 // Now convert to an integer and store. 9712 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9713 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9714 Value); 9715 9716 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9717 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9718 MachinePointerInfo PtrInfo = 9719 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9720 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9721 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9722 9723 SDValue Ops[] = {StoreChain, 9724 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9725 Value, FIdx}; 9726 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9727 9728 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9729 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9730 9731 // Move data into the byte array. 9732 SDValue Loads[4], LoadChains[4]; 9733 for (unsigned i = 0; i < 4; ++i) { 9734 unsigned Offset = 4*i; 9735 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 9736 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 9737 9738 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 9739 PtrInfo.getWithOffset(Offset)); 9740 LoadChains[i] = Loads[i].getValue(1); 9741 } 9742 9743 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 9744 9745 SDValue Stores[4]; 9746 for (unsigned i = 0; i < 4; ++i) { 9747 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 9748 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 9749 9750 Stores[i] = DAG.getTruncStore( 9751 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 9752 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 9753 SN->getAAInfo()); 9754 } 9755 9756 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 9757 9758 return StoreChain; 9759 } 9760 9761 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 9762 SDLoc dl(Op); 9763 if (Op.getValueType() == MVT::v4i32) { 9764 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9765 9766 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 9767 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 9768 9769 SDValue RHSSwap = // = vrlw RHS, 16 9770 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 9771 9772 // Shrinkify inputs to v8i16. 9773 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 9774 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 9775 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 9776 9777 // Low parts multiplied together, generating 32-bit results (we ignore the 9778 // top parts). 9779 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 9780 LHS, RHS, DAG, dl, MVT::v4i32); 9781 9782 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 9783 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 9784 // Shift the high parts up 16 bits. 9785 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 9786 Neg16, DAG, dl); 9787 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 9788 } else if (Op.getValueType() == MVT::v8i16) { 9789 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9790 9791 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 9792 9793 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 9794 LHS, RHS, Zero, DAG, dl); 9795 } else if (Op.getValueType() == MVT::v16i8) { 9796 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 9797 bool isLittleEndian = Subtarget.isLittleEndian(); 9798 9799 // Multiply the even 8-bit parts, producing 16-bit sums. 9800 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 9801 LHS, RHS, DAG, dl, MVT::v8i16); 9802 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 9803 9804 // Multiply the odd 8-bit parts, producing 16-bit sums. 9805 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 9806 LHS, RHS, DAG, dl, MVT::v8i16); 9807 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 9808 9809 // Merge the results together. Because vmuleub and vmuloub are 9810 // instructions with a big-endian bias, we must reverse the 9811 // element numbering and reverse the meaning of "odd" and "even" 9812 // when generating little endian code. 9813 int Ops[16]; 9814 for (unsigned i = 0; i != 8; ++i) { 9815 if (isLittleEndian) { 9816 Ops[i*2 ] = 2*i; 9817 Ops[i*2+1] = 2*i+16; 9818 } else { 9819 Ops[i*2 ] = 2*i+1; 9820 Ops[i*2+1] = 2*i+1+16; 9821 } 9822 } 9823 if (isLittleEndian) 9824 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 9825 else 9826 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 9827 } else { 9828 llvm_unreachable("Unknown mul to lower!"); 9829 } 9830 } 9831 9832 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 9833 9834 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 9835 9836 EVT VT = Op.getValueType(); 9837 assert(VT.isVector() && 9838 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 9839 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 9840 VT == MVT::v16i8) && 9841 "Unexpected vector element type!"); 9842 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 9843 "Current subtarget doesn't support smax v2i64!"); 9844 9845 // For vector abs, it can be lowered to: 9846 // abs x 9847 // ==> 9848 // y = -x 9849 // smax(x, y) 9850 9851 SDLoc dl(Op); 9852 SDValue X = Op.getOperand(0); 9853 SDValue Zero = DAG.getConstant(0, dl, VT); 9854 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 9855 9856 // SMAX patch https://reviews.llvm.org/D47332 9857 // hasn't landed yet, so use intrinsic first here. 9858 // TODO: Should use SMAX directly once SMAX patch landed 9859 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 9860 if (VT == MVT::v2i64) 9861 BifID = Intrinsic::ppc_altivec_vmaxsd; 9862 else if (VT == MVT::v8i16) 9863 BifID = Intrinsic::ppc_altivec_vmaxsh; 9864 else if (VT == MVT::v16i8) 9865 BifID = Intrinsic::ppc_altivec_vmaxsb; 9866 9867 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 9868 } 9869 9870 // Custom lowering for fpext vf32 to v2f64 9871 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 9872 9873 assert(Op.getOpcode() == ISD::FP_EXTEND && 9874 "Should only be called for ISD::FP_EXTEND"); 9875 9876 // We only want to custom lower an extend from v2f32 to v2f64. 9877 if (Op.getValueType() != MVT::v2f64 || 9878 Op.getOperand(0).getValueType() != MVT::v2f32) 9879 return SDValue(); 9880 9881 SDLoc dl(Op); 9882 SDValue Op0 = Op.getOperand(0); 9883 9884 switch (Op0.getOpcode()) { 9885 default: 9886 return SDValue(); 9887 case ISD::FADD: 9888 case ISD::FMUL: 9889 case ISD::FSUB: { 9890 SDValue NewLoad[2]; 9891 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 9892 // Ensure both input are loads. 9893 SDValue LdOp = Op0.getOperand(i); 9894 if (LdOp.getOpcode() != ISD::LOAD) 9895 return SDValue(); 9896 // Generate new load node. 9897 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 9898 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9899 NewLoad[i] = 9900 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9901 DAG.getVTList(MVT::v4f32, MVT::Other), 9902 LoadOps, LD->getMemoryVT(), 9903 LD->getMemOperand()); 9904 } 9905 SDValue NewOp = DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, 9906 NewLoad[0], NewLoad[1], 9907 Op0.getNode()->getFlags()); 9908 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewOp); 9909 } 9910 case ISD::LOAD: { 9911 LoadSDNode *LD = cast<LoadSDNode>(Op0); 9912 SDValue LoadOps[] = { LD->getChain(), LD->getBasePtr() }; 9913 SDValue NewLd = 9914 DAG.getMemIntrinsicNode(PPCISD::LD_VSX_LH, dl, 9915 DAG.getVTList(MVT::v4f32, MVT::Other), 9916 LoadOps, LD->getMemoryVT(), LD->getMemOperand()); 9917 return DAG.getNode(PPCISD::FP_EXTEND_LH, dl, MVT::v2f64, NewLd); 9918 } 9919 } 9920 llvm_unreachable("ERROR:Should return for all cases within swtich."); 9921 } 9922 9923 /// LowerOperation - Provide custom lowering hooks for some operations. 9924 /// 9925 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9926 switch (Op.getOpcode()) { 9927 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 9928 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 9929 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 9930 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 9931 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 9932 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 9933 case ISD::SETCC: return LowerSETCC(Op, DAG); 9934 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 9935 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 9936 9937 // Variable argument lowering. 9938 case ISD::VASTART: return LowerVASTART(Op, DAG); 9939 case ISD::VAARG: return LowerVAARG(Op, DAG); 9940 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 9941 9942 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 9943 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 9944 case ISD::GET_DYNAMIC_AREA_OFFSET: 9945 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 9946 9947 // Exception handling lowering. 9948 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 9949 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 9950 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 9951 9952 case ISD::LOAD: return LowerLOAD(Op, DAG); 9953 case ISD::STORE: return LowerSTORE(Op, DAG); 9954 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 9955 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 9956 case ISD::FP_TO_UINT: 9957 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 9958 case ISD::UINT_TO_FP: 9959 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 9960 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 9961 9962 // Lower 64-bit shifts. 9963 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 9964 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 9965 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 9966 9967 // Vector-related lowering. 9968 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 9969 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 9970 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 9971 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 9972 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 9973 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 9974 case ISD::MUL: return LowerMUL(Op, DAG); 9975 case ISD::ABS: return LowerABS(Op, DAG); 9976 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 9977 9978 // For counter-based loop handling. 9979 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 9980 9981 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 9982 9983 // Frame & Return address. 9984 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 9985 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 9986 9987 case ISD::INTRINSIC_VOID: 9988 return LowerINTRINSIC_VOID(Op, DAG); 9989 case ISD::SREM: 9990 case ISD::UREM: 9991 return LowerREM(Op, DAG); 9992 case ISD::BSWAP: 9993 return LowerBSWAP(Op, DAG); 9994 case ISD::ATOMIC_CMP_SWAP: 9995 return LowerATOMIC_CMP_SWAP(Op, DAG); 9996 } 9997 } 9998 9999 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10000 SmallVectorImpl<SDValue>&Results, 10001 SelectionDAG &DAG) const { 10002 SDLoc dl(N); 10003 switch (N->getOpcode()) { 10004 default: 10005 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10006 case ISD::READCYCLECOUNTER: { 10007 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10008 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10009 10010 Results.push_back(RTB); 10011 Results.push_back(RTB.getValue(1)); 10012 Results.push_back(RTB.getValue(2)); 10013 break; 10014 } 10015 case ISD::INTRINSIC_W_CHAIN: { 10016 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10017 Intrinsic::loop_decrement) 10018 break; 10019 10020 assert(N->getValueType(0) == MVT::i1 && 10021 "Unexpected result type for CTR decrement intrinsic"); 10022 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10023 N->getValueType(0)); 10024 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10025 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10026 N->getOperand(1)); 10027 10028 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10029 Results.push_back(NewInt.getValue(1)); 10030 break; 10031 } 10032 case ISD::VAARG: { 10033 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10034 return; 10035 10036 EVT VT = N->getValueType(0); 10037 10038 if (VT == MVT::i64) { 10039 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10040 10041 Results.push_back(NewNode); 10042 Results.push_back(NewNode.getValue(1)); 10043 } 10044 return; 10045 } 10046 case ISD::FP_TO_SINT: 10047 case ISD::FP_TO_UINT: 10048 // LowerFP_TO_INT() can only handle f32 and f64. 10049 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10050 return; 10051 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10052 return; 10053 case ISD::TRUNCATE: { 10054 EVT TrgVT = N->getValueType(0); 10055 if (TrgVT.isVector() && 10056 isOperationCustom(N->getOpcode(), TrgVT) && 10057 N->getOperand(0).getValueType().getSizeInBits() <= 128) 10058 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10059 return; 10060 } 10061 case ISD::BITCAST: 10062 // Don't handle bitcast here. 10063 return; 10064 } 10065 } 10066 10067 //===----------------------------------------------------------------------===// 10068 // Other Lowering Code 10069 //===----------------------------------------------------------------------===// 10070 10071 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10072 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10073 Function *Func = Intrinsic::getDeclaration(M, Id); 10074 return Builder.CreateCall(Func, {}); 10075 } 10076 10077 // The mappings for emitLeading/TrailingFence is taken from 10078 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10079 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10080 Instruction *Inst, 10081 AtomicOrdering Ord) const { 10082 if (Ord == AtomicOrdering::SequentiallyConsistent) 10083 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10084 if (isReleaseOrStronger(Ord)) 10085 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10086 return nullptr; 10087 } 10088 10089 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10090 Instruction *Inst, 10091 AtomicOrdering Ord) const { 10092 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10093 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10094 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10095 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10096 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10097 return Builder.CreateCall( 10098 Intrinsic::getDeclaration( 10099 Builder.GetInsertBlock()->getParent()->getParent(), 10100 Intrinsic::ppc_cfence, {Inst->getType()}), 10101 {Inst}); 10102 // FIXME: Can use isync for rmw operation. 10103 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10104 } 10105 return nullptr; 10106 } 10107 10108 MachineBasicBlock * 10109 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10110 unsigned AtomicSize, 10111 unsigned BinOpcode, 10112 unsigned CmpOpcode, 10113 unsigned CmpPred) const { 10114 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10115 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10116 10117 auto LoadMnemonic = PPC::LDARX; 10118 auto StoreMnemonic = PPC::STDCX; 10119 switch (AtomicSize) { 10120 default: 10121 llvm_unreachable("Unexpected size of atomic entity"); 10122 case 1: 10123 LoadMnemonic = PPC::LBARX; 10124 StoreMnemonic = PPC::STBCX; 10125 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10126 break; 10127 case 2: 10128 LoadMnemonic = PPC::LHARX; 10129 StoreMnemonic = PPC::STHCX; 10130 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10131 break; 10132 case 4: 10133 LoadMnemonic = PPC::LWARX; 10134 StoreMnemonic = PPC::STWCX; 10135 break; 10136 case 8: 10137 LoadMnemonic = PPC::LDARX; 10138 StoreMnemonic = PPC::STDCX; 10139 break; 10140 } 10141 10142 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10143 MachineFunction *F = BB->getParent(); 10144 MachineFunction::iterator It = ++BB->getIterator(); 10145 10146 Register dest = MI.getOperand(0).getReg(); 10147 Register ptrA = MI.getOperand(1).getReg(); 10148 Register ptrB = MI.getOperand(2).getReg(); 10149 Register incr = MI.getOperand(3).getReg(); 10150 DebugLoc dl = MI.getDebugLoc(); 10151 10152 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10153 MachineBasicBlock *loop2MBB = 10154 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10155 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10156 F->insert(It, loopMBB); 10157 if (CmpOpcode) 10158 F->insert(It, loop2MBB); 10159 F->insert(It, exitMBB); 10160 exitMBB->splice(exitMBB->begin(), BB, 10161 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10162 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10163 10164 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10165 Register TmpReg = (!BinOpcode) ? incr : 10166 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10167 : &PPC::GPRCRegClass); 10168 10169 // thisMBB: 10170 // ... 10171 // fallthrough --> loopMBB 10172 BB->addSuccessor(loopMBB); 10173 10174 // loopMBB: 10175 // l[wd]arx dest, ptr 10176 // add r0, dest, incr 10177 // st[wd]cx. r0, ptr 10178 // bne- loopMBB 10179 // fallthrough --> exitMBB 10180 10181 // For max/min... 10182 // loopMBB: 10183 // l[wd]arx dest, ptr 10184 // cmpl?[wd] incr, dest 10185 // bgt exitMBB 10186 // loop2MBB: 10187 // st[wd]cx. dest, ptr 10188 // bne- loopMBB 10189 // fallthrough --> exitMBB 10190 10191 BB = loopMBB; 10192 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10193 .addReg(ptrA).addReg(ptrB); 10194 if (BinOpcode) 10195 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10196 if (CmpOpcode) { 10197 // Signed comparisons of byte or halfword values must be sign-extended. 10198 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10199 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10200 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10201 ExtReg).addReg(dest); 10202 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10203 .addReg(incr).addReg(ExtReg); 10204 } else 10205 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10206 .addReg(incr).addReg(dest); 10207 10208 BuildMI(BB, dl, TII->get(PPC::BCC)) 10209 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10210 BB->addSuccessor(loop2MBB); 10211 BB->addSuccessor(exitMBB); 10212 BB = loop2MBB; 10213 } 10214 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10215 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10216 BuildMI(BB, dl, TII->get(PPC::BCC)) 10217 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10218 BB->addSuccessor(loopMBB); 10219 BB->addSuccessor(exitMBB); 10220 10221 // exitMBB: 10222 // ... 10223 BB = exitMBB; 10224 return BB; 10225 } 10226 10227 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10228 MachineInstr &MI, MachineBasicBlock *BB, 10229 bool is8bit, // operation 10230 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10231 // If we support part-word atomic mnemonics, just use them 10232 if (Subtarget.hasPartwordAtomics()) 10233 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10234 CmpPred); 10235 10236 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10237 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10238 // In 64 bit mode we have to use 64 bits for addresses, even though the 10239 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10240 // registers without caring whether they're 32 or 64, but here we're 10241 // doing actual arithmetic on the addresses. 10242 bool is64bit = Subtarget.isPPC64(); 10243 bool isLittleEndian = Subtarget.isLittleEndian(); 10244 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10245 10246 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10247 MachineFunction *F = BB->getParent(); 10248 MachineFunction::iterator It = ++BB->getIterator(); 10249 10250 unsigned dest = MI.getOperand(0).getReg(); 10251 unsigned ptrA = MI.getOperand(1).getReg(); 10252 unsigned ptrB = MI.getOperand(2).getReg(); 10253 unsigned incr = MI.getOperand(3).getReg(); 10254 DebugLoc dl = MI.getDebugLoc(); 10255 10256 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10257 MachineBasicBlock *loop2MBB = 10258 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10259 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10260 F->insert(It, loopMBB); 10261 if (CmpOpcode) 10262 F->insert(It, loop2MBB); 10263 F->insert(It, exitMBB); 10264 exitMBB->splice(exitMBB->begin(), BB, 10265 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10266 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10267 10268 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10269 const TargetRegisterClass *RC = 10270 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10271 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10272 10273 Register PtrReg = RegInfo.createVirtualRegister(RC); 10274 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10275 Register ShiftReg = 10276 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10277 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10278 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10279 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10280 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10281 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10282 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10283 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10284 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10285 Register Ptr1Reg; 10286 Register TmpReg = 10287 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10288 10289 // thisMBB: 10290 // ... 10291 // fallthrough --> loopMBB 10292 BB->addSuccessor(loopMBB); 10293 10294 // The 4-byte load must be aligned, while a char or short may be 10295 // anywhere in the word. Hence all this nasty bookkeeping code. 10296 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10297 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10298 // xori shift, shift1, 24 [16] 10299 // rlwinm ptr, ptr1, 0, 0, 29 10300 // slw incr2, incr, shift 10301 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10302 // slw mask, mask2, shift 10303 // loopMBB: 10304 // lwarx tmpDest, ptr 10305 // add tmp, tmpDest, incr2 10306 // andc tmp2, tmpDest, mask 10307 // and tmp3, tmp, mask 10308 // or tmp4, tmp3, tmp2 10309 // stwcx. tmp4, ptr 10310 // bne- loopMBB 10311 // fallthrough --> exitMBB 10312 // srw dest, tmpDest, shift 10313 if (ptrA != ZeroReg) { 10314 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10315 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10316 .addReg(ptrA) 10317 .addReg(ptrB); 10318 } else { 10319 Ptr1Reg = ptrB; 10320 } 10321 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10322 // mode. 10323 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10324 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10325 .addImm(3) 10326 .addImm(27) 10327 .addImm(is8bit ? 28 : 27); 10328 if (!isLittleEndian) 10329 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10330 .addReg(Shift1Reg) 10331 .addImm(is8bit ? 24 : 16); 10332 if (is64bit) 10333 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10334 .addReg(Ptr1Reg) 10335 .addImm(0) 10336 .addImm(61); 10337 else 10338 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10339 .addReg(Ptr1Reg) 10340 .addImm(0) 10341 .addImm(0) 10342 .addImm(29); 10343 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10344 if (is8bit) 10345 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10346 else { 10347 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10348 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10349 .addReg(Mask3Reg) 10350 .addImm(65535); 10351 } 10352 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10353 .addReg(Mask2Reg) 10354 .addReg(ShiftReg); 10355 10356 BB = loopMBB; 10357 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10358 .addReg(ZeroReg) 10359 .addReg(PtrReg); 10360 if (BinOpcode) 10361 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10362 .addReg(Incr2Reg) 10363 .addReg(TmpDestReg); 10364 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10365 .addReg(TmpDestReg) 10366 .addReg(MaskReg); 10367 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10368 if (CmpOpcode) { 10369 // For unsigned comparisons, we can directly compare the shifted values. 10370 // For signed comparisons we shift and sign extend. 10371 unsigned SReg = RegInfo.createVirtualRegister(GPRC); 10372 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10373 .addReg(TmpDestReg) 10374 .addReg(MaskReg); 10375 unsigned ValueReg = SReg; 10376 unsigned CmpReg = Incr2Reg; 10377 if (CmpOpcode == PPC::CMPW) { 10378 ValueReg = RegInfo.createVirtualRegister(GPRC); 10379 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10380 .addReg(SReg) 10381 .addReg(ShiftReg); 10382 unsigned ValueSReg = RegInfo.createVirtualRegister(GPRC); 10383 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10384 .addReg(ValueReg); 10385 ValueReg = ValueSReg; 10386 CmpReg = incr; 10387 } 10388 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10389 .addReg(CmpReg) 10390 .addReg(ValueReg); 10391 BuildMI(BB, dl, TII->get(PPC::BCC)) 10392 .addImm(CmpPred) 10393 .addReg(PPC::CR0) 10394 .addMBB(exitMBB); 10395 BB->addSuccessor(loop2MBB); 10396 BB->addSuccessor(exitMBB); 10397 BB = loop2MBB; 10398 } 10399 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10400 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10401 .addReg(Tmp4Reg) 10402 .addReg(ZeroReg) 10403 .addReg(PtrReg); 10404 BuildMI(BB, dl, TII->get(PPC::BCC)) 10405 .addImm(PPC::PRED_NE) 10406 .addReg(PPC::CR0) 10407 .addMBB(loopMBB); 10408 BB->addSuccessor(loopMBB); 10409 BB->addSuccessor(exitMBB); 10410 10411 // exitMBB: 10412 // ... 10413 BB = exitMBB; 10414 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10415 .addReg(TmpDestReg) 10416 .addReg(ShiftReg); 10417 return BB; 10418 } 10419 10420 llvm::MachineBasicBlock * 10421 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10422 MachineBasicBlock *MBB) const { 10423 DebugLoc DL = MI.getDebugLoc(); 10424 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10425 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10426 10427 MachineFunction *MF = MBB->getParent(); 10428 MachineRegisterInfo &MRI = MF->getRegInfo(); 10429 10430 const BasicBlock *BB = MBB->getBasicBlock(); 10431 MachineFunction::iterator I = ++MBB->getIterator(); 10432 10433 unsigned DstReg = MI.getOperand(0).getReg(); 10434 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10435 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10436 unsigned mainDstReg = MRI.createVirtualRegister(RC); 10437 unsigned restoreDstReg = MRI.createVirtualRegister(RC); 10438 10439 MVT PVT = getPointerTy(MF->getDataLayout()); 10440 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10441 "Invalid Pointer Size!"); 10442 // For v = setjmp(buf), we generate 10443 // 10444 // thisMBB: 10445 // SjLjSetup mainMBB 10446 // bl mainMBB 10447 // v_restore = 1 10448 // b sinkMBB 10449 // 10450 // mainMBB: 10451 // buf[LabelOffset] = LR 10452 // v_main = 0 10453 // 10454 // sinkMBB: 10455 // v = phi(main, restore) 10456 // 10457 10458 MachineBasicBlock *thisMBB = MBB; 10459 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10460 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10461 MF->insert(I, mainMBB); 10462 MF->insert(I, sinkMBB); 10463 10464 MachineInstrBuilder MIB; 10465 10466 // Transfer the remainder of BB and its successor edges to sinkMBB. 10467 sinkMBB->splice(sinkMBB->begin(), MBB, 10468 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10469 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10470 10471 // Note that the structure of the jmp_buf used here is not compatible 10472 // with that used by libc, and is not designed to be. Specifically, it 10473 // stores only those 'reserved' registers that LLVM does not otherwise 10474 // understand how to spill. Also, by convention, by the time this 10475 // intrinsic is called, Clang has already stored the frame address in the 10476 // first slot of the buffer and stack address in the third. Following the 10477 // X86 target code, we'll store the jump address in the second slot. We also 10478 // need to save the TOC pointer (R2) to handle jumps between shared 10479 // libraries, and that will be stored in the fourth slot. The thread 10480 // identifier (R13) is not affected. 10481 10482 // thisMBB: 10483 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10484 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10485 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10486 10487 // Prepare IP either in reg. 10488 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10489 unsigned LabelReg = MRI.createVirtualRegister(PtrRC); 10490 unsigned BufReg = MI.getOperand(1).getReg(); 10491 10492 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { 10493 setUsesTOCBasePtr(*MBB->getParent()); 10494 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10495 .addReg(PPC::X2) 10496 .addImm(TOCOffset) 10497 .addReg(BufReg) 10498 .cloneMemRefs(MI); 10499 } 10500 10501 // Naked functions never have a base pointer, and so we use r1. For all 10502 // other functions, this decision must be delayed until during PEI. 10503 unsigned BaseReg; 10504 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10505 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10506 else 10507 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10508 10509 MIB = BuildMI(*thisMBB, MI, DL, 10510 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 10511 .addReg(BaseReg) 10512 .addImm(BPOffset) 10513 .addReg(BufReg) 10514 .cloneMemRefs(MI); 10515 10516 // Setup 10517 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 10518 MIB.addRegMask(TRI->getNoPreservedMask()); 10519 10520 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 10521 10522 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 10523 .addMBB(mainMBB); 10524 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 10525 10526 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 10527 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 10528 10529 // mainMBB: 10530 // mainDstReg = 0 10531 MIB = 10532 BuildMI(mainMBB, DL, 10533 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 10534 10535 // Store IP 10536 if (Subtarget.isPPC64()) { 10537 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 10538 .addReg(LabelReg) 10539 .addImm(LabelOffset) 10540 .addReg(BufReg); 10541 } else { 10542 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 10543 .addReg(LabelReg) 10544 .addImm(LabelOffset) 10545 .addReg(BufReg); 10546 } 10547 MIB.cloneMemRefs(MI); 10548 10549 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 10550 mainMBB->addSuccessor(sinkMBB); 10551 10552 // sinkMBB: 10553 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 10554 TII->get(PPC::PHI), DstReg) 10555 .addReg(mainDstReg).addMBB(mainMBB) 10556 .addReg(restoreDstReg).addMBB(thisMBB); 10557 10558 MI.eraseFromParent(); 10559 return sinkMBB; 10560 } 10561 10562 MachineBasicBlock * 10563 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 10564 MachineBasicBlock *MBB) const { 10565 DebugLoc DL = MI.getDebugLoc(); 10566 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10567 10568 MachineFunction *MF = MBB->getParent(); 10569 MachineRegisterInfo &MRI = MF->getRegInfo(); 10570 10571 MVT PVT = getPointerTy(MF->getDataLayout()); 10572 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10573 "Invalid Pointer Size!"); 10574 10575 const TargetRegisterClass *RC = 10576 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10577 unsigned Tmp = MRI.createVirtualRegister(RC); 10578 // Since FP is only updated here but NOT referenced, it's treated as GPR. 10579 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 10580 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 10581 unsigned BP = 10582 (PVT == MVT::i64) 10583 ? PPC::X30 10584 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 10585 : PPC::R30); 10586 10587 MachineInstrBuilder MIB; 10588 10589 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10590 const int64_t SPOffset = 2 * PVT.getStoreSize(); 10591 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10592 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10593 10594 unsigned BufReg = MI.getOperand(0).getReg(); 10595 10596 // Reload FP (the jumped-to function may not have had a 10597 // frame pointer, and if so, then its r31 will be restored 10598 // as necessary). 10599 if (PVT == MVT::i64) { 10600 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 10601 .addImm(0) 10602 .addReg(BufReg); 10603 } else { 10604 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 10605 .addImm(0) 10606 .addReg(BufReg); 10607 } 10608 MIB.cloneMemRefs(MI); 10609 10610 // Reload IP 10611 if (PVT == MVT::i64) { 10612 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 10613 .addImm(LabelOffset) 10614 .addReg(BufReg); 10615 } else { 10616 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 10617 .addImm(LabelOffset) 10618 .addReg(BufReg); 10619 } 10620 MIB.cloneMemRefs(MI); 10621 10622 // Reload SP 10623 if (PVT == MVT::i64) { 10624 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 10625 .addImm(SPOffset) 10626 .addReg(BufReg); 10627 } else { 10628 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 10629 .addImm(SPOffset) 10630 .addReg(BufReg); 10631 } 10632 MIB.cloneMemRefs(MI); 10633 10634 // Reload BP 10635 if (PVT == MVT::i64) { 10636 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 10637 .addImm(BPOffset) 10638 .addReg(BufReg); 10639 } else { 10640 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 10641 .addImm(BPOffset) 10642 .addReg(BufReg); 10643 } 10644 MIB.cloneMemRefs(MI); 10645 10646 // Reload TOC 10647 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 10648 setUsesTOCBasePtr(*MBB->getParent()); 10649 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 10650 .addImm(TOCOffset) 10651 .addReg(BufReg) 10652 .cloneMemRefs(MI); 10653 } 10654 10655 // Jump 10656 BuildMI(*MBB, MI, DL, 10657 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 10658 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 10659 10660 MI.eraseFromParent(); 10661 return MBB; 10662 } 10663 10664 MachineBasicBlock * 10665 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10666 MachineBasicBlock *BB) const { 10667 if (MI.getOpcode() == TargetOpcode::STACKMAP || 10668 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10669 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && 10670 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 10671 // Call lowering should have added an r2 operand to indicate a dependence 10672 // on the TOC base pointer value. It can't however, because there is no 10673 // way to mark the dependence as implicit there, and so the stackmap code 10674 // will confuse it with a regular operand. Instead, add the dependence 10675 // here. 10676 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 10677 } 10678 10679 return emitPatchPoint(MI, BB); 10680 } 10681 10682 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 10683 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 10684 return emitEHSjLjSetJmp(MI, BB); 10685 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 10686 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 10687 return emitEHSjLjLongJmp(MI, BB); 10688 } 10689 10690 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10691 10692 // To "insert" these instructions we actually have to insert their 10693 // control-flow patterns. 10694 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10695 MachineFunction::iterator It = ++BB->getIterator(); 10696 10697 MachineFunction *F = BB->getParent(); 10698 10699 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10700 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 10701 MI.getOpcode() == PPC::SELECT_I8) { 10702 SmallVector<MachineOperand, 2> Cond; 10703 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10704 MI.getOpcode() == PPC::SELECT_CC_I8) 10705 Cond.push_back(MI.getOperand(4)); 10706 else 10707 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 10708 Cond.push_back(MI.getOperand(1)); 10709 10710 DebugLoc dl = MI.getDebugLoc(); 10711 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 10712 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 10713 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 || 10714 MI.getOpcode() == PPC::SELECT_CC_I8 || 10715 MI.getOpcode() == PPC::SELECT_CC_F4 || 10716 MI.getOpcode() == PPC::SELECT_CC_F8 || 10717 MI.getOpcode() == PPC::SELECT_CC_F16 || 10718 MI.getOpcode() == PPC::SELECT_CC_QFRC || 10719 MI.getOpcode() == PPC::SELECT_CC_QSRC || 10720 MI.getOpcode() == PPC::SELECT_CC_QBRC || 10721 MI.getOpcode() == PPC::SELECT_CC_VRRC || 10722 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 10723 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 10724 MI.getOpcode() == PPC::SELECT_CC_VSRC || 10725 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 10726 MI.getOpcode() == PPC::SELECT_CC_SPE || 10727 MI.getOpcode() == PPC::SELECT_I4 || 10728 MI.getOpcode() == PPC::SELECT_I8 || 10729 MI.getOpcode() == PPC::SELECT_F4 || 10730 MI.getOpcode() == PPC::SELECT_F8 || 10731 MI.getOpcode() == PPC::SELECT_F16 || 10732 MI.getOpcode() == PPC::SELECT_QFRC || 10733 MI.getOpcode() == PPC::SELECT_QSRC || 10734 MI.getOpcode() == PPC::SELECT_QBRC || 10735 MI.getOpcode() == PPC::SELECT_SPE || 10736 MI.getOpcode() == PPC::SELECT_SPE4 || 10737 MI.getOpcode() == PPC::SELECT_VRRC || 10738 MI.getOpcode() == PPC::SELECT_VSFRC || 10739 MI.getOpcode() == PPC::SELECT_VSSRC || 10740 MI.getOpcode() == PPC::SELECT_VSRC) { 10741 // The incoming instruction knows the destination vreg to set, the 10742 // condition code register to branch on, the true/false values to 10743 // select between, and a branch opcode to use. 10744 10745 // thisMBB: 10746 // ... 10747 // TrueVal = ... 10748 // cmpTY ccX, r1, r2 10749 // bCC copy1MBB 10750 // fallthrough --> copy0MBB 10751 MachineBasicBlock *thisMBB = BB; 10752 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 10753 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10754 DebugLoc dl = MI.getDebugLoc(); 10755 F->insert(It, copy0MBB); 10756 F->insert(It, sinkMBB); 10757 10758 // Transfer the remainder of BB and its successor edges to sinkMBB. 10759 sinkMBB->splice(sinkMBB->begin(), BB, 10760 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10761 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10762 10763 // Next, add the true and fallthrough blocks as its successors. 10764 BB->addSuccessor(copy0MBB); 10765 BB->addSuccessor(sinkMBB); 10766 10767 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 10768 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 10769 MI.getOpcode() == PPC::SELECT_F16 || 10770 MI.getOpcode() == PPC::SELECT_SPE4 || 10771 MI.getOpcode() == PPC::SELECT_SPE || 10772 MI.getOpcode() == PPC::SELECT_QFRC || 10773 MI.getOpcode() == PPC::SELECT_QSRC || 10774 MI.getOpcode() == PPC::SELECT_QBRC || 10775 MI.getOpcode() == PPC::SELECT_VRRC || 10776 MI.getOpcode() == PPC::SELECT_VSFRC || 10777 MI.getOpcode() == PPC::SELECT_VSSRC || 10778 MI.getOpcode() == PPC::SELECT_VSRC) { 10779 BuildMI(BB, dl, TII->get(PPC::BC)) 10780 .addReg(MI.getOperand(1).getReg()) 10781 .addMBB(sinkMBB); 10782 } else { 10783 unsigned SelectPred = MI.getOperand(4).getImm(); 10784 BuildMI(BB, dl, TII->get(PPC::BCC)) 10785 .addImm(SelectPred) 10786 .addReg(MI.getOperand(1).getReg()) 10787 .addMBB(sinkMBB); 10788 } 10789 10790 // copy0MBB: 10791 // %FalseValue = ... 10792 // # fallthrough to sinkMBB 10793 BB = copy0MBB; 10794 10795 // Update machine-CFG edges 10796 BB->addSuccessor(sinkMBB); 10797 10798 // sinkMBB: 10799 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 10800 // ... 10801 BB = sinkMBB; 10802 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 10803 .addReg(MI.getOperand(3).getReg()) 10804 .addMBB(copy0MBB) 10805 .addReg(MI.getOperand(2).getReg()) 10806 .addMBB(thisMBB); 10807 } else if (MI.getOpcode() == PPC::ReadTB) { 10808 // To read the 64-bit time-base register on a 32-bit target, we read the 10809 // two halves. Should the counter have wrapped while it was being read, we 10810 // need to try again. 10811 // ... 10812 // readLoop: 10813 // mfspr Rx,TBU # load from TBU 10814 // mfspr Ry,TB # load from TB 10815 // mfspr Rz,TBU # load from TBU 10816 // cmpw crX,Rx,Rz # check if 'old'='new' 10817 // bne readLoop # branch if they're not equal 10818 // ... 10819 10820 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 10821 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 10822 DebugLoc dl = MI.getDebugLoc(); 10823 F->insert(It, readMBB); 10824 F->insert(It, sinkMBB); 10825 10826 // Transfer the remainder of BB and its successor edges to sinkMBB. 10827 sinkMBB->splice(sinkMBB->begin(), BB, 10828 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10829 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 10830 10831 BB->addSuccessor(readMBB); 10832 BB = readMBB; 10833 10834 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10835 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10836 unsigned LoReg = MI.getOperand(0).getReg(); 10837 unsigned HiReg = MI.getOperand(1).getReg(); 10838 10839 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 10840 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 10841 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 10842 10843 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 10844 10845 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 10846 .addReg(HiReg) 10847 .addReg(ReadAgainReg); 10848 BuildMI(BB, dl, TII->get(PPC::BCC)) 10849 .addImm(PPC::PRED_NE) 10850 .addReg(CmpReg) 10851 .addMBB(readMBB); 10852 10853 BB->addSuccessor(readMBB); 10854 BB->addSuccessor(sinkMBB); 10855 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 10856 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 10857 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 10858 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 10859 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 10860 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 10861 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 10862 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 10863 10864 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 10865 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 10866 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 10867 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 10868 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 10869 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 10870 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 10871 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 10872 10873 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 10874 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 10875 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 10876 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 10877 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 10878 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 10879 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 10880 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 10881 10882 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 10883 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 10884 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 10885 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 10886 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 10887 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 10888 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 10889 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 10890 10891 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 10892 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 10893 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 10894 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 10895 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 10896 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 10897 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 10898 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 10899 10900 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 10901 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 10902 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 10903 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 10904 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 10905 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 10906 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 10907 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 10908 10909 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 10910 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 10911 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 10912 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 10913 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 10914 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 10915 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 10916 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 10917 10918 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 10919 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 10920 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 10921 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 10922 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 10923 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 10924 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 10925 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 10926 10927 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 10928 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 10929 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 10930 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 10931 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 10932 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 10933 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 10934 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 10935 10936 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 10937 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 10938 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 10939 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 10940 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 10941 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 10942 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 10943 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 10944 10945 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 10946 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 10947 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 10948 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 10949 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 10950 BB = EmitAtomicBinary(MI, BB, 4, 0); 10951 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 10952 BB = EmitAtomicBinary(MI, BB, 8, 0); 10953 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 10954 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 10955 (Subtarget.hasPartwordAtomics() && 10956 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 10957 (Subtarget.hasPartwordAtomics() && 10958 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 10959 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 10960 10961 auto LoadMnemonic = PPC::LDARX; 10962 auto StoreMnemonic = PPC::STDCX; 10963 switch (MI.getOpcode()) { 10964 default: 10965 llvm_unreachable("Compare and swap of unknown size"); 10966 case PPC::ATOMIC_CMP_SWAP_I8: 10967 LoadMnemonic = PPC::LBARX; 10968 StoreMnemonic = PPC::STBCX; 10969 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10970 break; 10971 case PPC::ATOMIC_CMP_SWAP_I16: 10972 LoadMnemonic = PPC::LHARX; 10973 StoreMnemonic = PPC::STHCX; 10974 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 10975 break; 10976 case PPC::ATOMIC_CMP_SWAP_I32: 10977 LoadMnemonic = PPC::LWARX; 10978 StoreMnemonic = PPC::STWCX; 10979 break; 10980 case PPC::ATOMIC_CMP_SWAP_I64: 10981 LoadMnemonic = PPC::LDARX; 10982 StoreMnemonic = PPC::STDCX; 10983 break; 10984 } 10985 unsigned dest = MI.getOperand(0).getReg(); 10986 unsigned ptrA = MI.getOperand(1).getReg(); 10987 unsigned ptrB = MI.getOperand(2).getReg(); 10988 unsigned oldval = MI.getOperand(3).getReg(); 10989 unsigned newval = MI.getOperand(4).getReg(); 10990 DebugLoc dl = MI.getDebugLoc(); 10991 10992 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 10993 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 10994 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 10995 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10996 F->insert(It, loop1MBB); 10997 F->insert(It, loop2MBB); 10998 F->insert(It, midMBB); 10999 F->insert(It, exitMBB); 11000 exitMBB->splice(exitMBB->begin(), BB, 11001 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11002 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11003 11004 // thisMBB: 11005 // ... 11006 // fallthrough --> loopMBB 11007 BB->addSuccessor(loop1MBB); 11008 11009 // loop1MBB: 11010 // l[bhwd]arx dest, ptr 11011 // cmp[wd] dest, oldval 11012 // bne- midMBB 11013 // loop2MBB: 11014 // st[bhwd]cx. newval, ptr 11015 // bne- loopMBB 11016 // b exitBB 11017 // midMBB: 11018 // st[bhwd]cx. dest, ptr 11019 // exitBB: 11020 BB = loop1MBB; 11021 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11022 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11023 .addReg(oldval) 11024 .addReg(dest); 11025 BuildMI(BB, dl, TII->get(PPC::BCC)) 11026 .addImm(PPC::PRED_NE) 11027 .addReg(PPC::CR0) 11028 .addMBB(midMBB); 11029 BB->addSuccessor(loop2MBB); 11030 BB->addSuccessor(midMBB); 11031 11032 BB = loop2MBB; 11033 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11034 .addReg(newval) 11035 .addReg(ptrA) 11036 .addReg(ptrB); 11037 BuildMI(BB, dl, TII->get(PPC::BCC)) 11038 .addImm(PPC::PRED_NE) 11039 .addReg(PPC::CR0) 11040 .addMBB(loop1MBB); 11041 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11042 BB->addSuccessor(loop1MBB); 11043 BB->addSuccessor(exitMBB); 11044 11045 BB = midMBB; 11046 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11047 .addReg(dest) 11048 .addReg(ptrA) 11049 .addReg(ptrB); 11050 BB->addSuccessor(exitMBB); 11051 11052 // exitMBB: 11053 // ... 11054 BB = exitMBB; 11055 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11056 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11057 // We must use 64-bit registers for addresses when targeting 64-bit, 11058 // since we're actually doing arithmetic on them. Other registers 11059 // can be 32-bit. 11060 bool is64bit = Subtarget.isPPC64(); 11061 bool isLittleEndian = Subtarget.isLittleEndian(); 11062 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11063 11064 unsigned dest = MI.getOperand(0).getReg(); 11065 unsigned ptrA = MI.getOperand(1).getReg(); 11066 unsigned ptrB = MI.getOperand(2).getReg(); 11067 unsigned oldval = MI.getOperand(3).getReg(); 11068 unsigned newval = MI.getOperand(4).getReg(); 11069 DebugLoc dl = MI.getDebugLoc(); 11070 11071 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11072 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11073 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11074 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11075 F->insert(It, loop1MBB); 11076 F->insert(It, loop2MBB); 11077 F->insert(It, midMBB); 11078 F->insert(It, exitMBB); 11079 exitMBB->splice(exitMBB->begin(), BB, 11080 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11081 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11082 11083 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11084 const TargetRegisterClass *RC = 11085 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11086 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11087 11088 Register PtrReg = RegInfo.createVirtualRegister(RC); 11089 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11090 Register ShiftReg = 11091 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11092 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11093 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11094 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11095 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11096 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11097 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11098 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11099 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11100 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11101 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11102 Register Ptr1Reg; 11103 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11104 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11105 // thisMBB: 11106 // ... 11107 // fallthrough --> loopMBB 11108 BB->addSuccessor(loop1MBB); 11109 11110 // The 4-byte load must be aligned, while a char or short may be 11111 // anywhere in the word. Hence all this nasty bookkeeping code. 11112 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11113 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11114 // xori shift, shift1, 24 [16] 11115 // rlwinm ptr, ptr1, 0, 0, 29 11116 // slw newval2, newval, shift 11117 // slw oldval2, oldval,shift 11118 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11119 // slw mask, mask2, shift 11120 // and newval3, newval2, mask 11121 // and oldval3, oldval2, mask 11122 // loop1MBB: 11123 // lwarx tmpDest, ptr 11124 // and tmp, tmpDest, mask 11125 // cmpw tmp, oldval3 11126 // bne- midMBB 11127 // loop2MBB: 11128 // andc tmp2, tmpDest, mask 11129 // or tmp4, tmp2, newval3 11130 // stwcx. tmp4, ptr 11131 // bne- loop1MBB 11132 // b exitBB 11133 // midMBB: 11134 // stwcx. tmpDest, ptr 11135 // exitBB: 11136 // srw dest, tmpDest, shift 11137 if (ptrA != ZeroReg) { 11138 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11139 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11140 .addReg(ptrA) 11141 .addReg(ptrB); 11142 } else { 11143 Ptr1Reg = ptrB; 11144 } 11145 11146 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11147 // mode. 11148 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11149 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11150 .addImm(3) 11151 .addImm(27) 11152 .addImm(is8bit ? 28 : 27); 11153 if (!isLittleEndian) 11154 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11155 .addReg(Shift1Reg) 11156 .addImm(is8bit ? 24 : 16); 11157 if (is64bit) 11158 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11159 .addReg(Ptr1Reg) 11160 .addImm(0) 11161 .addImm(61); 11162 else 11163 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11164 .addReg(Ptr1Reg) 11165 .addImm(0) 11166 .addImm(0) 11167 .addImm(29); 11168 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11169 .addReg(newval) 11170 .addReg(ShiftReg); 11171 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11172 .addReg(oldval) 11173 .addReg(ShiftReg); 11174 if (is8bit) 11175 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11176 else { 11177 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11178 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11179 .addReg(Mask3Reg) 11180 .addImm(65535); 11181 } 11182 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11183 .addReg(Mask2Reg) 11184 .addReg(ShiftReg); 11185 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11186 .addReg(NewVal2Reg) 11187 .addReg(MaskReg); 11188 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11189 .addReg(OldVal2Reg) 11190 .addReg(MaskReg); 11191 11192 BB = loop1MBB; 11193 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11194 .addReg(ZeroReg) 11195 .addReg(PtrReg); 11196 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11197 .addReg(TmpDestReg) 11198 .addReg(MaskReg); 11199 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11200 .addReg(TmpReg) 11201 .addReg(OldVal3Reg); 11202 BuildMI(BB, dl, TII->get(PPC::BCC)) 11203 .addImm(PPC::PRED_NE) 11204 .addReg(PPC::CR0) 11205 .addMBB(midMBB); 11206 BB->addSuccessor(loop2MBB); 11207 BB->addSuccessor(midMBB); 11208 11209 BB = loop2MBB; 11210 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11211 .addReg(TmpDestReg) 11212 .addReg(MaskReg); 11213 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11214 .addReg(Tmp2Reg) 11215 .addReg(NewVal3Reg); 11216 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11217 .addReg(Tmp4Reg) 11218 .addReg(ZeroReg) 11219 .addReg(PtrReg); 11220 BuildMI(BB, dl, TII->get(PPC::BCC)) 11221 .addImm(PPC::PRED_NE) 11222 .addReg(PPC::CR0) 11223 .addMBB(loop1MBB); 11224 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11225 BB->addSuccessor(loop1MBB); 11226 BB->addSuccessor(exitMBB); 11227 11228 BB = midMBB; 11229 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11230 .addReg(TmpDestReg) 11231 .addReg(ZeroReg) 11232 .addReg(PtrReg); 11233 BB->addSuccessor(exitMBB); 11234 11235 // exitMBB: 11236 // ... 11237 BB = exitMBB; 11238 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11239 .addReg(TmpReg) 11240 .addReg(ShiftReg); 11241 } else if (MI.getOpcode() == PPC::FADDrtz) { 11242 // This pseudo performs an FADD with rounding mode temporarily forced 11243 // to round-to-zero. We emit this via custom inserter since the FPSCR 11244 // is not modeled at the SelectionDAG level. 11245 unsigned Dest = MI.getOperand(0).getReg(); 11246 unsigned Src1 = MI.getOperand(1).getReg(); 11247 unsigned Src2 = MI.getOperand(2).getReg(); 11248 DebugLoc dl = MI.getDebugLoc(); 11249 11250 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11251 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11252 11253 // Save FPSCR value. 11254 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11255 11256 // Set rounding mode to round-to-zero. 11257 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11258 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11259 11260 // Perform addition. 11261 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11262 11263 // Restore FPSCR value. 11264 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11265 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11266 MI.getOpcode() == PPC::ANDIo_1_GT_BIT || 11267 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11268 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) { 11269 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 || 11270 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) 11271 ? PPC::ANDIo8 11272 : PPC::ANDIo; 11273 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT || 11274 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8); 11275 11276 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11277 unsigned Dest = RegInfo.createVirtualRegister( 11278 Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11279 11280 DebugLoc dl = MI.getDebugLoc(); 11281 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) 11282 .addReg(MI.getOperand(1).getReg()) 11283 .addImm(1); 11284 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), 11285 MI.getOperand(0).getReg()) 11286 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); 11287 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11288 DebugLoc Dl = MI.getDebugLoc(); 11289 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11290 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11291 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11292 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11293 MI.getOperand(0).getReg()) 11294 .addReg(CRReg); 11295 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11296 DebugLoc Dl = MI.getDebugLoc(); 11297 unsigned Imm = MI.getOperand(1).getImm(); 11298 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11299 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11300 MI.getOperand(0).getReg()) 11301 .addReg(PPC::CR0EQ); 11302 } else if (MI.getOpcode() == PPC::SETRNDi) { 11303 DebugLoc dl = MI.getDebugLoc(); 11304 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11305 11306 // Save FPSCR value. 11307 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11308 11309 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11310 // the following settings: 11311 // 00 Round to nearest 11312 // 01 Round to 0 11313 // 10 Round to +inf 11314 // 11 Round to -inf 11315 11316 // When the operand is immediate, using the two least significant bits of 11317 // the immediate to set the bits 62:63 of FPSCR. 11318 unsigned Mode = MI.getOperand(1).getImm(); 11319 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11320 .addImm(31); 11321 11322 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11323 .addImm(30); 11324 } else if (MI.getOpcode() == PPC::SETRND) { 11325 DebugLoc dl = MI.getDebugLoc(); 11326 11327 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11328 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11329 // If the target doesn't have DirectMove, we should use stack to do the 11330 // conversion, because the target doesn't have the instructions like mtvsrd 11331 // or mfvsrd to do this conversion directly. 11332 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11333 if (Subtarget.hasDirectMove()) { 11334 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11335 .addReg(SrcReg); 11336 } else { 11337 // Use stack to do the register copy. 11338 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11339 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11340 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11341 if (RC == &PPC::F8RCRegClass) { 11342 // Copy register from F8RCRegClass to G8RCRegclass. 11343 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11344 "Unsupported RegClass."); 11345 11346 StoreOp = PPC::STFD; 11347 LoadOp = PPC::LD; 11348 } else { 11349 // Copy register from G8RCRegClass to F8RCRegclass. 11350 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11351 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11352 "Unsupported RegClass."); 11353 } 11354 11355 MachineFrameInfo &MFI = F->getFrameInfo(); 11356 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11357 11358 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11359 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11360 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11361 MFI.getObjectAlignment(FrameIdx)); 11362 11363 // Store the SrcReg into the stack. 11364 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11365 .addReg(SrcReg) 11366 .addImm(0) 11367 .addFrameIndex(FrameIdx) 11368 .addMemOperand(MMOStore); 11369 11370 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11371 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11372 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11373 MFI.getObjectAlignment(FrameIdx)); 11374 11375 // Load from the stack where SrcReg is stored, and save to DestReg, 11376 // so we have done the RegClass conversion from RegClass::SrcReg to 11377 // RegClass::DestReg. 11378 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11379 .addImm(0) 11380 .addFrameIndex(FrameIdx) 11381 .addMemOperand(MMOLoad); 11382 } 11383 }; 11384 11385 unsigned OldFPSCRReg = MI.getOperand(0).getReg(); 11386 11387 // Save FPSCR value. 11388 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11389 11390 // When the operand is gprc register, use two least significant bits of the 11391 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11392 // 11393 // copy OldFPSCRTmpReg, OldFPSCRReg 11394 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11395 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11396 // copy NewFPSCRReg, NewFPSCRTmpReg 11397 // mtfsf 255, NewFPSCRReg 11398 MachineOperand SrcOp = MI.getOperand(1); 11399 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11400 unsigned OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11401 11402 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11403 11404 unsigned ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11405 unsigned ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11406 11407 // The first operand of INSERT_SUBREG should be a register which has 11408 // subregisters, we only care about its RegClass, so we should use an 11409 // IMPLICIT_DEF register. 11410 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11411 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11412 .addReg(ImDefReg) 11413 .add(SrcOp) 11414 .addImm(1); 11415 11416 unsigned NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11417 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11418 .addReg(OldFPSCRTmpReg) 11419 .addReg(ExtSrcReg) 11420 .addImm(0) 11421 .addImm(62); 11422 11423 unsigned NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11424 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11425 11426 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11427 // bits of FPSCR. 11428 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11429 .addImm(255) 11430 .addReg(NewFPSCRReg) 11431 .addImm(0) 11432 .addImm(0); 11433 } else { 11434 llvm_unreachable("Unexpected instr type to insert"); 11435 } 11436 11437 MI.eraseFromParent(); // The pseudo instruction is gone now. 11438 return BB; 11439 } 11440 11441 //===----------------------------------------------------------------------===// 11442 // Target Optimization Hooks 11443 //===----------------------------------------------------------------------===// 11444 11445 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11446 // For the estimates, convergence is quadratic, so we essentially double the 11447 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11448 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11449 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11450 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11451 if (VT.getScalarType() == MVT::f64) 11452 RefinementSteps++; 11453 return RefinementSteps; 11454 } 11455 11456 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11457 int Enabled, int &RefinementSteps, 11458 bool &UseOneConstNR, 11459 bool Reciprocal) const { 11460 EVT VT = Operand.getValueType(); 11461 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11462 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11463 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11464 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11465 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11466 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11467 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11468 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11469 11470 // The Newton-Raphson computation with a single constant does not provide 11471 // enough accuracy on some CPUs. 11472 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11473 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11474 } 11475 return SDValue(); 11476 } 11477 11478 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11479 int Enabled, 11480 int &RefinementSteps) const { 11481 EVT VT = Operand.getValueType(); 11482 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11483 (VT == MVT::f64 && Subtarget.hasFRE()) || 11484 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11485 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11486 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11487 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11488 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11489 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11490 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11491 } 11492 return SDValue(); 11493 } 11494 11495 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11496 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11497 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11498 // enabled for division), this functionality is redundant with the default 11499 // combiner logic (once the division -> reciprocal/multiply transformation 11500 // has taken place). As a result, this matters more for older cores than for 11501 // newer ones. 11502 11503 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11504 // reciprocal if there are two or more FDIVs (for embedded cores with only 11505 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11506 switch (Subtarget.getDarwinDirective()) { 11507 default: 11508 return 3; 11509 case PPC::DIR_440: 11510 case PPC::DIR_A2: 11511 case PPC::DIR_E500: 11512 case PPC::DIR_E500mc: 11513 case PPC::DIR_E5500: 11514 return 2; 11515 } 11516 } 11517 11518 // isConsecutiveLSLoc needs to work even if all adds have not yet been 11519 // collapsed, and so we need to look through chains of them. 11520 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 11521 int64_t& Offset, SelectionDAG &DAG) { 11522 if (DAG.isBaseWithConstantOffset(Loc)) { 11523 Base = Loc.getOperand(0); 11524 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 11525 11526 // The base might itself be a base plus an offset, and if so, accumulate 11527 // that as well. 11528 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 11529 } 11530 } 11531 11532 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 11533 unsigned Bytes, int Dist, 11534 SelectionDAG &DAG) { 11535 if (VT.getSizeInBits() / 8 != Bytes) 11536 return false; 11537 11538 SDValue BaseLoc = Base->getBasePtr(); 11539 if (Loc.getOpcode() == ISD::FrameIndex) { 11540 if (BaseLoc.getOpcode() != ISD::FrameIndex) 11541 return false; 11542 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 11543 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 11544 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 11545 int FS = MFI.getObjectSize(FI); 11546 int BFS = MFI.getObjectSize(BFI); 11547 if (FS != BFS || FS != (int)Bytes) return false; 11548 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 11549 } 11550 11551 SDValue Base1 = Loc, Base2 = BaseLoc; 11552 int64_t Offset1 = 0, Offset2 = 0; 11553 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 11554 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 11555 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 11556 return true; 11557 11558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11559 const GlobalValue *GV1 = nullptr; 11560 const GlobalValue *GV2 = nullptr; 11561 Offset1 = 0; 11562 Offset2 = 0; 11563 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 11564 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 11565 if (isGA1 && isGA2 && GV1 == GV2) 11566 return Offset1 == (Offset2 + Dist*Bytes); 11567 return false; 11568 } 11569 11570 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 11571 // not enforce equality of the chain operands. 11572 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 11573 unsigned Bytes, int Dist, 11574 SelectionDAG &DAG) { 11575 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 11576 EVT VT = LS->getMemoryVT(); 11577 SDValue Loc = LS->getBasePtr(); 11578 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 11579 } 11580 11581 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 11582 EVT VT; 11583 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11584 default: return false; 11585 case Intrinsic::ppc_qpx_qvlfd: 11586 case Intrinsic::ppc_qpx_qvlfda: 11587 VT = MVT::v4f64; 11588 break; 11589 case Intrinsic::ppc_qpx_qvlfs: 11590 case Intrinsic::ppc_qpx_qvlfsa: 11591 VT = MVT::v4f32; 11592 break; 11593 case Intrinsic::ppc_qpx_qvlfcd: 11594 case Intrinsic::ppc_qpx_qvlfcda: 11595 VT = MVT::v2f64; 11596 break; 11597 case Intrinsic::ppc_qpx_qvlfcs: 11598 case Intrinsic::ppc_qpx_qvlfcsa: 11599 VT = MVT::v2f32; 11600 break; 11601 case Intrinsic::ppc_qpx_qvlfiwa: 11602 case Intrinsic::ppc_qpx_qvlfiwz: 11603 case Intrinsic::ppc_altivec_lvx: 11604 case Intrinsic::ppc_altivec_lvxl: 11605 case Intrinsic::ppc_vsx_lxvw4x: 11606 case Intrinsic::ppc_vsx_lxvw4x_be: 11607 VT = MVT::v4i32; 11608 break; 11609 case Intrinsic::ppc_vsx_lxvd2x: 11610 case Intrinsic::ppc_vsx_lxvd2x_be: 11611 VT = MVT::v2f64; 11612 break; 11613 case Intrinsic::ppc_altivec_lvebx: 11614 VT = MVT::i8; 11615 break; 11616 case Intrinsic::ppc_altivec_lvehx: 11617 VT = MVT::i16; 11618 break; 11619 case Intrinsic::ppc_altivec_lvewx: 11620 VT = MVT::i32; 11621 break; 11622 } 11623 11624 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 11625 } 11626 11627 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 11628 EVT VT; 11629 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11630 default: return false; 11631 case Intrinsic::ppc_qpx_qvstfd: 11632 case Intrinsic::ppc_qpx_qvstfda: 11633 VT = MVT::v4f64; 11634 break; 11635 case Intrinsic::ppc_qpx_qvstfs: 11636 case Intrinsic::ppc_qpx_qvstfsa: 11637 VT = MVT::v4f32; 11638 break; 11639 case Intrinsic::ppc_qpx_qvstfcd: 11640 case Intrinsic::ppc_qpx_qvstfcda: 11641 VT = MVT::v2f64; 11642 break; 11643 case Intrinsic::ppc_qpx_qvstfcs: 11644 case Intrinsic::ppc_qpx_qvstfcsa: 11645 VT = MVT::v2f32; 11646 break; 11647 case Intrinsic::ppc_qpx_qvstfiw: 11648 case Intrinsic::ppc_qpx_qvstfiwa: 11649 case Intrinsic::ppc_altivec_stvx: 11650 case Intrinsic::ppc_altivec_stvxl: 11651 case Intrinsic::ppc_vsx_stxvw4x: 11652 VT = MVT::v4i32; 11653 break; 11654 case Intrinsic::ppc_vsx_stxvd2x: 11655 VT = MVT::v2f64; 11656 break; 11657 case Intrinsic::ppc_vsx_stxvw4x_be: 11658 VT = MVT::v4i32; 11659 break; 11660 case Intrinsic::ppc_vsx_stxvd2x_be: 11661 VT = MVT::v2f64; 11662 break; 11663 case Intrinsic::ppc_altivec_stvebx: 11664 VT = MVT::i8; 11665 break; 11666 case Intrinsic::ppc_altivec_stvehx: 11667 VT = MVT::i16; 11668 break; 11669 case Intrinsic::ppc_altivec_stvewx: 11670 VT = MVT::i32; 11671 break; 11672 } 11673 11674 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 11675 } 11676 11677 return false; 11678 } 11679 11680 // Return true is there is a nearyby consecutive load to the one provided 11681 // (regardless of alignment). We search up and down the chain, looking though 11682 // token factors and other loads (but nothing else). As a result, a true result 11683 // indicates that it is safe to create a new consecutive load adjacent to the 11684 // load provided. 11685 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 11686 SDValue Chain = LD->getChain(); 11687 EVT VT = LD->getMemoryVT(); 11688 11689 SmallSet<SDNode *, 16> LoadRoots; 11690 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 11691 SmallSet<SDNode *, 16> Visited; 11692 11693 // First, search up the chain, branching to follow all token-factor operands. 11694 // If we find a consecutive load, then we're done, otherwise, record all 11695 // nodes just above the top-level loads and token factors. 11696 while (!Queue.empty()) { 11697 SDNode *ChainNext = Queue.pop_back_val(); 11698 if (!Visited.insert(ChainNext).second) 11699 continue; 11700 11701 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 11702 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11703 return true; 11704 11705 if (!Visited.count(ChainLD->getChain().getNode())) 11706 Queue.push_back(ChainLD->getChain().getNode()); 11707 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 11708 for (const SDUse &O : ChainNext->ops()) 11709 if (!Visited.count(O.getNode())) 11710 Queue.push_back(O.getNode()); 11711 } else 11712 LoadRoots.insert(ChainNext); 11713 } 11714 11715 // Second, search down the chain, starting from the top-level nodes recorded 11716 // in the first phase. These top-level nodes are the nodes just above all 11717 // loads and token factors. Starting with their uses, recursively look though 11718 // all loads (just the chain uses) and token factors to find a consecutive 11719 // load. 11720 Visited.clear(); 11721 Queue.clear(); 11722 11723 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 11724 IE = LoadRoots.end(); I != IE; ++I) { 11725 Queue.push_back(*I); 11726 11727 while (!Queue.empty()) { 11728 SDNode *LoadRoot = Queue.pop_back_val(); 11729 if (!Visited.insert(LoadRoot).second) 11730 continue; 11731 11732 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 11733 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 11734 return true; 11735 11736 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 11737 UE = LoadRoot->use_end(); UI != UE; ++UI) 11738 if (((isa<MemSDNode>(*UI) && 11739 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 11740 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 11741 Queue.push_back(*UI); 11742 } 11743 } 11744 11745 return false; 11746 } 11747 11748 /// This function is called when we have proved that a SETCC node can be replaced 11749 /// by subtraction (and other supporting instructions) so that the result of 11750 /// comparison is kept in a GPR instead of CR. This function is purely for 11751 /// codegen purposes and has some flags to guide the codegen process. 11752 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 11753 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 11754 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11755 11756 // Zero extend the operands to the largest legal integer. Originally, they 11757 // must be of a strictly smaller size. 11758 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 11759 DAG.getConstant(Size, DL, MVT::i32)); 11760 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 11761 DAG.getConstant(Size, DL, MVT::i32)); 11762 11763 // Swap if needed. Depends on the condition code. 11764 if (Swap) 11765 std::swap(Op0, Op1); 11766 11767 // Subtract extended integers. 11768 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 11769 11770 // Move the sign bit to the least significant position and zero out the rest. 11771 // Now the least significant bit carries the result of original comparison. 11772 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 11773 DAG.getConstant(Size - 1, DL, MVT::i32)); 11774 auto Final = Shifted; 11775 11776 // Complement the result if needed. Based on the condition code. 11777 if (Complement) 11778 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 11779 DAG.getConstant(1, DL, MVT::i64)); 11780 11781 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 11782 } 11783 11784 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 11785 DAGCombinerInfo &DCI) const { 11786 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 11787 11788 SelectionDAG &DAG = DCI.DAG; 11789 SDLoc DL(N); 11790 11791 // Size of integers being compared has a critical role in the following 11792 // analysis, so we prefer to do this when all types are legal. 11793 if (!DCI.isAfterLegalizeDAG()) 11794 return SDValue(); 11795 11796 // If all users of SETCC extend its value to a legal integer type 11797 // then we replace SETCC with a subtraction 11798 for (SDNode::use_iterator UI = N->use_begin(), 11799 UE = N->use_end(); UI != UE; ++UI) { 11800 if (UI->getOpcode() != ISD::ZERO_EXTEND) 11801 return SDValue(); 11802 } 11803 11804 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11805 auto OpSize = N->getOperand(0).getValueSizeInBits(); 11806 11807 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 11808 11809 if (OpSize < Size) { 11810 switch (CC) { 11811 default: break; 11812 case ISD::SETULT: 11813 return generateEquivalentSub(N, Size, false, false, DL, DAG); 11814 case ISD::SETULE: 11815 return generateEquivalentSub(N, Size, true, true, DL, DAG); 11816 case ISD::SETUGT: 11817 return generateEquivalentSub(N, Size, false, true, DL, DAG); 11818 case ISD::SETUGE: 11819 return generateEquivalentSub(N, Size, true, false, DL, DAG); 11820 } 11821 } 11822 11823 return SDValue(); 11824 } 11825 11826 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 11827 DAGCombinerInfo &DCI) const { 11828 SelectionDAG &DAG = DCI.DAG; 11829 SDLoc dl(N); 11830 11831 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 11832 // If we're tracking CR bits, we need to be careful that we don't have: 11833 // trunc(binary-ops(zext(x), zext(y))) 11834 // or 11835 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 11836 // such that we're unnecessarily moving things into GPRs when it would be 11837 // better to keep them in CR bits. 11838 11839 // Note that trunc here can be an actual i1 trunc, or can be the effective 11840 // truncation that comes from a setcc or select_cc. 11841 if (N->getOpcode() == ISD::TRUNCATE && 11842 N->getValueType(0) != MVT::i1) 11843 return SDValue(); 11844 11845 if (N->getOperand(0).getValueType() != MVT::i32 && 11846 N->getOperand(0).getValueType() != MVT::i64) 11847 return SDValue(); 11848 11849 if (N->getOpcode() == ISD::SETCC || 11850 N->getOpcode() == ISD::SELECT_CC) { 11851 // If we're looking at a comparison, then we need to make sure that the 11852 // high bits (all except for the first) don't matter the result. 11853 ISD::CondCode CC = 11854 cast<CondCodeSDNode>(N->getOperand( 11855 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 11856 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 11857 11858 if (ISD::isSignedIntSetCC(CC)) { 11859 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 11860 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 11861 return SDValue(); 11862 } else if (ISD::isUnsignedIntSetCC(CC)) { 11863 if (!DAG.MaskedValueIsZero(N->getOperand(0), 11864 APInt::getHighBitsSet(OpBits, OpBits-1)) || 11865 !DAG.MaskedValueIsZero(N->getOperand(1), 11866 APInt::getHighBitsSet(OpBits, OpBits-1))) 11867 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 11868 : SDValue()); 11869 } else { 11870 // This is neither a signed nor an unsigned comparison, just make sure 11871 // that the high bits are equal. 11872 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 11873 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 11874 11875 // We don't really care about what is known about the first bit (if 11876 // anything), so clear it in all masks prior to comparing them. 11877 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 11878 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 11879 11880 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 11881 return SDValue(); 11882 } 11883 } 11884 11885 // We now know that the higher-order bits are irrelevant, we just need to 11886 // make sure that all of the intermediate operations are bit operations, and 11887 // all inputs are extensions. 11888 if (N->getOperand(0).getOpcode() != ISD::AND && 11889 N->getOperand(0).getOpcode() != ISD::OR && 11890 N->getOperand(0).getOpcode() != ISD::XOR && 11891 N->getOperand(0).getOpcode() != ISD::SELECT && 11892 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 11893 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 11894 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 11895 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 11896 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 11897 return SDValue(); 11898 11899 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 11900 N->getOperand(1).getOpcode() != ISD::AND && 11901 N->getOperand(1).getOpcode() != ISD::OR && 11902 N->getOperand(1).getOpcode() != ISD::XOR && 11903 N->getOperand(1).getOpcode() != ISD::SELECT && 11904 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 11905 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 11906 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 11907 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 11908 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 11909 return SDValue(); 11910 11911 SmallVector<SDValue, 4> Inputs; 11912 SmallVector<SDValue, 8> BinOps, PromOps; 11913 SmallPtrSet<SDNode *, 16> Visited; 11914 11915 for (unsigned i = 0; i < 2; ++i) { 11916 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11917 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11918 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11919 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11920 isa<ConstantSDNode>(N->getOperand(i))) 11921 Inputs.push_back(N->getOperand(i)); 11922 else 11923 BinOps.push_back(N->getOperand(i)); 11924 11925 if (N->getOpcode() == ISD::TRUNCATE) 11926 break; 11927 } 11928 11929 // Visit all inputs, collect all binary operations (and, or, xor and 11930 // select) that are all fed by extensions. 11931 while (!BinOps.empty()) { 11932 SDValue BinOp = BinOps.back(); 11933 BinOps.pop_back(); 11934 11935 if (!Visited.insert(BinOp.getNode()).second) 11936 continue; 11937 11938 PromOps.push_back(BinOp); 11939 11940 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 11941 // The condition of the select is not promoted. 11942 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 11943 continue; 11944 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 11945 continue; 11946 11947 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11948 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11949 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 11950 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 11951 isa<ConstantSDNode>(BinOp.getOperand(i))) { 11952 Inputs.push_back(BinOp.getOperand(i)); 11953 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 11954 BinOp.getOperand(i).getOpcode() == ISD::OR || 11955 BinOp.getOperand(i).getOpcode() == ISD::XOR || 11956 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 11957 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 11958 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 11959 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 11960 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 11961 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 11962 BinOps.push_back(BinOp.getOperand(i)); 11963 } else { 11964 // We have an input that is not an extension or another binary 11965 // operation; we'll abort this transformation. 11966 return SDValue(); 11967 } 11968 } 11969 } 11970 11971 // Make sure that this is a self-contained cluster of operations (which 11972 // is not quite the same thing as saying that everything has only one 11973 // use). 11974 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 11975 if (isa<ConstantSDNode>(Inputs[i])) 11976 continue; 11977 11978 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 11979 UE = Inputs[i].getNode()->use_end(); 11980 UI != UE; ++UI) { 11981 SDNode *User = *UI; 11982 if (User != N && !Visited.count(User)) 11983 return SDValue(); 11984 11985 // Make sure that we're not going to promote the non-output-value 11986 // operand(s) or SELECT or SELECT_CC. 11987 // FIXME: Although we could sometimes handle this, and it does occur in 11988 // practice that one of the condition inputs to the select is also one of 11989 // the outputs, we currently can't deal with this. 11990 if (User->getOpcode() == ISD::SELECT) { 11991 if (User->getOperand(0) == Inputs[i]) 11992 return SDValue(); 11993 } else if (User->getOpcode() == ISD::SELECT_CC) { 11994 if (User->getOperand(0) == Inputs[i] || 11995 User->getOperand(1) == Inputs[i]) 11996 return SDValue(); 11997 } 11998 } 11999 } 12000 12001 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12002 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12003 UE = PromOps[i].getNode()->use_end(); 12004 UI != UE; ++UI) { 12005 SDNode *User = *UI; 12006 if (User != N && !Visited.count(User)) 12007 return SDValue(); 12008 12009 // Make sure that we're not going to promote the non-output-value 12010 // operand(s) or SELECT or SELECT_CC. 12011 // FIXME: Although we could sometimes handle this, and it does occur in 12012 // practice that one of the condition inputs to the select is also one of 12013 // the outputs, we currently can't deal with this. 12014 if (User->getOpcode() == ISD::SELECT) { 12015 if (User->getOperand(0) == PromOps[i]) 12016 return SDValue(); 12017 } else if (User->getOpcode() == ISD::SELECT_CC) { 12018 if (User->getOperand(0) == PromOps[i] || 12019 User->getOperand(1) == PromOps[i]) 12020 return SDValue(); 12021 } 12022 } 12023 } 12024 12025 // Replace all inputs with the extension operand. 12026 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12027 // Constants may have users outside the cluster of to-be-promoted nodes, 12028 // and so we need to replace those as we do the promotions. 12029 if (isa<ConstantSDNode>(Inputs[i])) 12030 continue; 12031 else 12032 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12033 } 12034 12035 std::list<HandleSDNode> PromOpHandles; 12036 for (auto &PromOp : PromOps) 12037 PromOpHandles.emplace_back(PromOp); 12038 12039 // Replace all operations (these are all the same, but have a different 12040 // (i1) return type). DAG.getNode will validate that the types of 12041 // a binary operator match, so go through the list in reverse so that 12042 // we've likely promoted both operands first. Any intermediate truncations or 12043 // extensions disappear. 12044 while (!PromOpHandles.empty()) { 12045 SDValue PromOp = PromOpHandles.back().getValue(); 12046 PromOpHandles.pop_back(); 12047 12048 if (PromOp.getOpcode() == ISD::TRUNCATE || 12049 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12050 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12051 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12052 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12053 PromOp.getOperand(0).getValueType() != MVT::i1) { 12054 // The operand is not yet ready (see comment below). 12055 PromOpHandles.emplace_front(PromOp); 12056 continue; 12057 } 12058 12059 SDValue RepValue = PromOp.getOperand(0); 12060 if (isa<ConstantSDNode>(RepValue)) 12061 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12062 12063 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12064 continue; 12065 } 12066 12067 unsigned C; 12068 switch (PromOp.getOpcode()) { 12069 default: C = 0; break; 12070 case ISD::SELECT: C = 1; break; 12071 case ISD::SELECT_CC: C = 2; break; 12072 } 12073 12074 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12075 PromOp.getOperand(C).getValueType() != MVT::i1) || 12076 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12077 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12078 // The to-be-promoted operands of this node have not yet been 12079 // promoted (this should be rare because we're going through the 12080 // list backward, but if one of the operands has several users in 12081 // this cluster of to-be-promoted nodes, it is possible). 12082 PromOpHandles.emplace_front(PromOp); 12083 continue; 12084 } 12085 12086 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12087 PromOp.getNode()->op_end()); 12088 12089 // If there are any constant inputs, make sure they're replaced now. 12090 for (unsigned i = 0; i < 2; ++i) 12091 if (isa<ConstantSDNode>(Ops[C+i])) 12092 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12093 12094 DAG.ReplaceAllUsesOfValueWith(PromOp, 12095 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12096 } 12097 12098 // Now we're left with the initial truncation itself. 12099 if (N->getOpcode() == ISD::TRUNCATE) 12100 return N->getOperand(0); 12101 12102 // Otherwise, this is a comparison. The operands to be compared have just 12103 // changed type (to i1), but everything else is the same. 12104 return SDValue(N, 0); 12105 } 12106 12107 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12108 DAGCombinerInfo &DCI) const { 12109 SelectionDAG &DAG = DCI.DAG; 12110 SDLoc dl(N); 12111 12112 // If we're tracking CR bits, we need to be careful that we don't have: 12113 // zext(binary-ops(trunc(x), trunc(y))) 12114 // or 12115 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12116 // such that we're unnecessarily moving things into CR bits that can more 12117 // efficiently stay in GPRs. Note that if we're not certain that the high 12118 // bits are set as required by the final extension, we still may need to do 12119 // some masking to get the proper behavior. 12120 12121 // This same functionality is important on PPC64 when dealing with 12122 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12123 // the return values of functions. Because it is so similar, it is handled 12124 // here as well. 12125 12126 if (N->getValueType(0) != MVT::i32 && 12127 N->getValueType(0) != MVT::i64) 12128 return SDValue(); 12129 12130 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12131 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12132 return SDValue(); 12133 12134 if (N->getOperand(0).getOpcode() != ISD::AND && 12135 N->getOperand(0).getOpcode() != ISD::OR && 12136 N->getOperand(0).getOpcode() != ISD::XOR && 12137 N->getOperand(0).getOpcode() != ISD::SELECT && 12138 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12139 return SDValue(); 12140 12141 SmallVector<SDValue, 4> Inputs; 12142 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12143 SmallPtrSet<SDNode *, 16> Visited; 12144 12145 // Visit all inputs, collect all binary operations (and, or, xor and 12146 // select) that are all fed by truncations. 12147 while (!BinOps.empty()) { 12148 SDValue BinOp = BinOps.back(); 12149 BinOps.pop_back(); 12150 12151 if (!Visited.insert(BinOp.getNode()).second) 12152 continue; 12153 12154 PromOps.push_back(BinOp); 12155 12156 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12157 // The condition of the select is not promoted. 12158 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12159 continue; 12160 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12161 continue; 12162 12163 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12164 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12165 Inputs.push_back(BinOp.getOperand(i)); 12166 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12167 BinOp.getOperand(i).getOpcode() == ISD::OR || 12168 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12169 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12170 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12171 BinOps.push_back(BinOp.getOperand(i)); 12172 } else { 12173 // We have an input that is not a truncation or another binary 12174 // operation; we'll abort this transformation. 12175 return SDValue(); 12176 } 12177 } 12178 } 12179 12180 // The operands of a select that must be truncated when the select is 12181 // promoted because the operand is actually part of the to-be-promoted set. 12182 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12183 12184 // Make sure that this is a self-contained cluster of operations (which 12185 // is not quite the same thing as saying that everything has only one 12186 // use). 12187 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12188 if (isa<ConstantSDNode>(Inputs[i])) 12189 continue; 12190 12191 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12192 UE = Inputs[i].getNode()->use_end(); 12193 UI != UE; ++UI) { 12194 SDNode *User = *UI; 12195 if (User != N && !Visited.count(User)) 12196 return SDValue(); 12197 12198 // If we're going to promote the non-output-value operand(s) or SELECT or 12199 // SELECT_CC, record them for truncation. 12200 if (User->getOpcode() == ISD::SELECT) { 12201 if (User->getOperand(0) == Inputs[i]) 12202 SelectTruncOp[0].insert(std::make_pair(User, 12203 User->getOperand(0).getValueType())); 12204 } else if (User->getOpcode() == ISD::SELECT_CC) { 12205 if (User->getOperand(0) == Inputs[i]) 12206 SelectTruncOp[0].insert(std::make_pair(User, 12207 User->getOperand(0).getValueType())); 12208 if (User->getOperand(1) == Inputs[i]) 12209 SelectTruncOp[1].insert(std::make_pair(User, 12210 User->getOperand(1).getValueType())); 12211 } 12212 } 12213 } 12214 12215 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12216 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12217 UE = PromOps[i].getNode()->use_end(); 12218 UI != UE; ++UI) { 12219 SDNode *User = *UI; 12220 if (User != N && !Visited.count(User)) 12221 return SDValue(); 12222 12223 // If we're going to promote the non-output-value operand(s) or SELECT or 12224 // SELECT_CC, record them for truncation. 12225 if (User->getOpcode() == ISD::SELECT) { 12226 if (User->getOperand(0) == PromOps[i]) 12227 SelectTruncOp[0].insert(std::make_pair(User, 12228 User->getOperand(0).getValueType())); 12229 } else if (User->getOpcode() == ISD::SELECT_CC) { 12230 if (User->getOperand(0) == PromOps[i]) 12231 SelectTruncOp[0].insert(std::make_pair(User, 12232 User->getOperand(0).getValueType())); 12233 if (User->getOperand(1) == PromOps[i]) 12234 SelectTruncOp[1].insert(std::make_pair(User, 12235 User->getOperand(1).getValueType())); 12236 } 12237 } 12238 } 12239 12240 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12241 bool ReallyNeedsExt = false; 12242 if (N->getOpcode() != ISD::ANY_EXTEND) { 12243 // If all of the inputs are not already sign/zero extended, then 12244 // we'll still need to do that at the end. 12245 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12246 if (isa<ConstantSDNode>(Inputs[i])) 12247 continue; 12248 12249 unsigned OpBits = 12250 Inputs[i].getOperand(0).getValueSizeInBits(); 12251 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12252 12253 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12254 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12255 APInt::getHighBitsSet(OpBits, 12256 OpBits-PromBits))) || 12257 (N->getOpcode() == ISD::SIGN_EXTEND && 12258 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12259 (OpBits-(PromBits-1)))) { 12260 ReallyNeedsExt = true; 12261 break; 12262 } 12263 } 12264 } 12265 12266 // Replace all inputs, either with the truncation operand, or a 12267 // truncation or extension to the final output type. 12268 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12269 // Constant inputs need to be replaced with the to-be-promoted nodes that 12270 // use them because they might have users outside of the cluster of 12271 // promoted nodes. 12272 if (isa<ConstantSDNode>(Inputs[i])) 12273 continue; 12274 12275 SDValue InSrc = Inputs[i].getOperand(0); 12276 if (Inputs[i].getValueType() == N->getValueType(0)) 12277 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12278 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12279 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12280 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12281 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12282 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12283 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12284 else 12285 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12286 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12287 } 12288 12289 std::list<HandleSDNode> PromOpHandles; 12290 for (auto &PromOp : PromOps) 12291 PromOpHandles.emplace_back(PromOp); 12292 12293 // Replace all operations (these are all the same, but have a different 12294 // (promoted) return type). DAG.getNode will validate that the types of 12295 // a binary operator match, so go through the list in reverse so that 12296 // we've likely promoted both operands first. 12297 while (!PromOpHandles.empty()) { 12298 SDValue PromOp = PromOpHandles.back().getValue(); 12299 PromOpHandles.pop_back(); 12300 12301 unsigned C; 12302 switch (PromOp.getOpcode()) { 12303 default: C = 0; break; 12304 case ISD::SELECT: C = 1; break; 12305 case ISD::SELECT_CC: C = 2; break; 12306 } 12307 12308 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12309 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12310 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12311 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12312 // The to-be-promoted operands of this node have not yet been 12313 // promoted (this should be rare because we're going through the 12314 // list backward, but if one of the operands has several users in 12315 // this cluster of to-be-promoted nodes, it is possible). 12316 PromOpHandles.emplace_front(PromOp); 12317 continue; 12318 } 12319 12320 // For SELECT and SELECT_CC nodes, we do a similar check for any 12321 // to-be-promoted comparison inputs. 12322 if (PromOp.getOpcode() == ISD::SELECT || 12323 PromOp.getOpcode() == ISD::SELECT_CC) { 12324 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12325 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12326 (SelectTruncOp[1].count(PromOp.getNode()) && 12327 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12328 PromOpHandles.emplace_front(PromOp); 12329 continue; 12330 } 12331 } 12332 12333 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12334 PromOp.getNode()->op_end()); 12335 12336 // If this node has constant inputs, then they'll need to be promoted here. 12337 for (unsigned i = 0; i < 2; ++i) { 12338 if (!isa<ConstantSDNode>(Ops[C+i])) 12339 continue; 12340 if (Ops[C+i].getValueType() == N->getValueType(0)) 12341 continue; 12342 12343 if (N->getOpcode() == ISD::SIGN_EXTEND) 12344 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12345 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12346 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12347 else 12348 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12349 } 12350 12351 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12352 // truncate them again to the original value type. 12353 if (PromOp.getOpcode() == ISD::SELECT || 12354 PromOp.getOpcode() == ISD::SELECT_CC) { 12355 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12356 if (SI0 != SelectTruncOp[0].end()) 12357 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12358 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12359 if (SI1 != SelectTruncOp[1].end()) 12360 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12361 } 12362 12363 DAG.ReplaceAllUsesOfValueWith(PromOp, 12364 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12365 } 12366 12367 // Now we're left with the initial extension itself. 12368 if (!ReallyNeedsExt) 12369 return N->getOperand(0); 12370 12371 // To zero extend, just mask off everything except for the first bit (in the 12372 // i1 case). 12373 if (N->getOpcode() == ISD::ZERO_EXTEND) 12374 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12375 DAG.getConstant(APInt::getLowBitsSet( 12376 N->getValueSizeInBits(0), PromBits), 12377 dl, N->getValueType(0))); 12378 12379 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12380 "Invalid extension type"); 12381 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12382 SDValue ShiftCst = 12383 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12384 return DAG.getNode( 12385 ISD::SRA, dl, N->getValueType(0), 12386 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12387 ShiftCst); 12388 } 12389 12390 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12391 DAGCombinerInfo &DCI) const { 12392 assert(N->getOpcode() == ISD::SETCC && 12393 "Should be called with a SETCC node"); 12394 12395 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12396 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12397 SDValue LHS = N->getOperand(0); 12398 SDValue RHS = N->getOperand(1); 12399 12400 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12401 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12402 LHS.hasOneUse()) 12403 std::swap(LHS, RHS); 12404 12405 // x == 0-y --> x+y == 0 12406 // x != 0-y --> x+y != 0 12407 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12408 RHS.hasOneUse()) { 12409 SDLoc DL(N); 12410 SelectionDAG &DAG = DCI.DAG; 12411 EVT VT = N->getValueType(0); 12412 EVT OpVT = LHS.getValueType(); 12413 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12414 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12415 } 12416 } 12417 12418 return DAGCombineTruncBoolExt(N, DCI); 12419 } 12420 12421 // Is this an extending load from an f32 to an f64? 12422 static bool isFPExtLoad(SDValue Op) { 12423 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12424 return LD->getExtensionType() == ISD::EXTLOAD && 12425 Op.getValueType() == MVT::f64; 12426 return false; 12427 } 12428 12429 /// Reduces the number of fp-to-int conversion when building a vector. 12430 /// 12431 /// If this vector is built out of floating to integer conversions, 12432 /// transform it to a vector built out of floating point values followed by a 12433 /// single floating to integer conversion of the vector. 12434 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12435 /// becomes (fptosi (build_vector ($A, $B, ...))) 12436 SDValue PPCTargetLowering:: 12437 combineElementTruncationToVectorTruncation(SDNode *N, 12438 DAGCombinerInfo &DCI) const { 12439 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12440 "Should be called with a BUILD_VECTOR node"); 12441 12442 SelectionDAG &DAG = DCI.DAG; 12443 SDLoc dl(N); 12444 12445 SDValue FirstInput = N->getOperand(0); 12446 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12447 "The input operand must be an fp-to-int conversion."); 12448 12449 // This combine happens after legalization so the fp_to_[su]i nodes are 12450 // already converted to PPCSISD nodes. 12451 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12452 if (FirstConversion == PPCISD::FCTIDZ || 12453 FirstConversion == PPCISD::FCTIDUZ || 12454 FirstConversion == PPCISD::FCTIWZ || 12455 FirstConversion == PPCISD::FCTIWUZ) { 12456 bool IsSplat = true; 12457 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12458 FirstConversion == PPCISD::FCTIWUZ; 12459 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12460 SmallVector<SDValue, 4> Ops; 12461 EVT TargetVT = N->getValueType(0); 12462 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12463 SDValue NextOp = N->getOperand(i); 12464 if (NextOp.getOpcode() != PPCISD::MFVSR) 12465 return SDValue(); 12466 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12467 if (NextConversion != FirstConversion) 12468 return SDValue(); 12469 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12470 // This is not valid if the input was originally double precision. It is 12471 // also not profitable to do unless this is an extending load in which 12472 // case doing this combine will allow us to combine consecutive loads. 12473 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12474 return SDValue(); 12475 if (N->getOperand(i) != FirstInput) 12476 IsSplat = false; 12477 } 12478 12479 // If this is a splat, we leave it as-is since there will be only a single 12480 // fp-to-int conversion followed by a splat of the integer. This is better 12481 // for 32-bit and smaller ints and neutral for 64-bit ints. 12482 if (IsSplat) 12483 return SDValue(); 12484 12485 // Now that we know we have the right type of node, get its operands 12486 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12487 SDValue In = N->getOperand(i).getOperand(0); 12488 if (Is32Bit) { 12489 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12490 // here, we know that all inputs are extending loads so this is safe). 12491 if (In.isUndef()) 12492 Ops.push_back(DAG.getUNDEF(SrcVT)); 12493 else { 12494 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12495 MVT::f32, In.getOperand(0), 12496 DAG.getIntPtrConstant(1, dl)); 12497 Ops.push_back(Trunc); 12498 } 12499 } else 12500 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12501 } 12502 12503 unsigned Opcode; 12504 if (FirstConversion == PPCISD::FCTIDZ || 12505 FirstConversion == PPCISD::FCTIWZ) 12506 Opcode = ISD::FP_TO_SINT; 12507 else 12508 Opcode = ISD::FP_TO_UINT; 12509 12510 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12511 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12512 return DAG.getNode(Opcode, dl, TargetVT, BV); 12513 } 12514 return SDValue(); 12515 } 12516 12517 /// Reduce the number of loads when building a vector. 12518 /// 12519 /// Building a vector out of multiple loads can be converted to a load 12520 /// of the vector type if the loads are consecutive. If the loads are 12521 /// consecutive but in descending order, a shuffle is added at the end 12522 /// to reorder the vector. 12523 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 12524 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12525 "Should be called with a BUILD_VECTOR node"); 12526 12527 SDLoc dl(N); 12528 12529 // Return early for non byte-sized type, as they can't be consecutive. 12530 if (!N->getValueType(0).getVectorElementType().isByteSized()) 12531 return SDValue(); 12532 12533 bool InputsAreConsecutiveLoads = true; 12534 bool InputsAreReverseConsecutive = true; 12535 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 12536 SDValue FirstInput = N->getOperand(0); 12537 bool IsRoundOfExtLoad = false; 12538 12539 if (FirstInput.getOpcode() == ISD::FP_ROUND && 12540 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 12541 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 12542 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 12543 } 12544 // Not a build vector of (possibly fp_rounded) loads. 12545 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 12546 N->getNumOperands() == 1) 12547 return SDValue(); 12548 12549 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 12550 // If any inputs are fp_round(extload), they all must be. 12551 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 12552 return SDValue(); 12553 12554 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 12555 N->getOperand(i); 12556 if (NextInput.getOpcode() != ISD::LOAD) 12557 return SDValue(); 12558 12559 SDValue PreviousInput = 12560 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 12561 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 12562 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 12563 12564 // If any inputs are fp_round(extload), they all must be. 12565 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 12566 return SDValue(); 12567 12568 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 12569 InputsAreConsecutiveLoads = false; 12570 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 12571 InputsAreReverseConsecutive = false; 12572 12573 // Exit early if the loads are neither consecutive nor reverse consecutive. 12574 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 12575 return SDValue(); 12576 } 12577 12578 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 12579 "The loads cannot be both consecutive and reverse consecutive."); 12580 12581 SDValue FirstLoadOp = 12582 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 12583 SDValue LastLoadOp = 12584 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 12585 N->getOperand(N->getNumOperands()-1); 12586 12587 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 12588 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 12589 if (InputsAreConsecutiveLoads) { 12590 assert(LD1 && "Input needs to be a LoadSDNode."); 12591 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 12592 LD1->getBasePtr(), LD1->getPointerInfo(), 12593 LD1->getAlignment()); 12594 } 12595 if (InputsAreReverseConsecutive) { 12596 assert(LDL && "Input needs to be a LoadSDNode."); 12597 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 12598 LDL->getBasePtr(), LDL->getPointerInfo(), 12599 LDL->getAlignment()); 12600 SmallVector<int, 16> Ops; 12601 for (int i = N->getNumOperands() - 1; i >= 0; i--) 12602 Ops.push_back(i); 12603 12604 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 12605 DAG.getUNDEF(N->getValueType(0)), Ops); 12606 } 12607 return SDValue(); 12608 } 12609 12610 // This function adds the required vector_shuffle needed to get 12611 // the elements of the vector extract in the correct position 12612 // as specified by the CorrectElems encoding. 12613 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 12614 SDValue Input, uint64_t Elems, 12615 uint64_t CorrectElems) { 12616 SDLoc dl(N); 12617 12618 unsigned NumElems = Input.getValueType().getVectorNumElements(); 12619 SmallVector<int, 16> ShuffleMask(NumElems, -1); 12620 12621 // Knowing the element indices being extracted from the original 12622 // vector and the order in which they're being inserted, just put 12623 // them at element indices required for the instruction. 12624 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12625 if (DAG.getDataLayout().isLittleEndian()) 12626 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 12627 else 12628 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 12629 CorrectElems = CorrectElems >> 8; 12630 Elems = Elems >> 8; 12631 } 12632 12633 SDValue Shuffle = 12634 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 12635 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 12636 12637 EVT Ty = N->getValueType(0); 12638 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 12639 return BV; 12640 } 12641 12642 // Look for build vector patterns where input operands come from sign 12643 // extended vector_extract elements of specific indices. If the correct indices 12644 // aren't used, add a vector shuffle to fix up the indices and create a new 12645 // PPCISD:SExtVElems node which selects the vector sign extend instructions 12646 // during instruction selection. 12647 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 12648 // This array encodes the indices that the vector sign extend instructions 12649 // extract from when extending from one type to another for both BE and LE. 12650 // The right nibble of each byte corresponds to the LE incides. 12651 // and the left nibble of each byte corresponds to the BE incides. 12652 // For example: 0x3074B8FC byte->word 12653 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 12654 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 12655 // For example: 0x000070F8 byte->double word 12656 // For LE: the allowed indices are: 0x0,0x8 12657 // For BE: the allowed indices are: 0x7,0xF 12658 uint64_t TargetElems[] = { 12659 0x3074B8FC, // b->w 12660 0x000070F8, // b->d 12661 0x10325476, // h->w 12662 0x00003074, // h->d 12663 0x00001032, // w->d 12664 }; 12665 12666 uint64_t Elems = 0; 12667 int Index; 12668 SDValue Input; 12669 12670 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 12671 if (!Op) 12672 return false; 12673 if (Op.getOpcode() != ISD::SIGN_EXTEND && 12674 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 12675 return false; 12676 12677 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 12678 // of the right width. 12679 SDValue Extract = Op.getOperand(0); 12680 if (Extract.getOpcode() == ISD::ANY_EXTEND) 12681 Extract = Extract.getOperand(0); 12682 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12683 return false; 12684 12685 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 12686 if (!ExtOp) 12687 return false; 12688 12689 Index = ExtOp->getZExtValue(); 12690 if (Input && Input != Extract.getOperand(0)) 12691 return false; 12692 12693 if (!Input) 12694 Input = Extract.getOperand(0); 12695 12696 Elems = Elems << 8; 12697 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 12698 Elems |= Index; 12699 12700 return true; 12701 }; 12702 12703 // If the build vector operands aren't sign extended vector extracts, 12704 // of the same input vector, then return. 12705 for (unsigned i = 0; i < N->getNumOperands(); i++) { 12706 if (!isSExtOfVecExtract(N->getOperand(i))) { 12707 return SDValue(); 12708 } 12709 } 12710 12711 // If the vector extract indicies are not correct, add the appropriate 12712 // vector_shuffle. 12713 int TgtElemArrayIdx; 12714 int InputSize = Input.getValueType().getScalarSizeInBits(); 12715 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 12716 if (InputSize + OutputSize == 40) 12717 TgtElemArrayIdx = 0; 12718 else if (InputSize + OutputSize == 72) 12719 TgtElemArrayIdx = 1; 12720 else if (InputSize + OutputSize == 48) 12721 TgtElemArrayIdx = 2; 12722 else if (InputSize + OutputSize == 80) 12723 TgtElemArrayIdx = 3; 12724 else if (InputSize + OutputSize == 96) 12725 TgtElemArrayIdx = 4; 12726 else 12727 return SDValue(); 12728 12729 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 12730 CorrectElems = DAG.getDataLayout().isLittleEndian() 12731 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 12732 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 12733 if (Elems != CorrectElems) { 12734 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 12735 } 12736 12737 // Regular lowering will catch cases where a shuffle is not needed. 12738 return SDValue(); 12739 } 12740 12741 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 12742 DAGCombinerInfo &DCI) const { 12743 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12744 "Should be called with a BUILD_VECTOR node"); 12745 12746 SelectionDAG &DAG = DCI.DAG; 12747 SDLoc dl(N); 12748 12749 if (!Subtarget.hasVSX()) 12750 return SDValue(); 12751 12752 // The target independent DAG combiner will leave a build_vector of 12753 // float-to-int conversions intact. We can generate MUCH better code for 12754 // a float-to-int conversion of a vector of floats. 12755 SDValue FirstInput = N->getOperand(0); 12756 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 12757 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 12758 if (Reduced) 12759 return Reduced; 12760 } 12761 12762 // If we're building a vector out of consecutive loads, just load that 12763 // vector type. 12764 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 12765 if (Reduced) 12766 return Reduced; 12767 12768 // If we're building a vector out of extended elements from another vector 12769 // we have P9 vector integer extend instructions. The code assumes legal 12770 // input types (i.e. it can't handle things like v4i16) so do not run before 12771 // legalization. 12772 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 12773 Reduced = combineBVOfVecSExt(N, DAG); 12774 if (Reduced) 12775 return Reduced; 12776 } 12777 12778 12779 if (N->getValueType(0) != MVT::v2f64) 12780 return SDValue(); 12781 12782 // Looking for: 12783 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 12784 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 12785 FirstInput.getOpcode() != ISD::UINT_TO_FP) 12786 return SDValue(); 12787 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 12788 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 12789 return SDValue(); 12790 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 12791 return SDValue(); 12792 12793 SDValue Ext1 = FirstInput.getOperand(0); 12794 SDValue Ext2 = N->getOperand(1).getOperand(0); 12795 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12796 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 12797 return SDValue(); 12798 12799 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 12800 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 12801 if (!Ext1Op || !Ext2Op) 12802 return SDValue(); 12803 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 12804 Ext1.getOperand(0) != Ext2.getOperand(0)) 12805 return SDValue(); 12806 12807 int FirstElem = Ext1Op->getZExtValue(); 12808 int SecondElem = Ext2Op->getZExtValue(); 12809 int SubvecIdx; 12810 if (FirstElem == 0 && SecondElem == 1) 12811 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 12812 else if (FirstElem == 2 && SecondElem == 3) 12813 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 12814 else 12815 return SDValue(); 12816 12817 SDValue SrcVec = Ext1.getOperand(0); 12818 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 12819 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 12820 return DAG.getNode(NodeType, dl, MVT::v2f64, 12821 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 12822 } 12823 12824 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 12825 DAGCombinerInfo &DCI) const { 12826 assert((N->getOpcode() == ISD::SINT_TO_FP || 12827 N->getOpcode() == ISD::UINT_TO_FP) && 12828 "Need an int -> FP conversion node here"); 12829 12830 if (useSoftFloat() || !Subtarget.has64BitSupport()) 12831 return SDValue(); 12832 12833 SelectionDAG &DAG = DCI.DAG; 12834 SDLoc dl(N); 12835 SDValue Op(N, 0); 12836 12837 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 12838 // from the hardware. 12839 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 12840 return SDValue(); 12841 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 12842 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 12843 return SDValue(); 12844 12845 SDValue FirstOperand(Op.getOperand(0)); 12846 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 12847 (FirstOperand.getValueType() == MVT::i8 || 12848 FirstOperand.getValueType() == MVT::i16); 12849 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 12850 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 12851 bool DstDouble = Op.getValueType() == MVT::f64; 12852 unsigned ConvOp = Signed ? 12853 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 12854 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 12855 SDValue WidthConst = 12856 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 12857 dl, false); 12858 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 12859 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 12860 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 12861 DAG.getVTList(MVT::f64, MVT::Other), 12862 Ops, MVT::i8, LDN->getMemOperand()); 12863 12864 // For signed conversion, we need to sign-extend the value in the VSR 12865 if (Signed) { 12866 SDValue ExtOps[] = { Ld, WidthConst }; 12867 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 12868 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 12869 } else 12870 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 12871 } 12872 12873 12874 // For i32 intermediate values, unfortunately, the conversion functions 12875 // leave the upper 32 bits of the value are undefined. Within the set of 12876 // scalar instructions, we have no method for zero- or sign-extending the 12877 // value. Thus, we cannot handle i32 intermediate values here. 12878 if (Op.getOperand(0).getValueType() == MVT::i32) 12879 return SDValue(); 12880 12881 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 12882 "UINT_TO_FP is supported only with FPCVT"); 12883 12884 // If we have FCFIDS, then use it when converting to single-precision. 12885 // Otherwise, convert to double-precision and then round. 12886 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12887 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 12888 : PPCISD::FCFIDS) 12889 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 12890 : PPCISD::FCFID); 12891 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 12892 ? MVT::f32 12893 : MVT::f64; 12894 12895 // If we're converting from a float, to an int, and back to a float again, 12896 // then we don't need the store/load pair at all. 12897 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 12898 Subtarget.hasFPCVT()) || 12899 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 12900 SDValue Src = Op.getOperand(0).getOperand(0); 12901 if (Src.getValueType() == MVT::f32) { 12902 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 12903 DCI.AddToWorklist(Src.getNode()); 12904 } else if (Src.getValueType() != MVT::f64) { 12905 // Make sure that we don't pick up a ppc_fp128 source value. 12906 return SDValue(); 12907 } 12908 12909 unsigned FCTOp = 12910 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 12911 PPCISD::FCTIDUZ; 12912 12913 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 12914 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 12915 12916 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 12917 FP = DAG.getNode(ISD::FP_ROUND, dl, 12918 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 12919 DCI.AddToWorklist(FP.getNode()); 12920 } 12921 12922 return FP; 12923 } 12924 12925 return SDValue(); 12926 } 12927 12928 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 12929 // builtins) into loads with swaps. 12930 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 12931 DAGCombinerInfo &DCI) const { 12932 SelectionDAG &DAG = DCI.DAG; 12933 SDLoc dl(N); 12934 SDValue Chain; 12935 SDValue Base; 12936 MachineMemOperand *MMO; 12937 12938 switch (N->getOpcode()) { 12939 default: 12940 llvm_unreachable("Unexpected opcode for little endian VSX load"); 12941 case ISD::LOAD: { 12942 LoadSDNode *LD = cast<LoadSDNode>(N); 12943 Chain = LD->getChain(); 12944 Base = LD->getBasePtr(); 12945 MMO = LD->getMemOperand(); 12946 // If the MMO suggests this isn't a load of a full vector, leave 12947 // things alone. For a built-in, we have to make the change for 12948 // correctness, so if there is a size problem that will be a bug. 12949 if (MMO->getSize() < 16) 12950 return SDValue(); 12951 break; 12952 } 12953 case ISD::INTRINSIC_W_CHAIN: { 12954 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 12955 Chain = Intrin->getChain(); 12956 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 12957 // us what we want. Get operand 2 instead. 12958 Base = Intrin->getOperand(2); 12959 MMO = Intrin->getMemOperand(); 12960 break; 12961 } 12962 } 12963 12964 MVT VecTy = N->getValueType(0).getSimpleVT(); 12965 12966 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 12967 // aligned and the type is a vector with elements up to 4 bytes 12968 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 12969 && VecTy.getScalarSizeInBits() <= 32 ) { 12970 return SDValue(); 12971 } 12972 12973 SDValue LoadOps[] = { Chain, Base }; 12974 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 12975 DAG.getVTList(MVT::v2f64, MVT::Other), 12976 LoadOps, MVT::v2f64, MMO); 12977 12978 DCI.AddToWorklist(Load.getNode()); 12979 Chain = Load.getValue(1); 12980 SDValue Swap = DAG.getNode( 12981 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 12982 DCI.AddToWorklist(Swap.getNode()); 12983 12984 // Add a bitcast if the resulting load type doesn't match v2f64. 12985 if (VecTy != MVT::v2f64) { 12986 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 12987 DCI.AddToWorklist(N.getNode()); 12988 // Package {bitcast value, swap's chain} to match Load's shape. 12989 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 12990 N, Swap.getValue(1)); 12991 } 12992 12993 return Swap; 12994 } 12995 12996 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 12997 // builtins) into stores with swaps. 12998 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 12999 DAGCombinerInfo &DCI) const { 13000 SelectionDAG &DAG = DCI.DAG; 13001 SDLoc dl(N); 13002 SDValue Chain; 13003 SDValue Base; 13004 unsigned SrcOpnd; 13005 MachineMemOperand *MMO; 13006 13007 switch (N->getOpcode()) { 13008 default: 13009 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13010 case ISD::STORE: { 13011 StoreSDNode *ST = cast<StoreSDNode>(N); 13012 Chain = ST->getChain(); 13013 Base = ST->getBasePtr(); 13014 MMO = ST->getMemOperand(); 13015 SrcOpnd = 1; 13016 // If the MMO suggests this isn't a store of a full vector, leave 13017 // things alone. For a built-in, we have to make the change for 13018 // correctness, so if there is a size problem that will be a bug. 13019 if (MMO->getSize() < 16) 13020 return SDValue(); 13021 break; 13022 } 13023 case ISD::INTRINSIC_VOID: { 13024 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13025 Chain = Intrin->getChain(); 13026 // Intrin->getBasePtr() oddly does not get what we want. 13027 Base = Intrin->getOperand(3); 13028 MMO = Intrin->getMemOperand(); 13029 SrcOpnd = 2; 13030 break; 13031 } 13032 } 13033 13034 SDValue Src = N->getOperand(SrcOpnd); 13035 MVT VecTy = Src.getValueType().getSimpleVT(); 13036 13037 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13038 // aligned and the type is a vector with elements up to 4 bytes 13039 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13040 && VecTy.getScalarSizeInBits() <= 32 ) { 13041 return SDValue(); 13042 } 13043 13044 // All stores are done as v2f64 and possible bit cast. 13045 if (VecTy != MVT::v2f64) { 13046 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13047 DCI.AddToWorklist(Src.getNode()); 13048 } 13049 13050 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13051 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13052 DCI.AddToWorklist(Swap.getNode()); 13053 Chain = Swap.getValue(1); 13054 SDValue StoreOps[] = { Chain, Swap, Base }; 13055 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13056 DAG.getVTList(MVT::Other), 13057 StoreOps, VecTy, MMO); 13058 DCI.AddToWorklist(Store.getNode()); 13059 return Store; 13060 } 13061 13062 // Handle DAG combine for STORE (FP_TO_INT F). 13063 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13064 DAGCombinerInfo &DCI) const { 13065 13066 SelectionDAG &DAG = DCI.DAG; 13067 SDLoc dl(N); 13068 unsigned Opcode = N->getOperand(1).getOpcode(); 13069 13070 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13071 && "Not a FP_TO_INT Instruction!"); 13072 13073 SDValue Val = N->getOperand(1).getOperand(0); 13074 EVT Op1VT = N->getOperand(1).getValueType(); 13075 EVT ResVT = Val.getValueType(); 13076 13077 // Floating point types smaller than 32 bits are not legal on Power. 13078 if (ResVT.getScalarSizeInBits() < 32) 13079 return SDValue(); 13080 13081 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13082 bool ValidTypeForStoreFltAsInt = 13083 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13084 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13085 13086 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13087 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13088 return SDValue(); 13089 13090 // Extend f32 values to f64 13091 if (ResVT.getScalarSizeInBits() == 32) { 13092 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13093 DCI.AddToWorklist(Val.getNode()); 13094 } 13095 13096 // Set signed or unsigned conversion opcode. 13097 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13098 PPCISD::FP_TO_SINT_IN_VSR : 13099 PPCISD::FP_TO_UINT_IN_VSR; 13100 13101 Val = DAG.getNode(ConvOpcode, 13102 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13103 DCI.AddToWorklist(Val.getNode()); 13104 13105 // Set number of bytes being converted. 13106 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13107 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13108 DAG.getIntPtrConstant(ByteSize, dl, false), 13109 DAG.getValueType(Op1VT) }; 13110 13111 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13112 DAG.getVTList(MVT::Other), Ops, 13113 cast<StoreSDNode>(N)->getMemoryVT(), 13114 cast<StoreSDNode>(N)->getMemOperand()); 13115 13116 DCI.AddToWorklist(Val.getNode()); 13117 return Val; 13118 } 13119 13120 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13121 LSBaseSDNode *LSBase, 13122 DAGCombinerInfo &DCI) const { 13123 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13124 "Not a reverse memop pattern!"); 13125 13126 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13127 auto Mask = SVN->getMask(); 13128 int i = 0; 13129 auto I = Mask.rbegin(); 13130 auto E = Mask.rend(); 13131 13132 for (; I != E; ++I) { 13133 if (*I != i) 13134 return false; 13135 i++; 13136 } 13137 return true; 13138 }; 13139 13140 SelectionDAG &DAG = DCI.DAG; 13141 EVT VT = SVN->getValueType(0); 13142 13143 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13144 return SDValue(); 13145 13146 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13147 // See comment in PPCVSXSwapRemoval.cpp. 13148 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13149 if (!Subtarget.hasP9Vector()) 13150 return SDValue(); 13151 13152 if(!IsElementReverse(SVN)) 13153 return SDValue(); 13154 13155 if (LSBase->getOpcode() == ISD::LOAD) { 13156 SDLoc dl(SVN); 13157 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13158 return DAG.getMemIntrinsicNode( 13159 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13160 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13161 } 13162 13163 if (LSBase->getOpcode() == ISD::STORE) { 13164 SDLoc dl(LSBase); 13165 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13166 LSBase->getBasePtr()}; 13167 return DAG.getMemIntrinsicNode( 13168 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13169 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13170 } 13171 13172 llvm_unreachable("Expected a load or store node here"); 13173 } 13174 13175 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13176 DAGCombinerInfo &DCI) const { 13177 SelectionDAG &DAG = DCI.DAG; 13178 SDLoc dl(N); 13179 switch (N->getOpcode()) { 13180 default: break; 13181 case ISD::ADD: 13182 return combineADD(N, DCI); 13183 case ISD::SHL: 13184 return combineSHL(N, DCI); 13185 case ISD::SRA: 13186 return combineSRA(N, DCI); 13187 case ISD::SRL: 13188 return combineSRL(N, DCI); 13189 case ISD::MUL: 13190 return combineMUL(N, DCI); 13191 case PPCISD::SHL: 13192 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13193 return N->getOperand(0); 13194 break; 13195 case PPCISD::SRL: 13196 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13197 return N->getOperand(0); 13198 break; 13199 case PPCISD::SRA: 13200 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13201 if (C->isNullValue() || // 0 >>s V -> 0. 13202 C->isAllOnesValue()) // -1 >>s V -> -1. 13203 return N->getOperand(0); 13204 } 13205 break; 13206 case ISD::SIGN_EXTEND: 13207 case ISD::ZERO_EXTEND: 13208 case ISD::ANY_EXTEND: 13209 return DAGCombineExtBoolTrunc(N, DCI); 13210 case ISD::TRUNCATE: 13211 return combineTRUNCATE(N, DCI); 13212 case ISD::SETCC: 13213 if (SDValue CSCC = combineSetCC(N, DCI)) 13214 return CSCC; 13215 LLVM_FALLTHROUGH; 13216 case ISD::SELECT_CC: 13217 return DAGCombineTruncBoolExt(N, DCI); 13218 case ISD::SINT_TO_FP: 13219 case ISD::UINT_TO_FP: 13220 return combineFPToIntToFP(N, DCI); 13221 case ISD::VECTOR_SHUFFLE: 13222 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13223 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13224 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13225 } 13226 break; 13227 case ISD::STORE: { 13228 13229 EVT Op1VT = N->getOperand(1).getValueType(); 13230 unsigned Opcode = N->getOperand(1).getOpcode(); 13231 13232 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13233 SDValue Val= combineStoreFPToInt(N, DCI); 13234 if (Val) 13235 return Val; 13236 } 13237 13238 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13239 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13240 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13241 if (Val) 13242 return Val; 13243 } 13244 13245 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13246 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13247 N->getOperand(1).getNode()->hasOneUse() && 13248 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13249 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13250 13251 // STBRX can only handle simple types and it makes no sense to store less 13252 // two bytes in byte-reversed order. 13253 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13254 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13255 break; 13256 13257 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13258 // Do an any-extend to 32-bits if this is a half-word input. 13259 if (BSwapOp.getValueType() == MVT::i16) 13260 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13261 13262 // If the type of BSWAP operand is wider than stored memory width 13263 // it need to be shifted to the right side before STBRX. 13264 if (Op1VT.bitsGT(mVT)) { 13265 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13266 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13267 DAG.getConstant(Shift, dl, MVT::i32)); 13268 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13269 if (Op1VT == MVT::i64) 13270 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13271 } 13272 13273 SDValue Ops[] = { 13274 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13275 }; 13276 return 13277 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13278 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13279 cast<StoreSDNode>(N)->getMemOperand()); 13280 } 13281 13282 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13283 // So it can increase the chance of CSE constant construction. 13284 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13285 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13286 // Need to sign-extended to 64-bits to handle negative values. 13287 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13288 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13289 MemVT.getSizeInBits()); 13290 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13291 13292 // DAG.getTruncStore() can't be used here because it doesn't accept 13293 // the general (base + offset) addressing mode. 13294 // So we use UpdateNodeOperands and setTruncatingStore instead. 13295 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13296 N->getOperand(3)); 13297 cast<StoreSDNode>(N)->setTruncatingStore(true); 13298 return SDValue(N, 0); 13299 } 13300 13301 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13302 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13303 if (Op1VT.isSimple()) { 13304 MVT StoreVT = Op1VT.getSimpleVT(); 13305 if (Subtarget.needsSwapsForVSXMemOps() && 13306 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13307 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13308 return expandVSXStoreForLE(N, DCI); 13309 } 13310 break; 13311 } 13312 case ISD::LOAD: { 13313 LoadSDNode *LD = cast<LoadSDNode>(N); 13314 EVT VT = LD->getValueType(0); 13315 13316 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13317 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13318 if (VT.isSimple()) { 13319 MVT LoadVT = VT.getSimpleVT(); 13320 if (Subtarget.needsSwapsForVSXMemOps() && 13321 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13322 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13323 return expandVSXLoadForLE(N, DCI); 13324 } 13325 13326 // We sometimes end up with a 64-bit integer load, from which we extract 13327 // two single-precision floating-point numbers. This happens with 13328 // std::complex<float>, and other similar structures, because of the way we 13329 // canonicalize structure copies. However, if we lack direct moves, 13330 // then the final bitcasts from the extracted integer values to the 13331 // floating-point numbers turn into store/load pairs. Even with direct moves, 13332 // just loading the two floating-point numbers is likely better. 13333 auto ReplaceTwoFloatLoad = [&]() { 13334 if (VT != MVT::i64) 13335 return false; 13336 13337 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13338 LD->isVolatile()) 13339 return false; 13340 13341 // We're looking for a sequence like this: 13342 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13343 // t16: i64 = srl t13, Constant:i32<32> 13344 // t17: i32 = truncate t16 13345 // t18: f32 = bitcast t17 13346 // t19: i32 = truncate t13 13347 // t20: f32 = bitcast t19 13348 13349 if (!LD->hasNUsesOfValue(2, 0)) 13350 return false; 13351 13352 auto UI = LD->use_begin(); 13353 while (UI.getUse().getResNo() != 0) ++UI; 13354 SDNode *Trunc = *UI++; 13355 while (UI.getUse().getResNo() != 0) ++UI; 13356 SDNode *RightShift = *UI; 13357 if (Trunc->getOpcode() != ISD::TRUNCATE) 13358 std::swap(Trunc, RightShift); 13359 13360 if (Trunc->getOpcode() != ISD::TRUNCATE || 13361 Trunc->getValueType(0) != MVT::i32 || 13362 !Trunc->hasOneUse()) 13363 return false; 13364 if (RightShift->getOpcode() != ISD::SRL || 13365 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13366 RightShift->getConstantOperandVal(1) != 32 || 13367 !RightShift->hasOneUse()) 13368 return false; 13369 13370 SDNode *Trunc2 = *RightShift->use_begin(); 13371 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13372 Trunc2->getValueType(0) != MVT::i32 || 13373 !Trunc2->hasOneUse()) 13374 return false; 13375 13376 SDNode *Bitcast = *Trunc->use_begin(); 13377 SDNode *Bitcast2 = *Trunc2->use_begin(); 13378 13379 if (Bitcast->getOpcode() != ISD::BITCAST || 13380 Bitcast->getValueType(0) != MVT::f32) 13381 return false; 13382 if (Bitcast2->getOpcode() != ISD::BITCAST || 13383 Bitcast2->getValueType(0) != MVT::f32) 13384 return false; 13385 13386 if (Subtarget.isLittleEndian()) 13387 std::swap(Bitcast, Bitcast2); 13388 13389 // Bitcast has the second float (in memory-layout order) and Bitcast2 13390 // has the first one. 13391 13392 SDValue BasePtr = LD->getBasePtr(); 13393 if (LD->isIndexed()) { 13394 assert(LD->getAddressingMode() == ISD::PRE_INC && 13395 "Non-pre-inc AM on PPC?"); 13396 BasePtr = 13397 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13398 LD->getOffset()); 13399 } 13400 13401 auto MMOFlags = 13402 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13403 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13404 LD->getPointerInfo(), LD->getAlignment(), 13405 MMOFlags, LD->getAAInfo()); 13406 SDValue AddPtr = 13407 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13408 BasePtr, DAG.getIntPtrConstant(4, dl)); 13409 SDValue FloatLoad2 = DAG.getLoad( 13410 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13411 LD->getPointerInfo().getWithOffset(4), 13412 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13413 13414 if (LD->isIndexed()) { 13415 // Note that DAGCombine should re-form any pre-increment load(s) from 13416 // what is produced here if that makes sense. 13417 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13418 } 13419 13420 DCI.CombineTo(Bitcast2, FloatLoad); 13421 DCI.CombineTo(Bitcast, FloatLoad2); 13422 13423 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13424 SDValue(FloatLoad2.getNode(), 1)); 13425 return true; 13426 }; 13427 13428 if (ReplaceTwoFloatLoad()) 13429 return SDValue(N, 0); 13430 13431 EVT MemVT = LD->getMemoryVT(); 13432 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13433 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13434 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13435 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13436 if (LD->isUnindexed() && VT.isVector() && 13437 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13438 // P8 and later hardware should just use LOAD. 13439 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13440 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13441 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13442 LD->getAlignment() >= ScalarABIAlignment)) && 13443 LD->getAlignment() < ABIAlignment) { 13444 // This is a type-legal unaligned Altivec or QPX load. 13445 SDValue Chain = LD->getChain(); 13446 SDValue Ptr = LD->getBasePtr(); 13447 bool isLittleEndian = Subtarget.isLittleEndian(); 13448 13449 // This implements the loading of unaligned vectors as described in 13450 // the venerable Apple Velocity Engine overview. Specifically: 13451 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13452 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13453 // 13454 // The general idea is to expand a sequence of one or more unaligned 13455 // loads into an alignment-based permutation-control instruction (lvsl 13456 // or lvsr), a series of regular vector loads (which always truncate 13457 // their input address to an aligned address), and a series of 13458 // permutations. The results of these permutations are the requested 13459 // loaded values. The trick is that the last "extra" load is not taken 13460 // from the address you might suspect (sizeof(vector) bytes after the 13461 // last requested load), but rather sizeof(vector) - 1 bytes after the 13462 // last requested vector. The point of this is to avoid a page fault if 13463 // the base address happened to be aligned. This works because if the 13464 // base address is aligned, then adding less than a full vector length 13465 // will cause the last vector in the sequence to be (re)loaded. 13466 // Otherwise, the next vector will be fetched as you might suspect was 13467 // necessary. 13468 13469 // We might be able to reuse the permutation generation from 13470 // a different base address offset from this one by an aligned amount. 13471 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13472 // optimization later. 13473 Intrinsic::ID Intr, IntrLD, IntrPerm; 13474 MVT PermCntlTy, PermTy, LDTy; 13475 if (Subtarget.hasAltivec()) { 13476 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13477 Intrinsic::ppc_altivec_lvsl; 13478 IntrLD = Intrinsic::ppc_altivec_lvx; 13479 IntrPerm = Intrinsic::ppc_altivec_vperm; 13480 PermCntlTy = MVT::v16i8; 13481 PermTy = MVT::v4i32; 13482 LDTy = MVT::v4i32; 13483 } else { 13484 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13485 Intrinsic::ppc_qpx_qvlpcls; 13486 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13487 Intrinsic::ppc_qpx_qvlfs; 13488 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13489 PermCntlTy = MVT::v4f64; 13490 PermTy = MVT::v4f64; 13491 LDTy = MemVT.getSimpleVT(); 13492 } 13493 13494 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13495 13496 // Create the new MMO for the new base load. It is like the original MMO, 13497 // but represents an area in memory almost twice the vector size centered 13498 // on the original address. If the address is unaligned, we might start 13499 // reading up to (sizeof(vector)-1) bytes below the address of the 13500 // original unaligned load. 13501 MachineFunction &MF = DAG.getMachineFunction(); 13502 MachineMemOperand *BaseMMO = 13503 MF.getMachineMemOperand(LD->getMemOperand(), 13504 -(long)MemVT.getStoreSize()+1, 13505 2*MemVT.getStoreSize()-1); 13506 13507 // Create the new base load. 13508 SDValue LDXIntID = 13509 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13510 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13511 SDValue BaseLoad = 13512 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13513 DAG.getVTList(PermTy, MVT::Other), 13514 BaseLoadOps, LDTy, BaseMMO); 13515 13516 // Note that the value of IncOffset (which is provided to the next 13517 // load's pointer info offset value, and thus used to calculate the 13518 // alignment), and the value of IncValue (which is actually used to 13519 // increment the pointer value) are different! This is because we 13520 // require the next load to appear to be aligned, even though it 13521 // is actually offset from the base pointer by a lesser amount. 13522 int IncOffset = VT.getSizeInBits() / 8; 13523 int IncValue = IncOffset; 13524 13525 // Walk (both up and down) the chain looking for another load at the real 13526 // (aligned) offset (the alignment of the other load does not matter in 13527 // this case). If found, then do not use the offset reduction trick, as 13528 // that will prevent the loads from being later combined (as they would 13529 // otherwise be duplicates). 13530 if (!findConsecutiveLoad(LD, DAG)) 13531 --IncValue; 13532 13533 SDValue Increment = 13534 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 13535 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 13536 13537 MachineMemOperand *ExtraMMO = 13538 MF.getMachineMemOperand(LD->getMemOperand(), 13539 1, 2*MemVT.getStoreSize()-1); 13540 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 13541 SDValue ExtraLoad = 13542 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 13543 DAG.getVTList(PermTy, MVT::Other), 13544 ExtraLoadOps, LDTy, ExtraMMO); 13545 13546 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 13547 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 13548 13549 // Because vperm has a big-endian bias, we must reverse the order 13550 // of the input vectors and complement the permute control vector 13551 // when generating little endian code. We have already handled the 13552 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 13553 // and ExtraLoad here. 13554 SDValue Perm; 13555 if (isLittleEndian) 13556 Perm = BuildIntrinsicOp(IntrPerm, 13557 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 13558 else 13559 Perm = BuildIntrinsicOp(IntrPerm, 13560 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 13561 13562 if (VT != PermTy) 13563 Perm = Subtarget.hasAltivec() ? 13564 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 13565 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 13566 DAG.getTargetConstant(1, dl, MVT::i64)); 13567 // second argument is 1 because this rounding 13568 // is always exact. 13569 13570 // The output of the permutation is our loaded result, the TokenFactor is 13571 // our new chain. 13572 DCI.CombineTo(N, Perm, TF); 13573 return SDValue(N, 0); 13574 } 13575 } 13576 break; 13577 case ISD::INTRINSIC_WO_CHAIN: { 13578 bool isLittleEndian = Subtarget.isLittleEndian(); 13579 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 13580 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 13581 : Intrinsic::ppc_altivec_lvsl); 13582 if ((IID == Intr || 13583 IID == Intrinsic::ppc_qpx_qvlpcld || 13584 IID == Intrinsic::ppc_qpx_qvlpcls) && 13585 N->getOperand(1)->getOpcode() == ISD::ADD) { 13586 SDValue Add = N->getOperand(1); 13587 13588 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 13589 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 13590 13591 if (DAG.MaskedValueIsZero(Add->getOperand(1), 13592 APInt::getAllOnesValue(Bits /* alignment */) 13593 .zext(Add.getScalarValueSizeInBits()))) { 13594 SDNode *BasePtr = Add->getOperand(0).getNode(); 13595 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13596 UE = BasePtr->use_end(); 13597 UI != UE; ++UI) { 13598 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13599 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 13600 // We've found another LVSL/LVSR, and this address is an aligned 13601 // multiple of that one. The results will be the same, so use the 13602 // one we've just found instead. 13603 13604 return SDValue(*UI, 0); 13605 } 13606 } 13607 } 13608 13609 if (isa<ConstantSDNode>(Add->getOperand(1))) { 13610 SDNode *BasePtr = Add->getOperand(0).getNode(); 13611 for (SDNode::use_iterator UI = BasePtr->use_begin(), 13612 UE = BasePtr->use_end(); UI != UE; ++UI) { 13613 if (UI->getOpcode() == ISD::ADD && 13614 isa<ConstantSDNode>(UI->getOperand(1)) && 13615 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 13616 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 13617 (1ULL << Bits) == 0) { 13618 SDNode *OtherAdd = *UI; 13619 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 13620 VE = OtherAdd->use_end(); VI != VE; ++VI) { 13621 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13622 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 13623 return SDValue(*VI, 0); 13624 } 13625 } 13626 } 13627 } 13628 } 13629 } 13630 13631 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 13632 // Expose the vabsduw/h/b opportunity for down stream 13633 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 13634 (IID == Intrinsic::ppc_altivec_vmaxsw || 13635 IID == Intrinsic::ppc_altivec_vmaxsh || 13636 IID == Intrinsic::ppc_altivec_vmaxsb)) { 13637 SDValue V1 = N->getOperand(1); 13638 SDValue V2 = N->getOperand(2); 13639 if ((V1.getSimpleValueType() == MVT::v4i32 || 13640 V1.getSimpleValueType() == MVT::v8i16 || 13641 V1.getSimpleValueType() == MVT::v16i8) && 13642 V1.getSimpleValueType() == V2.getSimpleValueType()) { 13643 // (0-a, a) 13644 if (V1.getOpcode() == ISD::SUB && 13645 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 13646 V1.getOperand(1) == V2) { 13647 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 13648 } 13649 // (a, 0-a) 13650 if (V2.getOpcode() == ISD::SUB && 13651 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 13652 V2.getOperand(1) == V1) { 13653 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13654 } 13655 // (x-y, y-x) 13656 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 13657 V1.getOperand(0) == V2.getOperand(1) && 13658 V1.getOperand(1) == V2.getOperand(0)) { 13659 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 13660 } 13661 } 13662 } 13663 } 13664 13665 break; 13666 case ISD::INTRINSIC_W_CHAIN: 13667 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13668 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13669 if (Subtarget.needsSwapsForVSXMemOps()) { 13670 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13671 default: 13672 break; 13673 case Intrinsic::ppc_vsx_lxvw4x: 13674 case Intrinsic::ppc_vsx_lxvd2x: 13675 return expandVSXLoadForLE(N, DCI); 13676 } 13677 } 13678 break; 13679 case ISD::INTRINSIC_VOID: 13680 // For little endian, VSX stores require generating xxswapd/stxvd2x. 13681 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13682 if (Subtarget.needsSwapsForVSXMemOps()) { 13683 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13684 default: 13685 break; 13686 case Intrinsic::ppc_vsx_stxvw4x: 13687 case Intrinsic::ppc_vsx_stxvd2x: 13688 return expandVSXStoreForLE(N, DCI); 13689 } 13690 } 13691 break; 13692 case ISD::BSWAP: 13693 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 13694 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 13695 N->getOperand(0).hasOneUse() && 13696 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 13697 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 13698 N->getValueType(0) == MVT::i64))) { 13699 SDValue Load = N->getOperand(0); 13700 LoadSDNode *LD = cast<LoadSDNode>(Load); 13701 // Create the byte-swapping load. 13702 SDValue Ops[] = { 13703 LD->getChain(), // Chain 13704 LD->getBasePtr(), // Ptr 13705 DAG.getValueType(N->getValueType(0)) // VT 13706 }; 13707 SDValue BSLoad = 13708 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 13709 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 13710 MVT::i64 : MVT::i32, MVT::Other), 13711 Ops, LD->getMemoryVT(), LD->getMemOperand()); 13712 13713 // If this is an i16 load, insert the truncate. 13714 SDValue ResVal = BSLoad; 13715 if (N->getValueType(0) == MVT::i16) 13716 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 13717 13718 // First, combine the bswap away. This makes the value produced by the 13719 // load dead. 13720 DCI.CombineTo(N, ResVal); 13721 13722 // Next, combine the load away, we give it a bogus result value but a real 13723 // chain result. The result value is dead because the bswap is dead. 13724 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 13725 13726 // Return N so it doesn't get rechecked! 13727 return SDValue(N, 0); 13728 } 13729 break; 13730 case PPCISD::VCMP: 13731 // If a VCMPo node already exists with exactly the same operands as this 13732 // node, use its result instead of this node (VCMPo computes both a CR6 and 13733 // a normal output). 13734 // 13735 if (!N->getOperand(0).hasOneUse() && 13736 !N->getOperand(1).hasOneUse() && 13737 !N->getOperand(2).hasOneUse()) { 13738 13739 // Scan all of the users of the LHS, looking for VCMPo's that match. 13740 SDNode *VCMPoNode = nullptr; 13741 13742 SDNode *LHSN = N->getOperand(0).getNode(); 13743 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 13744 UI != E; ++UI) 13745 if (UI->getOpcode() == PPCISD::VCMPo && 13746 UI->getOperand(1) == N->getOperand(1) && 13747 UI->getOperand(2) == N->getOperand(2) && 13748 UI->getOperand(0) == N->getOperand(0)) { 13749 VCMPoNode = *UI; 13750 break; 13751 } 13752 13753 // If there is no VCMPo node, or if the flag value has a single use, don't 13754 // transform this. 13755 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 13756 break; 13757 13758 // Look at the (necessarily single) use of the flag value. If it has a 13759 // chain, this transformation is more complex. Note that multiple things 13760 // could use the value result, which we should ignore. 13761 SDNode *FlagUser = nullptr; 13762 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 13763 FlagUser == nullptr; ++UI) { 13764 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 13765 SDNode *User = *UI; 13766 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 13767 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 13768 FlagUser = User; 13769 break; 13770 } 13771 } 13772 } 13773 13774 // If the user is a MFOCRF instruction, we know this is safe. 13775 // Otherwise we give up for right now. 13776 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 13777 return SDValue(VCMPoNode, 0); 13778 } 13779 break; 13780 case ISD::BRCOND: { 13781 SDValue Cond = N->getOperand(1); 13782 SDValue Target = N->getOperand(2); 13783 13784 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13785 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 13786 Intrinsic::loop_decrement) { 13787 13788 // We now need to make the intrinsic dead (it cannot be instruction 13789 // selected). 13790 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 13791 assert(Cond.getNode()->hasOneUse() && 13792 "Counter decrement has more than one use"); 13793 13794 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 13795 N->getOperand(0), Target); 13796 } 13797 } 13798 break; 13799 case ISD::BR_CC: { 13800 // If this is a branch on an altivec predicate comparison, lower this so 13801 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 13802 // lowering is done pre-legalize, because the legalizer lowers the predicate 13803 // compare down to code that is difficult to reassemble. 13804 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 13805 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 13806 13807 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 13808 // value. If so, pass-through the AND to get to the intrinsic. 13809 if (LHS.getOpcode() == ISD::AND && 13810 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 13811 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 13812 Intrinsic::loop_decrement && 13813 isa<ConstantSDNode>(LHS.getOperand(1)) && 13814 !isNullConstant(LHS.getOperand(1))) 13815 LHS = LHS.getOperand(0); 13816 13817 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 13818 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 13819 Intrinsic::loop_decrement && 13820 isa<ConstantSDNode>(RHS)) { 13821 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 13822 "Counter decrement comparison is not EQ or NE"); 13823 13824 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13825 bool isBDNZ = (CC == ISD::SETEQ && Val) || 13826 (CC == ISD::SETNE && !Val); 13827 13828 // We now need to make the intrinsic dead (it cannot be instruction 13829 // selected). 13830 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 13831 assert(LHS.getNode()->hasOneUse() && 13832 "Counter decrement has more than one use"); 13833 13834 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 13835 N->getOperand(0), N->getOperand(4)); 13836 } 13837 13838 int CompareOpc; 13839 bool isDot; 13840 13841 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 13842 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 13843 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 13844 assert(isDot && "Can't compare against a vector result!"); 13845 13846 // If this is a comparison against something other than 0/1, then we know 13847 // that the condition is never/always true. 13848 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 13849 if (Val != 0 && Val != 1) { 13850 if (CC == ISD::SETEQ) // Cond never true, remove branch. 13851 return N->getOperand(0); 13852 // Always !=, turn it into an unconditional branch. 13853 return DAG.getNode(ISD::BR, dl, MVT::Other, 13854 N->getOperand(0), N->getOperand(4)); 13855 } 13856 13857 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 13858 13859 // Create the PPCISD altivec 'dot' comparison node. 13860 SDValue Ops[] = { 13861 LHS.getOperand(2), // LHS of compare 13862 LHS.getOperand(3), // RHS of compare 13863 DAG.getConstant(CompareOpc, dl, MVT::i32) 13864 }; 13865 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 13866 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 13867 13868 // Unpack the result based on how the target uses it. 13869 PPC::Predicate CompOpc; 13870 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 13871 default: // Can't happen, don't crash on invalid number though. 13872 case 0: // Branch on the value of the EQ bit of CR6. 13873 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 13874 break; 13875 case 1: // Branch on the inverted value of the EQ bit of CR6. 13876 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 13877 break; 13878 case 2: // Branch on the value of the LT bit of CR6. 13879 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 13880 break; 13881 case 3: // Branch on the inverted value of the LT bit of CR6. 13882 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 13883 break; 13884 } 13885 13886 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 13887 DAG.getConstant(CompOpc, dl, MVT::i32), 13888 DAG.getRegister(PPC::CR6, MVT::i32), 13889 N->getOperand(4), CompNode.getValue(1)); 13890 } 13891 break; 13892 } 13893 case ISD::BUILD_VECTOR: 13894 return DAGCombineBuildVector(N, DCI); 13895 case ISD::ABS: 13896 return combineABS(N, DCI); 13897 case ISD::VSELECT: 13898 return combineVSelect(N, DCI); 13899 } 13900 13901 return SDValue(); 13902 } 13903 13904 SDValue 13905 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 13906 SelectionDAG &DAG, 13907 SmallVectorImpl<SDNode *> &Created) const { 13908 // fold (sdiv X, pow2) 13909 EVT VT = N->getValueType(0); 13910 if (VT == MVT::i64 && !Subtarget.isPPC64()) 13911 return SDValue(); 13912 if ((VT != MVT::i32 && VT != MVT::i64) || 13913 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 13914 return SDValue(); 13915 13916 SDLoc DL(N); 13917 SDValue N0 = N->getOperand(0); 13918 13919 bool IsNegPow2 = (-Divisor).isPowerOf2(); 13920 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 13921 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 13922 13923 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 13924 Created.push_back(Op.getNode()); 13925 13926 if (IsNegPow2) { 13927 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 13928 Created.push_back(Op.getNode()); 13929 } 13930 13931 return Op; 13932 } 13933 13934 //===----------------------------------------------------------------------===// 13935 // Inline Assembly Support 13936 //===----------------------------------------------------------------------===// 13937 13938 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 13939 KnownBits &Known, 13940 const APInt &DemandedElts, 13941 const SelectionDAG &DAG, 13942 unsigned Depth) const { 13943 Known.resetAll(); 13944 switch (Op.getOpcode()) { 13945 default: break; 13946 case PPCISD::LBRX: { 13947 // lhbrx is known to have the top bits cleared out. 13948 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 13949 Known.Zero = 0xFFFF0000; 13950 break; 13951 } 13952 case ISD::INTRINSIC_WO_CHAIN: { 13953 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 13954 default: break; 13955 case Intrinsic::ppc_altivec_vcmpbfp_p: 13956 case Intrinsic::ppc_altivec_vcmpeqfp_p: 13957 case Intrinsic::ppc_altivec_vcmpequb_p: 13958 case Intrinsic::ppc_altivec_vcmpequh_p: 13959 case Intrinsic::ppc_altivec_vcmpequw_p: 13960 case Intrinsic::ppc_altivec_vcmpequd_p: 13961 case Intrinsic::ppc_altivec_vcmpgefp_p: 13962 case Intrinsic::ppc_altivec_vcmpgtfp_p: 13963 case Intrinsic::ppc_altivec_vcmpgtsb_p: 13964 case Intrinsic::ppc_altivec_vcmpgtsh_p: 13965 case Intrinsic::ppc_altivec_vcmpgtsw_p: 13966 case Intrinsic::ppc_altivec_vcmpgtsd_p: 13967 case Intrinsic::ppc_altivec_vcmpgtub_p: 13968 case Intrinsic::ppc_altivec_vcmpgtuh_p: 13969 case Intrinsic::ppc_altivec_vcmpgtuw_p: 13970 case Intrinsic::ppc_altivec_vcmpgtud_p: 13971 Known.Zero = ~1U; // All bits but the low one are known to be zero. 13972 break; 13973 } 13974 } 13975 } 13976 } 13977 13978 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 13979 switch (Subtarget.getDarwinDirective()) { 13980 default: break; 13981 case PPC::DIR_970: 13982 case PPC::DIR_PWR4: 13983 case PPC::DIR_PWR5: 13984 case PPC::DIR_PWR5X: 13985 case PPC::DIR_PWR6: 13986 case PPC::DIR_PWR6X: 13987 case PPC::DIR_PWR7: 13988 case PPC::DIR_PWR8: 13989 case PPC::DIR_PWR9: { 13990 if (!ML) 13991 break; 13992 13993 if (!DisableInnermostLoopAlign32) { 13994 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 13995 // so that we can decrease cache misses and branch-prediction misses. 13996 // Actual alignment of the loop will depend on the hotness check and other 13997 // logic in alignBlocks. 13998 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 13999 return 5; 14000 } 14001 14002 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14003 14004 // For small loops (between 5 and 8 instructions), align to a 32-byte 14005 // boundary so that the entire loop fits in one instruction-cache line. 14006 uint64_t LoopSize = 0; 14007 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14008 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14009 LoopSize += TII->getInstSizeInBytes(*J); 14010 if (LoopSize > 32) 14011 break; 14012 } 14013 14014 if (LoopSize > 16 && LoopSize <= 32) 14015 return 5; 14016 14017 break; 14018 } 14019 } 14020 14021 return TargetLowering::getPrefLoopAlignment(ML); 14022 } 14023 14024 /// getConstraintType - Given a constraint, return the type of 14025 /// constraint it is for this target. 14026 PPCTargetLowering::ConstraintType 14027 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14028 if (Constraint.size() == 1) { 14029 switch (Constraint[0]) { 14030 default: break; 14031 case 'b': 14032 case 'r': 14033 case 'f': 14034 case 'd': 14035 case 'v': 14036 case 'y': 14037 return C_RegisterClass; 14038 case 'Z': 14039 // FIXME: While Z does indicate a memory constraint, it specifically 14040 // indicates an r+r address (used in conjunction with the 'y' modifier 14041 // in the replacement string). Currently, we're forcing the base 14042 // register to be r0 in the asm printer (which is interpreted as zero) 14043 // and forming the complete address in the second register. This is 14044 // suboptimal. 14045 return C_Memory; 14046 } 14047 } else if (Constraint == "wc") { // individual CR bits. 14048 return C_RegisterClass; 14049 } else if (Constraint == "wa" || Constraint == "wd" || 14050 Constraint == "wf" || Constraint == "ws" || 14051 Constraint == "wi" || Constraint == "ww") { 14052 return C_RegisterClass; // VSX registers. 14053 } 14054 return TargetLowering::getConstraintType(Constraint); 14055 } 14056 14057 /// Examine constraint type and operand type and determine a weight value. 14058 /// This object must already have been set up with the operand type 14059 /// and the current alternative constraint selected. 14060 TargetLowering::ConstraintWeight 14061 PPCTargetLowering::getSingleConstraintMatchWeight( 14062 AsmOperandInfo &info, const char *constraint) const { 14063 ConstraintWeight weight = CW_Invalid; 14064 Value *CallOperandVal = info.CallOperandVal; 14065 // If we don't have a value, we can't do a match, 14066 // but allow it at the lowest weight. 14067 if (!CallOperandVal) 14068 return CW_Default; 14069 Type *type = CallOperandVal->getType(); 14070 14071 // Look at the constraint type. 14072 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14073 return CW_Register; // an individual CR bit. 14074 else if ((StringRef(constraint) == "wa" || 14075 StringRef(constraint) == "wd" || 14076 StringRef(constraint) == "wf") && 14077 type->isVectorTy()) 14078 return CW_Register; 14079 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14080 return CW_Register; // just hold 64-bit integers data. 14081 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14082 return CW_Register; 14083 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14084 return CW_Register; 14085 14086 switch (*constraint) { 14087 default: 14088 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14089 break; 14090 case 'b': 14091 if (type->isIntegerTy()) 14092 weight = CW_Register; 14093 break; 14094 case 'f': 14095 if (type->isFloatTy()) 14096 weight = CW_Register; 14097 break; 14098 case 'd': 14099 if (type->isDoubleTy()) 14100 weight = CW_Register; 14101 break; 14102 case 'v': 14103 if (type->isVectorTy()) 14104 weight = CW_Register; 14105 break; 14106 case 'y': 14107 weight = CW_Register; 14108 break; 14109 case 'Z': 14110 weight = CW_Memory; 14111 break; 14112 } 14113 return weight; 14114 } 14115 14116 std::pair<unsigned, const TargetRegisterClass *> 14117 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14118 StringRef Constraint, 14119 MVT VT) const { 14120 if (Constraint.size() == 1) { 14121 // GCC RS6000 Constraint Letters 14122 switch (Constraint[0]) { 14123 case 'b': // R1-R31 14124 if (VT == MVT::i64 && Subtarget.isPPC64()) 14125 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14126 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14127 case 'r': // R0-R31 14128 if (VT == MVT::i64 && Subtarget.isPPC64()) 14129 return std::make_pair(0U, &PPC::G8RCRegClass); 14130 return std::make_pair(0U, &PPC::GPRCRegClass); 14131 // 'd' and 'f' constraints are both defined to be "the floating point 14132 // registers", where one is for 32-bit and the other for 64-bit. We don't 14133 // really care overly much here so just give them all the same reg classes. 14134 case 'd': 14135 case 'f': 14136 if (Subtarget.hasSPE()) { 14137 if (VT == MVT::f32 || VT == MVT::i32) 14138 return std::make_pair(0U, &PPC::SPE4RCRegClass); 14139 if (VT == MVT::f64 || VT == MVT::i64) 14140 return std::make_pair(0U, &PPC::SPERCRegClass); 14141 } else { 14142 if (VT == MVT::f32 || VT == MVT::i32) 14143 return std::make_pair(0U, &PPC::F4RCRegClass); 14144 if (VT == MVT::f64 || VT == MVT::i64) 14145 return std::make_pair(0U, &PPC::F8RCRegClass); 14146 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14147 return std::make_pair(0U, &PPC::QFRCRegClass); 14148 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14149 return std::make_pair(0U, &PPC::QSRCRegClass); 14150 } 14151 break; 14152 case 'v': 14153 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14154 return std::make_pair(0U, &PPC::QFRCRegClass); 14155 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14156 return std::make_pair(0U, &PPC::QSRCRegClass); 14157 if (Subtarget.hasAltivec()) 14158 return std::make_pair(0U, &PPC::VRRCRegClass); 14159 break; 14160 case 'y': // crrc 14161 return std::make_pair(0U, &PPC::CRRCRegClass); 14162 } 14163 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14164 // An individual CR bit. 14165 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14166 } else if ((Constraint == "wa" || Constraint == "wd" || 14167 Constraint == "wf" || Constraint == "wi") && 14168 Subtarget.hasVSX()) { 14169 return std::make_pair(0U, &PPC::VSRCRegClass); 14170 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14171 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14172 return std::make_pair(0U, &PPC::VSSRCRegClass); 14173 else 14174 return std::make_pair(0U, &PPC::VSFRCRegClass); 14175 } 14176 14177 std::pair<unsigned, const TargetRegisterClass *> R = 14178 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14179 14180 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14181 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14182 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14183 // register. 14184 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14185 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14186 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14187 PPC::GPRCRegClass.contains(R.first)) 14188 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14189 PPC::sub_32, &PPC::G8RCRegClass), 14190 &PPC::G8RCRegClass); 14191 14192 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14193 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14194 R.first = PPC::CR0; 14195 R.second = &PPC::CRRCRegClass; 14196 } 14197 14198 return R; 14199 } 14200 14201 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14202 /// vector. If it is invalid, don't add anything to Ops. 14203 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14204 std::string &Constraint, 14205 std::vector<SDValue>&Ops, 14206 SelectionDAG &DAG) const { 14207 SDValue Result; 14208 14209 // Only support length 1 constraints. 14210 if (Constraint.length() > 1) return; 14211 14212 char Letter = Constraint[0]; 14213 switch (Letter) { 14214 default: break; 14215 case 'I': 14216 case 'J': 14217 case 'K': 14218 case 'L': 14219 case 'M': 14220 case 'N': 14221 case 'O': 14222 case 'P': { 14223 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14224 if (!CST) return; // Must be an immediate to match. 14225 SDLoc dl(Op); 14226 int64_t Value = CST->getSExtValue(); 14227 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14228 // numbers are printed as such. 14229 switch (Letter) { 14230 default: llvm_unreachable("Unknown constraint letter!"); 14231 case 'I': // "I" is a signed 16-bit constant. 14232 if (isInt<16>(Value)) 14233 Result = DAG.getTargetConstant(Value, dl, TCVT); 14234 break; 14235 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14236 if (isShiftedUInt<16, 16>(Value)) 14237 Result = DAG.getTargetConstant(Value, dl, TCVT); 14238 break; 14239 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14240 if (isShiftedInt<16, 16>(Value)) 14241 Result = DAG.getTargetConstant(Value, dl, TCVT); 14242 break; 14243 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14244 if (isUInt<16>(Value)) 14245 Result = DAG.getTargetConstant(Value, dl, TCVT); 14246 break; 14247 case 'M': // "M" is a constant that is greater than 31. 14248 if (Value > 31) 14249 Result = DAG.getTargetConstant(Value, dl, TCVT); 14250 break; 14251 case 'N': // "N" is a positive constant that is an exact power of two. 14252 if (Value > 0 && isPowerOf2_64(Value)) 14253 Result = DAG.getTargetConstant(Value, dl, TCVT); 14254 break; 14255 case 'O': // "O" is the constant zero. 14256 if (Value == 0) 14257 Result = DAG.getTargetConstant(Value, dl, TCVT); 14258 break; 14259 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14260 if (isInt<16>(-Value)) 14261 Result = DAG.getTargetConstant(Value, dl, TCVT); 14262 break; 14263 } 14264 break; 14265 } 14266 } 14267 14268 if (Result.getNode()) { 14269 Ops.push_back(Result); 14270 return; 14271 } 14272 14273 // Handle standard constraint letters. 14274 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14275 } 14276 14277 // isLegalAddressingMode - Return true if the addressing mode represented 14278 // by AM is legal for this target, for a load/store of the specified type. 14279 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14280 const AddrMode &AM, Type *Ty, 14281 unsigned AS, Instruction *I) const { 14282 // PPC does not allow r+i addressing modes for vectors! 14283 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14284 return false; 14285 14286 // PPC allows a sign-extended 16-bit immediate field. 14287 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14288 return false; 14289 14290 // No global is ever allowed as a base. 14291 if (AM.BaseGV) 14292 return false; 14293 14294 // PPC only support r+r, 14295 switch (AM.Scale) { 14296 case 0: // "r+i" or just "i", depending on HasBaseReg. 14297 break; 14298 case 1: 14299 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14300 return false; 14301 // Otherwise we have r+r or r+i. 14302 break; 14303 case 2: 14304 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14305 return false; 14306 // Allow 2*r as r+r. 14307 break; 14308 default: 14309 // No other scales are supported. 14310 return false; 14311 } 14312 14313 return true; 14314 } 14315 14316 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14317 SelectionDAG &DAG) const { 14318 MachineFunction &MF = DAG.getMachineFunction(); 14319 MachineFrameInfo &MFI = MF.getFrameInfo(); 14320 MFI.setReturnAddressIsTaken(true); 14321 14322 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14323 return SDValue(); 14324 14325 SDLoc dl(Op); 14326 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14327 14328 // Make sure the function does not optimize away the store of the RA to 14329 // the stack. 14330 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14331 FuncInfo->setLRStoreRequired(); 14332 bool isPPC64 = Subtarget.isPPC64(); 14333 auto PtrVT = getPointerTy(MF.getDataLayout()); 14334 14335 if (Depth > 0) { 14336 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14337 SDValue Offset = 14338 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14339 isPPC64 ? MVT::i64 : MVT::i32); 14340 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14341 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14342 MachinePointerInfo()); 14343 } 14344 14345 // Just load the return address off the stack. 14346 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14347 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14348 MachinePointerInfo()); 14349 } 14350 14351 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14352 SelectionDAG &DAG) const { 14353 SDLoc dl(Op); 14354 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14355 14356 MachineFunction &MF = DAG.getMachineFunction(); 14357 MachineFrameInfo &MFI = MF.getFrameInfo(); 14358 MFI.setFrameAddressIsTaken(true); 14359 14360 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14361 bool isPPC64 = PtrVT == MVT::i64; 14362 14363 // Naked functions never have a frame pointer, and so we use r1. For all 14364 // other functions, this decision must be delayed until during PEI. 14365 unsigned FrameReg; 14366 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14367 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14368 else 14369 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14370 14371 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14372 PtrVT); 14373 while (Depth--) 14374 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14375 FrameAddr, MachinePointerInfo()); 14376 return FrameAddr; 14377 } 14378 14379 // FIXME? Maybe this could be a TableGen attribute on some registers and 14380 // this table could be generated automatically from RegInfo. 14381 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, 14382 SelectionDAG &DAG) const { 14383 bool isPPC64 = Subtarget.isPPC64(); 14384 bool isDarwinABI = Subtarget.isDarwinABI(); 14385 14386 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || 14387 (!isPPC64 && VT != MVT::i32)) 14388 report_fatal_error("Invalid register global variable type"); 14389 14390 bool is64Bit = isPPC64 && VT == MVT::i64; 14391 unsigned Reg = StringSwitch<unsigned>(RegName) 14392 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14393 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) 14394 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : 14395 (is64Bit ? PPC::X13 : PPC::R13)) 14396 .Default(0); 14397 14398 if (Reg) 14399 return Reg; 14400 report_fatal_error("Invalid register name global variable"); 14401 } 14402 14403 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14404 // 32-bit SVR4 ABI access everything as got-indirect. 14405 if (Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) 14406 return true; 14407 14408 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14409 // If it is small or large code model, module locals are accessed 14410 // indirectly by loading their address from .toc/.got. The difference 14411 // is that for large code model we have ADDIStocHA8 + LDtocL and for 14412 // small code model we simply have LDtoc. 14413 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14414 return true; 14415 14416 // JumpTable and BlockAddress are accessed as got-indirect. 14417 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14418 return true; 14419 14420 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 14421 const GlobalValue *GV = G->getGlobal(); 14422 unsigned char GVFlags = Subtarget.classifyGlobalReference(GV); 14423 // The NLP flag indicates that a global access has to use an 14424 // extra indirection. 14425 if (GVFlags & PPCII::MO_NLP_FLAG) 14426 return true; 14427 } 14428 14429 return false; 14430 } 14431 14432 bool 14433 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14434 // The PowerPC target isn't yet aware of offsets. 14435 return false; 14436 } 14437 14438 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14439 const CallInst &I, 14440 MachineFunction &MF, 14441 unsigned Intrinsic) const { 14442 switch (Intrinsic) { 14443 case Intrinsic::ppc_qpx_qvlfd: 14444 case Intrinsic::ppc_qpx_qvlfs: 14445 case Intrinsic::ppc_qpx_qvlfcd: 14446 case Intrinsic::ppc_qpx_qvlfcs: 14447 case Intrinsic::ppc_qpx_qvlfiwa: 14448 case Intrinsic::ppc_qpx_qvlfiwz: 14449 case Intrinsic::ppc_altivec_lvx: 14450 case Intrinsic::ppc_altivec_lvxl: 14451 case Intrinsic::ppc_altivec_lvebx: 14452 case Intrinsic::ppc_altivec_lvehx: 14453 case Intrinsic::ppc_altivec_lvewx: 14454 case Intrinsic::ppc_vsx_lxvd2x: 14455 case Intrinsic::ppc_vsx_lxvw4x: { 14456 EVT VT; 14457 switch (Intrinsic) { 14458 case Intrinsic::ppc_altivec_lvebx: 14459 VT = MVT::i8; 14460 break; 14461 case Intrinsic::ppc_altivec_lvehx: 14462 VT = MVT::i16; 14463 break; 14464 case Intrinsic::ppc_altivec_lvewx: 14465 VT = MVT::i32; 14466 break; 14467 case Intrinsic::ppc_vsx_lxvd2x: 14468 VT = MVT::v2f64; 14469 break; 14470 case Intrinsic::ppc_qpx_qvlfd: 14471 VT = MVT::v4f64; 14472 break; 14473 case Intrinsic::ppc_qpx_qvlfs: 14474 VT = MVT::v4f32; 14475 break; 14476 case Intrinsic::ppc_qpx_qvlfcd: 14477 VT = MVT::v2f64; 14478 break; 14479 case Intrinsic::ppc_qpx_qvlfcs: 14480 VT = MVT::v2f32; 14481 break; 14482 default: 14483 VT = MVT::v4i32; 14484 break; 14485 } 14486 14487 Info.opc = ISD::INTRINSIC_W_CHAIN; 14488 Info.memVT = VT; 14489 Info.ptrVal = I.getArgOperand(0); 14490 Info.offset = -VT.getStoreSize()+1; 14491 Info.size = 2*VT.getStoreSize()-1; 14492 Info.align = 1; 14493 Info.flags = MachineMemOperand::MOLoad; 14494 return true; 14495 } 14496 case Intrinsic::ppc_qpx_qvlfda: 14497 case Intrinsic::ppc_qpx_qvlfsa: 14498 case Intrinsic::ppc_qpx_qvlfcda: 14499 case Intrinsic::ppc_qpx_qvlfcsa: 14500 case Intrinsic::ppc_qpx_qvlfiwaa: 14501 case Intrinsic::ppc_qpx_qvlfiwza: { 14502 EVT VT; 14503 switch (Intrinsic) { 14504 case Intrinsic::ppc_qpx_qvlfda: 14505 VT = MVT::v4f64; 14506 break; 14507 case Intrinsic::ppc_qpx_qvlfsa: 14508 VT = MVT::v4f32; 14509 break; 14510 case Intrinsic::ppc_qpx_qvlfcda: 14511 VT = MVT::v2f64; 14512 break; 14513 case Intrinsic::ppc_qpx_qvlfcsa: 14514 VT = MVT::v2f32; 14515 break; 14516 default: 14517 VT = MVT::v4i32; 14518 break; 14519 } 14520 14521 Info.opc = ISD::INTRINSIC_W_CHAIN; 14522 Info.memVT = VT; 14523 Info.ptrVal = I.getArgOperand(0); 14524 Info.offset = 0; 14525 Info.size = VT.getStoreSize(); 14526 Info.align = 1; 14527 Info.flags = MachineMemOperand::MOLoad; 14528 return true; 14529 } 14530 case Intrinsic::ppc_qpx_qvstfd: 14531 case Intrinsic::ppc_qpx_qvstfs: 14532 case Intrinsic::ppc_qpx_qvstfcd: 14533 case Intrinsic::ppc_qpx_qvstfcs: 14534 case Intrinsic::ppc_qpx_qvstfiw: 14535 case Intrinsic::ppc_altivec_stvx: 14536 case Intrinsic::ppc_altivec_stvxl: 14537 case Intrinsic::ppc_altivec_stvebx: 14538 case Intrinsic::ppc_altivec_stvehx: 14539 case Intrinsic::ppc_altivec_stvewx: 14540 case Intrinsic::ppc_vsx_stxvd2x: 14541 case Intrinsic::ppc_vsx_stxvw4x: { 14542 EVT VT; 14543 switch (Intrinsic) { 14544 case Intrinsic::ppc_altivec_stvebx: 14545 VT = MVT::i8; 14546 break; 14547 case Intrinsic::ppc_altivec_stvehx: 14548 VT = MVT::i16; 14549 break; 14550 case Intrinsic::ppc_altivec_stvewx: 14551 VT = MVT::i32; 14552 break; 14553 case Intrinsic::ppc_vsx_stxvd2x: 14554 VT = MVT::v2f64; 14555 break; 14556 case Intrinsic::ppc_qpx_qvstfd: 14557 VT = MVT::v4f64; 14558 break; 14559 case Intrinsic::ppc_qpx_qvstfs: 14560 VT = MVT::v4f32; 14561 break; 14562 case Intrinsic::ppc_qpx_qvstfcd: 14563 VT = MVT::v2f64; 14564 break; 14565 case Intrinsic::ppc_qpx_qvstfcs: 14566 VT = MVT::v2f32; 14567 break; 14568 default: 14569 VT = MVT::v4i32; 14570 break; 14571 } 14572 14573 Info.opc = ISD::INTRINSIC_VOID; 14574 Info.memVT = VT; 14575 Info.ptrVal = I.getArgOperand(1); 14576 Info.offset = -VT.getStoreSize()+1; 14577 Info.size = 2*VT.getStoreSize()-1; 14578 Info.align = 1; 14579 Info.flags = MachineMemOperand::MOStore; 14580 return true; 14581 } 14582 case Intrinsic::ppc_qpx_qvstfda: 14583 case Intrinsic::ppc_qpx_qvstfsa: 14584 case Intrinsic::ppc_qpx_qvstfcda: 14585 case Intrinsic::ppc_qpx_qvstfcsa: 14586 case Intrinsic::ppc_qpx_qvstfiwa: { 14587 EVT VT; 14588 switch (Intrinsic) { 14589 case Intrinsic::ppc_qpx_qvstfda: 14590 VT = MVT::v4f64; 14591 break; 14592 case Intrinsic::ppc_qpx_qvstfsa: 14593 VT = MVT::v4f32; 14594 break; 14595 case Intrinsic::ppc_qpx_qvstfcda: 14596 VT = MVT::v2f64; 14597 break; 14598 case Intrinsic::ppc_qpx_qvstfcsa: 14599 VT = MVT::v2f32; 14600 break; 14601 default: 14602 VT = MVT::v4i32; 14603 break; 14604 } 14605 14606 Info.opc = ISD::INTRINSIC_VOID; 14607 Info.memVT = VT; 14608 Info.ptrVal = I.getArgOperand(1); 14609 Info.offset = 0; 14610 Info.size = VT.getStoreSize(); 14611 Info.align = 1; 14612 Info.flags = MachineMemOperand::MOStore; 14613 return true; 14614 } 14615 default: 14616 break; 14617 } 14618 14619 return false; 14620 } 14621 14622 /// getOptimalMemOpType - Returns the target specific optimal type for load 14623 /// and store operations as a result of memset, memcpy, and memmove 14624 /// lowering. If DstAlign is zero that means it's safe to destination 14625 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 14626 /// means there isn't a need to check it against alignment requirement, 14627 /// probably because the source does not need to be loaded. If 'IsMemset' is 14628 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that 14629 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy 14630 /// source is constant so it does not need to be loaded. 14631 /// It returns EVT::Other if the type should be determined using generic 14632 /// target-independent logic. 14633 EVT PPCTargetLowering::getOptimalMemOpType( 14634 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 14635 bool ZeroMemset, bool MemcpyStrSrc, 14636 const AttributeList &FuncAttributes) const { 14637 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 14638 // When expanding a memset, require at least two QPX instructions to cover 14639 // the cost of loading the value to be stored from the constant pool. 14640 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && 14641 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && 14642 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 14643 return MVT::v4f64; 14644 } 14645 14646 // We should use Altivec/VSX loads and stores when available. For unaligned 14647 // addresses, unaligned VSX loads are only fast starting with the P8. 14648 if (Subtarget.hasAltivec() && Size >= 16 && 14649 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || 14650 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 14651 return MVT::v4i32; 14652 } 14653 14654 if (Subtarget.isPPC64()) { 14655 return MVT::i64; 14656 } 14657 14658 return MVT::i32; 14659 } 14660 14661 /// Returns true if it is beneficial to convert a load of a constant 14662 /// to just the constant itself. 14663 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 14664 Type *Ty) const { 14665 assert(Ty->isIntegerTy()); 14666 14667 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 14668 return !(BitSize == 0 || BitSize > 64); 14669 } 14670 14671 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 14672 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 14673 return false; 14674 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 14675 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 14676 return NumBits1 == 64 && NumBits2 == 32; 14677 } 14678 14679 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 14680 if (!VT1.isInteger() || !VT2.isInteger()) 14681 return false; 14682 unsigned NumBits1 = VT1.getSizeInBits(); 14683 unsigned NumBits2 = VT2.getSizeInBits(); 14684 return NumBits1 == 64 && NumBits2 == 32; 14685 } 14686 14687 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 14688 // Generally speaking, zexts are not free, but they are free when they can be 14689 // folded with other operations. 14690 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 14691 EVT MemVT = LD->getMemoryVT(); 14692 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 14693 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 14694 (LD->getExtensionType() == ISD::NON_EXTLOAD || 14695 LD->getExtensionType() == ISD::ZEXTLOAD)) 14696 return true; 14697 } 14698 14699 // FIXME: Add other cases... 14700 // - 32-bit shifts with a zext to i64 14701 // - zext after ctlz, bswap, etc. 14702 // - zext after and by a constant mask 14703 14704 return TargetLowering::isZExtFree(Val, VT2); 14705 } 14706 14707 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 14708 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 14709 "invalid fpext types"); 14710 // Extending to float128 is not free. 14711 if (DestVT == MVT::f128) 14712 return false; 14713 return true; 14714 } 14715 14716 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 14717 return isInt<16>(Imm) || isUInt<16>(Imm); 14718 } 14719 14720 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 14721 return isInt<16>(Imm) || isUInt<16>(Imm); 14722 } 14723 14724 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 14725 unsigned, 14726 unsigned, 14727 MachineMemOperand::Flags, 14728 bool *Fast) const { 14729 if (DisablePPCUnaligned) 14730 return false; 14731 14732 // PowerPC supports unaligned memory access for simple non-vector types. 14733 // Although accessing unaligned addresses is not as efficient as accessing 14734 // aligned addresses, it is generally more efficient than manual expansion, 14735 // and generally only traps for software emulation when crossing page 14736 // boundaries. 14737 14738 if (!VT.isSimple()) 14739 return false; 14740 14741 if (VT.getSimpleVT().isVector()) { 14742 if (Subtarget.hasVSX()) { 14743 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 14744 VT != MVT::v4f32 && VT != MVT::v4i32) 14745 return false; 14746 } else { 14747 return false; 14748 } 14749 } 14750 14751 if (VT == MVT::ppcf128) 14752 return false; 14753 14754 if (Fast) 14755 *Fast = true; 14756 14757 return true; 14758 } 14759 14760 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 14761 VT = VT.getScalarType(); 14762 14763 if (!VT.isSimple()) 14764 return false; 14765 14766 switch (VT.getSimpleVT().SimpleTy) { 14767 case MVT::f32: 14768 case MVT::f64: 14769 return true; 14770 case MVT::f128: 14771 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 14772 default: 14773 break; 14774 } 14775 14776 return false; 14777 } 14778 14779 const MCPhysReg * 14780 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 14781 // LR is a callee-save register, but we must treat it as clobbered by any call 14782 // site. Hence we include LR in the scratch registers, which are in turn added 14783 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 14784 // to CTR, which is used by any indirect call. 14785 static const MCPhysReg ScratchRegs[] = { 14786 PPC::X12, PPC::LR8, PPC::CTR8, 0 14787 }; 14788 14789 return ScratchRegs; 14790 } 14791 14792 unsigned PPCTargetLowering::getExceptionPointerRegister( 14793 const Constant *PersonalityFn) const { 14794 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 14795 } 14796 14797 unsigned PPCTargetLowering::getExceptionSelectorRegister( 14798 const Constant *PersonalityFn) const { 14799 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 14800 } 14801 14802 bool 14803 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 14804 EVT VT , unsigned DefinedValues) const { 14805 if (VT == MVT::v2i64) 14806 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 14807 14808 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 14809 return true; 14810 14811 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 14812 } 14813 14814 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 14815 if (DisableILPPref || Subtarget.enableMachineScheduler()) 14816 return TargetLowering::getSchedulingPreference(N); 14817 14818 return Sched::ILP; 14819 } 14820 14821 // Create a fast isel object. 14822 FastISel * 14823 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 14824 const TargetLibraryInfo *LibInfo) const { 14825 return PPC::createFastISel(FuncInfo, LibInfo); 14826 } 14827 14828 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 14829 if (Subtarget.isDarwinABI()) return; 14830 if (!Subtarget.isPPC64()) return; 14831 14832 // Update IsSplitCSR in PPCFunctionInfo 14833 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 14834 PFI->setIsSplitCSR(true); 14835 } 14836 14837 void PPCTargetLowering::insertCopiesSplitCSR( 14838 MachineBasicBlock *Entry, 14839 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 14840 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 14841 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 14842 if (!IStart) 14843 return; 14844 14845 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 14846 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 14847 MachineBasicBlock::iterator MBBI = Entry->begin(); 14848 for (const MCPhysReg *I = IStart; *I; ++I) { 14849 const TargetRegisterClass *RC = nullptr; 14850 if (PPC::G8RCRegClass.contains(*I)) 14851 RC = &PPC::G8RCRegClass; 14852 else if (PPC::F8RCRegClass.contains(*I)) 14853 RC = &PPC::F8RCRegClass; 14854 else if (PPC::CRRCRegClass.contains(*I)) 14855 RC = &PPC::CRRCRegClass; 14856 else if (PPC::VRRCRegClass.contains(*I)) 14857 RC = &PPC::VRRCRegClass; 14858 else 14859 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 14860 14861 unsigned NewVR = MRI->createVirtualRegister(RC); 14862 // Create copy from CSR to a virtual register. 14863 // FIXME: this currently does not emit CFI pseudo-instructions, it works 14864 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 14865 // nounwind. If we want to generalize this later, we may need to emit 14866 // CFI pseudo-instructions. 14867 assert(Entry->getParent()->getFunction().hasFnAttribute( 14868 Attribute::NoUnwind) && 14869 "Function should be nounwind in insertCopiesSplitCSR!"); 14870 Entry->addLiveIn(*I); 14871 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 14872 .addReg(*I); 14873 14874 // Insert the copy-back instructions right before the terminator. 14875 for (auto *Exit : Exits) 14876 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 14877 TII->get(TargetOpcode::COPY), *I) 14878 .addReg(NewVR); 14879 } 14880 } 14881 14882 // Override to enable LOAD_STACK_GUARD lowering on Linux. 14883 bool PPCTargetLowering::useLoadStackGuardNode() const { 14884 if (!Subtarget.isTargetLinux()) 14885 return TargetLowering::useLoadStackGuardNode(); 14886 return true; 14887 } 14888 14889 // Override to disable global variable loading on Linux. 14890 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 14891 if (!Subtarget.isTargetLinux()) 14892 return TargetLowering::insertSSPDeclarations(M); 14893 } 14894 14895 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 14896 bool ForCodeSize) const { 14897 if (!VT.isSimple() || !Subtarget.hasVSX()) 14898 return false; 14899 14900 switch(VT.getSimpleVT().SimpleTy) { 14901 default: 14902 // For FP types that are currently not supported by PPC backend, return 14903 // false. Examples: f16, f80. 14904 return false; 14905 case MVT::f32: 14906 case MVT::f64: 14907 case MVT::ppcf128: 14908 return Imm.isPosZero(); 14909 } 14910 } 14911 14912 // For vector shift operation op, fold 14913 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 14914 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 14915 SelectionDAG &DAG) { 14916 SDValue N0 = N->getOperand(0); 14917 SDValue N1 = N->getOperand(1); 14918 EVT VT = N0.getValueType(); 14919 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 14920 unsigned Opcode = N->getOpcode(); 14921 unsigned TargetOpcode; 14922 14923 switch (Opcode) { 14924 default: 14925 llvm_unreachable("Unexpected shift operation"); 14926 case ISD::SHL: 14927 TargetOpcode = PPCISD::SHL; 14928 break; 14929 case ISD::SRL: 14930 TargetOpcode = PPCISD::SRL; 14931 break; 14932 case ISD::SRA: 14933 TargetOpcode = PPCISD::SRA; 14934 break; 14935 } 14936 14937 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 14938 N1->getOpcode() == ISD::AND) 14939 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 14940 if (Mask->getZExtValue() == OpSizeInBits - 1) 14941 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 14942 14943 return SDValue(); 14944 } 14945 14946 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 14947 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14948 return Value; 14949 14950 SDValue N0 = N->getOperand(0); 14951 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14952 if (!Subtarget.isISA3_0() || 14953 N0.getOpcode() != ISD::SIGN_EXTEND || 14954 N0.getOperand(0).getValueType() != MVT::i32 || 14955 CN1 == nullptr || N->getValueType(0) != MVT::i64) 14956 return SDValue(); 14957 14958 // We can't save an operation here if the value is already extended, and 14959 // the existing shift is easier to combine. 14960 SDValue ExtsSrc = N0.getOperand(0); 14961 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 14962 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 14963 return SDValue(); 14964 14965 SDLoc DL(N0); 14966 SDValue ShiftBy = SDValue(CN1, 0); 14967 // We want the shift amount to be i32 on the extswli, but the shift could 14968 // have an i64. 14969 if (ShiftBy.getValueType() == MVT::i64) 14970 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 14971 14972 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 14973 ShiftBy); 14974 } 14975 14976 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 14977 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14978 return Value; 14979 14980 return SDValue(); 14981 } 14982 14983 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 14984 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 14985 return Value; 14986 14987 return SDValue(); 14988 } 14989 14990 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 14991 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 14992 // When C is zero, the equation (addi Z, -C) can be simplified to Z 14993 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 14994 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 14995 const PPCSubtarget &Subtarget) { 14996 if (!Subtarget.isPPC64()) 14997 return SDValue(); 14998 14999 SDValue LHS = N->getOperand(0); 15000 SDValue RHS = N->getOperand(1); 15001 15002 auto isZextOfCompareWithConstant = [](SDValue Op) { 15003 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15004 Op.getValueType() != MVT::i64) 15005 return false; 15006 15007 SDValue Cmp = Op.getOperand(0); 15008 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15009 Cmp.getOperand(0).getValueType() != MVT::i64) 15010 return false; 15011 15012 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15013 int64_t NegConstant = 0 - Constant->getSExtValue(); 15014 // Due to the limitations of the addi instruction, 15015 // -C is required to be [-32768, 32767]. 15016 return isInt<16>(NegConstant); 15017 } 15018 15019 return false; 15020 }; 15021 15022 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15023 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15024 15025 // If there is a pattern, canonicalize a zext operand to the RHS. 15026 if (LHSHasPattern && !RHSHasPattern) 15027 std::swap(LHS, RHS); 15028 else if (!LHSHasPattern && !RHSHasPattern) 15029 return SDValue(); 15030 15031 SDLoc DL(N); 15032 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15033 SDValue Cmp = RHS.getOperand(0); 15034 SDValue Z = Cmp.getOperand(0); 15035 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15036 15037 assert(Constant && "Constant Should not be a null pointer."); 15038 int64_t NegConstant = 0 - Constant->getSExtValue(); 15039 15040 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15041 default: break; 15042 case ISD::SETNE: { 15043 // when C == 0 15044 // --> addze X, (addic Z, -1).carry 15045 // / 15046 // add X, (zext(setne Z, C))-- 15047 // \ when -32768 <= -C <= 32767 && C != 0 15048 // --> addze X, (addic (addi Z, -C), -1).carry 15049 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15050 DAG.getConstant(NegConstant, DL, MVT::i64)); 15051 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15052 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15053 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15054 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15055 SDValue(Addc.getNode(), 1)); 15056 } 15057 case ISD::SETEQ: { 15058 // when C == 0 15059 // --> addze X, (subfic Z, 0).carry 15060 // / 15061 // add X, (zext(sete Z, C))-- 15062 // \ when -32768 <= -C <= 32767 && C != 0 15063 // --> addze X, (subfic (addi Z, -C), 0).carry 15064 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15065 DAG.getConstant(NegConstant, DL, MVT::i64)); 15066 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15067 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15068 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15069 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15070 SDValue(Subc.getNode(), 1)); 15071 } 15072 } 15073 15074 return SDValue(); 15075 } 15076 15077 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15078 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15079 return Value; 15080 15081 return SDValue(); 15082 } 15083 15084 // Detect TRUNCATE operations on bitcasts of float128 values. 15085 // What we are looking for here is the situtation where we extract a subset 15086 // of bits from a 128 bit float. 15087 // This can be of two forms: 15088 // 1) BITCAST of f128 feeding TRUNCATE 15089 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15090 // The reason this is required is because we do not have a legal i128 type 15091 // and so we want to prevent having to store the f128 and then reload part 15092 // of it. 15093 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15094 DAGCombinerInfo &DCI) const { 15095 // If we are using CRBits then try that first. 15096 if (Subtarget.useCRBits()) { 15097 // Check if CRBits did anything and return that if it did. 15098 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15099 return CRTruncValue; 15100 } 15101 15102 SDLoc dl(N); 15103 SDValue Op0 = N->getOperand(0); 15104 15105 // Looking for a truncate of i128 to i64. 15106 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15107 return SDValue(); 15108 15109 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15110 15111 // SRL feeding TRUNCATE. 15112 if (Op0.getOpcode() == ISD::SRL) { 15113 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15114 // The right shift has to be by 64 bits. 15115 if (!ConstNode || ConstNode->getZExtValue() != 64) 15116 return SDValue(); 15117 15118 // Switch the element number to extract. 15119 EltToExtract = EltToExtract ? 0 : 1; 15120 // Update Op0 past the SRL. 15121 Op0 = Op0.getOperand(0); 15122 } 15123 15124 // BITCAST feeding a TRUNCATE possibly via SRL. 15125 if (Op0.getOpcode() == ISD::BITCAST && 15126 Op0.getValueType() == MVT::i128 && 15127 Op0.getOperand(0).getValueType() == MVT::f128) { 15128 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15129 return DCI.DAG.getNode( 15130 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15131 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15132 } 15133 return SDValue(); 15134 } 15135 15136 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15137 SelectionDAG &DAG = DCI.DAG; 15138 15139 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15140 if (!ConstOpOrElement) 15141 return SDValue(); 15142 15143 // An imul is usually smaller than the alternative sequence for legal type. 15144 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15145 isOperationLegal(ISD::MUL, N->getValueType(0))) 15146 return SDValue(); 15147 15148 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15149 switch (this->Subtarget.getDarwinDirective()) { 15150 default: 15151 // TODO: enhance the condition for subtarget before pwr8 15152 return false; 15153 case PPC::DIR_PWR8: 15154 // type mul add shl 15155 // scalar 4 1 1 15156 // vector 7 2 2 15157 return true; 15158 case PPC::DIR_PWR9: 15159 // type mul add shl 15160 // scalar 5 2 2 15161 // vector 7 2 2 15162 15163 // The cycle RATIO of related operations are showed as a table above. 15164 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15165 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15166 // are 4, it is always profitable; but for 3 instrs patterns 15167 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15168 // So we should only do it for vector type. 15169 return IsAddOne && IsNeg ? VT.isVector() : true; 15170 } 15171 }; 15172 15173 EVT VT = N->getValueType(0); 15174 SDLoc DL(N); 15175 15176 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15177 bool IsNeg = MulAmt.isNegative(); 15178 APInt MulAmtAbs = MulAmt.abs(); 15179 15180 if ((MulAmtAbs - 1).isPowerOf2()) { 15181 // (mul x, 2^N + 1) => (add (shl x, N), x) 15182 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15183 15184 if (!IsProfitable(IsNeg, true, VT)) 15185 return SDValue(); 15186 15187 SDValue Op0 = N->getOperand(0); 15188 SDValue Op1 = 15189 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15190 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15191 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15192 15193 if (!IsNeg) 15194 return Res; 15195 15196 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15197 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15198 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15199 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15200 15201 if (!IsProfitable(IsNeg, false, VT)) 15202 return SDValue(); 15203 15204 SDValue Op0 = N->getOperand(0); 15205 SDValue Op1 = 15206 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15207 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15208 15209 if (!IsNeg) 15210 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15211 else 15212 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15213 15214 } else { 15215 return SDValue(); 15216 } 15217 } 15218 15219 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15220 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15221 if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64()) 15222 return false; 15223 15224 // If not a tail call then no need to proceed. 15225 if (!CI->isTailCall()) 15226 return false; 15227 15228 // If tail calls are disabled for the caller then we are done. 15229 const Function *Caller = CI->getParent()->getParent(); 15230 auto Attr = Caller->getFnAttribute("disable-tail-calls"); 15231 if (Attr.getValueAsString() == "true") 15232 return false; 15233 15234 // If sibling calls have been disabled and tail-calls aren't guaranteed 15235 // there is no reason to duplicate. 15236 auto &TM = getTargetMachine(); 15237 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15238 return false; 15239 15240 // Can't tail call a function called indirectly, or if it has variadic args. 15241 const Function *Callee = CI->getCalledFunction(); 15242 if (!Callee || Callee->isVarArg()) 15243 return false; 15244 15245 // Make sure the callee and caller calling conventions are eligible for tco. 15246 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15247 CI->getCallingConv())) 15248 return false; 15249 15250 // If the function is local then we have a good chance at tail-calling it 15251 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15252 } 15253 15254 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15255 if (!Subtarget.hasVSX()) 15256 return false; 15257 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15258 return true; 15259 return VT == MVT::f32 || VT == MVT::f64 || 15260 VT == MVT::v4f32 || VT == MVT::v2f64; 15261 } 15262 15263 bool PPCTargetLowering:: 15264 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15265 const Value *Mask = AndI.getOperand(1); 15266 // If the mask is suitable for andi. or andis. we should sink the and. 15267 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15268 // Can't handle constants wider than 64-bits. 15269 if (CI->getBitWidth() > 64) 15270 return false; 15271 int64_t ConstVal = CI->getZExtValue(); 15272 return isUInt<16>(ConstVal) || 15273 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15274 } 15275 15276 // For non-constant masks, we can always use the record-form and. 15277 return true; 15278 } 15279 15280 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15281 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15282 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15283 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15284 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15285 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15286 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15287 assert(Subtarget.hasP9Altivec() && 15288 "Only combine this when P9 altivec supported!"); 15289 EVT VT = N->getValueType(0); 15290 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15291 return SDValue(); 15292 15293 SelectionDAG &DAG = DCI.DAG; 15294 SDLoc dl(N); 15295 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15296 // Even for signed integers, if it's known to be positive (as signed 15297 // integer) due to zero-extended inputs. 15298 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15299 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15300 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15301 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15302 (SubOpcd1 == ISD::ZERO_EXTEND || 15303 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15304 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15305 N->getOperand(0)->getOperand(0), 15306 N->getOperand(0)->getOperand(1), 15307 DAG.getTargetConstant(0, dl, MVT::i32)); 15308 } 15309 15310 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15311 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15312 N->getOperand(0).hasOneUse()) { 15313 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15314 N->getOperand(0)->getOperand(0), 15315 N->getOperand(0)->getOperand(1), 15316 DAG.getTargetConstant(1, dl, MVT::i32)); 15317 } 15318 } 15319 15320 return SDValue(); 15321 } 15322 15323 // For type v4i32/v8ii16/v16i8, transform 15324 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15325 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15326 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15327 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15328 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15329 DAGCombinerInfo &DCI) const { 15330 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15331 assert(Subtarget.hasP9Altivec() && 15332 "Only combine this when P9 altivec supported!"); 15333 15334 SelectionDAG &DAG = DCI.DAG; 15335 SDLoc dl(N); 15336 SDValue Cond = N->getOperand(0); 15337 SDValue TrueOpnd = N->getOperand(1); 15338 SDValue FalseOpnd = N->getOperand(2); 15339 EVT VT = N->getOperand(1).getValueType(); 15340 15341 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15342 FalseOpnd.getOpcode() != ISD::SUB) 15343 return SDValue(); 15344 15345 // ABSD only available for type v4i32/v8i16/v16i8 15346 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15347 return SDValue(); 15348 15349 // At least to save one more dependent computation 15350 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15351 return SDValue(); 15352 15353 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15354 15355 // Can only handle unsigned comparison here 15356 switch (CC) { 15357 default: 15358 return SDValue(); 15359 case ISD::SETUGT: 15360 case ISD::SETUGE: 15361 break; 15362 case ISD::SETULT: 15363 case ISD::SETULE: 15364 std::swap(TrueOpnd, FalseOpnd); 15365 break; 15366 } 15367 15368 SDValue CmpOpnd1 = Cond.getOperand(0); 15369 SDValue CmpOpnd2 = Cond.getOperand(1); 15370 15371 // SETCC CmpOpnd1 CmpOpnd2 cond 15372 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15373 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15374 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15375 TrueOpnd.getOperand(1) == CmpOpnd2 && 15376 FalseOpnd.getOperand(0) == CmpOpnd2 && 15377 FalseOpnd.getOperand(1) == CmpOpnd1) { 15378 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15379 CmpOpnd1, CmpOpnd2, 15380 DAG.getTargetConstant(0, dl, MVT::i32)); 15381 } 15382 15383 return SDValue(); 15384 } 15385