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/TargetLoweringObjectFileImpl.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/CallSite.h" 59 #include "llvm/IR/CallingConv.h" 60 #include "llvm/IR/Constant.h" 61 #include "llvm/IR/Constants.h" 62 #include "llvm/IR/DataLayout.h" 63 #include "llvm/IR/DebugLoc.h" 64 #include "llvm/IR/DerivedTypes.h" 65 #include "llvm/IR/Function.h" 66 #include "llvm/IR/GlobalValue.h" 67 #include "llvm/IR/IRBuilder.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/IntrinsicsPowerPC.h" 71 #include "llvm/IR/Module.h" 72 #include "llvm/IR/Type.h" 73 #include "llvm/IR/Use.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/MC/MCContext.h" 76 #include "llvm/MC/MCExpr.h" 77 #include "llvm/MC/MCRegisterInfo.h" 78 #include "llvm/MC/MCSymbolXCOFF.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/BranchProbability.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/CodeGen.h" 83 #include "llvm/Support/CommandLine.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Debug.h" 86 #include "llvm/Support/ErrorHandling.h" 87 #include "llvm/Support/Format.h" 88 #include "llvm/Support/KnownBits.h" 89 #include "llvm/Support/MachineValueType.h" 90 #include "llvm/Support/MathExtras.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Target/TargetMachine.h" 93 #include "llvm/Target/TargetOptions.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <cstdint> 97 #include <iterator> 98 #include <list> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 104 #define DEBUG_TYPE "ppc-lowering" 105 106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", 107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); 108 109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", 110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); 111 112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", 113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); 114 115 static cl::opt<bool> DisableSCO("disable-ppc-sco", 116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden); 117 118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32", 119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden); 120 121 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision", 122 cl::desc("enable quad precision float support on ppc"), cl::Hidden); 123 124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 125 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 126 127 STATISTIC(NumTailCalls, "Number of tail calls"); 128 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 129 130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 131 132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 133 134 // FIXME: Remove this once the bug has been fixed! 135 extern cl::opt<bool> ANDIGlueBug; 136 137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 138 const PPCSubtarget &STI) 139 : TargetLowering(TM), Subtarget(STI) { 140 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 141 // arguments are at least 4/8 bytes aligned. 142 bool isPPC64 = Subtarget.isPPC64(); 143 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 144 145 // Set up the register classes. 146 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 147 if (!useSoftFloat()) { 148 if (hasSPE()) { 149 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 150 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 151 } else { 152 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 153 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 154 } 155 } 156 157 // Match BITREVERSE to customized fast code sequence in the td file. 158 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 159 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 160 161 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 162 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 163 164 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 165 for (MVT VT : MVT::integer_valuetypes()) { 166 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 167 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 168 } 169 170 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 171 172 // PowerPC has pre-inc load and store's. 173 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 174 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 175 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 176 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 177 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 178 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 179 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 180 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 181 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 182 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 183 if (!Subtarget.hasSPE()) { 184 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 185 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 186 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 187 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 188 } 189 190 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 191 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 192 for (MVT VT : ScalarIntVTs) { 193 setOperationAction(ISD::ADDC, VT, Legal); 194 setOperationAction(ISD::ADDE, VT, Legal); 195 setOperationAction(ISD::SUBC, VT, Legal); 196 setOperationAction(ISD::SUBE, VT, Legal); 197 } 198 199 if (Subtarget.useCRBits()) { 200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 201 202 if (isPPC64 || Subtarget.hasFPCVT()) { 203 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 204 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 205 isPPC64 ? MVT::i64 : MVT::i32); 206 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 207 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 208 isPPC64 ? MVT::i64 : MVT::i32); 209 } else { 210 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 211 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 212 } 213 214 // PowerPC does not support direct load/store of condition registers. 215 setOperationAction(ISD::LOAD, MVT::i1, Custom); 216 setOperationAction(ISD::STORE, MVT::i1, Custom); 217 218 // FIXME: Remove this once the ANDI glue bug is fixed: 219 if (ANDIGlueBug) 220 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 221 222 for (MVT VT : MVT::integer_valuetypes()) { 223 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 224 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 225 setTruncStoreAction(VT, MVT::i1, Expand); 226 } 227 228 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 229 } 230 231 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 232 // PPC (the libcall is not available). 233 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 234 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 235 236 // We do not currently implement these libm ops for PowerPC. 237 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 238 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 239 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 240 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 241 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 242 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 243 244 // PowerPC has no SREM/UREM instructions unless we are on P9 245 // On P9 we may use a hardware instruction to compute the remainder. 246 // The instructions are not legalized directly because in the cases where the 247 // result of both the remainder and the division is required it is more 248 // efficient to compute the remainder from the result of the division rather 249 // than use the remainder instruction. 250 if (Subtarget.isISA3_0()) { 251 setOperationAction(ISD::SREM, MVT::i32, Custom); 252 setOperationAction(ISD::UREM, MVT::i32, Custom); 253 setOperationAction(ISD::SREM, MVT::i64, Custom); 254 setOperationAction(ISD::UREM, MVT::i64, Custom); 255 } else { 256 setOperationAction(ISD::SREM, MVT::i32, Expand); 257 setOperationAction(ISD::UREM, MVT::i32, Expand); 258 setOperationAction(ISD::SREM, MVT::i64, Expand); 259 setOperationAction(ISD::UREM, MVT::i64, Expand); 260 } 261 262 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 263 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 264 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 265 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 266 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 267 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 268 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 269 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 270 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 271 272 // We don't support sin/cos/sqrt/fmod/pow 273 setOperationAction(ISD::FSIN , MVT::f64, Expand); 274 setOperationAction(ISD::FCOS , MVT::f64, Expand); 275 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 276 setOperationAction(ISD::FREM , MVT::f64, Expand); 277 setOperationAction(ISD::FPOW , MVT::f64, Expand); 278 setOperationAction(ISD::FSIN , MVT::f32, Expand); 279 setOperationAction(ISD::FCOS , MVT::f32, Expand); 280 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 281 setOperationAction(ISD::FREM , MVT::f32, Expand); 282 setOperationAction(ISD::FPOW , MVT::f32, Expand); 283 if (Subtarget.hasSPE()) { 284 setOperationAction(ISD::FMA , MVT::f64, Expand); 285 setOperationAction(ISD::FMA , MVT::f32, Expand); 286 } else { 287 setOperationAction(ISD::FMA , MVT::f64, Legal); 288 setOperationAction(ISD::FMA , MVT::f32, Legal); 289 } 290 291 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 292 293 // If we're enabling GP optimizations, use hardware square root 294 if (!Subtarget.hasFSQRT() && 295 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 296 Subtarget.hasFRE())) 297 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 298 299 if (!Subtarget.hasFSQRT() && 300 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 301 Subtarget.hasFRES())) 302 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 303 304 if (Subtarget.hasFCPSGN()) { 305 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 306 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 307 } else { 308 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 309 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 310 } 311 312 if (Subtarget.hasFPRND()) { 313 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 314 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 315 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 316 setOperationAction(ISD::FROUND, MVT::f64, Legal); 317 318 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 319 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 320 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 321 setOperationAction(ISD::FROUND, MVT::f32, Legal); 322 } 323 324 // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd 325 // to speed up scalar BSWAP64. 326 // CTPOP or CTTZ were introduced in P8/P9 respectively 327 setOperationAction(ISD::BSWAP, MVT::i32 , Expand); 328 if (Subtarget.hasP9Vector()) 329 setOperationAction(ISD::BSWAP, MVT::i64 , Custom); 330 else 331 setOperationAction(ISD::BSWAP, MVT::i64 , Expand); 332 if (Subtarget.isISA3_0()) { 333 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 334 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 335 } else { 336 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 337 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 338 } 339 340 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 341 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 342 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 343 } else { 344 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 345 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 346 } 347 348 // PowerPC does not have ROTR 349 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 350 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 351 352 if (!Subtarget.useCRBits()) { 353 // PowerPC does not have Select 354 setOperationAction(ISD::SELECT, MVT::i32, Expand); 355 setOperationAction(ISD::SELECT, MVT::i64, Expand); 356 setOperationAction(ISD::SELECT, MVT::f32, Expand); 357 setOperationAction(ISD::SELECT, MVT::f64, Expand); 358 } 359 360 // PowerPC wants to turn select_cc of FP into fsel when possible. 361 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 362 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 363 364 // PowerPC wants to optimize integer setcc a bit 365 if (!Subtarget.useCRBits()) 366 setOperationAction(ISD::SETCC, MVT::i32, Custom); 367 368 // PowerPC does not have BRCOND which requires SetCC 369 if (!Subtarget.useCRBits()) 370 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 371 372 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 373 374 if (Subtarget.hasSPE()) { 375 // SPE has built-in conversions 376 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 377 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 378 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 379 } else { 380 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 381 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 382 383 // PowerPC does not have [U|S]INT_TO_FP 384 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 385 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 386 } 387 388 if (Subtarget.hasDirectMove() && isPPC64) { 389 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 390 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 391 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 392 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 393 if (TM.Options.UnsafeFPMath) { 394 setOperationAction(ISD::LRINT, MVT::f64, Legal); 395 setOperationAction(ISD::LRINT, MVT::f32, Legal); 396 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 397 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 398 setOperationAction(ISD::LROUND, MVT::f64, Legal); 399 setOperationAction(ISD::LROUND, MVT::f32, Legal); 400 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 401 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 402 } 403 } else { 404 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 405 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 406 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 407 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 408 } 409 410 // We cannot sextinreg(i1). Expand to shifts. 411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 412 413 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 414 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 415 // support continuation, user-level threading, and etc.. As a result, no 416 // other SjLj exception interfaces are implemented and please don't build 417 // your own exception handling based on them. 418 // LLVM/Clang supports zero-cost DWARF exception handling. 419 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 420 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 421 422 // We want to legalize GlobalAddress and ConstantPool nodes into the 423 // appropriate instructions to materialize the address. 424 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 425 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 426 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 427 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 428 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 429 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 430 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 431 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 432 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 433 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 434 435 // TRAP is legal. 436 setOperationAction(ISD::TRAP, MVT::Other, Legal); 437 438 // TRAMPOLINE is custom lowered. 439 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 440 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 441 442 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 443 setOperationAction(ISD::VASTART , MVT::Other, Custom); 444 445 if (Subtarget.is64BitELFABI()) { 446 // VAARG always uses double-word chunks, so promote anything smaller. 447 setOperationAction(ISD::VAARG, MVT::i1, Promote); 448 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 449 setOperationAction(ISD::VAARG, MVT::i8, Promote); 450 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 451 setOperationAction(ISD::VAARG, MVT::i16, Promote); 452 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 453 setOperationAction(ISD::VAARG, MVT::i32, Promote); 454 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 455 setOperationAction(ISD::VAARG, MVT::Other, Expand); 456 } else if (Subtarget.is32BitELFABI()) { 457 // VAARG is custom lowered with the 32-bit SVR4 ABI. 458 setOperationAction(ISD::VAARG, MVT::Other, Custom); 459 setOperationAction(ISD::VAARG, MVT::i64, Custom); 460 } else 461 setOperationAction(ISD::VAARG, MVT::Other, Expand); 462 463 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 464 if (Subtarget.is32BitELFABI()) 465 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 466 else 467 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 468 469 // Use the default implementation. 470 setOperationAction(ISD::VAEND , MVT::Other, Expand); 471 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 472 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 474 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 475 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 476 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 477 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 478 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 479 480 // We want to custom lower some of our intrinsics. 481 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 482 483 // To handle counter-based loop conditions. 484 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 485 486 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 487 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 488 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 489 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 490 491 // Comparisons that require checking two conditions. 492 if (Subtarget.hasSPE()) { 493 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 494 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 495 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 496 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 497 } 498 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 499 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 500 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 501 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 502 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 503 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 504 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 505 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 506 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 507 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 508 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 509 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 510 511 if (Subtarget.has64BitSupport()) { 512 // They also have instructions for converting between i64 and fp. 513 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 514 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 515 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 516 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 517 // This is just the low 32 bits of a (signed) fp->i64 conversion. 518 // We cannot do this with Promote because i64 is not a legal type. 519 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 520 521 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) 522 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 523 } else { 524 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 525 if (Subtarget.hasSPE()) 526 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 527 else 528 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 529 } 530 531 // With the instructions enabled under FPCVT, we can do everything. 532 if (Subtarget.hasFPCVT()) { 533 if (Subtarget.has64BitSupport()) { 534 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 535 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 536 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 537 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 538 } 539 540 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 541 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 542 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 543 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 544 } 545 546 if (Subtarget.use64BitRegs()) { 547 // 64-bit PowerPC implementations can support i64 types directly 548 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 549 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 550 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 551 // 64-bit PowerPC wants to expand i128 shifts itself. 552 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 553 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 554 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 555 } else { 556 // 32-bit PowerPC wants to expand i64 shifts itself. 557 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 558 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 559 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 560 } 561 562 if (Subtarget.hasVSX()) { 563 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 564 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 565 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 566 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 567 } 568 569 if (Subtarget.hasAltivec()) { 570 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 571 setOperationAction(ISD::SADDSAT, VT, Legal); 572 setOperationAction(ISD::SSUBSAT, VT, Legal); 573 setOperationAction(ISD::UADDSAT, VT, Legal); 574 setOperationAction(ISD::USUBSAT, VT, Legal); 575 } 576 // First set operation action for all vector types to expand. Then we 577 // will selectively turn on ones that can be effectively codegen'd. 578 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 579 // add/sub are legal for all supported vector VT's. 580 setOperationAction(ISD::ADD, VT, Legal); 581 setOperationAction(ISD::SUB, VT, Legal); 582 583 // For v2i64, these are only valid with P8Vector. This is corrected after 584 // the loop. 585 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 586 setOperationAction(ISD::SMAX, VT, Legal); 587 setOperationAction(ISD::SMIN, VT, Legal); 588 setOperationAction(ISD::UMAX, VT, Legal); 589 setOperationAction(ISD::UMIN, VT, Legal); 590 } 591 else { 592 setOperationAction(ISD::SMAX, VT, Expand); 593 setOperationAction(ISD::SMIN, VT, Expand); 594 setOperationAction(ISD::UMAX, VT, Expand); 595 setOperationAction(ISD::UMIN, VT, Expand); 596 } 597 598 if (Subtarget.hasVSX()) { 599 setOperationAction(ISD::FMAXNUM, VT, Legal); 600 setOperationAction(ISD::FMINNUM, VT, Legal); 601 } 602 603 // Vector instructions introduced in P8 604 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 605 setOperationAction(ISD::CTPOP, VT, Legal); 606 setOperationAction(ISD::CTLZ, VT, Legal); 607 } 608 else { 609 setOperationAction(ISD::CTPOP, VT, Expand); 610 setOperationAction(ISD::CTLZ, VT, Expand); 611 } 612 613 // Vector instructions introduced in P9 614 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 615 setOperationAction(ISD::CTTZ, VT, Legal); 616 else 617 setOperationAction(ISD::CTTZ, VT, Expand); 618 619 // We promote all shuffles to v16i8. 620 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 621 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 622 623 // We promote all non-typed operations to v4i32. 624 setOperationAction(ISD::AND , VT, Promote); 625 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 626 setOperationAction(ISD::OR , VT, Promote); 627 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 628 setOperationAction(ISD::XOR , VT, Promote); 629 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 630 setOperationAction(ISD::LOAD , VT, Promote); 631 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 632 setOperationAction(ISD::SELECT, VT, Promote); 633 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 634 setOperationAction(ISD::VSELECT, VT, Legal); 635 setOperationAction(ISD::SELECT_CC, VT, Promote); 636 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 637 setOperationAction(ISD::STORE, VT, Promote); 638 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 639 640 // No other operations are legal. 641 setOperationAction(ISD::MUL , VT, Expand); 642 setOperationAction(ISD::SDIV, VT, Expand); 643 setOperationAction(ISD::SREM, VT, Expand); 644 setOperationAction(ISD::UDIV, VT, Expand); 645 setOperationAction(ISD::UREM, VT, Expand); 646 setOperationAction(ISD::FDIV, VT, Expand); 647 setOperationAction(ISD::FREM, VT, Expand); 648 setOperationAction(ISD::FNEG, VT, Expand); 649 setOperationAction(ISD::FSQRT, VT, Expand); 650 setOperationAction(ISD::FLOG, VT, Expand); 651 setOperationAction(ISD::FLOG10, VT, Expand); 652 setOperationAction(ISD::FLOG2, VT, Expand); 653 setOperationAction(ISD::FEXP, VT, Expand); 654 setOperationAction(ISD::FEXP2, VT, Expand); 655 setOperationAction(ISD::FSIN, VT, Expand); 656 setOperationAction(ISD::FCOS, VT, Expand); 657 setOperationAction(ISD::FABS, VT, Expand); 658 setOperationAction(ISD::FFLOOR, VT, Expand); 659 setOperationAction(ISD::FCEIL, VT, Expand); 660 setOperationAction(ISD::FTRUNC, VT, Expand); 661 setOperationAction(ISD::FRINT, VT, Expand); 662 setOperationAction(ISD::FNEARBYINT, VT, Expand); 663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 664 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 665 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 666 setOperationAction(ISD::MULHU, VT, Expand); 667 setOperationAction(ISD::MULHS, VT, Expand); 668 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 669 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 670 setOperationAction(ISD::UDIVREM, VT, Expand); 671 setOperationAction(ISD::SDIVREM, VT, Expand); 672 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 673 setOperationAction(ISD::FPOW, VT, Expand); 674 setOperationAction(ISD::BSWAP, VT, Expand); 675 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 676 setOperationAction(ISD::ROTL, VT, Expand); 677 setOperationAction(ISD::ROTR, VT, Expand); 678 679 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 680 setTruncStoreAction(VT, InnerVT, Expand); 681 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 682 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 683 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 684 } 685 } 686 if (!Subtarget.hasP8Vector()) { 687 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 688 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 689 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 690 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 691 } 692 693 for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8}) 694 setOperationAction(ISD::ABS, VT, Custom); 695 696 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 697 // with merges, splats, etc. 698 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 699 700 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 701 // are cheap, so handle them before they get expanded to scalar. 702 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 703 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 704 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 705 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 706 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 707 708 setOperationAction(ISD::AND , MVT::v4i32, Legal); 709 setOperationAction(ISD::OR , MVT::v4i32, Legal); 710 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 711 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 712 setOperationAction(ISD::SELECT, MVT::v4i32, 713 Subtarget.useCRBits() ? Legal : Expand); 714 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 715 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 716 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 717 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 718 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 719 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 720 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 721 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 722 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 723 724 // Without hasP8Altivec set, v2i64 SMAX isn't available. 725 // But ABS custom lowering requires SMAX support. 726 if (!Subtarget.hasP8Altivec()) 727 setOperationAction(ISD::ABS, MVT::v2i64, Expand); 728 729 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 730 if (Subtarget.hasAltivec()) 731 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 732 setOperationAction(ISD::ROTL, VT, Legal); 733 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 734 if (Subtarget.hasP8Altivec()) 735 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 736 737 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 738 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 739 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 740 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 741 742 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 743 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 744 745 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { 746 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 747 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 748 } 749 750 if (Subtarget.hasP8Altivec()) 751 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 752 else 753 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 754 755 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 756 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 757 758 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 759 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 760 761 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 762 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 763 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 764 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 765 766 // Altivec does not contain unordered floating-point compare instructions 767 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 768 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 769 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 770 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 771 772 if (Subtarget.hasVSX()) { 773 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 775 if (Subtarget.hasP8Vector()) { 776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 778 } 779 if (Subtarget.hasDirectMove() && isPPC64) { 780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 783 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 784 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 788 } 789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 790 791 // The nearbyint variants are not allowed to raise the inexact exception 792 // so we can only code-gen them with unsafe math. 793 if (TM.Options.UnsafeFPMath) { 794 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 795 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 796 } 797 798 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 799 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 800 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 801 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 802 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 803 setOperationAction(ISD::FROUND, MVT::f64, Legal); 804 805 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 806 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 807 setOperationAction(ISD::FROUND, MVT::f32, Legal); 808 809 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 810 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 811 812 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 813 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 814 815 // Share the Altivec comparison restrictions. 816 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 817 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 818 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 819 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 820 821 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 822 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 823 824 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 825 826 if (Subtarget.hasP8Vector()) 827 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 828 829 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 830 831 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 832 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 833 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 834 835 if (Subtarget.hasP8Altivec()) { 836 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 837 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 838 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 839 840 // 128 bit shifts can be accomplished via 3 instructions for SHL and 841 // SRL, but not for SRA because of the instructions available: 842 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 843 // doing 844 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 845 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 846 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 847 848 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 849 } 850 else { 851 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 852 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 853 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 854 855 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 856 857 // VSX v2i64 only supports non-arithmetic operations. 858 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 859 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 860 } 861 862 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 863 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 864 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 865 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 866 867 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 868 869 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 870 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 871 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 872 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 873 874 // Custom handling for partial vectors of integers converted to 875 // floating point. We already have optimal handling for v2i32 through 876 // the DAG combine, so those aren't necessary. 877 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 878 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 879 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 880 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 881 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 882 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 883 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 884 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 885 886 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 887 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 888 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 889 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 890 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 891 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 892 893 if (Subtarget.hasDirectMove()) 894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 896 897 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 898 } 899 900 if (Subtarget.hasP8Altivec()) { 901 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 902 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 903 } 904 905 if (Subtarget.hasP9Vector()) { 906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 908 909 // 128 bit shifts can be accomplished via 3 instructions for SHL and 910 // SRL, but not for SRA because of the instructions available: 911 // VS{RL} and VS{RL}O. 912 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 913 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 914 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 915 916 if (EnableQuadPrecision) { 917 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 918 setOperationAction(ISD::FADD, MVT::f128, Legal); 919 setOperationAction(ISD::FSUB, MVT::f128, Legal); 920 setOperationAction(ISD::FDIV, MVT::f128, Legal); 921 setOperationAction(ISD::FMUL, MVT::f128, Legal); 922 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 923 // No extending loads to f128 on PPC. 924 for (MVT FPT : MVT::fp_valuetypes()) 925 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 926 setOperationAction(ISD::FMA, MVT::f128, Legal); 927 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 928 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 929 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 930 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 931 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 932 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 933 934 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 935 setOperationAction(ISD::FRINT, MVT::f128, Legal); 936 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 937 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 938 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 939 setOperationAction(ISD::FROUND, MVT::f128, Legal); 940 941 setOperationAction(ISD::SELECT, MVT::f128, Expand); 942 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 943 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 944 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 945 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 946 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 947 // No implementation for these ops for PowerPC. 948 setOperationAction(ISD::FSIN , MVT::f128, Expand); 949 setOperationAction(ISD::FCOS , MVT::f128, Expand); 950 setOperationAction(ISD::FPOW, MVT::f128, Expand); 951 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 952 setOperationAction(ISD::FREM, MVT::f128, Expand); 953 } 954 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 955 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 956 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 957 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 958 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 959 } 960 961 if (Subtarget.hasP9Altivec()) { 962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 963 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 964 965 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 966 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 967 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 968 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 969 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 970 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 971 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 972 } 973 } 974 975 if (Subtarget.hasQPX()) { 976 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 977 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 978 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 979 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 980 981 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 982 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 983 984 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 985 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 986 987 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 988 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 989 990 if (!Subtarget.useCRBits()) 991 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 992 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 993 994 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 995 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 996 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 997 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 998 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 999 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1000 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1001 1002 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1003 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1004 1005 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1006 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1007 1008 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1009 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1010 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1011 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1012 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1013 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1014 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1015 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1016 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1017 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1018 1019 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1020 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1021 1022 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1023 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1024 1025 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1026 1027 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1028 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1029 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1030 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1031 1032 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1034 1035 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1036 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1037 1038 if (!Subtarget.useCRBits()) 1039 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1040 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1041 1042 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1043 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1044 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1045 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1046 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1047 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1048 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1049 1050 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1051 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1052 1053 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1054 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1055 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1056 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1057 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1058 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1059 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1060 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1061 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1062 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1063 1064 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1065 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1066 1067 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1068 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1069 1070 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1071 1072 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1073 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1074 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1075 1076 if (!Subtarget.useCRBits()) 1077 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1078 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1079 1080 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1081 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1082 1083 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1084 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1085 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1086 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1087 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1088 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1089 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1090 1091 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1092 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1093 1094 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1095 1096 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1097 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1098 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1099 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1100 1101 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1102 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1103 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1104 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1105 1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1107 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1108 1109 // These need to set FE_INEXACT, and so cannot be vectorized here. 1110 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1111 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1112 1113 if (TM.Options.UnsafeFPMath) { 1114 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1115 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1116 1117 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1118 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1119 } else { 1120 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1121 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1122 1123 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1124 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1125 } 1126 } 1127 1128 if (Subtarget.has64BitSupport()) 1129 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1130 1131 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1132 1133 if (!isPPC64) { 1134 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1135 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1136 } 1137 1138 setBooleanContents(ZeroOrOneBooleanContent); 1139 1140 if (Subtarget.hasAltivec()) { 1141 // Altivec instructions set fields to all zeros or all ones. 1142 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1143 } 1144 1145 if (!isPPC64) { 1146 // These libcalls are not available in 32-bit. 1147 setLibcallName(RTLIB::SHL_I128, nullptr); 1148 setLibcallName(RTLIB::SRL_I128, nullptr); 1149 setLibcallName(RTLIB::SRA_I128, nullptr); 1150 } 1151 1152 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1153 1154 // We have target-specific dag combine patterns for the following nodes: 1155 setTargetDAGCombine(ISD::ADD); 1156 setTargetDAGCombine(ISD::SHL); 1157 setTargetDAGCombine(ISD::SRA); 1158 setTargetDAGCombine(ISD::SRL); 1159 setTargetDAGCombine(ISD::MUL); 1160 setTargetDAGCombine(ISD::SINT_TO_FP); 1161 setTargetDAGCombine(ISD::BUILD_VECTOR); 1162 if (Subtarget.hasFPCVT()) 1163 setTargetDAGCombine(ISD::UINT_TO_FP); 1164 setTargetDAGCombine(ISD::LOAD); 1165 setTargetDAGCombine(ISD::STORE); 1166 setTargetDAGCombine(ISD::BR_CC); 1167 if (Subtarget.useCRBits()) 1168 setTargetDAGCombine(ISD::BRCOND); 1169 setTargetDAGCombine(ISD::BSWAP); 1170 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1171 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1172 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1173 1174 setTargetDAGCombine(ISD::SIGN_EXTEND); 1175 setTargetDAGCombine(ISD::ZERO_EXTEND); 1176 setTargetDAGCombine(ISD::ANY_EXTEND); 1177 1178 setTargetDAGCombine(ISD::TRUNCATE); 1179 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1180 1181 1182 if (Subtarget.useCRBits()) { 1183 setTargetDAGCombine(ISD::TRUNCATE); 1184 setTargetDAGCombine(ISD::SETCC); 1185 setTargetDAGCombine(ISD::SELECT_CC); 1186 } 1187 1188 // Use reciprocal estimates. 1189 if (TM.Options.UnsafeFPMath) { 1190 setTargetDAGCombine(ISD::FDIV); 1191 setTargetDAGCombine(ISD::FSQRT); 1192 } 1193 1194 if (Subtarget.hasP9Altivec()) { 1195 setTargetDAGCombine(ISD::ABS); 1196 setTargetDAGCombine(ISD::VSELECT); 1197 } 1198 1199 if (EnableQuadPrecision) { 1200 setLibcallName(RTLIB::LOG_F128, "logf128"); 1201 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1202 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1203 setLibcallName(RTLIB::EXP_F128, "expf128"); 1204 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1205 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1206 setLibcallName(RTLIB::COS_F128, "cosf128"); 1207 setLibcallName(RTLIB::POW_F128, "powf128"); 1208 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1209 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1210 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1211 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1212 } 1213 1214 // With 32 condition bits, we don't need to sink (and duplicate) compares 1215 // aggressively in CodeGenPrep. 1216 if (Subtarget.useCRBits()) { 1217 setHasMultipleConditionRegisters(); 1218 setJumpIsExpensive(); 1219 } 1220 1221 setMinFunctionAlignment(Align(4)); 1222 1223 switch (Subtarget.getCPUDirective()) { 1224 default: break; 1225 case PPC::DIR_970: 1226 case PPC::DIR_A2: 1227 case PPC::DIR_E500: 1228 case PPC::DIR_E500mc: 1229 case PPC::DIR_E5500: 1230 case PPC::DIR_PWR4: 1231 case PPC::DIR_PWR5: 1232 case PPC::DIR_PWR5X: 1233 case PPC::DIR_PWR6: 1234 case PPC::DIR_PWR6X: 1235 case PPC::DIR_PWR7: 1236 case PPC::DIR_PWR8: 1237 case PPC::DIR_PWR9: 1238 case PPC::DIR_PWR_FUTURE: 1239 setPrefLoopAlignment(Align(16)); 1240 setPrefFunctionAlignment(Align(16)); 1241 break; 1242 } 1243 1244 if (Subtarget.enableMachineScheduler()) 1245 setSchedulingPreference(Sched::Source); 1246 else 1247 setSchedulingPreference(Sched::Hybrid); 1248 1249 computeRegisterProperties(STI.getRegisterInfo()); 1250 1251 // The Freescale cores do better with aggressive inlining of memcpy and 1252 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1253 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1254 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1255 MaxStoresPerMemset = 32; 1256 MaxStoresPerMemsetOptSize = 16; 1257 MaxStoresPerMemcpy = 32; 1258 MaxStoresPerMemcpyOptSize = 8; 1259 MaxStoresPerMemmove = 32; 1260 MaxStoresPerMemmoveOptSize = 8; 1261 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1262 // The A2 also benefits from (very) aggressive inlining of memcpy and 1263 // friends. The overhead of a the function call, even when warm, can be 1264 // over one hundred cycles. 1265 MaxStoresPerMemset = 128; 1266 MaxStoresPerMemcpy = 128; 1267 MaxStoresPerMemmove = 128; 1268 MaxLoadsPerMemcmp = 128; 1269 } else { 1270 MaxLoadsPerMemcmp = 8; 1271 MaxLoadsPerMemcmpOptSize = 4; 1272 } 1273 } 1274 1275 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1276 /// the desired ByVal argument alignment. 1277 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1278 unsigned MaxMaxAlign) { 1279 if (MaxAlign == MaxMaxAlign) 1280 return; 1281 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1282 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1283 MaxAlign = 32; 1284 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1285 MaxAlign = 16; 1286 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1287 unsigned EltAlign = 0; 1288 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1289 if (EltAlign > MaxAlign) 1290 MaxAlign = EltAlign; 1291 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1292 for (auto *EltTy : STy->elements()) { 1293 unsigned EltAlign = 0; 1294 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1295 if (EltAlign > MaxAlign) 1296 MaxAlign = EltAlign; 1297 if (MaxAlign == MaxMaxAlign) 1298 break; 1299 } 1300 } 1301 } 1302 1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1304 /// function arguments in the caller parameter area. 1305 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1306 const DataLayout &DL) const { 1307 // 16byte and wider vectors are passed on 16byte boundary. 1308 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1309 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1310 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1311 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1312 return Align; 1313 } 1314 1315 bool PPCTargetLowering::useSoftFloat() const { 1316 return Subtarget.useSoftFloat(); 1317 } 1318 1319 bool PPCTargetLowering::hasSPE() const { 1320 return Subtarget.hasSPE(); 1321 } 1322 1323 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1324 return VT.isScalarInteger(); 1325 } 1326 1327 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1328 switch ((PPCISD::NodeType)Opcode) { 1329 case PPCISD::FIRST_NUMBER: break; 1330 case PPCISD::FSEL: return "PPCISD::FSEL"; 1331 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1332 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1333 case PPCISD::FCFID: return "PPCISD::FCFID"; 1334 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1335 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1336 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1337 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1338 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1339 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1340 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1341 case PPCISD::FP_TO_UINT_IN_VSR: 1342 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1343 case PPCISD::FP_TO_SINT_IN_VSR: 1344 return "PPCISD::FP_TO_SINT_IN_VSR"; 1345 case PPCISD::FRE: return "PPCISD::FRE"; 1346 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1347 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1348 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1349 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1350 case PPCISD::VPERM: return "PPCISD::VPERM"; 1351 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1352 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1353 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1354 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1355 case PPCISD::CMPB: return "PPCISD::CMPB"; 1356 case PPCISD::Hi: return "PPCISD::Hi"; 1357 case PPCISD::Lo: return "PPCISD::Lo"; 1358 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1359 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1360 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1361 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1362 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1363 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1364 case PPCISD::SRL: return "PPCISD::SRL"; 1365 case PPCISD::SRA: return "PPCISD::SRA"; 1366 case PPCISD::SHL: return "PPCISD::SHL"; 1367 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1368 case PPCISD::CALL: return "PPCISD::CALL"; 1369 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1370 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1371 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1372 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1373 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1374 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1375 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1376 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1377 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1378 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1379 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1380 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1381 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1382 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1383 case PPCISD::ANDI_rec_1_EQ_BIT: 1384 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1385 case PPCISD::ANDI_rec_1_GT_BIT: 1386 return "PPCISD::ANDI_rec_1_GT_BIT"; 1387 case PPCISD::VCMP: return "PPCISD::VCMP"; 1388 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1389 case PPCISD::LBRX: return "PPCISD::LBRX"; 1390 case PPCISD::STBRX: return "PPCISD::STBRX"; 1391 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1392 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1393 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1394 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1395 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1396 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1397 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1398 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1399 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1400 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1401 case PPCISD::ST_VSR_SCAL_INT: 1402 return "PPCISD::ST_VSR_SCAL_INT"; 1403 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1404 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1405 case PPCISD::BDZ: return "PPCISD::BDZ"; 1406 case PPCISD::MFFS: return "PPCISD::MFFS"; 1407 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1408 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1409 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1410 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1411 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1412 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1413 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1414 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1415 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1416 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1417 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1418 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1419 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1420 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1421 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1422 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1423 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1424 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1425 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1426 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1427 case PPCISD::SC: return "PPCISD::SC"; 1428 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1429 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1430 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1431 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1432 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1433 case PPCISD::VABSD: return "PPCISD::VABSD"; 1434 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1435 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1436 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1437 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1438 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1439 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1440 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1441 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1442 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1443 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1444 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1445 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1446 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1447 } 1448 return nullptr; 1449 } 1450 1451 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1452 EVT VT) const { 1453 if (!VT.isVector()) 1454 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1455 1456 if (Subtarget.hasQPX()) 1457 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1458 1459 return VT.changeVectorElementTypeToInteger(); 1460 } 1461 1462 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1463 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1464 return true; 1465 } 1466 1467 //===----------------------------------------------------------------------===// 1468 // Node matching predicates, for use by the tblgen matching code. 1469 //===----------------------------------------------------------------------===// 1470 1471 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1472 static bool isFloatingPointZero(SDValue Op) { 1473 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1474 return CFP->getValueAPF().isZero(); 1475 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1476 // Maybe this has already been legalized into the constant pool? 1477 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1478 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1479 return CFP->getValueAPF().isZero(); 1480 } 1481 return false; 1482 } 1483 1484 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1485 /// true if Op is undef or if it matches the specified value. 1486 static bool isConstantOrUndef(int Op, int Val) { 1487 return Op < 0 || Op == Val; 1488 } 1489 1490 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1491 /// VPKUHUM instruction. 1492 /// The ShuffleKind distinguishes between big-endian operations with 1493 /// two different inputs (0), either-endian operations with two identical 1494 /// inputs (1), and little-endian operations with two different inputs (2). 1495 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1496 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1497 SelectionDAG &DAG) { 1498 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1499 if (ShuffleKind == 0) { 1500 if (IsLE) 1501 return false; 1502 for (unsigned i = 0; i != 16; ++i) 1503 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1504 return false; 1505 } else if (ShuffleKind == 2) { 1506 if (!IsLE) 1507 return false; 1508 for (unsigned i = 0; i != 16; ++i) 1509 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1510 return false; 1511 } else if (ShuffleKind == 1) { 1512 unsigned j = IsLE ? 0 : 1; 1513 for (unsigned i = 0; i != 8; ++i) 1514 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1515 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1516 return false; 1517 } 1518 return true; 1519 } 1520 1521 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1522 /// VPKUWUM instruction. 1523 /// The ShuffleKind distinguishes between big-endian operations with 1524 /// two different inputs (0), either-endian operations with two identical 1525 /// inputs (1), and little-endian operations with two different inputs (2). 1526 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1527 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1528 SelectionDAG &DAG) { 1529 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1530 if (ShuffleKind == 0) { 1531 if (IsLE) 1532 return false; 1533 for (unsigned i = 0; i != 16; i += 2) 1534 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1535 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1536 return false; 1537 } else if (ShuffleKind == 2) { 1538 if (!IsLE) 1539 return false; 1540 for (unsigned i = 0; i != 16; i += 2) 1541 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1542 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1543 return false; 1544 } else if (ShuffleKind == 1) { 1545 unsigned j = IsLE ? 0 : 2; 1546 for (unsigned i = 0; i != 8; i += 2) 1547 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1548 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1549 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1550 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1551 return false; 1552 } 1553 return true; 1554 } 1555 1556 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1557 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1558 /// current subtarget. 1559 /// 1560 /// The ShuffleKind distinguishes between big-endian operations with 1561 /// two different inputs (0), either-endian operations with two identical 1562 /// inputs (1), and little-endian operations with two different inputs (2). 1563 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1564 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1565 SelectionDAG &DAG) { 1566 const PPCSubtarget& Subtarget = 1567 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1568 if (!Subtarget.hasP8Vector()) 1569 return false; 1570 1571 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1572 if (ShuffleKind == 0) { 1573 if (IsLE) 1574 return false; 1575 for (unsigned i = 0; i != 16; i += 4) 1576 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1577 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1578 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1579 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1580 return false; 1581 } else if (ShuffleKind == 2) { 1582 if (!IsLE) 1583 return false; 1584 for (unsigned i = 0; i != 16; i += 4) 1585 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1586 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1587 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1588 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1589 return false; 1590 } else if (ShuffleKind == 1) { 1591 unsigned j = IsLE ? 0 : 4; 1592 for (unsigned i = 0; i != 8; i += 4) 1593 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1594 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1595 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1596 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1597 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1598 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1599 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1600 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1601 return false; 1602 } 1603 return true; 1604 } 1605 1606 /// isVMerge - Common function, used to match vmrg* shuffles. 1607 /// 1608 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1609 unsigned LHSStart, unsigned RHSStart) { 1610 if (N->getValueType(0) != MVT::v16i8) 1611 return false; 1612 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1613 "Unsupported merge size!"); 1614 1615 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1616 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1617 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1618 LHSStart+j+i*UnitSize) || 1619 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1620 RHSStart+j+i*UnitSize)) 1621 return false; 1622 } 1623 return true; 1624 } 1625 1626 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1627 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1628 /// The ShuffleKind distinguishes between big-endian merges with two 1629 /// different inputs (0), either-endian merges with two identical inputs (1), 1630 /// and little-endian merges with two different inputs (2). For the latter, 1631 /// the input operands are swapped (see PPCInstrAltivec.td). 1632 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1633 unsigned ShuffleKind, SelectionDAG &DAG) { 1634 if (DAG.getDataLayout().isLittleEndian()) { 1635 if (ShuffleKind == 1) // unary 1636 return isVMerge(N, UnitSize, 0, 0); 1637 else if (ShuffleKind == 2) // swapped 1638 return isVMerge(N, UnitSize, 0, 16); 1639 else 1640 return false; 1641 } else { 1642 if (ShuffleKind == 1) // unary 1643 return isVMerge(N, UnitSize, 8, 8); 1644 else if (ShuffleKind == 0) // normal 1645 return isVMerge(N, UnitSize, 8, 24); 1646 else 1647 return false; 1648 } 1649 } 1650 1651 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1652 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1653 /// The ShuffleKind distinguishes between big-endian merges with two 1654 /// different inputs (0), either-endian merges with two identical inputs (1), 1655 /// and little-endian merges with two different inputs (2). For the latter, 1656 /// the input operands are swapped (see PPCInstrAltivec.td). 1657 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1658 unsigned ShuffleKind, SelectionDAG &DAG) { 1659 if (DAG.getDataLayout().isLittleEndian()) { 1660 if (ShuffleKind == 1) // unary 1661 return isVMerge(N, UnitSize, 8, 8); 1662 else if (ShuffleKind == 2) // swapped 1663 return isVMerge(N, UnitSize, 8, 24); 1664 else 1665 return false; 1666 } else { 1667 if (ShuffleKind == 1) // unary 1668 return isVMerge(N, UnitSize, 0, 0); 1669 else if (ShuffleKind == 0) // normal 1670 return isVMerge(N, UnitSize, 0, 16); 1671 else 1672 return false; 1673 } 1674 } 1675 1676 /** 1677 * Common function used to match vmrgew and vmrgow shuffles 1678 * 1679 * The indexOffset determines whether to look for even or odd words in 1680 * the shuffle mask. This is based on the of the endianness of the target 1681 * machine. 1682 * - Little Endian: 1683 * - Use offset of 0 to check for odd elements 1684 * - Use offset of 4 to check for even elements 1685 * - Big Endian: 1686 * - Use offset of 0 to check for even elements 1687 * - Use offset of 4 to check for odd elements 1688 * A detailed description of the vector element ordering for little endian and 1689 * big endian can be found at 1690 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1691 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1692 * compiler differences mean to you 1693 * 1694 * The mask to the shuffle vector instruction specifies the indices of the 1695 * elements from the two input vectors to place in the result. The elements are 1696 * numbered in array-access order, starting with the first vector. These vectors 1697 * are always of type v16i8, thus each vector will contain 16 elements of size 1698 * 8. More info on the shuffle vector can be found in the 1699 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1700 * Language Reference. 1701 * 1702 * The RHSStartValue indicates whether the same input vectors are used (unary) 1703 * or two different input vectors are used, based on the following: 1704 * - If the instruction uses the same vector for both inputs, the range of the 1705 * indices will be 0 to 15. In this case, the RHSStart value passed should 1706 * be 0. 1707 * - If the instruction has two different vectors then the range of the 1708 * indices will be 0 to 31. In this case, the RHSStart value passed should 1709 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1710 * to 31 specify elements in the second vector). 1711 * 1712 * \param[in] N The shuffle vector SD Node to analyze 1713 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1714 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1715 * vector to the shuffle_vector instruction 1716 * \return true iff this shuffle vector represents an even or odd word merge 1717 */ 1718 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1719 unsigned RHSStartValue) { 1720 if (N->getValueType(0) != MVT::v16i8) 1721 return false; 1722 1723 for (unsigned i = 0; i < 2; ++i) 1724 for (unsigned j = 0; j < 4; ++j) 1725 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1726 i*RHSStartValue+j+IndexOffset) || 1727 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1728 i*RHSStartValue+j+IndexOffset+8)) 1729 return false; 1730 return true; 1731 } 1732 1733 /** 1734 * Determine if the specified shuffle mask is suitable for the vmrgew or 1735 * vmrgow instructions. 1736 * 1737 * \param[in] N The shuffle vector SD Node to analyze 1738 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1739 * \param[in] ShuffleKind Identify the type of merge: 1740 * - 0 = big-endian merge with two different inputs; 1741 * - 1 = either-endian merge with two identical inputs; 1742 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1743 * little-endian merges). 1744 * \param[in] DAG The current SelectionDAG 1745 * \return true iff this shuffle mask 1746 */ 1747 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1748 unsigned ShuffleKind, SelectionDAG &DAG) { 1749 if (DAG.getDataLayout().isLittleEndian()) { 1750 unsigned indexOffset = CheckEven ? 4 : 0; 1751 if (ShuffleKind == 1) // Unary 1752 return isVMerge(N, indexOffset, 0); 1753 else if (ShuffleKind == 2) // swapped 1754 return isVMerge(N, indexOffset, 16); 1755 else 1756 return false; 1757 } 1758 else { 1759 unsigned indexOffset = CheckEven ? 0 : 4; 1760 if (ShuffleKind == 1) // Unary 1761 return isVMerge(N, indexOffset, 0); 1762 else if (ShuffleKind == 0) // Normal 1763 return isVMerge(N, indexOffset, 16); 1764 else 1765 return false; 1766 } 1767 return false; 1768 } 1769 1770 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1771 /// amount, otherwise return -1. 1772 /// The ShuffleKind distinguishes between big-endian operations with two 1773 /// different inputs (0), either-endian operations with two identical inputs 1774 /// (1), and little-endian operations with two different inputs (2). For the 1775 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1776 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1777 SelectionDAG &DAG) { 1778 if (N->getValueType(0) != MVT::v16i8) 1779 return -1; 1780 1781 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1782 1783 // Find the first non-undef value in the shuffle mask. 1784 unsigned i; 1785 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1786 /*search*/; 1787 1788 if (i == 16) return -1; // all undef. 1789 1790 // Otherwise, check to see if the rest of the elements are consecutively 1791 // numbered from this value. 1792 unsigned ShiftAmt = SVOp->getMaskElt(i); 1793 if (ShiftAmt < i) return -1; 1794 1795 ShiftAmt -= i; 1796 bool isLE = DAG.getDataLayout().isLittleEndian(); 1797 1798 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1799 // Check the rest of the elements to see if they are consecutive. 1800 for (++i; i != 16; ++i) 1801 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1802 return -1; 1803 } else if (ShuffleKind == 1) { 1804 // Check the rest of the elements to see if they are consecutive. 1805 for (++i; i != 16; ++i) 1806 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1807 return -1; 1808 } else 1809 return -1; 1810 1811 if (isLE) 1812 ShiftAmt = 16 - ShiftAmt; 1813 1814 return ShiftAmt; 1815 } 1816 1817 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1818 /// specifies a splat of a single element that is suitable for input to 1819 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1820 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1821 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1822 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1823 1824 // The consecutive indices need to specify an element, not part of two 1825 // different elements. So abandon ship early if this isn't the case. 1826 if (N->getMaskElt(0) % EltSize != 0) 1827 return false; 1828 1829 // This is a splat operation if each element of the permute is the same, and 1830 // if the value doesn't reference the second vector. 1831 unsigned ElementBase = N->getMaskElt(0); 1832 1833 // FIXME: Handle UNDEF elements too! 1834 if (ElementBase >= 16) 1835 return false; 1836 1837 // Check that the indices are consecutive, in the case of a multi-byte element 1838 // splatted with a v16i8 mask. 1839 for (unsigned i = 1; i != EltSize; ++i) 1840 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1841 return false; 1842 1843 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1844 if (N->getMaskElt(i) < 0) continue; 1845 for (unsigned j = 0; j != EltSize; ++j) 1846 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1847 return false; 1848 } 1849 return true; 1850 } 1851 1852 /// Check that the mask is shuffling N byte elements. Within each N byte 1853 /// element of the mask, the indices could be either in increasing or 1854 /// decreasing order as long as they are consecutive. 1855 /// \param[in] N the shuffle vector SD Node to analyze 1856 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1857 /// Word/DoubleWord/QuadWord). 1858 /// \param[in] StepLen the delta indices number among the N byte element, if 1859 /// the mask is in increasing/decreasing order then it is 1/-1. 1860 /// \return true iff the mask is shuffling N byte elements. 1861 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1862 int StepLen) { 1863 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1864 "Unexpected element width."); 1865 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1866 1867 unsigned NumOfElem = 16 / Width; 1868 unsigned MaskVal[16]; // Width is never greater than 16 1869 for (unsigned i = 0; i < NumOfElem; ++i) { 1870 MaskVal[0] = N->getMaskElt(i * Width); 1871 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1872 return false; 1873 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1874 return false; 1875 } 1876 1877 for (unsigned int j = 1; j < Width; ++j) { 1878 MaskVal[j] = N->getMaskElt(i * Width + j); 1879 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1880 return false; 1881 } 1882 } 1883 } 1884 1885 return true; 1886 } 1887 1888 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1889 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1890 if (!isNByteElemShuffleMask(N, 4, 1)) 1891 return false; 1892 1893 // Now we look at mask elements 0,4,8,12 1894 unsigned M0 = N->getMaskElt(0) / 4; 1895 unsigned M1 = N->getMaskElt(4) / 4; 1896 unsigned M2 = N->getMaskElt(8) / 4; 1897 unsigned M3 = N->getMaskElt(12) / 4; 1898 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1899 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1900 1901 // Below, let H and L be arbitrary elements of the shuffle mask 1902 // where H is in the range [4,7] and L is in the range [0,3]. 1903 // H, 1, 2, 3 or L, 5, 6, 7 1904 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1905 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1906 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1907 InsertAtByte = IsLE ? 12 : 0; 1908 Swap = M0 < 4; 1909 return true; 1910 } 1911 // 0, H, 2, 3 or 4, L, 6, 7 1912 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1913 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1914 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1915 InsertAtByte = IsLE ? 8 : 4; 1916 Swap = M1 < 4; 1917 return true; 1918 } 1919 // 0, 1, H, 3 or 4, 5, L, 7 1920 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1921 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1922 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1923 InsertAtByte = IsLE ? 4 : 8; 1924 Swap = M2 < 4; 1925 return true; 1926 } 1927 // 0, 1, 2, H or 4, 5, 6, L 1928 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1929 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1930 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1931 InsertAtByte = IsLE ? 0 : 12; 1932 Swap = M3 < 4; 1933 return true; 1934 } 1935 1936 // If both vector operands for the shuffle are the same vector, the mask will 1937 // contain only elements from the first one and the second one will be undef. 1938 if (N->getOperand(1).isUndef()) { 1939 ShiftElts = 0; 1940 Swap = true; 1941 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1942 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1943 InsertAtByte = IsLE ? 12 : 0; 1944 return true; 1945 } 1946 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1947 InsertAtByte = IsLE ? 8 : 4; 1948 return true; 1949 } 1950 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1951 InsertAtByte = IsLE ? 4 : 8; 1952 return true; 1953 } 1954 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1955 InsertAtByte = IsLE ? 0 : 12; 1956 return true; 1957 } 1958 } 1959 1960 return false; 1961 } 1962 1963 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1964 bool &Swap, bool IsLE) { 1965 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1966 // Ensure each byte index of the word is consecutive. 1967 if (!isNByteElemShuffleMask(N, 4, 1)) 1968 return false; 1969 1970 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1971 unsigned M0 = N->getMaskElt(0) / 4; 1972 unsigned M1 = N->getMaskElt(4) / 4; 1973 unsigned M2 = N->getMaskElt(8) / 4; 1974 unsigned M3 = N->getMaskElt(12) / 4; 1975 1976 // If both vector operands for the shuffle are the same vector, the mask will 1977 // contain only elements from the first one and the second one will be undef. 1978 if (N->getOperand(1).isUndef()) { 1979 assert(M0 < 4 && "Indexing into an undef vector?"); 1980 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1981 return false; 1982 1983 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1984 Swap = false; 1985 return true; 1986 } 1987 1988 // Ensure each word index of the ShuffleVector Mask is consecutive. 1989 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1990 return false; 1991 1992 if (IsLE) { 1993 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1994 // Input vectors don't need to be swapped if the leading element 1995 // of the result is one of the 3 left elements of the second vector 1996 // (or if there is no shift to be done at all). 1997 Swap = false; 1998 ShiftElts = (8 - M0) % 8; 1999 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2000 // Input vectors need to be swapped if the leading element 2001 // of the result is one of the 3 left elements of the first vector 2002 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2003 Swap = true; 2004 ShiftElts = (4 - M0) % 4; 2005 } 2006 2007 return true; 2008 } else { // BE 2009 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2010 // Input vectors don't need to be swapped if the leading element 2011 // of the result is one of the 4 elements of the first vector. 2012 Swap = false; 2013 ShiftElts = M0; 2014 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2015 // Input vectors need to be swapped if the leading element 2016 // of the result is one of the 4 elements of the right vector. 2017 Swap = true; 2018 ShiftElts = M0 - 4; 2019 } 2020 2021 return true; 2022 } 2023 } 2024 2025 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2026 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2027 2028 if (!isNByteElemShuffleMask(N, Width, -1)) 2029 return false; 2030 2031 for (int i = 0; i < 16; i += Width) 2032 if (N->getMaskElt(i) != i + Width - 1) 2033 return false; 2034 2035 return true; 2036 } 2037 2038 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2039 return isXXBRShuffleMaskHelper(N, 2); 2040 } 2041 2042 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2043 return isXXBRShuffleMaskHelper(N, 4); 2044 } 2045 2046 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2047 return isXXBRShuffleMaskHelper(N, 8); 2048 } 2049 2050 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2051 return isXXBRShuffleMaskHelper(N, 16); 2052 } 2053 2054 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2055 /// if the inputs to the instruction should be swapped and set \p DM to the 2056 /// value for the immediate. 2057 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2058 /// AND element 0 of the result comes from the first input (LE) or second input 2059 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2060 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2061 /// mask. 2062 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2063 bool &Swap, bool IsLE) { 2064 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2065 2066 // Ensure each byte index of the double word is consecutive. 2067 if (!isNByteElemShuffleMask(N, 8, 1)) 2068 return false; 2069 2070 unsigned M0 = N->getMaskElt(0) / 8; 2071 unsigned M1 = N->getMaskElt(8) / 8; 2072 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2073 2074 // If both vector operands for the shuffle are the same vector, the mask will 2075 // contain only elements from the first one and the second one will be undef. 2076 if (N->getOperand(1).isUndef()) { 2077 if ((M0 | M1) < 2) { 2078 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2079 Swap = false; 2080 return true; 2081 } else 2082 return false; 2083 } 2084 2085 if (IsLE) { 2086 if (M0 > 1 && M1 < 2) { 2087 Swap = false; 2088 } else if (M0 < 2 && M1 > 1) { 2089 M0 = (M0 + 2) % 4; 2090 M1 = (M1 + 2) % 4; 2091 Swap = true; 2092 } else 2093 return false; 2094 2095 // Note: if control flow comes here that means Swap is already set above 2096 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2097 return true; 2098 } else { // BE 2099 if (M0 < 2 && M1 > 1) { 2100 Swap = false; 2101 } else if (M0 > 1 && M1 < 2) { 2102 M0 = (M0 + 2) % 4; 2103 M1 = (M1 + 2) % 4; 2104 Swap = true; 2105 } else 2106 return false; 2107 2108 // Note: if control flow comes here that means Swap is already set above 2109 DM = (M0 << 1) + (M1 & 1); 2110 return true; 2111 } 2112 } 2113 2114 2115 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2116 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2117 /// elements are counted from the left of the vector register). 2118 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2119 SelectionDAG &DAG) { 2120 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2121 assert(isSplatShuffleMask(SVOp, EltSize)); 2122 if (DAG.getDataLayout().isLittleEndian()) 2123 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2124 else 2125 return SVOp->getMaskElt(0) / EltSize; 2126 } 2127 2128 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2129 /// by using a vspltis[bhw] instruction of the specified element size, return 2130 /// the constant being splatted. The ByteSize field indicates the number of 2131 /// bytes of each element [124] -> [bhw]. 2132 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2133 SDValue OpVal(nullptr, 0); 2134 2135 // If ByteSize of the splat is bigger than the element size of the 2136 // build_vector, then we have a case where we are checking for a splat where 2137 // multiple elements of the buildvector are folded together into a single 2138 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2139 unsigned EltSize = 16/N->getNumOperands(); 2140 if (EltSize < ByteSize) { 2141 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2142 SDValue UniquedVals[4]; 2143 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2144 2145 // See if all of the elements in the buildvector agree across. 2146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2147 if (N->getOperand(i).isUndef()) continue; 2148 // If the element isn't a constant, bail fully out. 2149 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2150 2151 if (!UniquedVals[i&(Multiple-1)].getNode()) 2152 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2153 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2154 return SDValue(); // no match. 2155 } 2156 2157 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2158 // either constant or undef values that are identical for each chunk. See 2159 // if these chunks can form into a larger vspltis*. 2160 2161 // Check to see if all of the leading entries are either 0 or -1. If 2162 // neither, then this won't fit into the immediate field. 2163 bool LeadingZero = true; 2164 bool LeadingOnes = true; 2165 for (unsigned i = 0; i != Multiple-1; ++i) { 2166 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2167 2168 LeadingZero &= isNullConstant(UniquedVals[i]); 2169 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2170 } 2171 // Finally, check the least significant entry. 2172 if (LeadingZero) { 2173 if (!UniquedVals[Multiple-1].getNode()) 2174 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2175 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2176 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2177 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2178 } 2179 if (LeadingOnes) { 2180 if (!UniquedVals[Multiple-1].getNode()) 2181 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2182 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2183 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2184 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2185 } 2186 2187 return SDValue(); 2188 } 2189 2190 // Check to see if this buildvec has a single non-undef value in its elements. 2191 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2192 if (N->getOperand(i).isUndef()) continue; 2193 if (!OpVal.getNode()) 2194 OpVal = N->getOperand(i); 2195 else if (OpVal != N->getOperand(i)) 2196 return SDValue(); 2197 } 2198 2199 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2200 2201 unsigned ValSizeInBytes = EltSize; 2202 uint64_t Value = 0; 2203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2204 Value = CN->getZExtValue(); 2205 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2206 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2207 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2208 } 2209 2210 // If the splat value is larger than the element value, then we can never do 2211 // this splat. The only case that we could fit the replicated bits into our 2212 // immediate field for would be zero, and we prefer to use vxor for it. 2213 if (ValSizeInBytes < ByteSize) return SDValue(); 2214 2215 // If the element value is larger than the splat value, check if it consists 2216 // of a repeated bit pattern of size ByteSize. 2217 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2218 return SDValue(); 2219 2220 // Properly sign extend the value. 2221 int MaskVal = SignExtend32(Value, ByteSize * 8); 2222 2223 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2224 if (MaskVal == 0) return SDValue(); 2225 2226 // Finally, if this value fits in a 5 bit sext field, return it 2227 if (SignExtend32<5>(MaskVal) == MaskVal) 2228 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2229 return SDValue(); 2230 } 2231 2232 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2233 /// amount, otherwise return -1. 2234 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2235 EVT VT = N->getValueType(0); 2236 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2237 return -1; 2238 2239 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2240 2241 // Find the first non-undef value in the shuffle mask. 2242 unsigned i; 2243 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2244 /*search*/; 2245 2246 if (i == 4) return -1; // all undef. 2247 2248 // Otherwise, check to see if the rest of the elements are consecutively 2249 // numbered from this value. 2250 unsigned ShiftAmt = SVOp->getMaskElt(i); 2251 if (ShiftAmt < i) return -1; 2252 ShiftAmt -= i; 2253 2254 // Check the rest of the elements to see if they are consecutive. 2255 for (++i; i != 4; ++i) 2256 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2257 return -1; 2258 2259 return ShiftAmt; 2260 } 2261 2262 //===----------------------------------------------------------------------===// 2263 // Addressing Mode Selection 2264 //===----------------------------------------------------------------------===// 2265 2266 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2267 /// or 64-bit immediate, and if the value can be accurately represented as a 2268 /// sign extension from a 16-bit value. If so, this returns true and the 2269 /// immediate. 2270 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2271 if (!isa<ConstantSDNode>(N)) 2272 return false; 2273 2274 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2275 if (N->getValueType(0) == MVT::i32) 2276 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2277 else 2278 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2279 } 2280 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2281 return isIntS16Immediate(Op.getNode(), Imm); 2282 } 2283 2284 2285 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2286 /// be represented as an indexed [r+r] operation. 2287 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2288 SDValue &Index, 2289 SelectionDAG &DAG) const { 2290 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2291 UI != E; ++UI) { 2292 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2293 if (Memop->getMemoryVT() == MVT::f64) { 2294 Base = N.getOperand(0); 2295 Index = N.getOperand(1); 2296 return true; 2297 } 2298 } 2299 } 2300 return false; 2301 } 2302 2303 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2304 /// can be represented as an indexed [r+r] operation. Returns false if it 2305 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2306 /// non-zero and N can be represented by a base register plus a signed 16-bit 2307 /// displacement, make a more precise judgement by checking (displacement % \p 2308 /// EncodingAlignment). 2309 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2310 SDValue &Index, SelectionDAG &DAG, 2311 unsigned EncodingAlignment) const { 2312 int16_t imm = 0; 2313 if (N.getOpcode() == ISD::ADD) { 2314 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2315 // SPE load/store can only handle 8-bit offsets. 2316 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2317 return true; 2318 if (isIntS16Immediate(N.getOperand(1), imm) && 2319 (!EncodingAlignment || !(imm % EncodingAlignment))) 2320 return false; // r+i 2321 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2322 return false; // r+i 2323 2324 Base = N.getOperand(0); 2325 Index = N.getOperand(1); 2326 return true; 2327 } else if (N.getOpcode() == ISD::OR) { 2328 if (isIntS16Immediate(N.getOperand(1), imm) && 2329 (!EncodingAlignment || !(imm % EncodingAlignment))) 2330 return false; // r+i can fold it if we can. 2331 2332 // If this is an or of disjoint bitfields, we can codegen this as an add 2333 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2334 // disjoint. 2335 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2336 2337 if (LHSKnown.Zero.getBoolValue()) { 2338 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2339 // If all of the bits are known zero on the LHS or RHS, the add won't 2340 // carry. 2341 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2342 Base = N.getOperand(0); 2343 Index = N.getOperand(1); 2344 return true; 2345 } 2346 } 2347 } 2348 2349 return false; 2350 } 2351 2352 // If we happen to be doing an i64 load or store into a stack slot that has 2353 // less than a 4-byte alignment, then the frame-index elimination may need to 2354 // use an indexed load or store instruction (because the offset may not be a 2355 // multiple of 4). The extra register needed to hold the offset comes from the 2356 // register scavenger, and it is possible that the scavenger will need to use 2357 // an emergency spill slot. As a result, we need to make sure that a spill slot 2358 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2359 // stack slot. 2360 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2361 // FIXME: This does not handle the LWA case. 2362 if (VT != MVT::i64) 2363 return; 2364 2365 // NOTE: We'll exclude negative FIs here, which come from argument 2366 // lowering, because there are no known test cases triggering this problem 2367 // using packed structures (or similar). We can remove this exclusion if 2368 // we find such a test case. The reason why this is so test-case driven is 2369 // because this entire 'fixup' is only to prevent crashes (from the 2370 // register scavenger) on not-really-valid inputs. For example, if we have: 2371 // %a = alloca i1 2372 // %b = bitcast i1* %a to i64* 2373 // store i64* a, i64 b 2374 // then the store should really be marked as 'align 1', but is not. If it 2375 // were marked as 'align 1' then the indexed form would have been 2376 // instruction-selected initially, and the problem this 'fixup' is preventing 2377 // won't happen regardless. 2378 if (FrameIdx < 0) 2379 return; 2380 2381 MachineFunction &MF = DAG.getMachineFunction(); 2382 MachineFrameInfo &MFI = MF.getFrameInfo(); 2383 2384 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2385 if (Align >= 4) 2386 return; 2387 2388 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2389 FuncInfo->setHasNonRISpills(); 2390 } 2391 2392 /// Returns true if the address N can be represented by a base register plus 2393 /// a signed 16-bit displacement [r+imm], and if it is not better 2394 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2395 /// displacements that are multiples of that value. 2396 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2397 SDValue &Base, 2398 SelectionDAG &DAG, 2399 unsigned EncodingAlignment) const { 2400 // FIXME dl should come from parent load or store, not from address 2401 SDLoc dl(N); 2402 // If this can be more profitably realized as r+r, fail. 2403 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2404 return false; 2405 2406 if (N.getOpcode() == ISD::ADD) { 2407 int16_t imm = 0; 2408 if (isIntS16Immediate(N.getOperand(1), imm) && 2409 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2410 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2411 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2412 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2413 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2414 } else { 2415 Base = N.getOperand(0); 2416 } 2417 return true; // [r+i] 2418 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2419 // Match LOAD (ADD (X, Lo(G))). 2420 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2421 && "Cannot handle constant offsets yet!"); 2422 Disp = N.getOperand(1).getOperand(0); // The global address. 2423 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2424 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2425 Disp.getOpcode() == ISD::TargetConstantPool || 2426 Disp.getOpcode() == ISD::TargetJumpTable); 2427 Base = N.getOperand(0); 2428 return true; // [&g+r] 2429 } 2430 } else if (N.getOpcode() == ISD::OR) { 2431 int16_t imm = 0; 2432 if (isIntS16Immediate(N.getOperand(1), imm) && 2433 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2434 // If this is an or of disjoint bitfields, we can codegen this as an add 2435 // (for better address arithmetic) if the LHS and RHS of the OR are 2436 // provably disjoint. 2437 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2438 2439 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2440 // If all of the bits are known zero on the LHS or RHS, the add won't 2441 // carry. 2442 if (FrameIndexSDNode *FI = 2443 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2444 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2445 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2446 } else { 2447 Base = N.getOperand(0); 2448 } 2449 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2450 return true; 2451 } 2452 } 2453 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2454 // Loading from a constant address. 2455 2456 // If this address fits entirely in a 16-bit sext immediate field, codegen 2457 // this as "d, 0" 2458 int16_t Imm; 2459 if (isIntS16Immediate(CN, Imm) && 2460 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2461 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2462 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2463 CN->getValueType(0)); 2464 return true; 2465 } 2466 2467 // Handle 32-bit sext immediates with LIS + addr mode. 2468 if ((CN->getValueType(0) == MVT::i32 || 2469 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2470 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2471 int Addr = (int)CN->getZExtValue(); 2472 2473 // Otherwise, break this down into an LIS + disp. 2474 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2475 2476 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2477 MVT::i32); 2478 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2479 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2480 return true; 2481 } 2482 } 2483 2484 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2485 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2486 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2487 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2488 } else 2489 Base = N; 2490 return true; // [r+0] 2491 } 2492 2493 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2494 /// represented as an indexed [r+r] operation. 2495 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2496 SDValue &Index, 2497 SelectionDAG &DAG) const { 2498 // Check to see if we can easily represent this as an [r+r] address. This 2499 // will fail if it thinks that the address is more profitably represented as 2500 // reg+imm, e.g. where imm = 0. 2501 if (SelectAddressRegReg(N, Base, Index, DAG)) 2502 return true; 2503 2504 // If the address is the result of an add, we will utilize the fact that the 2505 // address calculation includes an implicit add. However, we can reduce 2506 // register pressure if we do not materialize a constant just for use as the 2507 // index register. We only get rid of the add if it is not an add of a 2508 // value and a 16-bit signed constant and both have a single use. 2509 int16_t imm = 0; 2510 if (N.getOpcode() == ISD::ADD && 2511 (!isIntS16Immediate(N.getOperand(1), imm) || 2512 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2513 Base = N.getOperand(0); 2514 Index = N.getOperand(1); 2515 return true; 2516 } 2517 2518 // Otherwise, do it the hard way, using R0 as the base register. 2519 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2520 N.getValueType()); 2521 Index = N; 2522 return true; 2523 } 2524 2525 /// Returns true if we should use a direct load into vector instruction 2526 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2527 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2528 2529 // If there are any other uses other than scalar to vector, then we should 2530 // keep it as a scalar load -> direct move pattern to prevent multiple 2531 // loads. 2532 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2533 if (!LD) 2534 return false; 2535 2536 EVT MemVT = LD->getMemoryVT(); 2537 if (!MemVT.isSimple()) 2538 return false; 2539 switch(MemVT.getSimpleVT().SimpleTy) { 2540 case MVT::i64: 2541 break; 2542 case MVT::i32: 2543 if (!ST.hasP8Vector()) 2544 return false; 2545 break; 2546 case MVT::i16: 2547 case MVT::i8: 2548 if (!ST.hasP9Vector()) 2549 return false; 2550 break; 2551 default: 2552 return false; 2553 } 2554 2555 SDValue LoadedVal(N, 0); 2556 if (!LoadedVal.hasOneUse()) 2557 return false; 2558 2559 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2560 UI != UE; ++UI) 2561 if (UI.getUse().get().getResNo() == 0 && 2562 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2563 return false; 2564 2565 return true; 2566 } 2567 2568 /// getPreIndexedAddressParts - returns true by value, base pointer and 2569 /// offset pointer and addressing mode by reference if the node's address 2570 /// can be legally represented as pre-indexed load / store address. 2571 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2572 SDValue &Offset, 2573 ISD::MemIndexedMode &AM, 2574 SelectionDAG &DAG) const { 2575 if (DisablePPCPreinc) return false; 2576 2577 bool isLoad = true; 2578 SDValue Ptr; 2579 EVT VT; 2580 unsigned Alignment; 2581 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2582 Ptr = LD->getBasePtr(); 2583 VT = LD->getMemoryVT(); 2584 Alignment = LD->getAlignment(); 2585 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2586 Ptr = ST->getBasePtr(); 2587 VT = ST->getMemoryVT(); 2588 Alignment = ST->getAlignment(); 2589 isLoad = false; 2590 } else 2591 return false; 2592 2593 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2594 // instructions because we can fold these into a more efficient instruction 2595 // instead, (such as LXSD). 2596 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2597 return false; 2598 } 2599 2600 // PowerPC doesn't have preinc load/store instructions for vectors (except 2601 // for QPX, which does have preinc r+r forms). 2602 if (VT.isVector()) { 2603 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2604 return false; 2605 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2606 AM = ISD::PRE_INC; 2607 return true; 2608 } 2609 } 2610 2611 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2612 // Common code will reject creating a pre-inc form if the base pointer 2613 // is a frame index, or if N is a store and the base pointer is either 2614 // the same as or a predecessor of the value being stored. Check for 2615 // those situations here, and try with swapped Base/Offset instead. 2616 bool Swap = false; 2617 2618 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2619 Swap = true; 2620 else if (!isLoad) { 2621 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2622 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2623 Swap = true; 2624 } 2625 2626 if (Swap) 2627 std::swap(Base, Offset); 2628 2629 AM = ISD::PRE_INC; 2630 return true; 2631 } 2632 2633 // LDU/STU can only handle immediates that are a multiple of 4. 2634 if (VT != MVT::i64) { 2635 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2636 return false; 2637 } else { 2638 // LDU/STU need an address with at least 4-byte alignment. 2639 if (Alignment < 4) 2640 return false; 2641 2642 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2643 return false; 2644 } 2645 2646 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2647 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2648 // sext i32 to i64 when addr mode is r+i. 2649 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2650 LD->getExtensionType() == ISD::SEXTLOAD && 2651 isa<ConstantSDNode>(Offset)) 2652 return false; 2653 } 2654 2655 AM = ISD::PRE_INC; 2656 return true; 2657 } 2658 2659 //===----------------------------------------------------------------------===// 2660 // LowerOperation implementation 2661 //===----------------------------------------------------------------------===// 2662 2663 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2664 /// and LoOpFlags to the target MO flags. 2665 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2666 unsigned &HiOpFlags, unsigned &LoOpFlags, 2667 const GlobalValue *GV = nullptr) { 2668 HiOpFlags = PPCII::MO_HA; 2669 LoOpFlags = PPCII::MO_LO; 2670 2671 // Don't use the pic base if not in PIC relocation model. 2672 if (IsPIC) { 2673 HiOpFlags |= PPCII::MO_PIC_FLAG; 2674 LoOpFlags |= PPCII::MO_PIC_FLAG; 2675 } 2676 } 2677 2678 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2679 SelectionDAG &DAG) { 2680 SDLoc DL(HiPart); 2681 EVT PtrVT = HiPart.getValueType(); 2682 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2683 2684 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2685 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2686 2687 // With PIC, the first instruction is actually "GR+hi(&G)". 2688 if (isPIC) 2689 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2690 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2691 2692 // Generate non-pic code that has direct accesses to the constant pool. 2693 // The address of the global is just (hi(&g)+lo(&g)). 2694 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2695 } 2696 2697 static void setUsesTOCBasePtr(MachineFunction &MF) { 2698 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2699 FuncInfo->setUsesTOCBasePtr(); 2700 } 2701 2702 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2703 setUsesTOCBasePtr(DAG.getMachineFunction()); 2704 } 2705 2706 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2707 SDValue GA) const { 2708 const bool Is64Bit = Subtarget.isPPC64(); 2709 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2710 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2711 : Subtarget.isAIXABI() 2712 ? DAG.getRegister(PPC::R2, VT) 2713 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2714 SDValue Ops[] = { GA, Reg }; 2715 return DAG.getMemIntrinsicNode( 2716 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2717 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2718 MachineMemOperand::MOLoad); 2719 } 2720 2721 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2722 SelectionDAG &DAG) const { 2723 EVT PtrVT = Op.getValueType(); 2724 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2725 const Constant *C = CP->getConstVal(); 2726 2727 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2728 // The actual address of the GlobalValue is stored in the TOC. 2729 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2730 setUsesTOCBasePtr(DAG); 2731 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2732 return getTOCEntry(DAG, SDLoc(CP), GA); 2733 } 2734 2735 unsigned MOHiFlag, MOLoFlag; 2736 bool IsPIC = isPositionIndependent(); 2737 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2738 2739 if (IsPIC && Subtarget.isSVR4ABI()) { 2740 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2741 PPCII::MO_PIC_FLAG); 2742 return getTOCEntry(DAG, SDLoc(CP), GA); 2743 } 2744 2745 SDValue CPIHi = 2746 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2747 SDValue CPILo = 2748 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2749 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2750 } 2751 2752 // For 64-bit PowerPC, prefer the more compact relative encodings. 2753 // This trades 32 bits per jump table entry for one or two instructions 2754 // on the jump site. 2755 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2756 if (isJumpTableRelative()) 2757 return MachineJumpTableInfo::EK_LabelDifference32; 2758 2759 return TargetLowering::getJumpTableEncoding(); 2760 } 2761 2762 bool PPCTargetLowering::isJumpTableRelative() const { 2763 if (UseAbsoluteJumpTables) 2764 return false; 2765 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2766 return true; 2767 return TargetLowering::isJumpTableRelative(); 2768 } 2769 2770 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2771 SelectionDAG &DAG) const { 2772 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2773 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2774 2775 switch (getTargetMachine().getCodeModel()) { 2776 case CodeModel::Small: 2777 case CodeModel::Medium: 2778 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2779 default: 2780 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2781 getPointerTy(DAG.getDataLayout())); 2782 } 2783 } 2784 2785 const MCExpr * 2786 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2787 unsigned JTI, 2788 MCContext &Ctx) const { 2789 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2790 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2791 2792 switch (getTargetMachine().getCodeModel()) { 2793 case CodeModel::Small: 2794 case CodeModel::Medium: 2795 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2796 default: 2797 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2798 } 2799 } 2800 2801 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2802 EVT PtrVT = Op.getValueType(); 2803 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2804 2805 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2806 // The actual address of the GlobalValue is stored in the TOC. 2807 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2808 setUsesTOCBasePtr(DAG); 2809 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2810 return getTOCEntry(DAG, SDLoc(JT), GA); 2811 } 2812 2813 unsigned MOHiFlag, MOLoFlag; 2814 bool IsPIC = isPositionIndependent(); 2815 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2816 2817 if (IsPIC && Subtarget.isSVR4ABI()) { 2818 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2819 PPCII::MO_PIC_FLAG); 2820 return getTOCEntry(DAG, SDLoc(GA), GA); 2821 } 2822 2823 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2824 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2825 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2826 } 2827 2828 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2829 SelectionDAG &DAG) const { 2830 EVT PtrVT = Op.getValueType(); 2831 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2832 const BlockAddress *BA = BASDN->getBlockAddress(); 2833 2834 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2835 // The actual BlockAddress is stored in the TOC. 2836 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2837 setUsesTOCBasePtr(DAG); 2838 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2839 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2840 } 2841 2842 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2843 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2844 return getTOCEntry( 2845 DAG, SDLoc(BASDN), 2846 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2847 2848 unsigned MOHiFlag, MOLoFlag; 2849 bool IsPIC = isPositionIndependent(); 2850 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2851 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2852 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2853 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2854 } 2855 2856 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2857 SelectionDAG &DAG) const { 2858 // FIXME: TLS addresses currently use medium model code sequences, 2859 // which is the most useful form. Eventually support for small and 2860 // large models could be added if users need it, at the cost of 2861 // additional complexity. 2862 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2863 if (DAG.getTarget().useEmulatedTLS()) 2864 return LowerToTLSEmulatedModel(GA, DAG); 2865 2866 SDLoc dl(GA); 2867 const GlobalValue *GV = GA->getGlobal(); 2868 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2869 bool is64bit = Subtarget.isPPC64(); 2870 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2871 PICLevel::Level picLevel = M->getPICLevel(); 2872 2873 const TargetMachine &TM = getTargetMachine(); 2874 TLSModel::Model Model = TM.getTLSModel(GV); 2875 2876 if (Model == TLSModel::LocalExec) { 2877 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2878 PPCII::MO_TPREL_HA); 2879 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2880 PPCII::MO_TPREL_LO); 2881 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2882 : DAG.getRegister(PPC::R2, MVT::i32); 2883 2884 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2885 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2886 } 2887 2888 if (Model == TLSModel::InitialExec) { 2889 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2890 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2891 PPCII::MO_TLS); 2892 SDValue GOTPtr; 2893 if (is64bit) { 2894 setUsesTOCBasePtr(DAG); 2895 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2896 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2897 PtrVT, GOTReg, TGA); 2898 } else { 2899 if (!TM.isPositionIndependent()) 2900 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2901 else if (picLevel == PICLevel::SmallPIC) 2902 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2903 else 2904 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2905 } 2906 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2907 PtrVT, TGA, GOTPtr); 2908 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2909 } 2910 2911 if (Model == TLSModel::GeneralDynamic) { 2912 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2913 SDValue GOTPtr; 2914 if (is64bit) { 2915 setUsesTOCBasePtr(DAG); 2916 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2917 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2918 GOTReg, TGA); 2919 } else { 2920 if (picLevel == PICLevel::SmallPIC) 2921 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2922 else 2923 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2924 } 2925 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2926 GOTPtr, TGA, TGA); 2927 } 2928 2929 if (Model == TLSModel::LocalDynamic) { 2930 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2931 SDValue GOTPtr; 2932 if (is64bit) { 2933 setUsesTOCBasePtr(DAG); 2934 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2935 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2936 GOTReg, TGA); 2937 } else { 2938 if (picLevel == PICLevel::SmallPIC) 2939 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2940 else 2941 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2942 } 2943 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2944 PtrVT, GOTPtr, TGA, TGA); 2945 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2946 PtrVT, TLSAddr, TGA); 2947 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2948 } 2949 2950 llvm_unreachable("Unknown TLS model!"); 2951 } 2952 2953 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2954 SelectionDAG &DAG) const { 2955 EVT PtrVT = Op.getValueType(); 2956 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2957 SDLoc DL(GSDN); 2958 const GlobalValue *GV = GSDN->getGlobal(); 2959 2960 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2961 // The actual address of the GlobalValue is stored in the TOC. 2962 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2963 setUsesTOCBasePtr(DAG); 2964 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2965 return getTOCEntry(DAG, DL, GA); 2966 } 2967 2968 unsigned MOHiFlag, MOLoFlag; 2969 bool IsPIC = isPositionIndependent(); 2970 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2971 2972 if (IsPIC && Subtarget.isSVR4ABI()) { 2973 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2974 GSDN->getOffset(), 2975 PPCII::MO_PIC_FLAG); 2976 return getTOCEntry(DAG, DL, GA); 2977 } 2978 2979 SDValue GAHi = 2980 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2981 SDValue GALo = 2982 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2983 2984 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2985 } 2986 2987 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2988 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2989 SDLoc dl(Op); 2990 2991 if (Op.getValueType() == MVT::v2i64) { 2992 // When the operands themselves are v2i64 values, we need to do something 2993 // special because VSX has no underlying comparison operations for these. 2994 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2995 // Equality can be handled by casting to the legal type for Altivec 2996 // comparisons, everything else needs to be expanded. 2997 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2998 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 2999 DAG.getSetCC(dl, MVT::v4i32, 3000 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3001 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3002 CC)); 3003 } 3004 3005 return SDValue(); 3006 } 3007 3008 // We handle most of these in the usual way. 3009 return Op; 3010 } 3011 3012 // If we're comparing for equality to zero, expose the fact that this is 3013 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3014 // fold the new nodes. 3015 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3016 return V; 3017 3018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3019 // Leave comparisons against 0 and -1 alone for now, since they're usually 3020 // optimized. FIXME: revisit this when we can custom lower all setcc 3021 // optimizations. 3022 if (C->isAllOnesValue() || C->isNullValue()) 3023 return SDValue(); 3024 } 3025 3026 // If we have an integer seteq/setne, turn it into a compare against zero 3027 // by xor'ing the rhs with the lhs, which is faster than setting a 3028 // condition register, reading it back out, and masking the correct bit. The 3029 // normal approach here uses sub to do this instead of xor. Using xor exposes 3030 // the result to other bit-twiddling opportunities. 3031 EVT LHSVT = Op.getOperand(0).getValueType(); 3032 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3033 EVT VT = Op.getValueType(); 3034 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3035 Op.getOperand(1)); 3036 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3037 } 3038 return SDValue(); 3039 } 3040 3041 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3042 SDNode *Node = Op.getNode(); 3043 EVT VT = Node->getValueType(0); 3044 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3045 SDValue InChain = Node->getOperand(0); 3046 SDValue VAListPtr = Node->getOperand(1); 3047 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3048 SDLoc dl(Node); 3049 3050 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3051 3052 // gpr_index 3053 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3054 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3055 InChain = GprIndex.getValue(1); 3056 3057 if (VT == MVT::i64) { 3058 // Check if GprIndex is even 3059 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3060 DAG.getConstant(1, dl, MVT::i32)); 3061 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3062 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3063 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3064 DAG.getConstant(1, dl, MVT::i32)); 3065 // Align GprIndex to be even if it isn't 3066 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3067 GprIndex); 3068 } 3069 3070 // fpr index is 1 byte after gpr 3071 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3072 DAG.getConstant(1, dl, MVT::i32)); 3073 3074 // fpr 3075 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3076 FprPtr, MachinePointerInfo(SV), MVT::i8); 3077 InChain = FprIndex.getValue(1); 3078 3079 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3080 DAG.getConstant(8, dl, MVT::i32)); 3081 3082 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3083 DAG.getConstant(4, dl, MVT::i32)); 3084 3085 // areas 3086 SDValue OverflowArea = 3087 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3088 InChain = OverflowArea.getValue(1); 3089 3090 SDValue RegSaveArea = 3091 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3092 InChain = RegSaveArea.getValue(1); 3093 3094 // select overflow_area if index > 8 3095 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3096 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3097 3098 // adjustment constant gpr_index * 4/8 3099 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3100 VT.isInteger() ? GprIndex : FprIndex, 3101 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3102 MVT::i32)); 3103 3104 // OurReg = RegSaveArea + RegConstant 3105 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3106 RegConstant); 3107 3108 // Floating types are 32 bytes into RegSaveArea 3109 if (VT.isFloatingPoint()) 3110 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3111 DAG.getConstant(32, dl, MVT::i32)); 3112 3113 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3114 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3115 VT.isInteger() ? GprIndex : FprIndex, 3116 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3117 MVT::i32)); 3118 3119 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3120 VT.isInteger() ? VAListPtr : FprPtr, 3121 MachinePointerInfo(SV), MVT::i8); 3122 3123 // determine if we should load from reg_save_area or overflow_area 3124 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3125 3126 // increase overflow_area by 4/8 if gpr/fpr > 8 3127 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3128 DAG.getConstant(VT.isInteger() ? 4 : 8, 3129 dl, MVT::i32)); 3130 3131 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3132 OverflowAreaPlusN); 3133 3134 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3135 MachinePointerInfo(), MVT::i32); 3136 3137 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3138 } 3139 3140 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3141 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3142 3143 // We have to copy the entire va_list struct: 3144 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3145 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3146 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3147 false, true, false, MachinePointerInfo(), 3148 MachinePointerInfo()); 3149 } 3150 3151 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3152 SelectionDAG &DAG) const { 3153 if (Subtarget.isAIXABI()) 3154 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3155 3156 return Op.getOperand(0); 3157 } 3158 3159 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3160 SelectionDAG &DAG) const { 3161 if (Subtarget.isAIXABI()) 3162 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3163 3164 SDValue Chain = Op.getOperand(0); 3165 SDValue Trmp = Op.getOperand(1); // trampoline 3166 SDValue FPtr = Op.getOperand(2); // nested function 3167 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3168 SDLoc dl(Op); 3169 3170 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3171 bool isPPC64 = (PtrVT == MVT::i64); 3172 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3173 3174 TargetLowering::ArgListTy Args; 3175 TargetLowering::ArgListEntry Entry; 3176 3177 Entry.Ty = IntPtrTy; 3178 Entry.Node = Trmp; Args.push_back(Entry); 3179 3180 // TrampSize == (isPPC64 ? 48 : 40); 3181 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3182 isPPC64 ? MVT::i64 : MVT::i32); 3183 Args.push_back(Entry); 3184 3185 Entry.Node = FPtr; Args.push_back(Entry); 3186 Entry.Node = Nest; Args.push_back(Entry); 3187 3188 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3189 TargetLowering::CallLoweringInfo CLI(DAG); 3190 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3191 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3192 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3193 3194 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3195 return CallResult.second; 3196 } 3197 3198 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3199 MachineFunction &MF = DAG.getMachineFunction(); 3200 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3201 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3202 3203 SDLoc dl(Op); 3204 3205 if (Subtarget.isPPC64()) { 3206 // vastart just stores the address of the VarArgsFrameIndex slot into the 3207 // memory location argument. 3208 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3209 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3210 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3211 MachinePointerInfo(SV)); 3212 } 3213 3214 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3215 // We suppose the given va_list is already allocated. 3216 // 3217 // typedef struct { 3218 // char gpr; /* index into the array of 8 GPRs 3219 // * stored in the register save area 3220 // * gpr=0 corresponds to r3, 3221 // * gpr=1 to r4, etc. 3222 // */ 3223 // char fpr; /* index into the array of 8 FPRs 3224 // * stored in the register save area 3225 // * fpr=0 corresponds to f1, 3226 // * fpr=1 to f2, etc. 3227 // */ 3228 // char *overflow_arg_area; 3229 // /* location on stack that holds 3230 // * the next overflow argument 3231 // */ 3232 // char *reg_save_area; 3233 // /* where r3:r10 and f1:f8 (if saved) 3234 // * are stored 3235 // */ 3236 // } va_list[1]; 3237 3238 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3239 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3240 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3241 PtrVT); 3242 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3243 PtrVT); 3244 3245 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3246 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3247 3248 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3249 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3250 3251 uint64_t FPROffset = 1; 3252 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3253 3254 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3255 3256 // Store first byte : number of int regs 3257 SDValue firstStore = 3258 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3259 MachinePointerInfo(SV), MVT::i8); 3260 uint64_t nextOffset = FPROffset; 3261 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3262 ConstFPROffset); 3263 3264 // Store second byte : number of float regs 3265 SDValue secondStore = 3266 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3267 MachinePointerInfo(SV, nextOffset), MVT::i8); 3268 nextOffset += StackOffset; 3269 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3270 3271 // Store second word : arguments given on stack 3272 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3273 MachinePointerInfo(SV, nextOffset)); 3274 nextOffset += FrameOffset; 3275 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3276 3277 // Store third word : arguments given in registers 3278 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3279 MachinePointerInfo(SV, nextOffset)); 3280 } 3281 3282 /// FPR - The set of FP registers that should be allocated for arguments 3283 /// on Darwin and AIX. 3284 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3285 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3286 PPC::F11, PPC::F12, PPC::F13}; 3287 3288 /// QFPR - The set of QPX registers that should be allocated for arguments. 3289 static const MCPhysReg QFPR[] = { 3290 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3291 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3292 3293 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3294 /// the stack. 3295 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3296 unsigned PtrByteSize) { 3297 unsigned ArgSize = ArgVT.getStoreSize(); 3298 if (Flags.isByVal()) 3299 ArgSize = Flags.getByValSize(); 3300 3301 // Round up to multiples of the pointer size, except for array members, 3302 // which are always packed. 3303 if (!Flags.isInConsecutiveRegs()) 3304 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3305 3306 return ArgSize; 3307 } 3308 3309 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3310 /// on the stack. 3311 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3312 ISD::ArgFlagsTy Flags, 3313 unsigned PtrByteSize) { 3314 Align Alignment(PtrByteSize); 3315 3316 // Altivec parameters are padded to a 16 byte boundary. 3317 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3318 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3319 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3320 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3321 Alignment = Align(16); 3322 // QPX vector types stored in double-precision are padded to a 32 byte 3323 // boundary. 3324 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3325 Alignment = Align(32); 3326 3327 // ByVal parameters are aligned as requested. 3328 if (Flags.isByVal()) { 3329 auto BVAlign = Flags.getNonZeroByValAlign(); 3330 if (BVAlign > PtrByteSize) { 3331 if (BVAlign.value() % PtrByteSize != 0) 3332 llvm_unreachable( 3333 "ByVal alignment is not a multiple of the pointer size"); 3334 3335 Alignment = BVAlign; 3336 } 3337 } 3338 3339 // Array members are always packed to their original alignment. 3340 if (Flags.isInConsecutiveRegs()) { 3341 // If the array member was split into multiple registers, the first 3342 // needs to be aligned to the size of the full type. (Except for 3343 // ppcf128, which is only aligned as its f64 components.) 3344 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3345 Alignment = Align(OrigVT.getStoreSize()); 3346 else 3347 Alignment = Align(ArgVT.getStoreSize()); 3348 } 3349 3350 return Alignment; 3351 } 3352 3353 /// CalculateStackSlotUsed - Return whether this argument will use its 3354 /// stack slot (instead of being passed in registers). ArgOffset, 3355 /// AvailableFPRs, and AvailableVRs must hold the current argument 3356 /// position, and will be updated to account for this argument. 3357 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3358 ISD::ArgFlagsTy Flags, 3359 unsigned PtrByteSize, 3360 unsigned LinkageSize, 3361 unsigned ParamAreaSize, 3362 unsigned &ArgOffset, 3363 unsigned &AvailableFPRs, 3364 unsigned &AvailableVRs, bool HasQPX) { 3365 bool UseMemory = false; 3366 3367 // Respect alignment of argument on the stack. 3368 Align Alignment = 3369 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3370 ArgOffset = alignTo(ArgOffset, Alignment); 3371 // If there's no space left in the argument save area, we must 3372 // use memory (this check also catches zero-sized arguments). 3373 if (ArgOffset >= LinkageSize + ParamAreaSize) 3374 UseMemory = true; 3375 3376 // Allocate argument on the stack. 3377 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3378 if (Flags.isInConsecutiveRegsLast()) 3379 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3380 // If we overran the argument save area, we must use memory 3381 // (this check catches arguments passed partially in memory) 3382 if (ArgOffset > LinkageSize + ParamAreaSize) 3383 UseMemory = true; 3384 3385 // However, if the argument is actually passed in an FPR or a VR, 3386 // we don't use memory after all. 3387 if (!Flags.isByVal()) { 3388 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3389 // QPX registers overlap with the scalar FP registers. 3390 (HasQPX && (ArgVT == MVT::v4f32 || 3391 ArgVT == MVT::v4f64 || 3392 ArgVT == MVT::v4i1))) 3393 if (AvailableFPRs > 0) { 3394 --AvailableFPRs; 3395 return false; 3396 } 3397 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3398 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3399 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3400 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3401 if (AvailableVRs > 0) { 3402 --AvailableVRs; 3403 return false; 3404 } 3405 } 3406 3407 return UseMemory; 3408 } 3409 3410 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3411 /// ensure minimum alignment required for target. 3412 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3413 unsigned NumBytes) { 3414 unsigned TargetAlign = Lowering->getStackAlignment(); 3415 unsigned AlignMask = TargetAlign - 1; 3416 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3417 return NumBytes; 3418 } 3419 3420 SDValue PPCTargetLowering::LowerFormalArguments( 3421 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3422 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3423 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3424 if (Subtarget.isAIXABI()) 3425 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3426 InVals); 3427 if (Subtarget.is64BitELFABI()) 3428 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3429 InVals); 3430 if (Subtarget.is32BitELFABI()) 3431 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3432 InVals); 3433 3434 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3435 InVals); 3436 } 3437 3438 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3439 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3440 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3441 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3442 3443 // 32-bit SVR4 ABI Stack Frame Layout: 3444 // +-----------------------------------+ 3445 // +--> | Back chain | 3446 // | +-----------------------------------+ 3447 // | | Floating-point register save area | 3448 // | +-----------------------------------+ 3449 // | | General register save area | 3450 // | +-----------------------------------+ 3451 // | | CR save word | 3452 // | +-----------------------------------+ 3453 // | | VRSAVE save word | 3454 // | +-----------------------------------+ 3455 // | | Alignment padding | 3456 // | +-----------------------------------+ 3457 // | | Vector register save area | 3458 // | +-----------------------------------+ 3459 // | | Local variable space | 3460 // | +-----------------------------------+ 3461 // | | Parameter list area | 3462 // | +-----------------------------------+ 3463 // | | LR save word | 3464 // | +-----------------------------------+ 3465 // SP--> +--- | Back chain | 3466 // +-----------------------------------+ 3467 // 3468 // Specifications: 3469 // System V Application Binary Interface PowerPC Processor Supplement 3470 // AltiVec Technology Programming Interface Manual 3471 3472 MachineFunction &MF = DAG.getMachineFunction(); 3473 MachineFrameInfo &MFI = MF.getFrameInfo(); 3474 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3475 3476 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3477 // Potential tail calls could cause overwriting of argument stack slots. 3478 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3479 (CallConv == CallingConv::Fast)); 3480 unsigned PtrByteSize = 4; 3481 3482 // Assign locations to all of the incoming arguments. 3483 SmallVector<CCValAssign, 16> ArgLocs; 3484 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3485 *DAG.getContext()); 3486 3487 // Reserve space for the linkage area on the stack. 3488 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3489 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3490 if (useSoftFloat()) 3491 CCInfo.PreAnalyzeFormalArguments(Ins); 3492 3493 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3494 CCInfo.clearWasPPCF128(); 3495 3496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3497 CCValAssign &VA = ArgLocs[i]; 3498 3499 // Arguments stored in registers. 3500 if (VA.isRegLoc()) { 3501 const TargetRegisterClass *RC; 3502 EVT ValVT = VA.getValVT(); 3503 3504 switch (ValVT.getSimpleVT().SimpleTy) { 3505 default: 3506 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3507 case MVT::i1: 3508 case MVT::i32: 3509 RC = &PPC::GPRCRegClass; 3510 break; 3511 case MVT::f32: 3512 if (Subtarget.hasP8Vector()) 3513 RC = &PPC::VSSRCRegClass; 3514 else if (Subtarget.hasSPE()) 3515 RC = &PPC::GPRCRegClass; 3516 else 3517 RC = &PPC::F4RCRegClass; 3518 break; 3519 case MVT::f64: 3520 if (Subtarget.hasVSX()) 3521 RC = &PPC::VSFRCRegClass; 3522 else if (Subtarget.hasSPE()) 3523 // SPE passes doubles in GPR pairs. 3524 RC = &PPC::GPRCRegClass; 3525 else 3526 RC = &PPC::F8RCRegClass; 3527 break; 3528 case MVT::v16i8: 3529 case MVT::v8i16: 3530 case MVT::v4i32: 3531 RC = &PPC::VRRCRegClass; 3532 break; 3533 case MVT::v4f32: 3534 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3535 break; 3536 case MVT::v2f64: 3537 case MVT::v2i64: 3538 RC = &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v4f64: 3541 RC = &PPC::QFRCRegClass; 3542 break; 3543 case MVT::v4i1: 3544 RC = &PPC::QBRCRegClass; 3545 break; 3546 } 3547 3548 SDValue ArgValue; 3549 // Transform the arguments stored in physical registers into 3550 // virtual ones. 3551 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3552 assert(i + 1 < e && "No second half of double precision argument"); 3553 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3554 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3555 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3556 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3557 if (!Subtarget.isLittleEndian()) 3558 std::swap (ArgValueLo, ArgValueHi); 3559 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3560 ArgValueHi); 3561 } else { 3562 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3563 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3564 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3565 if (ValVT == MVT::i1) 3566 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3567 } 3568 3569 InVals.push_back(ArgValue); 3570 } else { 3571 // Argument stored in memory. 3572 assert(VA.isMemLoc()); 3573 3574 // Get the extended size of the argument type in stack 3575 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3576 // Get the actual size of the argument type 3577 unsigned ObjSize = VA.getValVT().getStoreSize(); 3578 unsigned ArgOffset = VA.getLocMemOffset(); 3579 // Stack objects in PPC32 are right justified. 3580 ArgOffset += ArgSize - ObjSize; 3581 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3582 3583 // Create load nodes to retrieve arguments from the stack. 3584 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3585 InVals.push_back( 3586 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3587 } 3588 } 3589 3590 // Assign locations to all of the incoming aggregate by value arguments. 3591 // Aggregates passed by value are stored in the local variable space of the 3592 // caller's stack frame, right above the parameter list area. 3593 SmallVector<CCValAssign, 16> ByValArgLocs; 3594 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3595 ByValArgLocs, *DAG.getContext()); 3596 3597 // Reserve stack space for the allocations in CCInfo. 3598 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3599 3600 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3601 3602 // Area that is at least reserved in the caller of this function. 3603 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3604 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3605 3606 // Set the size that is at least reserved in caller of this function. Tail 3607 // call optimized function's reserved stack space needs to be aligned so that 3608 // taking the difference between two stack areas will result in an aligned 3609 // stack. 3610 MinReservedArea = 3611 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3612 FuncInfo->setMinReservedArea(MinReservedArea); 3613 3614 SmallVector<SDValue, 8> MemOps; 3615 3616 // If the function takes variable number of arguments, make a frame index for 3617 // the start of the first vararg value... for expansion of llvm.va_start. 3618 if (isVarArg) { 3619 static const MCPhysReg GPArgRegs[] = { 3620 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3621 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3622 }; 3623 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3624 3625 static const MCPhysReg FPArgRegs[] = { 3626 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3627 PPC::F8 3628 }; 3629 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3630 3631 if (useSoftFloat() || hasSPE()) 3632 NumFPArgRegs = 0; 3633 3634 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3635 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3636 3637 // Make room for NumGPArgRegs and NumFPArgRegs. 3638 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3639 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3640 3641 FuncInfo->setVarArgsStackOffset( 3642 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3643 CCInfo.getNextStackOffset(), true)); 3644 3645 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3646 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3647 3648 // The fixed integer arguments of a variadic function are stored to the 3649 // VarArgsFrameIndex on the stack so that they may be loaded by 3650 // dereferencing the result of va_next. 3651 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3652 // Get an existing live-in vreg, or add a new one. 3653 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3654 if (!VReg) 3655 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3656 3657 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3658 SDValue Store = 3659 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3660 MemOps.push_back(Store); 3661 // Increment the address by four for the next argument to store 3662 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3663 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3664 } 3665 3666 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3667 // is set. 3668 // The double arguments are stored to the VarArgsFrameIndex 3669 // on the stack. 3670 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3671 // Get an existing live-in vreg, or add a new one. 3672 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3673 if (!VReg) 3674 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3675 3676 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3677 SDValue Store = 3678 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3679 MemOps.push_back(Store); 3680 // Increment the address by eight for the next argument to store 3681 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3682 PtrVT); 3683 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3684 } 3685 } 3686 3687 if (!MemOps.empty()) 3688 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3689 3690 return Chain; 3691 } 3692 3693 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3694 // value to MVT::i64 and then truncate to the correct register size. 3695 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3696 EVT ObjectVT, SelectionDAG &DAG, 3697 SDValue ArgVal, 3698 const SDLoc &dl) const { 3699 if (Flags.isSExt()) 3700 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3701 DAG.getValueType(ObjectVT)); 3702 else if (Flags.isZExt()) 3703 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3704 DAG.getValueType(ObjectVT)); 3705 3706 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3707 } 3708 3709 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3710 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3711 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3712 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3713 // TODO: add description of PPC stack frame format, or at least some docs. 3714 // 3715 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3716 bool isLittleEndian = Subtarget.isLittleEndian(); 3717 MachineFunction &MF = DAG.getMachineFunction(); 3718 MachineFrameInfo &MFI = MF.getFrameInfo(); 3719 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3720 3721 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3722 "fastcc not supported on varargs functions"); 3723 3724 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3725 // Potential tail calls could cause overwriting of argument stack slots. 3726 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3727 (CallConv == CallingConv::Fast)); 3728 unsigned PtrByteSize = 8; 3729 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3730 3731 static const MCPhysReg GPR[] = { 3732 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3733 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3734 }; 3735 static const MCPhysReg VR[] = { 3736 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3737 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3738 }; 3739 3740 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3741 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3742 const unsigned Num_VR_Regs = array_lengthof(VR); 3743 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3744 3745 // Do a first pass over the arguments to determine whether the ABI 3746 // guarantees that our caller has allocated the parameter save area 3747 // on its stack frame. In the ELFv1 ABI, this is always the case; 3748 // in the ELFv2 ABI, it is true if this is a vararg function or if 3749 // any parameter is located in a stack slot. 3750 3751 bool HasParameterArea = !isELFv2ABI || isVarArg; 3752 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3753 unsigned NumBytes = LinkageSize; 3754 unsigned AvailableFPRs = Num_FPR_Regs; 3755 unsigned AvailableVRs = Num_VR_Regs; 3756 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3757 if (Ins[i].Flags.isNest()) 3758 continue; 3759 3760 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3761 PtrByteSize, LinkageSize, ParamAreaSize, 3762 NumBytes, AvailableFPRs, AvailableVRs, 3763 Subtarget.hasQPX())) 3764 HasParameterArea = true; 3765 } 3766 3767 // Add DAG nodes to load the arguments or copy them out of registers. On 3768 // entry to a function on PPC, the arguments start after the linkage area, 3769 // although the first ones are often in registers. 3770 3771 unsigned ArgOffset = LinkageSize; 3772 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3773 unsigned &QFPR_idx = FPR_idx; 3774 SmallVector<SDValue, 8> MemOps; 3775 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3776 unsigned CurArgIdx = 0; 3777 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3778 SDValue ArgVal; 3779 bool needsLoad = false; 3780 EVT ObjectVT = Ins[ArgNo].VT; 3781 EVT OrigVT = Ins[ArgNo].ArgVT; 3782 unsigned ObjSize = ObjectVT.getStoreSize(); 3783 unsigned ArgSize = ObjSize; 3784 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3785 if (Ins[ArgNo].isOrigArg()) { 3786 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3787 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3788 } 3789 // We re-align the argument offset for each argument, except when using the 3790 // fast calling convention, when we need to make sure we do that only when 3791 // we'll actually use a stack slot. 3792 unsigned CurArgOffset; 3793 Align Alignment; 3794 auto ComputeArgOffset = [&]() { 3795 /* Respect alignment of argument on the stack. */ 3796 Alignment = 3797 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3798 ArgOffset = alignTo(ArgOffset, Alignment); 3799 CurArgOffset = ArgOffset; 3800 }; 3801 3802 if (CallConv != CallingConv::Fast) { 3803 ComputeArgOffset(); 3804 3805 /* Compute GPR index associated with argument offset. */ 3806 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3807 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3808 } 3809 3810 // FIXME the codegen can be much improved in some cases. 3811 // We do not have to keep everything in memory. 3812 if (Flags.isByVal()) { 3813 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3814 3815 if (CallConv == CallingConv::Fast) 3816 ComputeArgOffset(); 3817 3818 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3819 ObjSize = Flags.getByValSize(); 3820 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3821 // Empty aggregate parameters do not take up registers. Examples: 3822 // struct { } a; 3823 // union { } b; 3824 // int c[0]; 3825 // etc. However, we have to provide a place-holder in InVals, so 3826 // pretend we have an 8-byte item at the current address for that 3827 // purpose. 3828 if (!ObjSize) { 3829 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3830 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3831 InVals.push_back(FIN); 3832 continue; 3833 } 3834 3835 // Create a stack object covering all stack doublewords occupied 3836 // by the argument. If the argument is (fully or partially) on 3837 // the stack, or if the argument is fully in registers but the 3838 // caller has allocated the parameter save anyway, we can refer 3839 // directly to the caller's stack frame. Otherwise, create a 3840 // local copy in our own frame. 3841 int FI; 3842 if (HasParameterArea || 3843 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3844 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3845 else 3846 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3847 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3848 3849 // Handle aggregates smaller than 8 bytes. 3850 if (ObjSize < PtrByteSize) { 3851 // The value of the object is its address, which differs from the 3852 // address of the enclosing doubleword on big-endian systems. 3853 SDValue Arg = FIN; 3854 if (!isLittleEndian) { 3855 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3856 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3857 } 3858 InVals.push_back(Arg); 3859 3860 if (GPR_idx != Num_GPR_Regs) { 3861 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3862 FuncInfo->addLiveInAttr(VReg, Flags); 3863 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3864 SDValue Store; 3865 3866 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3867 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3868 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3869 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3870 MachinePointerInfo(&*FuncArg), ObjType); 3871 } else { 3872 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3873 // store the whole register as-is to the parameter save area 3874 // slot. 3875 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3876 MachinePointerInfo(&*FuncArg)); 3877 } 3878 3879 MemOps.push_back(Store); 3880 } 3881 // Whether we copied from a register or not, advance the offset 3882 // into the parameter save area by a full doubleword. 3883 ArgOffset += PtrByteSize; 3884 continue; 3885 } 3886 3887 // The value of the object is its address, which is the address of 3888 // its first stack doubleword. 3889 InVals.push_back(FIN); 3890 3891 // Store whatever pieces of the object are in registers to memory. 3892 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3893 if (GPR_idx == Num_GPR_Regs) 3894 break; 3895 3896 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3897 FuncInfo->addLiveInAttr(VReg, Flags); 3898 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3899 SDValue Addr = FIN; 3900 if (j) { 3901 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3902 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3903 } 3904 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3905 MachinePointerInfo(&*FuncArg, j)); 3906 MemOps.push_back(Store); 3907 ++GPR_idx; 3908 } 3909 ArgOffset += ArgSize; 3910 continue; 3911 } 3912 3913 switch (ObjectVT.getSimpleVT().SimpleTy) { 3914 default: llvm_unreachable("Unhandled argument type!"); 3915 case MVT::i1: 3916 case MVT::i32: 3917 case MVT::i64: 3918 if (Flags.isNest()) { 3919 // The 'nest' parameter, if any, is passed in R11. 3920 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3921 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3922 3923 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3924 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3925 3926 break; 3927 } 3928 3929 // These can be scalar arguments or elements of an integer array type 3930 // passed directly. Clang may use those instead of "byval" aggregate 3931 // types to avoid forcing arguments to memory unnecessarily. 3932 if (GPR_idx != Num_GPR_Regs) { 3933 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3934 FuncInfo->addLiveInAttr(VReg, Flags); 3935 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3936 3937 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3938 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3939 // value to MVT::i64 and then truncate to the correct register size. 3940 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3941 } else { 3942 if (CallConv == CallingConv::Fast) 3943 ComputeArgOffset(); 3944 3945 needsLoad = true; 3946 ArgSize = PtrByteSize; 3947 } 3948 if (CallConv != CallingConv::Fast || needsLoad) 3949 ArgOffset += 8; 3950 break; 3951 3952 case MVT::f32: 3953 case MVT::f64: 3954 // These can be scalar arguments or elements of a float array type 3955 // passed directly. The latter are used to implement ELFv2 homogenous 3956 // float aggregates. 3957 if (FPR_idx != Num_FPR_Regs) { 3958 unsigned VReg; 3959 3960 if (ObjectVT == MVT::f32) 3961 VReg = MF.addLiveIn(FPR[FPR_idx], 3962 Subtarget.hasP8Vector() 3963 ? &PPC::VSSRCRegClass 3964 : &PPC::F4RCRegClass); 3965 else 3966 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3967 ? &PPC::VSFRCRegClass 3968 : &PPC::F8RCRegClass); 3969 3970 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3971 ++FPR_idx; 3972 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3973 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3974 // once we support fp <-> gpr moves. 3975 3976 // This can only ever happen in the presence of f32 array types, 3977 // since otherwise we never run out of FPRs before running out 3978 // of GPRs. 3979 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3980 FuncInfo->addLiveInAttr(VReg, Flags); 3981 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3982 3983 if (ObjectVT == MVT::f32) { 3984 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3985 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3986 DAG.getConstant(32, dl, MVT::i32)); 3987 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3988 } 3989 3990 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3991 } else { 3992 if (CallConv == CallingConv::Fast) 3993 ComputeArgOffset(); 3994 3995 needsLoad = true; 3996 } 3997 3998 // When passing an array of floats, the array occupies consecutive 3999 // space in the argument area; only round up to the next doubleword 4000 // at the end of the array. Otherwise, each float takes 8 bytes. 4001 if (CallConv != CallingConv::Fast || needsLoad) { 4002 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4003 ArgOffset += ArgSize; 4004 if (Flags.isInConsecutiveRegsLast()) 4005 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4006 } 4007 break; 4008 case MVT::v4f32: 4009 case MVT::v4i32: 4010 case MVT::v8i16: 4011 case MVT::v16i8: 4012 case MVT::v2f64: 4013 case MVT::v2i64: 4014 case MVT::v1i128: 4015 case MVT::f128: 4016 if (!Subtarget.hasQPX()) { 4017 // These can be scalar arguments or elements of a vector array type 4018 // passed directly. The latter are used to implement ELFv2 homogenous 4019 // vector aggregates. 4020 if (VR_idx != Num_VR_Regs) { 4021 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4022 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4023 ++VR_idx; 4024 } else { 4025 if (CallConv == CallingConv::Fast) 4026 ComputeArgOffset(); 4027 needsLoad = true; 4028 } 4029 if (CallConv != CallingConv::Fast || needsLoad) 4030 ArgOffset += 16; 4031 break; 4032 } // not QPX 4033 4034 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4035 "Invalid QPX parameter type"); 4036 LLVM_FALLTHROUGH; 4037 4038 case MVT::v4f64: 4039 case MVT::v4i1: 4040 // QPX vectors are treated like their scalar floating-point subregisters 4041 // (except that they're larger). 4042 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4043 if (QFPR_idx != Num_QFPR_Regs) { 4044 const TargetRegisterClass *RC; 4045 switch (ObjectVT.getSimpleVT().SimpleTy) { 4046 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4047 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4048 default: RC = &PPC::QBRCRegClass; break; 4049 } 4050 4051 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4052 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4053 ++QFPR_idx; 4054 } else { 4055 if (CallConv == CallingConv::Fast) 4056 ComputeArgOffset(); 4057 needsLoad = true; 4058 } 4059 if (CallConv != CallingConv::Fast || needsLoad) 4060 ArgOffset += Sz; 4061 break; 4062 } 4063 4064 // We need to load the argument to a virtual register if we determined 4065 // above that we ran out of physical registers of the appropriate type. 4066 if (needsLoad) { 4067 if (ObjSize < ArgSize && !isLittleEndian) 4068 CurArgOffset += ArgSize - ObjSize; 4069 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4070 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4071 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4072 } 4073 4074 InVals.push_back(ArgVal); 4075 } 4076 4077 // Area that is at least reserved in the caller of this function. 4078 unsigned MinReservedArea; 4079 if (HasParameterArea) 4080 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4081 else 4082 MinReservedArea = LinkageSize; 4083 4084 // Set the size that is at least reserved in caller of this function. Tail 4085 // call optimized functions' reserved stack space needs to be aligned so that 4086 // taking the difference between two stack areas will result in an aligned 4087 // stack. 4088 MinReservedArea = 4089 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4090 FuncInfo->setMinReservedArea(MinReservedArea); 4091 4092 // If the function takes variable number of arguments, make a frame index for 4093 // the start of the first vararg value... for expansion of llvm.va_start. 4094 if (isVarArg) { 4095 int Depth = ArgOffset; 4096 4097 FuncInfo->setVarArgsFrameIndex( 4098 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4099 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4100 4101 // If this function is vararg, store any remaining integer argument regs 4102 // to their spots on the stack so that they may be loaded by dereferencing 4103 // the result of va_next. 4104 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4105 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4106 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4107 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4108 SDValue Store = 4109 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4110 MemOps.push_back(Store); 4111 // Increment the address by four for the next argument to store 4112 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4113 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4114 } 4115 } 4116 4117 if (!MemOps.empty()) 4118 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4119 4120 return Chain; 4121 } 4122 4123 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4124 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4125 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4126 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4127 // TODO: add description of PPC stack frame format, or at least some docs. 4128 // 4129 MachineFunction &MF = DAG.getMachineFunction(); 4130 MachineFrameInfo &MFI = MF.getFrameInfo(); 4131 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4132 4133 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4134 bool isPPC64 = PtrVT == MVT::i64; 4135 // Potential tail calls could cause overwriting of argument stack slots. 4136 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4137 (CallConv == CallingConv::Fast)); 4138 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4139 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4140 unsigned ArgOffset = LinkageSize; 4141 // Area that is at least reserved in caller of this function. 4142 unsigned MinReservedArea = ArgOffset; 4143 4144 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4145 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4146 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4147 }; 4148 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4149 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4150 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4151 }; 4152 static const MCPhysReg VR[] = { 4153 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4154 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4155 }; 4156 4157 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4158 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4159 const unsigned Num_VR_Regs = array_lengthof( VR); 4160 4161 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4162 4163 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4164 4165 // In 32-bit non-varargs functions, the stack space for vectors is after the 4166 // stack space for non-vectors. We do not use this space unless we have 4167 // too many vectors to fit in registers, something that only occurs in 4168 // constructed examples:), but we have to walk the arglist to figure 4169 // that out...for the pathological case, compute VecArgOffset as the 4170 // start of the vector parameter area. Computing VecArgOffset is the 4171 // entire point of the following loop. 4172 unsigned VecArgOffset = ArgOffset; 4173 if (!isVarArg && !isPPC64) { 4174 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4175 ++ArgNo) { 4176 EVT ObjectVT = Ins[ArgNo].VT; 4177 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4178 4179 if (Flags.isByVal()) { 4180 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4181 unsigned ObjSize = Flags.getByValSize(); 4182 unsigned ArgSize = 4183 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4184 VecArgOffset += ArgSize; 4185 continue; 4186 } 4187 4188 switch(ObjectVT.getSimpleVT().SimpleTy) { 4189 default: llvm_unreachable("Unhandled argument type!"); 4190 case MVT::i1: 4191 case MVT::i32: 4192 case MVT::f32: 4193 VecArgOffset += 4; 4194 break; 4195 case MVT::i64: // PPC64 4196 case MVT::f64: 4197 // FIXME: We are guaranteed to be !isPPC64 at this point. 4198 // Does MVT::i64 apply? 4199 VecArgOffset += 8; 4200 break; 4201 case MVT::v4f32: 4202 case MVT::v4i32: 4203 case MVT::v8i16: 4204 case MVT::v16i8: 4205 // Nothing to do, we're only looking at Nonvector args here. 4206 break; 4207 } 4208 } 4209 } 4210 // We've found where the vector parameter area in memory is. Skip the 4211 // first 12 parameters; these don't use that memory. 4212 VecArgOffset = ((VecArgOffset+15)/16)*16; 4213 VecArgOffset += 12*16; 4214 4215 // Add DAG nodes to load the arguments or copy them out of registers. On 4216 // entry to a function on PPC, the arguments start after the linkage area, 4217 // although the first ones are often in registers. 4218 4219 SmallVector<SDValue, 8> MemOps; 4220 unsigned nAltivecParamsAtEnd = 0; 4221 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4222 unsigned CurArgIdx = 0; 4223 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4224 SDValue ArgVal; 4225 bool needsLoad = false; 4226 EVT ObjectVT = Ins[ArgNo].VT; 4227 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4228 unsigned ArgSize = ObjSize; 4229 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4230 if (Ins[ArgNo].isOrigArg()) { 4231 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4232 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4233 } 4234 unsigned CurArgOffset = ArgOffset; 4235 4236 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4237 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4238 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4239 if (isVarArg || isPPC64) { 4240 MinReservedArea = ((MinReservedArea+15)/16)*16; 4241 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4242 Flags, 4243 PtrByteSize); 4244 } else nAltivecParamsAtEnd++; 4245 } else 4246 // Calculate min reserved area. 4247 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4248 Flags, 4249 PtrByteSize); 4250 4251 // FIXME the codegen can be much improved in some cases. 4252 // We do not have to keep everything in memory. 4253 if (Flags.isByVal()) { 4254 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4255 4256 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4257 ObjSize = Flags.getByValSize(); 4258 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4259 // Objects of size 1 and 2 are right justified, everything else is 4260 // left justified. This means the memory address is adjusted forwards. 4261 if (ObjSize==1 || ObjSize==2) { 4262 CurArgOffset = CurArgOffset + (4 - ObjSize); 4263 } 4264 // The value of the object is its address. 4265 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4266 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4267 InVals.push_back(FIN); 4268 if (ObjSize==1 || ObjSize==2) { 4269 if (GPR_idx != Num_GPR_Regs) { 4270 unsigned VReg; 4271 if (isPPC64) 4272 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4273 else 4274 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4275 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4276 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4277 SDValue Store = 4278 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4279 MachinePointerInfo(&*FuncArg), ObjType); 4280 MemOps.push_back(Store); 4281 ++GPR_idx; 4282 } 4283 4284 ArgOffset += PtrByteSize; 4285 4286 continue; 4287 } 4288 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4289 // Store whatever pieces of the object are in registers 4290 // to memory. ArgOffset will be the address of the beginning 4291 // of the object. 4292 if (GPR_idx != Num_GPR_Regs) { 4293 unsigned VReg; 4294 if (isPPC64) 4295 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4296 else 4297 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4298 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4299 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4300 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4301 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4302 MachinePointerInfo(&*FuncArg, j)); 4303 MemOps.push_back(Store); 4304 ++GPR_idx; 4305 ArgOffset += PtrByteSize; 4306 } else { 4307 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4308 break; 4309 } 4310 } 4311 continue; 4312 } 4313 4314 switch (ObjectVT.getSimpleVT().SimpleTy) { 4315 default: llvm_unreachable("Unhandled argument type!"); 4316 case MVT::i1: 4317 case MVT::i32: 4318 if (!isPPC64) { 4319 if (GPR_idx != Num_GPR_Regs) { 4320 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4321 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4322 4323 if (ObjectVT == MVT::i1) 4324 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4325 4326 ++GPR_idx; 4327 } else { 4328 needsLoad = true; 4329 ArgSize = PtrByteSize; 4330 } 4331 // All int arguments reserve stack space in the Darwin ABI. 4332 ArgOffset += PtrByteSize; 4333 break; 4334 } 4335 LLVM_FALLTHROUGH; 4336 case MVT::i64: // PPC64 4337 if (GPR_idx != Num_GPR_Regs) { 4338 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4339 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4340 4341 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4342 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4343 // value to MVT::i64 and then truncate to the correct register size. 4344 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4345 4346 ++GPR_idx; 4347 } else { 4348 needsLoad = true; 4349 ArgSize = PtrByteSize; 4350 } 4351 // All int arguments reserve stack space in the Darwin ABI. 4352 ArgOffset += 8; 4353 break; 4354 4355 case MVT::f32: 4356 case MVT::f64: 4357 // Every 4 bytes of argument space consumes one of the GPRs available for 4358 // argument passing. 4359 if (GPR_idx != Num_GPR_Regs) { 4360 ++GPR_idx; 4361 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4362 ++GPR_idx; 4363 } 4364 if (FPR_idx != Num_FPR_Regs) { 4365 unsigned VReg; 4366 4367 if (ObjectVT == MVT::f32) 4368 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4369 else 4370 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4371 4372 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4373 ++FPR_idx; 4374 } else { 4375 needsLoad = true; 4376 } 4377 4378 // All FP arguments reserve stack space in the Darwin ABI. 4379 ArgOffset += isPPC64 ? 8 : ObjSize; 4380 break; 4381 case MVT::v4f32: 4382 case MVT::v4i32: 4383 case MVT::v8i16: 4384 case MVT::v16i8: 4385 // Note that vector arguments in registers don't reserve stack space, 4386 // except in varargs functions. 4387 if (VR_idx != Num_VR_Regs) { 4388 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4389 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4390 if (isVarArg) { 4391 while ((ArgOffset % 16) != 0) { 4392 ArgOffset += PtrByteSize; 4393 if (GPR_idx != Num_GPR_Regs) 4394 GPR_idx++; 4395 } 4396 ArgOffset += 16; 4397 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4398 } 4399 ++VR_idx; 4400 } else { 4401 if (!isVarArg && !isPPC64) { 4402 // Vectors go after all the nonvectors. 4403 CurArgOffset = VecArgOffset; 4404 VecArgOffset += 16; 4405 } else { 4406 // Vectors are aligned. 4407 ArgOffset = ((ArgOffset+15)/16)*16; 4408 CurArgOffset = ArgOffset; 4409 ArgOffset += 16; 4410 } 4411 needsLoad = true; 4412 } 4413 break; 4414 } 4415 4416 // We need to load the argument to a virtual register if we determined above 4417 // that we ran out of physical registers of the appropriate type. 4418 if (needsLoad) { 4419 int FI = MFI.CreateFixedObject(ObjSize, 4420 CurArgOffset + (ArgSize - ObjSize), 4421 isImmutable); 4422 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4423 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4424 } 4425 4426 InVals.push_back(ArgVal); 4427 } 4428 4429 // Allow for Altivec parameters at the end, if needed. 4430 if (nAltivecParamsAtEnd) { 4431 MinReservedArea = ((MinReservedArea+15)/16)*16; 4432 MinReservedArea += 16*nAltivecParamsAtEnd; 4433 } 4434 4435 // Area that is at least reserved in the caller of this function. 4436 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4437 4438 // Set the size that is at least reserved in caller of this function. Tail 4439 // call optimized functions' reserved stack space needs to be aligned so that 4440 // taking the difference between two stack areas will result in an aligned 4441 // stack. 4442 MinReservedArea = 4443 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4444 FuncInfo->setMinReservedArea(MinReservedArea); 4445 4446 // If the function takes variable number of arguments, make a frame index for 4447 // the start of the first vararg value... for expansion of llvm.va_start. 4448 if (isVarArg) { 4449 int Depth = ArgOffset; 4450 4451 FuncInfo->setVarArgsFrameIndex( 4452 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4453 Depth, true)); 4454 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4455 4456 // If this function is vararg, store any remaining integer argument regs 4457 // to their spots on the stack so that they may be loaded by dereferencing 4458 // the result of va_next. 4459 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4460 unsigned VReg; 4461 4462 if (isPPC64) 4463 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4464 else 4465 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4466 4467 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4468 SDValue Store = 4469 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4470 MemOps.push_back(Store); 4471 // Increment the address by four for the next argument to store 4472 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4473 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4474 } 4475 } 4476 4477 if (!MemOps.empty()) 4478 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4479 4480 return Chain; 4481 } 4482 4483 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4484 /// adjusted to accommodate the arguments for the tailcall. 4485 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4486 unsigned ParamSize) { 4487 4488 if (!isTailCall) return 0; 4489 4490 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4491 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4492 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4493 // Remember only if the new adjustment is bigger. 4494 if (SPDiff < FI->getTailCallSPDelta()) 4495 FI->setTailCallSPDelta(SPDiff); 4496 4497 return SPDiff; 4498 } 4499 4500 static bool isFunctionGlobalAddress(SDValue Callee); 4501 4502 static bool 4503 callsShareTOCBase(const Function *Caller, SDValue Callee, 4504 const TargetMachine &TM) { 4505 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4506 // don't have enough information to determine if the caller and calle share 4507 // the same TOC base, so we have to pessimistically assume they don't for 4508 // correctness. 4509 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4510 if (!G) 4511 return false; 4512 4513 const GlobalValue *GV = G->getGlobal(); 4514 // The medium and large code models are expected to provide a sufficiently 4515 // large TOC to provide all data addressing needs of a module with a 4516 // single TOC. Since each module will be addressed with a single TOC then we 4517 // only need to check that caller and callee don't cross dso boundaries. 4518 if (CodeModel::Medium == TM.getCodeModel() || 4519 CodeModel::Large == TM.getCodeModel()) 4520 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4521 4522 // Otherwise we need to ensure callee and caller are in the same section, 4523 // since the linker may allocate multiple TOCs, and we don't know which 4524 // sections will belong to the same TOC base. 4525 4526 if (!GV->isStrongDefinitionForLinker()) 4527 return false; 4528 4529 // Any explicitly-specified sections and section prefixes must also match. 4530 // Also, if we're using -ffunction-sections, then each function is always in 4531 // a different section (the same is true for COMDAT functions). 4532 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4533 GV->getSection() != Caller->getSection()) 4534 return false; 4535 if (const auto *F = dyn_cast<Function>(GV)) { 4536 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4537 return false; 4538 } 4539 4540 // If the callee might be interposed, then we can't assume the ultimate call 4541 // target will be in the same section. Even in cases where we can assume that 4542 // interposition won't happen, in any case where the linker might insert a 4543 // stub to allow for interposition, we must generate code as though 4544 // interposition might occur. To understand why this matters, consider a 4545 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4546 // in the same section, but a is in a different module (i.e. has a different 4547 // TOC base pointer). If the linker allows for interposition between b and c, 4548 // then it will generate a stub for the call edge between b and c which will 4549 // save the TOC pointer into the designated stack slot allocated by b. If we 4550 // return true here, and therefore allow a tail call between b and c, that 4551 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4552 // pointer into the stack slot allocated by a (where the a -> b stub saved 4553 // a's TOC base pointer). If we're not considering a tail call, but rather, 4554 // whether a nop is needed after the call instruction in b, because the linker 4555 // will insert a stub, it might complain about a missing nop if we omit it 4556 // (although many don't complain in this case). 4557 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4558 return false; 4559 4560 return true; 4561 } 4562 4563 static bool 4564 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4565 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4566 assert(Subtarget.is64BitELFABI()); 4567 4568 const unsigned PtrByteSize = 8; 4569 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4570 4571 static const MCPhysReg GPR[] = { 4572 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4573 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4574 }; 4575 static const MCPhysReg VR[] = { 4576 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4577 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4578 }; 4579 4580 const unsigned NumGPRs = array_lengthof(GPR); 4581 const unsigned NumFPRs = 13; 4582 const unsigned NumVRs = array_lengthof(VR); 4583 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4584 4585 unsigned NumBytes = LinkageSize; 4586 unsigned AvailableFPRs = NumFPRs; 4587 unsigned AvailableVRs = NumVRs; 4588 4589 for (const ISD::OutputArg& Param : Outs) { 4590 if (Param.Flags.isNest()) continue; 4591 4592 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4593 PtrByteSize, LinkageSize, ParamAreaSize, 4594 NumBytes, AvailableFPRs, AvailableVRs, 4595 Subtarget.hasQPX())) 4596 return true; 4597 } 4598 return false; 4599 } 4600 4601 static bool 4602 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4603 if (CS.arg_size() != CallerFn->arg_size()) 4604 return false; 4605 4606 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4607 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4608 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4609 4610 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4611 const Value* CalleeArg = *CalleeArgIter; 4612 const Value* CallerArg = &(*CallerArgIter); 4613 if (CalleeArg == CallerArg) 4614 continue; 4615 4616 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4617 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4618 // } 4619 // 1st argument of callee is undef and has the same type as caller. 4620 if (CalleeArg->getType() == CallerArg->getType() && 4621 isa<UndefValue>(CalleeArg)) 4622 continue; 4623 4624 return false; 4625 } 4626 4627 return true; 4628 } 4629 4630 // Returns true if TCO is possible between the callers and callees 4631 // calling conventions. 4632 static bool 4633 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4634 CallingConv::ID CalleeCC) { 4635 // Tail calls are possible with fastcc and ccc. 4636 auto isTailCallableCC = [] (CallingConv::ID CC){ 4637 return CC == CallingConv::C || CC == CallingConv::Fast; 4638 }; 4639 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4640 return false; 4641 4642 // We can safely tail call both fastcc and ccc callees from a c calling 4643 // convention caller. If the caller is fastcc, we may have less stack space 4644 // than a non-fastcc caller with the same signature so disable tail-calls in 4645 // that case. 4646 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4647 } 4648 4649 bool 4650 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4651 SDValue Callee, 4652 CallingConv::ID CalleeCC, 4653 ImmutableCallSite CS, 4654 bool isVarArg, 4655 const SmallVectorImpl<ISD::OutputArg> &Outs, 4656 const SmallVectorImpl<ISD::InputArg> &Ins, 4657 SelectionDAG& DAG) const { 4658 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4659 4660 if (DisableSCO && !TailCallOpt) return false; 4661 4662 // Variadic argument functions are not supported. 4663 if (isVarArg) return false; 4664 4665 auto &Caller = DAG.getMachineFunction().getFunction(); 4666 // Check that the calling conventions are compatible for tco. 4667 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4668 return false; 4669 4670 // Caller contains any byval parameter is not supported. 4671 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4672 return false; 4673 4674 // Callee contains any byval parameter is not supported, too. 4675 // Note: This is a quick work around, because in some cases, e.g. 4676 // caller's stack size > callee's stack size, we are still able to apply 4677 // sibling call optimization. For example, gcc is able to do SCO for caller1 4678 // in the following example, but not for caller2. 4679 // struct test { 4680 // long int a; 4681 // char ary[56]; 4682 // } gTest; 4683 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4684 // b->a = v.a; 4685 // return 0; 4686 // } 4687 // void caller1(struct test a, struct test c, struct test *b) { 4688 // callee(gTest, b); } 4689 // void caller2(struct test *b) { callee(gTest, b); } 4690 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4691 return false; 4692 4693 // If callee and caller use different calling conventions, we cannot pass 4694 // parameters on stack since offsets for the parameter area may be different. 4695 if (Caller.getCallingConv() != CalleeCC && 4696 needStackSlotPassParameters(Subtarget, Outs)) 4697 return false; 4698 4699 // No TCO/SCO on indirect call because Caller have to restore its TOC 4700 if (!isFunctionGlobalAddress(Callee) && 4701 !isa<ExternalSymbolSDNode>(Callee)) 4702 return false; 4703 4704 // If the caller and callee potentially have different TOC bases then we 4705 // cannot tail call since we need to restore the TOC pointer after the call. 4706 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4707 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4708 return false; 4709 4710 // TCO allows altering callee ABI, so we don't have to check further. 4711 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4712 return true; 4713 4714 if (DisableSCO) return false; 4715 4716 // If callee use the same argument list that caller is using, then we can 4717 // apply SCO on this case. If it is not, then we need to check if callee needs 4718 // stack for passing arguments. 4719 if (!hasSameArgumentList(&Caller, CS) && 4720 needStackSlotPassParameters(Subtarget, Outs)) { 4721 return false; 4722 } 4723 4724 return true; 4725 } 4726 4727 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4728 /// for tail call optimization. Targets which want to do tail call 4729 /// optimization should implement this function. 4730 bool 4731 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4732 CallingConv::ID CalleeCC, 4733 bool isVarArg, 4734 const SmallVectorImpl<ISD::InputArg> &Ins, 4735 SelectionDAG& DAG) const { 4736 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4737 return false; 4738 4739 // Variable argument functions are not supported. 4740 if (isVarArg) 4741 return false; 4742 4743 MachineFunction &MF = DAG.getMachineFunction(); 4744 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4745 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4746 // Functions containing by val parameters are not supported. 4747 for (unsigned i = 0; i != Ins.size(); i++) { 4748 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4749 if (Flags.isByVal()) return false; 4750 } 4751 4752 // Non-PIC/GOT tail calls are supported. 4753 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4754 return true; 4755 4756 // At the moment we can only do local tail calls (in same module, hidden 4757 // or protected) if we are generating PIC. 4758 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4759 return G->getGlobal()->hasHiddenVisibility() 4760 || G->getGlobal()->hasProtectedVisibility(); 4761 } 4762 4763 return false; 4764 } 4765 4766 /// isCallCompatibleAddress - Return the immediate to use if the specified 4767 /// 32-bit value is representable in the immediate field of a BxA instruction. 4768 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4769 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4770 if (!C) return nullptr; 4771 4772 int Addr = C->getZExtValue(); 4773 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4774 SignExtend32<26>(Addr) != Addr) 4775 return nullptr; // Top 6 bits have to be sext of immediate. 4776 4777 return DAG 4778 .getConstant( 4779 (int)C->getZExtValue() >> 2, SDLoc(Op), 4780 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4781 .getNode(); 4782 } 4783 4784 namespace { 4785 4786 struct TailCallArgumentInfo { 4787 SDValue Arg; 4788 SDValue FrameIdxOp; 4789 int FrameIdx = 0; 4790 4791 TailCallArgumentInfo() = default; 4792 }; 4793 4794 } // end anonymous namespace 4795 4796 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4797 static void StoreTailCallArgumentsToStackSlot( 4798 SelectionDAG &DAG, SDValue Chain, 4799 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4800 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4801 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4802 SDValue Arg = TailCallArgs[i].Arg; 4803 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4804 int FI = TailCallArgs[i].FrameIdx; 4805 // Store relative to framepointer. 4806 MemOpChains.push_back(DAG.getStore( 4807 Chain, dl, Arg, FIN, 4808 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4809 } 4810 } 4811 4812 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4813 /// the appropriate stack slot for the tail call optimized function call. 4814 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4815 SDValue OldRetAddr, SDValue OldFP, 4816 int SPDiff, const SDLoc &dl) { 4817 if (SPDiff) { 4818 // Calculate the new stack slot for the return address. 4819 MachineFunction &MF = DAG.getMachineFunction(); 4820 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4821 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4822 bool isPPC64 = Subtarget.isPPC64(); 4823 int SlotSize = isPPC64 ? 8 : 4; 4824 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4825 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4826 NewRetAddrLoc, true); 4827 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4828 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4829 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4830 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4831 } 4832 return Chain; 4833 } 4834 4835 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4836 /// the position of the argument. 4837 static void 4838 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4839 SDValue Arg, int SPDiff, unsigned ArgOffset, 4840 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4841 int Offset = ArgOffset + SPDiff; 4842 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4843 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4844 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4845 SDValue FIN = DAG.getFrameIndex(FI, VT); 4846 TailCallArgumentInfo Info; 4847 Info.Arg = Arg; 4848 Info.FrameIdxOp = FIN; 4849 Info.FrameIdx = FI; 4850 TailCallArguments.push_back(Info); 4851 } 4852 4853 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4854 /// stack slot. Returns the chain as result and the loaded frame pointers in 4855 /// LROpOut/FPOpout. Used when tail calling. 4856 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4857 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4858 SDValue &FPOpOut, const SDLoc &dl) const { 4859 if (SPDiff) { 4860 // Load the LR and FP stack slot for later adjusting. 4861 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4862 LROpOut = getReturnAddrFrameIndex(DAG); 4863 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4864 Chain = SDValue(LROpOut.getNode(), 1); 4865 } 4866 return Chain; 4867 } 4868 4869 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4870 /// by "Src" to address "Dst" of size "Size". Alignment information is 4871 /// specified by the specific parameter attribute. The copy will be passed as 4872 /// a byval function parameter. 4873 /// Sometimes what we are copying is the end of a larger object, the part that 4874 /// does not fit in registers. 4875 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4876 SDValue Chain, ISD::ArgFlagsTy Flags, 4877 SelectionDAG &DAG, const SDLoc &dl) { 4878 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4879 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4880 Flags.getNonZeroByValAlign(), false, false, false, 4881 MachinePointerInfo(), MachinePointerInfo()); 4882 } 4883 4884 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4885 /// tail calls. 4886 static void LowerMemOpCallTo( 4887 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4888 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4889 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4890 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4891 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4892 if (!isTailCall) { 4893 if (isVector) { 4894 SDValue StackPtr; 4895 if (isPPC64) 4896 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4897 else 4898 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4899 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4900 DAG.getConstant(ArgOffset, dl, PtrVT)); 4901 } 4902 MemOpChains.push_back( 4903 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4904 // Calculate and remember argument location. 4905 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4906 TailCallArguments); 4907 } 4908 4909 static void 4910 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4911 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4912 SDValue FPOp, 4913 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4914 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4915 // might overwrite each other in case of tail call optimization. 4916 SmallVector<SDValue, 8> MemOpChains2; 4917 // Do not flag preceding copytoreg stuff together with the following stuff. 4918 InFlag = SDValue(); 4919 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4920 MemOpChains2, dl); 4921 if (!MemOpChains2.empty()) 4922 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4923 4924 // Store the return address to the appropriate stack slot. 4925 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4926 4927 // Emit callseq_end just before tailcall node. 4928 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4929 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4930 InFlag = Chain.getValue(1); 4931 } 4932 4933 // Is this global address that of a function that can be called by name? (as 4934 // opposed to something that must hold a descriptor for an indirect call). 4935 static bool isFunctionGlobalAddress(SDValue Callee) { 4936 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4937 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4938 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4939 return false; 4940 4941 return G->getGlobal()->getValueType()->isFunctionTy(); 4942 } 4943 4944 return false; 4945 } 4946 4947 SDValue PPCTargetLowering::LowerCallResult( 4948 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4949 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4950 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4951 SmallVector<CCValAssign, 16> RVLocs; 4952 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4953 *DAG.getContext()); 4954 4955 CCRetInfo.AnalyzeCallResult( 4956 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4957 ? RetCC_PPC_Cold 4958 : RetCC_PPC); 4959 4960 // Copy all of the result registers out of their specified physreg. 4961 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4962 CCValAssign &VA = RVLocs[i]; 4963 assert(VA.isRegLoc() && "Can only return in registers!"); 4964 4965 SDValue Val; 4966 4967 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4968 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4969 InFlag); 4970 Chain = Lo.getValue(1); 4971 InFlag = Lo.getValue(2); 4972 VA = RVLocs[++i]; // skip ahead to next loc 4973 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4974 InFlag); 4975 Chain = Hi.getValue(1); 4976 InFlag = Hi.getValue(2); 4977 if (!Subtarget.isLittleEndian()) 4978 std::swap (Lo, Hi); 4979 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4980 } else { 4981 Val = DAG.getCopyFromReg(Chain, dl, 4982 VA.getLocReg(), VA.getLocVT(), InFlag); 4983 Chain = Val.getValue(1); 4984 InFlag = Val.getValue(2); 4985 } 4986 4987 switch (VA.getLocInfo()) { 4988 default: llvm_unreachable("Unknown loc info!"); 4989 case CCValAssign::Full: break; 4990 case CCValAssign::AExt: 4991 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4992 break; 4993 case CCValAssign::ZExt: 4994 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4995 DAG.getValueType(VA.getValVT())); 4996 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4997 break; 4998 case CCValAssign::SExt: 4999 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5000 DAG.getValueType(VA.getValVT())); 5001 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5002 break; 5003 } 5004 5005 InVals.push_back(Val); 5006 } 5007 5008 return Chain; 5009 } 5010 5011 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5012 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5013 // PatchPoint calls are not indirect. 5014 if (isPatchPoint) 5015 return false; 5016 5017 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5018 return false; 5019 5020 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5021 // becuase the immediate function pointer points to a descriptor instead of 5022 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5023 // pointer immediate points to the global entry point, while the BLA would 5024 // need to jump to the local entry point (see rL211174). 5025 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5026 isBLACompatibleAddress(Callee, DAG)) 5027 return false; 5028 5029 return true; 5030 } 5031 5032 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5033 const Function &Caller, 5034 const SDValue &Callee, 5035 const PPCSubtarget &Subtarget, 5036 const TargetMachine &TM) { 5037 if (CFlags.IsTailCall) 5038 return PPCISD::TC_RETURN; 5039 5040 // This is a call through a function pointer. 5041 if (CFlags.IsIndirect) { 5042 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5043 // indirect calls. The save of the caller's TOC pointer to the stack will be 5044 // inserted into the DAG as part of call lowering. The restore of the TOC 5045 // pointer is modeled by using a pseudo instruction for the call opcode that 5046 // represents the 2 instruction sequence of an indirect branch and link, 5047 // immediately followed by a load of the TOC pointer from the the stack save 5048 // slot into gpr2. 5049 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5050 return PPCISD::BCTRL_LOAD_TOC; 5051 5052 // An indirect call that does not need a TOC restore. 5053 return PPCISD::BCTRL; 5054 } 5055 5056 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5057 // immediately following the call instruction if the caller and callee may 5058 // have different TOC bases. At link time if the linker determines the calls 5059 // may not share a TOC base, the call is redirected to a trampoline inserted 5060 // by the linker. The trampoline will (among other things) save the callers 5061 // TOC pointer at an ABI designated offset in the linkage area and the linker 5062 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5063 // into gpr2. 5064 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5065 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5066 : PPCISD::CALL_NOP; 5067 5068 return PPCISD::CALL; 5069 } 5070 5071 static bool isValidAIXExternalSymSDNode(StringRef SymName) { 5072 return StringSwitch<bool>(SymName) 5073 .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf", 5074 "__moddi3", "__udivdi3", "__umoddi3", true) 5075 .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true) 5076 .Default(false); 5077 } 5078 5079 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5080 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5081 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5082 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5083 return SDValue(Dest, 0); 5084 5085 // Returns true if the callee is local, and false otherwise. 5086 auto isLocalCallee = [&]() { 5087 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5088 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5089 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5090 5091 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5092 !dyn_cast_or_null<GlobalIFunc>(GV); 5093 }; 5094 5095 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5096 // a static relocation model causes some versions of GNU LD (2.17.50, at 5097 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5098 // built with secure-PLT. 5099 bool UsePlt = 5100 Subtarget.is32BitELFABI() && !isLocalCallee() && 5101 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5102 5103 // On AIX, direct function calls reference the symbol for the function's 5104 // entry point, which is named by prepending a "." before the function's 5105 // C-linkage name. 5106 const auto getAIXFuncEntryPointSymbolSDNode = 5107 [&](StringRef FuncName, bool IsDeclaration, 5108 const XCOFF::StorageClass &SC) { 5109 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5110 5111 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5112 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5113 5114 if (IsDeclaration && !S->hasContainingCsect()) { 5115 // On AIX, an undefined symbol needs to be associated with a 5116 // MCSectionXCOFF to get the correct storage mapping class. 5117 // In this case, XCOFF::XMC_PR. 5118 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5119 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5120 SectionKind::getMetadata()); 5121 S->setContainingCsect(Sec); 5122 } 5123 5124 MVT PtrVT = 5125 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5126 return DAG.getMCSymbol(S, PtrVT); 5127 }; 5128 5129 if (isFunctionGlobalAddress(Callee)) { 5130 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5131 const GlobalValue *GV = G->getGlobal(); 5132 5133 if (!Subtarget.isAIXABI()) 5134 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5135 UsePlt ? PPCII::MO_PLT : 0); 5136 5137 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5138 const GlobalObject *GO = cast<GlobalObject>(GV); 5139 const XCOFF::StorageClass SC = 5140 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5141 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5142 SC); 5143 } 5144 5145 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5146 const char *SymName = S->getSymbol(); 5147 if (!Subtarget.isAIXABI()) 5148 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5149 UsePlt ? PPCII::MO_PLT : 0); 5150 5151 // If there exists a user-declared function whose name is the same as the 5152 // ExternalSymbol's, then we pick up the user-declared version. 5153 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5154 if (const Function *F = 5155 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5156 const XCOFF::StorageClass SC = 5157 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5158 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5159 SC); 5160 } 5161 5162 // TODO: Remove this when the support for ExternalSymbolSDNode is complete. 5163 if (isValidAIXExternalSymSDNode(SymName)) { 5164 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5165 } 5166 5167 report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName)); 5168 } 5169 5170 // No transformation needed. 5171 assert(Callee.getNode() && "What no callee?"); 5172 return Callee; 5173 } 5174 5175 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5176 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5177 "Expected a CALLSEQ_STARTSDNode."); 5178 5179 // The last operand is the chain, except when the node has glue. If the node 5180 // has glue, then the last operand is the glue, and the chain is the second 5181 // last operand. 5182 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5183 if (LastValue.getValueType() != MVT::Glue) 5184 return LastValue; 5185 5186 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5187 } 5188 5189 // Creates the node that moves a functions address into the count register 5190 // to prepare for an indirect call instruction. 5191 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5192 SDValue &Glue, SDValue &Chain, 5193 const SDLoc &dl) { 5194 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5195 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5196 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5197 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5198 // The glue is the second value produced. 5199 Glue = Chain.getValue(1); 5200 } 5201 5202 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5203 SDValue &Glue, SDValue &Chain, 5204 SDValue CallSeqStart, 5205 ImmutableCallSite CS, const SDLoc &dl, 5206 bool hasNest, 5207 const PPCSubtarget &Subtarget) { 5208 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5209 // entry point, but to the function descriptor (the function entry point 5210 // address is part of the function descriptor though). 5211 // The function descriptor is a three doubleword structure with the 5212 // following fields: function entry point, TOC base address and 5213 // environment pointer. 5214 // Thus for a call through a function pointer, the following actions need 5215 // to be performed: 5216 // 1. Save the TOC of the caller in the TOC save area of its stack 5217 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5218 // 2. Load the address of the function entry point from the function 5219 // descriptor. 5220 // 3. Load the TOC of the callee from the function descriptor into r2. 5221 // 4. Load the environment pointer from the function descriptor into 5222 // r11. 5223 // 5. Branch to the function entry point address. 5224 // 6. On return of the callee, the TOC of the caller needs to be 5225 // restored (this is done in FinishCall()). 5226 // 5227 // The loads are scheduled at the beginning of the call sequence, and the 5228 // register copies are flagged together to ensure that no other 5229 // operations can be scheduled in between. E.g. without flagging the 5230 // copies together, a TOC access in the caller could be scheduled between 5231 // the assignment of the callee TOC and the branch to the callee, which leads 5232 // to incorrect code. 5233 5234 // Start by loading the function address from the descriptor. 5235 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5236 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5237 ? (MachineMemOperand::MODereferenceable | 5238 MachineMemOperand::MOInvariant) 5239 : MachineMemOperand::MONone; 5240 5241 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5242 5243 // Registers used in building the DAG. 5244 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5245 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5246 5247 // Offsets of descriptor members. 5248 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5249 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5250 5251 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5252 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5253 5254 // One load for the functions entry point address. 5255 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5256 Alignment, MMOFlags); 5257 5258 // One for loading the TOC anchor for the module that contains the called 5259 // function. 5260 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5261 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5262 SDValue TOCPtr = 5263 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5264 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5265 5266 // One for loading the environment pointer. 5267 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5268 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5269 SDValue LoadEnvPtr = 5270 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5271 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5272 5273 5274 // Then copy the newly loaded TOC anchor to the TOC pointer. 5275 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5276 Chain = TOCVal.getValue(0); 5277 Glue = TOCVal.getValue(1); 5278 5279 // If the function call has an explicit 'nest' parameter, it takes the 5280 // place of the environment pointer. 5281 assert((!hasNest || !Subtarget.isAIXABI()) && 5282 "Nest parameter is not supported on AIX."); 5283 if (!hasNest) { 5284 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5285 Chain = EnvVal.getValue(0); 5286 Glue = EnvVal.getValue(1); 5287 } 5288 5289 // The rest of the indirect call sequence is the same as the non-descriptor 5290 // DAG. 5291 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5292 } 5293 5294 static void 5295 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5296 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5297 SelectionDAG &DAG, 5298 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5299 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5300 const PPCSubtarget &Subtarget) { 5301 const bool IsPPC64 = Subtarget.isPPC64(); 5302 // MVT for a general purpose register. 5303 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5304 5305 // First operand is always the chain. 5306 Ops.push_back(Chain); 5307 5308 // If it's a direct call pass the callee as the second operand. 5309 if (!CFlags.IsIndirect) 5310 Ops.push_back(Callee); 5311 else { 5312 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5313 5314 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5315 // on the stack (this would have been done in `LowerCall_64SVR4` or 5316 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5317 // represents both the indirect branch and a load that restores the TOC 5318 // pointer from the linkage area. The operand for the TOC restore is an add 5319 // of the TOC save offset to the stack pointer. This must be the second 5320 // operand: after the chain input but before any other variadic arguments. 5321 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5322 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5323 5324 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5325 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5326 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5327 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5328 Ops.push_back(AddTOC); 5329 } 5330 5331 // Add the register used for the environment pointer. 5332 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5333 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5334 RegVT)); 5335 5336 5337 // Add CTR register as callee so a bctr can be emitted later. 5338 if (CFlags.IsTailCall) 5339 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5340 } 5341 5342 // If this is a tail call add stack pointer delta. 5343 if (CFlags.IsTailCall) 5344 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5345 5346 // Add argument registers to the end of the list so that they are known live 5347 // into the call. 5348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5349 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5350 RegsToPass[i].second.getValueType())); 5351 5352 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5353 // no way to mark dependencies as implicit here. 5354 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5355 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5356 !CFlags.IsPatchPoint) 5357 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5358 5359 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5360 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5361 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5362 5363 // Add a register mask operand representing the call-preserved registers. 5364 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5365 const uint32_t *Mask = 5366 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5367 assert(Mask && "Missing call preserved mask for calling convention"); 5368 Ops.push_back(DAG.getRegisterMask(Mask)); 5369 5370 // If the glue is valid, it is the last operand. 5371 if (Glue.getNode()) 5372 Ops.push_back(Glue); 5373 } 5374 5375 SDValue PPCTargetLowering::FinishCall( 5376 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5377 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5378 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5379 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5380 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5381 5382 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5383 setUsesTOCBasePtr(DAG); 5384 5385 unsigned CallOpc = 5386 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5387 Subtarget, DAG.getTarget()); 5388 5389 if (!CFlags.IsIndirect) 5390 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5391 else if (Subtarget.usesFunctionDescriptors()) 5392 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5393 dl, CFlags.HasNest, Subtarget); 5394 else 5395 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5396 5397 // Build the operand list for the call instruction. 5398 SmallVector<SDValue, 8> Ops; 5399 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5400 SPDiff, Subtarget); 5401 5402 // Emit tail call. 5403 if (CFlags.IsTailCall) { 5404 assert(((Callee.getOpcode() == ISD::Register && 5405 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5406 Callee.getOpcode() == ISD::TargetExternalSymbol || 5407 Callee.getOpcode() == ISD::TargetGlobalAddress || 5408 isa<ConstantSDNode>(Callee)) && 5409 "Expecting a global address, external symbol, absolute value or " 5410 "register"); 5411 assert(CallOpc == PPCISD::TC_RETURN && 5412 "Unexpected call opcode for a tail call."); 5413 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5414 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5415 } 5416 5417 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5418 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5419 Glue = Chain.getValue(1); 5420 5421 // When performing tail call optimization the callee pops its arguments off 5422 // the stack. Account for this here so these bytes can be pushed back on in 5423 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5424 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5425 getTargetMachine().Options.GuaranteedTailCallOpt) 5426 ? NumBytes 5427 : 0; 5428 5429 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5430 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5431 Glue, dl); 5432 Glue = Chain.getValue(1); 5433 5434 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5435 DAG, InVals); 5436 } 5437 5438 SDValue 5439 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5440 SmallVectorImpl<SDValue> &InVals) const { 5441 SelectionDAG &DAG = CLI.DAG; 5442 SDLoc &dl = CLI.DL; 5443 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5444 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5445 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5446 SDValue Chain = CLI.Chain; 5447 SDValue Callee = CLI.Callee; 5448 bool &isTailCall = CLI.IsTailCall; 5449 CallingConv::ID CallConv = CLI.CallConv; 5450 bool isVarArg = CLI.IsVarArg; 5451 bool isPatchPoint = CLI.IsPatchPoint; 5452 ImmutableCallSite CS = CLI.CS; 5453 5454 if (isTailCall) { 5455 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5456 isTailCall = false; 5457 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5458 isTailCall = 5459 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5460 isVarArg, Outs, Ins, DAG); 5461 else 5462 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5463 Ins, DAG); 5464 if (isTailCall) { 5465 ++NumTailCalls; 5466 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5467 ++NumSiblingCalls; 5468 5469 assert(isa<GlobalAddressSDNode>(Callee) && 5470 "Callee should be an llvm::Function object."); 5471 LLVM_DEBUG( 5472 const GlobalValue *GV = 5473 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5474 const unsigned Width = 5475 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5476 dbgs() << "TCO caller: " 5477 << left_justify(DAG.getMachineFunction().getName(), Width) 5478 << ", callee linkage: " << GV->getVisibility() << ", " 5479 << GV->getLinkage() << "\n"); 5480 } 5481 } 5482 5483 if (!isTailCall && CS && CS.isMustTailCall()) 5484 report_fatal_error("failed to perform tail call elimination on a call " 5485 "site marked musttail"); 5486 5487 // When long calls (i.e. indirect calls) are always used, calls are always 5488 // made via function pointer. If we have a function name, first translate it 5489 // into a pointer. 5490 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5491 !isTailCall) 5492 Callee = LowerGlobalAddress(Callee, DAG); 5493 5494 CallFlags CFlags( 5495 CallConv, isTailCall, isVarArg, isPatchPoint, 5496 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5497 // hasNest 5498 Subtarget.is64BitELFABI() && 5499 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5500 5501 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5502 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5503 InVals, CS); 5504 5505 if (Subtarget.isSVR4ABI()) 5506 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5507 InVals, CS); 5508 5509 if (Subtarget.isAIXABI()) 5510 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5511 InVals, CS); 5512 5513 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5514 InVals, CS); 5515 } 5516 5517 SDValue PPCTargetLowering::LowerCall_32SVR4( 5518 SDValue Chain, SDValue Callee, CallFlags CFlags, 5519 const SmallVectorImpl<ISD::OutputArg> &Outs, 5520 const SmallVectorImpl<SDValue> &OutVals, 5521 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5522 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5523 ImmutableCallSite CS) const { 5524 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5525 // of the 32-bit SVR4 ABI stack frame layout. 5526 5527 const CallingConv::ID CallConv = CFlags.CallConv; 5528 const bool IsVarArg = CFlags.IsVarArg; 5529 const bool IsTailCall = CFlags.IsTailCall; 5530 5531 assert((CallConv == CallingConv::C || 5532 CallConv == CallingConv::Cold || 5533 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5534 5535 unsigned PtrByteSize = 4; 5536 5537 MachineFunction &MF = DAG.getMachineFunction(); 5538 5539 // Mark this function as potentially containing a function that contains a 5540 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5541 // and restoring the callers stack pointer in this functions epilog. This is 5542 // done because by tail calling the called function might overwrite the value 5543 // in this function's (MF) stack pointer stack slot 0(SP). 5544 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5545 CallConv == CallingConv::Fast) 5546 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5547 5548 // Count how many bytes are to be pushed on the stack, including the linkage 5549 // area, parameter list area and the part of the local variable space which 5550 // contains copies of aggregates which are passed by value. 5551 5552 // Assign locations to all of the outgoing arguments. 5553 SmallVector<CCValAssign, 16> ArgLocs; 5554 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5555 5556 // Reserve space for the linkage area on the stack. 5557 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5558 PtrByteSize); 5559 if (useSoftFloat()) 5560 CCInfo.PreAnalyzeCallOperands(Outs); 5561 5562 if (IsVarArg) { 5563 // Handle fixed and variable vector arguments differently. 5564 // Fixed vector arguments go into registers as long as registers are 5565 // available. Variable vector arguments always go into memory. 5566 unsigned NumArgs = Outs.size(); 5567 5568 for (unsigned i = 0; i != NumArgs; ++i) { 5569 MVT ArgVT = Outs[i].VT; 5570 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5571 bool Result; 5572 5573 if (Outs[i].IsFixed) { 5574 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5575 CCInfo); 5576 } else { 5577 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5578 ArgFlags, CCInfo); 5579 } 5580 5581 if (Result) { 5582 #ifndef NDEBUG 5583 errs() << "Call operand #" << i << " has unhandled type " 5584 << EVT(ArgVT).getEVTString() << "\n"; 5585 #endif 5586 llvm_unreachable(nullptr); 5587 } 5588 } 5589 } else { 5590 // All arguments are treated the same. 5591 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5592 } 5593 CCInfo.clearWasPPCF128(); 5594 5595 // Assign locations to all of the outgoing aggregate by value arguments. 5596 SmallVector<CCValAssign, 16> ByValArgLocs; 5597 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5598 5599 // Reserve stack space for the allocations in CCInfo. 5600 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5601 5602 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5603 5604 // Size of the linkage area, parameter list area and the part of the local 5605 // space variable where copies of aggregates which are passed by value are 5606 // stored. 5607 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5608 5609 // Calculate by how many bytes the stack has to be adjusted in case of tail 5610 // call optimization. 5611 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5612 5613 // Adjust the stack pointer for the new arguments... 5614 // These operations are automatically eliminated by the prolog/epilog pass 5615 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5616 SDValue CallSeqStart = Chain; 5617 5618 // Load the return address and frame pointer so it can be moved somewhere else 5619 // later. 5620 SDValue LROp, FPOp; 5621 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5622 5623 // Set up a copy of the stack pointer for use loading and storing any 5624 // arguments that may not fit in the registers available for argument 5625 // passing. 5626 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5627 5628 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5629 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5630 SmallVector<SDValue, 8> MemOpChains; 5631 5632 bool seenFloatArg = false; 5633 // Walk the register/memloc assignments, inserting copies/loads. 5634 // i - Tracks the index into the list of registers allocated for the call 5635 // RealArgIdx - Tracks the index into the list of actual function arguments 5636 // j - Tracks the index into the list of byval arguments 5637 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5638 i != e; 5639 ++i, ++RealArgIdx) { 5640 CCValAssign &VA = ArgLocs[i]; 5641 SDValue Arg = OutVals[RealArgIdx]; 5642 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5643 5644 if (Flags.isByVal()) { 5645 // Argument is an aggregate which is passed by value, thus we need to 5646 // create a copy of it in the local variable space of the current stack 5647 // frame (which is the stack frame of the caller) and pass the address of 5648 // this copy to the callee. 5649 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5650 CCValAssign &ByValVA = ByValArgLocs[j++]; 5651 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5652 5653 // Memory reserved in the local variable space of the callers stack frame. 5654 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5655 5656 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5657 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5658 StackPtr, PtrOff); 5659 5660 // Create a copy of the argument in the local area of the current 5661 // stack frame. 5662 SDValue MemcpyCall = 5663 CreateCopyOfByValArgument(Arg, PtrOff, 5664 CallSeqStart.getNode()->getOperand(0), 5665 Flags, DAG, dl); 5666 5667 // This must go outside the CALLSEQ_START..END. 5668 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5669 SDLoc(MemcpyCall)); 5670 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5671 NewCallSeqStart.getNode()); 5672 Chain = CallSeqStart = NewCallSeqStart; 5673 5674 // Pass the address of the aggregate copy on the stack either in a 5675 // physical register or in the parameter list area of the current stack 5676 // frame to the callee. 5677 Arg = PtrOff; 5678 } 5679 5680 // When useCRBits() is true, there can be i1 arguments. 5681 // It is because getRegisterType(MVT::i1) => MVT::i1, 5682 // and for other integer types getRegisterType() => MVT::i32. 5683 // Extend i1 and ensure callee will get i32. 5684 if (Arg.getValueType() == MVT::i1) 5685 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5686 dl, MVT::i32, Arg); 5687 5688 if (VA.isRegLoc()) { 5689 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5690 // Put argument in a physical register. 5691 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5692 bool IsLE = Subtarget.isLittleEndian(); 5693 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5694 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5695 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5696 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5697 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5698 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5699 SVal.getValue(0))); 5700 } else 5701 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5702 } else { 5703 // Put argument in the parameter list area of the current stack frame. 5704 assert(VA.isMemLoc()); 5705 unsigned LocMemOffset = VA.getLocMemOffset(); 5706 5707 if (!IsTailCall) { 5708 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5709 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5710 StackPtr, PtrOff); 5711 5712 MemOpChains.push_back( 5713 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5714 } else { 5715 // Calculate and remember argument location. 5716 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5717 TailCallArguments); 5718 } 5719 } 5720 } 5721 5722 if (!MemOpChains.empty()) 5723 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5724 5725 // Build a sequence of copy-to-reg nodes chained together with token chain 5726 // and flag operands which copy the outgoing args into the appropriate regs. 5727 SDValue InFlag; 5728 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5729 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5730 RegsToPass[i].second, InFlag); 5731 InFlag = Chain.getValue(1); 5732 } 5733 5734 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5735 // registers. 5736 if (IsVarArg) { 5737 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5738 SDValue Ops[] = { Chain, InFlag }; 5739 5740 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5741 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5742 5743 InFlag = Chain.getValue(1); 5744 } 5745 5746 if (IsTailCall) 5747 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5748 TailCallArguments); 5749 5750 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5751 Callee, SPDiff, NumBytes, Ins, InVals, CS); 5752 } 5753 5754 // Copy an argument into memory, being careful to do this outside the 5755 // call sequence for the call to which the argument belongs. 5756 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5757 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5758 SelectionDAG &DAG, const SDLoc &dl) const { 5759 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5760 CallSeqStart.getNode()->getOperand(0), 5761 Flags, DAG, dl); 5762 // The MEMCPY must go outside the CALLSEQ_START..END. 5763 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5764 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5765 SDLoc(MemcpyCall)); 5766 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5767 NewCallSeqStart.getNode()); 5768 return NewCallSeqStart; 5769 } 5770 5771 SDValue PPCTargetLowering::LowerCall_64SVR4( 5772 SDValue Chain, SDValue Callee, CallFlags CFlags, 5773 const SmallVectorImpl<ISD::OutputArg> &Outs, 5774 const SmallVectorImpl<SDValue> &OutVals, 5775 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5776 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5777 ImmutableCallSite CS) const { 5778 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5779 bool isLittleEndian = Subtarget.isLittleEndian(); 5780 unsigned NumOps = Outs.size(); 5781 bool IsSibCall = false; 5782 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5783 5784 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5785 unsigned PtrByteSize = 8; 5786 5787 MachineFunction &MF = DAG.getMachineFunction(); 5788 5789 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5790 IsSibCall = true; 5791 5792 // Mark this function as potentially containing a function that contains a 5793 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5794 // and restoring the callers stack pointer in this functions epilog. This is 5795 // done because by tail calling the called function might overwrite the value 5796 // in this function's (MF) stack pointer stack slot 0(SP). 5797 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5798 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5799 5800 assert(!(IsFastCall && CFlags.IsVarArg) && 5801 "fastcc not supported on varargs functions"); 5802 5803 // Count how many bytes are to be pushed on the stack, including the linkage 5804 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5805 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5806 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5807 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5808 unsigned NumBytes = LinkageSize; 5809 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5810 unsigned &QFPR_idx = FPR_idx; 5811 5812 static const MCPhysReg GPR[] = { 5813 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5814 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5815 }; 5816 static const MCPhysReg VR[] = { 5817 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5818 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5819 }; 5820 5821 const unsigned NumGPRs = array_lengthof(GPR); 5822 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5823 const unsigned NumVRs = array_lengthof(VR); 5824 const unsigned NumQFPRs = NumFPRs; 5825 5826 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5827 // can be passed to the callee in registers. 5828 // For the fast calling convention, there is another check below. 5829 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5830 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5831 if (!HasParameterArea) { 5832 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5833 unsigned AvailableFPRs = NumFPRs; 5834 unsigned AvailableVRs = NumVRs; 5835 unsigned NumBytesTmp = NumBytes; 5836 for (unsigned i = 0; i != NumOps; ++i) { 5837 if (Outs[i].Flags.isNest()) continue; 5838 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5839 PtrByteSize, LinkageSize, ParamAreaSize, 5840 NumBytesTmp, AvailableFPRs, AvailableVRs, 5841 Subtarget.hasQPX())) 5842 HasParameterArea = true; 5843 } 5844 } 5845 5846 // When using the fast calling convention, we don't provide backing for 5847 // arguments that will be in registers. 5848 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5849 5850 // Avoid allocating parameter area for fastcc functions if all the arguments 5851 // can be passed in the registers. 5852 if (IsFastCall) 5853 HasParameterArea = false; 5854 5855 // Add up all the space actually used. 5856 for (unsigned i = 0; i != NumOps; ++i) { 5857 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5858 EVT ArgVT = Outs[i].VT; 5859 EVT OrigVT = Outs[i].ArgVT; 5860 5861 if (Flags.isNest()) 5862 continue; 5863 5864 if (IsFastCall) { 5865 if (Flags.isByVal()) { 5866 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5867 if (NumGPRsUsed > NumGPRs) 5868 HasParameterArea = true; 5869 } else { 5870 switch (ArgVT.getSimpleVT().SimpleTy) { 5871 default: llvm_unreachable("Unexpected ValueType for argument!"); 5872 case MVT::i1: 5873 case MVT::i32: 5874 case MVT::i64: 5875 if (++NumGPRsUsed <= NumGPRs) 5876 continue; 5877 break; 5878 case MVT::v4i32: 5879 case MVT::v8i16: 5880 case MVT::v16i8: 5881 case MVT::v2f64: 5882 case MVT::v2i64: 5883 case MVT::v1i128: 5884 case MVT::f128: 5885 if (++NumVRsUsed <= NumVRs) 5886 continue; 5887 break; 5888 case MVT::v4f32: 5889 // When using QPX, this is handled like a FP register, otherwise, it 5890 // is an Altivec register. 5891 if (Subtarget.hasQPX()) { 5892 if (++NumFPRsUsed <= NumFPRs) 5893 continue; 5894 } else { 5895 if (++NumVRsUsed <= NumVRs) 5896 continue; 5897 } 5898 break; 5899 case MVT::f32: 5900 case MVT::f64: 5901 case MVT::v4f64: // QPX 5902 case MVT::v4i1: // QPX 5903 if (++NumFPRsUsed <= NumFPRs) 5904 continue; 5905 break; 5906 } 5907 HasParameterArea = true; 5908 } 5909 } 5910 5911 /* Respect alignment of argument on the stack. */ 5912 auto Alignement = 5913 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5914 NumBytes = alignTo(NumBytes, Alignement); 5915 5916 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5917 if (Flags.isInConsecutiveRegsLast()) 5918 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5919 } 5920 5921 unsigned NumBytesActuallyUsed = NumBytes; 5922 5923 // In the old ELFv1 ABI, 5924 // the prolog code of the callee may store up to 8 GPR argument registers to 5925 // the stack, allowing va_start to index over them in memory if its varargs. 5926 // Because we cannot tell if this is needed on the caller side, we have to 5927 // conservatively assume that it is needed. As such, make sure we have at 5928 // least enough stack space for the caller to store the 8 GPRs. 5929 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5930 // really requires memory operands, e.g. a vararg function. 5931 if (HasParameterArea) 5932 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5933 else 5934 NumBytes = LinkageSize; 5935 5936 // Tail call needs the stack to be aligned. 5937 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5938 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5939 5940 int SPDiff = 0; 5941 5942 // Calculate by how many bytes the stack has to be adjusted in case of tail 5943 // call optimization. 5944 if (!IsSibCall) 5945 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5946 5947 // To protect arguments on the stack from being clobbered in a tail call, 5948 // force all the loads to happen before doing any other lowering. 5949 if (CFlags.IsTailCall) 5950 Chain = DAG.getStackArgumentTokenFactor(Chain); 5951 5952 // Adjust the stack pointer for the new arguments... 5953 // These operations are automatically eliminated by the prolog/epilog pass 5954 if (!IsSibCall) 5955 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5956 SDValue CallSeqStart = Chain; 5957 5958 // Load the return address and frame pointer so it can be move somewhere else 5959 // later. 5960 SDValue LROp, FPOp; 5961 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5962 5963 // Set up a copy of the stack pointer for use loading and storing any 5964 // arguments that may not fit in the registers available for argument 5965 // passing. 5966 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5967 5968 // Figure out which arguments are going to go in registers, and which in 5969 // memory. Also, if this is a vararg function, floating point operations 5970 // must be stored to our stack, and loaded into integer regs as well, if 5971 // any integer regs are available for argument passing. 5972 unsigned ArgOffset = LinkageSize; 5973 5974 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5975 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5976 5977 SmallVector<SDValue, 8> MemOpChains; 5978 for (unsigned i = 0; i != NumOps; ++i) { 5979 SDValue Arg = OutVals[i]; 5980 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5981 EVT ArgVT = Outs[i].VT; 5982 EVT OrigVT = Outs[i].ArgVT; 5983 5984 // PtrOff will be used to store the current argument to the stack if a 5985 // register cannot be found for it. 5986 SDValue PtrOff; 5987 5988 // We re-align the argument offset for each argument, except when using the 5989 // fast calling convention, when we need to make sure we do that only when 5990 // we'll actually use a stack slot. 5991 auto ComputePtrOff = [&]() { 5992 /* Respect alignment of argument on the stack. */ 5993 auto Alignment = 5994 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5995 ArgOffset = alignTo(ArgOffset, Alignment); 5996 5997 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 5998 5999 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6000 }; 6001 6002 if (!IsFastCall) { 6003 ComputePtrOff(); 6004 6005 /* Compute GPR index associated with argument offset. */ 6006 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6007 GPR_idx = std::min(GPR_idx, NumGPRs); 6008 } 6009 6010 // Promote integers to 64-bit values. 6011 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6012 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6013 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6014 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6015 } 6016 6017 // FIXME memcpy is used way more than necessary. Correctness first. 6018 // Note: "by value" is code for passing a structure by value, not 6019 // basic types. 6020 if (Flags.isByVal()) { 6021 // Note: Size includes alignment padding, so 6022 // struct x { short a; char b; } 6023 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6024 // These are the proper values we need for right-justifying the 6025 // aggregate in a parameter register. 6026 unsigned Size = Flags.getByValSize(); 6027 6028 // An empty aggregate parameter takes up no storage and no 6029 // registers. 6030 if (Size == 0) 6031 continue; 6032 6033 if (IsFastCall) 6034 ComputePtrOff(); 6035 6036 // All aggregates smaller than 8 bytes must be passed right-justified. 6037 if (Size==1 || Size==2 || Size==4) { 6038 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6039 if (GPR_idx != NumGPRs) { 6040 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6041 MachinePointerInfo(), VT); 6042 MemOpChains.push_back(Load.getValue(1)); 6043 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6044 6045 ArgOffset += PtrByteSize; 6046 continue; 6047 } 6048 } 6049 6050 if (GPR_idx == NumGPRs && Size < 8) { 6051 SDValue AddPtr = PtrOff; 6052 if (!isLittleEndian) { 6053 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6054 PtrOff.getValueType()); 6055 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6056 } 6057 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6058 CallSeqStart, 6059 Flags, DAG, dl); 6060 ArgOffset += PtrByteSize; 6061 continue; 6062 } 6063 // Copy entire object into memory. There are cases where gcc-generated 6064 // code assumes it is there, even if it could be put entirely into 6065 // registers. (This is not what the doc says.) 6066 6067 // FIXME: The above statement is likely due to a misunderstanding of the 6068 // documents. All arguments must be copied into the parameter area BY 6069 // THE CALLEE in the event that the callee takes the address of any 6070 // formal argument. That has not yet been implemented. However, it is 6071 // reasonable to use the stack area as a staging area for the register 6072 // load. 6073 6074 // Skip this for small aggregates, as we will use the same slot for a 6075 // right-justified copy, below. 6076 if (Size >= 8) 6077 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6078 CallSeqStart, 6079 Flags, DAG, dl); 6080 6081 // When a register is available, pass a small aggregate right-justified. 6082 if (Size < 8 && GPR_idx != NumGPRs) { 6083 // The easiest way to get this right-justified in a register 6084 // is to copy the structure into the rightmost portion of a 6085 // local variable slot, then load the whole slot into the 6086 // register. 6087 // FIXME: The memcpy seems to produce pretty awful code for 6088 // small aggregates, particularly for packed ones. 6089 // FIXME: It would be preferable to use the slot in the 6090 // parameter save area instead of a new local variable. 6091 SDValue AddPtr = PtrOff; 6092 if (!isLittleEndian) { 6093 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6094 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6095 } 6096 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6097 CallSeqStart, 6098 Flags, DAG, dl); 6099 6100 // Load the slot into the register. 6101 SDValue Load = 6102 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6103 MemOpChains.push_back(Load.getValue(1)); 6104 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6105 6106 // Done with this argument. 6107 ArgOffset += PtrByteSize; 6108 continue; 6109 } 6110 6111 // For aggregates larger than PtrByteSize, copy the pieces of the 6112 // object that fit into registers from the parameter save area. 6113 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6114 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6115 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6116 if (GPR_idx != NumGPRs) { 6117 SDValue Load = 6118 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6119 MemOpChains.push_back(Load.getValue(1)); 6120 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6121 ArgOffset += PtrByteSize; 6122 } else { 6123 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6124 break; 6125 } 6126 } 6127 continue; 6128 } 6129 6130 switch (Arg.getSimpleValueType().SimpleTy) { 6131 default: llvm_unreachable("Unexpected ValueType for argument!"); 6132 case MVT::i1: 6133 case MVT::i32: 6134 case MVT::i64: 6135 if (Flags.isNest()) { 6136 // The 'nest' parameter, if any, is passed in R11. 6137 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6138 break; 6139 } 6140 6141 // These can be scalar arguments or elements of an integer array type 6142 // passed directly. Clang may use those instead of "byval" aggregate 6143 // types to avoid forcing arguments to memory unnecessarily. 6144 if (GPR_idx != NumGPRs) { 6145 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6146 } else { 6147 if (IsFastCall) 6148 ComputePtrOff(); 6149 6150 assert(HasParameterArea && 6151 "Parameter area must exist to pass an argument in memory."); 6152 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6153 true, CFlags.IsTailCall, false, MemOpChains, 6154 TailCallArguments, dl); 6155 if (IsFastCall) 6156 ArgOffset += PtrByteSize; 6157 } 6158 if (!IsFastCall) 6159 ArgOffset += PtrByteSize; 6160 break; 6161 case MVT::f32: 6162 case MVT::f64: { 6163 // These can be scalar arguments or elements of a float array type 6164 // passed directly. The latter are used to implement ELFv2 homogenous 6165 // float aggregates. 6166 6167 // Named arguments go into FPRs first, and once they overflow, the 6168 // remaining arguments go into GPRs and then the parameter save area. 6169 // Unnamed arguments for vararg functions always go to GPRs and 6170 // then the parameter save area. For now, put all arguments to vararg 6171 // routines always in both locations (FPR *and* GPR or stack slot). 6172 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6173 bool NeededLoad = false; 6174 6175 // First load the argument into the next available FPR. 6176 if (FPR_idx != NumFPRs) 6177 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6178 6179 // Next, load the argument into GPR or stack slot if needed. 6180 if (!NeedGPROrStack) 6181 ; 6182 else if (GPR_idx != NumGPRs && !IsFastCall) { 6183 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6184 // once we support fp <-> gpr moves. 6185 6186 // In the non-vararg case, this can only ever happen in the 6187 // presence of f32 array types, since otherwise we never run 6188 // out of FPRs before running out of GPRs. 6189 SDValue ArgVal; 6190 6191 // Double values are always passed in a single GPR. 6192 if (Arg.getValueType() != MVT::f32) { 6193 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6194 6195 // Non-array float values are extended and passed in a GPR. 6196 } else if (!Flags.isInConsecutiveRegs()) { 6197 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6198 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6199 6200 // If we have an array of floats, we collect every odd element 6201 // together with its predecessor into one GPR. 6202 } else if (ArgOffset % PtrByteSize != 0) { 6203 SDValue Lo, Hi; 6204 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6205 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6206 if (!isLittleEndian) 6207 std::swap(Lo, Hi); 6208 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6209 6210 // The final element, if even, goes into the first half of a GPR. 6211 } else if (Flags.isInConsecutiveRegsLast()) { 6212 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6213 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6214 if (!isLittleEndian) 6215 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6216 DAG.getConstant(32, dl, MVT::i32)); 6217 6218 // Non-final even elements are skipped; they will be handled 6219 // together the with subsequent argument on the next go-around. 6220 } else 6221 ArgVal = SDValue(); 6222 6223 if (ArgVal.getNode()) 6224 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6225 } else { 6226 if (IsFastCall) 6227 ComputePtrOff(); 6228 6229 // Single-precision floating-point values are mapped to the 6230 // second (rightmost) word of the stack doubleword. 6231 if (Arg.getValueType() == MVT::f32 && 6232 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6233 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6234 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6235 } 6236 6237 assert(HasParameterArea && 6238 "Parameter area must exist to pass an argument in memory."); 6239 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6240 true, CFlags.IsTailCall, false, MemOpChains, 6241 TailCallArguments, dl); 6242 6243 NeededLoad = true; 6244 } 6245 // When passing an array of floats, the array occupies consecutive 6246 // space in the argument area; only round up to the next doubleword 6247 // at the end of the array. Otherwise, each float takes 8 bytes. 6248 if (!IsFastCall || NeededLoad) { 6249 ArgOffset += (Arg.getValueType() == MVT::f32 && 6250 Flags.isInConsecutiveRegs()) ? 4 : 8; 6251 if (Flags.isInConsecutiveRegsLast()) 6252 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6253 } 6254 break; 6255 } 6256 case MVT::v4f32: 6257 case MVT::v4i32: 6258 case MVT::v8i16: 6259 case MVT::v16i8: 6260 case MVT::v2f64: 6261 case MVT::v2i64: 6262 case MVT::v1i128: 6263 case MVT::f128: 6264 if (!Subtarget.hasQPX()) { 6265 // These can be scalar arguments or elements of a vector array type 6266 // passed directly. The latter are used to implement ELFv2 homogenous 6267 // vector aggregates. 6268 6269 // For a varargs call, named arguments go into VRs or on the stack as 6270 // usual; unnamed arguments always go to the stack or the corresponding 6271 // GPRs when within range. For now, we always put the value in both 6272 // locations (or even all three). 6273 if (CFlags.IsVarArg) { 6274 assert(HasParameterArea && 6275 "Parameter area must exist if we have a varargs call."); 6276 // We could elide this store in the case where the object fits 6277 // entirely in R registers. Maybe later. 6278 SDValue Store = 6279 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6280 MemOpChains.push_back(Store); 6281 if (VR_idx != NumVRs) { 6282 SDValue Load = 6283 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6284 MemOpChains.push_back(Load.getValue(1)); 6285 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6286 } 6287 ArgOffset += 16; 6288 for (unsigned i=0; i<16; i+=PtrByteSize) { 6289 if (GPR_idx == NumGPRs) 6290 break; 6291 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6292 DAG.getConstant(i, dl, PtrVT)); 6293 SDValue Load = 6294 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6295 MemOpChains.push_back(Load.getValue(1)); 6296 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6297 } 6298 break; 6299 } 6300 6301 // Non-varargs Altivec params go into VRs or on the stack. 6302 if (VR_idx != NumVRs) { 6303 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6304 } else { 6305 if (IsFastCall) 6306 ComputePtrOff(); 6307 6308 assert(HasParameterArea && 6309 "Parameter area must exist to pass an argument in memory."); 6310 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6311 true, CFlags.IsTailCall, true, MemOpChains, 6312 TailCallArguments, dl); 6313 if (IsFastCall) 6314 ArgOffset += 16; 6315 } 6316 6317 if (!IsFastCall) 6318 ArgOffset += 16; 6319 break; 6320 } // not QPX 6321 6322 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6323 "Invalid QPX parameter type"); 6324 6325 LLVM_FALLTHROUGH; 6326 case MVT::v4f64: 6327 case MVT::v4i1: { 6328 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6329 if (CFlags.IsVarArg) { 6330 assert(HasParameterArea && 6331 "Parameter area must exist if we have a varargs call."); 6332 // We could elide this store in the case where the object fits 6333 // entirely in R registers. Maybe later. 6334 SDValue Store = 6335 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6336 MemOpChains.push_back(Store); 6337 if (QFPR_idx != NumQFPRs) { 6338 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6339 PtrOff, MachinePointerInfo()); 6340 MemOpChains.push_back(Load.getValue(1)); 6341 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6342 } 6343 ArgOffset += (IsF32 ? 16 : 32); 6344 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6345 if (GPR_idx == NumGPRs) 6346 break; 6347 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6348 DAG.getConstant(i, dl, PtrVT)); 6349 SDValue Load = 6350 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6351 MemOpChains.push_back(Load.getValue(1)); 6352 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6353 } 6354 break; 6355 } 6356 6357 // Non-varargs QPX params go into registers or on the stack. 6358 if (QFPR_idx != NumQFPRs) { 6359 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6360 } else { 6361 if (IsFastCall) 6362 ComputePtrOff(); 6363 6364 assert(HasParameterArea && 6365 "Parameter area must exist to pass an argument in memory."); 6366 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6367 true, CFlags.IsTailCall, true, MemOpChains, 6368 TailCallArguments, dl); 6369 if (IsFastCall) 6370 ArgOffset += (IsF32 ? 16 : 32); 6371 } 6372 6373 if (!IsFastCall) 6374 ArgOffset += (IsF32 ? 16 : 32); 6375 break; 6376 } 6377 } 6378 } 6379 6380 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6381 "mismatch in size of parameter area"); 6382 (void)NumBytesActuallyUsed; 6383 6384 if (!MemOpChains.empty()) 6385 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6386 6387 // Check if this is an indirect call (MTCTR/BCTRL). 6388 // See prepareDescriptorIndirectCall and buildCallOperands for more 6389 // information about calls through function pointers in the 64-bit SVR4 ABI. 6390 if (CFlags.IsIndirect) { 6391 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6392 // Load r2 into a virtual register and store it to the TOC save area. 6393 setUsesTOCBasePtr(DAG); 6394 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6395 // TOC save area offset. 6396 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6397 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6398 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6399 Chain = DAG.getStore( 6400 Val.getValue(1), dl, Val, AddPtr, 6401 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6402 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6403 // This does not mean the MTCTR instruction must use R12; it's easier 6404 // to model this as an extra parameter, so do that. 6405 if (isELFv2ABI && !CFlags.IsPatchPoint) 6406 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6407 } 6408 6409 // Build a sequence of copy-to-reg nodes chained together with token chain 6410 // and flag operands which copy the outgoing args into the appropriate regs. 6411 SDValue InFlag; 6412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6413 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6414 RegsToPass[i].second, InFlag); 6415 InFlag = Chain.getValue(1); 6416 } 6417 6418 if (CFlags.IsTailCall && !IsSibCall) 6419 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6420 TailCallArguments); 6421 6422 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6423 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6424 } 6425 6426 SDValue PPCTargetLowering::LowerCall_Darwin( 6427 SDValue Chain, SDValue Callee, CallFlags CFlags, 6428 const SmallVectorImpl<ISD::OutputArg> &Outs, 6429 const SmallVectorImpl<SDValue> &OutVals, 6430 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6431 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6432 ImmutableCallSite CS) const { 6433 unsigned NumOps = Outs.size(); 6434 6435 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6436 bool isPPC64 = PtrVT == MVT::i64; 6437 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6438 6439 MachineFunction &MF = DAG.getMachineFunction(); 6440 6441 // Mark this function as potentially containing a function that contains a 6442 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6443 // and restoring the callers stack pointer in this functions epilog. This is 6444 // done because by tail calling the called function might overwrite the value 6445 // in this function's (MF) stack pointer stack slot 0(SP). 6446 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6447 CFlags.CallConv == CallingConv::Fast) 6448 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6449 6450 // Count how many bytes are to be pushed on the stack, including the linkage 6451 // area, and parameter passing area. We start with 24/48 bytes, which is 6452 // prereserved space for [SP][CR][LR][3 x unused]. 6453 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6454 unsigned NumBytes = LinkageSize; 6455 6456 // Add up all the space actually used. 6457 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6458 // they all go in registers, but we must reserve stack space for them for 6459 // possible use by the caller. In varargs or 64-bit calls, parameters are 6460 // assigned stack space in order, with padding so Altivec parameters are 6461 // 16-byte aligned. 6462 unsigned nAltivecParamsAtEnd = 0; 6463 for (unsigned i = 0; i != NumOps; ++i) { 6464 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6465 EVT ArgVT = Outs[i].VT; 6466 // Varargs Altivec parameters are padded to a 16 byte boundary. 6467 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6468 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6469 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6470 if (!CFlags.IsVarArg && !isPPC64) { 6471 // Non-varargs Altivec parameters go after all the non-Altivec 6472 // parameters; handle those later so we know how much padding we need. 6473 nAltivecParamsAtEnd++; 6474 continue; 6475 } 6476 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6477 NumBytes = ((NumBytes+15)/16)*16; 6478 } 6479 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6480 } 6481 6482 // Allow for Altivec parameters at the end, if needed. 6483 if (nAltivecParamsAtEnd) { 6484 NumBytes = ((NumBytes+15)/16)*16; 6485 NumBytes += 16*nAltivecParamsAtEnd; 6486 } 6487 6488 // The prolog code of the callee may store up to 8 GPR argument registers to 6489 // the stack, allowing va_start to index over them in memory if its varargs. 6490 // Because we cannot tell if this is needed on the caller side, we have to 6491 // conservatively assume that it is needed. As such, make sure we have at 6492 // least enough stack space for the caller to store the 8 GPRs. 6493 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6494 6495 // Tail call needs the stack to be aligned. 6496 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6497 CFlags.CallConv == CallingConv::Fast) 6498 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6499 6500 // Calculate by how many bytes the stack has to be adjusted in case of tail 6501 // call optimization. 6502 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6503 6504 // To protect arguments on the stack from being clobbered in a tail call, 6505 // force all the loads to happen before doing any other lowering. 6506 if (CFlags.IsTailCall) 6507 Chain = DAG.getStackArgumentTokenFactor(Chain); 6508 6509 // Adjust the stack pointer for the new arguments... 6510 // These operations are automatically eliminated by the prolog/epilog pass 6511 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6512 SDValue CallSeqStart = Chain; 6513 6514 // Load the return address and frame pointer so it can be move somewhere else 6515 // later. 6516 SDValue LROp, FPOp; 6517 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6518 6519 // Set up a copy of the stack pointer for use loading and storing any 6520 // arguments that may not fit in the registers available for argument 6521 // passing. 6522 SDValue StackPtr; 6523 if (isPPC64) 6524 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6525 else 6526 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6527 6528 // Figure out which arguments are going to go in registers, and which in 6529 // memory. Also, if this is a vararg function, floating point operations 6530 // must be stored to our stack, and loaded into integer regs as well, if 6531 // any integer regs are available for argument passing. 6532 unsigned ArgOffset = LinkageSize; 6533 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6534 6535 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6536 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6537 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6538 }; 6539 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6540 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6541 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6542 }; 6543 static const MCPhysReg VR[] = { 6544 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6545 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6546 }; 6547 const unsigned NumGPRs = array_lengthof(GPR_32); 6548 const unsigned NumFPRs = 13; 6549 const unsigned NumVRs = array_lengthof(VR); 6550 6551 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6552 6553 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6554 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6555 6556 SmallVector<SDValue, 8> MemOpChains; 6557 for (unsigned i = 0; i != NumOps; ++i) { 6558 SDValue Arg = OutVals[i]; 6559 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6560 6561 // PtrOff will be used to store the current argument to the stack if a 6562 // register cannot be found for it. 6563 SDValue PtrOff; 6564 6565 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6566 6567 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6568 6569 // On PPC64, promote integers to 64-bit values. 6570 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6571 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6572 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6573 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6574 } 6575 6576 // FIXME memcpy is used way more than necessary. Correctness first. 6577 // Note: "by value" is code for passing a structure by value, not 6578 // basic types. 6579 if (Flags.isByVal()) { 6580 unsigned Size = Flags.getByValSize(); 6581 // Very small objects are passed right-justified. Everything else is 6582 // passed left-justified. 6583 if (Size==1 || Size==2) { 6584 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6585 if (GPR_idx != NumGPRs) { 6586 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6587 MachinePointerInfo(), VT); 6588 MemOpChains.push_back(Load.getValue(1)); 6589 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6590 6591 ArgOffset += PtrByteSize; 6592 } else { 6593 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6594 PtrOff.getValueType()); 6595 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6596 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6597 CallSeqStart, 6598 Flags, DAG, dl); 6599 ArgOffset += PtrByteSize; 6600 } 6601 continue; 6602 } 6603 // Copy entire object into memory. There are cases where gcc-generated 6604 // code assumes it is there, even if it could be put entirely into 6605 // registers. (This is not what the doc says.) 6606 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6607 CallSeqStart, 6608 Flags, DAG, dl); 6609 6610 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6611 // copy the pieces of the object that fit into registers from the 6612 // parameter save area. 6613 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6614 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6615 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6616 if (GPR_idx != NumGPRs) { 6617 SDValue Load = 6618 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6619 MemOpChains.push_back(Load.getValue(1)); 6620 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6621 ArgOffset += PtrByteSize; 6622 } else { 6623 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6624 break; 6625 } 6626 } 6627 continue; 6628 } 6629 6630 switch (Arg.getSimpleValueType().SimpleTy) { 6631 default: llvm_unreachable("Unexpected ValueType for argument!"); 6632 case MVT::i1: 6633 case MVT::i32: 6634 case MVT::i64: 6635 if (GPR_idx != NumGPRs) { 6636 if (Arg.getValueType() == MVT::i1) 6637 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6638 6639 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6640 } else { 6641 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6642 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6643 TailCallArguments, dl); 6644 } 6645 ArgOffset += PtrByteSize; 6646 break; 6647 case MVT::f32: 6648 case MVT::f64: 6649 if (FPR_idx != NumFPRs) { 6650 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6651 6652 if (CFlags.IsVarArg) { 6653 SDValue Store = 6654 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6655 MemOpChains.push_back(Store); 6656 6657 // Float varargs are always shadowed in available integer registers 6658 if (GPR_idx != NumGPRs) { 6659 SDValue Load = 6660 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6661 MemOpChains.push_back(Load.getValue(1)); 6662 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6663 } 6664 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6665 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6666 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6667 SDValue Load = 6668 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6669 MemOpChains.push_back(Load.getValue(1)); 6670 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6671 } 6672 } else { 6673 // If we have any FPRs remaining, we may also have GPRs remaining. 6674 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6675 // GPRs. 6676 if (GPR_idx != NumGPRs) 6677 ++GPR_idx; 6678 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6679 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6680 ++GPR_idx; 6681 } 6682 } else 6683 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6684 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6685 TailCallArguments, dl); 6686 if (isPPC64) 6687 ArgOffset += 8; 6688 else 6689 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6690 break; 6691 case MVT::v4f32: 6692 case MVT::v4i32: 6693 case MVT::v8i16: 6694 case MVT::v16i8: 6695 if (CFlags.IsVarArg) { 6696 // These go aligned on the stack, or in the corresponding R registers 6697 // when within range. The Darwin PPC ABI doc claims they also go in 6698 // V registers; in fact gcc does this only for arguments that are 6699 // prototyped, not for those that match the ... We do it for all 6700 // arguments, seems to work. 6701 while (ArgOffset % 16 !=0) { 6702 ArgOffset += PtrByteSize; 6703 if (GPR_idx != NumGPRs) 6704 GPR_idx++; 6705 } 6706 // We could elide this store in the case where the object fits 6707 // entirely in R registers. Maybe later. 6708 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6709 DAG.getConstant(ArgOffset, dl, PtrVT)); 6710 SDValue Store = 6711 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6712 MemOpChains.push_back(Store); 6713 if (VR_idx != NumVRs) { 6714 SDValue Load = 6715 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6716 MemOpChains.push_back(Load.getValue(1)); 6717 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6718 } 6719 ArgOffset += 16; 6720 for (unsigned i=0; i<16; i+=PtrByteSize) { 6721 if (GPR_idx == NumGPRs) 6722 break; 6723 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6724 DAG.getConstant(i, dl, PtrVT)); 6725 SDValue Load = 6726 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6727 MemOpChains.push_back(Load.getValue(1)); 6728 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6729 } 6730 break; 6731 } 6732 6733 // Non-varargs Altivec params generally go in registers, but have 6734 // stack space allocated at the end. 6735 if (VR_idx != NumVRs) { 6736 // Doesn't have GPR space allocated. 6737 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6738 } else if (nAltivecParamsAtEnd==0) { 6739 // We are emitting Altivec params in order. 6740 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6741 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6742 TailCallArguments, dl); 6743 ArgOffset += 16; 6744 } 6745 break; 6746 } 6747 } 6748 // If all Altivec parameters fit in registers, as they usually do, 6749 // they get stack space following the non-Altivec parameters. We 6750 // don't track this here because nobody below needs it. 6751 // If there are more Altivec parameters than fit in registers emit 6752 // the stores here. 6753 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6754 unsigned j = 0; 6755 // Offset is aligned; skip 1st 12 params which go in V registers. 6756 ArgOffset = ((ArgOffset+15)/16)*16; 6757 ArgOffset += 12*16; 6758 for (unsigned i = 0; i != NumOps; ++i) { 6759 SDValue Arg = OutVals[i]; 6760 EVT ArgType = Outs[i].VT; 6761 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6762 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6763 if (++j > NumVRs) { 6764 SDValue PtrOff; 6765 // We are emitting Altivec params in order. 6766 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6767 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6768 TailCallArguments, dl); 6769 ArgOffset += 16; 6770 } 6771 } 6772 } 6773 } 6774 6775 if (!MemOpChains.empty()) 6776 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6777 6778 // On Darwin, R12 must contain the address of an indirect callee. This does 6779 // not mean the MTCTR instruction must use R12; it's easier to model this as 6780 // an extra parameter, so do that. 6781 if (CFlags.IsIndirect) { 6782 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6783 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6784 PPC::R12), Callee)); 6785 } 6786 6787 // Build a sequence of copy-to-reg nodes chained together with token chain 6788 // and flag operands which copy the outgoing args into the appropriate regs. 6789 SDValue InFlag; 6790 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6791 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6792 RegsToPass[i].second, InFlag); 6793 InFlag = Chain.getValue(1); 6794 } 6795 6796 if (CFlags.IsTailCall) 6797 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6798 TailCallArguments); 6799 6800 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6801 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6802 } 6803 6804 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6805 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6806 CCState &State) { 6807 6808 if (ValVT == MVT::f128) 6809 report_fatal_error("f128 is unimplemented on AIX."); 6810 6811 if (ArgFlags.isByVal()) 6812 report_fatal_error("Passing structure by value is unimplemented."); 6813 6814 if (ArgFlags.isNest()) 6815 report_fatal_error("Nest arguments are unimplemented."); 6816 6817 if (ValVT.isVector() || LocVT.isVector()) 6818 report_fatal_error("Vector arguments are unimplemented on AIX."); 6819 6820 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6821 State.getMachineFunction().getSubtarget()); 6822 const bool IsPPC64 = Subtarget.isPPC64(); 6823 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6824 6825 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6826 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6827 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6828 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6829 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6830 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6831 6832 // Arguments always reserve parameter save area. 6833 switch (ValVT.SimpleTy) { 6834 default: 6835 report_fatal_error("Unhandled value type for argument."); 6836 case MVT::i64: 6837 // i64 arguments should have been split to i32 for PPC32. 6838 assert(IsPPC64 && "PPC32 should have split i64 values."); 6839 LLVM_FALLTHROUGH; 6840 case MVT::i1: 6841 case MVT::i32: { 6842 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 6843 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6844 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6845 // Promote integers if needed. 6846 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6847 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6848 : CCValAssign::LocInfo::ZExt; 6849 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6850 } 6851 else 6852 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6853 6854 return false; 6855 } 6856 case MVT::f32: 6857 case MVT::f64: { 6858 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6859 const unsigned StoreSize = LocVT.getStoreSize(); 6860 // Floats are always 4-byte aligned in the PSA on AIX. 6861 // This includes f64 in 64-bit mode for ABI compatibility. 6862 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6863 unsigned FReg = State.AllocateReg(FPR); 6864 if (FReg) 6865 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6866 6867 // Reserve and initialize GPRs or initialize the PSA as required. 6868 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6869 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 6870 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6871 assert(FReg && "An FPR should be available when a GPR is reserved."); 6872 if (State.isVarArg()) { 6873 // Successfully reserved GPRs are only initialized for vararg calls. 6874 // Custom handling is required for: 6875 // f64 in PPC32 needs to be split into 2 GPRs. 6876 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6877 State.addLoc( 6878 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6879 } 6880 } else { 6881 // If there are insufficient GPRs, the PSA needs to be initialized. 6882 // Initialization occurs even if an FPR was initialized for 6883 // compatibility with the AIX XL compiler. The full memory for the 6884 // argument will be initialized even if a prior word is saved in GPR. 6885 // A custom memLoc is used when the argument also passes in FPR so 6886 // that the callee handling can skip over it easily. 6887 State.addLoc( 6888 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6889 LocInfo) 6890 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6891 break; 6892 } 6893 } 6894 6895 return false; 6896 } 6897 } 6898 return true; 6899 } 6900 6901 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6902 bool IsPPC64) { 6903 assert((IsPPC64 || SVT != MVT::i64) && 6904 "i64 should have been split for 32-bit codegen."); 6905 6906 switch (SVT) { 6907 default: 6908 report_fatal_error("Unexpected value type for formal argument"); 6909 case MVT::i1: 6910 case MVT::i32: 6911 case MVT::i64: 6912 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6913 case MVT::f32: 6914 return &PPC::F4RCRegClass; 6915 case MVT::f64: 6916 return &PPC::F8RCRegClass; 6917 } 6918 } 6919 6920 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6921 SelectionDAG &DAG, SDValue ArgValue, 6922 MVT LocVT, const SDLoc &dl) { 6923 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6924 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6925 6926 if (Flags.isSExt()) 6927 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6928 DAG.getValueType(ValVT)); 6929 else if (Flags.isZExt()) 6930 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6931 DAG.getValueType(ValVT)); 6932 6933 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6934 } 6935 6936 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6937 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6938 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6939 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6940 6941 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6942 CallConv == CallingConv::Fast) && 6943 "Unexpected calling convention!"); 6944 6945 if (isVarArg) 6946 report_fatal_error("This call type is unimplemented on AIX."); 6947 6948 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6949 report_fatal_error("Tail call support is unimplemented on AIX."); 6950 6951 if (useSoftFloat()) 6952 report_fatal_error("Soft float support is unimplemented on AIX."); 6953 6954 const PPCSubtarget &Subtarget = 6955 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6956 if (Subtarget.hasQPX()) 6957 report_fatal_error("QPX support is not supported on AIX."); 6958 6959 const bool IsPPC64 = Subtarget.isPPC64(); 6960 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6961 6962 // Assign locations to all of the incoming arguments. 6963 SmallVector<CCValAssign, 16> ArgLocs; 6964 MachineFunction &MF = DAG.getMachineFunction(); 6965 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6966 6967 // Reserve space for the linkage area on the stack. 6968 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6969 // On AIX a minimum of 8 words is saved to the parameter save area. 6970 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6971 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6972 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6973 6974 for (CCValAssign &VA : ArgLocs) { 6975 6976 if (VA.isMemLoc()) { 6977 // For compatibility with the AIX XL compiler, the float args in the 6978 // parameter save area are initialized even if the argument is available 6979 // in register. The caller is required to initialize both the register 6980 // and memory, however, the callee can choose to expect it in either. The 6981 // memloc is dismissed here because the argument is retrieved from the 6982 // register. 6983 if (VA.needsCustom()) 6984 continue; 6985 report_fatal_error( 6986 "Handling of formal arguments on the stack is unimplemented!"); 6987 } 6988 6989 assert(VA.isRegLoc() && "Unexpected argument location."); 6990 6991 EVT ValVT = VA.getValVT(); 6992 MVT LocVT = VA.getLocVT(); 6993 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6994 unsigned VReg = 6995 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 6996 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 6997 if (ValVT.isScalarInteger() && 6998 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 6999 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7000 ArgValue = 7001 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7002 } 7003 InVals.push_back(ArgValue); 7004 } 7005 7006 // Area that is at least reserved in the caller of this function. 7007 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 7008 7009 // Set the size that is at least reserved in caller of this function. Tail 7010 // call optimized function's reserved stack space needs to be aligned so 7011 // that taking the difference between two stack areas will result in an 7012 // aligned stack. 7013 MinReservedArea = 7014 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 7015 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7016 FuncInfo->setMinReservedArea(MinReservedArea); 7017 7018 return Chain; 7019 } 7020 7021 SDValue PPCTargetLowering::LowerCall_AIX( 7022 SDValue Chain, SDValue Callee, CallFlags CFlags, 7023 const SmallVectorImpl<ISD::OutputArg> &Outs, 7024 const SmallVectorImpl<SDValue> &OutVals, 7025 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7026 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7027 ImmutableCallSite CS) const { 7028 7029 assert((CFlags.CallConv == CallingConv::C || 7030 CFlags.CallConv == CallingConv::Cold || 7031 CFlags.CallConv == CallingConv::Fast) && 7032 "Unexpected calling convention!"); 7033 7034 if (CFlags.IsPatchPoint) 7035 report_fatal_error("This call type is unimplemented on AIX."); 7036 7037 const PPCSubtarget& Subtarget = 7038 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7039 if (Subtarget.hasQPX()) 7040 report_fatal_error("QPX is not supported on AIX."); 7041 if (Subtarget.hasAltivec()) 7042 report_fatal_error("Altivec support is unimplemented on AIX."); 7043 7044 MachineFunction &MF = DAG.getMachineFunction(); 7045 SmallVector<CCValAssign, 16> ArgLocs; 7046 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7047 *DAG.getContext()); 7048 7049 // Reserve space for the linkage save area (LSA) on the stack. 7050 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7051 // [SP][CR][LR][2 x reserved][TOC]. 7052 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7053 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7054 const bool IsPPC64 = Subtarget.isPPC64(); 7055 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7056 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7057 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7058 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7059 7060 // The prolog code of the callee may store up to 8 GPR argument registers to 7061 // the stack, allowing va_start to index over them in memory if the callee 7062 // is variadic. 7063 // Because we cannot tell if this is needed on the caller side, we have to 7064 // conservatively assume that it is needed. As such, make sure we have at 7065 // least enough stack space for the caller to store the 8 GPRs. 7066 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7067 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7068 CCInfo.getNextStackOffset()); 7069 7070 // Adjust the stack pointer for the new arguments... 7071 // These operations are automatically eliminated by the prolog/epilog pass. 7072 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7073 SDValue CallSeqStart = Chain; 7074 7075 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7076 SmallVector<SDValue, 8> MemOpChains; 7077 7078 // Set up a copy of the stack pointer for loading and storing any 7079 // arguments that may not fit in the registers available for argument 7080 // passing. 7081 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7082 : DAG.getRegister(PPC::R1, MVT::i32); 7083 7084 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7085 CCValAssign &VA = ArgLocs[I++]; 7086 7087 SDValue Arg = OutVals[VA.getValNo()]; 7088 7089 if (!VA.isRegLoc() && !VA.isMemLoc()) 7090 report_fatal_error("Unexpected location for function call argument."); 7091 7092 if (VA.isRegLoc() && !VA.needsCustom()) { 7093 switch (VA.getLocInfo()) { 7094 default: 7095 report_fatal_error("Unexpected argument extension type."); 7096 case CCValAssign::Full: 7097 break; 7098 case CCValAssign::ZExt: 7099 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7100 break; 7101 case CCValAssign::SExt: 7102 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7103 break; 7104 } 7105 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7106 7107 continue; 7108 } 7109 7110 if (VA.isMemLoc()) { 7111 SDValue PtrOff = 7112 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7113 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7114 MemOpChains.push_back( 7115 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7116 7117 continue; 7118 } 7119 7120 // Custom handling is used for GPR initializations for vararg float 7121 // arguments. 7122 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7123 VA.getValVT().isFloatingPoint() && VA.getLocVT().isInteger() && 7124 "Unexpected register handling for calling convention."); 7125 7126 SDValue ArgAsInt = 7127 DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg); 7128 7129 if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize()) 7130 // f32 in 32-bit GPR 7131 // f64 in 64-bit GPR 7132 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7133 else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits()) 7134 // f32 in 64-bit GPR. 7135 RegsToPass.push_back(std::make_pair( 7136 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT()))); 7137 else { 7138 // f64 in two 32-bit GPRs 7139 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7140 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7141 "Unexpected custom register for argument!"); 7142 CCValAssign &GPR1 = VA; 7143 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7144 DAG.getConstant(32, dl, MVT::i8)); 7145 RegsToPass.push_back(std::make_pair( 7146 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7147 7148 if (I != E) { 7149 // If only 1 GPR was available, there will only be one custom GPR and 7150 // the argument will also pass in memory. 7151 CCValAssign &PeekArg = ArgLocs[I]; 7152 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7153 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7154 CCValAssign &GPR2 = ArgLocs[I++]; 7155 RegsToPass.push_back(std::make_pair( 7156 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7157 } 7158 } 7159 } 7160 } 7161 7162 if (!MemOpChains.empty()) 7163 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7164 7165 // For indirect calls, we need to save the TOC base to the stack for 7166 // restoration after the call. 7167 if (CFlags.IsIndirect) { 7168 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7169 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7170 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7171 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7172 const unsigned TOCSaveOffset = 7173 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7174 7175 setUsesTOCBasePtr(DAG); 7176 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7177 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7178 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7179 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7180 Chain = DAG.getStore( 7181 Val.getValue(1), dl, Val, AddPtr, 7182 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7183 } 7184 7185 // Build a sequence of copy-to-reg nodes chained together with token chain 7186 // and flag operands which copy the outgoing args into the appropriate regs. 7187 SDValue InFlag; 7188 for (auto Reg : RegsToPass) { 7189 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7190 InFlag = Chain.getValue(1); 7191 } 7192 7193 const int SPDiff = 0; 7194 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7195 Callee, SPDiff, NumBytes, Ins, InVals, CS); 7196 } 7197 7198 bool 7199 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7200 MachineFunction &MF, bool isVarArg, 7201 const SmallVectorImpl<ISD::OutputArg> &Outs, 7202 LLVMContext &Context) const { 7203 SmallVector<CCValAssign, 16> RVLocs; 7204 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7205 return CCInfo.CheckReturn( 7206 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7207 ? RetCC_PPC_Cold 7208 : RetCC_PPC); 7209 } 7210 7211 SDValue 7212 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7213 bool isVarArg, 7214 const SmallVectorImpl<ISD::OutputArg> &Outs, 7215 const SmallVectorImpl<SDValue> &OutVals, 7216 const SDLoc &dl, SelectionDAG &DAG) const { 7217 SmallVector<CCValAssign, 16> RVLocs; 7218 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7219 *DAG.getContext()); 7220 CCInfo.AnalyzeReturn(Outs, 7221 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7222 ? RetCC_PPC_Cold 7223 : RetCC_PPC); 7224 7225 SDValue Flag; 7226 SmallVector<SDValue, 4> RetOps(1, Chain); 7227 7228 // Copy the result values into the output registers. 7229 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7230 CCValAssign &VA = RVLocs[i]; 7231 assert(VA.isRegLoc() && "Can only return in registers!"); 7232 7233 SDValue Arg = OutVals[RealResIdx]; 7234 7235 switch (VA.getLocInfo()) { 7236 default: llvm_unreachable("Unknown loc info!"); 7237 case CCValAssign::Full: break; 7238 case CCValAssign::AExt: 7239 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7240 break; 7241 case CCValAssign::ZExt: 7242 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7243 break; 7244 case CCValAssign::SExt: 7245 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7246 break; 7247 } 7248 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7249 bool isLittleEndian = Subtarget.isLittleEndian(); 7250 // Legalize ret f64 -> ret 2 x i32. 7251 SDValue SVal = 7252 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7253 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7254 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7255 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7256 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7257 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7258 Flag = Chain.getValue(1); 7259 VA = RVLocs[++i]; // skip ahead to next loc 7260 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7261 } else 7262 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7263 Flag = Chain.getValue(1); 7264 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7265 } 7266 7267 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7268 const MCPhysReg *I = 7269 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7270 if (I) { 7271 for (; *I; ++I) { 7272 7273 if (PPC::G8RCRegClass.contains(*I)) 7274 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7275 else if (PPC::F8RCRegClass.contains(*I)) 7276 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7277 else if (PPC::CRRCRegClass.contains(*I)) 7278 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7279 else if (PPC::VRRCRegClass.contains(*I)) 7280 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7281 else 7282 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7283 } 7284 } 7285 7286 RetOps[0] = Chain; // Update chain. 7287 7288 // Add the flag if we have it. 7289 if (Flag.getNode()) 7290 RetOps.push_back(Flag); 7291 7292 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7293 } 7294 7295 SDValue 7296 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7297 SelectionDAG &DAG) const { 7298 SDLoc dl(Op); 7299 7300 // Get the correct type for integers. 7301 EVT IntVT = Op.getValueType(); 7302 7303 // Get the inputs. 7304 SDValue Chain = Op.getOperand(0); 7305 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7306 // Build a DYNAREAOFFSET node. 7307 SDValue Ops[2] = {Chain, FPSIdx}; 7308 SDVTList VTs = DAG.getVTList(IntVT); 7309 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7310 } 7311 7312 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7313 SelectionDAG &DAG) const { 7314 // When we pop the dynamic allocation we need to restore the SP link. 7315 SDLoc dl(Op); 7316 7317 // Get the correct type for pointers. 7318 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7319 7320 // Construct the stack pointer operand. 7321 bool isPPC64 = Subtarget.isPPC64(); 7322 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7323 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7324 7325 // Get the operands for the STACKRESTORE. 7326 SDValue Chain = Op.getOperand(0); 7327 SDValue SaveSP = Op.getOperand(1); 7328 7329 // Load the old link SP. 7330 SDValue LoadLinkSP = 7331 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7332 7333 // Restore the stack pointer. 7334 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7335 7336 // Store the old link SP. 7337 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7338 } 7339 7340 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7341 MachineFunction &MF = DAG.getMachineFunction(); 7342 bool isPPC64 = Subtarget.isPPC64(); 7343 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7344 7345 // Get current frame pointer save index. The users of this index will be 7346 // primarily DYNALLOC instructions. 7347 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7348 int RASI = FI->getReturnAddrSaveIndex(); 7349 7350 // If the frame pointer save index hasn't been defined yet. 7351 if (!RASI) { 7352 // Find out what the fix offset of the frame pointer save area. 7353 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7354 // Allocate the frame index for frame pointer save area. 7355 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7356 // Save the result. 7357 FI->setReturnAddrSaveIndex(RASI); 7358 } 7359 return DAG.getFrameIndex(RASI, PtrVT); 7360 } 7361 7362 SDValue 7363 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7364 MachineFunction &MF = DAG.getMachineFunction(); 7365 bool isPPC64 = Subtarget.isPPC64(); 7366 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7367 7368 // Get current frame pointer save index. The users of this index will be 7369 // primarily DYNALLOC instructions. 7370 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7371 int FPSI = FI->getFramePointerSaveIndex(); 7372 7373 // If the frame pointer save index hasn't been defined yet. 7374 if (!FPSI) { 7375 // Find out what the fix offset of the frame pointer save area. 7376 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7377 // Allocate the frame index for frame pointer save area. 7378 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7379 // Save the result. 7380 FI->setFramePointerSaveIndex(FPSI); 7381 } 7382 return DAG.getFrameIndex(FPSI, PtrVT); 7383 } 7384 7385 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7386 SelectionDAG &DAG) const { 7387 // Get the inputs. 7388 SDValue Chain = Op.getOperand(0); 7389 SDValue Size = Op.getOperand(1); 7390 SDLoc dl(Op); 7391 7392 // Get the correct type for pointers. 7393 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7394 // Negate the size. 7395 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7396 DAG.getConstant(0, dl, PtrVT), Size); 7397 // Construct a node for the frame pointer save index. 7398 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7399 // Build a DYNALLOC node. 7400 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7401 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7402 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7403 } 7404 7405 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7406 SelectionDAG &DAG) const { 7407 MachineFunction &MF = DAG.getMachineFunction(); 7408 7409 bool isPPC64 = Subtarget.isPPC64(); 7410 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7411 7412 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7413 return DAG.getFrameIndex(FI, PtrVT); 7414 } 7415 7416 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7417 SelectionDAG &DAG) const { 7418 SDLoc DL(Op); 7419 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7420 DAG.getVTList(MVT::i32, MVT::Other), 7421 Op.getOperand(0), Op.getOperand(1)); 7422 } 7423 7424 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7425 SelectionDAG &DAG) const { 7426 SDLoc DL(Op); 7427 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7428 Op.getOperand(0), Op.getOperand(1)); 7429 } 7430 7431 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7432 if (Op.getValueType().isVector()) 7433 return LowerVectorLoad(Op, DAG); 7434 7435 assert(Op.getValueType() == MVT::i1 && 7436 "Custom lowering only for i1 loads"); 7437 7438 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7439 7440 SDLoc dl(Op); 7441 LoadSDNode *LD = cast<LoadSDNode>(Op); 7442 7443 SDValue Chain = LD->getChain(); 7444 SDValue BasePtr = LD->getBasePtr(); 7445 MachineMemOperand *MMO = LD->getMemOperand(); 7446 7447 SDValue NewLD = 7448 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7449 BasePtr, MVT::i8, MMO); 7450 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7451 7452 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7453 return DAG.getMergeValues(Ops, dl); 7454 } 7455 7456 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7457 if (Op.getOperand(1).getValueType().isVector()) 7458 return LowerVectorStore(Op, DAG); 7459 7460 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7461 "Custom lowering only for i1 stores"); 7462 7463 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7464 7465 SDLoc dl(Op); 7466 StoreSDNode *ST = cast<StoreSDNode>(Op); 7467 7468 SDValue Chain = ST->getChain(); 7469 SDValue BasePtr = ST->getBasePtr(); 7470 SDValue Value = ST->getValue(); 7471 MachineMemOperand *MMO = ST->getMemOperand(); 7472 7473 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7474 Value); 7475 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7476 } 7477 7478 // FIXME: Remove this once the ANDI glue bug is fixed: 7479 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7480 assert(Op.getValueType() == MVT::i1 && 7481 "Custom lowering only for i1 results"); 7482 7483 SDLoc DL(Op); 7484 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7485 } 7486 7487 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7488 SelectionDAG &DAG) const { 7489 7490 // Implements a vector truncate that fits in a vector register as a shuffle. 7491 // We want to legalize vector truncates down to where the source fits in 7492 // a vector register (and target is therefore smaller than vector register 7493 // size). At that point legalization will try to custom lower the sub-legal 7494 // result and get here - where we can contain the truncate as a single target 7495 // operation. 7496 7497 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7498 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7499 // 7500 // We will implement it for big-endian ordering as this (where x denotes 7501 // undefined): 7502 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7503 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7504 // 7505 // The same operation in little-endian ordering will be: 7506 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7507 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7508 7509 assert(Op.getValueType().isVector() && "Vector type expected."); 7510 7511 SDLoc DL(Op); 7512 SDValue N1 = Op.getOperand(0); 7513 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7514 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7515 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7516 7517 EVT TrgVT = Op.getValueType(); 7518 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7519 EVT EltVT = TrgVT.getVectorElementType(); 7520 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7521 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7522 7523 // First list the elements we want to keep. 7524 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7525 SmallVector<int, 16> ShuffV; 7526 if (Subtarget.isLittleEndian()) 7527 for (unsigned i = 0; i < TrgNumElts; ++i) 7528 ShuffV.push_back(i * SizeMult); 7529 else 7530 for (unsigned i = 1; i <= TrgNumElts; ++i) 7531 ShuffV.push_back(i * SizeMult - 1); 7532 7533 // Populate the remaining elements with undefs. 7534 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7535 // ShuffV.push_back(i + WideNumElts); 7536 ShuffV.push_back(WideNumElts + 1); 7537 7538 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7539 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7540 } 7541 7542 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7543 /// possible. 7544 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7545 // Not FP? Not a fsel. 7546 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7547 !Op.getOperand(2).getValueType().isFloatingPoint()) 7548 return Op; 7549 7550 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7551 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7552 // We might be able to do better than this under some circumstances, but in 7553 // general, fsel-based lowering of select is a finite-math-only optimization. 7554 // For more information, see section F.3 of the 2.06 ISA specification. 7555 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7556 // presence of infinities. 7557 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7558 return Op; 7559 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7560 7561 EVT ResVT = Op.getValueType(); 7562 EVT CmpVT = Op.getOperand(0).getValueType(); 7563 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7564 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7565 SDLoc dl(Op); 7566 7567 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7568 switch (CC) { 7569 default: 7570 // Not a min/max but with finite math, we may still be able to use fsel. 7571 if (HasNoInfs && HasNoNaNs) 7572 break; 7573 return Op; 7574 case ISD::SETOGT: 7575 case ISD::SETGT: 7576 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7577 case ISD::SETOLT: 7578 case ISD::SETLT: 7579 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7580 } 7581 } 7582 7583 // TODO: Propagate flags from the select rather than global settings. 7584 SDNodeFlags Flags; 7585 Flags.setNoInfs(true); 7586 Flags.setNoNaNs(true); 7587 7588 // If the RHS of the comparison is a 0.0, we don't need to do the 7589 // subtraction at all. 7590 SDValue Sel1; 7591 if (isFloatingPointZero(RHS)) 7592 switch (CC) { 7593 default: break; // SETUO etc aren't handled by fsel. 7594 case ISD::SETNE: 7595 std::swap(TV, FV); 7596 LLVM_FALLTHROUGH; 7597 case ISD::SETEQ: 7598 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7599 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7600 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7601 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7602 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7603 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7604 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7605 case ISD::SETULT: 7606 case ISD::SETLT: 7607 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7608 LLVM_FALLTHROUGH; 7609 case ISD::SETOGE: 7610 case ISD::SETGE: 7611 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7612 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7613 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7614 case ISD::SETUGT: 7615 case ISD::SETGT: 7616 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7617 LLVM_FALLTHROUGH; 7618 case ISD::SETOLE: 7619 case ISD::SETLE: 7620 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7621 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7622 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7623 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7624 } 7625 7626 SDValue Cmp; 7627 switch (CC) { 7628 default: break; // SETUO etc aren't handled by fsel. 7629 case ISD::SETNE: 7630 std::swap(TV, FV); 7631 LLVM_FALLTHROUGH; 7632 case ISD::SETEQ: 7633 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7634 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7635 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7636 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7637 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7638 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7639 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7640 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7641 case ISD::SETULT: 7642 case ISD::SETLT: 7643 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7644 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7645 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7646 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7647 case ISD::SETOGE: 7648 case ISD::SETGE: 7649 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7650 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7651 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7652 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7653 case ISD::SETUGT: 7654 case ISD::SETGT: 7655 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7656 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7657 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7658 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7659 case ISD::SETOLE: 7660 case ISD::SETLE: 7661 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7662 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7663 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7664 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7665 } 7666 return Op; 7667 } 7668 7669 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7670 SelectionDAG &DAG, 7671 const SDLoc &dl) const { 7672 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7673 SDValue Src = Op.getOperand(0); 7674 if (Src.getValueType() == MVT::f32) 7675 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7676 7677 SDValue Tmp; 7678 switch (Op.getSimpleValueType().SimpleTy) { 7679 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7680 case MVT::i32: 7681 Tmp = DAG.getNode( 7682 Op.getOpcode() == ISD::FP_TO_SINT 7683 ? PPCISD::FCTIWZ 7684 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7685 dl, MVT::f64, Src); 7686 break; 7687 case MVT::i64: 7688 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7689 "i64 FP_TO_UINT is supported only with FPCVT"); 7690 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7691 PPCISD::FCTIDUZ, 7692 dl, MVT::f64, Src); 7693 break; 7694 } 7695 7696 // Convert the FP value to an int value through memory. 7697 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7698 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7699 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7700 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7701 MachinePointerInfo MPI = 7702 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7703 7704 // Emit a store to the stack slot. 7705 SDValue Chain; 7706 if (i32Stack) { 7707 MachineFunction &MF = DAG.getMachineFunction(); 7708 MachineMemOperand *MMO = 7709 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7710 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7711 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7712 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7713 } else 7714 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7715 7716 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7717 // add in a bias on big endian. 7718 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7719 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7720 DAG.getConstant(4, dl, FIPtr.getValueType())); 7721 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7722 } 7723 7724 RLI.Chain = Chain; 7725 RLI.Ptr = FIPtr; 7726 RLI.MPI = MPI; 7727 } 7728 7729 /// Custom lowers floating point to integer conversions to use 7730 /// the direct move instructions available in ISA 2.07 to avoid the 7731 /// need for load/store combinations. 7732 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7733 SelectionDAG &DAG, 7734 const SDLoc &dl) const { 7735 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7736 SDValue Src = Op.getOperand(0); 7737 7738 if (Src.getValueType() == MVT::f32) 7739 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7740 7741 SDValue Tmp; 7742 switch (Op.getSimpleValueType().SimpleTy) { 7743 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7744 case MVT::i32: 7745 Tmp = DAG.getNode( 7746 Op.getOpcode() == ISD::FP_TO_SINT 7747 ? PPCISD::FCTIWZ 7748 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7749 dl, MVT::f64, Src); 7750 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7751 break; 7752 case MVT::i64: 7753 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7754 "i64 FP_TO_UINT is supported only with FPCVT"); 7755 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7756 PPCISD::FCTIDUZ, 7757 dl, MVT::f64, Src); 7758 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7759 break; 7760 } 7761 return Tmp; 7762 } 7763 7764 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7765 const SDLoc &dl) const { 7766 7767 // FP to INT conversions are legal for f128. 7768 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7769 return Op; 7770 7771 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7772 // PPC (the libcall is not available). 7773 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7774 if (Op.getValueType() == MVT::i32) { 7775 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7776 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7777 MVT::f64, Op.getOperand(0), 7778 DAG.getIntPtrConstant(0, dl)); 7779 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7780 MVT::f64, Op.getOperand(0), 7781 DAG.getIntPtrConstant(1, dl)); 7782 7783 // Add the two halves of the long double in round-to-zero mode. 7784 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7785 7786 // Now use a smaller FP_TO_SINT. 7787 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7788 } 7789 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7790 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7791 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7792 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7793 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7794 // FIXME: generated code sucks. 7795 // TODO: Are there fast-math-flags to propagate to this FSUB? 7796 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7797 Op.getOperand(0), Tmp); 7798 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7799 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7800 DAG.getConstant(0x80000000, dl, MVT::i32)); 7801 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7802 Op.getOperand(0)); 7803 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7804 ISD::SETGE); 7805 } 7806 } 7807 7808 return SDValue(); 7809 } 7810 7811 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7812 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7813 7814 ReuseLoadInfo RLI; 7815 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7816 7817 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7818 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7819 } 7820 7821 // We're trying to insert a regular store, S, and then a load, L. If the 7822 // incoming value, O, is a load, we might just be able to have our load use the 7823 // address used by O. However, we don't know if anything else will store to 7824 // that address before we can load from it. To prevent this situation, we need 7825 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7826 // the same chain operand as O, we create a token factor from the chain results 7827 // of O and L, and we replace all uses of O's chain result with that token 7828 // factor (see spliceIntoChain below for this last part). 7829 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7830 ReuseLoadInfo &RLI, 7831 SelectionDAG &DAG, 7832 ISD::LoadExtType ET) const { 7833 SDLoc dl(Op); 7834 if (ET == ISD::NON_EXTLOAD && 7835 (Op.getOpcode() == ISD::FP_TO_UINT || 7836 Op.getOpcode() == ISD::FP_TO_SINT) && 7837 isOperationLegalOrCustom(Op.getOpcode(), 7838 Op.getOperand(0).getValueType())) { 7839 7840 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7841 return true; 7842 } 7843 7844 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7845 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7846 LD->isNonTemporal()) 7847 return false; 7848 if (LD->getMemoryVT() != MemVT) 7849 return false; 7850 7851 RLI.Ptr = LD->getBasePtr(); 7852 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7853 assert(LD->getAddressingMode() == ISD::PRE_INC && 7854 "Non-pre-inc AM on PPC?"); 7855 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7856 LD->getOffset()); 7857 } 7858 7859 RLI.Chain = LD->getChain(); 7860 RLI.MPI = LD->getPointerInfo(); 7861 RLI.IsDereferenceable = LD->isDereferenceable(); 7862 RLI.IsInvariant = LD->isInvariant(); 7863 RLI.Alignment = LD->getAlignment(); 7864 RLI.AAInfo = LD->getAAInfo(); 7865 RLI.Ranges = LD->getRanges(); 7866 7867 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7868 return true; 7869 } 7870 7871 // Given the head of the old chain, ResChain, insert a token factor containing 7872 // it and NewResChain, and make users of ResChain now be users of that token 7873 // factor. 7874 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7875 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7876 SDValue NewResChain, 7877 SelectionDAG &DAG) const { 7878 if (!ResChain) 7879 return; 7880 7881 SDLoc dl(NewResChain); 7882 7883 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7884 NewResChain, DAG.getUNDEF(MVT::Other)); 7885 assert(TF.getNode() != NewResChain.getNode() && 7886 "A new TF really is required here"); 7887 7888 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7889 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7890 } 7891 7892 /// Analyze profitability of direct move 7893 /// prefer float load to int load plus direct move 7894 /// when there is no integer use of int load 7895 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7896 SDNode *Origin = Op.getOperand(0).getNode(); 7897 if (Origin->getOpcode() != ISD::LOAD) 7898 return true; 7899 7900 // If there is no LXSIBZX/LXSIHZX, like Power8, 7901 // prefer direct move if the memory size is 1 or 2 bytes. 7902 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7903 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7904 return true; 7905 7906 for (SDNode::use_iterator UI = Origin->use_begin(), 7907 UE = Origin->use_end(); 7908 UI != UE; ++UI) { 7909 7910 // Only look at the users of the loaded value. 7911 if (UI.getUse().get().getResNo() != 0) 7912 continue; 7913 7914 if (UI->getOpcode() != ISD::SINT_TO_FP && 7915 UI->getOpcode() != ISD::UINT_TO_FP) 7916 return true; 7917 } 7918 7919 return false; 7920 } 7921 7922 /// Custom lowers integer to floating point conversions to use 7923 /// the direct move instructions available in ISA 2.07 to avoid the 7924 /// need for load/store combinations. 7925 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7926 SelectionDAG &DAG, 7927 const SDLoc &dl) const { 7928 assert((Op.getValueType() == MVT::f32 || 7929 Op.getValueType() == MVT::f64) && 7930 "Invalid floating point type as target of conversion"); 7931 assert(Subtarget.hasFPCVT() && 7932 "Int to FP conversions with direct moves require FPCVT"); 7933 SDValue FP; 7934 SDValue Src = Op.getOperand(0); 7935 bool SinglePrec = Op.getValueType() == MVT::f32; 7936 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7937 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7938 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7939 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7940 7941 if (WordInt) { 7942 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7943 dl, MVT::f64, Src); 7944 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7945 } 7946 else { 7947 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7948 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7949 } 7950 7951 return FP; 7952 } 7953 7954 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7955 7956 EVT VecVT = Vec.getValueType(); 7957 assert(VecVT.isVector() && "Expected a vector type."); 7958 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7959 7960 EVT EltVT = VecVT.getVectorElementType(); 7961 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7962 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7963 7964 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7965 SmallVector<SDValue, 16> Ops(NumConcat); 7966 Ops[0] = Vec; 7967 SDValue UndefVec = DAG.getUNDEF(VecVT); 7968 for (unsigned i = 1; i < NumConcat; ++i) 7969 Ops[i] = UndefVec; 7970 7971 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7972 } 7973 7974 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7975 const SDLoc &dl) const { 7976 7977 unsigned Opc = Op.getOpcode(); 7978 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7979 "Unexpected conversion type"); 7980 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7981 "Supports conversions to v2f64/v4f32 only."); 7982 7983 bool SignedConv = Opc == ISD::SINT_TO_FP; 7984 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7985 7986 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7987 EVT WideVT = Wide.getValueType(); 7988 unsigned WideNumElts = WideVT.getVectorNumElements(); 7989 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7990 7991 SmallVector<int, 16> ShuffV; 7992 for (unsigned i = 0; i < WideNumElts; ++i) 7993 ShuffV.push_back(i + WideNumElts); 7994 7995 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 7996 int SaveElts = FourEltRes ? 4 : 2; 7997 if (Subtarget.isLittleEndian()) 7998 for (int i = 0; i < SaveElts; i++) 7999 ShuffV[i * Stride] = i; 8000 else 8001 for (int i = 1; i <= SaveElts; i++) 8002 ShuffV[i * Stride - 1] = i - 1; 8003 8004 SDValue ShuffleSrc2 = 8005 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8006 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8007 unsigned ExtendOp = 8008 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 8009 8010 SDValue Extend; 8011 if (!Subtarget.hasP9Altivec() && SignedConv) { 8012 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8013 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8014 DAG.getValueType(Op.getOperand(0).getValueType())); 8015 } else 8016 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 8017 8018 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8019 } 8020 8021 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8022 SelectionDAG &DAG) const { 8023 SDLoc dl(Op); 8024 8025 EVT InVT = Op.getOperand(0).getValueType(); 8026 EVT OutVT = Op.getValueType(); 8027 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8028 isOperationCustom(Op.getOpcode(), InVT)) 8029 return LowerINT_TO_FPVector(Op, DAG, dl); 8030 8031 // Conversions to f128 are legal. 8032 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8033 return Op; 8034 8035 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8036 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8037 return SDValue(); 8038 8039 SDValue Value = Op.getOperand(0); 8040 // The values are now known to be -1 (false) or 1 (true). To convert this 8041 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8042 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8043 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8044 8045 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8046 8047 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8048 8049 if (Op.getValueType() != MVT::v4f64) 8050 Value = DAG.getNode(ISD::FP_ROUND, dl, 8051 Op.getValueType(), Value, 8052 DAG.getIntPtrConstant(1, dl)); 8053 return Value; 8054 } 8055 8056 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8057 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8058 return SDValue(); 8059 8060 if (Op.getOperand(0).getValueType() == MVT::i1) 8061 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8062 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8063 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8064 8065 // If we have direct moves, we can do all the conversion, skip the store/load 8066 // however, without FPCVT we can't do most conversions. 8067 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8068 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8069 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8070 8071 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8072 "UINT_TO_FP is supported only with FPCVT"); 8073 8074 // If we have FCFIDS, then use it when converting to single-precision. 8075 // Otherwise, convert to double-precision and then round. 8076 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8077 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8078 : PPCISD::FCFIDS) 8079 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8080 : PPCISD::FCFID); 8081 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8082 ? MVT::f32 8083 : MVT::f64; 8084 8085 if (Op.getOperand(0).getValueType() == MVT::i64) { 8086 SDValue SINT = Op.getOperand(0); 8087 // When converting to single-precision, we actually need to convert 8088 // to double-precision first and then round to single-precision. 8089 // To avoid double-rounding effects during that operation, we have 8090 // to prepare the input operand. Bits that might be truncated when 8091 // converting to double-precision are replaced by a bit that won't 8092 // be lost at this stage, but is below the single-precision rounding 8093 // position. 8094 // 8095 // However, if -enable-unsafe-fp-math is in effect, accept double 8096 // rounding to avoid the extra overhead. 8097 if (Op.getValueType() == MVT::f32 && 8098 !Subtarget.hasFPCVT() && 8099 !DAG.getTarget().Options.UnsafeFPMath) { 8100 8101 // Twiddle input to make sure the low 11 bits are zero. (If this 8102 // is the case, we are guaranteed the value will fit into the 53 bit 8103 // mantissa of an IEEE double-precision value without rounding.) 8104 // If any of those low 11 bits were not zero originally, make sure 8105 // bit 12 (value 2048) is set instead, so that the final rounding 8106 // to single-precision gets the correct result. 8107 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8108 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8109 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8110 Round, DAG.getConstant(2047, dl, MVT::i64)); 8111 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8112 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8113 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8114 8115 // However, we cannot use that value unconditionally: if the magnitude 8116 // of the input value is small, the bit-twiddling we did above might 8117 // end up visibly changing the output. Fortunately, in that case, we 8118 // don't need to twiddle bits since the original input will convert 8119 // exactly to double-precision floating-point already. Therefore, 8120 // construct a conditional to use the original value if the top 11 8121 // bits are all sign-bit copies, and use the rounded value computed 8122 // above otherwise. 8123 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8124 SINT, DAG.getConstant(53, dl, MVT::i32)); 8125 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8126 Cond, DAG.getConstant(1, dl, MVT::i64)); 8127 Cond = DAG.getSetCC(dl, MVT::i32, 8128 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8129 8130 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8131 } 8132 8133 ReuseLoadInfo RLI; 8134 SDValue Bits; 8135 8136 MachineFunction &MF = DAG.getMachineFunction(); 8137 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8138 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8139 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8140 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8141 } else if (Subtarget.hasLFIWAX() && 8142 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8143 MachineMemOperand *MMO = 8144 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8145 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8146 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8147 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8148 DAG.getVTList(MVT::f64, MVT::Other), 8149 Ops, MVT::i32, MMO); 8150 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8151 } else if (Subtarget.hasFPCVT() && 8152 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8153 MachineMemOperand *MMO = 8154 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8155 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8156 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8157 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8158 DAG.getVTList(MVT::f64, MVT::Other), 8159 Ops, MVT::i32, MMO); 8160 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8161 } else if (((Subtarget.hasLFIWAX() && 8162 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8163 (Subtarget.hasFPCVT() && 8164 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8165 SINT.getOperand(0).getValueType() == MVT::i32) { 8166 MachineFrameInfo &MFI = MF.getFrameInfo(); 8167 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8168 8169 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8170 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8171 8172 SDValue Store = 8173 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8174 MachinePointerInfo::getFixedStack( 8175 DAG.getMachineFunction(), FrameIdx)); 8176 8177 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8178 "Expected an i32 store"); 8179 8180 RLI.Ptr = FIdx; 8181 RLI.Chain = Store; 8182 RLI.MPI = 8183 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8184 RLI.Alignment = 4; 8185 8186 MachineMemOperand *MMO = 8187 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8188 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8189 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8190 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8191 PPCISD::LFIWZX : PPCISD::LFIWAX, 8192 dl, DAG.getVTList(MVT::f64, MVT::Other), 8193 Ops, MVT::i32, MMO); 8194 } else 8195 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8196 8197 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8198 8199 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8200 FP = DAG.getNode(ISD::FP_ROUND, dl, 8201 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8202 return FP; 8203 } 8204 8205 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8206 "Unhandled INT_TO_FP type in custom expander!"); 8207 // Since we only generate this in 64-bit mode, we can take advantage of 8208 // 64-bit registers. In particular, sign extend the input value into the 8209 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8210 // then lfd it and fcfid it. 8211 MachineFunction &MF = DAG.getMachineFunction(); 8212 MachineFrameInfo &MFI = MF.getFrameInfo(); 8213 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8214 8215 SDValue Ld; 8216 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8217 ReuseLoadInfo RLI; 8218 bool ReusingLoad; 8219 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8220 DAG))) { 8221 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8222 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8223 8224 SDValue Store = 8225 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8226 MachinePointerInfo::getFixedStack( 8227 DAG.getMachineFunction(), FrameIdx)); 8228 8229 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8230 "Expected an i32 store"); 8231 8232 RLI.Ptr = FIdx; 8233 RLI.Chain = Store; 8234 RLI.MPI = 8235 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8236 RLI.Alignment = 4; 8237 } 8238 8239 MachineMemOperand *MMO = 8240 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8241 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8242 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8243 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8244 PPCISD::LFIWZX : PPCISD::LFIWAX, 8245 dl, DAG.getVTList(MVT::f64, MVT::Other), 8246 Ops, MVT::i32, MMO); 8247 if (ReusingLoad) 8248 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8249 } else { 8250 assert(Subtarget.isPPC64() && 8251 "i32->FP without LFIWAX supported only on PPC64"); 8252 8253 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8254 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8255 8256 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8257 Op.getOperand(0)); 8258 8259 // STD the extended value into the stack slot. 8260 SDValue Store = DAG.getStore( 8261 DAG.getEntryNode(), dl, Ext64, FIdx, 8262 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8263 8264 // Load the value as a double. 8265 Ld = DAG.getLoad( 8266 MVT::f64, dl, Store, FIdx, 8267 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8268 } 8269 8270 // FCFID it and return it. 8271 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8272 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8273 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8274 DAG.getIntPtrConstant(0, dl)); 8275 return FP; 8276 } 8277 8278 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8279 SelectionDAG &DAG) const { 8280 SDLoc dl(Op); 8281 /* 8282 The rounding mode is in bits 30:31 of FPSR, and has the following 8283 settings: 8284 00 Round to nearest 8285 01 Round to 0 8286 10 Round to +inf 8287 11 Round to -inf 8288 8289 FLT_ROUNDS, on the other hand, expects the following: 8290 -1 Undefined 8291 0 Round to 0 8292 1 Round to nearest 8293 2 Round to +inf 8294 3 Round to -inf 8295 8296 To perform the conversion, we do: 8297 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8298 */ 8299 8300 MachineFunction &MF = DAG.getMachineFunction(); 8301 EVT VT = Op.getValueType(); 8302 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8303 8304 // Save FP Control Word to register 8305 EVT NodeTys[] = { 8306 MVT::f64, // return register 8307 MVT::Glue // unused in this context 8308 }; 8309 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 8310 8311 // Save FP register to stack slot 8312 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8313 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8314 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 8315 MachinePointerInfo()); 8316 8317 // Load FP Control Word from low 32 bits of stack slot. 8318 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8319 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8320 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 8321 8322 // Transform as necessary 8323 SDValue CWD1 = 8324 DAG.getNode(ISD::AND, dl, MVT::i32, 8325 CWD, DAG.getConstant(3, dl, MVT::i32)); 8326 SDValue CWD2 = 8327 DAG.getNode(ISD::SRL, dl, MVT::i32, 8328 DAG.getNode(ISD::AND, dl, MVT::i32, 8329 DAG.getNode(ISD::XOR, dl, MVT::i32, 8330 CWD, DAG.getConstant(3, dl, MVT::i32)), 8331 DAG.getConstant(3, dl, MVT::i32)), 8332 DAG.getConstant(1, dl, MVT::i32)); 8333 8334 SDValue RetVal = 8335 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8336 8337 return DAG.getNode((VT.getSizeInBits() < 16 ? 8338 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8339 } 8340 8341 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8342 EVT VT = Op.getValueType(); 8343 unsigned BitWidth = VT.getSizeInBits(); 8344 SDLoc dl(Op); 8345 assert(Op.getNumOperands() == 3 && 8346 VT == Op.getOperand(1).getValueType() && 8347 "Unexpected SHL!"); 8348 8349 // Expand into a bunch of logical ops. Note that these ops 8350 // depend on the PPC behavior for oversized shift amounts. 8351 SDValue Lo = Op.getOperand(0); 8352 SDValue Hi = Op.getOperand(1); 8353 SDValue Amt = Op.getOperand(2); 8354 EVT AmtVT = Amt.getValueType(); 8355 8356 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8357 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8358 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8359 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8360 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8361 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8362 DAG.getConstant(-BitWidth, dl, AmtVT)); 8363 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8364 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8365 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8366 SDValue OutOps[] = { OutLo, OutHi }; 8367 return DAG.getMergeValues(OutOps, dl); 8368 } 8369 8370 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8371 EVT VT = Op.getValueType(); 8372 SDLoc dl(Op); 8373 unsigned BitWidth = VT.getSizeInBits(); 8374 assert(Op.getNumOperands() == 3 && 8375 VT == Op.getOperand(1).getValueType() && 8376 "Unexpected SRL!"); 8377 8378 // Expand into a bunch of logical ops. Note that these ops 8379 // depend on the PPC behavior for oversized shift amounts. 8380 SDValue Lo = Op.getOperand(0); 8381 SDValue Hi = Op.getOperand(1); 8382 SDValue Amt = Op.getOperand(2); 8383 EVT AmtVT = Amt.getValueType(); 8384 8385 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8386 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8387 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8388 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8389 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8390 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8391 DAG.getConstant(-BitWidth, dl, AmtVT)); 8392 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8393 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8394 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8395 SDValue OutOps[] = { OutLo, OutHi }; 8396 return DAG.getMergeValues(OutOps, dl); 8397 } 8398 8399 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8400 SDLoc dl(Op); 8401 EVT VT = Op.getValueType(); 8402 unsigned BitWidth = VT.getSizeInBits(); 8403 assert(Op.getNumOperands() == 3 && 8404 VT == Op.getOperand(1).getValueType() && 8405 "Unexpected SRA!"); 8406 8407 // Expand into a bunch of logical ops, followed by a select_cc. 8408 SDValue Lo = Op.getOperand(0); 8409 SDValue Hi = Op.getOperand(1); 8410 SDValue Amt = Op.getOperand(2); 8411 EVT AmtVT = Amt.getValueType(); 8412 8413 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8414 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8415 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8416 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8417 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8418 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8419 DAG.getConstant(-BitWidth, dl, AmtVT)); 8420 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8421 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8422 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8423 Tmp4, Tmp6, ISD::SETLE); 8424 SDValue OutOps[] = { OutLo, OutHi }; 8425 return DAG.getMergeValues(OutOps, dl); 8426 } 8427 8428 //===----------------------------------------------------------------------===// 8429 // Vector related lowering. 8430 // 8431 8432 /// BuildSplatI - Build a canonical splati of Val with an element size of 8433 /// SplatSize. Cast the result to VT. 8434 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8435 SelectionDAG &DAG, const SDLoc &dl) { 8436 static const MVT VTys[] = { // canonical VT to use for each size. 8437 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8438 }; 8439 8440 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8441 8442 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8443 if (Val == -1) 8444 SplatSize = 1; 8445 8446 EVT CanonicalVT = VTys[SplatSize-1]; 8447 8448 // Build a canonical splat for this value. 8449 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8450 } 8451 8452 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8453 /// specified intrinsic ID. 8454 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8455 const SDLoc &dl, EVT DestVT = MVT::Other) { 8456 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8457 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8458 DAG.getConstant(IID, dl, MVT::i32), Op); 8459 } 8460 8461 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8462 /// specified intrinsic ID. 8463 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8464 SelectionDAG &DAG, const SDLoc &dl, 8465 EVT DestVT = MVT::Other) { 8466 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8467 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8468 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8469 } 8470 8471 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8472 /// specified intrinsic ID. 8473 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8474 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8475 EVT DestVT = MVT::Other) { 8476 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8477 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8478 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8479 } 8480 8481 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8482 /// amount. The result has the specified value type. 8483 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8484 SelectionDAG &DAG, const SDLoc &dl) { 8485 // Force LHS/RHS to be the right type. 8486 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8487 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8488 8489 int Ops[16]; 8490 for (unsigned i = 0; i != 16; ++i) 8491 Ops[i] = i + Amt; 8492 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8493 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8494 } 8495 8496 /// Do we have an efficient pattern in a .td file for this node? 8497 /// 8498 /// \param V - pointer to the BuildVectorSDNode being matched 8499 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8500 /// 8501 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8502 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8503 /// the opposite is true (expansion is beneficial) are: 8504 /// - The node builds a vector out of integers that are not 32 or 64-bits 8505 /// - The node builds a vector out of constants 8506 /// - The node is a "load-and-splat" 8507 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8508 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8509 bool HasDirectMove, 8510 bool HasP8Vector) { 8511 EVT VecVT = V->getValueType(0); 8512 bool RightType = VecVT == MVT::v2f64 || 8513 (HasP8Vector && VecVT == MVT::v4f32) || 8514 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8515 if (!RightType) 8516 return false; 8517 8518 bool IsSplat = true; 8519 bool IsLoad = false; 8520 SDValue Op0 = V->getOperand(0); 8521 8522 // This function is called in a block that confirms the node is not a constant 8523 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8524 // different constants. 8525 if (V->isConstant()) 8526 return false; 8527 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8528 if (V->getOperand(i).isUndef()) 8529 return false; 8530 // We want to expand nodes that represent load-and-splat even if the 8531 // loaded value is a floating point truncation or conversion to int. 8532 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8533 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8534 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8535 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8536 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8537 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8538 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8539 IsLoad = true; 8540 // If the operands are different or the input is not a load and has more 8541 // uses than just this BV node, then it isn't a splat. 8542 if (V->getOperand(i) != Op0 || 8543 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8544 IsSplat = false; 8545 } 8546 return !(IsSplat && IsLoad); 8547 } 8548 8549 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8550 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8551 8552 SDLoc dl(Op); 8553 SDValue Op0 = Op->getOperand(0); 8554 8555 if (!EnableQuadPrecision || 8556 (Op.getValueType() != MVT::f128 ) || 8557 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8558 (Op0.getOperand(0).getValueType() != MVT::i64) || 8559 (Op0.getOperand(1).getValueType() != MVT::i64)) 8560 return SDValue(); 8561 8562 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8563 Op0.getOperand(1)); 8564 } 8565 8566 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8567 const SDValue *InputLoad = &Op; 8568 if (InputLoad->getOpcode() == ISD::BITCAST) 8569 InputLoad = &InputLoad->getOperand(0); 8570 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8571 InputLoad = &InputLoad->getOperand(0); 8572 if (InputLoad->getOpcode() != ISD::LOAD) 8573 return nullptr; 8574 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8575 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8576 } 8577 8578 // If this is a case we can't handle, return null and let the default 8579 // expansion code take care of it. If we CAN select this case, and if it 8580 // selects to a single instruction, return Op. Otherwise, if we can codegen 8581 // this case more efficiently than a constant pool load, lower it to the 8582 // sequence of ops that should be used. 8583 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8584 SelectionDAG &DAG) const { 8585 SDLoc dl(Op); 8586 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8587 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8588 8589 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8590 // We first build an i32 vector, load it into a QPX register, 8591 // then convert it to a floating-point vector and compare it 8592 // to a zero vector to get the boolean result. 8593 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8594 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8595 MachinePointerInfo PtrInfo = 8596 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8597 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8598 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8599 8600 assert(BVN->getNumOperands() == 4 && 8601 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8602 8603 bool IsConst = true; 8604 for (unsigned i = 0; i < 4; ++i) { 8605 if (BVN->getOperand(i).isUndef()) continue; 8606 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8607 IsConst = false; 8608 break; 8609 } 8610 } 8611 8612 if (IsConst) { 8613 Constant *One = 8614 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8615 Constant *NegOne = 8616 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8617 8618 Constant *CV[4]; 8619 for (unsigned i = 0; i < 4; ++i) { 8620 if (BVN->getOperand(i).isUndef()) 8621 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8622 else if (isNullConstant(BVN->getOperand(i))) 8623 CV[i] = NegOne; 8624 else 8625 CV[i] = One; 8626 } 8627 8628 Constant *CP = ConstantVector::get(CV); 8629 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8630 16 /* alignment */); 8631 8632 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8633 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8634 return DAG.getMemIntrinsicNode( 8635 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8636 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8637 } 8638 8639 SmallVector<SDValue, 4> Stores; 8640 for (unsigned i = 0; i < 4; ++i) { 8641 if (BVN->getOperand(i).isUndef()) continue; 8642 8643 unsigned Offset = 4*i; 8644 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8645 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8646 8647 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8648 if (StoreSize > 4) { 8649 Stores.push_back( 8650 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8651 PtrInfo.getWithOffset(Offset), MVT::i32)); 8652 } else { 8653 SDValue StoreValue = BVN->getOperand(i); 8654 if (StoreSize < 4) 8655 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8656 8657 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8658 PtrInfo.getWithOffset(Offset))); 8659 } 8660 } 8661 8662 SDValue StoreChain; 8663 if (!Stores.empty()) 8664 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8665 else 8666 StoreChain = DAG.getEntryNode(); 8667 8668 // Now load from v4i32 into the QPX register; this will extend it to 8669 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8670 // is typed as v4f64 because the QPX register integer states are not 8671 // explicitly represented. 8672 8673 SDValue Ops[] = {StoreChain, 8674 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8675 FIdx}; 8676 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8677 8678 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8679 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8680 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8681 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8682 LoadedVect); 8683 8684 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8685 8686 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8687 } 8688 8689 // All other QPX vectors are handled by generic code. 8690 if (Subtarget.hasQPX()) 8691 return SDValue(); 8692 8693 // Check if this is a splat of a constant value. 8694 APInt APSplatBits, APSplatUndef; 8695 unsigned SplatBitSize; 8696 bool HasAnyUndefs; 8697 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8698 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8699 SplatBitSize > 32) { 8700 8701 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8702 // Handle load-and-splat patterns as we have instructions that will do this 8703 // in one go. 8704 if (InputLoad && DAG.isSplatValue(Op, true)) { 8705 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8706 8707 // We have handling for 4 and 8 byte elements. 8708 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8709 8710 // Checking for a single use of this load, we have to check for vector 8711 // width (128 bits) / ElementSize uses (since each operand of the 8712 // BUILD_VECTOR is a separate use of the value. 8713 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8714 ((Subtarget.hasVSX() && ElementSize == 64) || 8715 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8716 SDValue Ops[] = { 8717 LD->getChain(), // Chain 8718 LD->getBasePtr(), // Ptr 8719 DAG.getValueType(Op.getValueType()) // VT 8720 }; 8721 return 8722 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8723 DAG.getVTList(Op.getValueType(), MVT::Other), 8724 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8725 } 8726 } 8727 8728 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8729 // lowered to VSX instructions under certain conditions. 8730 // Without VSX, there is no pattern more efficient than expanding the node. 8731 if (Subtarget.hasVSX() && 8732 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8733 Subtarget.hasP8Vector())) 8734 return Op; 8735 return SDValue(); 8736 } 8737 8738 unsigned SplatBits = APSplatBits.getZExtValue(); 8739 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8740 unsigned SplatSize = SplatBitSize / 8; 8741 8742 // First, handle single instruction cases. 8743 8744 // All zeros? 8745 if (SplatBits == 0) { 8746 // Canonicalize all zero vectors to be v4i32. 8747 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8748 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8749 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8750 } 8751 return Op; 8752 } 8753 8754 // We have XXSPLTIB for constant splats one byte wide 8755 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8756 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8757 if (Subtarget.hasP9Vector() && SplatSize == 1) 8758 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8759 8760 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8761 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8762 (32-SplatBitSize)); 8763 if (SextVal >= -16 && SextVal <= 15) 8764 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8765 8766 // Two instruction sequences. 8767 8768 // If this value is in the range [-32,30] and is even, use: 8769 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8770 // If this value is in the range [17,31] and is odd, use: 8771 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8772 // If this value is in the range [-31,-17] and is odd, use: 8773 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8774 // Note the last two are three-instruction sequences. 8775 if (SextVal >= -32 && SextVal <= 31) { 8776 // To avoid having these optimizations undone by constant folding, 8777 // we convert to a pseudo that will be expanded later into one of 8778 // the above forms. 8779 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8780 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8781 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8782 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8783 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8784 if (VT == Op.getValueType()) 8785 return RetVal; 8786 else 8787 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8788 } 8789 8790 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8791 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8792 // for fneg/fabs. 8793 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8794 // Make -1 and vspltisw -1: 8795 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8796 8797 // Make the VSLW intrinsic, computing 0x8000_0000. 8798 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8799 OnesV, DAG, dl); 8800 8801 // xor by OnesV to invert it. 8802 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8803 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8804 } 8805 8806 // Check to see if this is a wide variety of vsplti*, binop self cases. 8807 static const signed char SplatCsts[] = { 8808 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8809 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8810 }; 8811 8812 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8813 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8814 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8815 int i = SplatCsts[idx]; 8816 8817 // Figure out what shift amount will be used by altivec if shifted by i in 8818 // this splat size. 8819 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8820 8821 // vsplti + shl self. 8822 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8823 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8824 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8825 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8826 Intrinsic::ppc_altivec_vslw 8827 }; 8828 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8829 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8830 } 8831 8832 // vsplti + srl self. 8833 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8834 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8835 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8836 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8837 Intrinsic::ppc_altivec_vsrw 8838 }; 8839 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8840 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8841 } 8842 8843 // vsplti + sra self. 8844 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8845 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8846 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8847 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8848 Intrinsic::ppc_altivec_vsraw 8849 }; 8850 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8851 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8852 } 8853 8854 // vsplti + rol self. 8855 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8856 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8857 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8858 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8859 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8860 Intrinsic::ppc_altivec_vrlw 8861 }; 8862 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8863 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8864 } 8865 8866 // t = vsplti c, result = vsldoi t, t, 1 8867 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8868 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8869 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8870 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8871 } 8872 // t = vsplti c, result = vsldoi t, t, 2 8873 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8874 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8875 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8876 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8877 } 8878 // t = vsplti c, result = vsldoi t, t, 3 8879 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8880 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8881 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8882 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8883 } 8884 } 8885 8886 return SDValue(); 8887 } 8888 8889 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8890 /// the specified operations to build the shuffle. 8891 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8892 SDValue RHS, SelectionDAG &DAG, 8893 const SDLoc &dl) { 8894 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8895 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8896 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8897 8898 enum { 8899 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8900 OP_VMRGHW, 8901 OP_VMRGLW, 8902 OP_VSPLTISW0, 8903 OP_VSPLTISW1, 8904 OP_VSPLTISW2, 8905 OP_VSPLTISW3, 8906 OP_VSLDOI4, 8907 OP_VSLDOI8, 8908 OP_VSLDOI12 8909 }; 8910 8911 if (OpNum == OP_COPY) { 8912 if (LHSID == (1*9+2)*9+3) return LHS; 8913 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8914 return RHS; 8915 } 8916 8917 SDValue OpLHS, OpRHS; 8918 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8919 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8920 8921 int ShufIdxs[16]; 8922 switch (OpNum) { 8923 default: llvm_unreachable("Unknown i32 permute!"); 8924 case OP_VMRGHW: 8925 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8926 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8927 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8928 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8929 break; 8930 case OP_VMRGLW: 8931 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8932 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8933 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8934 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8935 break; 8936 case OP_VSPLTISW0: 8937 for (unsigned i = 0; i != 16; ++i) 8938 ShufIdxs[i] = (i&3)+0; 8939 break; 8940 case OP_VSPLTISW1: 8941 for (unsigned i = 0; i != 16; ++i) 8942 ShufIdxs[i] = (i&3)+4; 8943 break; 8944 case OP_VSPLTISW2: 8945 for (unsigned i = 0; i != 16; ++i) 8946 ShufIdxs[i] = (i&3)+8; 8947 break; 8948 case OP_VSPLTISW3: 8949 for (unsigned i = 0; i != 16; ++i) 8950 ShufIdxs[i] = (i&3)+12; 8951 break; 8952 case OP_VSLDOI4: 8953 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8954 case OP_VSLDOI8: 8955 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8956 case OP_VSLDOI12: 8957 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8958 } 8959 EVT VT = OpLHS.getValueType(); 8960 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8961 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8962 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8963 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8964 } 8965 8966 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8967 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8968 /// SDValue. 8969 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8970 SelectionDAG &DAG) const { 8971 const unsigned BytesInVector = 16; 8972 bool IsLE = Subtarget.isLittleEndian(); 8973 SDLoc dl(N); 8974 SDValue V1 = N->getOperand(0); 8975 SDValue V2 = N->getOperand(1); 8976 unsigned ShiftElts = 0, InsertAtByte = 0; 8977 bool Swap = false; 8978 8979 // Shifts required to get the byte we want at element 7. 8980 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8981 0, 15, 14, 13, 12, 11, 10, 9}; 8982 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8983 1, 2, 3, 4, 5, 6, 7, 8}; 8984 8985 ArrayRef<int> Mask = N->getMask(); 8986 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8987 8988 // For each mask element, find out if we're just inserting something 8989 // from V2 into V1 or vice versa. 8990 // Possible permutations inserting an element from V2 into V1: 8991 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8992 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8993 // ... 8994 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8995 // Inserting from V1 into V2 will be similar, except mask range will be 8996 // [16,31]. 8997 8998 bool FoundCandidate = false; 8999 // If both vector operands for the shuffle are the same vector, the mask 9000 // will contain only elements from the first one and the second one will be 9001 // undef. 9002 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9003 // Go through the mask of half-words to find an element that's being moved 9004 // from one vector to the other. 9005 for (unsigned i = 0; i < BytesInVector; ++i) { 9006 unsigned CurrentElement = Mask[i]; 9007 // If 2nd operand is undefined, we should only look for element 7 in the 9008 // Mask. 9009 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9010 continue; 9011 9012 bool OtherElementsInOrder = true; 9013 // Examine the other elements in the Mask to see if they're in original 9014 // order. 9015 for (unsigned j = 0; j < BytesInVector; ++j) { 9016 if (j == i) 9017 continue; 9018 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9019 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9020 // in which we always assume we're always picking from the 1st operand. 9021 int MaskOffset = 9022 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9023 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9024 OtherElementsInOrder = false; 9025 break; 9026 } 9027 } 9028 // If other elements are in original order, we record the number of shifts 9029 // we need to get the element we want into element 7. Also record which byte 9030 // in the vector we should insert into. 9031 if (OtherElementsInOrder) { 9032 // If 2nd operand is undefined, we assume no shifts and no swapping. 9033 if (V2.isUndef()) { 9034 ShiftElts = 0; 9035 Swap = false; 9036 } else { 9037 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9038 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9039 : BigEndianShifts[CurrentElement & 0xF]; 9040 Swap = CurrentElement < BytesInVector; 9041 } 9042 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9043 FoundCandidate = true; 9044 break; 9045 } 9046 } 9047 9048 if (!FoundCandidate) 9049 return SDValue(); 9050 9051 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9052 // optionally with VECSHL if shift is required. 9053 if (Swap) 9054 std::swap(V1, V2); 9055 if (V2.isUndef()) 9056 V2 = V1; 9057 if (ShiftElts) { 9058 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9059 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9060 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9061 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9062 } 9063 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9064 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9065 } 9066 9067 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9068 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9069 /// SDValue. 9070 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9071 SelectionDAG &DAG) const { 9072 const unsigned NumHalfWords = 8; 9073 const unsigned BytesInVector = NumHalfWords * 2; 9074 // Check that the shuffle is on half-words. 9075 if (!isNByteElemShuffleMask(N, 2, 1)) 9076 return SDValue(); 9077 9078 bool IsLE = Subtarget.isLittleEndian(); 9079 SDLoc dl(N); 9080 SDValue V1 = N->getOperand(0); 9081 SDValue V2 = N->getOperand(1); 9082 unsigned ShiftElts = 0, InsertAtByte = 0; 9083 bool Swap = false; 9084 9085 // Shifts required to get the half-word we want at element 3. 9086 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9087 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9088 9089 uint32_t Mask = 0; 9090 uint32_t OriginalOrderLow = 0x1234567; 9091 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9092 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9093 // 32-bit space, only need 4-bit nibbles per element. 9094 for (unsigned i = 0; i < NumHalfWords; ++i) { 9095 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9096 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9097 } 9098 9099 // For each mask element, find out if we're just inserting something 9100 // from V2 into V1 or vice versa. Possible permutations inserting an element 9101 // from V2 into V1: 9102 // X, 1, 2, 3, 4, 5, 6, 7 9103 // 0, X, 2, 3, 4, 5, 6, 7 9104 // 0, 1, X, 3, 4, 5, 6, 7 9105 // 0, 1, 2, X, 4, 5, 6, 7 9106 // 0, 1, 2, 3, X, 5, 6, 7 9107 // 0, 1, 2, 3, 4, X, 6, 7 9108 // 0, 1, 2, 3, 4, 5, X, 7 9109 // 0, 1, 2, 3, 4, 5, 6, X 9110 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9111 9112 bool FoundCandidate = false; 9113 // Go through the mask of half-words to find an element that's being moved 9114 // from one vector to the other. 9115 for (unsigned i = 0; i < NumHalfWords; ++i) { 9116 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9117 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9118 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9119 uint32_t TargetOrder = 0x0; 9120 9121 // If both vector operands for the shuffle are the same vector, the mask 9122 // will contain only elements from the first one and the second one will be 9123 // undef. 9124 if (V2.isUndef()) { 9125 ShiftElts = 0; 9126 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9127 TargetOrder = OriginalOrderLow; 9128 Swap = false; 9129 // Skip if not the correct element or mask of other elements don't equal 9130 // to our expected order. 9131 if (MaskOneElt == VINSERTHSrcElem && 9132 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9133 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9134 FoundCandidate = true; 9135 break; 9136 } 9137 } else { // If both operands are defined. 9138 // Target order is [8,15] if the current mask is between [0,7]. 9139 TargetOrder = 9140 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9141 // Skip if mask of other elements don't equal our expected order. 9142 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9143 // We only need the last 3 bits for the number of shifts. 9144 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9145 : BigEndianShifts[MaskOneElt & 0x7]; 9146 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9147 Swap = MaskOneElt < NumHalfWords; 9148 FoundCandidate = true; 9149 break; 9150 } 9151 } 9152 } 9153 9154 if (!FoundCandidate) 9155 return SDValue(); 9156 9157 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9158 // optionally with VECSHL if shift is required. 9159 if (Swap) 9160 std::swap(V1, V2); 9161 if (V2.isUndef()) 9162 V2 = V1; 9163 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9164 if (ShiftElts) { 9165 // Double ShiftElts because we're left shifting on v16i8 type. 9166 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9167 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9168 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9169 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9170 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9171 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9172 } 9173 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9174 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9175 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9176 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9177 } 9178 9179 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9180 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9181 /// return the code it can be lowered into. Worst case, it can always be 9182 /// lowered into a vperm. 9183 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9184 SelectionDAG &DAG) const { 9185 SDLoc dl(Op); 9186 SDValue V1 = Op.getOperand(0); 9187 SDValue V2 = Op.getOperand(1); 9188 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9189 EVT VT = Op.getValueType(); 9190 bool isLittleEndian = Subtarget.isLittleEndian(); 9191 9192 unsigned ShiftElts, InsertAtByte; 9193 bool Swap = false; 9194 9195 // If this is a load-and-splat, we can do that with a single instruction 9196 // in some cases. However if the load has multiple uses, we don't want to 9197 // combine it because that will just produce multiple loads. 9198 const SDValue *InputLoad = getNormalLoadInput(V1); 9199 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9200 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9201 InputLoad->hasOneUse()) { 9202 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9203 int SplatIdx = 9204 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9205 9206 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9207 // For 4-byte load-and-splat, we need Power9. 9208 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9209 uint64_t Offset = 0; 9210 if (IsFourByte) 9211 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9212 else 9213 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9214 SDValue BasePtr = LD->getBasePtr(); 9215 if (Offset != 0) 9216 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9217 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9218 SDValue Ops[] = { 9219 LD->getChain(), // Chain 9220 BasePtr, // BasePtr 9221 DAG.getValueType(Op.getValueType()) // VT 9222 }; 9223 SDVTList VTL = 9224 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9225 SDValue LdSplt = 9226 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9227 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9228 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9229 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9230 return LdSplt; 9231 } 9232 } 9233 if (Subtarget.hasP9Vector() && 9234 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9235 isLittleEndian)) { 9236 if (Swap) 9237 std::swap(V1, V2); 9238 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9239 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9240 if (ShiftElts) { 9241 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9242 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9243 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9244 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9245 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9246 } 9247 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9248 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9249 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9250 } 9251 9252 if (Subtarget.hasP9Altivec()) { 9253 SDValue NewISDNode; 9254 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9255 return NewISDNode; 9256 9257 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9258 return NewISDNode; 9259 } 9260 9261 if (Subtarget.hasVSX() && 9262 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9263 if (Swap) 9264 std::swap(V1, V2); 9265 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9266 SDValue Conv2 = 9267 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9268 9269 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9270 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9271 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9272 } 9273 9274 if (Subtarget.hasVSX() && 9275 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9276 if (Swap) 9277 std::swap(V1, V2); 9278 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9279 SDValue Conv2 = 9280 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9281 9282 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9283 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9284 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9285 } 9286 9287 if (Subtarget.hasP9Vector()) { 9288 if (PPC::isXXBRHShuffleMask(SVOp)) { 9289 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9290 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9291 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9292 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9293 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9294 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9295 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9296 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9297 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9298 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9299 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9300 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9301 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9302 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9303 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9304 } 9305 } 9306 9307 if (Subtarget.hasVSX()) { 9308 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9309 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9310 9311 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9312 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9313 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9314 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9315 } 9316 9317 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9318 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9319 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9320 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9321 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9322 } 9323 } 9324 9325 if (Subtarget.hasQPX()) { 9326 if (VT.getVectorNumElements() != 4) 9327 return SDValue(); 9328 9329 if (V2.isUndef()) V2 = V1; 9330 9331 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9332 if (AlignIdx != -1) { 9333 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9334 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9335 } else if (SVOp->isSplat()) { 9336 int SplatIdx = SVOp->getSplatIndex(); 9337 if (SplatIdx >= 4) { 9338 std::swap(V1, V2); 9339 SplatIdx -= 4; 9340 } 9341 9342 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9343 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9344 } 9345 9346 // Lower this into a qvgpci/qvfperm pair. 9347 9348 // Compute the qvgpci literal 9349 unsigned idx = 0; 9350 for (unsigned i = 0; i < 4; ++i) { 9351 int m = SVOp->getMaskElt(i); 9352 unsigned mm = m >= 0 ? (unsigned) m : i; 9353 idx |= mm << (3-i)*3; 9354 } 9355 9356 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9357 DAG.getConstant(idx, dl, MVT::i32)); 9358 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9359 } 9360 9361 // Cases that are handled by instructions that take permute immediates 9362 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9363 // selected by the instruction selector. 9364 if (V2.isUndef()) { 9365 if (PPC::isSplatShuffleMask(SVOp, 1) || 9366 PPC::isSplatShuffleMask(SVOp, 2) || 9367 PPC::isSplatShuffleMask(SVOp, 4) || 9368 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9369 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9370 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9371 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9372 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9373 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9374 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9375 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9376 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9377 (Subtarget.hasP8Altivec() && ( 9378 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9379 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9380 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9381 return Op; 9382 } 9383 } 9384 9385 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9386 // and produce a fixed permutation. If any of these match, do not lower to 9387 // VPERM. 9388 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9389 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9390 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9391 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9392 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9393 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9394 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9395 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9396 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9397 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9398 (Subtarget.hasP8Altivec() && ( 9399 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9400 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9401 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9402 return Op; 9403 9404 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9405 // perfect shuffle table to emit an optimal matching sequence. 9406 ArrayRef<int> PermMask = SVOp->getMask(); 9407 9408 unsigned PFIndexes[4]; 9409 bool isFourElementShuffle = true; 9410 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9411 unsigned EltNo = 8; // Start out undef. 9412 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9413 if (PermMask[i*4+j] < 0) 9414 continue; // Undef, ignore it. 9415 9416 unsigned ByteSource = PermMask[i*4+j]; 9417 if ((ByteSource & 3) != j) { 9418 isFourElementShuffle = false; 9419 break; 9420 } 9421 9422 if (EltNo == 8) { 9423 EltNo = ByteSource/4; 9424 } else if (EltNo != ByteSource/4) { 9425 isFourElementShuffle = false; 9426 break; 9427 } 9428 } 9429 PFIndexes[i] = EltNo; 9430 } 9431 9432 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9433 // perfect shuffle vector to determine if it is cost effective to do this as 9434 // discrete instructions, or whether we should use a vperm. 9435 // For now, we skip this for little endian until such time as we have a 9436 // little-endian perfect shuffle table. 9437 if (isFourElementShuffle && !isLittleEndian) { 9438 // Compute the index in the perfect shuffle table. 9439 unsigned PFTableIndex = 9440 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9441 9442 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9443 unsigned Cost = (PFEntry >> 30); 9444 9445 // Determining when to avoid vperm is tricky. Many things affect the cost 9446 // of vperm, particularly how many times the perm mask needs to be computed. 9447 // For example, if the perm mask can be hoisted out of a loop or is already 9448 // used (perhaps because there are multiple permutes with the same shuffle 9449 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9450 // the loop requires an extra register. 9451 // 9452 // As a compromise, we only emit discrete instructions if the shuffle can be 9453 // generated in 3 or fewer operations. When we have loop information 9454 // available, if this block is within a loop, we should avoid using vperm 9455 // for 3-operation perms and use a constant pool load instead. 9456 if (Cost < 3) 9457 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9458 } 9459 9460 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9461 // vector that will get spilled to the constant pool. 9462 if (V2.isUndef()) V2 = V1; 9463 9464 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9465 // that it is in input element units, not in bytes. Convert now. 9466 9467 // For little endian, the order of the input vectors is reversed, and 9468 // the permutation mask is complemented with respect to 31. This is 9469 // necessary to produce proper semantics with the big-endian-biased vperm 9470 // instruction. 9471 EVT EltVT = V1.getValueType().getVectorElementType(); 9472 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9473 9474 SmallVector<SDValue, 16> ResultMask; 9475 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9476 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9477 9478 for (unsigned j = 0; j != BytesPerElement; ++j) 9479 if (isLittleEndian) 9480 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9481 dl, MVT::i32)); 9482 else 9483 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9484 MVT::i32)); 9485 } 9486 9487 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9488 if (isLittleEndian) 9489 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9490 V2, V1, VPermMask); 9491 else 9492 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9493 V1, V2, VPermMask); 9494 } 9495 9496 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9497 /// vector comparison. If it is, return true and fill in Opc/isDot with 9498 /// information about the intrinsic. 9499 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9500 bool &isDot, const PPCSubtarget &Subtarget) { 9501 unsigned IntrinsicID = 9502 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9503 CompareOpc = -1; 9504 isDot = false; 9505 switch (IntrinsicID) { 9506 default: 9507 return false; 9508 // Comparison predicates. 9509 case Intrinsic::ppc_altivec_vcmpbfp_p: 9510 CompareOpc = 966; 9511 isDot = true; 9512 break; 9513 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9514 CompareOpc = 198; 9515 isDot = true; 9516 break; 9517 case Intrinsic::ppc_altivec_vcmpequb_p: 9518 CompareOpc = 6; 9519 isDot = true; 9520 break; 9521 case Intrinsic::ppc_altivec_vcmpequh_p: 9522 CompareOpc = 70; 9523 isDot = true; 9524 break; 9525 case Intrinsic::ppc_altivec_vcmpequw_p: 9526 CompareOpc = 134; 9527 isDot = true; 9528 break; 9529 case Intrinsic::ppc_altivec_vcmpequd_p: 9530 if (Subtarget.hasP8Altivec()) { 9531 CompareOpc = 199; 9532 isDot = true; 9533 } else 9534 return false; 9535 break; 9536 case Intrinsic::ppc_altivec_vcmpneb_p: 9537 case Intrinsic::ppc_altivec_vcmpneh_p: 9538 case Intrinsic::ppc_altivec_vcmpnew_p: 9539 case Intrinsic::ppc_altivec_vcmpnezb_p: 9540 case Intrinsic::ppc_altivec_vcmpnezh_p: 9541 case Intrinsic::ppc_altivec_vcmpnezw_p: 9542 if (Subtarget.hasP9Altivec()) { 9543 switch (IntrinsicID) { 9544 default: 9545 llvm_unreachable("Unknown comparison intrinsic."); 9546 case Intrinsic::ppc_altivec_vcmpneb_p: 9547 CompareOpc = 7; 9548 break; 9549 case Intrinsic::ppc_altivec_vcmpneh_p: 9550 CompareOpc = 71; 9551 break; 9552 case Intrinsic::ppc_altivec_vcmpnew_p: 9553 CompareOpc = 135; 9554 break; 9555 case Intrinsic::ppc_altivec_vcmpnezb_p: 9556 CompareOpc = 263; 9557 break; 9558 case Intrinsic::ppc_altivec_vcmpnezh_p: 9559 CompareOpc = 327; 9560 break; 9561 case Intrinsic::ppc_altivec_vcmpnezw_p: 9562 CompareOpc = 391; 9563 break; 9564 } 9565 isDot = true; 9566 } else 9567 return false; 9568 break; 9569 case Intrinsic::ppc_altivec_vcmpgefp_p: 9570 CompareOpc = 454; 9571 isDot = true; 9572 break; 9573 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9574 CompareOpc = 710; 9575 isDot = true; 9576 break; 9577 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9578 CompareOpc = 774; 9579 isDot = true; 9580 break; 9581 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9582 CompareOpc = 838; 9583 isDot = true; 9584 break; 9585 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9586 CompareOpc = 902; 9587 isDot = true; 9588 break; 9589 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9590 if (Subtarget.hasP8Altivec()) { 9591 CompareOpc = 967; 9592 isDot = true; 9593 } else 9594 return false; 9595 break; 9596 case Intrinsic::ppc_altivec_vcmpgtub_p: 9597 CompareOpc = 518; 9598 isDot = true; 9599 break; 9600 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9601 CompareOpc = 582; 9602 isDot = true; 9603 break; 9604 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9605 CompareOpc = 646; 9606 isDot = true; 9607 break; 9608 case Intrinsic::ppc_altivec_vcmpgtud_p: 9609 if (Subtarget.hasP8Altivec()) { 9610 CompareOpc = 711; 9611 isDot = true; 9612 } else 9613 return false; 9614 break; 9615 9616 // VSX predicate comparisons use the same infrastructure 9617 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9618 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9619 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9620 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9621 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9622 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9623 if (Subtarget.hasVSX()) { 9624 switch (IntrinsicID) { 9625 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9626 CompareOpc = 99; 9627 break; 9628 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9629 CompareOpc = 115; 9630 break; 9631 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9632 CompareOpc = 107; 9633 break; 9634 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9635 CompareOpc = 67; 9636 break; 9637 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9638 CompareOpc = 83; 9639 break; 9640 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9641 CompareOpc = 75; 9642 break; 9643 } 9644 isDot = true; 9645 } else 9646 return false; 9647 break; 9648 9649 // Normal Comparisons. 9650 case Intrinsic::ppc_altivec_vcmpbfp: 9651 CompareOpc = 966; 9652 break; 9653 case Intrinsic::ppc_altivec_vcmpeqfp: 9654 CompareOpc = 198; 9655 break; 9656 case Intrinsic::ppc_altivec_vcmpequb: 9657 CompareOpc = 6; 9658 break; 9659 case Intrinsic::ppc_altivec_vcmpequh: 9660 CompareOpc = 70; 9661 break; 9662 case Intrinsic::ppc_altivec_vcmpequw: 9663 CompareOpc = 134; 9664 break; 9665 case Intrinsic::ppc_altivec_vcmpequd: 9666 if (Subtarget.hasP8Altivec()) 9667 CompareOpc = 199; 9668 else 9669 return false; 9670 break; 9671 case Intrinsic::ppc_altivec_vcmpneb: 9672 case Intrinsic::ppc_altivec_vcmpneh: 9673 case Intrinsic::ppc_altivec_vcmpnew: 9674 case Intrinsic::ppc_altivec_vcmpnezb: 9675 case Intrinsic::ppc_altivec_vcmpnezh: 9676 case Intrinsic::ppc_altivec_vcmpnezw: 9677 if (Subtarget.hasP9Altivec()) 9678 switch (IntrinsicID) { 9679 default: 9680 llvm_unreachable("Unknown comparison intrinsic."); 9681 case Intrinsic::ppc_altivec_vcmpneb: 9682 CompareOpc = 7; 9683 break; 9684 case Intrinsic::ppc_altivec_vcmpneh: 9685 CompareOpc = 71; 9686 break; 9687 case Intrinsic::ppc_altivec_vcmpnew: 9688 CompareOpc = 135; 9689 break; 9690 case Intrinsic::ppc_altivec_vcmpnezb: 9691 CompareOpc = 263; 9692 break; 9693 case Intrinsic::ppc_altivec_vcmpnezh: 9694 CompareOpc = 327; 9695 break; 9696 case Intrinsic::ppc_altivec_vcmpnezw: 9697 CompareOpc = 391; 9698 break; 9699 } 9700 else 9701 return false; 9702 break; 9703 case Intrinsic::ppc_altivec_vcmpgefp: 9704 CompareOpc = 454; 9705 break; 9706 case Intrinsic::ppc_altivec_vcmpgtfp: 9707 CompareOpc = 710; 9708 break; 9709 case Intrinsic::ppc_altivec_vcmpgtsb: 9710 CompareOpc = 774; 9711 break; 9712 case Intrinsic::ppc_altivec_vcmpgtsh: 9713 CompareOpc = 838; 9714 break; 9715 case Intrinsic::ppc_altivec_vcmpgtsw: 9716 CompareOpc = 902; 9717 break; 9718 case Intrinsic::ppc_altivec_vcmpgtsd: 9719 if (Subtarget.hasP8Altivec()) 9720 CompareOpc = 967; 9721 else 9722 return false; 9723 break; 9724 case Intrinsic::ppc_altivec_vcmpgtub: 9725 CompareOpc = 518; 9726 break; 9727 case Intrinsic::ppc_altivec_vcmpgtuh: 9728 CompareOpc = 582; 9729 break; 9730 case Intrinsic::ppc_altivec_vcmpgtuw: 9731 CompareOpc = 646; 9732 break; 9733 case Intrinsic::ppc_altivec_vcmpgtud: 9734 if (Subtarget.hasP8Altivec()) 9735 CompareOpc = 711; 9736 else 9737 return false; 9738 break; 9739 } 9740 return true; 9741 } 9742 9743 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9744 /// lower, do it, otherwise return null. 9745 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9746 SelectionDAG &DAG) const { 9747 unsigned IntrinsicID = 9748 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9749 9750 SDLoc dl(Op); 9751 9752 if (IntrinsicID == Intrinsic::thread_pointer) { 9753 // Reads the thread pointer register, used for __builtin_thread_pointer. 9754 if (Subtarget.isPPC64()) 9755 return DAG.getRegister(PPC::X13, MVT::i64); 9756 return DAG.getRegister(PPC::R2, MVT::i32); 9757 } 9758 9759 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9760 // opcode number of the comparison. 9761 int CompareOpc; 9762 bool isDot; 9763 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9764 return SDValue(); // Don't custom lower most intrinsics. 9765 9766 // If this is a non-dot comparison, make the VCMP node and we are done. 9767 if (!isDot) { 9768 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9769 Op.getOperand(1), Op.getOperand(2), 9770 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9771 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9772 } 9773 9774 // Create the PPCISD altivec 'dot' comparison node. 9775 SDValue Ops[] = { 9776 Op.getOperand(2), // LHS 9777 Op.getOperand(3), // RHS 9778 DAG.getConstant(CompareOpc, dl, MVT::i32) 9779 }; 9780 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9781 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9782 9783 // Now that we have the comparison, emit a copy from the CR to a GPR. 9784 // This is flagged to the above dot comparison. 9785 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9786 DAG.getRegister(PPC::CR6, MVT::i32), 9787 CompNode.getValue(1)); 9788 9789 // Unpack the result based on how the target uses it. 9790 unsigned BitNo; // Bit # of CR6. 9791 bool InvertBit; // Invert result? 9792 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9793 default: // Can't happen, don't crash on invalid number though. 9794 case 0: // Return the value of the EQ bit of CR6. 9795 BitNo = 0; InvertBit = false; 9796 break; 9797 case 1: // Return the inverted value of the EQ bit of CR6. 9798 BitNo = 0; InvertBit = true; 9799 break; 9800 case 2: // Return the value of the LT bit of CR6. 9801 BitNo = 2; InvertBit = false; 9802 break; 9803 case 3: // Return the inverted value of the LT bit of CR6. 9804 BitNo = 2; InvertBit = true; 9805 break; 9806 } 9807 9808 // Shift the bit into the low position. 9809 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9810 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9811 // Isolate the bit. 9812 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9813 DAG.getConstant(1, dl, MVT::i32)); 9814 9815 // If we are supposed to, toggle the bit. 9816 if (InvertBit) 9817 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9818 DAG.getConstant(1, dl, MVT::i32)); 9819 return Flags; 9820 } 9821 9822 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9823 SelectionDAG &DAG) const { 9824 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9825 // the beginning of the argument list. 9826 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9827 SDLoc DL(Op); 9828 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9829 case Intrinsic::ppc_cfence: { 9830 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9831 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9832 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9833 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9834 Op.getOperand(ArgStart + 1)), 9835 Op.getOperand(0)), 9836 0); 9837 } 9838 default: 9839 break; 9840 } 9841 return SDValue(); 9842 } 9843 9844 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9845 // Check for a DIV with the same operands as this REM. 9846 for (auto UI : Op.getOperand(1)->uses()) { 9847 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9848 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9849 if (UI->getOperand(0) == Op.getOperand(0) && 9850 UI->getOperand(1) == Op.getOperand(1)) 9851 return SDValue(); 9852 } 9853 return Op; 9854 } 9855 9856 // Lower scalar BSWAP64 to xxbrd. 9857 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9858 SDLoc dl(Op); 9859 // MTVSRDD 9860 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9861 Op.getOperand(0)); 9862 // XXBRD 9863 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 9864 // MFVSRD 9865 int VectorIndex = 0; 9866 if (Subtarget.isLittleEndian()) 9867 VectorIndex = 1; 9868 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9869 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9870 return Op; 9871 } 9872 9873 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9874 // compared to a value that is atomically loaded (atomic loads zero-extend). 9875 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9876 SelectionDAG &DAG) const { 9877 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9878 "Expecting an atomic compare-and-swap here."); 9879 SDLoc dl(Op); 9880 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9881 EVT MemVT = AtomicNode->getMemoryVT(); 9882 if (MemVT.getSizeInBits() >= 32) 9883 return Op; 9884 9885 SDValue CmpOp = Op.getOperand(2); 9886 // If this is already correctly zero-extended, leave it alone. 9887 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9888 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9889 return Op; 9890 9891 // Clear the high bits of the compare operand. 9892 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9893 SDValue NewCmpOp = 9894 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9895 DAG.getConstant(MaskVal, dl, MVT::i32)); 9896 9897 // Replace the existing compare operand with the properly zero-extended one. 9898 SmallVector<SDValue, 4> Ops; 9899 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9900 Ops.push_back(AtomicNode->getOperand(i)); 9901 Ops[2] = NewCmpOp; 9902 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9903 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9904 auto NodeTy = 9905 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9906 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9907 } 9908 9909 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9910 SelectionDAG &DAG) const { 9911 SDLoc dl(Op); 9912 // Create a stack slot that is 16-byte aligned. 9913 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9914 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9915 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9916 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9917 9918 // Store the input value into Value#0 of the stack slot. 9919 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9920 MachinePointerInfo()); 9921 // Load it out. 9922 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9923 } 9924 9925 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9926 SelectionDAG &DAG) const { 9927 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9928 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9929 9930 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9931 // We have legal lowering for constant indices but not for variable ones. 9932 if (!C) 9933 return SDValue(); 9934 9935 EVT VT = Op.getValueType(); 9936 SDLoc dl(Op); 9937 SDValue V1 = Op.getOperand(0); 9938 SDValue V2 = Op.getOperand(1); 9939 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9940 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9941 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9942 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9943 unsigned InsertAtElement = C->getZExtValue(); 9944 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9945 if (Subtarget.isLittleEndian()) { 9946 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9947 } 9948 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9949 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9950 } 9951 return Op; 9952 } 9953 9954 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9955 SelectionDAG &DAG) const { 9956 SDLoc dl(Op); 9957 SDNode *N = Op.getNode(); 9958 9959 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9960 "Unknown extract_vector_elt type"); 9961 9962 SDValue Value = N->getOperand(0); 9963 9964 // The first part of this is like the store lowering except that we don't 9965 // need to track the chain. 9966 9967 // The values are now known to be -1 (false) or 1 (true). To convert this 9968 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9969 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9970 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9971 9972 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9973 // understand how to form the extending load. 9974 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9975 9976 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9977 9978 // Now convert to an integer and store. 9979 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9980 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9981 Value); 9982 9983 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9984 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9985 MachinePointerInfo PtrInfo = 9986 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9987 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9988 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9989 9990 SDValue StoreChain = DAG.getEntryNode(); 9991 SDValue Ops[] = {StoreChain, 9992 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9993 Value, FIdx}; 9994 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9995 9996 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 9997 dl, VTs, Ops, MVT::v4i32, PtrInfo); 9998 9999 // Extract the value requested. 10000 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10001 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10002 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10003 10004 SDValue IntVal = 10005 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10006 10007 if (!Subtarget.useCRBits()) 10008 return IntVal; 10009 10010 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10011 } 10012 10013 /// Lowering for QPX v4i1 loads 10014 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10015 SelectionDAG &DAG) const { 10016 SDLoc dl(Op); 10017 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10018 SDValue LoadChain = LN->getChain(); 10019 SDValue BasePtr = LN->getBasePtr(); 10020 10021 if (Op.getValueType() == MVT::v4f64 || 10022 Op.getValueType() == MVT::v4f32) { 10023 EVT MemVT = LN->getMemoryVT(); 10024 unsigned Alignment = LN->getAlignment(); 10025 10026 // If this load is properly aligned, then it is legal. 10027 if (Alignment >= MemVT.getStoreSize()) 10028 return Op; 10029 10030 EVT ScalarVT = Op.getValueType().getScalarType(), 10031 ScalarMemVT = MemVT.getScalarType(); 10032 unsigned Stride = ScalarMemVT.getStoreSize(); 10033 10034 SDValue Vals[4], LoadChains[4]; 10035 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10036 SDValue Load; 10037 if (ScalarVT != ScalarMemVT) 10038 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10039 BasePtr, 10040 LN->getPointerInfo().getWithOffset(Idx * Stride), 10041 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10042 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10043 else 10044 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10045 LN->getPointerInfo().getWithOffset(Idx * Stride), 10046 MinAlign(Alignment, Idx * Stride), 10047 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10048 10049 if (Idx == 0 && LN->isIndexed()) { 10050 assert(LN->getAddressingMode() == ISD::PRE_INC && 10051 "Unknown addressing mode on vector load"); 10052 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10053 LN->getAddressingMode()); 10054 } 10055 10056 Vals[Idx] = Load; 10057 LoadChains[Idx] = Load.getValue(1); 10058 10059 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10060 DAG.getConstant(Stride, dl, 10061 BasePtr.getValueType())); 10062 } 10063 10064 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10065 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10066 10067 if (LN->isIndexed()) { 10068 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10069 return DAG.getMergeValues(RetOps, dl); 10070 } 10071 10072 SDValue RetOps[] = { Value, TF }; 10073 return DAG.getMergeValues(RetOps, dl); 10074 } 10075 10076 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10077 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10078 10079 // To lower v4i1 from a byte array, we load the byte elements of the 10080 // vector and then reuse the BUILD_VECTOR logic. 10081 10082 SDValue VectElmts[4], VectElmtChains[4]; 10083 for (unsigned i = 0; i < 4; ++i) { 10084 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10085 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10086 10087 VectElmts[i] = DAG.getExtLoad( 10088 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10089 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10090 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10091 VectElmtChains[i] = VectElmts[i].getValue(1); 10092 } 10093 10094 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10095 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10096 10097 SDValue RVals[] = { Value, LoadChain }; 10098 return DAG.getMergeValues(RVals, dl); 10099 } 10100 10101 /// Lowering for QPX v4i1 stores 10102 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10103 SelectionDAG &DAG) const { 10104 SDLoc dl(Op); 10105 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10106 SDValue StoreChain = SN->getChain(); 10107 SDValue BasePtr = SN->getBasePtr(); 10108 SDValue Value = SN->getValue(); 10109 10110 if (Value.getValueType() == MVT::v4f64 || 10111 Value.getValueType() == MVT::v4f32) { 10112 EVT MemVT = SN->getMemoryVT(); 10113 unsigned Alignment = SN->getAlignment(); 10114 10115 // If this store is properly aligned, then it is legal. 10116 if (Alignment >= MemVT.getStoreSize()) 10117 return Op; 10118 10119 EVT ScalarVT = Value.getValueType().getScalarType(), 10120 ScalarMemVT = MemVT.getScalarType(); 10121 unsigned Stride = ScalarMemVT.getStoreSize(); 10122 10123 SDValue Stores[4]; 10124 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10125 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10126 DAG.getVectorIdxConstant(Idx, dl)); 10127 SDValue Store; 10128 if (ScalarVT != ScalarMemVT) 10129 Store = 10130 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10131 SN->getPointerInfo().getWithOffset(Idx * Stride), 10132 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10133 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10134 else 10135 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10136 SN->getPointerInfo().getWithOffset(Idx * Stride), 10137 MinAlign(Alignment, Idx * Stride), 10138 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10139 10140 if (Idx == 0 && SN->isIndexed()) { 10141 assert(SN->getAddressingMode() == ISD::PRE_INC && 10142 "Unknown addressing mode on vector store"); 10143 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10144 SN->getAddressingMode()); 10145 } 10146 10147 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10148 DAG.getConstant(Stride, dl, 10149 BasePtr.getValueType())); 10150 Stores[Idx] = Store; 10151 } 10152 10153 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10154 10155 if (SN->isIndexed()) { 10156 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10157 return DAG.getMergeValues(RetOps, dl); 10158 } 10159 10160 return TF; 10161 } 10162 10163 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10164 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10165 10166 // The values are now known to be -1 (false) or 1 (true). To convert this 10167 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10168 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10169 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10170 10171 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10172 // understand how to form the extending load. 10173 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10174 10175 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10176 10177 // Now convert to an integer and store. 10178 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10179 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10180 Value); 10181 10182 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10183 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10184 MachinePointerInfo PtrInfo = 10185 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10186 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10187 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10188 10189 SDValue Ops[] = {StoreChain, 10190 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10191 Value, FIdx}; 10192 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10193 10194 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10195 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10196 10197 // Move data into the byte array. 10198 SDValue Loads[4], LoadChains[4]; 10199 for (unsigned i = 0; i < 4; ++i) { 10200 unsigned Offset = 4*i; 10201 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10202 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10203 10204 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10205 PtrInfo.getWithOffset(Offset)); 10206 LoadChains[i] = Loads[i].getValue(1); 10207 } 10208 10209 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10210 10211 SDValue Stores[4]; 10212 for (unsigned i = 0; i < 4; ++i) { 10213 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10214 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10215 10216 Stores[i] = DAG.getTruncStore( 10217 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10218 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10219 SN->getAAInfo()); 10220 } 10221 10222 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10223 10224 return StoreChain; 10225 } 10226 10227 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10228 SDLoc dl(Op); 10229 if (Op.getValueType() == MVT::v4i32) { 10230 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10231 10232 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10233 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10234 10235 SDValue RHSSwap = // = vrlw RHS, 16 10236 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10237 10238 // Shrinkify inputs to v8i16. 10239 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10240 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10241 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10242 10243 // Low parts multiplied together, generating 32-bit results (we ignore the 10244 // top parts). 10245 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10246 LHS, RHS, DAG, dl, MVT::v4i32); 10247 10248 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10249 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10250 // Shift the high parts up 16 bits. 10251 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10252 Neg16, DAG, dl); 10253 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10254 } else if (Op.getValueType() == MVT::v8i16) { 10255 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10256 10257 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10258 10259 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10260 LHS, RHS, Zero, DAG, dl); 10261 } else if (Op.getValueType() == MVT::v16i8) { 10262 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10263 bool isLittleEndian = Subtarget.isLittleEndian(); 10264 10265 // Multiply the even 8-bit parts, producing 16-bit sums. 10266 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10267 LHS, RHS, DAG, dl, MVT::v8i16); 10268 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10269 10270 // Multiply the odd 8-bit parts, producing 16-bit sums. 10271 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10272 LHS, RHS, DAG, dl, MVT::v8i16); 10273 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10274 10275 // Merge the results together. Because vmuleub and vmuloub are 10276 // instructions with a big-endian bias, we must reverse the 10277 // element numbering and reverse the meaning of "odd" and "even" 10278 // when generating little endian code. 10279 int Ops[16]; 10280 for (unsigned i = 0; i != 8; ++i) { 10281 if (isLittleEndian) { 10282 Ops[i*2 ] = 2*i; 10283 Ops[i*2+1] = 2*i+16; 10284 } else { 10285 Ops[i*2 ] = 2*i+1; 10286 Ops[i*2+1] = 2*i+1+16; 10287 } 10288 } 10289 if (isLittleEndian) 10290 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10291 else 10292 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10293 } else { 10294 llvm_unreachable("Unknown mul to lower!"); 10295 } 10296 } 10297 10298 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10299 10300 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10301 10302 EVT VT = Op.getValueType(); 10303 assert(VT.isVector() && 10304 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10305 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10306 VT == MVT::v16i8) && 10307 "Unexpected vector element type!"); 10308 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10309 "Current subtarget doesn't support smax v2i64!"); 10310 10311 // For vector abs, it can be lowered to: 10312 // abs x 10313 // ==> 10314 // y = -x 10315 // smax(x, y) 10316 10317 SDLoc dl(Op); 10318 SDValue X = Op.getOperand(0); 10319 SDValue Zero = DAG.getConstant(0, dl, VT); 10320 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10321 10322 // SMAX patch https://reviews.llvm.org/D47332 10323 // hasn't landed yet, so use intrinsic first here. 10324 // TODO: Should use SMAX directly once SMAX patch landed 10325 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10326 if (VT == MVT::v2i64) 10327 BifID = Intrinsic::ppc_altivec_vmaxsd; 10328 else if (VT == MVT::v8i16) 10329 BifID = Intrinsic::ppc_altivec_vmaxsh; 10330 else if (VT == MVT::v16i8) 10331 BifID = Intrinsic::ppc_altivec_vmaxsb; 10332 10333 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10334 } 10335 10336 // Custom lowering for fpext vf32 to v2f64 10337 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10338 10339 assert(Op.getOpcode() == ISD::FP_EXTEND && 10340 "Should only be called for ISD::FP_EXTEND"); 10341 10342 // We only want to custom lower an extend from v2f32 to v2f64. 10343 if (Op.getValueType() != MVT::v2f64 || 10344 Op.getOperand(0).getValueType() != MVT::v2f32) 10345 return SDValue(); 10346 10347 SDLoc dl(Op); 10348 SDValue Op0 = Op.getOperand(0); 10349 10350 switch (Op0.getOpcode()) { 10351 default: 10352 return SDValue(); 10353 case ISD::EXTRACT_SUBVECTOR: { 10354 assert(Op0.getNumOperands() == 2 && 10355 isa<ConstantSDNode>(Op0->getOperand(1)) && 10356 "Node should have 2 operands with second one being a constant!"); 10357 10358 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10359 return SDValue(); 10360 10361 // Custom lower is only done for high or low doubleword. 10362 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10363 if (Idx % 2 != 0) 10364 return SDValue(); 10365 10366 // Since input is v4f32, at this point Idx is either 0 or 2. 10367 // Shift to get the doubleword position we want. 10368 int DWord = Idx >> 1; 10369 10370 // High and low word positions are different on little endian. 10371 if (Subtarget.isLittleEndian()) 10372 DWord ^= 0x1; 10373 10374 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10375 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10376 } 10377 case ISD::FADD: 10378 case ISD::FMUL: 10379 case ISD::FSUB: { 10380 SDValue NewLoad[2]; 10381 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10382 // Ensure both input are loads. 10383 SDValue LdOp = Op0.getOperand(i); 10384 if (LdOp.getOpcode() != ISD::LOAD) 10385 return SDValue(); 10386 // Generate new load node. 10387 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10388 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10389 NewLoad[i] = DAG.getMemIntrinsicNode( 10390 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10391 LD->getMemoryVT(), LD->getMemOperand()); 10392 } 10393 SDValue NewOp = 10394 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10395 NewLoad[1], Op0.getNode()->getFlags()); 10396 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10397 DAG.getConstant(0, dl, MVT::i32)); 10398 } 10399 case ISD::LOAD: { 10400 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10401 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10402 SDValue NewLd = DAG.getMemIntrinsicNode( 10403 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10404 LD->getMemoryVT(), LD->getMemOperand()); 10405 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10406 DAG.getConstant(0, dl, MVT::i32)); 10407 } 10408 } 10409 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10410 } 10411 10412 /// LowerOperation - Provide custom lowering hooks for some operations. 10413 /// 10414 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10415 switch (Op.getOpcode()) { 10416 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10417 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10418 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10419 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10420 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10421 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10422 case ISD::SETCC: return LowerSETCC(Op, DAG); 10423 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10424 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10425 10426 // Variable argument lowering. 10427 case ISD::VASTART: return LowerVASTART(Op, DAG); 10428 case ISD::VAARG: return LowerVAARG(Op, DAG); 10429 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10430 10431 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10432 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10433 case ISD::GET_DYNAMIC_AREA_OFFSET: 10434 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10435 10436 // Exception handling lowering. 10437 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10438 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10439 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10440 10441 case ISD::LOAD: return LowerLOAD(Op, DAG); 10442 case ISD::STORE: return LowerSTORE(Op, DAG); 10443 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10444 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10445 case ISD::FP_TO_UINT: 10446 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10447 case ISD::UINT_TO_FP: 10448 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10449 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10450 10451 // Lower 64-bit shifts. 10452 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10453 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10454 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10455 10456 // Vector-related lowering. 10457 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10458 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10459 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10460 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10461 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10462 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10463 case ISD::MUL: return LowerMUL(Op, DAG); 10464 case ISD::ABS: return LowerABS(Op, DAG); 10465 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10466 10467 // For counter-based loop handling. 10468 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10469 10470 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10471 10472 // Frame & Return address. 10473 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10474 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10475 10476 case ISD::INTRINSIC_VOID: 10477 return LowerINTRINSIC_VOID(Op, DAG); 10478 case ISD::SREM: 10479 case ISD::UREM: 10480 return LowerREM(Op, DAG); 10481 case ISD::BSWAP: 10482 return LowerBSWAP(Op, DAG); 10483 case ISD::ATOMIC_CMP_SWAP: 10484 return LowerATOMIC_CMP_SWAP(Op, DAG); 10485 } 10486 } 10487 10488 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10489 SmallVectorImpl<SDValue>&Results, 10490 SelectionDAG &DAG) const { 10491 SDLoc dl(N); 10492 switch (N->getOpcode()) { 10493 default: 10494 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10495 case ISD::READCYCLECOUNTER: { 10496 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10497 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10498 10499 Results.push_back(RTB); 10500 Results.push_back(RTB.getValue(1)); 10501 Results.push_back(RTB.getValue(2)); 10502 break; 10503 } 10504 case ISD::INTRINSIC_W_CHAIN: { 10505 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10506 Intrinsic::loop_decrement) 10507 break; 10508 10509 assert(N->getValueType(0) == MVT::i1 && 10510 "Unexpected result type for CTR decrement intrinsic"); 10511 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10512 N->getValueType(0)); 10513 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10514 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10515 N->getOperand(1)); 10516 10517 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10518 Results.push_back(NewInt.getValue(1)); 10519 break; 10520 } 10521 case ISD::VAARG: { 10522 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10523 return; 10524 10525 EVT VT = N->getValueType(0); 10526 10527 if (VT == MVT::i64) { 10528 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10529 10530 Results.push_back(NewNode); 10531 Results.push_back(NewNode.getValue(1)); 10532 } 10533 return; 10534 } 10535 case ISD::FP_TO_SINT: 10536 case ISD::FP_TO_UINT: 10537 // LowerFP_TO_INT() can only handle f32 and f64. 10538 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10539 return; 10540 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10541 return; 10542 case ISD::TRUNCATE: { 10543 EVT TrgVT = N->getValueType(0); 10544 EVT OpVT = N->getOperand(0).getValueType(); 10545 if (TrgVT.isVector() && 10546 isOperationCustom(N->getOpcode(), TrgVT) && 10547 OpVT.getSizeInBits() <= 128 && 10548 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10549 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10550 return; 10551 } 10552 case ISD::BITCAST: 10553 // Don't handle bitcast here. 10554 return; 10555 } 10556 } 10557 10558 //===----------------------------------------------------------------------===// 10559 // Other Lowering Code 10560 //===----------------------------------------------------------------------===// 10561 10562 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10563 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10564 Function *Func = Intrinsic::getDeclaration(M, Id); 10565 return Builder.CreateCall(Func, {}); 10566 } 10567 10568 // The mappings for emitLeading/TrailingFence is taken from 10569 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10570 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10571 Instruction *Inst, 10572 AtomicOrdering Ord) const { 10573 if (Ord == AtomicOrdering::SequentiallyConsistent) 10574 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10575 if (isReleaseOrStronger(Ord)) 10576 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10577 return nullptr; 10578 } 10579 10580 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10581 Instruction *Inst, 10582 AtomicOrdering Ord) const { 10583 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10584 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10585 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10586 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10587 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10588 return Builder.CreateCall( 10589 Intrinsic::getDeclaration( 10590 Builder.GetInsertBlock()->getParent()->getParent(), 10591 Intrinsic::ppc_cfence, {Inst->getType()}), 10592 {Inst}); 10593 // FIXME: Can use isync for rmw operation. 10594 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10595 } 10596 return nullptr; 10597 } 10598 10599 MachineBasicBlock * 10600 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10601 unsigned AtomicSize, 10602 unsigned BinOpcode, 10603 unsigned CmpOpcode, 10604 unsigned CmpPred) const { 10605 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10606 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10607 10608 auto LoadMnemonic = PPC::LDARX; 10609 auto StoreMnemonic = PPC::STDCX; 10610 switch (AtomicSize) { 10611 default: 10612 llvm_unreachable("Unexpected size of atomic entity"); 10613 case 1: 10614 LoadMnemonic = PPC::LBARX; 10615 StoreMnemonic = PPC::STBCX; 10616 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10617 break; 10618 case 2: 10619 LoadMnemonic = PPC::LHARX; 10620 StoreMnemonic = PPC::STHCX; 10621 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10622 break; 10623 case 4: 10624 LoadMnemonic = PPC::LWARX; 10625 StoreMnemonic = PPC::STWCX; 10626 break; 10627 case 8: 10628 LoadMnemonic = PPC::LDARX; 10629 StoreMnemonic = PPC::STDCX; 10630 break; 10631 } 10632 10633 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10634 MachineFunction *F = BB->getParent(); 10635 MachineFunction::iterator It = ++BB->getIterator(); 10636 10637 Register dest = MI.getOperand(0).getReg(); 10638 Register ptrA = MI.getOperand(1).getReg(); 10639 Register ptrB = MI.getOperand(2).getReg(); 10640 Register incr = MI.getOperand(3).getReg(); 10641 DebugLoc dl = MI.getDebugLoc(); 10642 10643 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10644 MachineBasicBlock *loop2MBB = 10645 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10646 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10647 F->insert(It, loopMBB); 10648 if (CmpOpcode) 10649 F->insert(It, loop2MBB); 10650 F->insert(It, exitMBB); 10651 exitMBB->splice(exitMBB->begin(), BB, 10652 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10653 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10654 10655 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10656 Register TmpReg = (!BinOpcode) ? incr : 10657 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10658 : &PPC::GPRCRegClass); 10659 10660 // thisMBB: 10661 // ... 10662 // fallthrough --> loopMBB 10663 BB->addSuccessor(loopMBB); 10664 10665 // loopMBB: 10666 // l[wd]arx dest, ptr 10667 // add r0, dest, incr 10668 // st[wd]cx. r0, ptr 10669 // bne- loopMBB 10670 // fallthrough --> exitMBB 10671 10672 // For max/min... 10673 // loopMBB: 10674 // l[wd]arx dest, ptr 10675 // cmpl?[wd] incr, dest 10676 // bgt exitMBB 10677 // loop2MBB: 10678 // st[wd]cx. dest, ptr 10679 // bne- loopMBB 10680 // fallthrough --> exitMBB 10681 10682 BB = loopMBB; 10683 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10684 .addReg(ptrA).addReg(ptrB); 10685 if (BinOpcode) 10686 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10687 if (CmpOpcode) { 10688 // Signed comparisons of byte or halfword values must be sign-extended. 10689 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10690 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10691 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10692 ExtReg).addReg(dest); 10693 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10694 .addReg(incr).addReg(ExtReg); 10695 } else 10696 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10697 .addReg(incr).addReg(dest); 10698 10699 BuildMI(BB, dl, TII->get(PPC::BCC)) 10700 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10701 BB->addSuccessor(loop2MBB); 10702 BB->addSuccessor(exitMBB); 10703 BB = loop2MBB; 10704 } 10705 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10706 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10707 BuildMI(BB, dl, TII->get(PPC::BCC)) 10708 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10709 BB->addSuccessor(loopMBB); 10710 BB->addSuccessor(exitMBB); 10711 10712 // exitMBB: 10713 // ... 10714 BB = exitMBB; 10715 return BB; 10716 } 10717 10718 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10719 MachineInstr &MI, MachineBasicBlock *BB, 10720 bool is8bit, // operation 10721 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10722 // If we support part-word atomic mnemonics, just use them 10723 if (Subtarget.hasPartwordAtomics()) 10724 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10725 CmpPred); 10726 10727 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10728 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10729 // In 64 bit mode we have to use 64 bits for addresses, even though the 10730 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10731 // registers without caring whether they're 32 or 64, but here we're 10732 // doing actual arithmetic on the addresses. 10733 bool is64bit = Subtarget.isPPC64(); 10734 bool isLittleEndian = Subtarget.isLittleEndian(); 10735 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10736 10737 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10738 MachineFunction *F = BB->getParent(); 10739 MachineFunction::iterator It = ++BB->getIterator(); 10740 10741 Register dest = MI.getOperand(0).getReg(); 10742 Register ptrA = MI.getOperand(1).getReg(); 10743 Register ptrB = MI.getOperand(2).getReg(); 10744 Register incr = MI.getOperand(3).getReg(); 10745 DebugLoc dl = MI.getDebugLoc(); 10746 10747 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10748 MachineBasicBlock *loop2MBB = 10749 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10750 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10751 F->insert(It, loopMBB); 10752 if (CmpOpcode) 10753 F->insert(It, loop2MBB); 10754 F->insert(It, exitMBB); 10755 exitMBB->splice(exitMBB->begin(), BB, 10756 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10757 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10758 10759 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10760 const TargetRegisterClass *RC = 10761 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10762 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10763 10764 Register PtrReg = RegInfo.createVirtualRegister(RC); 10765 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10766 Register ShiftReg = 10767 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10768 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10769 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10770 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10771 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10772 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10773 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10774 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10775 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10776 Register Ptr1Reg; 10777 Register TmpReg = 10778 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10779 10780 // thisMBB: 10781 // ... 10782 // fallthrough --> loopMBB 10783 BB->addSuccessor(loopMBB); 10784 10785 // The 4-byte load must be aligned, while a char or short may be 10786 // anywhere in the word. Hence all this nasty bookkeeping code. 10787 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10788 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10789 // xori shift, shift1, 24 [16] 10790 // rlwinm ptr, ptr1, 0, 0, 29 10791 // slw incr2, incr, shift 10792 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10793 // slw mask, mask2, shift 10794 // loopMBB: 10795 // lwarx tmpDest, ptr 10796 // add tmp, tmpDest, incr2 10797 // andc tmp2, tmpDest, mask 10798 // and tmp3, tmp, mask 10799 // or tmp4, tmp3, tmp2 10800 // stwcx. tmp4, ptr 10801 // bne- loopMBB 10802 // fallthrough --> exitMBB 10803 // srw dest, tmpDest, shift 10804 if (ptrA != ZeroReg) { 10805 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10806 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10807 .addReg(ptrA) 10808 .addReg(ptrB); 10809 } else { 10810 Ptr1Reg = ptrB; 10811 } 10812 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10813 // mode. 10814 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10815 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10816 .addImm(3) 10817 .addImm(27) 10818 .addImm(is8bit ? 28 : 27); 10819 if (!isLittleEndian) 10820 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10821 .addReg(Shift1Reg) 10822 .addImm(is8bit ? 24 : 16); 10823 if (is64bit) 10824 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10825 .addReg(Ptr1Reg) 10826 .addImm(0) 10827 .addImm(61); 10828 else 10829 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10830 .addReg(Ptr1Reg) 10831 .addImm(0) 10832 .addImm(0) 10833 .addImm(29); 10834 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10835 if (is8bit) 10836 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10837 else { 10838 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10839 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10840 .addReg(Mask3Reg) 10841 .addImm(65535); 10842 } 10843 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10844 .addReg(Mask2Reg) 10845 .addReg(ShiftReg); 10846 10847 BB = loopMBB; 10848 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10849 .addReg(ZeroReg) 10850 .addReg(PtrReg); 10851 if (BinOpcode) 10852 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10853 .addReg(Incr2Reg) 10854 .addReg(TmpDestReg); 10855 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10856 .addReg(TmpDestReg) 10857 .addReg(MaskReg); 10858 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10859 if (CmpOpcode) { 10860 // For unsigned comparisons, we can directly compare the shifted values. 10861 // For signed comparisons we shift and sign extend. 10862 Register SReg = RegInfo.createVirtualRegister(GPRC); 10863 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10864 .addReg(TmpDestReg) 10865 .addReg(MaskReg); 10866 unsigned ValueReg = SReg; 10867 unsigned CmpReg = Incr2Reg; 10868 if (CmpOpcode == PPC::CMPW) { 10869 ValueReg = RegInfo.createVirtualRegister(GPRC); 10870 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10871 .addReg(SReg) 10872 .addReg(ShiftReg); 10873 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10874 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10875 .addReg(ValueReg); 10876 ValueReg = ValueSReg; 10877 CmpReg = incr; 10878 } 10879 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10880 .addReg(CmpReg) 10881 .addReg(ValueReg); 10882 BuildMI(BB, dl, TII->get(PPC::BCC)) 10883 .addImm(CmpPred) 10884 .addReg(PPC::CR0) 10885 .addMBB(exitMBB); 10886 BB->addSuccessor(loop2MBB); 10887 BB->addSuccessor(exitMBB); 10888 BB = loop2MBB; 10889 } 10890 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10891 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10892 .addReg(Tmp4Reg) 10893 .addReg(ZeroReg) 10894 .addReg(PtrReg); 10895 BuildMI(BB, dl, TII->get(PPC::BCC)) 10896 .addImm(PPC::PRED_NE) 10897 .addReg(PPC::CR0) 10898 .addMBB(loopMBB); 10899 BB->addSuccessor(loopMBB); 10900 BB->addSuccessor(exitMBB); 10901 10902 // exitMBB: 10903 // ... 10904 BB = exitMBB; 10905 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10906 .addReg(TmpDestReg) 10907 .addReg(ShiftReg); 10908 return BB; 10909 } 10910 10911 llvm::MachineBasicBlock * 10912 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10913 MachineBasicBlock *MBB) const { 10914 DebugLoc DL = MI.getDebugLoc(); 10915 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10916 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10917 10918 MachineFunction *MF = MBB->getParent(); 10919 MachineRegisterInfo &MRI = MF->getRegInfo(); 10920 10921 const BasicBlock *BB = MBB->getBasicBlock(); 10922 MachineFunction::iterator I = ++MBB->getIterator(); 10923 10924 Register DstReg = MI.getOperand(0).getReg(); 10925 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10926 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10927 Register mainDstReg = MRI.createVirtualRegister(RC); 10928 Register restoreDstReg = MRI.createVirtualRegister(RC); 10929 10930 MVT PVT = getPointerTy(MF->getDataLayout()); 10931 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10932 "Invalid Pointer Size!"); 10933 // For v = setjmp(buf), we generate 10934 // 10935 // thisMBB: 10936 // SjLjSetup mainMBB 10937 // bl mainMBB 10938 // v_restore = 1 10939 // b sinkMBB 10940 // 10941 // mainMBB: 10942 // buf[LabelOffset] = LR 10943 // v_main = 0 10944 // 10945 // sinkMBB: 10946 // v = phi(main, restore) 10947 // 10948 10949 MachineBasicBlock *thisMBB = MBB; 10950 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10951 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10952 MF->insert(I, mainMBB); 10953 MF->insert(I, sinkMBB); 10954 10955 MachineInstrBuilder MIB; 10956 10957 // Transfer the remainder of BB and its successor edges to sinkMBB. 10958 sinkMBB->splice(sinkMBB->begin(), MBB, 10959 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10960 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10961 10962 // Note that the structure of the jmp_buf used here is not compatible 10963 // with that used by libc, and is not designed to be. Specifically, it 10964 // stores only those 'reserved' registers that LLVM does not otherwise 10965 // understand how to spill. Also, by convention, by the time this 10966 // intrinsic is called, Clang has already stored the frame address in the 10967 // first slot of the buffer and stack address in the third. Following the 10968 // X86 target code, we'll store the jump address in the second slot. We also 10969 // need to save the TOC pointer (R2) to handle jumps between shared 10970 // libraries, and that will be stored in the fourth slot. The thread 10971 // identifier (R13) is not affected. 10972 10973 // thisMBB: 10974 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10975 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10976 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10977 10978 // Prepare IP either in reg. 10979 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10980 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10981 Register BufReg = MI.getOperand(1).getReg(); 10982 10983 if (Subtarget.is64BitELFABI()) { 10984 setUsesTOCBasePtr(*MBB->getParent()); 10985 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10986 .addReg(PPC::X2) 10987 .addImm(TOCOffset) 10988 .addReg(BufReg) 10989 .cloneMemRefs(MI); 10990 } 10991 10992 // Naked functions never have a base pointer, and so we use r1. For all 10993 // other functions, this decision must be delayed until during PEI. 10994 unsigned BaseReg; 10995 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 10996 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 10997 else 10998 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 10999 11000 MIB = BuildMI(*thisMBB, MI, DL, 11001 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11002 .addReg(BaseReg) 11003 .addImm(BPOffset) 11004 .addReg(BufReg) 11005 .cloneMemRefs(MI); 11006 11007 // Setup 11008 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11009 MIB.addRegMask(TRI->getNoPreservedMask()); 11010 11011 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11012 11013 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11014 .addMBB(mainMBB); 11015 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11016 11017 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11018 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11019 11020 // mainMBB: 11021 // mainDstReg = 0 11022 MIB = 11023 BuildMI(mainMBB, DL, 11024 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11025 11026 // Store IP 11027 if (Subtarget.isPPC64()) { 11028 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11029 .addReg(LabelReg) 11030 .addImm(LabelOffset) 11031 .addReg(BufReg); 11032 } else { 11033 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11034 .addReg(LabelReg) 11035 .addImm(LabelOffset) 11036 .addReg(BufReg); 11037 } 11038 MIB.cloneMemRefs(MI); 11039 11040 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11041 mainMBB->addSuccessor(sinkMBB); 11042 11043 // sinkMBB: 11044 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11045 TII->get(PPC::PHI), DstReg) 11046 .addReg(mainDstReg).addMBB(mainMBB) 11047 .addReg(restoreDstReg).addMBB(thisMBB); 11048 11049 MI.eraseFromParent(); 11050 return sinkMBB; 11051 } 11052 11053 MachineBasicBlock * 11054 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11055 MachineBasicBlock *MBB) const { 11056 DebugLoc DL = MI.getDebugLoc(); 11057 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11058 11059 MachineFunction *MF = MBB->getParent(); 11060 MachineRegisterInfo &MRI = MF->getRegInfo(); 11061 11062 MVT PVT = getPointerTy(MF->getDataLayout()); 11063 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11064 "Invalid Pointer Size!"); 11065 11066 const TargetRegisterClass *RC = 11067 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11068 Register Tmp = MRI.createVirtualRegister(RC); 11069 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11070 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11071 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11072 unsigned BP = 11073 (PVT == MVT::i64) 11074 ? PPC::X30 11075 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11076 : PPC::R30); 11077 11078 MachineInstrBuilder MIB; 11079 11080 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11081 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11082 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11083 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11084 11085 Register BufReg = MI.getOperand(0).getReg(); 11086 11087 // Reload FP (the jumped-to function may not have had a 11088 // frame pointer, and if so, then its r31 will be restored 11089 // as necessary). 11090 if (PVT == MVT::i64) { 11091 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11092 .addImm(0) 11093 .addReg(BufReg); 11094 } else { 11095 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11096 .addImm(0) 11097 .addReg(BufReg); 11098 } 11099 MIB.cloneMemRefs(MI); 11100 11101 // Reload IP 11102 if (PVT == MVT::i64) { 11103 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11104 .addImm(LabelOffset) 11105 .addReg(BufReg); 11106 } else { 11107 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11108 .addImm(LabelOffset) 11109 .addReg(BufReg); 11110 } 11111 MIB.cloneMemRefs(MI); 11112 11113 // Reload SP 11114 if (PVT == MVT::i64) { 11115 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11116 .addImm(SPOffset) 11117 .addReg(BufReg); 11118 } else { 11119 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11120 .addImm(SPOffset) 11121 .addReg(BufReg); 11122 } 11123 MIB.cloneMemRefs(MI); 11124 11125 // Reload BP 11126 if (PVT == MVT::i64) { 11127 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11128 .addImm(BPOffset) 11129 .addReg(BufReg); 11130 } else { 11131 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11132 .addImm(BPOffset) 11133 .addReg(BufReg); 11134 } 11135 MIB.cloneMemRefs(MI); 11136 11137 // Reload TOC 11138 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11139 setUsesTOCBasePtr(*MBB->getParent()); 11140 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11141 .addImm(TOCOffset) 11142 .addReg(BufReg) 11143 .cloneMemRefs(MI); 11144 } 11145 11146 // Jump 11147 BuildMI(*MBB, MI, DL, 11148 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11149 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11150 11151 MI.eraseFromParent(); 11152 return MBB; 11153 } 11154 11155 MachineBasicBlock * 11156 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11157 MachineBasicBlock *BB) const { 11158 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11159 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11160 if (Subtarget.is64BitELFABI() && 11161 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11162 // Call lowering should have added an r2 operand to indicate a dependence 11163 // on the TOC base pointer value. It can't however, because there is no 11164 // way to mark the dependence as implicit there, and so the stackmap code 11165 // will confuse it with a regular operand. Instead, add the dependence 11166 // here. 11167 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11168 } 11169 11170 return emitPatchPoint(MI, BB); 11171 } 11172 11173 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11174 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11175 return emitEHSjLjSetJmp(MI, BB); 11176 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11177 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11178 return emitEHSjLjLongJmp(MI, BB); 11179 } 11180 11181 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11182 11183 // To "insert" these instructions we actually have to insert their 11184 // control-flow patterns. 11185 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11186 MachineFunction::iterator It = ++BB->getIterator(); 11187 11188 MachineFunction *F = BB->getParent(); 11189 11190 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11191 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11192 MI.getOpcode() == PPC::SELECT_I8) { 11193 SmallVector<MachineOperand, 2> Cond; 11194 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11195 MI.getOpcode() == PPC::SELECT_CC_I8) 11196 Cond.push_back(MI.getOperand(4)); 11197 else 11198 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11199 Cond.push_back(MI.getOperand(1)); 11200 11201 DebugLoc dl = MI.getDebugLoc(); 11202 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11203 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11204 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11205 MI.getOpcode() == PPC::SELECT_CC_F8 || 11206 MI.getOpcode() == PPC::SELECT_CC_F16 || 11207 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11208 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11209 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11210 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11211 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11212 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11213 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11214 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11215 MI.getOpcode() == PPC::SELECT_CC_SPE || 11216 MI.getOpcode() == PPC::SELECT_F4 || 11217 MI.getOpcode() == PPC::SELECT_F8 || 11218 MI.getOpcode() == PPC::SELECT_F16 || 11219 MI.getOpcode() == PPC::SELECT_QFRC || 11220 MI.getOpcode() == PPC::SELECT_QSRC || 11221 MI.getOpcode() == PPC::SELECT_QBRC || 11222 MI.getOpcode() == PPC::SELECT_SPE || 11223 MI.getOpcode() == PPC::SELECT_SPE4 || 11224 MI.getOpcode() == PPC::SELECT_VRRC || 11225 MI.getOpcode() == PPC::SELECT_VSFRC || 11226 MI.getOpcode() == PPC::SELECT_VSSRC || 11227 MI.getOpcode() == PPC::SELECT_VSRC) { 11228 // The incoming instruction knows the destination vreg to set, the 11229 // condition code register to branch on, the true/false values to 11230 // select between, and a branch opcode to use. 11231 11232 // thisMBB: 11233 // ... 11234 // TrueVal = ... 11235 // cmpTY ccX, r1, r2 11236 // bCC copy1MBB 11237 // fallthrough --> copy0MBB 11238 MachineBasicBlock *thisMBB = BB; 11239 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11240 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11241 DebugLoc dl = MI.getDebugLoc(); 11242 F->insert(It, copy0MBB); 11243 F->insert(It, sinkMBB); 11244 11245 // Transfer the remainder of BB and its successor edges to sinkMBB. 11246 sinkMBB->splice(sinkMBB->begin(), BB, 11247 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11248 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11249 11250 // Next, add the true and fallthrough blocks as its successors. 11251 BB->addSuccessor(copy0MBB); 11252 BB->addSuccessor(sinkMBB); 11253 11254 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11255 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11256 MI.getOpcode() == PPC::SELECT_F16 || 11257 MI.getOpcode() == PPC::SELECT_SPE4 || 11258 MI.getOpcode() == PPC::SELECT_SPE || 11259 MI.getOpcode() == PPC::SELECT_QFRC || 11260 MI.getOpcode() == PPC::SELECT_QSRC || 11261 MI.getOpcode() == PPC::SELECT_QBRC || 11262 MI.getOpcode() == PPC::SELECT_VRRC || 11263 MI.getOpcode() == PPC::SELECT_VSFRC || 11264 MI.getOpcode() == PPC::SELECT_VSSRC || 11265 MI.getOpcode() == PPC::SELECT_VSRC) { 11266 BuildMI(BB, dl, TII->get(PPC::BC)) 11267 .addReg(MI.getOperand(1).getReg()) 11268 .addMBB(sinkMBB); 11269 } else { 11270 unsigned SelectPred = MI.getOperand(4).getImm(); 11271 BuildMI(BB, dl, TII->get(PPC::BCC)) 11272 .addImm(SelectPred) 11273 .addReg(MI.getOperand(1).getReg()) 11274 .addMBB(sinkMBB); 11275 } 11276 11277 // copy0MBB: 11278 // %FalseValue = ... 11279 // # fallthrough to sinkMBB 11280 BB = copy0MBB; 11281 11282 // Update machine-CFG edges 11283 BB->addSuccessor(sinkMBB); 11284 11285 // sinkMBB: 11286 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11287 // ... 11288 BB = sinkMBB; 11289 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11290 .addReg(MI.getOperand(3).getReg()) 11291 .addMBB(copy0MBB) 11292 .addReg(MI.getOperand(2).getReg()) 11293 .addMBB(thisMBB); 11294 } else if (MI.getOpcode() == PPC::ReadTB) { 11295 // To read the 64-bit time-base register on a 32-bit target, we read the 11296 // two halves. Should the counter have wrapped while it was being read, we 11297 // need to try again. 11298 // ... 11299 // readLoop: 11300 // mfspr Rx,TBU # load from TBU 11301 // mfspr Ry,TB # load from TB 11302 // mfspr Rz,TBU # load from TBU 11303 // cmpw crX,Rx,Rz # check if 'old'='new' 11304 // bne readLoop # branch if they're not equal 11305 // ... 11306 11307 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11308 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11309 DebugLoc dl = MI.getDebugLoc(); 11310 F->insert(It, readMBB); 11311 F->insert(It, sinkMBB); 11312 11313 // Transfer the remainder of BB and its successor edges to sinkMBB. 11314 sinkMBB->splice(sinkMBB->begin(), BB, 11315 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11316 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11317 11318 BB->addSuccessor(readMBB); 11319 BB = readMBB; 11320 11321 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11322 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11323 Register LoReg = MI.getOperand(0).getReg(); 11324 Register HiReg = MI.getOperand(1).getReg(); 11325 11326 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11327 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11328 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11329 11330 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11331 11332 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11333 .addReg(HiReg) 11334 .addReg(ReadAgainReg); 11335 BuildMI(BB, dl, TII->get(PPC::BCC)) 11336 .addImm(PPC::PRED_NE) 11337 .addReg(CmpReg) 11338 .addMBB(readMBB); 11339 11340 BB->addSuccessor(readMBB); 11341 BB->addSuccessor(sinkMBB); 11342 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11343 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11344 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11345 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11346 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11347 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11349 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11350 11351 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11352 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11353 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11354 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11355 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11356 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11357 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11358 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11359 11360 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11361 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11362 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11363 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11364 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11365 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11366 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11367 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11368 11369 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11370 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11371 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11372 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11373 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11374 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11375 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11376 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11377 11378 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11379 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11380 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11381 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11382 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11383 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11384 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11385 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11386 11387 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11388 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11389 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11390 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11391 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11392 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11393 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11394 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11395 11396 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11397 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11398 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11399 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11400 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11401 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11402 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11403 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11404 11405 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11406 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11407 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11408 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11409 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11410 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11411 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11412 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11413 11414 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11415 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11416 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11417 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11418 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11419 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11420 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11421 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11422 11423 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11424 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11425 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11426 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11427 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11428 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11429 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11430 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11431 11432 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11433 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11434 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11435 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11436 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11437 BB = EmitAtomicBinary(MI, BB, 4, 0); 11438 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11439 BB = EmitAtomicBinary(MI, BB, 8, 0); 11440 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11441 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11442 (Subtarget.hasPartwordAtomics() && 11443 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11444 (Subtarget.hasPartwordAtomics() && 11445 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11446 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11447 11448 auto LoadMnemonic = PPC::LDARX; 11449 auto StoreMnemonic = PPC::STDCX; 11450 switch (MI.getOpcode()) { 11451 default: 11452 llvm_unreachable("Compare and swap of unknown size"); 11453 case PPC::ATOMIC_CMP_SWAP_I8: 11454 LoadMnemonic = PPC::LBARX; 11455 StoreMnemonic = PPC::STBCX; 11456 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11457 break; 11458 case PPC::ATOMIC_CMP_SWAP_I16: 11459 LoadMnemonic = PPC::LHARX; 11460 StoreMnemonic = PPC::STHCX; 11461 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11462 break; 11463 case PPC::ATOMIC_CMP_SWAP_I32: 11464 LoadMnemonic = PPC::LWARX; 11465 StoreMnemonic = PPC::STWCX; 11466 break; 11467 case PPC::ATOMIC_CMP_SWAP_I64: 11468 LoadMnemonic = PPC::LDARX; 11469 StoreMnemonic = PPC::STDCX; 11470 break; 11471 } 11472 Register dest = MI.getOperand(0).getReg(); 11473 Register ptrA = MI.getOperand(1).getReg(); 11474 Register ptrB = MI.getOperand(2).getReg(); 11475 Register oldval = MI.getOperand(3).getReg(); 11476 Register newval = MI.getOperand(4).getReg(); 11477 DebugLoc dl = MI.getDebugLoc(); 11478 11479 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11480 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11481 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11482 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11483 F->insert(It, loop1MBB); 11484 F->insert(It, loop2MBB); 11485 F->insert(It, midMBB); 11486 F->insert(It, exitMBB); 11487 exitMBB->splice(exitMBB->begin(), BB, 11488 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11489 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11490 11491 // thisMBB: 11492 // ... 11493 // fallthrough --> loopMBB 11494 BB->addSuccessor(loop1MBB); 11495 11496 // loop1MBB: 11497 // l[bhwd]arx dest, ptr 11498 // cmp[wd] dest, oldval 11499 // bne- midMBB 11500 // loop2MBB: 11501 // st[bhwd]cx. newval, ptr 11502 // bne- loopMBB 11503 // b exitBB 11504 // midMBB: 11505 // st[bhwd]cx. dest, ptr 11506 // exitBB: 11507 BB = loop1MBB; 11508 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11509 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11510 .addReg(oldval) 11511 .addReg(dest); 11512 BuildMI(BB, dl, TII->get(PPC::BCC)) 11513 .addImm(PPC::PRED_NE) 11514 .addReg(PPC::CR0) 11515 .addMBB(midMBB); 11516 BB->addSuccessor(loop2MBB); 11517 BB->addSuccessor(midMBB); 11518 11519 BB = loop2MBB; 11520 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11521 .addReg(newval) 11522 .addReg(ptrA) 11523 .addReg(ptrB); 11524 BuildMI(BB, dl, TII->get(PPC::BCC)) 11525 .addImm(PPC::PRED_NE) 11526 .addReg(PPC::CR0) 11527 .addMBB(loop1MBB); 11528 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11529 BB->addSuccessor(loop1MBB); 11530 BB->addSuccessor(exitMBB); 11531 11532 BB = midMBB; 11533 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11534 .addReg(dest) 11535 .addReg(ptrA) 11536 .addReg(ptrB); 11537 BB->addSuccessor(exitMBB); 11538 11539 // exitMBB: 11540 // ... 11541 BB = exitMBB; 11542 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11543 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11544 // We must use 64-bit registers for addresses when targeting 64-bit, 11545 // since we're actually doing arithmetic on them. Other registers 11546 // can be 32-bit. 11547 bool is64bit = Subtarget.isPPC64(); 11548 bool isLittleEndian = Subtarget.isLittleEndian(); 11549 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11550 11551 Register dest = MI.getOperand(0).getReg(); 11552 Register ptrA = MI.getOperand(1).getReg(); 11553 Register ptrB = MI.getOperand(2).getReg(); 11554 Register oldval = MI.getOperand(3).getReg(); 11555 Register newval = MI.getOperand(4).getReg(); 11556 DebugLoc dl = MI.getDebugLoc(); 11557 11558 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11559 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11560 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11561 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11562 F->insert(It, loop1MBB); 11563 F->insert(It, loop2MBB); 11564 F->insert(It, midMBB); 11565 F->insert(It, exitMBB); 11566 exitMBB->splice(exitMBB->begin(), BB, 11567 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11568 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11569 11570 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11571 const TargetRegisterClass *RC = 11572 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11573 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11574 11575 Register PtrReg = RegInfo.createVirtualRegister(RC); 11576 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11577 Register ShiftReg = 11578 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11579 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11580 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11581 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11582 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11583 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11584 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11585 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11586 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11587 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11588 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11589 Register Ptr1Reg; 11590 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11591 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11592 // thisMBB: 11593 // ... 11594 // fallthrough --> loopMBB 11595 BB->addSuccessor(loop1MBB); 11596 11597 // The 4-byte load must be aligned, while a char or short may be 11598 // anywhere in the word. Hence all this nasty bookkeeping code. 11599 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11600 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11601 // xori shift, shift1, 24 [16] 11602 // rlwinm ptr, ptr1, 0, 0, 29 11603 // slw newval2, newval, shift 11604 // slw oldval2, oldval,shift 11605 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11606 // slw mask, mask2, shift 11607 // and newval3, newval2, mask 11608 // and oldval3, oldval2, mask 11609 // loop1MBB: 11610 // lwarx tmpDest, ptr 11611 // and tmp, tmpDest, mask 11612 // cmpw tmp, oldval3 11613 // bne- midMBB 11614 // loop2MBB: 11615 // andc tmp2, tmpDest, mask 11616 // or tmp4, tmp2, newval3 11617 // stwcx. tmp4, ptr 11618 // bne- loop1MBB 11619 // b exitBB 11620 // midMBB: 11621 // stwcx. tmpDest, ptr 11622 // exitBB: 11623 // srw dest, tmpDest, shift 11624 if (ptrA != ZeroReg) { 11625 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11626 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11627 .addReg(ptrA) 11628 .addReg(ptrB); 11629 } else { 11630 Ptr1Reg = ptrB; 11631 } 11632 11633 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11634 // mode. 11635 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11636 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11637 .addImm(3) 11638 .addImm(27) 11639 .addImm(is8bit ? 28 : 27); 11640 if (!isLittleEndian) 11641 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11642 .addReg(Shift1Reg) 11643 .addImm(is8bit ? 24 : 16); 11644 if (is64bit) 11645 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11646 .addReg(Ptr1Reg) 11647 .addImm(0) 11648 .addImm(61); 11649 else 11650 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11651 .addReg(Ptr1Reg) 11652 .addImm(0) 11653 .addImm(0) 11654 .addImm(29); 11655 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11656 .addReg(newval) 11657 .addReg(ShiftReg); 11658 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11659 .addReg(oldval) 11660 .addReg(ShiftReg); 11661 if (is8bit) 11662 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11663 else { 11664 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11665 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11666 .addReg(Mask3Reg) 11667 .addImm(65535); 11668 } 11669 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11670 .addReg(Mask2Reg) 11671 .addReg(ShiftReg); 11672 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11673 .addReg(NewVal2Reg) 11674 .addReg(MaskReg); 11675 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11676 .addReg(OldVal2Reg) 11677 .addReg(MaskReg); 11678 11679 BB = loop1MBB; 11680 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11681 .addReg(ZeroReg) 11682 .addReg(PtrReg); 11683 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11684 .addReg(TmpDestReg) 11685 .addReg(MaskReg); 11686 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11687 .addReg(TmpReg) 11688 .addReg(OldVal3Reg); 11689 BuildMI(BB, dl, TII->get(PPC::BCC)) 11690 .addImm(PPC::PRED_NE) 11691 .addReg(PPC::CR0) 11692 .addMBB(midMBB); 11693 BB->addSuccessor(loop2MBB); 11694 BB->addSuccessor(midMBB); 11695 11696 BB = loop2MBB; 11697 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11698 .addReg(TmpDestReg) 11699 .addReg(MaskReg); 11700 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11701 .addReg(Tmp2Reg) 11702 .addReg(NewVal3Reg); 11703 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11704 .addReg(Tmp4Reg) 11705 .addReg(ZeroReg) 11706 .addReg(PtrReg); 11707 BuildMI(BB, dl, TII->get(PPC::BCC)) 11708 .addImm(PPC::PRED_NE) 11709 .addReg(PPC::CR0) 11710 .addMBB(loop1MBB); 11711 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11712 BB->addSuccessor(loop1MBB); 11713 BB->addSuccessor(exitMBB); 11714 11715 BB = midMBB; 11716 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11717 .addReg(TmpDestReg) 11718 .addReg(ZeroReg) 11719 .addReg(PtrReg); 11720 BB->addSuccessor(exitMBB); 11721 11722 // exitMBB: 11723 // ... 11724 BB = exitMBB; 11725 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11726 .addReg(TmpReg) 11727 .addReg(ShiftReg); 11728 } else if (MI.getOpcode() == PPC::FADDrtz) { 11729 // This pseudo performs an FADD with rounding mode temporarily forced 11730 // to round-to-zero. We emit this via custom inserter since the FPSCR 11731 // is not modeled at the SelectionDAG level. 11732 Register Dest = MI.getOperand(0).getReg(); 11733 Register Src1 = MI.getOperand(1).getReg(); 11734 Register Src2 = MI.getOperand(2).getReg(); 11735 DebugLoc dl = MI.getDebugLoc(); 11736 11737 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11738 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11739 11740 // Save FPSCR value. 11741 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11742 11743 // Set rounding mode to round-to-zero. 11744 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11745 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11746 11747 // Perform addition. 11748 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11749 11750 // Restore FPSCR value. 11751 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11752 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11753 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11754 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11755 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11756 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11757 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11758 ? PPC::ANDI8_rec 11759 : PPC::ANDI_rec; 11760 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11761 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11762 11763 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11764 Register Dest = RegInfo.createVirtualRegister( 11765 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11766 11767 DebugLoc Dl = MI.getDebugLoc(); 11768 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11769 .addReg(MI.getOperand(1).getReg()) 11770 .addImm(1); 11771 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11772 MI.getOperand(0).getReg()) 11773 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11774 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11775 DebugLoc Dl = MI.getDebugLoc(); 11776 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11777 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11778 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11779 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11780 MI.getOperand(0).getReg()) 11781 .addReg(CRReg); 11782 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11783 DebugLoc Dl = MI.getDebugLoc(); 11784 unsigned Imm = MI.getOperand(1).getImm(); 11785 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11786 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11787 MI.getOperand(0).getReg()) 11788 .addReg(PPC::CR0EQ); 11789 } else if (MI.getOpcode() == PPC::SETRNDi) { 11790 DebugLoc dl = MI.getDebugLoc(); 11791 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11792 11793 // Save FPSCR value. 11794 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11795 11796 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11797 // the following settings: 11798 // 00 Round to nearest 11799 // 01 Round to 0 11800 // 10 Round to +inf 11801 // 11 Round to -inf 11802 11803 // When the operand is immediate, using the two least significant bits of 11804 // the immediate to set the bits 62:63 of FPSCR. 11805 unsigned Mode = MI.getOperand(1).getImm(); 11806 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11807 .addImm(31); 11808 11809 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11810 .addImm(30); 11811 } else if (MI.getOpcode() == PPC::SETRND) { 11812 DebugLoc dl = MI.getDebugLoc(); 11813 11814 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11815 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11816 // If the target doesn't have DirectMove, we should use stack to do the 11817 // conversion, because the target doesn't have the instructions like mtvsrd 11818 // or mfvsrd to do this conversion directly. 11819 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11820 if (Subtarget.hasDirectMove()) { 11821 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11822 .addReg(SrcReg); 11823 } else { 11824 // Use stack to do the register copy. 11825 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11826 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11827 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11828 if (RC == &PPC::F8RCRegClass) { 11829 // Copy register from F8RCRegClass to G8RCRegclass. 11830 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11831 "Unsupported RegClass."); 11832 11833 StoreOp = PPC::STFD; 11834 LoadOp = PPC::LD; 11835 } else { 11836 // Copy register from G8RCRegClass to F8RCRegclass. 11837 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11838 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11839 "Unsupported RegClass."); 11840 } 11841 11842 MachineFrameInfo &MFI = F->getFrameInfo(); 11843 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11844 11845 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11846 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11847 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11848 MFI.getObjectAlignment(FrameIdx)); 11849 11850 // Store the SrcReg into the stack. 11851 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11852 .addReg(SrcReg) 11853 .addImm(0) 11854 .addFrameIndex(FrameIdx) 11855 .addMemOperand(MMOStore); 11856 11857 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11858 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11859 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11860 MFI.getObjectAlignment(FrameIdx)); 11861 11862 // Load from the stack where SrcReg is stored, and save to DestReg, 11863 // so we have done the RegClass conversion from RegClass::SrcReg to 11864 // RegClass::DestReg. 11865 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11866 .addImm(0) 11867 .addFrameIndex(FrameIdx) 11868 .addMemOperand(MMOLoad); 11869 } 11870 }; 11871 11872 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11873 11874 // Save FPSCR value. 11875 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11876 11877 // When the operand is gprc register, use two least significant bits of the 11878 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11879 // 11880 // copy OldFPSCRTmpReg, OldFPSCRReg 11881 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11882 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11883 // copy NewFPSCRReg, NewFPSCRTmpReg 11884 // mtfsf 255, NewFPSCRReg 11885 MachineOperand SrcOp = MI.getOperand(1); 11886 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11887 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11888 11889 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11890 11891 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11892 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11893 11894 // The first operand of INSERT_SUBREG should be a register which has 11895 // subregisters, we only care about its RegClass, so we should use an 11896 // IMPLICIT_DEF register. 11897 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11898 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11899 .addReg(ImDefReg) 11900 .add(SrcOp) 11901 .addImm(1); 11902 11903 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11904 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11905 .addReg(OldFPSCRTmpReg) 11906 .addReg(ExtSrcReg) 11907 .addImm(0) 11908 .addImm(62); 11909 11910 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11911 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11912 11913 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11914 // bits of FPSCR. 11915 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11916 .addImm(255) 11917 .addReg(NewFPSCRReg) 11918 .addImm(0) 11919 .addImm(0); 11920 } else { 11921 llvm_unreachable("Unexpected instr type to insert"); 11922 } 11923 11924 MI.eraseFromParent(); // The pseudo instruction is gone now. 11925 return BB; 11926 } 11927 11928 //===----------------------------------------------------------------------===// 11929 // Target Optimization Hooks 11930 //===----------------------------------------------------------------------===// 11931 11932 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11933 // For the estimates, convergence is quadratic, so we essentially double the 11934 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11935 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11936 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11937 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11938 if (VT.getScalarType() == MVT::f64) 11939 RefinementSteps++; 11940 return RefinementSteps; 11941 } 11942 11943 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11944 int Enabled, int &RefinementSteps, 11945 bool &UseOneConstNR, 11946 bool Reciprocal) const { 11947 EVT VT = Operand.getValueType(); 11948 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11949 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11950 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11951 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11952 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11953 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11954 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11955 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11956 11957 // The Newton-Raphson computation with a single constant does not provide 11958 // enough accuracy on some CPUs. 11959 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11960 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11961 } 11962 return SDValue(); 11963 } 11964 11965 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11966 int Enabled, 11967 int &RefinementSteps) const { 11968 EVT VT = Operand.getValueType(); 11969 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11970 (VT == MVT::f64 && Subtarget.hasFRE()) || 11971 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11972 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11973 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11974 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11975 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11976 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11977 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11978 } 11979 return SDValue(); 11980 } 11981 11982 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11983 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11984 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11985 // enabled for division), this functionality is redundant with the default 11986 // combiner logic (once the division -> reciprocal/multiply transformation 11987 // has taken place). As a result, this matters more for older cores than for 11988 // newer ones. 11989 11990 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11991 // reciprocal if there are two or more FDIVs (for embedded cores with only 11992 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11993 switch (Subtarget.getCPUDirective()) { 11994 default: 11995 return 3; 11996 case PPC::DIR_440: 11997 case PPC::DIR_A2: 11998 case PPC::DIR_E500: 11999 case PPC::DIR_E500mc: 12000 case PPC::DIR_E5500: 12001 return 2; 12002 } 12003 } 12004 12005 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12006 // collapsed, and so we need to look through chains of them. 12007 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12008 int64_t& Offset, SelectionDAG &DAG) { 12009 if (DAG.isBaseWithConstantOffset(Loc)) { 12010 Base = Loc.getOperand(0); 12011 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12012 12013 // The base might itself be a base plus an offset, and if so, accumulate 12014 // that as well. 12015 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12016 } 12017 } 12018 12019 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12020 unsigned Bytes, int Dist, 12021 SelectionDAG &DAG) { 12022 if (VT.getSizeInBits() / 8 != Bytes) 12023 return false; 12024 12025 SDValue BaseLoc = Base->getBasePtr(); 12026 if (Loc.getOpcode() == ISD::FrameIndex) { 12027 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12028 return false; 12029 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12030 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12031 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12032 int FS = MFI.getObjectSize(FI); 12033 int BFS = MFI.getObjectSize(BFI); 12034 if (FS != BFS || FS != (int)Bytes) return false; 12035 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12036 } 12037 12038 SDValue Base1 = Loc, Base2 = BaseLoc; 12039 int64_t Offset1 = 0, Offset2 = 0; 12040 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12041 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12042 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12043 return true; 12044 12045 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12046 const GlobalValue *GV1 = nullptr; 12047 const GlobalValue *GV2 = nullptr; 12048 Offset1 = 0; 12049 Offset2 = 0; 12050 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12051 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12052 if (isGA1 && isGA2 && GV1 == GV2) 12053 return Offset1 == (Offset2 + Dist*Bytes); 12054 return false; 12055 } 12056 12057 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12058 // not enforce equality of the chain operands. 12059 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12060 unsigned Bytes, int Dist, 12061 SelectionDAG &DAG) { 12062 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12063 EVT VT = LS->getMemoryVT(); 12064 SDValue Loc = LS->getBasePtr(); 12065 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12066 } 12067 12068 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12069 EVT VT; 12070 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12071 default: return false; 12072 case Intrinsic::ppc_qpx_qvlfd: 12073 case Intrinsic::ppc_qpx_qvlfda: 12074 VT = MVT::v4f64; 12075 break; 12076 case Intrinsic::ppc_qpx_qvlfs: 12077 case Intrinsic::ppc_qpx_qvlfsa: 12078 VT = MVT::v4f32; 12079 break; 12080 case Intrinsic::ppc_qpx_qvlfcd: 12081 case Intrinsic::ppc_qpx_qvlfcda: 12082 VT = MVT::v2f64; 12083 break; 12084 case Intrinsic::ppc_qpx_qvlfcs: 12085 case Intrinsic::ppc_qpx_qvlfcsa: 12086 VT = MVT::v2f32; 12087 break; 12088 case Intrinsic::ppc_qpx_qvlfiwa: 12089 case Intrinsic::ppc_qpx_qvlfiwz: 12090 case Intrinsic::ppc_altivec_lvx: 12091 case Intrinsic::ppc_altivec_lvxl: 12092 case Intrinsic::ppc_vsx_lxvw4x: 12093 case Intrinsic::ppc_vsx_lxvw4x_be: 12094 VT = MVT::v4i32; 12095 break; 12096 case Intrinsic::ppc_vsx_lxvd2x: 12097 case Intrinsic::ppc_vsx_lxvd2x_be: 12098 VT = MVT::v2f64; 12099 break; 12100 case Intrinsic::ppc_altivec_lvebx: 12101 VT = MVT::i8; 12102 break; 12103 case Intrinsic::ppc_altivec_lvehx: 12104 VT = MVT::i16; 12105 break; 12106 case Intrinsic::ppc_altivec_lvewx: 12107 VT = MVT::i32; 12108 break; 12109 } 12110 12111 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12112 } 12113 12114 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12115 EVT VT; 12116 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12117 default: return false; 12118 case Intrinsic::ppc_qpx_qvstfd: 12119 case Intrinsic::ppc_qpx_qvstfda: 12120 VT = MVT::v4f64; 12121 break; 12122 case Intrinsic::ppc_qpx_qvstfs: 12123 case Intrinsic::ppc_qpx_qvstfsa: 12124 VT = MVT::v4f32; 12125 break; 12126 case Intrinsic::ppc_qpx_qvstfcd: 12127 case Intrinsic::ppc_qpx_qvstfcda: 12128 VT = MVT::v2f64; 12129 break; 12130 case Intrinsic::ppc_qpx_qvstfcs: 12131 case Intrinsic::ppc_qpx_qvstfcsa: 12132 VT = MVT::v2f32; 12133 break; 12134 case Intrinsic::ppc_qpx_qvstfiw: 12135 case Intrinsic::ppc_qpx_qvstfiwa: 12136 case Intrinsic::ppc_altivec_stvx: 12137 case Intrinsic::ppc_altivec_stvxl: 12138 case Intrinsic::ppc_vsx_stxvw4x: 12139 VT = MVT::v4i32; 12140 break; 12141 case Intrinsic::ppc_vsx_stxvd2x: 12142 VT = MVT::v2f64; 12143 break; 12144 case Intrinsic::ppc_vsx_stxvw4x_be: 12145 VT = MVT::v4i32; 12146 break; 12147 case Intrinsic::ppc_vsx_stxvd2x_be: 12148 VT = MVT::v2f64; 12149 break; 12150 case Intrinsic::ppc_altivec_stvebx: 12151 VT = MVT::i8; 12152 break; 12153 case Intrinsic::ppc_altivec_stvehx: 12154 VT = MVT::i16; 12155 break; 12156 case Intrinsic::ppc_altivec_stvewx: 12157 VT = MVT::i32; 12158 break; 12159 } 12160 12161 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12162 } 12163 12164 return false; 12165 } 12166 12167 // Return true is there is a nearyby consecutive load to the one provided 12168 // (regardless of alignment). We search up and down the chain, looking though 12169 // token factors and other loads (but nothing else). As a result, a true result 12170 // indicates that it is safe to create a new consecutive load adjacent to the 12171 // load provided. 12172 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12173 SDValue Chain = LD->getChain(); 12174 EVT VT = LD->getMemoryVT(); 12175 12176 SmallSet<SDNode *, 16> LoadRoots; 12177 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12178 SmallSet<SDNode *, 16> Visited; 12179 12180 // First, search up the chain, branching to follow all token-factor operands. 12181 // If we find a consecutive load, then we're done, otherwise, record all 12182 // nodes just above the top-level loads and token factors. 12183 while (!Queue.empty()) { 12184 SDNode *ChainNext = Queue.pop_back_val(); 12185 if (!Visited.insert(ChainNext).second) 12186 continue; 12187 12188 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12189 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12190 return true; 12191 12192 if (!Visited.count(ChainLD->getChain().getNode())) 12193 Queue.push_back(ChainLD->getChain().getNode()); 12194 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12195 for (const SDUse &O : ChainNext->ops()) 12196 if (!Visited.count(O.getNode())) 12197 Queue.push_back(O.getNode()); 12198 } else 12199 LoadRoots.insert(ChainNext); 12200 } 12201 12202 // Second, search down the chain, starting from the top-level nodes recorded 12203 // in the first phase. These top-level nodes are the nodes just above all 12204 // loads and token factors. Starting with their uses, recursively look though 12205 // all loads (just the chain uses) and token factors to find a consecutive 12206 // load. 12207 Visited.clear(); 12208 Queue.clear(); 12209 12210 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12211 IE = LoadRoots.end(); I != IE; ++I) { 12212 Queue.push_back(*I); 12213 12214 while (!Queue.empty()) { 12215 SDNode *LoadRoot = Queue.pop_back_val(); 12216 if (!Visited.insert(LoadRoot).second) 12217 continue; 12218 12219 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12220 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12221 return true; 12222 12223 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12224 UE = LoadRoot->use_end(); UI != UE; ++UI) 12225 if (((isa<MemSDNode>(*UI) && 12226 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12227 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12228 Queue.push_back(*UI); 12229 } 12230 } 12231 12232 return false; 12233 } 12234 12235 /// This function is called when we have proved that a SETCC node can be replaced 12236 /// by subtraction (and other supporting instructions) so that the result of 12237 /// comparison is kept in a GPR instead of CR. This function is purely for 12238 /// codegen purposes and has some flags to guide the codegen process. 12239 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12240 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12241 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12242 12243 // Zero extend the operands to the largest legal integer. Originally, they 12244 // must be of a strictly smaller size. 12245 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12246 DAG.getConstant(Size, DL, MVT::i32)); 12247 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12248 DAG.getConstant(Size, DL, MVT::i32)); 12249 12250 // Swap if needed. Depends on the condition code. 12251 if (Swap) 12252 std::swap(Op0, Op1); 12253 12254 // Subtract extended integers. 12255 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12256 12257 // Move the sign bit to the least significant position and zero out the rest. 12258 // Now the least significant bit carries the result of original comparison. 12259 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12260 DAG.getConstant(Size - 1, DL, MVT::i32)); 12261 auto Final = Shifted; 12262 12263 // Complement the result if needed. Based on the condition code. 12264 if (Complement) 12265 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12266 DAG.getConstant(1, DL, MVT::i64)); 12267 12268 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12269 } 12270 12271 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12272 DAGCombinerInfo &DCI) const { 12273 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12274 12275 SelectionDAG &DAG = DCI.DAG; 12276 SDLoc DL(N); 12277 12278 // Size of integers being compared has a critical role in the following 12279 // analysis, so we prefer to do this when all types are legal. 12280 if (!DCI.isAfterLegalizeDAG()) 12281 return SDValue(); 12282 12283 // If all users of SETCC extend its value to a legal integer type 12284 // then we replace SETCC with a subtraction 12285 for (SDNode::use_iterator UI = N->use_begin(), 12286 UE = N->use_end(); UI != UE; ++UI) { 12287 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12288 return SDValue(); 12289 } 12290 12291 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12292 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12293 12294 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12295 12296 if (OpSize < Size) { 12297 switch (CC) { 12298 default: break; 12299 case ISD::SETULT: 12300 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12301 case ISD::SETULE: 12302 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12303 case ISD::SETUGT: 12304 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12305 case ISD::SETUGE: 12306 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12307 } 12308 } 12309 12310 return SDValue(); 12311 } 12312 12313 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12314 DAGCombinerInfo &DCI) const { 12315 SelectionDAG &DAG = DCI.DAG; 12316 SDLoc dl(N); 12317 12318 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12319 // If we're tracking CR bits, we need to be careful that we don't have: 12320 // trunc(binary-ops(zext(x), zext(y))) 12321 // or 12322 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12323 // such that we're unnecessarily moving things into GPRs when it would be 12324 // better to keep them in CR bits. 12325 12326 // Note that trunc here can be an actual i1 trunc, or can be the effective 12327 // truncation that comes from a setcc or select_cc. 12328 if (N->getOpcode() == ISD::TRUNCATE && 12329 N->getValueType(0) != MVT::i1) 12330 return SDValue(); 12331 12332 if (N->getOperand(0).getValueType() != MVT::i32 && 12333 N->getOperand(0).getValueType() != MVT::i64) 12334 return SDValue(); 12335 12336 if (N->getOpcode() == ISD::SETCC || 12337 N->getOpcode() == ISD::SELECT_CC) { 12338 // If we're looking at a comparison, then we need to make sure that the 12339 // high bits (all except for the first) don't matter the result. 12340 ISD::CondCode CC = 12341 cast<CondCodeSDNode>(N->getOperand( 12342 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12343 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12344 12345 if (ISD::isSignedIntSetCC(CC)) { 12346 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12347 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12348 return SDValue(); 12349 } else if (ISD::isUnsignedIntSetCC(CC)) { 12350 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12351 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12352 !DAG.MaskedValueIsZero(N->getOperand(1), 12353 APInt::getHighBitsSet(OpBits, OpBits-1))) 12354 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12355 : SDValue()); 12356 } else { 12357 // This is neither a signed nor an unsigned comparison, just make sure 12358 // that the high bits are equal. 12359 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12360 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12361 12362 // We don't really care about what is known about the first bit (if 12363 // anything), so clear it in all masks prior to comparing them. 12364 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12365 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12366 12367 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12368 return SDValue(); 12369 } 12370 } 12371 12372 // We now know that the higher-order bits are irrelevant, we just need to 12373 // make sure that all of the intermediate operations are bit operations, and 12374 // all inputs are extensions. 12375 if (N->getOperand(0).getOpcode() != ISD::AND && 12376 N->getOperand(0).getOpcode() != ISD::OR && 12377 N->getOperand(0).getOpcode() != ISD::XOR && 12378 N->getOperand(0).getOpcode() != ISD::SELECT && 12379 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12380 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12381 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12382 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12383 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12384 return SDValue(); 12385 12386 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12387 N->getOperand(1).getOpcode() != ISD::AND && 12388 N->getOperand(1).getOpcode() != ISD::OR && 12389 N->getOperand(1).getOpcode() != ISD::XOR && 12390 N->getOperand(1).getOpcode() != ISD::SELECT && 12391 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12392 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12393 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12394 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12395 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12396 return SDValue(); 12397 12398 SmallVector<SDValue, 4> Inputs; 12399 SmallVector<SDValue, 8> BinOps, PromOps; 12400 SmallPtrSet<SDNode *, 16> Visited; 12401 12402 for (unsigned i = 0; i < 2; ++i) { 12403 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12404 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12405 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12406 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12407 isa<ConstantSDNode>(N->getOperand(i))) 12408 Inputs.push_back(N->getOperand(i)); 12409 else 12410 BinOps.push_back(N->getOperand(i)); 12411 12412 if (N->getOpcode() == ISD::TRUNCATE) 12413 break; 12414 } 12415 12416 // Visit all inputs, collect all binary operations (and, or, xor and 12417 // select) that are all fed by extensions. 12418 while (!BinOps.empty()) { 12419 SDValue BinOp = BinOps.back(); 12420 BinOps.pop_back(); 12421 12422 if (!Visited.insert(BinOp.getNode()).second) 12423 continue; 12424 12425 PromOps.push_back(BinOp); 12426 12427 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12428 // The condition of the select is not promoted. 12429 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12430 continue; 12431 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12432 continue; 12433 12434 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12435 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12436 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12437 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12438 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12439 Inputs.push_back(BinOp.getOperand(i)); 12440 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12441 BinOp.getOperand(i).getOpcode() == ISD::OR || 12442 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12443 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12444 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12445 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12446 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12447 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12448 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12449 BinOps.push_back(BinOp.getOperand(i)); 12450 } else { 12451 // We have an input that is not an extension or another binary 12452 // operation; we'll abort this transformation. 12453 return SDValue(); 12454 } 12455 } 12456 } 12457 12458 // Make sure that this is a self-contained cluster of operations (which 12459 // is not quite the same thing as saying that everything has only one 12460 // use). 12461 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12462 if (isa<ConstantSDNode>(Inputs[i])) 12463 continue; 12464 12465 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12466 UE = Inputs[i].getNode()->use_end(); 12467 UI != UE; ++UI) { 12468 SDNode *User = *UI; 12469 if (User != N && !Visited.count(User)) 12470 return SDValue(); 12471 12472 // Make sure that we're not going to promote the non-output-value 12473 // operand(s) or SELECT or SELECT_CC. 12474 // FIXME: Although we could sometimes handle this, and it does occur in 12475 // practice that one of the condition inputs to the select is also one of 12476 // the outputs, we currently can't deal with this. 12477 if (User->getOpcode() == ISD::SELECT) { 12478 if (User->getOperand(0) == Inputs[i]) 12479 return SDValue(); 12480 } else if (User->getOpcode() == ISD::SELECT_CC) { 12481 if (User->getOperand(0) == Inputs[i] || 12482 User->getOperand(1) == Inputs[i]) 12483 return SDValue(); 12484 } 12485 } 12486 } 12487 12488 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12489 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12490 UE = PromOps[i].getNode()->use_end(); 12491 UI != UE; ++UI) { 12492 SDNode *User = *UI; 12493 if (User != N && !Visited.count(User)) 12494 return SDValue(); 12495 12496 // Make sure that we're not going to promote the non-output-value 12497 // operand(s) or SELECT or SELECT_CC. 12498 // FIXME: Although we could sometimes handle this, and it does occur in 12499 // practice that one of the condition inputs to the select is also one of 12500 // the outputs, we currently can't deal with this. 12501 if (User->getOpcode() == ISD::SELECT) { 12502 if (User->getOperand(0) == PromOps[i]) 12503 return SDValue(); 12504 } else if (User->getOpcode() == ISD::SELECT_CC) { 12505 if (User->getOperand(0) == PromOps[i] || 12506 User->getOperand(1) == PromOps[i]) 12507 return SDValue(); 12508 } 12509 } 12510 } 12511 12512 // Replace all inputs with the extension operand. 12513 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12514 // Constants may have users outside the cluster of to-be-promoted nodes, 12515 // and so we need to replace those as we do the promotions. 12516 if (isa<ConstantSDNode>(Inputs[i])) 12517 continue; 12518 else 12519 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12520 } 12521 12522 std::list<HandleSDNode> PromOpHandles; 12523 for (auto &PromOp : PromOps) 12524 PromOpHandles.emplace_back(PromOp); 12525 12526 // Replace all operations (these are all the same, but have a different 12527 // (i1) return type). DAG.getNode will validate that the types of 12528 // a binary operator match, so go through the list in reverse so that 12529 // we've likely promoted both operands first. Any intermediate truncations or 12530 // extensions disappear. 12531 while (!PromOpHandles.empty()) { 12532 SDValue PromOp = PromOpHandles.back().getValue(); 12533 PromOpHandles.pop_back(); 12534 12535 if (PromOp.getOpcode() == ISD::TRUNCATE || 12536 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12537 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12538 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12539 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12540 PromOp.getOperand(0).getValueType() != MVT::i1) { 12541 // The operand is not yet ready (see comment below). 12542 PromOpHandles.emplace_front(PromOp); 12543 continue; 12544 } 12545 12546 SDValue RepValue = PromOp.getOperand(0); 12547 if (isa<ConstantSDNode>(RepValue)) 12548 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12549 12550 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12551 continue; 12552 } 12553 12554 unsigned C; 12555 switch (PromOp.getOpcode()) { 12556 default: C = 0; break; 12557 case ISD::SELECT: C = 1; break; 12558 case ISD::SELECT_CC: C = 2; break; 12559 } 12560 12561 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12562 PromOp.getOperand(C).getValueType() != MVT::i1) || 12563 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12564 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12565 // The to-be-promoted operands of this node have not yet been 12566 // promoted (this should be rare because we're going through the 12567 // list backward, but if one of the operands has several users in 12568 // this cluster of to-be-promoted nodes, it is possible). 12569 PromOpHandles.emplace_front(PromOp); 12570 continue; 12571 } 12572 12573 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12574 PromOp.getNode()->op_end()); 12575 12576 // If there are any constant inputs, make sure they're replaced now. 12577 for (unsigned i = 0; i < 2; ++i) 12578 if (isa<ConstantSDNode>(Ops[C+i])) 12579 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12580 12581 DAG.ReplaceAllUsesOfValueWith(PromOp, 12582 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12583 } 12584 12585 // Now we're left with the initial truncation itself. 12586 if (N->getOpcode() == ISD::TRUNCATE) 12587 return N->getOperand(0); 12588 12589 // Otherwise, this is a comparison. The operands to be compared have just 12590 // changed type (to i1), but everything else is the same. 12591 return SDValue(N, 0); 12592 } 12593 12594 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12595 DAGCombinerInfo &DCI) const { 12596 SelectionDAG &DAG = DCI.DAG; 12597 SDLoc dl(N); 12598 12599 // If we're tracking CR bits, we need to be careful that we don't have: 12600 // zext(binary-ops(trunc(x), trunc(y))) 12601 // or 12602 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12603 // such that we're unnecessarily moving things into CR bits that can more 12604 // efficiently stay in GPRs. Note that if we're not certain that the high 12605 // bits are set as required by the final extension, we still may need to do 12606 // some masking to get the proper behavior. 12607 12608 // This same functionality is important on PPC64 when dealing with 12609 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12610 // the return values of functions. Because it is so similar, it is handled 12611 // here as well. 12612 12613 if (N->getValueType(0) != MVT::i32 && 12614 N->getValueType(0) != MVT::i64) 12615 return SDValue(); 12616 12617 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12618 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12619 return SDValue(); 12620 12621 if (N->getOperand(0).getOpcode() != ISD::AND && 12622 N->getOperand(0).getOpcode() != ISD::OR && 12623 N->getOperand(0).getOpcode() != ISD::XOR && 12624 N->getOperand(0).getOpcode() != ISD::SELECT && 12625 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12626 return SDValue(); 12627 12628 SmallVector<SDValue, 4> Inputs; 12629 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12630 SmallPtrSet<SDNode *, 16> Visited; 12631 12632 // Visit all inputs, collect all binary operations (and, or, xor and 12633 // select) that are all fed by truncations. 12634 while (!BinOps.empty()) { 12635 SDValue BinOp = BinOps.back(); 12636 BinOps.pop_back(); 12637 12638 if (!Visited.insert(BinOp.getNode()).second) 12639 continue; 12640 12641 PromOps.push_back(BinOp); 12642 12643 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12644 // The condition of the select is not promoted. 12645 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12646 continue; 12647 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12648 continue; 12649 12650 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12651 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12652 Inputs.push_back(BinOp.getOperand(i)); 12653 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12654 BinOp.getOperand(i).getOpcode() == ISD::OR || 12655 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12656 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12657 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12658 BinOps.push_back(BinOp.getOperand(i)); 12659 } else { 12660 // We have an input that is not a truncation or another binary 12661 // operation; we'll abort this transformation. 12662 return SDValue(); 12663 } 12664 } 12665 } 12666 12667 // The operands of a select that must be truncated when the select is 12668 // promoted because the operand is actually part of the to-be-promoted set. 12669 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12670 12671 // Make sure that this is a self-contained cluster of operations (which 12672 // is not quite the same thing as saying that everything has only one 12673 // use). 12674 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12675 if (isa<ConstantSDNode>(Inputs[i])) 12676 continue; 12677 12678 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12679 UE = Inputs[i].getNode()->use_end(); 12680 UI != UE; ++UI) { 12681 SDNode *User = *UI; 12682 if (User != N && !Visited.count(User)) 12683 return SDValue(); 12684 12685 // If we're going to promote the non-output-value operand(s) or SELECT or 12686 // SELECT_CC, record them for truncation. 12687 if (User->getOpcode() == ISD::SELECT) { 12688 if (User->getOperand(0) == Inputs[i]) 12689 SelectTruncOp[0].insert(std::make_pair(User, 12690 User->getOperand(0).getValueType())); 12691 } else if (User->getOpcode() == ISD::SELECT_CC) { 12692 if (User->getOperand(0) == Inputs[i]) 12693 SelectTruncOp[0].insert(std::make_pair(User, 12694 User->getOperand(0).getValueType())); 12695 if (User->getOperand(1) == Inputs[i]) 12696 SelectTruncOp[1].insert(std::make_pair(User, 12697 User->getOperand(1).getValueType())); 12698 } 12699 } 12700 } 12701 12702 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12703 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12704 UE = PromOps[i].getNode()->use_end(); 12705 UI != UE; ++UI) { 12706 SDNode *User = *UI; 12707 if (User != N && !Visited.count(User)) 12708 return SDValue(); 12709 12710 // If we're going to promote the non-output-value operand(s) or SELECT or 12711 // SELECT_CC, record them for truncation. 12712 if (User->getOpcode() == ISD::SELECT) { 12713 if (User->getOperand(0) == PromOps[i]) 12714 SelectTruncOp[0].insert(std::make_pair(User, 12715 User->getOperand(0).getValueType())); 12716 } else if (User->getOpcode() == ISD::SELECT_CC) { 12717 if (User->getOperand(0) == PromOps[i]) 12718 SelectTruncOp[0].insert(std::make_pair(User, 12719 User->getOperand(0).getValueType())); 12720 if (User->getOperand(1) == PromOps[i]) 12721 SelectTruncOp[1].insert(std::make_pair(User, 12722 User->getOperand(1).getValueType())); 12723 } 12724 } 12725 } 12726 12727 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12728 bool ReallyNeedsExt = false; 12729 if (N->getOpcode() != ISD::ANY_EXTEND) { 12730 // If all of the inputs are not already sign/zero extended, then 12731 // we'll still need to do that at the end. 12732 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12733 if (isa<ConstantSDNode>(Inputs[i])) 12734 continue; 12735 12736 unsigned OpBits = 12737 Inputs[i].getOperand(0).getValueSizeInBits(); 12738 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12739 12740 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12741 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12742 APInt::getHighBitsSet(OpBits, 12743 OpBits-PromBits))) || 12744 (N->getOpcode() == ISD::SIGN_EXTEND && 12745 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12746 (OpBits-(PromBits-1)))) { 12747 ReallyNeedsExt = true; 12748 break; 12749 } 12750 } 12751 } 12752 12753 // Replace all inputs, either with the truncation operand, or a 12754 // truncation or extension to the final output type. 12755 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12756 // Constant inputs need to be replaced with the to-be-promoted nodes that 12757 // use them because they might have users outside of the cluster of 12758 // promoted nodes. 12759 if (isa<ConstantSDNode>(Inputs[i])) 12760 continue; 12761 12762 SDValue InSrc = Inputs[i].getOperand(0); 12763 if (Inputs[i].getValueType() == N->getValueType(0)) 12764 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12765 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12766 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12767 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12768 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12769 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12770 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12771 else 12772 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12773 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12774 } 12775 12776 std::list<HandleSDNode> PromOpHandles; 12777 for (auto &PromOp : PromOps) 12778 PromOpHandles.emplace_back(PromOp); 12779 12780 // Replace all operations (these are all the same, but have a different 12781 // (promoted) return type). DAG.getNode will validate that the types of 12782 // a binary operator match, so go through the list in reverse so that 12783 // we've likely promoted both operands first. 12784 while (!PromOpHandles.empty()) { 12785 SDValue PromOp = PromOpHandles.back().getValue(); 12786 PromOpHandles.pop_back(); 12787 12788 unsigned C; 12789 switch (PromOp.getOpcode()) { 12790 default: C = 0; break; 12791 case ISD::SELECT: C = 1; break; 12792 case ISD::SELECT_CC: C = 2; break; 12793 } 12794 12795 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12796 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12797 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12798 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12799 // The to-be-promoted operands of this node have not yet been 12800 // promoted (this should be rare because we're going through the 12801 // list backward, but if one of the operands has several users in 12802 // this cluster of to-be-promoted nodes, it is possible). 12803 PromOpHandles.emplace_front(PromOp); 12804 continue; 12805 } 12806 12807 // For SELECT and SELECT_CC nodes, we do a similar check for any 12808 // to-be-promoted comparison inputs. 12809 if (PromOp.getOpcode() == ISD::SELECT || 12810 PromOp.getOpcode() == ISD::SELECT_CC) { 12811 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12812 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12813 (SelectTruncOp[1].count(PromOp.getNode()) && 12814 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12815 PromOpHandles.emplace_front(PromOp); 12816 continue; 12817 } 12818 } 12819 12820 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12821 PromOp.getNode()->op_end()); 12822 12823 // If this node has constant inputs, then they'll need to be promoted here. 12824 for (unsigned i = 0; i < 2; ++i) { 12825 if (!isa<ConstantSDNode>(Ops[C+i])) 12826 continue; 12827 if (Ops[C+i].getValueType() == N->getValueType(0)) 12828 continue; 12829 12830 if (N->getOpcode() == ISD::SIGN_EXTEND) 12831 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12832 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12833 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12834 else 12835 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12836 } 12837 12838 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12839 // truncate them again to the original value type. 12840 if (PromOp.getOpcode() == ISD::SELECT || 12841 PromOp.getOpcode() == ISD::SELECT_CC) { 12842 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12843 if (SI0 != SelectTruncOp[0].end()) 12844 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12845 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12846 if (SI1 != SelectTruncOp[1].end()) 12847 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12848 } 12849 12850 DAG.ReplaceAllUsesOfValueWith(PromOp, 12851 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12852 } 12853 12854 // Now we're left with the initial extension itself. 12855 if (!ReallyNeedsExt) 12856 return N->getOperand(0); 12857 12858 // To zero extend, just mask off everything except for the first bit (in the 12859 // i1 case). 12860 if (N->getOpcode() == ISD::ZERO_EXTEND) 12861 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12862 DAG.getConstant(APInt::getLowBitsSet( 12863 N->getValueSizeInBits(0), PromBits), 12864 dl, N->getValueType(0))); 12865 12866 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12867 "Invalid extension type"); 12868 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12869 SDValue ShiftCst = 12870 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12871 return DAG.getNode( 12872 ISD::SRA, dl, N->getValueType(0), 12873 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12874 ShiftCst); 12875 } 12876 12877 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12878 DAGCombinerInfo &DCI) const { 12879 assert(N->getOpcode() == ISD::SETCC && 12880 "Should be called with a SETCC node"); 12881 12882 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12883 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12884 SDValue LHS = N->getOperand(0); 12885 SDValue RHS = N->getOperand(1); 12886 12887 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12888 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12889 LHS.hasOneUse()) 12890 std::swap(LHS, RHS); 12891 12892 // x == 0-y --> x+y == 0 12893 // x != 0-y --> x+y != 0 12894 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12895 RHS.hasOneUse()) { 12896 SDLoc DL(N); 12897 SelectionDAG &DAG = DCI.DAG; 12898 EVT VT = N->getValueType(0); 12899 EVT OpVT = LHS.getValueType(); 12900 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12901 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12902 } 12903 } 12904 12905 return DAGCombineTruncBoolExt(N, DCI); 12906 } 12907 12908 // Is this an extending load from an f32 to an f64? 12909 static bool isFPExtLoad(SDValue Op) { 12910 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12911 return LD->getExtensionType() == ISD::EXTLOAD && 12912 Op.getValueType() == MVT::f64; 12913 return false; 12914 } 12915 12916 /// Reduces the number of fp-to-int conversion when building a vector. 12917 /// 12918 /// If this vector is built out of floating to integer conversions, 12919 /// transform it to a vector built out of floating point values followed by a 12920 /// single floating to integer conversion of the vector. 12921 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12922 /// becomes (fptosi (build_vector ($A, $B, ...))) 12923 SDValue PPCTargetLowering:: 12924 combineElementTruncationToVectorTruncation(SDNode *N, 12925 DAGCombinerInfo &DCI) const { 12926 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12927 "Should be called with a BUILD_VECTOR node"); 12928 12929 SelectionDAG &DAG = DCI.DAG; 12930 SDLoc dl(N); 12931 12932 SDValue FirstInput = N->getOperand(0); 12933 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12934 "The input operand must be an fp-to-int conversion."); 12935 12936 // This combine happens after legalization so the fp_to_[su]i nodes are 12937 // already converted to PPCSISD nodes. 12938 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12939 if (FirstConversion == PPCISD::FCTIDZ || 12940 FirstConversion == PPCISD::FCTIDUZ || 12941 FirstConversion == PPCISD::FCTIWZ || 12942 FirstConversion == PPCISD::FCTIWUZ) { 12943 bool IsSplat = true; 12944 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12945 FirstConversion == PPCISD::FCTIWUZ; 12946 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12947 SmallVector<SDValue, 4> Ops; 12948 EVT TargetVT = N->getValueType(0); 12949 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12950 SDValue NextOp = N->getOperand(i); 12951 if (NextOp.getOpcode() != PPCISD::MFVSR) 12952 return SDValue(); 12953 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12954 if (NextConversion != FirstConversion) 12955 return SDValue(); 12956 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12957 // This is not valid if the input was originally double precision. It is 12958 // also not profitable to do unless this is an extending load in which 12959 // case doing this combine will allow us to combine consecutive loads. 12960 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12961 return SDValue(); 12962 if (N->getOperand(i) != FirstInput) 12963 IsSplat = false; 12964 } 12965 12966 // If this is a splat, we leave it as-is since there will be only a single 12967 // fp-to-int conversion followed by a splat of the integer. This is better 12968 // for 32-bit and smaller ints and neutral for 64-bit ints. 12969 if (IsSplat) 12970 return SDValue(); 12971 12972 // Now that we know we have the right type of node, get its operands 12973 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12974 SDValue In = N->getOperand(i).getOperand(0); 12975 if (Is32Bit) { 12976 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12977 // here, we know that all inputs are extending loads so this is safe). 12978 if (In.isUndef()) 12979 Ops.push_back(DAG.getUNDEF(SrcVT)); 12980 else { 12981 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12982 MVT::f32, In.getOperand(0), 12983 DAG.getIntPtrConstant(1, dl)); 12984 Ops.push_back(Trunc); 12985 } 12986 } else 12987 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12988 } 12989 12990 unsigned Opcode; 12991 if (FirstConversion == PPCISD::FCTIDZ || 12992 FirstConversion == PPCISD::FCTIWZ) 12993 Opcode = ISD::FP_TO_SINT; 12994 else 12995 Opcode = ISD::FP_TO_UINT; 12996 12997 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 12998 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 12999 return DAG.getNode(Opcode, dl, TargetVT, BV); 13000 } 13001 return SDValue(); 13002 } 13003 13004 /// Reduce the number of loads when building a vector. 13005 /// 13006 /// Building a vector out of multiple loads can be converted to a load 13007 /// of the vector type if the loads are consecutive. If the loads are 13008 /// consecutive but in descending order, a shuffle is added at the end 13009 /// to reorder the vector. 13010 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13011 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13012 "Should be called with a BUILD_VECTOR node"); 13013 13014 SDLoc dl(N); 13015 13016 // Return early for non byte-sized type, as they can't be consecutive. 13017 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13018 return SDValue(); 13019 13020 bool InputsAreConsecutiveLoads = true; 13021 bool InputsAreReverseConsecutive = true; 13022 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13023 SDValue FirstInput = N->getOperand(0); 13024 bool IsRoundOfExtLoad = false; 13025 13026 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13027 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13028 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13029 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13030 } 13031 // Not a build vector of (possibly fp_rounded) loads. 13032 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13033 N->getNumOperands() == 1) 13034 return SDValue(); 13035 13036 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13037 // If any inputs are fp_round(extload), they all must be. 13038 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13039 return SDValue(); 13040 13041 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13042 N->getOperand(i); 13043 if (NextInput.getOpcode() != ISD::LOAD) 13044 return SDValue(); 13045 13046 SDValue PreviousInput = 13047 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13048 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13049 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13050 13051 // If any inputs are fp_round(extload), they all must be. 13052 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13053 return SDValue(); 13054 13055 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13056 InputsAreConsecutiveLoads = false; 13057 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13058 InputsAreReverseConsecutive = false; 13059 13060 // Exit early if the loads are neither consecutive nor reverse consecutive. 13061 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13062 return SDValue(); 13063 } 13064 13065 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13066 "The loads cannot be both consecutive and reverse consecutive."); 13067 13068 SDValue FirstLoadOp = 13069 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13070 SDValue LastLoadOp = 13071 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13072 N->getOperand(N->getNumOperands()-1); 13073 13074 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13075 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13076 if (InputsAreConsecutiveLoads) { 13077 assert(LD1 && "Input needs to be a LoadSDNode."); 13078 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13079 LD1->getBasePtr(), LD1->getPointerInfo(), 13080 LD1->getAlignment()); 13081 } 13082 if (InputsAreReverseConsecutive) { 13083 assert(LDL && "Input needs to be a LoadSDNode."); 13084 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13085 LDL->getBasePtr(), LDL->getPointerInfo(), 13086 LDL->getAlignment()); 13087 SmallVector<int, 16> Ops; 13088 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13089 Ops.push_back(i); 13090 13091 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13092 DAG.getUNDEF(N->getValueType(0)), Ops); 13093 } 13094 return SDValue(); 13095 } 13096 13097 // This function adds the required vector_shuffle needed to get 13098 // the elements of the vector extract in the correct position 13099 // as specified by the CorrectElems encoding. 13100 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13101 SDValue Input, uint64_t Elems, 13102 uint64_t CorrectElems) { 13103 SDLoc dl(N); 13104 13105 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13106 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13107 13108 // Knowing the element indices being extracted from the original 13109 // vector and the order in which they're being inserted, just put 13110 // them at element indices required for the instruction. 13111 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13112 if (DAG.getDataLayout().isLittleEndian()) 13113 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13114 else 13115 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13116 CorrectElems = CorrectElems >> 8; 13117 Elems = Elems >> 8; 13118 } 13119 13120 SDValue Shuffle = 13121 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13122 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13123 13124 EVT Ty = N->getValueType(0); 13125 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13126 return BV; 13127 } 13128 13129 // Look for build vector patterns where input operands come from sign 13130 // extended vector_extract elements of specific indices. If the correct indices 13131 // aren't used, add a vector shuffle to fix up the indices and create a new 13132 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13133 // during instruction selection. 13134 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13135 // This array encodes the indices that the vector sign extend instructions 13136 // extract from when extending from one type to another for both BE and LE. 13137 // The right nibble of each byte corresponds to the LE incides. 13138 // and the left nibble of each byte corresponds to the BE incides. 13139 // For example: 0x3074B8FC byte->word 13140 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13141 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13142 // For example: 0x000070F8 byte->double word 13143 // For LE: the allowed indices are: 0x0,0x8 13144 // For BE: the allowed indices are: 0x7,0xF 13145 uint64_t TargetElems[] = { 13146 0x3074B8FC, // b->w 13147 0x000070F8, // b->d 13148 0x10325476, // h->w 13149 0x00003074, // h->d 13150 0x00001032, // w->d 13151 }; 13152 13153 uint64_t Elems = 0; 13154 int Index; 13155 SDValue Input; 13156 13157 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13158 if (!Op) 13159 return false; 13160 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13161 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13162 return false; 13163 13164 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13165 // of the right width. 13166 SDValue Extract = Op.getOperand(0); 13167 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13168 Extract = Extract.getOperand(0); 13169 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13170 return false; 13171 13172 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13173 if (!ExtOp) 13174 return false; 13175 13176 Index = ExtOp->getZExtValue(); 13177 if (Input && Input != Extract.getOperand(0)) 13178 return false; 13179 13180 if (!Input) 13181 Input = Extract.getOperand(0); 13182 13183 Elems = Elems << 8; 13184 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13185 Elems |= Index; 13186 13187 return true; 13188 }; 13189 13190 // If the build vector operands aren't sign extended vector extracts, 13191 // of the same input vector, then return. 13192 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13193 if (!isSExtOfVecExtract(N->getOperand(i))) { 13194 return SDValue(); 13195 } 13196 } 13197 13198 // If the vector extract indicies are not correct, add the appropriate 13199 // vector_shuffle. 13200 int TgtElemArrayIdx; 13201 int InputSize = Input.getValueType().getScalarSizeInBits(); 13202 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13203 if (InputSize + OutputSize == 40) 13204 TgtElemArrayIdx = 0; 13205 else if (InputSize + OutputSize == 72) 13206 TgtElemArrayIdx = 1; 13207 else if (InputSize + OutputSize == 48) 13208 TgtElemArrayIdx = 2; 13209 else if (InputSize + OutputSize == 80) 13210 TgtElemArrayIdx = 3; 13211 else if (InputSize + OutputSize == 96) 13212 TgtElemArrayIdx = 4; 13213 else 13214 return SDValue(); 13215 13216 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13217 CorrectElems = DAG.getDataLayout().isLittleEndian() 13218 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13219 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13220 if (Elems != CorrectElems) { 13221 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13222 } 13223 13224 // Regular lowering will catch cases where a shuffle is not needed. 13225 return SDValue(); 13226 } 13227 13228 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13229 DAGCombinerInfo &DCI) const { 13230 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13231 "Should be called with a BUILD_VECTOR node"); 13232 13233 SelectionDAG &DAG = DCI.DAG; 13234 SDLoc dl(N); 13235 13236 if (!Subtarget.hasVSX()) 13237 return SDValue(); 13238 13239 // The target independent DAG combiner will leave a build_vector of 13240 // float-to-int conversions intact. We can generate MUCH better code for 13241 // a float-to-int conversion of a vector of floats. 13242 SDValue FirstInput = N->getOperand(0); 13243 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13244 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13245 if (Reduced) 13246 return Reduced; 13247 } 13248 13249 // If we're building a vector out of consecutive loads, just load that 13250 // vector type. 13251 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13252 if (Reduced) 13253 return Reduced; 13254 13255 // If we're building a vector out of extended elements from another vector 13256 // we have P9 vector integer extend instructions. The code assumes legal 13257 // input types (i.e. it can't handle things like v4i16) so do not run before 13258 // legalization. 13259 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13260 Reduced = combineBVOfVecSExt(N, DAG); 13261 if (Reduced) 13262 return Reduced; 13263 } 13264 13265 13266 if (N->getValueType(0) != MVT::v2f64) 13267 return SDValue(); 13268 13269 // Looking for: 13270 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13271 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13272 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13273 return SDValue(); 13274 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13275 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13276 return SDValue(); 13277 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13278 return SDValue(); 13279 13280 SDValue Ext1 = FirstInput.getOperand(0); 13281 SDValue Ext2 = N->getOperand(1).getOperand(0); 13282 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13283 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13284 return SDValue(); 13285 13286 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13287 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13288 if (!Ext1Op || !Ext2Op) 13289 return SDValue(); 13290 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13291 Ext1.getOperand(0) != Ext2.getOperand(0)) 13292 return SDValue(); 13293 13294 int FirstElem = Ext1Op->getZExtValue(); 13295 int SecondElem = Ext2Op->getZExtValue(); 13296 int SubvecIdx; 13297 if (FirstElem == 0 && SecondElem == 1) 13298 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13299 else if (FirstElem == 2 && SecondElem == 3) 13300 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13301 else 13302 return SDValue(); 13303 13304 SDValue SrcVec = Ext1.getOperand(0); 13305 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13306 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13307 return DAG.getNode(NodeType, dl, MVT::v2f64, 13308 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13309 } 13310 13311 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13312 DAGCombinerInfo &DCI) const { 13313 assert((N->getOpcode() == ISD::SINT_TO_FP || 13314 N->getOpcode() == ISD::UINT_TO_FP) && 13315 "Need an int -> FP conversion node here"); 13316 13317 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13318 return SDValue(); 13319 13320 SelectionDAG &DAG = DCI.DAG; 13321 SDLoc dl(N); 13322 SDValue Op(N, 0); 13323 13324 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13325 // from the hardware. 13326 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13327 return SDValue(); 13328 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13329 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13330 return SDValue(); 13331 13332 SDValue FirstOperand(Op.getOperand(0)); 13333 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13334 (FirstOperand.getValueType() == MVT::i8 || 13335 FirstOperand.getValueType() == MVT::i16); 13336 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13337 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13338 bool DstDouble = Op.getValueType() == MVT::f64; 13339 unsigned ConvOp = Signed ? 13340 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13341 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13342 SDValue WidthConst = 13343 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13344 dl, false); 13345 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13346 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13347 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13348 DAG.getVTList(MVT::f64, MVT::Other), 13349 Ops, MVT::i8, LDN->getMemOperand()); 13350 13351 // For signed conversion, we need to sign-extend the value in the VSR 13352 if (Signed) { 13353 SDValue ExtOps[] = { Ld, WidthConst }; 13354 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13355 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13356 } else 13357 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13358 } 13359 13360 13361 // For i32 intermediate values, unfortunately, the conversion functions 13362 // leave the upper 32 bits of the value are undefined. Within the set of 13363 // scalar instructions, we have no method for zero- or sign-extending the 13364 // value. Thus, we cannot handle i32 intermediate values here. 13365 if (Op.getOperand(0).getValueType() == MVT::i32) 13366 return SDValue(); 13367 13368 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13369 "UINT_TO_FP is supported only with FPCVT"); 13370 13371 // If we have FCFIDS, then use it when converting to single-precision. 13372 // Otherwise, convert to double-precision and then round. 13373 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13374 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13375 : PPCISD::FCFIDS) 13376 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13377 : PPCISD::FCFID); 13378 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13379 ? MVT::f32 13380 : MVT::f64; 13381 13382 // If we're converting from a float, to an int, and back to a float again, 13383 // then we don't need the store/load pair at all. 13384 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13385 Subtarget.hasFPCVT()) || 13386 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13387 SDValue Src = Op.getOperand(0).getOperand(0); 13388 if (Src.getValueType() == MVT::f32) { 13389 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13390 DCI.AddToWorklist(Src.getNode()); 13391 } else if (Src.getValueType() != MVT::f64) { 13392 // Make sure that we don't pick up a ppc_fp128 source value. 13393 return SDValue(); 13394 } 13395 13396 unsigned FCTOp = 13397 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13398 PPCISD::FCTIDUZ; 13399 13400 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13401 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13402 13403 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13404 FP = DAG.getNode(ISD::FP_ROUND, dl, 13405 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13406 DCI.AddToWorklist(FP.getNode()); 13407 } 13408 13409 return FP; 13410 } 13411 13412 return SDValue(); 13413 } 13414 13415 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13416 // builtins) into loads with swaps. 13417 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13418 DAGCombinerInfo &DCI) const { 13419 SelectionDAG &DAG = DCI.DAG; 13420 SDLoc dl(N); 13421 SDValue Chain; 13422 SDValue Base; 13423 MachineMemOperand *MMO; 13424 13425 switch (N->getOpcode()) { 13426 default: 13427 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13428 case ISD::LOAD: { 13429 LoadSDNode *LD = cast<LoadSDNode>(N); 13430 Chain = LD->getChain(); 13431 Base = LD->getBasePtr(); 13432 MMO = LD->getMemOperand(); 13433 // If the MMO suggests this isn't a load of a full vector, leave 13434 // things alone. For a built-in, we have to make the change for 13435 // correctness, so if there is a size problem that will be a bug. 13436 if (MMO->getSize() < 16) 13437 return SDValue(); 13438 break; 13439 } 13440 case ISD::INTRINSIC_W_CHAIN: { 13441 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13442 Chain = Intrin->getChain(); 13443 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13444 // us what we want. Get operand 2 instead. 13445 Base = Intrin->getOperand(2); 13446 MMO = Intrin->getMemOperand(); 13447 break; 13448 } 13449 } 13450 13451 MVT VecTy = N->getValueType(0).getSimpleVT(); 13452 13453 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13454 // aligned and the type is a vector with elements up to 4 bytes 13455 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13456 && VecTy.getScalarSizeInBits() <= 32 ) { 13457 return SDValue(); 13458 } 13459 13460 SDValue LoadOps[] = { Chain, Base }; 13461 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13462 DAG.getVTList(MVT::v2f64, MVT::Other), 13463 LoadOps, MVT::v2f64, MMO); 13464 13465 DCI.AddToWorklist(Load.getNode()); 13466 Chain = Load.getValue(1); 13467 SDValue Swap = DAG.getNode( 13468 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13469 DCI.AddToWorklist(Swap.getNode()); 13470 13471 // Add a bitcast if the resulting load type doesn't match v2f64. 13472 if (VecTy != MVT::v2f64) { 13473 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13474 DCI.AddToWorklist(N.getNode()); 13475 // Package {bitcast value, swap's chain} to match Load's shape. 13476 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13477 N, Swap.getValue(1)); 13478 } 13479 13480 return Swap; 13481 } 13482 13483 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13484 // builtins) into stores with swaps. 13485 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13486 DAGCombinerInfo &DCI) const { 13487 SelectionDAG &DAG = DCI.DAG; 13488 SDLoc dl(N); 13489 SDValue Chain; 13490 SDValue Base; 13491 unsigned SrcOpnd; 13492 MachineMemOperand *MMO; 13493 13494 switch (N->getOpcode()) { 13495 default: 13496 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13497 case ISD::STORE: { 13498 StoreSDNode *ST = cast<StoreSDNode>(N); 13499 Chain = ST->getChain(); 13500 Base = ST->getBasePtr(); 13501 MMO = ST->getMemOperand(); 13502 SrcOpnd = 1; 13503 // If the MMO suggests this isn't a store of a full vector, leave 13504 // things alone. For a built-in, we have to make the change for 13505 // correctness, so if there is a size problem that will be a bug. 13506 if (MMO->getSize() < 16) 13507 return SDValue(); 13508 break; 13509 } 13510 case ISD::INTRINSIC_VOID: { 13511 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13512 Chain = Intrin->getChain(); 13513 // Intrin->getBasePtr() oddly does not get what we want. 13514 Base = Intrin->getOperand(3); 13515 MMO = Intrin->getMemOperand(); 13516 SrcOpnd = 2; 13517 break; 13518 } 13519 } 13520 13521 SDValue Src = N->getOperand(SrcOpnd); 13522 MVT VecTy = Src.getValueType().getSimpleVT(); 13523 13524 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13525 // aligned and the type is a vector with elements up to 4 bytes 13526 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13527 && VecTy.getScalarSizeInBits() <= 32 ) { 13528 return SDValue(); 13529 } 13530 13531 // All stores are done as v2f64 and possible bit cast. 13532 if (VecTy != MVT::v2f64) { 13533 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13534 DCI.AddToWorklist(Src.getNode()); 13535 } 13536 13537 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13538 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13539 DCI.AddToWorklist(Swap.getNode()); 13540 Chain = Swap.getValue(1); 13541 SDValue StoreOps[] = { Chain, Swap, Base }; 13542 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13543 DAG.getVTList(MVT::Other), 13544 StoreOps, VecTy, MMO); 13545 DCI.AddToWorklist(Store.getNode()); 13546 return Store; 13547 } 13548 13549 // Handle DAG combine for STORE (FP_TO_INT F). 13550 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13551 DAGCombinerInfo &DCI) const { 13552 13553 SelectionDAG &DAG = DCI.DAG; 13554 SDLoc dl(N); 13555 unsigned Opcode = N->getOperand(1).getOpcode(); 13556 13557 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13558 && "Not a FP_TO_INT Instruction!"); 13559 13560 SDValue Val = N->getOperand(1).getOperand(0); 13561 EVT Op1VT = N->getOperand(1).getValueType(); 13562 EVT ResVT = Val.getValueType(); 13563 13564 // Floating point types smaller than 32 bits are not legal on Power. 13565 if (ResVT.getScalarSizeInBits() < 32) 13566 return SDValue(); 13567 13568 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13569 bool ValidTypeForStoreFltAsInt = 13570 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13571 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13572 13573 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13574 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13575 return SDValue(); 13576 13577 // Extend f32 values to f64 13578 if (ResVT.getScalarSizeInBits() == 32) { 13579 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13580 DCI.AddToWorklist(Val.getNode()); 13581 } 13582 13583 // Set signed or unsigned conversion opcode. 13584 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13585 PPCISD::FP_TO_SINT_IN_VSR : 13586 PPCISD::FP_TO_UINT_IN_VSR; 13587 13588 Val = DAG.getNode(ConvOpcode, 13589 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13590 DCI.AddToWorklist(Val.getNode()); 13591 13592 // Set number of bytes being converted. 13593 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13594 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13595 DAG.getIntPtrConstant(ByteSize, dl, false), 13596 DAG.getValueType(Op1VT) }; 13597 13598 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13599 DAG.getVTList(MVT::Other), Ops, 13600 cast<StoreSDNode>(N)->getMemoryVT(), 13601 cast<StoreSDNode>(N)->getMemOperand()); 13602 13603 DCI.AddToWorklist(Val.getNode()); 13604 return Val; 13605 } 13606 13607 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13608 LSBaseSDNode *LSBase, 13609 DAGCombinerInfo &DCI) const { 13610 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13611 "Not a reverse memop pattern!"); 13612 13613 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13614 auto Mask = SVN->getMask(); 13615 int i = 0; 13616 auto I = Mask.rbegin(); 13617 auto E = Mask.rend(); 13618 13619 for (; I != E; ++I) { 13620 if (*I != i) 13621 return false; 13622 i++; 13623 } 13624 return true; 13625 }; 13626 13627 SelectionDAG &DAG = DCI.DAG; 13628 EVT VT = SVN->getValueType(0); 13629 13630 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13631 return SDValue(); 13632 13633 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13634 // See comment in PPCVSXSwapRemoval.cpp. 13635 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13636 if (!Subtarget.hasP9Vector()) 13637 return SDValue(); 13638 13639 if(!IsElementReverse(SVN)) 13640 return SDValue(); 13641 13642 if (LSBase->getOpcode() == ISD::LOAD) { 13643 SDLoc dl(SVN); 13644 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13645 return DAG.getMemIntrinsicNode( 13646 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13647 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13648 } 13649 13650 if (LSBase->getOpcode() == ISD::STORE) { 13651 SDLoc dl(LSBase); 13652 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13653 LSBase->getBasePtr()}; 13654 return DAG.getMemIntrinsicNode( 13655 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13656 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13657 } 13658 13659 llvm_unreachable("Expected a load or store node here"); 13660 } 13661 13662 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13663 DAGCombinerInfo &DCI) const { 13664 SelectionDAG &DAG = DCI.DAG; 13665 SDLoc dl(N); 13666 switch (N->getOpcode()) { 13667 default: break; 13668 case ISD::ADD: 13669 return combineADD(N, DCI); 13670 case ISD::SHL: 13671 return combineSHL(N, DCI); 13672 case ISD::SRA: 13673 return combineSRA(N, DCI); 13674 case ISD::SRL: 13675 return combineSRL(N, DCI); 13676 case ISD::MUL: 13677 return combineMUL(N, DCI); 13678 case PPCISD::SHL: 13679 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13680 return N->getOperand(0); 13681 break; 13682 case PPCISD::SRL: 13683 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13684 return N->getOperand(0); 13685 break; 13686 case PPCISD::SRA: 13687 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13688 if (C->isNullValue() || // 0 >>s V -> 0. 13689 C->isAllOnesValue()) // -1 >>s V -> -1. 13690 return N->getOperand(0); 13691 } 13692 break; 13693 case ISD::SIGN_EXTEND: 13694 case ISD::ZERO_EXTEND: 13695 case ISD::ANY_EXTEND: 13696 return DAGCombineExtBoolTrunc(N, DCI); 13697 case ISD::TRUNCATE: 13698 return combineTRUNCATE(N, DCI); 13699 case ISD::SETCC: 13700 if (SDValue CSCC = combineSetCC(N, DCI)) 13701 return CSCC; 13702 LLVM_FALLTHROUGH; 13703 case ISD::SELECT_CC: 13704 return DAGCombineTruncBoolExt(N, DCI); 13705 case ISD::SINT_TO_FP: 13706 case ISD::UINT_TO_FP: 13707 return combineFPToIntToFP(N, DCI); 13708 case ISD::VECTOR_SHUFFLE: 13709 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13710 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13711 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13712 } 13713 break; 13714 case ISD::STORE: { 13715 13716 EVT Op1VT = N->getOperand(1).getValueType(); 13717 unsigned Opcode = N->getOperand(1).getOpcode(); 13718 13719 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13720 SDValue Val= combineStoreFPToInt(N, DCI); 13721 if (Val) 13722 return Val; 13723 } 13724 13725 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13726 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13727 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13728 if (Val) 13729 return Val; 13730 } 13731 13732 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13733 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13734 N->getOperand(1).getNode()->hasOneUse() && 13735 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13736 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13737 13738 // STBRX can only handle simple types and it makes no sense to store less 13739 // two bytes in byte-reversed order. 13740 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13741 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13742 break; 13743 13744 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13745 // Do an any-extend to 32-bits if this is a half-word input. 13746 if (BSwapOp.getValueType() == MVT::i16) 13747 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13748 13749 // If the type of BSWAP operand is wider than stored memory width 13750 // it need to be shifted to the right side before STBRX. 13751 if (Op1VT.bitsGT(mVT)) { 13752 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13753 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13754 DAG.getConstant(Shift, dl, MVT::i32)); 13755 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13756 if (Op1VT == MVT::i64) 13757 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13758 } 13759 13760 SDValue Ops[] = { 13761 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13762 }; 13763 return 13764 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13765 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13766 cast<StoreSDNode>(N)->getMemOperand()); 13767 } 13768 13769 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13770 // So it can increase the chance of CSE constant construction. 13771 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13772 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13773 // Need to sign-extended to 64-bits to handle negative values. 13774 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13775 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13776 MemVT.getSizeInBits()); 13777 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13778 13779 // DAG.getTruncStore() can't be used here because it doesn't accept 13780 // the general (base + offset) addressing mode. 13781 // So we use UpdateNodeOperands and setTruncatingStore instead. 13782 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13783 N->getOperand(3)); 13784 cast<StoreSDNode>(N)->setTruncatingStore(true); 13785 return SDValue(N, 0); 13786 } 13787 13788 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13789 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13790 if (Op1VT.isSimple()) { 13791 MVT StoreVT = Op1VT.getSimpleVT(); 13792 if (Subtarget.needsSwapsForVSXMemOps() && 13793 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13794 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13795 return expandVSXStoreForLE(N, DCI); 13796 } 13797 break; 13798 } 13799 case ISD::LOAD: { 13800 LoadSDNode *LD = cast<LoadSDNode>(N); 13801 EVT VT = LD->getValueType(0); 13802 13803 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13804 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13805 if (VT.isSimple()) { 13806 MVT LoadVT = VT.getSimpleVT(); 13807 if (Subtarget.needsSwapsForVSXMemOps() && 13808 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13809 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13810 return expandVSXLoadForLE(N, DCI); 13811 } 13812 13813 // We sometimes end up with a 64-bit integer load, from which we extract 13814 // two single-precision floating-point numbers. This happens with 13815 // std::complex<float>, and other similar structures, because of the way we 13816 // canonicalize structure copies. However, if we lack direct moves, 13817 // then the final bitcasts from the extracted integer values to the 13818 // floating-point numbers turn into store/load pairs. Even with direct moves, 13819 // just loading the two floating-point numbers is likely better. 13820 auto ReplaceTwoFloatLoad = [&]() { 13821 if (VT != MVT::i64) 13822 return false; 13823 13824 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13825 LD->isVolatile()) 13826 return false; 13827 13828 // We're looking for a sequence like this: 13829 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13830 // t16: i64 = srl t13, Constant:i32<32> 13831 // t17: i32 = truncate t16 13832 // t18: f32 = bitcast t17 13833 // t19: i32 = truncate t13 13834 // t20: f32 = bitcast t19 13835 13836 if (!LD->hasNUsesOfValue(2, 0)) 13837 return false; 13838 13839 auto UI = LD->use_begin(); 13840 while (UI.getUse().getResNo() != 0) ++UI; 13841 SDNode *Trunc = *UI++; 13842 while (UI.getUse().getResNo() != 0) ++UI; 13843 SDNode *RightShift = *UI; 13844 if (Trunc->getOpcode() != ISD::TRUNCATE) 13845 std::swap(Trunc, RightShift); 13846 13847 if (Trunc->getOpcode() != ISD::TRUNCATE || 13848 Trunc->getValueType(0) != MVT::i32 || 13849 !Trunc->hasOneUse()) 13850 return false; 13851 if (RightShift->getOpcode() != ISD::SRL || 13852 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13853 RightShift->getConstantOperandVal(1) != 32 || 13854 !RightShift->hasOneUse()) 13855 return false; 13856 13857 SDNode *Trunc2 = *RightShift->use_begin(); 13858 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13859 Trunc2->getValueType(0) != MVT::i32 || 13860 !Trunc2->hasOneUse()) 13861 return false; 13862 13863 SDNode *Bitcast = *Trunc->use_begin(); 13864 SDNode *Bitcast2 = *Trunc2->use_begin(); 13865 13866 if (Bitcast->getOpcode() != ISD::BITCAST || 13867 Bitcast->getValueType(0) != MVT::f32) 13868 return false; 13869 if (Bitcast2->getOpcode() != ISD::BITCAST || 13870 Bitcast2->getValueType(0) != MVT::f32) 13871 return false; 13872 13873 if (Subtarget.isLittleEndian()) 13874 std::swap(Bitcast, Bitcast2); 13875 13876 // Bitcast has the second float (in memory-layout order) and Bitcast2 13877 // has the first one. 13878 13879 SDValue BasePtr = LD->getBasePtr(); 13880 if (LD->isIndexed()) { 13881 assert(LD->getAddressingMode() == ISD::PRE_INC && 13882 "Non-pre-inc AM on PPC?"); 13883 BasePtr = 13884 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13885 LD->getOffset()); 13886 } 13887 13888 auto MMOFlags = 13889 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13890 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13891 LD->getPointerInfo(), LD->getAlignment(), 13892 MMOFlags, LD->getAAInfo()); 13893 SDValue AddPtr = 13894 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13895 BasePtr, DAG.getIntPtrConstant(4, dl)); 13896 SDValue FloatLoad2 = DAG.getLoad( 13897 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13898 LD->getPointerInfo().getWithOffset(4), 13899 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13900 13901 if (LD->isIndexed()) { 13902 // Note that DAGCombine should re-form any pre-increment load(s) from 13903 // what is produced here if that makes sense. 13904 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13905 } 13906 13907 DCI.CombineTo(Bitcast2, FloatLoad); 13908 DCI.CombineTo(Bitcast, FloatLoad2); 13909 13910 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13911 SDValue(FloatLoad2.getNode(), 1)); 13912 return true; 13913 }; 13914 13915 if (ReplaceTwoFloatLoad()) 13916 return SDValue(N, 0); 13917 13918 EVT MemVT = LD->getMemoryVT(); 13919 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13920 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13921 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13922 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13923 if (LD->isUnindexed() && VT.isVector() && 13924 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13925 // P8 and later hardware should just use LOAD. 13926 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13927 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13928 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13929 LD->getAlignment() >= ScalarABIAlignment)) && 13930 LD->getAlignment() < ABIAlignment) { 13931 // This is a type-legal unaligned Altivec or QPX load. 13932 SDValue Chain = LD->getChain(); 13933 SDValue Ptr = LD->getBasePtr(); 13934 bool isLittleEndian = Subtarget.isLittleEndian(); 13935 13936 // This implements the loading of unaligned vectors as described in 13937 // the venerable Apple Velocity Engine overview. Specifically: 13938 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13939 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13940 // 13941 // The general idea is to expand a sequence of one or more unaligned 13942 // loads into an alignment-based permutation-control instruction (lvsl 13943 // or lvsr), a series of regular vector loads (which always truncate 13944 // their input address to an aligned address), and a series of 13945 // permutations. The results of these permutations are the requested 13946 // loaded values. The trick is that the last "extra" load is not taken 13947 // from the address you might suspect (sizeof(vector) bytes after the 13948 // last requested load), but rather sizeof(vector) - 1 bytes after the 13949 // last requested vector. The point of this is to avoid a page fault if 13950 // the base address happened to be aligned. This works because if the 13951 // base address is aligned, then adding less than a full vector length 13952 // will cause the last vector in the sequence to be (re)loaded. 13953 // Otherwise, the next vector will be fetched as you might suspect was 13954 // necessary. 13955 13956 // We might be able to reuse the permutation generation from 13957 // a different base address offset from this one by an aligned amount. 13958 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13959 // optimization later. 13960 Intrinsic::ID Intr, IntrLD, IntrPerm; 13961 MVT PermCntlTy, PermTy, LDTy; 13962 if (Subtarget.hasAltivec()) { 13963 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13964 Intrinsic::ppc_altivec_lvsl; 13965 IntrLD = Intrinsic::ppc_altivec_lvx; 13966 IntrPerm = Intrinsic::ppc_altivec_vperm; 13967 PermCntlTy = MVT::v16i8; 13968 PermTy = MVT::v4i32; 13969 LDTy = MVT::v4i32; 13970 } else { 13971 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13972 Intrinsic::ppc_qpx_qvlpcls; 13973 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13974 Intrinsic::ppc_qpx_qvlfs; 13975 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13976 PermCntlTy = MVT::v4f64; 13977 PermTy = MVT::v4f64; 13978 LDTy = MemVT.getSimpleVT(); 13979 } 13980 13981 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13982 13983 // Create the new MMO for the new base load. It is like the original MMO, 13984 // but represents an area in memory almost twice the vector size centered 13985 // on the original address. If the address is unaligned, we might start 13986 // reading up to (sizeof(vector)-1) bytes below the address of the 13987 // original unaligned load. 13988 MachineFunction &MF = DAG.getMachineFunction(); 13989 MachineMemOperand *BaseMMO = 13990 MF.getMachineMemOperand(LD->getMemOperand(), 13991 -(long)MemVT.getStoreSize()+1, 13992 2*MemVT.getStoreSize()-1); 13993 13994 // Create the new base load. 13995 SDValue LDXIntID = 13996 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 13997 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 13998 SDValue BaseLoad = 13999 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14000 DAG.getVTList(PermTy, MVT::Other), 14001 BaseLoadOps, LDTy, BaseMMO); 14002 14003 // Note that the value of IncOffset (which is provided to the next 14004 // load's pointer info offset value, and thus used to calculate the 14005 // alignment), and the value of IncValue (which is actually used to 14006 // increment the pointer value) are different! This is because we 14007 // require the next load to appear to be aligned, even though it 14008 // is actually offset from the base pointer by a lesser amount. 14009 int IncOffset = VT.getSizeInBits() / 8; 14010 int IncValue = IncOffset; 14011 14012 // Walk (both up and down) the chain looking for another load at the real 14013 // (aligned) offset (the alignment of the other load does not matter in 14014 // this case). If found, then do not use the offset reduction trick, as 14015 // that will prevent the loads from being later combined (as they would 14016 // otherwise be duplicates). 14017 if (!findConsecutiveLoad(LD, DAG)) 14018 --IncValue; 14019 14020 SDValue Increment = 14021 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14022 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14023 14024 MachineMemOperand *ExtraMMO = 14025 MF.getMachineMemOperand(LD->getMemOperand(), 14026 1, 2*MemVT.getStoreSize()-1); 14027 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14028 SDValue ExtraLoad = 14029 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14030 DAG.getVTList(PermTy, MVT::Other), 14031 ExtraLoadOps, LDTy, ExtraMMO); 14032 14033 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14034 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14035 14036 // Because vperm has a big-endian bias, we must reverse the order 14037 // of the input vectors and complement the permute control vector 14038 // when generating little endian code. We have already handled the 14039 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14040 // and ExtraLoad here. 14041 SDValue Perm; 14042 if (isLittleEndian) 14043 Perm = BuildIntrinsicOp(IntrPerm, 14044 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14045 else 14046 Perm = BuildIntrinsicOp(IntrPerm, 14047 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14048 14049 if (VT != PermTy) 14050 Perm = Subtarget.hasAltivec() ? 14051 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14052 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14053 DAG.getTargetConstant(1, dl, MVT::i64)); 14054 // second argument is 1 because this rounding 14055 // is always exact. 14056 14057 // The output of the permutation is our loaded result, the TokenFactor is 14058 // our new chain. 14059 DCI.CombineTo(N, Perm, TF); 14060 return SDValue(N, 0); 14061 } 14062 } 14063 break; 14064 case ISD::INTRINSIC_WO_CHAIN: { 14065 bool isLittleEndian = Subtarget.isLittleEndian(); 14066 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14067 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14068 : Intrinsic::ppc_altivec_lvsl); 14069 if ((IID == Intr || 14070 IID == Intrinsic::ppc_qpx_qvlpcld || 14071 IID == Intrinsic::ppc_qpx_qvlpcls) && 14072 N->getOperand(1)->getOpcode() == ISD::ADD) { 14073 SDValue Add = N->getOperand(1); 14074 14075 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14076 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14077 14078 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14079 APInt::getAllOnesValue(Bits /* alignment */) 14080 .zext(Add.getScalarValueSizeInBits()))) { 14081 SDNode *BasePtr = Add->getOperand(0).getNode(); 14082 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14083 UE = BasePtr->use_end(); 14084 UI != UE; ++UI) { 14085 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14086 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14087 // We've found another LVSL/LVSR, and this address is an aligned 14088 // multiple of that one. The results will be the same, so use the 14089 // one we've just found instead. 14090 14091 return SDValue(*UI, 0); 14092 } 14093 } 14094 } 14095 14096 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14097 SDNode *BasePtr = Add->getOperand(0).getNode(); 14098 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14099 UE = BasePtr->use_end(); UI != UE; ++UI) { 14100 if (UI->getOpcode() == ISD::ADD && 14101 isa<ConstantSDNode>(UI->getOperand(1)) && 14102 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14103 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14104 (1ULL << Bits) == 0) { 14105 SDNode *OtherAdd = *UI; 14106 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14107 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14108 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14109 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14110 return SDValue(*VI, 0); 14111 } 14112 } 14113 } 14114 } 14115 } 14116 } 14117 14118 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14119 // Expose the vabsduw/h/b opportunity for down stream 14120 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14121 (IID == Intrinsic::ppc_altivec_vmaxsw || 14122 IID == Intrinsic::ppc_altivec_vmaxsh || 14123 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14124 SDValue V1 = N->getOperand(1); 14125 SDValue V2 = N->getOperand(2); 14126 if ((V1.getSimpleValueType() == MVT::v4i32 || 14127 V1.getSimpleValueType() == MVT::v8i16 || 14128 V1.getSimpleValueType() == MVT::v16i8) && 14129 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14130 // (0-a, a) 14131 if (V1.getOpcode() == ISD::SUB && 14132 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14133 V1.getOperand(1) == V2) { 14134 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14135 } 14136 // (a, 0-a) 14137 if (V2.getOpcode() == ISD::SUB && 14138 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14139 V2.getOperand(1) == V1) { 14140 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14141 } 14142 // (x-y, y-x) 14143 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14144 V1.getOperand(0) == V2.getOperand(1) && 14145 V1.getOperand(1) == V2.getOperand(0)) { 14146 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14147 } 14148 } 14149 } 14150 } 14151 14152 break; 14153 case ISD::INTRINSIC_W_CHAIN: 14154 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14155 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14156 if (Subtarget.needsSwapsForVSXMemOps()) { 14157 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14158 default: 14159 break; 14160 case Intrinsic::ppc_vsx_lxvw4x: 14161 case Intrinsic::ppc_vsx_lxvd2x: 14162 return expandVSXLoadForLE(N, DCI); 14163 } 14164 } 14165 break; 14166 case ISD::INTRINSIC_VOID: 14167 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14168 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14169 if (Subtarget.needsSwapsForVSXMemOps()) { 14170 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14171 default: 14172 break; 14173 case Intrinsic::ppc_vsx_stxvw4x: 14174 case Intrinsic::ppc_vsx_stxvd2x: 14175 return expandVSXStoreForLE(N, DCI); 14176 } 14177 } 14178 break; 14179 case ISD::BSWAP: 14180 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14181 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14182 N->getOperand(0).hasOneUse() && 14183 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14184 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14185 N->getValueType(0) == MVT::i64))) { 14186 SDValue Load = N->getOperand(0); 14187 LoadSDNode *LD = cast<LoadSDNode>(Load); 14188 // Create the byte-swapping load. 14189 SDValue Ops[] = { 14190 LD->getChain(), // Chain 14191 LD->getBasePtr(), // Ptr 14192 DAG.getValueType(N->getValueType(0)) // VT 14193 }; 14194 SDValue BSLoad = 14195 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14196 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14197 MVT::i64 : MVT::i32, MVT::Other), 14198 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14199 14200 // If this is an i16 load, insert the truncate. 14201 SDValue ResVal = BSLoad; 14202 if (N->getValueType(0) == MVT::i16) 14203 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14204 14205 // First, combine the bswap away. This makes the value produced by the 14206 // load dead. 14207 DCI.CombineTo(N, ResVal); 14208 14209 // Next, combine the load away, we give it a bogus result value but a real 14210 // chain result. The result value is dead because the bswap is dead. 14211 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14212 14213 // Return N so it doesn't get rechecked! 14214 return SDValue(N, 0); 14215 } 14216 break; 14217 case PPCISD::VCMP: 14218 // If a VCMPo node already exists with exactly the same operands as this 14219 // node, use its result instead of this node (VCMPo computes both a CR6 and 14220 // a normal output). 14221 // 14222 if (!N->getOperand(0).hasOneUse() && 14223 !N->getOperand(1).hasOneUse() && 14224 !N->getOperand(2).hasOneUse()) { 14225 14226 // Scan all of the users of the LHS, looking for VCMPo's that match. 14227 SDNode *VCMPoNode = nullptr; 14228 14229 SDNode *LHSN = N->getOperand(0).getNode(); 14230 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14231 UI != E; ++UI) 14232 if (UI->getOpcode() == PPCISD::VCMPo && 14233 UI->getOperand(1) == N->getOperand(1) && 14234 UI->getOperand(2) == N->getOperand(2) && 14235 UI->getOperand(0) == N->getOperand(0)) { 14236 VCMPoNode = *UI; 14237 break; 14238 } 14239 14240 // If there is no VCMPo node, or if the flag value has a single use, don't 14241 // transform this. 14242 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14243 break; 14244 14245 // Look at the (necessarily single) use of the flag value. If it has a 14246 // chain, this transformation is more complex. Note that multiple things 14247 // could use the value result, which we should ignore. 14248 SDNode *FlagUser = nullptr; 14249 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14250 FlagUser == nullptr; ++UI) { 14251 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14252 SDNode *User = *UI; 14253 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14254 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14255 FlagUser = User; 14256 break; 14257 } 14258 } 14259 } 14260 14261 // If the user is a MFOCRF instruction, we know this is safe. 14262 // Otherwise we give up for right now. 14263 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14264 return SDValue(VCMPoNode, 0); 14265 } 14266 break; 14267 case ISD::BRCOND: { 14268 SDValue Cond = N->getOperand(1); 14269 SDValue Target = N->getOperand(2); 14270 14271 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14272 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14273 Intrinsic::loop_decrement) { 14274 14275 // We now need to make the intrinsic dead (it cannot be instruction 14276 // selected). 14277 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14278 assert(Cond.getNode()->hasOneUse() && 14279 "Counter decrement has more than one use"); 14280 14281 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14282 N->getOperand(0), Target); 14283 } 14284 } 14285 break; 14286 case ISD::BR_CC: { 14287 // If this is a branch on an altivec predicate comparison, lower this so 14288 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14289 // lowering is done pre-legalize, because the legalizer lowers the predicate 14290 // compare down to code that is difficult to reassemble. 14291 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14292 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14293 14294 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14295 // value. If so, pass-through the AND to get to the intrinsic. 14296 if (LHS.getOpcode() == ISD::AND && 14297 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14298 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14299 Intrinsic::loop_decrement && 14300 isa<ConstantSDNode>(LHS.getOperand(1)) && 14301 !isNullConstant(LHS.getOperand(1))) 14302 LHS = LHS.getOperand(0); 14303 14304 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14305 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14306 Intrinsic::loop_decrement && 14307 isa<ConstantSDNode>(RHS)) { 14308 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14309 "Counter decrement comparison is not EQ or NE"); 14310 14311 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14312 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14313 (CC == ISD::SETNE && !Val); 14314 14315 // We now need to make the intrinsic dead (it cannot be instruction 14316 // selected). 14317 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14318 assert(LHS.getNode()->hasOneUse() && 14319 "Counter decrement has more than one use"); 14320 14321 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14322 N->getOperand(0), N->getOperand(4)); 14323 } 14324 14325 int CompareOpc; 14326 bool isDot; 14327 14328 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14329 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14330 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14331 assert(isDot && "Can't compare against a vector result!"); 14332 14333 // If this is a comparison against something other than 0/1, then we know 14334 // that the condition is never/always true. 14335 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14336 if (Val != 0 && Val != 1) { 14337 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14338 return N->getOperand(0); 14339 // Always !=, turn it into an unconditional branch. 14340 return DAG.getNode(ISD::BR, dl, MVT::Other, 14341 N->getOperand(0), N->getOperand(4)); 14342 } 14343 14344 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14345 14346 // Create the PPCISD altivec 'dot' comparison node. 14347 SDValue Ops[] = { 14348 LHS.getOperand(2), // LHS of compare 14349 LHS.getOperand(3), // RHS of compare 14350 DAG.getConstant(CompareOpc, dl, MVT::i32) 14351 }; 14352 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14353 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14354 14355 // Unpack the result based on how the target uses it. 14356 PPC::Predicate CompOpc; 14357 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14358 default: // Can't happen, don't crash on invalid number though. 14359 case 0: // Branch on the value of the EQ bit of CR6. 14360 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14361 break; 14362 case 1: // Branch on the inverted value of the EQ bit of CR6. 14363 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14364 break; 14365 case 2: // Branch on the value of the LT bit of CR6. 14366 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14367 break; 14368 case 3: // Branch on the inverted value of the LT bit of CR6. 14369 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14370 break; 14371 } 14372 14373 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14374 DAG.getConstant(CompOpc, dl, MVT::i32), 14375 DAG.getRegister(PPC::CR6, MVT::i32), 14376 N->getOperand(4), CompNode.getValue(1)); 14377 } 14378 break; 14379 } 14380 case ISD::BUILD_VECTOR: 14381 return DAGCombineBuildVector(N, DCI); 14382 case ISD::ABS: 14383 return combineABS(N, DCI); 14384 case ISD::VSELECT: 14385 return combineVSelect(N, DCI); 14386 } 14387 14388 return SDValue(); 14389 } 14390 14391 SDValue 14392 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14393 SelectionDAG &DAG, 14394 SmallVectorImpl<SDNode *> &Created) const { 14395 // fold (sdiv X, pow2) 14396 EVT VT = N->getValueType(0); 14397 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14398 return SDValue(); 14399 if ((VT != MVT::i32 && VT != MVT::i64) || 14400 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14401 return SDValue(); 14402 14403 SDLoc DL(N); 14404 SDValue N0 = N->getOperand(0); 14405 14406 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14407 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14408 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14409 14410 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14411 Created.push_back(Op.getNode()); 14412 14413 if (IsNegPow2) { 14414 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14415 Created.push_back(Op.getNode()); 14416 } 14417 14418 return Op; 14419 } 14420 14421 //===----------------------------------------------------------------------===// 14422 // Inline Assembly Support 14423 //===----------------------------------------------------------------------===// 14424 14425 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14426 KnownBits &Known, 14427 const APInt &DemandedElts, 14428 const SelectionDAG &DAG, 14429 unsigned Depth) const { 14430 Known.resetAll(); 14431 switch (Op.getOpcode()) { 14432 default: break; 14433 case PPCISD::LBRX: { 14434 // lhbrx is known to have the top bits cleared out. 14435 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14436 Known.Zero = 0xFFFF0000; 14437 break; 14438 } 14439 case ISD::INTRINSIC_WO_CHAIN: { 14440 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14441 default: break; 14442 case Intrinsic::ppc_altivec_vcmpbfp_p: 14443 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14444 case Intrinsic::ppc_altivec_vcmpequb_p: 14445 case Intrinsic::ppc_altivec_vcmpequh_p: 14446 case Intrinsic::ppc_altivec_vcmpequw_p: 14447 case Intrinsic::ppc_altivec_vcmpequd_p: 14448 case Intrinsic::ppc_altivec_vcmpgefp_p: 14449 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14450 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14451 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14452 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14453 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14454 case Intrinsic::ppc_altivec_vcmpgtub_p: 14455 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14456 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14457 case Intrinsic::ppc_altivec_vcmpgtud_p: 14458 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14459 break; 14460 } 14461 } 14462 } 14463 } 14464 14465 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14466 switch (Subtarget.getCPUDirective()) { 14467 default: break; 14468 case PPC::DIR_970: 14469 case PPC::DIR_PWR4: 14470 case PPC::DIR_PWR5: 14471 case PPC::DIR_PWR5X: 14472 case PPC::DIR_PWR6: 14473 case PPC::DIR_PWR6X: 14474 case PPC::DIR_PWR7: 14475 case PPC::DIR_PWR8: 14476 case PPC::DIR_PWR9: 14477 case PPC::DIR_PWR_FUTURE: { 14478 if (!ML) 14479 break; 14480 14481 if (!DisableInnermostLoopAlign32) { 14482 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14483 // so that we can decrease cache misses and branch-prediction misses. 14484 // Actual alignment of the loop will depend on the hotness check and other 14485 // logic in alignBlocks. 14486 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14487 return Align(32); 14488 } 14489 14490 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14491 14492 // For small loops (between 5 and 8 instructions), align to a 32-byte 14493 // boundary so that the entire loop fits in one instruction-cache line. 14494 uint64_t LoopSize = 0; 14495 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14496 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14497 LoopSize += TII->getInstSizeInBytes(*J); 14498 if (LoopSize > 32) 14499 break; 14500 } 14501 14502 if (LoopSize > 16 && LoopSize <= 32) 14503 return Align(32); 14504 14505 break; 14506 } 14507 } 14508 14509 return TargetLowering::getPrefLoopAlignment(ML); 14510 } 14511 14512 /// getConstraintType - Given a constraint, return the type of 14513 /// constraint it is for this target. 14514 PPCTargetLowering::ConstraintType 14515 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14516 if (Constraint.size() == 1) { 14517 switch (Constraint[0]) { 14518 default: break; 14519 case 'b': 14520 case 'r': 14521 case 'f': 14522 case 'd': 14523 case 'v': 14524 case 'y': 14525 return C_RegisterClass; 14526 case 'Z': 14527 // FIXME: While Z does indicate a memory constraint, it specifically 14528 // indicates an r+r address (used in conjunction with the 'y' modifier 14529 // in the replacement string). Currently, we're forcing the base 14530 // register to be r0 in the asm printer (which is interpreted as zero) 14531 // and forming the complete address in the second register. This is 14532 // suboptimal. 14533 return C_Memory; 14534 } 14535 } else if (Constraint == "wc") { // individual CR bits. 14536 return C_RegisterClass; 14537 } else if (Constraint == "wa" || Constraint == "wd" || 14538 Constraint == "wf" || Constraint == "ws" || 14539 Constraint == "wi" || Constraint == "ww") { 14540 return C_RegisterClass; // VSX registers. 14541 } 14542 return TargetLowering::getConstraintType(Constraint); 14543 } 14544 14545 /// Examine constraint type and operand type and determine a weight value. 14546 /// This object must already have been set up with the operand type 14547 /// and the current alternative constraint selected. 14548 TargetLowering::ConstraintWeight 14549 PPCTargetLowering::getSingleConstraintMatchWeight( 14550 AsmOperandInfo &info, const char *constraint) const { 14551 ConstraintWeight weight = CW_Invalid; 14552 Value *CallOperandVal = info.CallOperandVal; 14553 // If we don't have a value, we can't do a match, 14554 // but allow it at the lowest weight. 14555 if (!CallOperandVal) 14556 return CW_Default; 14557 Type *type = CallOperandVal->getType(); 14558 14559 // Look at the constraint type. 14560 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14561 return CW_Register; // an individual CR bit. 14562 else if ((StringRef(constraint) == "wa" || 14563 StringRef(constraint) == "wd" || 14564 StringRef(constraint) == "wf") && 14565 type->isVectorTy()) 14566 return CW_Register; 14567 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14568 return CW_Register; // just hold 64-bit integers data. 14569 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14570 return CW_Register; 14571 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14572 return CW_Register; 14573 14574 switch (*constraint) { 14575 default: 14576 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14577 break; 14578 case 'b': 14579 if (type->isIntegerTy()) 14580 weight = CW_Register; 14581 break; 14582 case 'f': 14583 if (type->isFloatTy()) 14584 weight = CW_Register; 14585 break; 14586 case 'd': 14587 if (type->isDoubleTy()) 14588 weight = CW_Register; 14589 break; 14590 case 'v': 14591 if (type->isVectorTy()) 14592 weight = CW_Register; 14593 break; 14594 case 'y': 14595 weight = CW_Register; 14596 break; 14597 case 'Z': 14598 weight = CW_Memory; 14599 break; 14600 } 14601 return weight; 14602 } 14603 14604 std::pair<unsigned, const TargetRegisterClass *> 14605 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14606 StringRef Constraint, 14607 MVT VT) const { 14608 if (Constraint.size() == 1) { 14609 // GCC RS6000 Constraint Letters 14610 switch (Constraint[0]) { 14611 case 'b': // R1-R31 14612 if (VT == MVT::i64 && Subtarget.isPPC64()) 14613 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14614 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14615 case 'r': // R0-R31 14616 if (VT == MVT::i64 && Subtarget.isPPC64()) 14617 return std::make_pair(0U, &PPC::G8RCRegClass); 14618 return std::make_pair(0U, &PPC::GPRCRegClass); 14619 // 'd' and 'f' constraints are both defined to be "the floating point 14620 // registers", where one is for 32-bit and the other for 64-bit. We don't 14621 // really care overly much here so just give them all the same reg classes. 14622 case 'd': 14623 case 'f': 14624 if (Subtarget.hasSPE()) { 14625 if (VT == MVT::f32 || VT == MVT::i32) 14626 return std::make_pair(0U, &PPC::GPRCRegClass); 14627 if (VT == MVT::f64 || VT == MVT::i64) 14628 return std::make_pair(0U, &PPC::SPERCRegClass); 14629 } else { 14630 if (VT == MVT::f32 || VT == MVT::i32) 14631 return std::make_pair(0U, &PPC::F4RCRegClass); 14632 if (VT == MVT::f64 || VT == MVT::i64) 14633 return std::make_pair(0U, &PPC::F8RCRegClass); 14634 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14635 return std::make_pair(0U, &PPC::QFRCRegClass); 14636 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14637 return std::make_pair(0U, &PPC::QSRCRegClass); 14638 } 14639 break; 14640 case 'v': 14641 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14642 return std::make_pair(0U, &PPC::QFRCRegClass); 14643 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14644 return std::make_pair(0U, &PPC::QSRCRegClass); 14645 if (Subtarget.hasAltivec()) 14646 return std::make_pair(0U, &PPC::VRRCRegClass); 14647 break; 14648 case 'y': // crrc 14649 return std::make_pair(0U, &PPC::CRRCRegClass); 14650 } 14651 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14652 // An individual CR bit. 14653 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14654 } else if ((Constraint == "wa" || Constraint == "wd" || 14655 Constraint == "wf" || Constraint == "wi") && 14656 Subtarget.hasVSX()) { 14657 return std::make_pair(0U, &PPC::VSRCRegClass); 14658 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14659 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14660 return std::make_pair(0U, &PPC::VSSRCRegClass); 14661 else 14662 return std::make_pair(0U, &PPC::VSFRCRegClass); 14663 } 14664 14665 // If we name a VSX register, we can't defer to the base class because it 14666 // will not recognize the correct register (their names will be VSL{0-31} 14667 // and V{0-31} so they won't match). So we match them here. 14668 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14669 int VSNum = atoi(Constraint.data() + 3); 14670 assert(VSNum >= 0 && VSNum <= 63 && 14671 "Attempted to access a vsr out of range"); 14672 if (VSNum < 32) 14673 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14674 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14675 } 14676 std::pair<unsigned, const TargetRegisterClass *> R = 14677 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14678 14679 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14680 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14681 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14682 // register. 14683 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14684 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14685 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14686 PPC::GPRCRegClass.contains(R.first)) 14687 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14688 PPC::sub_32, &PPC::G8RCRegClass), 14689 &PPC::G8RCRegClass); 14690 14691 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14692 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14693 R.first = PPC::CR0; 14694 R.second = &PPC::CRRCRegClass; 14695 } 14696 14697 return R; 14698 } 14699 14700 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14701 /// vector. If it is invalid, don't add anything to Ops. 14702 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14703 std::string &Constraint, 14704 std::vector<SDValue>&Ops, 14705 SelectionDAG &DAG) const { 14706 SDValue Result; 14707 14708 // Only support length 1 constraints. 14709 if (Constraint.length() > 1) return; 14710 14711 char Letter = Constraint[0]; 14712 switch (Letter) { 14713 default: break; 14714 case 'I': 14715 case 'J': 14716 case 'K': 14717 case 'L': 14718 case 'M': 14719 case 'N': 14720 case 'O': 14721 case 'P': { 14722 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14723 if (!CST) return; // Must be an immediate to match. 14724 SDLoc dl(Op); 14725 int64_t Value = CST->getSExtValue(); 14726 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14727 // numbers are printed as such. 14728 switch (Letter) { 14729 default: llvm_unreachable("Unknown constraint letter!"); 14730 case 'I': // "I" is a signed 16-bit constant. 14731 if (isInt<16>(Value)) 14732 Result = DAG.getTargetConstant(Value, dl, TCVT); 14733 break; 14734 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14735 if (isShiftedUInt<16, 16>(Value)) 14736 Result = DAG.getTargetConstant(Value, dl, TCVT); 14737 break; 14738 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14739 if (isShiftedInt<16, 16>(Value)) 14740 Result = DAG.getTargetConstant(Value, dl, TCVT); 14741 break; 14742 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14743 if (isUInt<16>(Value)) 14744 Result = DAG.getTargetConstant(Value, dl, TCVT); 14745 break; 14746 case 'M': // "M" is a constant that is greater than 31. 14747 if (Value > 31) 14748 Result = DAG.getTargetConstant(Value, dl, TCVT); 14749 break; 14750 case 'N': // "N" is a positive constant that is an exact power of two. 14751 if (Value > 0 && isPowerOf2_64(Value)) 14752 Result = DAG.getTargetConstant(Value, dl, TCVT); 14753 break; 14754 case 'O': // "O" is the constant zero. 14755 if (Value == 0) 14756 Result = DAG.getTargetConstant(Value, dl, TCVT); 14757 break; 14758 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14759 if (isInt<16>(-Value)) 14760 Result = DAG.getTargetConstant(Value, dl, TCVT); 14761 break; 14762 } 14763 break; 14764 } 14765 } 14766 14767 if (Result.getNode()) { 14768 Ops.push_back(Result); 14769 return; 14770 } 14771 14772 // Handle standard constraint letters. 14773 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14774 } 14775 14776 // isLegalAddressingMode - Return true if the addressing mode represented 14777 // by AM is legal for this target, for a load/store of the specified type. 14778 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14779 const AddrMode &AM, Type *Ty, 14780 unsigned AS, Instruction *I) const { 14781 // PPC does not allow r+i addressing modes for vectors! 14782 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14783 return false; 14784 14785 // PPC allows a sign-extended 16-bit immediate field. 14786 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14787 return false; 14788 14789 // No global is ever allowed as a base. 14790 if (AM.BaseGV) 14791 return false; 14792 14793 // PPC only support r+r, 14794 switch (AM.Scale) { 14795 case 0: // "r+i" or just "i", depending on HasBaseReg. 14796 break; 14797 case 1: 14798 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14799 return false; 14800 // Otherwise we have r+r or r+i. 14801 break; 14802 case 2: 14803 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14804 return false; 14805 // Allow 2*r as r+r. 14806 break; 14807 default: 14808 // No other scales are supported. 14809 return false; 14810 } 14811 14812 return true; 14813 } 14814 14815 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14816 SelectionDAG &DAG) const { 14817 MachineFunction &MF = DAG.getMachineFunction(); 14818 MachineFrameInfo &MFI = MF.getFrameInfo(); 14819 MFI.setReturnAddressIsTaken(true); 14820 14821 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14822 return SDValue(); 14823 14824 SDLoc dl(Op); 14825 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14826 14827 // Make sure the function does not optimize away the store of the RA to 14828 // the stack. 14829 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14830 FuncInfo->setLRStoreRequired(); 14831 bool isPPC64 = Subtarget.isPPC64(); 14832 auto PtrVT = getPointerTy(MF.getDataLayout()); 14833 14834 if (Depth > 0) { 14835 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14836 SDValue Offset = 14837 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14838 isPPC64 ? MVT::i64 : MVT::i32); 14839 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14840 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14841 MachinePointerInfo()); 14842 } 14843 14844 // Just load the return address off the stack. 14845 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14846 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14847 MachinePointerInfo()); 14848 } 14849 14850 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14851 SelectionDAG &DAG) const { 14852 SDLoc dl(Op); 14853 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14854 14855 MachineFunction &MF = DAG.getMachineFunction(); 14856 MachineFrameInfo &MFI = MF.getFrameInfo(); 14857 MFI.setFrameAddressIsTaken(true); 14858 14859 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14860 bool isPPC64 = PtrVT == MVT::i64; 14861 14862 // Naked functions never have a frame pointer, and so we use r1. For all 14863 // other functions, this decision must be delayed until during PEI. 14864 unsigned FrameReg; 14865 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14866 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14867 else 14868 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14869 14870 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14871 PtrVT); 14872 while (Depth--) 14873 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14874 FrameAddr, MachinePointerInfo()); 14875 return FrameAddr; 14876 } 14877 14878 // FIXME? Maybe this could be a TableGen attribute on some registers and 14879 // this table could be generated automatically from RegInfo. 14880 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 14881 const MachineFunction &MF) const { 14882 bool isPPC64 = Subtarget.isPPC64(); 14883 14884 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 14885 if (!is64Bit && VT != LLT::scalar(32)) 14886 report_fatal_error("Invalid register global variable type"); 14887 14888 Register Reg = StringSwitch<Register>(RegName) 14889 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14890 .Case("r2", isPPC64 ? Register() : PPC::R2) 14891 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 14892 .Default(Register()); 14893 14894 if (Reg) 14895 return Reg; 14896 report_fatal_error("Invalid register name global variable"); 14897 } 14898 14899 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14900 // 32-bit SVR4 ABI access everything as got-indirect. 14901 if (Subtarget.is32BitELFABI()) 14902 return true; 14903 14904 // AIX accesses everything indirectly through the TOC, which is similar to 14905 // the GOT. 14906 if (Subtarget.isAIXABI()) 14907 return true; 14908 14909 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14910 // If it is small or large code model, module locals are accessed 14911 // indirectly by loading their address from .toc/.got. 14912 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14913 return true; 14914 14915 // JumpTable and BlockAddress are accessed as got-indirect. 14916 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14917 return true; 14918 14919 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14920 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14921 14922 return false; 14923 } 14924 14925 bool 14926 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14927 // The PowerPC target isn't yet aware of offsets. 14928 return false; 14929 } 14930 14931 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14932 const CallInst &I, 14933 MachineFunction &MF, 14934 unsigned Intrinsic) const { 14935 switch (Intrinsic) { 14936 case Intrinsic::ppc_qpx_qvlfd: 14937 case Intrinsic::ppc_qpx_qvlfs: 14938 case Intrinsic::ppc_qpx_qvlfcd: 14939 case Intrinsic::ppc_qpx_qvlfcs: 14940 case Intrinsic::ppc_qpx_qvlfiwa: 14941 case Intrinsic::ppc_qpx_qvlfiwz: 14942 case Intrinsic::ppc_altivec_lvx: 14943 case Intrinsic::ppc_altivec_lvxl: 14944 case Intrinsic::ppc_altivec_lvebx: 14945 case Intrinsic::ppc_altivec_lvehx: 14946 case Intrinsic::ppc_altivec_lvewx: 14947 case Intrinsic::ppc_vsx_lxvd2x: 14948 case Intrinsic::ppc_vsx_lxvw4x: { 14949 EVT VT; 14950 switch (Intrinsic) { 14951 case Intrinsic::ppc_altivec_lvebx: 14952 VT = MVT::i8; 14953 break; 14954 case Intrinsic::ppc_altivec_lvehx: 14955 VT = MVT::i16; 14956 break; 14957 case Intrinsic::ppc_altivec_lvewx: 14958 VT = MVT::i32; 14959 break; 14960 case Intrinsic::ppc_vsx_lxvd2x: 14961 VT = MVT::v2f64; 14962 break; 14963 case Intrinsic::ppc_qpx_qvlfd: 14964 VT = MVT::v4f64; 14965 break; 14966 case Intrinsic::ppc_qpx_qvlfs: 14967 VT = MVT::v4f32; 14968 break; 14969 case Intrinsic::ppc_qpx_qvlfcd: 14970 VT = MVT::v2f64; 14971 break; 14972 case Intrinsic::ppc_qpx_qvlfcs: 14973 VT = MVT::v2f32; 14974 break; 14975 default: 14976 VT = MVT::v4i32; 14977 break; 14978 } 14979 14980 Info.opc = ISD::INTRINSIC_W_CHAIN; 14981 Info.memVT = VT; 14982 Info.ptrVal = I.getArgOperand(0); 14983 Info.offset = -VT.getStoreSize()+1; 14984 Info.size = 2*VT.getStoreSize()-1; 14985 Info.align = Align(1); 14986 Info.flags = MachineMemOperand::MOLoad; 14987 return true; 14988 } 14989 case Intrinsic::ppc_qpx_qvlfda: 14990 case Intrinsic::ppc_qpx_qvlfsa: 14991 case Intrinsic::ppc_qpx_qvlfcda: 14992 case Intrinsic::ppc_qpx_qvlfcsa: 14993 case Intrinsic::ppc_qpx_qvlfiwaa: 14994 case Intrinsic::ppc_qpx_qvlfiwza: { 14995 EVT VT; 14996 switch (Intrinsic) { 14997 case Intrinsic::ppc_qpx_qvlfda: 14998 VT = MVT::v4f64; 14999 break; 15000 case Intrinsic::ppc_qpx_qvlfsa: 15001 VT = MVT::v4f32; 15002 break; 15003 case Intrinsic::ppc_qpx_qvlfcda: 15004 VT = MVT::v2f64; 15005 break; 15006 case Intrinsic::ppc_qpx_qvlfcsa: 15007 VT = MVT::v2f32; 15008 break; 15009 default: 15010 VT = MVT::v4i32; 15011 break; 15012 } 15013 15014 Info.opc = ISD::INTRINSIC_W_CHAIN; 15015 Info.memVT = VT; 15016 Info.ptrVal = I.getArgOperand(0); 15017 Info.offset = 0; 15018 Info.size = VT.getStoreSize(); 15019 Info.align = Align(1); 15020 Info.flags = MachineMemOperand::MOLoad; 15021 return true; 15022 } 15023 case Intrinsic::ppc_qpx_qvstfd: 15024 case Intrinsic::ppc_qpx_qvstfs: 15025 case Intrinsic::ppc_qpx_qvstfcd: 15026 case Intrinsic::ppc_qpx_qvstfcs: 15027 case Intrinsic::ppc_qpx_qvstfiw: 15028 case Intrinsic::ppc_altivec_stvx: 15029 case Intrinsic::ppc_altivec_stvxl: 15030 case Intrinsic::ppc_altivec_stvebx: 15031 case Intrinsic::ppc_altivec_stvehx: 15032 case Intrinsic::ppc_altivec_stvewx: 15033 case Intrinsic::ppc_vsx_stxvd2x: 15034 case Intrinsic::ppc_vsx_stxvw4x: { 15035 EVT VT; 15036 switch (Intrinsic) { 15037 case Intrinsic::ppc_altivec_stvebx: 15038 VT = MVT::i8; 15039 break; 15040 case Intrinsic::ppc_altivec_stvehx: 15041 VT = MVT::i16; 15042 break; 15043 case Intrinsic::ppc_altivec_stvewx: 15044 VT = MVT::i32; 15045 break; 15046 case Intrinsic::ppc_vsx_stxvd2x: 15047 VT = MVT::v2f64; 15048 break; 15049 case Intrinsic::ppc_qpx_qvstfd: 15050 VT = MVT::v4f64; 15051 break; 15052 case Intrinsic::ppc_qpx_qvstfs: 15053 VT = MVT::v4f32; 15054 break; 15055 case Intrinsic::ppc_qpx_qvstfcd: 15056 VT = MVT::v2f64; 15057 break; 15058 case Intrinsic::ppc_qpx_qvstfcs: 15059 VT = MVT::v2f32; 15060 break; 15061 default: 15062 VT = MVT::v4i32; 15063 break; 15064 } 15065 15066 Info.opc = ISD::INTRINSIC_VOID; 15067 Info.memVT = VT; 15068 Info.ptrVal = I.getArgOperand(1); 15069 Info.offset = -VT.getStoreSize()+1; 15070 Info.size = 2*VT.getStoreSize()-1; 15071 Info.align = Align(1); 15072 Info.flags = MachineMemOperand::MOStore; 15073 return true; 15074 } 15075 case Intrinsic::ppc_qpx_qvstfda: 15076 case Intrinsic::ppc_qpx_qvstfsa: 15077 case Intrinsic::ppc_qpx_qvstfcda: 15078 case Intrinsic::ppc_qpx_qvstfcsa: 15079 case Intrinsic::ppc_qpx_qvstfiwa: { 15080 EVT VT; 15081 switch (Intrinsic) { 15082 case Intrinsic::ppc_qpx_qvstfda: 15083 VT = MVT::v4f64; 15084 break; 15085 case Intrinsic::ppc_qpx_qvstfsa: 15086 VT = MVT::v4f32; 15087 break; 15088 case Intrinsic::ppc_qpx_qvstfcda: 15089 VT = MVT::v2f64; 15090 break; 15091 case Intrinsic::ppc_qpx_qvstfcsa: 15092 VT = MVT::v2f32; 15093 break; 15094 default: 15095 VT = MVT::v4i32; 15096 break; 15097 } 15098 15099 Info.opc = ISD::INTRINSIC_VOID; 15100 Info.memVT = VT; 15101 Info.ptrVal = I.getArgOperand(1); 15102 Info.offset = 0; 15103 Info.size = VT.getStoreSize(); 15104 Info.align = Align(1); 15105 Info.flags = MachineMemOperand::MOStore; 15106 return true; 15107 } 15108 default: 15109 break; 15110 } 15111 15112 return false; 15113 } 15114 15115 /// It returns EVT::Other if the type should be determined using generic 15116 /// target-independent logic. 15117 EVT PPCTargetLowering::getOptimalMemOpType( 15118 const MemOp &Op, const AttributeList &FuncAttributes) const { 15119 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15120 // When expanding a memset, require at least two QPX instructions to cover 15121 // the cost of loading the value to be stored from the constant pool. 15122 if (Subtarget.hasQPX() && Op.size() >= 32 && 15123 (!Op.isMemset() || Op.size() >= 64) && 15124 (!Op.getSrcAlign() || Op.getSrcAlign() >= 32) && 15125 (!Op.getDstAlign() || Op.getDstAlign() >= 32) && 15126 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15127 return MVT::v4f64; 15128 } 15129 15130 // We should use Altivec/VSX loads and stores when available. For unaligned 15131 // addresses, unaligned VSX loads are only fast starting with the P8. 15132 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15133 (((!Op.getSrcAlign() || Op.getSrcAlign() >= 16) && 15134 (!Op.getDstAlign() || Op.getDstAlign() >= 16)) || 15135 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15136 return MVT::v4i32; 15137 } 15138 15139 if (Subtarget.isPPC64()) { 15140 return MVT::i64; 15141 } 15142 15143 return MVT::i32; 15144 } 15145 15146 /// Returns true if it is beneficial to convert a load of a constant 15147 /// to just the constant itself. 15148 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15149 Type *Ty) const { 15150 assert(Ty->isIntegerTy()); 15151 15152 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15153 return !(BitSize == 0 || BitSize > 64); 15154 } 15155 15156 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15157 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15158 return false; 15159 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15160 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15161 return NumBits1 == 64 && NumBits2 == 32; 15162 } 15163 15164 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15165 if (!VT1.isInteger() || !VT2.isInteger()) 15166 return false; 15167 unsigned NumBits1 = VT1.getSizeInBits(); 15168 unsigned NumBits2 = VT2.getSizeInBits(); 15169 return NumBits1 == 64 && NumBits2 == 32; 15170 } 15171 15172 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15173 // Generally speaking, zexts are not free, but they are free when they can be 15174 // folded with other operations. 15175 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15176 EVT MemVT = LD->getMemoryVT(); 15177 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15178 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15179 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15180 LD->getExtensionType() == ISD::ZEXTLOAD)) 15181 return true; 15182 } 15183 15184 // FIXME: Add other cases... 15185 // - 32-bit shifts with a zext to i64 15186 // - zext after ctlz, bswap, etc. 15187 // - zext after and by a constant mask 15188 15189 return TargetLowering::isZExtFree(Val, VT2); 15190 } 15191 15192 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15193 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15194 "invalid fpext types"); 15195 // Extending to float128 is not free. 15196 if (DestVT == MVT::f128) 15197 return false; 15198 return true; 15199 } 15200 15201 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15202 return isInt<16>(Imm) || isUInt<16>(Imm); 15203 } 15204 15205 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15206 return isInt<16>(Imm) || isUInt<16>(Imm); 15207 } 15208 15209 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15210 unsigned, 15211 unsigned, 15212 MachineMemOperand::Flags, 15213 bool *Fast) const { 15214 if (DisablePPCUnaligned) 15215 return false; 15216 15217 // PowerPC supports unaligned memory access for simple non-vector types. 15218 // Although accessing unaligned addresses is not as efficient as accessing 15219 // aligned addresses, it is generally more efficient than manual expansion, 15220 // and generally only traps for software emulation when crossing page 15221 // boundaries. 15222 15223 if (!VT.isSimple()) 15224 return false; 15225 15226 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15227 return false; 15228 15229 if (VT.getSimpleVT().isVector()) { 15230 if (Subtarget.hasVSX()) { 15231 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15232 VT != MVT::v4f32 && VT != MVT::v4i32) 15233 return false; 15234 } else { 15235 return false; 15236 } 15237 } 15238 15239 if (VT == MVT::ppcf128) 15240 return false; 15241 15242 if (Fast) 15243 *Fast = true; 15244 15245 return true; 15246 } 15247 15248 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15249 EVT VT) const { 15250 VT = VT.getScalarType(); 15251 15252 if (!VT.isSimple()) 15253 return false; 15254 15255 switch (VT.getSimpleVT().SimpleTy) { 15256 case MVT::f32: 15257 case MVT::f64: 15258 return true; 15259 case MVT::f128: 15260 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15261 default: 15262 break; 15263 } 15264 15265 return false; 15266 } 15267 15268 const MCPhysReg * 15269 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15270 // LR is a callee-save register, but we must treat it as clobbered by any call 15271 // site. Hence we include LR in the scratch registers, which are in turn added 15272 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15273 // to CTR, which is used by any indirect call. 15274 static const MCPhysReg ScratchRegs[] = { 15275 PPC::X12, PPC::LR8, PPC::CTR8, 0 15276 }; 15277 15278 return ScratchRegs; 15279 } 15280 15281 unsigned PPCTargetLowering::getExceptionPointerRegister( 15282 const Constant *PersonalityFn) const { 15283 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15284 } 15285 15286 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15287 const Constant *PersonalityFn) const { 15288 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15289 } 15290 15291 bool 15292 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15293 EVT VT , unsigned DefinedValues) const { 15294 if (VT == MVT::v2i64) 15295 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15296 15297 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15298 return true; 15299 15300 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15301 } 15302 15303 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15304 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15305 return TargetLowering::getSchedulingPreference(N); 15306 15307 return Sched::ILP; 15308 } 15309 15310 // Create a fast isel object. 15311 FastISel * 15312 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15313 const TargetLibraryInfo *LibInfo) const { 15314 return PPC::createFastISel(FuncInfo, LibInfo); 15315 } 15316 15317 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15318 if (!Subtarget.isPPC64()) return; 15319 15320 // Update IsSplitCSR in PPCFunctionInfo 15321 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15322 PFI->setIsSplitCSR(true); 15323 } 15324 15325 void PPCTargetLowering::insertCopiesSplitCSR( 15326 MachineBasicBlock *Entry, 15327 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15328 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15329 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15330 if (!IStart) 15331 return; 15332 15333 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15334 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15335 MachineBasicBlock::iterator MBBI = Entry->begin(); 15336 for (const MCPhysReg *I = IStart; *I; ++I) { 15337 const TargetRegisterClass *RC = nullptr; 15338 if (PPC::G8RCRegClass.contains(*I)) 15339 RC = &PPC::G8RCRegClass; 15340 else if (PPC::F8RCRegClass.contains(*I)) 15341 RC = &PPC::F8RCRegClass; 15342 else if (PPC::CRRCRegClass.contains(*I)) 15343 RC = &PPC::CRRCRegClass; 15344 else if (PPC::VRRCRegClass.contains(*I)) 15345 RC = &PPC::VRRCRegClass; 15346 else 15347 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15348 15349 Register NewVR = MRI->createVirtualRegister(RC); 15350 // Create copy from CSR to a virtual register. 15351 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15352 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15353 // nounwind. If we want to generalize this later, we may need to emit 15354 // CFI pseudo-instructions. 15355 assert(Entry->getParent()->getFunction().hasFnAttribute( 15356 Attribute::NoUnwind) && 15357 "Function should be nounwind in insertCopiesSplitCSR!"); 15358 Entry->addLiveIn(*I); 15359 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15360 .addReg(*I); 15361 15362 // Insert the copy-back instructions right before the terminator. 15363 for (auto *Exit : Exits) 15364 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15365 TII->get(TargetOpcode::COPY), *I) 15366 .addReg(NewVR); 15367 } 15368 } 15369 15370 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15371 bool PPCTargetLowering::useLoadStackGuardNode() const { 15372 if (!Subtarget.isTargetLinux()) 15373 return TargetLowering::useLoadStackGuardNode(); 15374 return true; 15375 } 15376 15377 // Override to disable global variable loading on Linux. 15378 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15379 if (!Subtarget.isTargetLinux()) 15380 return TargetLowering::insertSSPDeclarations(M); 15381 } 15382 15383 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15384 bool ForCodeSize) const { 15385 if (!VT.isSimple() || !Subtarget.hasVSX()) 15386 return false; 15387 15388 switch(VT.getSimpleVT().SimpleTy) { 15389 default: 15390 // For FP types that are currently not supported by PPC backend, return 15391 // false. Examples: f16, f80. 15392 return false; 15393 case MVT::f32: 15394 case MVT::f64: 15395 case MVT::ppcf128: 15396 return Imm.isPosZero(); 15397 } 15398 } 15399 15400 // For vector shift operation op, fold 15401 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15402 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15403 SelectionDAG &DAG) { 15404 SDValue N0 = N->getOperand(0); 15405 SDValue N1 = N->getOperand(1); 15406 EVT VT = N0.getValueType(); 15407 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15408 unsigned Opcode = N->getOpcode(); 15409 unsigned TargetOpcode; 15410 15411 switch (Opcode) { 15412 default: 15413 llvm_unreachable("Unexpected shift operation"); 15414 case ISD::SHL: 15415 TargetOpcode = PPCISD::SHL; 15416 break; 15417 case ISD::SRL: 15418 TargetOpcode = PPCISD::SRL; 15419 break; 15420 case ISD::SRA: 15421 TargetOpcode = PPCISD::SRA; 15422 break; 15423 } 15424 15425 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15426 N1->getOpcode() == ISD::AND) 15427 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15428 if (Mask->getZExtValue() == OpSizeInBits - 1) 15429 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15430 15431 return SDValue(); 15432 } 15433 15434 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15435 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15436 return Value; 15437 15438 SDValue N0 = N->getOperand(0); 15439 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15440 if (!Subtarget.isISA3_0() || 15441 N0.getOpcode() != ISD::SIGN_EXTEND || 15442 N0.getOperand(0).getValueType() != MVT::i32 || 15443 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15444 return SDValue(); 15445 15446 // We can't save an operation here if the value is already extended, and 15447 // the existing shift is easier to combine. 15448 SDValue ExtsSrc = N0.getOperand(0); 15449 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15450 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15451 return SDValue(); 15452 15453 SDLoc DL(N0); 15454 SDValue ShiftBy = SDValue(CN1, 0); 15455 // We want the shift amount to be i32 on the extswli, but the shift could 15456 // have an i64. 15457 if (ShiftBy.getValueType() == MVT::i64) 15458 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15459 15460 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15461 ShiftBy); 15462 } 15463 15464 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15465 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15466 return Value; 15467 15468 return SDValue(); 15469 } 15470 15471 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15472 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15473 return Value; 15474 15475 return SDValue(); 15476 } 15477 15478 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15479 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15480 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15481 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15482 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15483 const PPCSubtarget &Subtarget) { 15484 if (!Subtarget.isPPC64()) 15485 return SDValue(); 15486 15487 SDValue LHS = N->getOperand(0); 15488 SDValue RHS = N->getOperand(1); 15489 15490 auto isZextOfCompareWithConstant = [](SDValue Op) { 15491 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15492 Op.getValueType() != MVT::i64) 15493 return false; 15494 15495 SDValue Cmp = Op.getOperand(0); 15496 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15497 Cmp.getOperand(0).getValueType() != MVT::i64) 15498 return false; 15499 15500 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15501 int64_t NegConstant = 0 - Constant->getSExtValue(); 15502 // Due to the limitations of the addi instruction, 15503 // -C is required to be [-32768, 32767]. 15504 return isInt<16>(NegConstant); 15505 } 15506 15507 return false; 15508 }; 15509 15510 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15511 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15512 15513 // If there is a pattern, canonicalize a zext operand to the RHS. 15514 if (LHSHasPattern && !RHSHasPattern) 15515 std::swap(LHS, RHS); 15516 else if (!LHSHasPattern && !RHSHasPattern) 15517 return SDValue(); 15518 15519 SDLoc DL(N); 15520 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15521 SDValue Cmp = RHS.getOperand(0); 15522 SDValue Z = Cmp.getOperand(0); 15523 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15524 15525 assert(Constant && "Constant Should not be a null pointer."); 15526 int64_t NegConstant = 0 - Constant->getSExtValue(); 15527 15528 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15529 default: break; 15530 case ISD::SETNE: { 15531 // when C == 0 15532 // --> addze X, (addic Z, -1).carry 15533 // / 15534 // add X, (zext(setne Z, C))-- 15535 // \ when -32768 <= -C <= 32767 && C != 0 15536 // --> addze X, (addic (addi Z, -C), -1).carry 15537 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15538 DAG.getConstant(NegConstant, DL, MVT::i64)); 15539 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15540 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15541 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15542 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15543 SDValue(Addc.getNode(), 1)); 15544 } 15545 case ISD::SETEQ: { 15546 // when C == 0 15547 // --> addze X, (subfic Z, 0).carry 15548 // / 15549 // add X, (zext(sete Z, C))-- 15550 // \ when -32768 <= -C <= 32767 && C != 0 15551 // --> addze X, (subfic (addi Z, -C), 0).carry 15552 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15553 DAG.getConstant(NegConstant, DL, MVT::i64)); 15554 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15555 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15556 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15557 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15558 SDValue(Subc.getNode(), 1)); 15559 } 15560 } 15561 15562 return SDValue(); 15563 } 15564 15565 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15566 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15567 return Value; 15568 15569 return SDValue(); 15570 } 15571 15572 // Detect TRUNCATE operations on bitcasts of float128 values. 15573 // What we are looking for here is the situtation where we extract a subset 15574 // of bits from a 128 bit float. 15575 // This can be of two forms: 15576 // 1) BITCAST of f128 feeding TRUNCATE 15577 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15578 // The reason this is required is because we do not have a legal i128 type 15579 // and so we want to prevent having to store the f128 and then reload part 15580 // of it. 15581 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15582 DAGCombinerInfo &DCI) const { 15583 // If we are using CRBits then try that first. 15584 if (Subtarget.useCRBits()) { 15585 // Check if CRBits did anything and return that if it did. 15586 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15587 return CRTruncValue; 15588 } 15589 15590 SDLoc dl(N); 15591 SDValue Op0 = N->getOperand(0); 15592 15593 // Looking for a truncate of i128 to i64. 15594 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15595 return SDValue(); 15596 15597 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15598 15599 // SRL feeding TRUNCATE. 15600 if (Op0.getOpcode() == ISD::SRL) { 15601 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15602 // The right shift has to be by 64 bits. 15603 if (!ConstNode || ConstNode->getZExtValue() != 64) 15604 return SDValue(); 15605 15606 // Switch the element number to extract. 15607 EltToExtract = EltToExtract ? 0 : 1; 15608 // Update Op0 past the SRL. 15609 Op0 = Op0.getOperand(0); 15610 } 15611 15612 // BITCAST feeding a TRUNCATE possibly via SRL. 15613 if (Op0.getOpcode() == ISD::BITCAST && 15614 Op0.getValueType() == MVT::i128 && 15615 Op0.getOperand(0).getValueType() == MVT::f128) { 15616 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15617 return DCI.DAG.getNode( 15618 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15619 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15620 } 15621 return SDValue(); 15622 } 15623 15624 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15625 SelectionDAG &DAG = DCI.DAG; 15626 15627 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15628 if (!ConstOpOrElement) 15629 return SDValue(); 15630 15631 // An imul is usually smaller than the alternative sequence for legal type. 15632 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15633 isOperationLegal(ISD::MUL, N->getValueType(0))) 15634 return SDValue(); 15635 15636 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15637 switch (this->Subtarget.getCPUDirective()) { 15638 default: 15639 // TODO: enhance the condition for subtarget before pwr8 15640 return false; 15641 case PPC::DIR_PWR8: 15642 // type mul add shl 15643 // scalar 4 1 1 15644 // vector 7 2 2 15645 return true; 15646 case PPC::DIR_PWR9: 15647 case PPC::DIR_PWR_FUTURE: 15648 // type mul add shl 15649 // scalar 5 2 2 15650 // vector 7 2 2 15651 15652 // The cycle RATIO of related operations are showed as a table above. 15653 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15654 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15655 // are 4, it is always profitable; but for 3 instrs patterns 15656 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15657 // So we should only do it for vector type. 15658 return IsAddOne && IsNeg ? VT.isVector() : true; 15659 } 15660 }; 15661 15662 EVT VT = N->getValueType(0); 15663 SDLoc DL(N); 15664 15665 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15666 bool IsNeg = MulAmt.isNegative(); 15667 APInt MulAmtAbs = MulAmt.abs(); 15668 15669 if ((MulAmtAbs - 1).isPowerOf2()) { 15670 // (mul x, 2^N + 1) => (add (shl x, N), x) 15671 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15672 15673 if (!IsProfitable(IsNeg, true, VT)) 15674 return SDValue(); 15675 15676 SDValue Op0 = N->getOperand(0); 15677 SDValue Op1 = 15678 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15679 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15680 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15681 15682 if (!IsNeg) 15683 return Res; 15684 15685 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15686 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15687 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15688 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15689 15690 if (!IsProfitable(IsNeg, false, VT)) 15691 return SDValue(); 15692 15693 SDValue Op0 = N->getOperand(0); 15694 SDValue Op1 = 15695 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15696 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15697 15698 if (!IsNeg) 15699 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15700 else 15701 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15702 15703 } else { 15704 return SDValue(); 15705 } 15706 } 15707 15708 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15709 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15710 if (!Subtarget.is64BitELFABI()) 15711 return false; 15712 15713 // If not a tail call then no need to proceed. 15714 if (!CI->isTailCall()) 15715 return false; 15716 15717 // If sibling calls have been disabled and tail-calls aren't guaranteed 15718 // there is no reason to duplicate. 15719 auto &TM = getTargetMachine(); 15720 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15721 return false; 15722 15723 // Can't tail call a function called indirectly, or if it has variadic args. 15724 const Function *Callee = CI->getCalledFunction(); 15725 if (!Callee || Callee->isVarArg()) 15726 return false; 15727 15728 // Make sure the callee and caller calling conventions are eligible for tco. 15729 const Function *Caller = CI->getParent()->getParent(); 15730 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15731 CI->getCallingConv())) 15732 return false; 15733 15734 // If the function is local then we have a good chance at tail-calling it 15735 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15736 } 15737 15738 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15739 if (!Subtarget.hasVSX()) 15740 return false; 15741 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15742 return true; 15743 return VT == MVT::f32 || VT == MVT::f64 || 15744 VT == MVT::v4f32 || VT == MVT::v2f64; 15745 } 15746 15747 bool PPCTargetLowering:: 15748 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15749 const Value *Mask = AndI.getOperand(1); 15750 // If the mask is suitable for andi. or andis. we should sink the and. 15751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15752 // Can't handle constants wider than 64-bits. 15753 if (CI->getBitWidth() > 64) 15754 return false; 15755 int64_t ConstVal = CI->getZExtValue(); 15756 return isUInt<16>(ConstVal) || 15757 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15758 } 15759 15760 // For non-constant masks, we can always use the record-form and. 15761 return true; 15762 } 15763 15764 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15765 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15766 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15767 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15768 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15769 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15770 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15771 assert(Subtarget.hasP9Altivec() && 15772 "Only combine this when P9 altivec supported!"); 15773 EVT VT = N->getValueType(0); 15774 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15775 return SDValue(); 15776 15777 SelectionDAG &DAG = DCI.DAG; 15778 SDLoc dl(N); 15779 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15780 // Even for signed integers, if it's known to be positive (as signed 15781 // integer) due to zero-extended inputs. 15782 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15783 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15784 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15785 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15786 (SubOpcd1 == ISD::ZERO_EXTEND || 15787 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15788 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15789 N->getOperand(0)->getOperand(0), 15790 N->getOperand(0)->getOperand(1), 15791 DAG.getTargetConstant(0, dl, MVT::i32)); 15792 } 15793 15794 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15795 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15796 N->getOperand(0).hasOneUse()) { 15797 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15798 N->getOperand(0)->getOperand(0), 15799 N->getOperand(0)->getOperand(1), 15800 DAG.getTargetConstant(1, dl, MVT::i32)); 15801 } 15802 } 15803 15804 return SDValue(); 15805 } 15806 15807 // For type v4i32/v8ii16/v16i8, transform 15808 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15809 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15810 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15811 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15812 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15813 DAGCombinerInfo &DCI) const { 15814 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15815 assert(Subtarget.hasP9Altivec() && 15816 "Only combine this when P9 altivec supported!"); 15817 15818 SelectionDAG &DAG = DCI.DAG; 15819 SDLoc dl(N); 15820 SDValue Cond = N->getOperand(0); 15821 SDValue TrueOpnd = N->getOperand(1); 15822 SDValue FalseOpnd = N->getOperand(2); 15823 EVT VT = N->getOperand(1).getValueType(); 15824 15825 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15826 FalseOpnd.getOpcode() != ISD::SUB) 15827 return SDValue(); 15828 15829 // ABSD only available for type v4i32/v8i16/v16i8 15830 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15831 return SDValue(); 15832 15833 // At least to save one more dependent computation 15834 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15835 return SDValue(); 15836 15837 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15838 15839 // Can only handle unsigned comparison here 15840 switch (CC) { 15841 default: 15842 return SDValue(); 15843 case ISD::SETUGT: 15844 case ISD::SETUGE: 15845 break; 15846 case ISD::SETULT: 15847 case ISD::SETULE: 15848 std::swap(TrueOpnd, FalseOpnd); 15849 break; 15850 } 15851 15852 SDValue CmpOpnd1 = Cond.getOperand(0); 15853 SDValue CmpOpnd2 = Cond.getOperand(1); 15854 15855 // SETCC CmpOpnd1 CmpOpnd2 cond 15856 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15857 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15858 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15859 TrueOpnd.getOperand(1) == CmpOpnd2 && 15860 FalseOpnd.getOperand(0) == CmpOpnd2 && 15861 FalseOpnd.getOperand(1) == CmpOpnd1) { 15862 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15863 CmpOpnd1, CmpOpnd2, 15864 DAG.getTargetConstant(0, dl, MVT::i32)); 15865 } 15866 15867 return SDValue(); 15868 } 15869