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::FRINT, MVT::v2f64, Legal); 803 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 804 setOperationAction(ISD::FROUND, MVT::f64, Legal); 805 setOperationAction(ISD::FRINT, MVT::f64, Legal); 806 807 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 808 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 809 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 810 setOperationAction(ISD::FROUND, MVT::f32, Legal); 811 setOperationAction(ISD::FRINT, MVT::f32, Legal); 812 813 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 814 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 815 816 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 817 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 818 819 // Share the Altivec comparison restrictions. 820 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 821 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 822 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 823 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 824 825 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 826 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 827 828 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); 829 830 if (Subtarget.hasP8Vector()) 831 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 832 833 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 834 835 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 836 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 837 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 838 839 if (Subtarget.hasP8Altivec()) { 840 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 841 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 842 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 843 844 // 128 bit shifts can be accomplished via 3 instructions for SHL and 845 // SRL, but not for SRA because of the instructions available: 846 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 847 // doing 848 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 849 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 850 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 851 852 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 853 } 854 else { 855 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 856 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 857 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 858 859 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 860 861 // VSX v2i64 only supports non-arithmetic operations. 862 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 863 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 864 } 865 866 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 867 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 868 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 869 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 870 871 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); 872 873 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 874 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 875 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 876 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 877 878 // Custom handling for partial vectors of integers converted to 879 // floating point. We already have optimal handling for v2i32 through 880 // the DAG combine, so those aren't necessary. 881 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 882 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 883 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 884 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 885 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 886 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 887 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 888 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 889 890 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 891 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 892 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 893 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 894 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 895 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 896 897 if (Subtarget.hasDirectMove()) 898 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 899 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 900 901 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 902 } 903 904 if (Subtarget.hasP8Altivec()) { 905 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 906 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 907 } 908 909 if (Subtarget.hasP9Vector()) { 910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 912 913 // 128 bit shifts can be accomplished via 3 instructions for SHL and 914 // SRL, but not for SRA because of the instructions available: 915 // VS{RL} and VS{RL}O. 916 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 917 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 918 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 919 920 if (EnableQuadPrecision) { 921 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 922 setOperationAction(ISD::FADD, MVT::f128, Legal); 923 setOperationAction(ISD::FSUB, MVT::f128, Legal); 924 setOperationAction(ISD::FDIV, MVT::f128, Legal); 925 setOperationAction(ISD::FMUL, MVT::f128, Legal); 926 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 927 // No extending loads to f128 on PPC. 928 for (MVT FPT : MVT::fp_valuetypes()) 929 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 930 setOperationAction(ISD::FMA, MVT::f128, Legal); 931 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 932 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 933 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 934 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 935 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 936 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 937 938 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 939 setOperationAction(ISD::FRINT, MVT::f128, Legal); 940 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 941 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 942 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 943 setOperationAction(ISD::FROUND, MVT::f128, Legal); 944 945 setOperationAction(ISD::SELECT, MVT::f128, Expand); 946 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 947 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 948 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 949 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 950 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 951 // No implementation for these ops for PowerPC. 952 setOperationAction(ISD::FSIN , MVT::f128, Expand); 953 setOperationAction(ISD::FCOS , MVT::f128, Expand); 954 setOperationAction(ISD::FPOW, MVT::f128, Expand); 955 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 956 setOperationAction(ISD::FREM, MVT::f128, Expand); 957 } 958 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 959 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 960 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 961 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 962 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 963 } 964 965 if (Subtarget.hasP9Altivec()) { 966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 968 969 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 970 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 971 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 972 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 973 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 974 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 975 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 976 } 977 } 978 979 if (Subtarget.hasQPX()) { 980 setOperationAction(ISD::FADD, MVT::v4f64, Legal); 981 setOperationAction(ISD::FSUB, MVT::v4f64, Legal); 982 setOperationAction(ISD::FMUL, MVT::v4f64, Legal); 983 setOperationAction(ISD::FREM, MVT::v4f64, Expand); 984 985 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); 986 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); 987 988 setOperationAction(ISD::LOAD , MVT::v4f64, Custom); 989 setOperationAction(ISD::STORE , MVT::v4f64, Custom); 990 991 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); 992 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); 993 994 if (!Subtarget.useCRBits()) 995 setOperationAction(ISD::SELECT, MVT::v4f64, Expand); 996 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); 997 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); 999 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); 1000 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); 1001 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); 1002 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); 1003 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); 1004 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); 1005 1006 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); 1007 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); 1008 1009 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); 1010 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); 1011 1012 setOperationAction(ISD::FNEG , MVT::v4f64, Legal); 1013 setOperationAction(ISD::FABS , MVT::v4f64, Legal); 1014 setOperationAction(ISD::FSIN , MVT::v4f64, Expand); 1015 setOperationAction(ISD::FCOS , MVT::v4f64, Expand); 1016 setOperationAction(ISD::FPOW , MVT::v4f64, Expand); 1017 setOperationAction(ISD::FLOG , MVT::v4f64, Expand); 1018 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); 1019 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); 1020 setOperationAction(ISD::FEXP , MVT::v4f64, Expand); 1021 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); 1022 1023 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); 1024 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); 1025 1026 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); 1027 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); 1028 1029 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); 1030 1031 setOperationAction(ISD::FADD, MVT::v4f32, Legal); 1032 setOperationAction(ISD::FSUB, MVT::v4f32, Legal); 1033 setOperationAction(ISD::FMUL, MVT::v4f32, Legal); 1034 setOperationAction(ISD::FREM, MVT::v4f32, Expand); 1035 1036 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1037 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); 1038 1039 setOperationAction(ISD::LOAD , MVT::v4f32, Custom); 1040 setOperationAction(ISD::STORE , MVT::v4f32, Custom); 1041 1042 if (!Subtarget.useCRBits()) 1043 setOperationAction(ISD::SELECT, MVT::v4f32, Expand); 1044 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); 1045 1046 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); 1047 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); 1048 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); 1049 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); 1050 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); 1051 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 1052 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 1053 1054 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); 1055 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); 1056 1057 setOperationAction(ISD::FNEG , MVT::v4f32, Legal); 1058 setOperationAction(ISD::FABS , MVT::v4f32, Legal); 1059 setOperationAction(ISD::FSIN , MVT::v4f32, Expand); 1060 setOperationAction(ISD::FCOS , MVT::v4f32, Expand); 1061 setOperationAction(ISD::FPOW , MVT::v4f32, Expand); 1062 setOperationAction(ISD::FLOG , MVT::v4f32, Expand); 1063 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); 1064 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); 1065 setOperationAction(ISD::FEXP , MVT::v4f32, Expand); 1066 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); 1067 1068 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); 1069 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); 1070 1071 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); 1072 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); 1073 1074 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); 1075 1076 setOperationAction(ISD::AND , MVT::v4i1, Legal); 1077 setOperationAction(ISD::OR , MVT::v4i1, Legal); 1078 setOperationAction(ISD::XOR , MVT::v4i1, Legal); 1079 1080 if (!Subtarget.useCRBits()) 1081 setOperationAction(ISD::SELECT, MVT::v4i1, Expand); 1082 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); 1083 1084 setOperationAction(ISD::LOAD , MVT::v4i1, Custom); 1085 setOperationAction(ISD::STORE , MVT::v4i1, Custom); 1086 1087 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); 1088 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); 1089 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); 1090 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); 1091 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); 1092 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); 1093 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); 1094 1095 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); 1096 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); 1097 1098 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); 1099 1100 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); 1101 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); 1102 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); 1103 setOperationAction(ISD::FROUND, MVT::v4f64, Legal); 1104 1105 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 1106 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 1107 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 1108 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1109 1110 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); 1111 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); 1112 1113 // These need to set FE_INEXACT, and so cannot be vectorized here. 1114 setOperationAction(ISD::FRINT, MVT::v4f64, Expand); 1115 setOperationAction(ISD::FRINT, MVT::v4f32, Expand); 1116 1117 if (TM.Options.UnsafeFPMath) { 1118 setOperationAction(ISD::FDIV, MVT::v4f64, Legal); 1119 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); 1120 1121 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 1122 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 1123 } else { 1124 setOperationAction(ISD::FDIV, MVT::v4f64, Expand); 1125 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); 1126 1127 setOperationAction(ISD::FDIV, MVT::v4f32, Expand); 1128 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); 1129 } 1130 } 1131 1132 if (Subtarget.has64BitSupport()) 1133 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1134 1135 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1136 1137 if (!isPPC64) { 1138 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1139 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1140 } 1141 1142 setBooleanContents(ZeroOrOneBooleanContent); 1143 1144 if (Subtarget.hasAltivec()) { 1145 // Altivec instructions set fields to all zeros or all ones. 1146 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1147 } 1148 1149 if (!isPPC64) { 1150 // These libcalls are not available in 32-bit. 1151 setLibcallName(RTLIB::SHL_I128, nullptr); 1152 setLibcallName(RTLIB::SRL_I128, nullptr); 1153 setLibcallName(RTLIB::SRA_I128, nullptr); 1154 } 1155 1156 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1157 1158 // We have target-specific dag combine patterns for the following nodes: 1159 setTargetDAGCombine(ISD::ADD); 1160 setTargetDAGCombine(ISD::SHL); 1161 setTargetDAGCombine(ISD::SRA); 1162 setTargetDAGCombine(ISD::SRL); 1163 setTargetDAGCombine(ISD::MUL); 1164 setTargetDAGCombine(ISD::SINT_TO_FP); 1165 setTargetDAGCombine(ISD::BUILD_VECTOR); 1166 if (Subtarget.hasFPCVT()) 1167 setTargetDAGCombine(ISD::UINT_TO_FP); 1168 setTargetDAGCombine(ISD::LOAD); 1169 setTargetDAGCombine(ISD::STORE); 1170 setTargetDAGCombine(ISD::BR_CC); 1171 if (Subtarget.useCRBits()) 1172 setTargetDAGCombine(ISD::BRCOND); 1173 setTargetDAGCombine(ISD::BSWAP); 1174 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 1175 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 1176 setTargetDAGCombine(ISD::INTRINSIC_VOID); 1177 1178 setTargetDAGCombine(ISD::SIGN_EXTEND); 1179 setTargetDAGCombine(ISD::ZERO_EXTEND); 1180 setTargetDAGCombine(ISD::ANY_EXTEND); 1181 1182 setTargetDAGCombine(ISD::TRUNCATE); 1183 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 1184 1185 1186 if (Subtarget.useCRBits()) { 1187 setTargetDAGCombine(ISD::TRUNCATE); 1188 setTargetDAGCombine(ISD::SETCC); 1189 setTargetDAGCombine(ISD::SELECT_CC); 1190 } 1191 1192 // Use reciprocal estimates. 1193 if (TM.Options.UnsafeFPMath) { 1194 setTargetDAGCombine(ISD::FDIV); 1195 setTargetDAGCombine(ISD::FSQRT); 1196 } 1197 1198 if (Subtarget.hasP9Altivec()) { 1199 setTargetDAGCombine(ISD::ABS); 1200 setTargetDAGCombine(ISD::VSELECT); 1201 } 1202 1203 if (EnableQuadPrecision) { 1204 setLibcallName(RTLIB::LOG_F128, "logf128"); 1205 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1206 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1207 setLibcallName(RTLIB::EXP_F128, "expf128"); 1208 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1209 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1210 setLibcallName(RTLIB::COS_F128, "cosf128"); 1211 setLibcallName(RTLIB::POW_F128, "powf128"); 1212 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1213 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1214 setLibcallName(RTLIB::POWI_F128, "__powikf2"); 1215 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1216 } 1217 1218 // With 32 condition bits, we don't need to sink (and duplicate) compares 1219 // aggressively in CodeGenPrep. 1220 if (Subtarget.useCRBits()) { 1221 setHasMultipleConditionRegisters(); 1222 setJumpIsExpensive(); 1223 } 1224 1225 setMinFunctionAlignment(Align(4)); 1226 1227 switch (Subtarget.getCPUDirective()) { 1228 default: break; 1229 case PPC::DIR_970: 1230 case PPC::DIR_A2: 1231 case PPC::DIR_E500: 1232 case PPC::DIR_E500mc: 1233 case PPC::DIR_E5500: 1234 case PPC::DIR_PWR4: 1235 case PPC::DIR_PWR5: 1236 case PPC::DIR_PWR5X: 1237 case PPC::DIR_PWR6: 1238 case PPC::DIR_PWR6X: 1239 case PPC::DIR_PWR7: 1240 case PPC::DIR_PWR8: 1241 case PPC::DIR_PWR9: 1242 case PPC::DIR_PWR_FUTURE: 1243 setPrefLoopAlignment(Align(16)); 1244 setPrefFunctionAlignment(Align(16)); 1245 break; 1246 } 1247 1248 if (Subtarget.enableMachineScheduler()) 1249 setSchedulingPreference(Sched::Source); 1250 else 1251 setSchedulingPreference(Sched::Hybrid); 1252 1253 computeRegisterProperties(STI.getRegisterInfo()); 1254 1255 // The Freescale cores do better with aggressive inlining of memcpy and 1256 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1257 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1258 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1259 MaxStoresPerMemset = 32; 1260 MaxStoresPerMemsetOptSize = 16; 1261 MaxStoresPerMemcpy = 32; 1262 MaxStoresPerMemcpyOptSize = 8; 1263 MaxStoresPerMemmove = 32; 1264 MaxStoresPerMemmoveOptSize = 8; 1265 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1266 // The A2 also benefits from (very) aggressive inlining of memcpy and 1267 // friends. The overhead of a the function call, even when warm, can be 1268 // over one hundred cycles. 1269 MaxStoresPerMemset = 128; 1270 MaxStoresPerMemcpy = 128; 1271 MaxStoresPerMemmove = 128; 1272 MaxLoadsPerMemcmp = 128; 1273 } else { 1274 MaxLoadsPerMemcmp = 8; 1275 MaxLoadsPerMemcmpOptSize = 4; 1276 } 1277 } 1278 1279 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1280 /// the desired ByVal argument alignment. 1281 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, 1282 unsigned MaxMaxAlign) { 1283 if (MaxAlign == MaxMaxAlign) 1284 return; 1285 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1286 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) 1287 MaxAlign = 32; 1288 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) 1289 MaxAlign = 16; 1290 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1291 unsigned EltAlign = 0; 1292 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1293 if (EltAlign > MaxAlign) 1294 MaxAlign = EltAlign; 1295 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1296 for (auto *EltTy : STy->elements()) { 1297 unsigned EltAlign = 0; 1298 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1299 if (EltAlign > MaxAlign) 1300 MaxAlign = EltAlign; 1301 if (MaxAlign == MaxMaxAlign) 1302 break; 1303 } 1304 } 1305 } 1306 1307 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1308 /// function arguments in the caller parameter area. 1309 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1310 const DataLayout &DL) const { 1311 // 16byte and wider vectors are passed on 16byte boundary. 1312 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1313 unsigned Align = Subtarget.isPPC64() ? 8 : 4; 1314 if (Subtarget.hasAltivec() || Subtarget.hasQPX()) 1315 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); 1316 return Align; 1317 } 1318 1319 bool PPCTargetLowering::useSoftFloat() const { 1320 return Subtarget.useSoftFloat(); 1321 } 1322 1323 bool PPCTargetLowering::hasSPE() const { 1324 return Subtarget.hasSPE(); 1325 } 1326 1327 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1328 return VT.isScalarInteger(); 1329 } 1330 1331 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1332 switch ((PPCISD::NodeType)Opcode) { 1333 case PPCISD::FIRST_NUMBER: break; 1334 case PPCISD::FSEL: return "PPCISD::FSEL"; 1335 case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP"; 1336 case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP"; 1337 case PPCISD::FCFID: return "PPCISD::FCFID"; 1338 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1339 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1340 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1341 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1342 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1343 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1344 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1345 case PPCISD::FP_TO_UINT_IN_VSR: 1346 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1347 case PPCISD::FP_TO_SINT_IN_VSR: 1348 return "PPCISD::FP_TO_SINT_IN_VSR"; 1349 case PPCISD::FRE: return "PPCISD::FRE"; 1350 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1351 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1352 case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; 1353 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; 1354 case PPCISD::VPERM: return "PPCISD::VPERM"; 1355 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1356 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1357 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1358 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1359 case PPCISD::CMPB: return "PPCISD::CMPB"; 1360 case PPCISD::Hi: return "PPCISD::Hi"; 1361 case PPCISD::Lo: return "PPCISD::Lo"; 1362 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1363 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1364 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1365 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1366 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1367 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1368 case PPCISD::SRL: return "PPCISD::SRL"; 1369 case PPCISD::SRA: return "PPCISD::SRA"; 1370 case PPCISD::SHL: return "PPCISD::SHL"; 1371 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1372 case PPCISD::CALL: return "PPCISD::CALL"; 1373 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1374 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1375 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1376 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1377 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1378 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1379 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1380 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1381 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1382 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1383 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1384 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1385 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1386 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1387 case PPCISD::ANDI_rec_1_EQ_BIT: 1388 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1389 case PPCISD::ANDI_rec_1_GT_BIT: 1390 return "PPCISD::ANDI_rec_1_GT_BIT"; 1391 case PPCISD::VCMP: return "PPCISD::VCMP"; 1392 case PPCISD::VCMPo: return "PPCISD::VCMPo"; 1393 case PPCISD::LBRX: return "PPCISD::LBRX"; 1394 case PPCISD::STBRX: return "PPCISD::STBRX"; 1395 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1396 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1397 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1398 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1399 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1400 case PPCISD::SExtVElems: return "PPCISD::SExtVElems"; 1401 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1402 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1403 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1404 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1405 case PPCISD::ST_VSR_SCAL_INT: 1406 return "PPCISD::ST_VSR_SCAL_INT"; 1407 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1408 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1409 case PPCISD::BDZ: return "PPCISD::BDZ"; 1410 case PPCISD::MFFS: return "PPCISD::MFFS"; 1411 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1412 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1413 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1414 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1415 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1416 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1417 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1418 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1419 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1420 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1421 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1422 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1423 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1424 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1425 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1426 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1427 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1428 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1429 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1430 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1431 case PPCISD::SC: return "PPCISD::SC"; 1432 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1433 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1434 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1435 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1436 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1437 case PPCISD::VABSD: return "PPCISD::VABSD"; 1438 case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; 1439 case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; 1440 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; 1441 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; 1442 case PPCISD::QBFLT: return "PPCISD::QBFLT"; 1443 case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; 1444 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1445 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1446 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1447 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1448 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1449 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1450 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1451 } 1452 return nullptr; 1453 } 1454 1455 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1456 EVT VT) const { 1457 if (!VT.isVector()) 1458 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1459 1460 if (Subtarget.hasQPX()) 1461 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); 1462 1463 return VT.changeVectorElementTypeToInteger(); 1464 } 1465 1466 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1467 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1468 return true; 1469 } 1470 1471 //===----------------------------------------------------------------------===// 1472 // Node matching predicates, for use by the tblgen matching code. 1473 //===----------------------------------------------------------------------===// 1474 1475 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1476 static bool isFloatingPointZero(SDValue Op) { 1477 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1478 return CFP->getValueAPF().isZero(); 1479 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1480 // Maybe this has already been legalized into the constant pool? 1481 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1482 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1483 return CFP->getValueAPF().isZero(); 1484 } 1485 return false; 1486 } 1487 1488 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1489 /// true if Op is undef or if it matches the specified value. 1490 static bool isConstantOrUndef(int Op, int Val) { 1491 return Op < 0 || Op == Val; 1492 } 1493 1494 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1495 /// VPKUHUM instruction. 1496 /// The ShuffleKind distinguishes between big-endian operations with 1497 /// two different inputs (0), either-endian operations with two identical 1498 /// inputs (1), and little-endian operations with two different inputs (2). 1499 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1500 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1501 SelectionDAG &DAG) { 1502 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1503 if (ShuffleKind == 0) { 1504 if (IsLE) 1505 return false; 1506 for (unsigned i = 0; i != 16; ++i) 1507 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1508 return false; 1509 } else if (ShuffleKind == 2) { 1510 if (!IsLE) 1511 return false; 1512 for (unsigned i = 0; i != 16; ++i) 1513 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1514 return false; 1515 } else if (ShuffleKind == 1) { 1516 unsigned j = IsLE ? 0 : 1; 1517 for (unsigned i = 0; i != 8; ++i) 1518 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1519 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1520 return false; 1521 } 1522 return true; 1523 } 1524 1525 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1526 /// VPKUWUM instruction. 1527 /// The ShuffleKind distinguishes between big-endian operations with 1528 /// two different inputs (0), either-endian operations with two identical 1529 /// inputs (1), and little-endian operations with two different inputs (2). 1530 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1531 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1532 SelectionDAG &DAG) { 1533 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1534 if (ShuffleKind == 0) { 1535 if (IsLE) 1536 return false; 1537 for (unsigned i = 0; i != 16; i += 2) 1538 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1539 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1540 return false; 1541 } else if (ShuffleKind == 2) { 1542 if (!IsLE) 1543 return false; 1544 for (unsigned i = 0; i != 16; i += 2) 1545 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1546 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1547 return false; 1548 } else if (ShuffleKind == 1) { 1549 unsigned j = IsLE ? 0 : 2; 1550 for (unsigned i = 0; i != 8; i += 2) 1551 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1552 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1553 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1554 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1555 return false; 1556 } 1557 return true; 1558 } 1559 1560 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1561 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1562 /// current subtarget. 1563 /// 1564 /// The ShuffleKind distinguishes between big-endian operations with 1565 /// two different inputs (0), either-endian operations with two identical 1566 /// inputs (1), and little-endian operations with two different inputs (2). 1567 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1568 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1569 SelectionDAG &DAG) { 1570 const PPCSubtarget& Subtarget = 1571 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 1572 if (!Subtarget.hasP8Vector()) 1573 return false; 1574 1575 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1576 if (ShuffleKind == 0) { 1577 if (IsLE) 1578 return false; 1579 for (unsigned i = 0; i != 16; i += 4) 1580 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1581 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1582 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1583 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1584 return false; 1585 } else if (ShuffleKind == 2) { 1586 if (!IsLE) 1587 return false; 1588 for (unsigned i = 0; i != 16; i += 4) 1589 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1590 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1591 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1592 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1593 return false; 1594 } else if (ShuffleKind == 1) { 1595 unsigned j = IsLE ? 0 : 4; 1596 for (unsigned i = 0; i != 8; i += 4) 1597 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1598 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1599 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1600 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1601 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1602 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1603 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1604 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1605 return false; 1606 } 1607 return true; 1608 } 1609 1610 /// isVMerge - Common function, used to match vmrg* shuffles. 1611 /// 1612 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1613 unsigned LHSStart, unsigned RHSStart) { 1614 if (N->getValueType(0) != MVT::v16i8) 1615 return false; 1616 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1617 "Unsupported merge size!"); 1618 1619 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1620 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1621 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1622 LHSStart+j+i*UnitSize) || 1623 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1624 RHSStart+j+i*UnitSize)) 1625 return false; 1626 } 1627 return true; 1628 } 1629 1630 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1631 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1632 /// The ShuffleKind distinguishes between big-endian merges with two 1633 /// different inputs (0), either-endian merges with two identical inputs (1), 1634 /// and little-endian merges with two different inputs (2). For the latter, 1635 /// the input operands are swapped (see PPCInstrAltivec.td). 1636 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1637 unsigned ShuffleKind, SelectionDAG &DAG) { 1638 if (DAG.getDataLayout().isLittleEndian()) { 1639 if (ShuffleKind == 1) // unary 1640 return isVMerge(N, UnitSize, 0, 0); 1641 else if (ShuffleKind == 2) // swapped 1642 return isVMerge(N, UnitSize, 0, 16); 1643 else 1644 return false; 1645 } else { 1646 if (ShuffleKind == 1) // unary 1647 return isVMerge(N, UnitSize, 8, 8); 1648 else if (ShuffleKind == 0) // normal 1649 return isVMerge(N, UnitSize, 8, 24); 1650 else 1651 return false; 1652 } 1653 } 1654 1655 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1656 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1657 /// The ShuffleKind distinguishes between big-endian merges with two 1658 /// different inputs (0), either-endian merges with two identical inputs (1), 1659 /// and little-endian merges with two different inputs (2). For the latter, 1660 /// the input operands are swapped (see PPCInstrAltivec.td). 1661 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1662 unsigned ShuffleKind, SelectionDAG &DAG) { 1663 if (DAG.getDataLayout().isLittleEndian()) { 1664 if (ShuffleKind == 1) // unary 1665 return isVMerge(N, UnitSize, 8, 8); 1666 else if (ShuffleKind == 2) // swapped 1667 return isVMerge(N, UnitSize, 8, 24); 1668 else 1669 return false; 1670 } else { 1671 if (ShuffleKind == 1) // unary 1672 return isVMerge(N, UnitSize, 0, 0); 1673 else if (ShuffleKind == 0) // normal 1674 return isVMerge(N, UnitSize, 0, 16); 1675 else 1676 return false; 1677 } 1678 } 1679 1680 /** 1681 * Common function used to match vmrgew and vmrgow shuffles 1682 * 1683 * The indexOffset determines whether to look for even or odd words in 1684 * the shuffle mask. This is based on the of the endianness of the target 1685 * machine. 1686 * - Little Endian: 1687 * - Use offset of 0 to check for odd elements 1688 * - Use offset of 4 to check for even elements 1689 * - Big Endian: 1690 * - Use offset of 0 to check for even elements 1691 * - Use offset of 4 to check for odd elements 1692 * A detailed description of the vector element ordering for little endian and 1693 * big endian can be found at 1694 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 1695 * Targeting your applications - what little endian and big endian IBM XL C/C++ 1696 * compiler differences mean to you 1697 * 1698 * The mask to the shuffle vector instruction specifies the indices of the 1699 * elements from the two input vectors to place in the result. The elements are 1700 * numbered in array-access order, starting with the first vector. These vectors 1701 * are always of type v16i8, thus each vector will contain 16 elements of size 1702 * 8. More info on the shuffle vector can be found in the 1703 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 1704 * Language Reference. 1705 * 1706 * The RHSStartValue indicates whether the same input vectors are used (unary) 1707 * or two different input vectors are used, based on the following: 1708 * - If the instruction uses the same vector for both inputs, the range of the 1709 * indices will be 0 to 15. In this case, the RHSStart value passed should 1710 * be 0. 1711 * - If the instruction has two different vectors then the range of the 1712 * indices will be 0 to 31. In this case, the RHSStart value passed should 1713 * be 16 (indices 0-15 specify elements in the first vector while indices 16 1714 * to 31 specify elements in the second vector). 1715 * 1716 * \param[in] N The shuffle vector SD Node to analyze 1717 * \param[in] IndexOffset Specifies whether to look for even or odd elements 1718 * \param[in] RHSStartValue Specifies the starting index for the righthand input 1719 * vector to the shuffle_vector instruction 1720 * \return true iff this shuffle vector represents an even or odd word merge 1721 */ 1722 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 1723 unsigned RHSStartValue) { 1724 if (N->getValueType(0) != MVT::v16i8) 1725 return false; 1726 1727 for (unsigned i = 0; i < 2; ++i) 1728 for (unsigned j = 0; j < 4; ++j) 1729 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 1730 i*RHSStartValue+j+IndexOffset) || 1731 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 1732 i*RHSStartValue+j+IndexOffset+8)) 1733 return false; 1734 return true; 1735 } 1736 1737 /** 1738 * Determine if the specified shuffle mask is suitable for the vmrgew or 1739 * vmrgow instructions. 1740 * 1741 * \param[in] N The shuffle vector SD Node to analyze 1742 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 1743 * \param[in] ShuffleKind Identify the type of merge: 1744 * - 0 = big-endian merge with two different inputs; 1745 * - 1 = either-endian merge with two identical inputs; 1746 * - 2 = little-endian merge with two different inputs (inputs are swapped for 1747 * little-endian merges). 1748 * \param[in] DAG The current SelectionDAG 1749 * \return true iff this shuffle mask 1750 */ 1751 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 1752 unsigned ShuffleKind, SelectionDAG &DAG) { 1753 if (DAG.getDataLayout().isLittleEndian()) { 1754 unsigned indexOffset = CheckEven ? 4 : 0; 1755 if (ShuffleKind == 1) // Unary 1756 return isVMerge(N, indexOffset, 0); 1757 else if (ShuffleKind == 2) // swapped 1758 return isVMerge(N, indexOffset, 16); 1759 else 1760 return false; 1761 } 1762 else { 1763 unsigned indexOffset = CheckEven ? 0 : 4; 1764 if (ShuffleKind == 1) // Unary 1765 return isVMerge(N, indexOffset, 0); 1766 else if (ShuffleKind == 0) // Normal 1767 return isVMerge(N, indexOffset, 16); 1768 else 1769 return false; 1770 } 1771 return false; 1772 } 1773 1774 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 1775 /// amount, otherwise return -1. 1776 /// The ShuffleKind distinguishes between big-endian operations with two 1777 /// different inputs (0), either-endian operations with two identical inputs 1778 /// (1), and little-endian operations with two different inputs (2). For the 1779 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 1780 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 1781 SelectionDAG &DAG) { 1782 if (N->getValueType(0) != MVT::v16i8) 1783 return -1; 1784 1785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 1786 1787 // Find the first non-undef value in the shuffle mask. 1788 unsigned i; 1789 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 1790 /*search*/; 1791 1792 if (i == 16) return -1; // all undef. 1793 1794 // Otherwise, check to see if the rest of the elements are consecutively 1795 // numbered from this value. 1796 unsigned ShiftAmt = SVOp->getMaskElt(i); 1797 if (ShiftAmt < i) return -1; 1798 1799 ShiftAmt -= i; 1800 bool isLE = DAG.getDataLayout().isLittleEndian(); 1801 1802 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 1803 // Check the rest of the elements to see if they are consecutive. 1804 for (++i; i != 16; ++i) 1805 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 1806 return -1; 1807 } else if (ShuffleKind == 1) { 1808 // Check the rest of the elements to see if they are consecutive. 1809 for (++i; i != 16; ++i) 1810 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 1811 return -1; 1812 } else 1813 return -1; 1814 1815 if (isLE) 1816 ShiftAmt = 16 - ShiftAmt; 1817 1818 return ShiftAmt; 1819 } 1820 1821 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 1822 /// specifies a splat of a single element that is suitable for input to 1823 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 1824 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 1825 assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) && 1826 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 1827 1828 // The consecutive indices need to specify an element, not part of two 1829 // different elements. So abandon ship early if this isn't the case. 1830 if (N->getMaskElt(0) % EltSize != 0) 1831 return false; 1832 1833 // This is a splat operation if each element of the permute is the same, and 1834 // if the value doesn't reference the second vector. 1835 unsigned ElementBase = N->getMaskElt(0); 1836 1837 // FIXME: Handle UNDEF elements too! 1838 if (ElementBase >= 16) 1839 return false; 1840 1841 // Check that the indices are consecutive, in the case of a multi-byte element 1842 // splatted with a v16i8 mask. 1843 for (unsigned i = 1; i != EltSize; ++i) 1844 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 1845 return false; 1846 1847 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 1848 if (N->getMaskElt(i) < 0) continue; 1849 for (unsigned j = 0; j != EltSize; ++j) 1850 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 1851 return false; 1852 } 1853 return true; 1854 } 1855 1856 /// Check that the mask is shuffling N byte elements. Within each N byte 1857 /// element of the mask, the indices could be either in increasing or 1858 /// decreasing order as long as they are consecutive. 1859 /// \param[in] N the shuffle vector SD Node to analyze 1860 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 1861 /// Word/DoubleWord/QuadWord). 1862 /// \param[in] StepLen the delta indices number among the N byte element, if 1863 /// the mask is in increasing/decreasing order then it is 1/-1. 1864 /// \return true iff the mask is shuffling N byte elements. 1865 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 1866 int StepLen) { 1867 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 1868 "Unexpected element width."); 1869 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 1870 1871 unsigned NumOfElem = 16 / Width; 1872 unsigned MaskVal[16]; // Width is never greater than 16 1873 for (unsigned i = 0; i < NumOfElem; ++i) { 1874 MaskVal[0] = N->getMaskElt(i * Width); 1875 if ((StepLen == 1) && (MaskVal[0] % Width)) { 1876 return false; 1877 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 1878 return false; 1879 } 1880 1881 for (unsigned int j = 1; j < Width; ++j) { 1882 MaskVal[j] = N->getMaskElt(i * Width + j); 1883 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 1884 return false; 1885 } 1886 } 1887 } 1888 1889 return true; 1890 } 1891 1892 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1893 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 1894 if (!isNByteElemShuffleMask(N, 4, 1)) 1895 return false; 1896 1897 // Now we look at mask elements 0,4,8,12 1898 unsigned M0 = N->getMaskElt(0) / 4; 1899 unsigned M1 = N->getMaskElt(4) / 4; 1900 unsigned M2 = N->getMaskElt(8) / 4; 1901 unsigned M3 = N->getMaskElt(12) / 4; 1902 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 1903 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 1904 1905 // Below, let H and L be arbitrary elements of the shuffle mask 1906 // where H is in the range [4,7] and L is in the range [0,3]. 1907 // H, 1, 2, 3 or L, 5, 6, 7 1908 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 1909 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 1910 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 1911 InsertAtByte = IsLE ? 12 : 0; 1912 Swap = M0 < 4; 1913 return true; 1914 } 1915 // 0, H, 2, 3 or 4, L, 6, 7 1916 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 1917 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 1918 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 1919 InsertAtByte = IsLE ? 8 : 4; 1920 Swap = M1 < 4; 1921 return true; 1922 } 1923 // 0, 1, H, 3 or 4, 5, L, 7 1924 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 1925 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 1926 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 1927 InsertAtByte = IsLE ? 4 : 8; 1928 Swap = M2 < 4; 1929 return true; 1930 } 1931 // 0, 1, 2, H or 4, 5, 6, L 1932 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 1933 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 1934 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 1935 InsertAtByte = IsLE ? 0 : 12; 1936 Swap = M3 < 4; 1937 return true; 1938 } 1939 1940 // If both vector operands for the shuffle are the same vector, the mask will 1941 // contain only elements from the first one and the second one will be undef. 1942 if (N->getOperand(1).isUndef()) { 1943 ShiftElts = 0; 1944 Swap = true; 1945 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 1946 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 1947 InsertAtByte = IsLE ? 12 : 0; 1948 return true; 1949 } 1950 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 1951 InsertAtByte = IsLE ? 8 : 4; 1952 return true; 1953 } 1954 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 1955 InsertAtByte = IsLE ? 4 : 8; 1956 return true; 1957 } 1958 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 1959 InsertAtByte = IsLE ? 0 : 12; 1960 return true; 1961 } 1962 } 1963 1964 return false; 1965 } 1966 1967 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 1968 bool &Swap, bool IsLE) { 1969 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 1970 // Ensure each byte index of the word is consecutive. 1971 if (!isNByteElemShuffleMask(N, 4, 1)) 1972 return false; 1973 1974 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 1975 unsigned M0 = N->getMaskElt(0) / 4; 1976 unsigned M1 = N->getMaskElt(4) / 4; 1977 unsigned M2 = N->getMaskElt(8) / 4; 1978 unsigned M3 = N->getMaskElt(12) / 4; 1979 1980 // If both vector operands for the shuffle are the same vector, the mask will 1981 // contain only elements from the first one and the second one will be undef. 1982 if (N->getOperand(1).isUndef()) { 1983 assert(M0 < 4 && "Indexing into an undef vector?"); 1984 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 1985 return false; 1986 1987 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 1988 Swap = false; 1989 return true; 1990 } 1991 1992 // Ensure each word index of the ShuffleVector Mask is consecutive. 1993 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 1994 return false; 1995 1996 if (IsLE) { 1997 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 1998 // Input vectors don't need to be swapped if the leading element 1999 // of the result is one of the 3 left elements of the second vector 2000 // (or if there is no shift to be done at all). 2001 Swap = false; 2002 ShiftElts = (8 - M0) % 8; 2003 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2004 // Input vectors need to be swapped if the leading element 2005 // of the result is one of the 3 left elements of the first vector 2006 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2007 Swap = true; 2008 ShiftElts = (4 - M0) % 4; 2009 } 2010 2011 return true; 2012 } else { // BE 2013 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2014 // Input vectors don't need to be swapped if the leading element 2015 // of the result is one of the 4 elements of the first vector. 2016 Swap = false; 2017 ShiftElts = M0; 2018 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2019 // Input vectors need to be swapped if the leading element 2020 // of the result is one of the 4 elements of the right vector. 2021 Swap = true; 2022 ShiftElts = M0 - 4; 2023 } 2024 2025 return true; 2026 } 2027 } 2028 2029 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2030 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2031 2032 if (!isNByteElemShuffleMask(N, Width, -1)) 2033 return false; 2034 2035 for (int i = 0; i < 16; i += Width) 2036 if (N->getMaskElt(i) != i + Width - 1) 2037 return false; 2038 2039 return true; 2040 } 2041 2042 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2043 return isXXBRShuffleMaskHelper(N, 2); 2044 } 2045 2046 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2047 return isXXBRShuffleMaskHelper(N, 4); 2048 } 2049 2050 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2051 return isXXBRShuffleMaskHelper(N, 8); 2052 } 2053 2054 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2055 return isXXBRShuffleMaskHelper(N, 16); 2056 } 2057 2058 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2059 /// if the inputs to the instruction should be swapped and set \p DM to the 2060 /// value for the immediate. 2061 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2062 /// AND element 0 of the result comes from the first input (LE) or second input 2063 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2064 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2065 /// mask. 2066 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2067 bool &Swap, bool IsLE) { 2068 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2069 2070 // Ensure each byte index of the double word is consecutive. 2071 if (!isNByteElemShuffleMask(N, 8, 1)) 2072 return false; 2073 2074 unsigned M0 = N->getMaskElt(0) / 8; 2075 unsigned M1 = N->getMaskElt(8) / 8; 2076 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2077 2078 // If both vector operands for the shuffle are the same vector, the mask will 2079 // contain only elements from the first one and the second one will be undef. 2080 if (N->getOperand(1).isUndef()) { 2081 if ((M0 | M1) < 2) { 2082 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2083 Swap = false; 2084 return true; 2085 } else 2086 return false; 2087 } 2088 2089 if (IsLE) { 2090 if (M0 > 1 && M1 < 2) { 2091 Swap = false; 2092 } else if (M0 < 2 && M1 > 1) { 2093 M0 = (M0 + 2) % 4; 2094 M1 = (M1 + 2) % 4; 2095 Swap = true; 2096 } else 2097 return false; 2098 2099 // Note: if control flow comes here that means Swap is already set above 2100 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2101 return true; 2102 } else { // BE 2103 if (M0 < 2 && M1 > 1) { 2104 Swap = false; 2105 } else if (M0 > 1 && M1 < 2) { 2106 M0 = (M0 + 2) % 4; 2107 M1 = (M1 + 2) % 4; 2108 Swap = true; 2109 } else 2110 return false; 2111 2112 // Note: if control flow comes here that means Swap is already set above 2113 DM = (M0 << 1) + (M1 & 1); 2114 return true; 2115 } 2116 } 2117 2118 2119 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2120 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2121 /// elements are counted from the left of the vector register). 2122 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2123 SelectionDAG &DAG) { 2124 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2125 assert(isSplatShuffleMask(SVOp, EltSize)); 2126 if (DAG.getDataLayout().isLittleEndian()) 2127 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2128 else 2129 return SVOp->getMaskElt(0) / EltSize; 2130 } 2131 2132 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2133 /// by using a vspltis[bhw] instruction of the specified element size, return 2134 /// the constant being splatted. The ByteSize field indicates the number of 2135 /// bytes of each element [124] -> [bhw]. 2136 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2137 SDValue OpVal(nullptr, 0); 2138 2139 // If ByteSize of the splat is bigger than the element size of the 2140 // build_vector, then we have a case where we are checking for a splat where 2141 // multiple elements of the buildvector are folded together into a single 2142 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2143 unsigned EltSize = 16/N->getNumOperands(); 2144 if (EltSize < ByteSize) { 2145 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2146 SDValue UniquedVals[4]; 2147 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2148 2149 // See if all of the elements in the buildvector agree across. 2150 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2151 if (N->getOperand(i).isUndef()) continue; 2152 // If the element isn't a constant, bail fully out. 2153 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2154 2155 if (!UniquedVals[i&(Multiple-1)].getNode()) 2156 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2157 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2158 return SDValue(); // no match. 2159 } 2160 2161 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2162 // either constant or undef values that are identical for each chunk. See 2163 // if these chunks can form into a larger vspltis*. 2164 2165 // Check to see if all of the leading entries are either 0 or -1. If 2166 // neither, then this won't fit into the immediate field. 2167 bool LeadingZero = true; 2168 bool LeadingOnes = true; 2169 for (unsigned i = 0; i != Multiple-1; ++i) { 2170 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2171 2172 LeadingZero &= isNullConstant(UniquedVals[i]); 2173 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2174 } 2175 // Finally, check the least significant entry. 2176 if (LeadingZero) { 2177 if (!UniquedVals[Multiple-1].getNode()) 2178 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2179 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2180 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2181 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2182 } 2183 if (LeadingOnes) { 2184 if (!UniquedVals[Multiple-1].getNode()) 2185 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2186 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2187 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2188 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2189 } 2190 2191 return SDValue(); 2192 } 2193 2194 // Check to see if this buildvec has a single non-undef value in its elements. 2195 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2196 if (N->getOperand(i).isUndef()) continue; 2197 if (!OpVal.getNode()) 2198 OpVal = N->getOperand(i); 2199 else if (OpVal != N->getOperand(i)) 2200 return SDValue(); 2201 } 2202 2203 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2204 2205 unsigned ValSizeInBytes = EltSize; 2206 uint64_t Value = 0; 2207 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2208 Value = CN->getZExtValue(); 2209 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2210 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2211 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2212 } 2213 2214 // If the splat value is larger than the element value, then we can never do 2215 // this splat. The only case that we could fit the replicated bits into our 2216 // immediate field for would be zero, and we prefer to use vxor for it. 2217 if (ValSizeInBytes < ByteSize) return SDValue(); 2218 2219 // If the element value is larger than the splat value, check if it consists 2220 // of a repeated bit pattern of size ByteSize. 2221 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2222 return SDValue(); 2223 2224 // Properly sign extend the value. 2225 int MaskVal = SignExtend32(Value, ByteSize * 8); 2226 2227 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2228 if (MaskVal == 0) return SDValue(); 2229 2230 // Finally, if this value fits in a 5 bit sext field, return it 2231 if (SignExtend32<5>(MaskVal) == MaskVal) 2232 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2233 return SDValue(); 2234 } 2235 2236 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift 2237 /// amount, otherwise return -1. 2238 int PPC::isQVALIGNIShuffleMask(SDNode *N) { 2239 EVT VT = N->getValueType(0); 2240 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) 2241 return -1; 2242 2243 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2244 2245 // Find the first non-undef value in the shuffle mask. 2246 unsigned i; 2247 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) 2248 /*search*/; 2249 2250 if (i == 4) return -1; // all undef. 2251 2252 // Otherwise, check to see if the rest of the elements are consecutively 2253 // numbered from this value. 2254 unsigned ShiftAmt = SVOp->getMaskElt(i); 2255 if (ShiftAmt < i) return -1; 2256 ShiftAmt -= i; 2257 2258 // Check the rest of the elements to see if they are consecutive. 2259 for (++i; i != 4; ++i) 2260 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2261 return -1; 2262 2263 return ShiftAmt; 2264 } 2265 2266 //===----------------------------------------------------------------------===// 2267 // Addressing Mode Selection 2268 //===----------------------------------------------------------------------===// 2269 2270 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2271 /// or 64-bit immediate, and if the value can be accurately represented as a 2272 /// sign extension from a 16-bit value. If so, this returns true and the 2273 /// immediate. 2274 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2275 if (!isa<ConstantSDNode>(N)) 2276 return false; 2277 2278 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2279 if (N->getValueType(0) == MVT::i32) 2280 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2281 else 2282 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2283 } 2284 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2285 return isIntS16Immediate(Op.getNode(), Imm); 2286 } 2287 2288 2289 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2290 /// be represented as an indexed [r+r] operation. 2291 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2292 SDValue &Index, 2293 SelectionDAG &DAG) const { 2294 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 2295 UI != E; ++UI) { 2296 if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) { 2297 if (Memop->getMemoryVT() == MVT::f64) { 2298 Base = N.getOperand(0); 2299 Index = N.getOperand(1); 2300 return true; 2301 } 2302 } 2303 } 2304 return false; 2305 } 2306 2307 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2308 /// can be represented as an indexed [r+r] operation. Returns false if it 2309 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2310 /// non-zero and N can be represented by a base register plus a signed 16-bit 2311 /// displacement, make a more precise judgement by checking (displacement % \p 2312 /// EncodingAlignment). 2313 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, 2314 SDValue &Index, SelectionDAG &DAG, 2315 unsigned EncodingAlignment) const { 2316 int16_t imm = 0; 2317 if (N.getOpcode() == ISD::ADD) { 2318 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2319 // SPE load/store can only handle 8-bit offsets. 2320 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2321 return true; 2322 if (isIntS16Immediate(N.getOperand(1), imm) && 2323 (!EncodingAlignment || !(imm % EncodingAlignment))) 2324 return false; // r+i 2325 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2326 return false; // r+i 2327 2328 Base = N.getOperand(0); 2329 Index = N.getOperand(1); 2330 return true; 2331 } else if (N.getOpcode() == ISD::OR) { 2332 if (isIntS16Immediate(N.getOperand(1), imm) && 2333 (!EncodingAlignment || !(imm % EncodingAlignment))) 2334 return false; // r+i can fold it if we can. 2335 2336 // If this is an or of disjoint bitfields, we can codegen this as an add 2337 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2338 // disjoint. 2339 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2340 2341 if (LHSKnown.Zero.getBoolValue()) { 2342 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2343 // If all of the bits are known zero on the LHS or RHS, the add won't 2344 // carry. 2345 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2346 Base = N.getOperand(0); 2347 Index = N.getOperand(1); 2348 return true; 2349 } 2350 } 2351 } 2352 2353 return false; 2354 } 2355 2356 // If we happen to be doing an i64 load or store into a stack slot that has 2357 // less than a 4-byte alignment, then the frame-index elimination may need to 2358 // use an indexed load or store instruction (because the offset may not be a 2359 // multiple of 4). The extra register needed to hold the offset comes from the 2360 // register scavenger, and it is possible that the scavenger will need to use 2361 // an emergency spill slot. As a result, we need to make sure that a spill slot 2362 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2363 // stack slot. 2364 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2365 // FIXME: This does not handle the LWA case. 2366 if (VT != MVT::i64) 2367 return; 2368 2369 // NOTE: We'll exclude negative FIs here, which come from argument 2370 // lowering, because there are no known test cases triggering this problem 2371 // using packed structures (or similar). We can remove this exclusion if 2372 // we find such a test case. The reason why this is so test-case driven is 2373 // because this entire 'fixup' is only to prevent crashes (from the 2374 // register scavenger) on not-really-valid inputs. For example, if we have: 2375 // %a = alloca i1 2376 // %b = bitcast i1* %a to i64* 2377 // store i64* a, i64 b 2378 // then the store should really be marked as 'align 1', but is not. If it 2379 // were marked as 'align 1' then the indexed form would have been 2380 // instruction-selected initially, and the problem this 'fixup' is preventing 2381 // won't happen regardless. 2382 if (FrameIdx < 0) 2383 return; 2384 2385 MachineFunction &MF = DAG.getMachineFunction(); 2386 MachineFrameInfo &MFI = MF.getFrameInfo(); 2387 2388 unsigned Align = MFI.getObjectAlignment(FrameIdx); 2389 if (Align >= 4) 2390 return; 2391 2392 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2393 FuncInfo->setHasNonRISpills(); 2394 } 2395 2396 /// Returns true if the address N can be represented by a base register plus 2397 /// a signed 16-bit displacement [r+imm], and if it is not better 2398 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2399 /// displacements that are multiples of that value. 2400 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, 2401 SDValue &Base, 2402 SelectionDAG &DAG, 2403 unsigned EncodingAlignment) const { 2404 // FIXME dl should come from parent load or store, not from address 2405 SDLoc dl(N); 2406 // If this can be more profitably realized as r+r, fail. 2407 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2408 return false; 2409 2410 if (N.getOpcode() == ISD::ADD) { 2411 int16_t imm = 0; 2412 if (isIntS16Immediate(N.getOperand(1), imm) && 2413 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2414 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2415 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2416 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2417 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2418 } else { 2419 Base = N.getOperand(0); 2420 } 2421 return true; // [r+i] 2422 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2423 // Match LOAD (ADD (X, Lo(G))). 2424 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2425 && "Cannot handle constant offsets yet!"); 2426 Disp = N.getOperand(1).getOperand(0); // The global address. 2427 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2428 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2429 Disp.getOpcode() == ISD::TargetConstantPool || 2430 Disp.getOpcode() == ISD::TargetJumpTable); 2431 Base = N.getOperand(0); 2432 return true; // [&g+r] 2433 } 2434 } else if (N.getOpcode() == ISD::OR) { 2435 int16_t imm = 0; 2436 if (isIntS16Immediate(N.getOperand(1), imm) && 2437 (!EncodingAlignment || (imm % EncodingAlignment) == 0)) { 2438 // If this is an or of disjoint bitfields, we can codegen this as an add 2439 // (for better address arithmetic) if the LHS and RHS of the OR are 2440 // provably disjoint. 2441 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2442 2443 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2444 // If all of the bits are known zero on the LHS or RHS, the add won't 2445 // carry. 2446 if (FrameIndexSDNode *FI = 2447 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2448 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2449 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2450 } else { 2451 Base = N.getOperand(0); 2452 } 2453 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2454 return true; 2455 } 2456 } 2457 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2458 // Loading from a constant address. 2459 2460 // If this address fits entirely in a 16-bit sext immediate field, codegen 2461 // this as "d, 0" 2462 int16_t Imm; 2463 if (isIntS16Immediate(CN, Imm) && 2464 (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) { 2465 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2466 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2467 CN->getValueType(0)); 2468 return true; 2469 } 2470 2471 // Handle 32-bit sext immediates with LIS + addr mode. 2472 if ((CN->getValueType(0) == MVT::i32 || 2473 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2474 (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) { 2475 int Addr = (int)CN->getZExtValue(); 2476 2477 // Otherwise, break this down into an LIS + disp. 2478 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2479 2480 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2481 MVT::i32); 2482 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2483 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2484 return true; 2485 } 2486 } 2487 2488 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2489 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2490 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2491 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2492 } else 2493 Base = N; 2494 return true; // [r+0] 2495 } 2496 2497 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2498 /// represented as an indexed [r+r] operation. 2499 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2500 SDValue &Index, 2501 SelectionDAG &DAG) const { 2502 // Check to see if we can easily represent this as an [r+r] address. This 2503 // will fail if it thinks that the address is more profitably represented as 2504 // reg+imm, e.g. where imm = 0. 2505 if (SelectAddressRegReg(N, Base, Index, DAG)) 2506 return true; 2507 2508 // If the address is the result of an add, we will utilize the fact that the 2509 // address calculation includes an implicit add. However, we can reduce 2510 // register pressure if we do not materialize a constant just for use as the 2511 // index register. We only get rid of the add if it is not an add of a 2512 // value and a 16-bit signed constant and both have a single use. 2513 int16_t imm = 0; 2514 if (N.getOpcode() == ISD::ADD && 2515 (!isIntS16Immediate(N.getOperand(1), imm) || 2516 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2517 Base = N.getOperand(0); 2518 Index = N.getOperand(1); 2519 return true; 2520 } 2521 2522 // Otherwise, do it the hard way, using R0 as the base register. 2523 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2524 N.getValueType()); 2525 Index = N; 2526 return true; 2527 } 2528 2529 /// Returns true if we should use a direct load into vector instruction 2530 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2531 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2532 2533 // If there are any other uses other than scalar to vector, then we should 2534 // keep it as a scalar load -> direct move pattern to prevent multiple 2535 // loads. 2536 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2537 if (!LD) 2538 return false; 2539 2540 EVT MemVT = LD->getMemoryVT(); 2541 if (!MemVT.isSimple()) 2542 return false; 2543 switch(MemVT.getSimpleVT().SimpleTy) { 2544 case MVT::i64: 2545 break; 2546 case MVT::i32: 2547 if (!ST.hasP8Vector()) 2548 return false; 2549 break; 2550 case MVT::i16: 2551 case MVT::i8: 2552 if (!ST.hasP9Vector()) 2553 return false; 2554 break; 2555 default: 2556 return false; 2557 } 2558 2559 SDValue LoadedVal(N, 0); 2560 if (!LoadedVal.hasOneUse()) 2561 return false; 2562 2563 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2564 UI != UE; ++UI) 2565 if (UI.getUse().get().getResNo() == 0 && 2566 UI->getOpcode() != ISD::SCALAR_TO_VECTOR) 2567 return false; 2568 2569 return true; 2570 } 2571 2572 /// getPreIndexedAddressParts - returns true by value, base pointer and 2573 /// offset pointer and addressing mode by reference if the node's address 2574 /// can be legally represented as pre-indexed load / store address. 2575 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 2576 SDValue &Offset, 2577 ISD::MemIndexedMode &AM, 2578 SelectionDAG &DAG) const { 2579 if (DisablePPCPreinc) return false; 2580 2581 bool isLoad = true; 2582 SDValue Ptr; 2583 EVT VT; 2584 unsigned Alignment; 2585 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2586 Ptr = LD->getBasePtr(); 2587 VT = LD->getMemoryVT(); 2588 Alignment = LD->getAlignment(); 2589 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 2590 Ptr = ST->getBasePtr(); 2591 VT = ST->getMemoryVT(); 2592 Alignment = ST->getAlignment(); 2593 isLoad = false; 2594 } else 2595 return false; 2596 2597 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 2598 // instructions because we can fold these into a more efficient instruction 2599 // instead, (such as LXSD). 2600 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 2601 return false; 2602 } 2603 2604 // PowerPC doesn't have preinc load/store instructions for vectors (except 2605 // for QPX, which does have preinc r+r forms). 2606 if (VT.isVector()) { 2607 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { 2608 return false; 2609 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { 2610 AM = ISD::PRE_INC; 2611 return true; 2612 } 2613 } 2614 2615 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 2616 // Common code will reject creating a pre-inc form if the base pointer 2617 // is a frame index, or if N is a store and the base pointer is either 2618 // the same as or a predecessor of the value being stored. Check for 2619 // those situations here, and try with swapped Base/Offset instead. 2620 bool Swap = false; 2621 2622 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 2623 Swap = true; 2624 else if (!isLoad) { 2625 SDValue Val = cast<StoreSDNode>(N)->getValue(); 2626 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 2627 Swap = true; 2628 } 2629 2630 if (Swap) 2631 std::swap(Base, Offset); 2632 2633 AM = ISD::PRE_INC; 2634 return true; 2635 } 2636 2637 // LDU/STU can only handle immediates that are a multiple of 4. 2638 if (VT != MVT::i64) { 2639 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0)) 2640 return false; 2641 } else { 2642 // LDU/STU need an address with at least 4-byte alignment. 2643 if (Alignment < 4) 2644 return false; 2645 2646 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4)) 2647 return false; 2648 } 2649 2650 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 2651 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 2652 // sext i32 to i64 when addr mode is r+i. 2653 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 2654 LD->getExtensionType() == ISD::SEXTLOAD && 2655 isa<ConstantSDNode>(Offset)) 2656 return false; 2657 } 2658 2659 AM = ISD::PRE_INC; 2660 return true; 2661 } 2662 2663 //===----------------------------------------------------------------------===// 2664 // LowerOperation implementation 2665 //===----------------------------------------------------------------------===// 2666 2667 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 2668 /// and LoOpFlags to the target MO flags. 2669 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 2670 unsigned &HiOpFlags, unsigned &LoOpFlags, 2671 const GlobalValue *GV = nullptr) { 2672 HiOpFlags = PPCII::MO_HA; 2673 LoOpFlags = PPCII::MO_LO; 2674 2675 // Don't use the pic base if not in PIC relocation model. 2676 if (IsPIC) { 2677 HiOpFlags |= PPCII::MO_PIC_FLAG; 2678 LoOpFlags |= PPCII::MO_PIC_FLAG; 2679 } 2680 } 2681 2682 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 2683 SelectionDAG &DAG) { 2684 SDLoc DL(HiPart); 2685 EVT PtrVT = HiPart.getValueType(); 2686 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 2687 2688 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 2689 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 2690 2691 // With PIC, the first instruction is actually "GR+hi(&G)". 2692 if (isPIC) 2693 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 2694 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 2695 2696 // Generate non-pic code that has direct accesses to the constant pool. 2697 // The address of the global is just (hi(&g)+lo(&g)). 2698 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 2699 } 2700 2701 static void setUsesTOCBasePtr(MachineFunction &MF) { 2702 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2703 FuncInfo->setUsesTOCBasePtr(); 2704 } 2705 2706 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 2707 setUsesTOCBasePtr(DAG.getMachineFunction()); 2708 } 2709 2710 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 2711 SDValue GA) const { 2712 const bool Is64Bit = Subtarget.isPPC64(); 2713 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 2714 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 2715 : Subtarget.isAIXABI() 2716 ? DAG.getRegister(PPC::R2, VT) 2717 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 2718 SDValue Ops[] = { GA, Reg }; 2719 return DAG.getMemIntrinsicNode( 2720 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 2721 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, 2722 MachineMemOperand::MOLoad); 2723 } 2724 2725 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 2726 SelectionDAG &DAG) const { 2727 EVT PtrVT = Op.getValueType(); 2728 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 2729 const Constant *C = CP->getConstVal(); 2730 2731 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2732 // The actual address of the GlobalValue is stored in the TOC. 2733 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2734 setUsesTOCBasePtr(DAG); 2735 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); 2736 return getTOCEntry(DAG, SDLoc(CP), GA); 2737 } 2738 2739 unsigned MOHiFlag, MOLoFlag; 2740 bool IsPIC = isPositionIndependent(); 2741 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2742 2743 if (IsPIC && Subtarget.isSVR4ABI()) { 2744 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 2745 PPCII::MO_PIC_FLAG); 2746 return getTOCEntry(DAG, SDLoc(CP), GA); 2747 } 2748 2749 SDValue CPIHi = 2750 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); 2751 SDValue CPILo = 2752 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); 2753 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 2754 } 2755 2756 // For 64-bit PowerPC, prefer the more compact relative encodings. 2757 // This trades 32 bits per jump table entry for one or two instructions 2758 // on the jump site. 2759 unsigned PPCTargetLowering::getJumpTableEncoding() const { 2760 if (isJumpTableRelative()) 2761 return MachineJumpTableInfo::EK_LabelDifference32; 2762 2763 return TargetLowering::getJumpTableEncoding(); 2764 } 2765 2766 bool PPCTargetLowering::isJumpTableRelative() const { 2767 if (UseAbsoluteJumpTables) 2768 return false; 2769 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 2770 return true; 2771 return TargetLowering::isJumpTableRelative(); 2772 } 2773 2774 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 2775 SelectionDAG &DAG) const { 2776 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2777 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2778 2779 switch (getTargetMachine().getCodeModel()) { 2780 case CodeModel::Small: 2781 case CodeModel::Medium: 2782 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 2783 default: 2784 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 2785 getPointerTy(DAG.getDataLayout())); 2786 } 2787 } 2788 2789 const MCExpr * 2790 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 2791 unsigned JTI, 2792 MCContext &Ctx) const { 2793 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 2794 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2795 2796 switch (getTargetMachine().getCodeModel()) { 2797 case CodeModel::Small: 2798 case CodeModel::Medium: 2799 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 2800 default: 2801 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 2802 } 2803 } 2804 2805 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 2806 EVT PtrVT = Op.getValueType(); 2807 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 2808 2809 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2810 // The actual address of the GlobalValue is stored in the TOC. 2811 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2812 setUsesTOCBasePtr(DAG); 2813 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 2814 return getTOCEntry(DAG, SDLoc(JT), GA); 2815 } 2816 2817 unsigned MOHiFlag, MOLoFlag; 2818 bool IsPIC = isPositionIndependent(); 2819 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2820 2821 if (IsPIC && Subtarget.isSVR4ABI()) { 2822 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 2823 PPCII::MO_PIC_FLAG); 2824 return getTOCEntry(DAG, SDLoc(GA), GA); 2825 } 2826 2827 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 2828 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 2829 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 2830 } 2831 2832 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 2833 SelectionDAG &DAG) const { 2834 EVT PtrVT = Op.getValueType(); 2835 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 2836 const BlockAddress *BA = BASDN->getBlockAddress(); 2837 2838 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 2839 // The actual BlockAddress is stored in the TOC. 2840 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2841 setUsesTOCBasePtr(DAG); 2842 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 2843 return getTOCEntry(DAG, SDLoc(BASDN), GA); 2844 } 2845 2846 // 32-bit position-independent ELF stores the BlockAddress in the .got. 2847 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 2848 return getTOCEntry( 2849 DAG, SDLoc(BASDN), 2850 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 2851 2852 unsigned MOHiFlag, MOLoFlag; 2853 bool IsPIC = isPositionIndependent(); 2854 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 2855 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 2856 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 2857 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 2858 } 2859 2860 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 2861 SelectionDAG &DAG) const { 2862 // FIXME: TLS addresses currently use medium model code sequences, 2863 // which is the most useful form. Eventually support for small and 2864 // large models could be added if users need it, at the cost of 2865 // additional complexity. 2866 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 2867 if (DAG.getTarget().useEmulatedTLS()) 2868 return LowerToTLSEmulatedModel(GA, DAG); 2869 2870 SDLoc dl(GA); 2871 const GlobalValue *GV = GA->getGlobal(); 2872 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2873 bool is64bit = Subtarget.isPPC64(); 2874 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 2875 PICLevel::Level picLevel = M->getPICLevel(); 2876 2877 const TargetMachine &TM = getTargetMachine(); 2878 TLSModel::Model Model = TM.getTLSModel(GV); 2879 2880 if (Model == TLSModel::LocalExec) { 2881 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2882 PPCII::MO_TPREL_HA); 2883 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2884 PPCII::MO_TPREL_LO); 2885 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 2886 : DAG.getRegister(PPC::R2, MVT::i32); 2887 2888 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 2889 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 2890 } 2891 2892 if (Model == TLSModel::InitialExec) { 2893 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2894 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 2895 PPCII::MO_TLS); 2896 SDValue GOTPtr; 2897 if (is64bit) { 2898 setUsesTOCBasePtr(DAG); 2899 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2900 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, 2901 PtrVT, GOTReg, TGA); 2902 } else { 2903 if (!TM.isPositionIndependent()) 2904 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 2905 else if (picLevel == PICLevel::SmallPIC) 2906 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2907 else 2908 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2909 } 2910 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, 2911 PtrVT, TGA, GOTPtr); 2912 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 2913 } 2914 2915 if (Model == TLSModel::GeneralDynamic) { 2916 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2917 SDValue GOTPtr; 2918 if (is64bit) { 2919 setUsesTOCBasePtr(DAG); 2920 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2921 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 2922 GOTReg, TGA); 2923 } else { 2924 if (picLevel == PICLevel::SmallPIC) 2925 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2926 else 2927 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2928 } 2929 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 2930 GOTPtr, TGA, TGA); 2931 } 2932 2933 if (Model == TLSModel::LocalDynamic) { 2934 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 2935 SDValue GOTPtr; 2936 if (is64bit) { 2937 setUsesTOCBasePtr(DAG); 2938 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 2939 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 2940 GOTReg, TGA); 2941 } else { 2942 if (picLevel == PICLevel::SmallPIC) 2943 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 2944 else 2945 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 2946 } 2947 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 2948 PtrVT, GOTPtr, TGA, TGA); 2949 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 2950 PtrVT, TLSAddr, TGA); 2951 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 2952 } 2953 2954 llvm_unreachable("Unknown TLS model!"); 2955 } 2956 2957 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 2958 SelectionDAG &DAG) const { 2959 EVT PtrVT = Op.getValueType(); 2960 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 2961 SDLoc DL(GSDN); 2962 const GlobalValue *GV = GSDN->getGlobal(); 2963 2964 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 2965 // The actual address of the GlobalValue is stored in the TOC. 2966 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 2967 setUsesTOCBasePtr(DAG); 2968 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 2969 return getTOCEntry(DAG, DL, GA); 2970 } 2971 2972 unsigned MOHiFlag, MOLoFlag; 2973 bool IsPIC = isPositionIndependent(); 2974 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 2975 2976 if (IsPIC && Subtarget.isSVR4ABI()) { 2977 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 2978 GSDN->getOffset(), 2979 PPCII::MO_PIC_FLAG); 2980 return getTOCEntry(DAG, DL, GA); 2981 } 2982 2983 SDValue GAHi = 2984 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 2985 SDValue GALo = 2986 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 2987 2988 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 2989 } 2990 2991 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 2992 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 2993 SDLoc dl(Op); 2994 2995 if (Op.getValueType() == MVT::v2i64) { 2996 // When the operands themselves are v2i64 values, we need to do something 2997 // special because VSX has no underlying comparison operations for these. 2998 if (Op.getOperand(0).getValueType() == MVT::v2i64) { 2999 // Equality can be handled by casting to the legal type for Altivec 3000 // comparisons, everything else needs to be expanded. 3001 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3002 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, 3003 DAG.getSetCC(dl, MVT::v4i32, 3004 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), 3005 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), 3006 CC)); 3007 } 3008 3009 return SDValue(); 3010 } 3011 3012 // We handle most of these in the usual way. 3013 return Op; 3014 } 3015 3016 // If we're comparing for equality to zero, expose the fact that this is 3017 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3018 // fold the new nodes. 3019 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3020 return V; 3021 3022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3023 // Leave comparisons against 0 and -1 alone for now, since they're usually 3024 // optimized. FIXME: revisit this when we can custom lower all setcc 3025 // optimizations. 3026 if (C->isAllOnesValue() || C->isNullValue()) 3027 return SDValue(); 3028 } 3029 3030 // If we have an integer seteq/setne, turn it into a compare against zero 3031 // by xor'ing the rhs with the lhs, which is faster than setting a 3032 // condition register, reading it back out, and masking the correct bit. The 3033 // normal approach here uses sub to do this instead of xor. Using xor exposes 3034 // the result to other bit-twiddling opportunities. 3035 EVT LHSVT = Op.getOperand(0).getValueType(); 3036 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3037 EVT VT = Op.getValueType(); 3038 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), 3039 Op.getOperand(1)); 3040 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3041 } 3042 return SDValue(); 3043 } 3044 3045 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3046 SDNode *Node = Op.getNode(); 3047 EVT VT = Node->getValueType(0); 3048 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3049 SDValue InChain = Node->getOperand(0); 3050 SDValue VAListPtr = Node->getOperand(1); 3051 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3052 SDLoc dl(Node); 3053 3054 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3055 3056 // gpr_index 3057 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3058 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3059 InChain = GprIndex.getValue(1); 3060 3061 if (VT == MVT::i64) { 3062 // Check if GprIndex is even 3063 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3064 DAG.getConstant(1, dl, MVT::i32)); 3065 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3066 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3067 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3068 DAG.getConstant(1, dl, MVT::i32)); 3069 // Align GprIndex to be even if it isn't 3070 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3071 GprIndex); 3072 } 3073 3074 // fpr index is 1 byte after gpr 3075 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3076 DAG.getConstant(1, dl, MVT::i32)); 3077 3078 // fpr 3079 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3080 FprPtr, MachinePointerInfo(SV), MVT::i8); 3081 InChain = FprIndex.getValue(1); 3082 3083 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3084 DAG.getConstant(8, dl, MVT::i32)); 3085 3086 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3087 DAG.getConstant(4, dl, MVT::i32)); 3088 3089 // areas 3090 SDValue OverflowArea = 3091 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3092 InChain = OverflowArea.getValue(1); 3093 3094 SDValue RegSaveArea = 3095 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3096 InChain = RegSaveArea.getValue(1); 3097 3098 // select overflow_area if index > 8 3099 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3100 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3101 3102 // adjustment constant gpr_index * 4/8 3103 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3104 VT.isInteger() ? GprIndex : FprIndex, 3105 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3106 MVT::i32)); 3107 3108 // OurReg = RegSaveArea + RegConstant 3109 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3110 RegConstant); 3111 3112 // Floating types are 32 bytes into RegSaveArea 3113 if (VT.isFloatingPoint()) 3114 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3115 DAG.getConstant(32, dl, MVT::i32)); 3116 3117 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3118 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3119 VT.isInteger() ? GprIndex : FprIndex, 3120 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3121 MVT::i32)); 3122 3123 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3124 VT.isInteger() ? VAListPtr : FprPtr, 3125 MachinePointerInfo(SV), MVT::i8); 3126 3127 // determine if we should load from reg_save_area or overflow_area 3128 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3129 3130 // increase overflow_area by 4/8 if gpr/fpr > 8 3131 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3132 DAG.getConstant(VT.isInteger() ? 4 : 8, 3133 dl, MVT::i32)); 3134 3135 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3136 OverflowAreaPlusN); 3137 3138 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3139 MachinePointerInfo(), MVT::i32); 3140 3141 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3142 } 3143 3144 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3145 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3146 3147 // We have to copy the entire va_list struct: 3148 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3149 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3150 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3151 false, true, false, MachinePointerInfo(), 3152 MachinePointerInfo()); 3153 } 3154 3155 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3156 SelectionDAG &DAG) const { 3157 if (Subtarget.isAIXABI()) 3158 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3159 3160 return Op.getOperand(0); 3161 } 3162 3163 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3164 SelectionDAG &DAG) const { 3165 if (Subtarget.isAIXABI()) 3166 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3167 3168 SDValue Chain = Op.getOperand(0); 3169 SDValue Trmp = Op.getOperand(1); // trampoline 3170 SDValue FPtr = Op.getOperand(2); // nested function 3171 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3172 SDLoc dl(Op); 3173 3174 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3175 bool isPPC64 = (PtrVT == MVT::i64); 3176 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3177 3178 TargetLowering::ArgListTy Args; 3179 TargetLowering::ArgListEntry Entry; 3180 3181 Entry.Ty = IntPtrTy; 3182 Entry.Node = Trmp; Args.push_back(Entry); 3183 3184 // TrampSize == (isPPC64 ? 48 : 40); 3185 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3186 isPPC64 ? MVT::i64 : MVT::i32); 3187 Args.push_back(Entry); 3188 3189 Entry.Node = FPtr; Args.push_back(Entry); 3190 Entry.Node = Nest; Args.push_back(Entry); 3191 3192 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3193 TargetLowering::CallLoweringInfo CLI(DAG); 3194 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3195 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3196 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3197 3198 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3199 return CallResult.second; 3200 } 3201 3202 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3203 MachineFunction &MF = DAG.getMachineFunction(); 3204 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3205 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3206 3207 SDLoc dl(Op); 3208 3209 if (Subtarget.isPPC64()) { 3210 // vastart just stores the address of the VarArgsFrameIndex slot into the 3211 // memory location argument. 3212 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3213 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3214 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3215 MachinePointerInfo(SV)); 3216 } 3217 3218 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3219 // We suppose the given va_list is already allocated. 3220 // 3221 // typedef struct { 3222 // char gpr; /* index into the array of 8 GPRs 3223 // * stored in the register save area 3224 // * gpr=0 corresponds to r3, 3225 // * gpr=1 to r4, etc. 3226 // */ 3227 // char fpr; /* index into the array of 8 FPRs 3228 // * stored in the register save area 3229 // * fpr=0 corresponds to f1, 3230 // * fpr=1 to f2, etc. 3231 // */ 3232 // char *overflow_arg_area; 3233 // /* location on stack that holds 3234 // * the next overflow argument 3235 // */ 3236 // char *reg_save_area; 3237 // /* where r3:r10 and f1:f8 (if saved) 3238 // * are stored 3239 // */ 3240 // } va_list[1]; 3241 3242 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3243 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3244 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3245 PtrVT); 3246 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3247 PtrVT); 3248 3249 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3250 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3251 3252 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3253 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3254 3255 uint64_t FPROffset = 1; 3256 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3257 3258 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3259 3260 // Store first byte : number of int regs 3261 SDValue firstStore = 3262 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3263 MachinePointerInfo(SV), MVT::i8); 3264 uint64_t nextOffset = FPROffset; 3265 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3266 ConstFPROffset); 3267 3268 // Store second byte : number of float regs 3269 SDValue secondStore = 3270 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3271 MachinePointerInfo(SV, nextOffset), MVT::i8); 3272 nextOffset += StackOffset; 3273 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3274 3275 // Store second word : arguments given on stack 3276 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3277 MachinePointerInfo(SV, nextOffset)); 3278 nextOffset += FrameOffset; 3279 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3280 3281 // Store third word : arguments given in registers 3282 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3283 MachinePointerInfo(SV, nextOffset)); 3284 } 3285 3286 /// FPR - The set of FP registers that should be allocated for arguments 3287 /// on Darwin and AIX. 3288 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3289 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3290 PPC::F11, PPC::F12, PPC::F13}; 3291 3292 /// QFPR - The set of QPX registers that should be allocated for arguments. 3293 static const MCPhysReg QFPR[] = { 3294 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, 3295 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; 3296 3297 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3298 /// the stack. 3299 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3300 unsigned PtrByteSize) { 3301 unsigned ArgSize = ArgVT.getStoreSize(); 3302 if (Flags.isByVal()) 3303 ArgSize = Flags.getByValSize(); 3304 3305 // Round up to multiples of the pointer size, except for array members, 3306 // which are always packed. 3307 if (!Flags.isInConsecutiveRegs()) 3308 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3309 3310 return ArgSize; 3311 } 3312 3313 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3314 /// on the stack. 3315 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3316 ISD::ArgFlagsTy Flags, 3317 unsigned PtrByteSize) { 3318 Align Alignment(PtrByteSize); 3319 3320 // Altivec parameters are padded to a 16 byte boundary. 3321 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3322 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3323 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3324 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3325 Alignment = Align(16); 3326 // QPX vector types stored in double-precision are padded to a 32 byte 3327 // boundary. 3328 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) 3329 Alignment = Align(32); 3330 3331 // ByVal parameters are aligned as requested. 3332 if (Flags.isByVal()) { 3333 auto BVAlign = Flags.getNonZeroByValAlign(); 3334 if (BVAlign > PtrByteSize) { 3335 if (BVAlign.value() % PtrByteSize != 0) 3336 llvm_unreachable( 3337 "ByVal alignment is not a multiple of the pointer size"); 3338 3339 Alignment = BVAlign; 3340 } 3341 } 3342 3343 // Array members are always packed to their original alignment. 3344 if (Flags.isInConsecutiveRegs()) { 3345 // If the array member was split into multiple registers, the first 3346 // needs to be aligned to the size of the full type. (Except for 3347 // ppcf128, which is only aligned as its f64 components.) 3348 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3349 Alignment = Align(OrigVT.getStoreSize()); 3350 else 3351 Alignment = Align(ArgVT.getStoreSize()); 3352 } 3353 3354 return Alignment; 3355 } 3356 3357 /// CalculateStackSlotUsed - Return whether this argument will use its 3358 /// stack slot (instead of being passed in registers). ArgOffset, 3359 /// AvailableFPRs, and AvailableVRs must hold the current argument 3360 /// position, and will be updated to account for this argument. 3361 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, 3362 ISD::ArgFlagsTy Flags, 3363 unsigned PtrByteSize, 3364 unsigned LinkageSize, 3365 unsigned ParamAreaSize, 3366 unsigned &ArgOffset, 3367 unsigned &AvailableFPRs, 3368 unsigned &AvailableVRs, bool HasQPX) { 3369 bool UseMemory = false; 3370 3371 // Respect alignment of argument on the stack. 3372 Align Alignment = 3373 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3374 ArgOffset = alignTo(ArgOffset, Alignment); 3375 // If there's no space left in the argument save area, we must 3376 // use memory (this check also catches zero-sized arguments). 3377 if (ArgOffset >= LinkageSize + ParamAreaSize) 3378 UseMemory = true; 3379 3380 // Allocate argument on the stack. 3381 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3382 if (Flags.isInConsecutiveRegsLast()) 3383 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3384 // If we overran the argument save area, we must use memory 3385 // (this check catches arguments passed partially in memory) 3386 if (ArgOffset > LinkageSize + ParamAreaSize) 3387 UseMemory = true; 3388 3389 // However, if the argument is actually passed in an FPR or a VR, 3390 // we don't use memory after all. 3391 if (!Flags.isByVal()) { 3392 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || 3393 // QPX registers overlap with the scalar FP registers. 3394 (HasQPX && (ArgVT == MVT::v4f32 || 3395 ArgVT == MVT::v4f64 || 3396 ArgVT == MVT::v4i1))) 3397 if (AvailableFPRs > 0) { 3398 --AvailableFPRs; 3399 return false; 3400 } 3401 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3402 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3403 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3404 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3405 if (AvailableVRs > 0) { 3406 --AvailableVRs; 3407 return false; 3408 } 3409 } 3410 3411 return UseMemory; 3412 } 3413 3414 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 3415 /// ensure minimum alignment required for target. 3416 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 3417 unsigned NumBytes) { 3418 unsigned TargetAlign = Lowering->getStackAlignment(); 3419 unsigned AlignMask = TargetAlign - 1; 3420 NumBytes = (NumBytes + AlignMask) & ~AlignMask; 3421 return NumBytes; 3422 } 3423 3424 SDValue PPCTargetLowering::LowerFormalArguments( 3425 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3426 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3427 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3428 if (Subtarget.isAIXABI()) 3429 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 3430 InVals); 3431 if (Subtarget.is64BitELFABI()) 3432 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3433 InVals); 3434 if (Subtarget.is32BitELFABI()) 3435 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 3436 InVals); 3437 3438 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, 3439 InVals); 3440 } 3441 3442 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 3443 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3444 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3445 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3446 3447 // 32-bit SVR4 ABI Stack Frame Layout: 3448 // +-----------------------------------+ 3449 // +--> | Back chain | 3450 // | +-----------------------------------+ 3451 // | | Floating-point register save area | 3452 // | +-----------------------------------+ 3453 // | | General register save area | 3454 // | +-----------------------------------+ 3455 // | | CR save word | 3456 // | +-----------------------------------+ 3457 // | | VRSAVE save word | 3458 // | +-----------------------------------+ 3459 // | | Alignment padding | 3460 // | +-----------------------------------+ 3461 // | | Vector register save area | 3462 // | +-----------------------------------+ 3463 // | | Local variable space | 3464 // | +-----------------------------------+ 3465 // | | Parameter list area | 3466 // | +-----------------------------------+ 3467 // | | LR save word | 3468 // | +-----------------------------------+ 3469 // SP--> +--- | Back chain | 3470 // +-----------------------------------+ 3471 // 3472 // Specifications: 3473 // System V Application Binary Interface PowerPC Processor Supplement 3474 // AltiVec Technology Programming Interface Manual 3475 3476 MachineFunction &MF = DAG.getMachineFunction(); 3477 MachineFrameInfo &MFI = MF.getFrameInfo(); 3478 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3479 3480 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3481 // Potential tail calls could cause overwriting of argument stack slots. 3482 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3483 (CallConv == CallingConv::Fast)); 3484 unsigned PtrByteSize = 4; 3485 3486 // Assign locations to all of the incoming arguments. 3487 SmallVector<CCValAssign, 16> ArgLocs; 3488 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3489 *DAG.getContext()); 3490 3491 // Reserve space for the linkage area on the stack. 3492 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3493 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 3494 if (useSoftFloat()) 3495 CCInfo.PreAnalyzeFormalArguments(Ins); 3496 3497 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 3498 CCInfo.clearWasPPCF128(); 3499 3500 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3501 CCValAssign &VA = ArgLocs[i]; 3502 3503 // Arguments stored in registers. 3504 if (VA.isRegLoc()) { 3505 const TargetRegisterClass *RC; 3506 EVT ValVT = VA.getValVT(); 3507 3508 switch (ValVT.getSimpleVT().SimpleTy) { 3509 default: 3510 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 3511 case MVT::i1: 3512 case MVT::i32: 3513 RC = &PPC::GPRCRegClass; 3514 break; 3515 case MVT::f32: 3516 if (Subtarget.hasP8Vector()) 3517 RC = &PPC::VSSRCRegClass; 3518 else if (Subtarget.hasSPE()) 3519 RC = &PPC::GPRCRegClass; 3520 else 3521 RC = &PPC::F4RCRegClass; 3522 break; 3523 case MVT::f64: 3524 if (Subtarget.hasVSX()) 3525 RC = &PPC::VSFRCRegClass; 3526 else if (Subtarget.hasSPE()) 3527 // SPE passes doubles in GPR pairs. 3528 RC = &PPC::GPRCRegClass; 3529 else 3530 RC = &PPC::F8RCRegClass; 3531 break; 3532 case MVT::v16i8: 3533 case MVT::v8i16: 3534 case MVT::v4i32: 3535 RC = &PPC::VRRCRegClass; 3536 break; 3537 case MVT::v4f32: 3538 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; 3539 break; 3540 case MVT::v2f64: 3541 case MVT::v2i64: 3542 RC = &PPC::VRRCRegClass; 3543 break; 3544 case MVT::v4f64: 3545 RC = &PPC::QFRCRegClass; 3546 break; 3547 case MVT::v4i1: 3548 RC = &PPC::QBRCRegClass; 3549 break; 3550 } 3551 3552 SDValue ArgValue; 3553 // Transform the arguments stored in physical registers into 3554 // virtual ones. 3555 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 3556 assert(i + 1 < e && "No second half of double precision argument"); 3557 unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC); 3558 unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 3559 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 3560 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 3561 if (!Subtarget.isLittleEndian()) 3562 std::swap (ArgValueLo, ArgValueHi); 3563 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 3564 ArgValueHi); 3565 } else { 3566 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3567 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 3568 ValVT == MVT::i1 ? MVT::i32 : ValVT); 3569 if (ValVT == MVT::i1) 3570 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 3571 } 3572 3573 InVals.push_back(ArgValue); 3574 } else { 3575 // Argument stored in memory. 3576 assert(VA.isMemLoc()); 3577 3578 // Get the extended size of the argument type in stack 3579 unsigned ArgSize = VA.getLocVT().getStoreSize(); 3580 // Get the actual size of the argument type 3581 unsigned ObjSize = VA.getValVT().getStoreSize(); 3582 unsigned ArgOffset = VA.getLocMemOffset(); 3583 // Stack objects in PPC32 are right justified. 3584 ArgOffset += ArgSize - ObjSize; 3585 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 3586 3587 // Create load nodes to retrieve arguments from the stack. 3588 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3589 InVals.push_back( 3590 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 3591 } 3592 } 3593 3594 // Assign locations to all of the incoming aggregate by value arguments. 3595 // Aggregates passed by value are stored in the local variable space of the 3596 // caller's stack frame, right above the parameter list area. 3597 SmallVector<CCValAssign, 16> ByValArgLocs; 3598 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 3599 ByValArgLocs, *DAG.getContext()); 3600 3601 // Reserve stack space for the allocations in CCInfo. 3602 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 3603 3604 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 3605 3606 // Area that is at least reserved in the caller of this function. 3607 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 3608 MinReservedArea = std::max(MinReservedArea, LinkageSize); 3609 3610 // Set the size that is at least reserved in caller of this function. Tail 3611 // call optimized function's reserved stack space needs to be aligned so that 3612 // taking the difference between two stack areas will result in an aligned 3613 // stack. 3614 MinReservedArea = 3615 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 3616 FuncInfo->setMinReservedArea(MinReservedArea); 3617 3618 SmallVector<SDValue, 8> MemOps; 3619 3620 // If the function takes variable number of arguments, make a frame index for 3621 // the start of the first vararg value... for expansion of llvm.va_start. 3622 if (isVarArg) { 3623 static const MCPhysReg GPArgRegs[] = { 3624 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 3625 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 3626 }; 3627 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); 3628 3629 static const MCPhysReg FPArgRegs[] = { 3630 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 3631 PPC::F8 3632 }; 3633 unsigned NumFPArgRegs = array_lengthof(FPArgRegs); 3634 3635 if (useSoftFloat() || hasSPE()) 3636 NumFPArgRegs = 0; 3637 3638 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 3639 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 3640 3641 // Make room for NumGPArgRegs and NumFPArgRegs. 3642 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 3643 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 3644 3645 FuncInfo->setVarArgsStackOffset( 3646 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 3647 CCInfo.getNextStackOffset(), true)); 3648 3649 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false)); 3650 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3651 3652 // The fixed integer arguments of a variadic function are stored to the 3653 // VarArgsFrameIndex on the stack so that they may be loaded by 3654 // dereferencing the result of va_next. 3655 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 3656 // Get an existing live-in vreg, or add a new one. 3657 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 3658 if (!VReg) 3659 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 3660 3661 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3662 SDValue Store = 3663 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3664 MemOps.push_back(Store); 3665 // Increment the address by four for the next argument to store 3666 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 3667 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3668 } 3669 3670 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 3671 // is set. 3672 // The double arguments are stored to the VarArgsFrameIndex 3673 // on the stack. 3674 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 3675 // Get an existing live-in vreg, or add a new one. 3676 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 3677 if (!VReg) 3678 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 3679 3680 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 3681 SDValue Store = 3682 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 3683 MemOps.push_back(Store); 3684 // Increment the address by eight for the next argument to store 3685 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 3686 PtrVT); 3687 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 3688 } 3689 } 3690 3691 if (!MemOps.empty()) 3692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 3693 3694 return Chain; 3695 } 3696 3697 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3698 // value to MVT::i64 and then truncate to the correct register size. 3699 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 3700 EVT ObjectVT, SelectionDAG &DAG, 3701 SDValue ArgVal, 3702 const SDLoc &dl) const { 3703 if (Flags.isSExt()) 3704 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 3705 DAG.getValueType(ObjectVT)); 3706 else if (Flags.isZExt()) 3707 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 3708 DAG.getValueType(ObjectVT)); 3709 3710 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 3711 } 3712 3713 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 3714 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3715 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 3716 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3717 // TODO: add description of PPC stack frame format, or at least some docs. 3718 // 3719 bool isELFv2ABI = Subtarget.isELFv2ABI(); 3720 bool isLittleEndian = Subtarget.isLittleEndian(); 3721 MachineFunction &MF = DAG.getMachineFunction(); 3722 MachineFrameInfo &MFI = MF.getFrameInfo(); 3723 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3724 3725 assert(!(CallConv == CallingConv::Fast && isVarArg) && 3726 "fastcc not supported on varargs functions"); 3727 3728 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3729 // Potential tail calls could cause overwriting of argument stack slots. 3730 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 3731 (CallConv == CallingConv::Fast)); 3732 unsigned PtrByteSize = 8; 3733 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 3734 3735 static const MCPhysReg GPR[] = { 3736 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 3737 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 3738 }; 3739 static const MCPhysReg VR[] = { 3740 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 3741 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 3742 }; 3743 3744 const unsigned Num_GPR_Regs = array_lengthof(GPR); 3745 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 3746 const unsigned Num_VR_Regs = array_lengthof(VR); 3747 const unsigned Num_QFPR_Regs = Num_FPR_Regs; 3748 3749 // Do a first pass over the arguments to determine whether the ABI 3750 // guarantees that our caller has allocated the parameter save area 3751 // on its stack frame. In the ELFv1 ABI, this is always the case; 3752 // in the ELFv2 ABI, it is true if this is a vararg function or if 3753 // any parameter is located in a stack slot. 3754 3755 bool HasParameterArea = !isELFv2ABI || isVarArg; 3756 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 3757 unsigned NumBytes = LinkageSize; 3758 unsigned AvailableFPRs = Num_FPR_Regs; 3759 unsigned AvailableVRs = Num_VR_Regs; 3760 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 3761 if (Ins[i].Flags.isNest()) 3762 continue; 3763 3764 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 3765 PtrByteSize, LinkageSize, ParamAreaSize, 3766 NumBytes, AvailableFPRs, AvailableVRs, 3767 Subtarget.hasQPX())) 3768 HasParameterArea = true; 3769 } 3770 3771 // Add DAG nodes to load the arguments or copy them out of registers. On 3772 // entry to a function on PPC, the arguments start after the linkage area, 3773 // although the first ones are often in registers. 3774 3775 unsigned ArgOffset = LinkageSize; 3776 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 3777 unsigned &QFPR_idx = FPR_idx; 3778 SmallVector<SDValue, 8> MemOps; 3779 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 3780 unsigned CurArgIdx = 0; 3781 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 3782 SDValue ArgVal; 3783 bool needsLoad = false; 3784 EVT ObjectVT = Ins[ArgNo].VT; 3785 EVT OrigVT = Ins[ArgNo].ArgVT; 3786 unsigned ObjSize = ObjectVT.getStoreSize(); 3787 unsigned ArgSize = ObjSize; 3788 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 3789 if (Ins[ArgNo].isOrigArg()) { 3790 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 3791 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 3792 } 3793 // We re-align the argument offset for each argument, except when using the 3794 // fast calling convention, when we need to make sure we do that only when 3795 // we'll actually use a stack slot. 3796 unsigned CurArgOffset; 3797 Align Alignment; 3798 auto ComputeArgOffset = [&]() { 3799 /* Respect alignment of argument on the stack. */ 3800 Alignment = 3801 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 3802 ArgOffset = alignTo(ArgOffset, Alignment); 3803 CurArgOffset = ArgOffset; 3804 }; 3805 3806 if (CallConv != CallingConv::Fast) { 3807 ComputeArgOffset(); 3808 3809 /* Compute GPR index associated with argument offset. */ 3810 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 3811 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 3812 } 3813 3814 // FIXME the codegen can be much improved in some cases. 3815 // We do not have to keep everything in memory. 3816 if (Flags.isByVal()) { 3817 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 3818 3819 if (CallConv == CallingConv::Fast) 3820 ComputeArgOffset(); 3821 3822 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 3823 ObjSize = Flags.getByValSize(); 3824 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3825 // Empty aggregate parameters do not take up registers. Examples: 3826 // struct { } a; 3827 // union { } b; 3828 // int c[0]; 3829 // etc. However, we have to provide a place-holder in InVals, so 3830 // pretend we have an 8-byte item at the current address for that 3831 // purpose. 3832 if (!ObjSize) { 3833 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 3834 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3835 InVals.push_back(FIN); 3836 continue; 3837 } 3838 3839 // Create a stack object covering all stack doublewords occupied 3840 // by the argument. If the argument is (fully or partially) on 3841 // the stack, or if the argument is fully in registers but the 3842 // caller has allocated the parameter save anyway, we can refer 3843 // directly to the caller's stack frame. Otherwise, create a 3844 // local copy in our own frame. 3845 int FI; 3846 if (HasParameterArea || 3847 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 3848 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 3849 else 3850 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 3851 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 3852 3853 // Handle aggregates smaller than 8 bytes. 3854 if (ObjSize < PtrByteSize) { 3855 // The value of the object is its address, which differs from the 3856 // address of the enclosing doubleword on big-endian systems. 3857 SDValue Arg = FIN; 3858 if (!isLittleEndian) { 3859 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 3860 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 3861 } 3862 InVals.push_back(Arg); 3863 3864 if (GPR_idx != Num_GPR_Regs) { 3865 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3866 FuncInfo->addLiveInAttr(VReg, Flags); 3867 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3868 SDValue Store; 3869 3870 if (ObjSize==1 || ObjSize==2 || ObjSize==4) { 3871 EVT ObjType = (ObjSize == 1 ? MVT::i8 : 3872 (ObjSize == 2 ? MVT::i16 : MVT::i32)); 3873 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 3874 MachinePointerInfo(&*FuncArg), ObjType); 3875 } else { 3876 // For sizes that don't fit a truncating store (3, 5, 6, 7), 3877 // store the whole register as-is to the parameter save area 3878 // slot. 3879 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 3880 MachinePointerInfo(&*FuncArg)); 3881 } 3882 3883 MemOps.push_back(Store); 3884 } 3885 // Whether we copied from a register or not, advance the offset 3886 // into the parameter save area by a full doubleword. 3887 ArgOffset += PtrByteSize; 3888 continue; 3889 } 3890 3891 // The value of the object is its address, which is the address of 3892 // its first stack doubleword. 3893 InVals.push_back(FIN); 3894 3895 // Store whatever pieces of the object are in registers to memory. 3896 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 3897 if (GPR_idx == Num_GPR_Regs) 3898 break; 3899 3900 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 3901 FuncInfo->addLiveInAttr(VReg, Flags); 3902 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 3903 SDValue Addr = FIN; 3904 if (j) { 3905 SDValue Off = DAG.getConstant(j, dl, PtrVT); 3906 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 3907 } 3908 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, 3909 MachinePointerInfo(&*FuncArg, j)); 3910 MemOps.push_back(Store); 3911 ++GPR_idx; 3912 } 3913 ArgOffset += ArgSize; 3914 continue; 3915 } 3916 3917 switch (ObjectVT.getSimpleVT().SimpleTy) { 3918 default: llvm_unreachable("Unhandled argument type!"); 3919 case MVT::i1: 3920 case MVT::i32: 3921 case MVT::i64: 3922 if (Flags.isNest()) { 3923 // The 'nest' parameter, if any, is passed in R11. 3924 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 3925 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3926 3927 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3928 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3929 3930 break; 3931 } 3932 3933 // These can be scalar arguments or elements of an integer array type 3934 // passed directly. Clang may use those instead of "byval" aggregate 3935 // types to avoid forcing arguments to memory unnecessarily. 3936 if (GPR_idx != Num_GPR_Regs) { 3937 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3938 FuncInfo->addLiveInAttr(VReg, Flags); 3939 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3940 3941 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 3942 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 3943 // value to MVT::i64 and then truncate to the correct register size. 3944 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 3945 } else { 3946 if (CallConv == CallingConv::Fast) 3947 ComputeArgOffset(); 3948 3949 needsLoad = true; 3950 ArgSize = PtrByteSize; 3951 } 3952 if (CallConv != CallingConv::Fast || needsLoad) 3953 ArgOffset += 8; 3954 break; 3955 3956 case MVT::f32: 3957 case MVT::f64: 3958 // These can be scalar arguments or elements of a float array type 3959 // passed directly. The latter are used to implement ELFv2 homogenous 3960 // float aggregates. 3961 if (FPR_idx != Num_FPR_Regs) { 3962 unsigned VReg; 3963 3964 if (ObjectVT == MVT::f32) 3965 VReg = MF.addLiveIn(FPR[FPR_idx], 3966 Subtarget.hasP8Vector() 3967 ? &PPC::VSSRCRegClass 3968 : &PPC::F4RCRegClass); 3969 else 3970 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 3971 ? &PPC::VSFRCRegClass 3972 : &PPC::F8RCRegClass); 3973 3974 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 3975 ++FPR_idx; 3976 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 3977 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 3978 // once we support fp <-> gpr moves. 3979 3980 // This can only ever happen in the presence of f32 array types, 3981 // since otherwise we never run out of FPRs before running out 3982 // of GPRs. 3983 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 3984 FuncInfo->addLiveInAttr(VReg, Flags); 3985 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 3986 3987 if (ObjectVT == MVT::f32) { 3988 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 3989 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 3990 DAG.getConstant(32, dl, MVT::i32)); 3991 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 3992 } 3993 3994 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 3995 } else { 3996 if (CallConv == CallingConv::Fast) 3997 ComputeArgOffset(); 3998 3999 needsLoad = true; 4000 } 4001 4002 // When passing an array of floats, the array occupies consecutive 4003 // space in the argument area; only round up to the next doubleword 4004 // at the end of the array. Otherwise, each float takes 8 bytes. 4005 if (CallConv != CallingConv::Fast || needsLoad) { 4006 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4007 ArgOffset += ArgSize; 4008 if (Flags.isInConsecutiveRegsLast()) 4009 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4010 } 4011 break; 4012 case MVT::v4f32: 4013 case MVT::v4i32: 4014 case MVT::v8i16: 4015 case MVT::v16i8: 4016 case MVT::v2f64: 4017 case MVT::v2i64: 4018 case MVT::v1i128: 4019 case MVT::f128: 4020 if (!Subtarget.hasQPX()) { 4021 // These can be scalar arguments or elements of a vector array type 4022 // passed directly. The latter are used to implement ELFv2 homogenous 4023 // vector aggregates. 4024 if (VR_idx != Num_VR_Regs) { 4025 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4026 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4027 ++VR_idx; 4028 } else { 4029 if (CallConv == CallingConv::Fast) 4030 ComputeArgOffset(); 4031 needsLoad = true; 4032 } 4033 if (CallConv != CallingConv::Fast || needsLoad) 4034 ArgOffset += 16; 4035 break; 4036 } // not QPX 4037 4038 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && 4039 "Invalid QPX parameter type"); 4040 LLVM_FALLTHROUGH; 4041 4042 case MVT::v4f64: 4043 case MVT::v4i1: 4044 // QPX vectors are treated like their scalar floating-point subregisters 4045 // (except that they're larger). 4046 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; 4047 if (QFPR_idx != Num_QFPR_Regs) { 4048 const TargetRegisterClass *RC; 4049 switch (ObjectVT.getSimpleVT().SimpleTy) { 4050 case MVT::v4f64: RC = &PPC::QFRCRegClass; break; 4051 case MVT::v4f32: RC = &PPC::QSRCRegClass; break; 4052 default: RC = &PPC::QBRCRegClass; break; 4053 } 4054 4055 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); 4056 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4057 ++QFPR_idx; 4058 } else { 4059 if (CallConv == CallingConv::Fast) 4060 ComputeArgOffset(); 4061 needsLoad = true; 4062 } 4063 if (CallConv != CallingConv::Fast || needsLoad) 4064 ArgOffset += Sz; 4065 break; 4066 } 4067 4068 // We need to load the argument to a virtual register if we determined 4069 // above that we ran out of physical registers of the appropriate type. 4070 if (needsLoad) { 4071 if (ObjSize < ArgSize && !isLittleEndian) 4072 CurArgOffset += ArgSize - ObjSize; 4073 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4074 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4075 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4076 } 4077 4078 InVals.push_back(ArgVal); 4079 } 4080 4081 // Area that is at least reserved in the caller of this function. 4082 unsigned MinReservedArea; 4083 if (HasParameterArea) 4084 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4085 else 4086 MinReservedArea = LinkageSize; 4087 4088 // Set the size that is at least reserved in caller of this function. Tail 4089 // call optimized functions' reserved stack space needs to be aligned so that 4090 // taking the difference between two stack areas will result in an aligned 4091 // stack. 4092 MinReservedArea = 4093 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4094 FuncInfo->setMinReservedArea(MinReservedArea); 4095 4096 // If the function takes variable number of arguments, make a frame index for 4097 // the start of the first vararg value... for expansion of llvm.va_start. 4098 if (isVarArg) { 4099 int Depth = ArgOffset; 4100 4101 FuncInfo->setVarArgsFrameIndex( 4102 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4103 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4104 4105 // If this function is vararg, store any remaining integer argument regs 4106 // to their spots on the stack so that they may be loaded by dereferencing 4107 // the result of va_next. 4108 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4109 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4110 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4111 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4112 SDValue Store = 4113 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4114 MemOps.push_back(Store); 4115 // Increment the address by four for the next argument to store 4116 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4117 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4118 } 4119 } 4120 4121 if (!MemOps.empty()) 4122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4123 4124 return Chain; 4125 } 4126 4127 SDValue PPCTargetLowering::LowerFormalArguments_Darwin( 4128 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4129 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4130 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4131 // TODO: add description of PPC stack frame format, or at least some docs. 4132 // 4133 MachineFunction &MF = DAG.getMachineFunction(); 4134 MachineFrameInfo &MFI = MF.getFrameInfo(); 4135 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4136 4137 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4138 bool isPPC64 = PtrVT == MVT::i64; 4139 // Potential tail calls could cause overwriting of argument stack slots. 4140 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4141 (CallConv == CallingConv::Fast)); 4142 unsigned PtrByteSize = isPPC64 ? 8 : 4; 4143 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4144 unsigned ArgOffset = LinkageSize; 4145 // Area that is at least reserved in caller of this function. 4146 unsigned MinReservedArea = ArgOffset; 4147 4148 static const MCPhysReg GPR_32[] = { // 32-bit registers. 4149 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4150 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4151 }; 4152 static const MCPhysReg GPR_64[] = { // 64-bit registers. 4153 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4154 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4155 }; 4156 static const MCPhysReg VR[] = { 4157 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4158 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4159 }; 4160 4161 const unsigned Num_GPR_Regs = array_lengthof(GPR_32); 4162 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4163 const unsigned Num_VR_Regs = array_lengthof( VR); 4164 4165 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4166 4167 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 4168 4169 // In 32-bit non-varargs functions, the stack space for vectors is after the 4170 // stack space for non-vectors. We do not use this space unless we have 4171 // too many vectors to fit in registers, something that only occurs in 4172 // constructed examples:), but we have to walk the arglist to figure 4173 // that out...for the pathological case, compute VecArgOffset as the 4174 // start of the vector parameter area. Computing VecArgOffset is the 4175 // entire point of the following loop. 4176 unsigned VecArgOffset = ArgOffset; 4177 if (!isVarArg && !isPPC64) { 4178 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; 4179 ++ArgNo) { 4180 EVT ObjectVT = Ins[ArgNo].VT; 4181 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4182 4183 if (Flags.isByVal()) { 4184 // ObjSize is the true size, ArgSize rounded up to multiple of regs. 4185 unsigned ObjSize = Flags.getByValSize(); 4186 unsigned ArgSize = 4187 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4188 VecArgOffset += ArgSize; 4189 continue; 4190 } 4191 4192 switch(ObjectVT.getSimpleVT().SimpleTy) { 4193 default: llvm_unreachable("Unhandled argument type!"); 4194 case MVT::i1: 4195 case MVT::i32: 4196 case MVT::f32: 4197 VecArgOffset += 4; 4198 break; 4199 case MVT::i64: // PPC64 4200 case MVT::f64: 4201 // FIXME: We are guaranteed to be !isPPC64 at this point. 4202 // Does MVT::i64 apply? 4203 VecArgOffset += 8; 4204 break; 4205 case MVT::v4f32: 4206 case MVT::v4i32: 4207 case MVT::v8i16: 4208 case MVT::v16i8: 4209 // Nothing to do, we're only looking at Nonvector args here. 4210 break; 4211 } 4212 } 4213 } 4214 // We've found where the vector parameter area in memory is. Skip the 4215 // first 12 parameters; these don't use that memory. 4216 VecArgOffset = ((VecArgOffset+15)/16)*16; 4217 VecArgOffset += 12*16; 4218 4219 // Add DAG nodes to load the arguments or copy them out of registers. On 4220 // entry to a function on PPC, the arguments start after the linkage area, 4221 // although the first ones are often in registers. 4222 4223 SmallVector<SDValue, 8> MemOps; 4224 unsigned nAltivecParamsAtEnd = 0; 4225 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4226 unsigned CurArgIdx = 0; 4227 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4228 SDValue ArgVal; 4229 bool needsLoad = false; 4230 EVT ObjectVT = Ins[ArgNo].VT; 4231 unsigned ObjSize = ObjectVT.getSizeInBits()/8; 4232 unsigned ArgSize = ObjSize; 4233 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4234 if (Ins[ArgNo].isOrigArg()) { 4235 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4236 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4237 } 4238 unsigned CurArgOffset = ArgOffset; 4239 4240 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. 4241 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || 4242 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { 4243 if (isVarArg || isPPC64) { 4244 MinReservedArea = ((MinReservedArea+15)/16)*16; 4245 MinReservedArea += CalculateStackSlotSize(ObjectVT, 4246 Flags, 4247 PtrByteSize); 4248 } else nAltivecParamsAtEnd++; 4249 } else 4250 // Calculate min reserved area. 4251 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, 4252 Flags, 4253 PtrByteSize); 4254 4255 // FIXME the codegen can be much improved in some cases. 4256 // We do not have to keep everything in memory. 4257 if (Flags.isByVal()) { 4258 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4259 4260 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4261 ObjSize = Flags.getByValSize(); 4262 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4263 // Objects of size 1 and 2 are right justified, everything else is 4264 // left justified. This means the memory address is adjusted forwards. 4265 if (ObjSize==1 || ObjSize==2) { 4266 CurArgOffset = CurArgOffset + (4 - ObjSize); 4267 } 4268 // The value of the object is its address. 4269 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true); 4270 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4271 InVals.push_back(FIN); 4272 if (ObjSize==1 || ObjSize==2) { 4273 if (GPR_idx != Num_GPR_Regs) { 4274 unsigned VReg; 4275 if (isPPC64) 4276 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4277 else 4278 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4279 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4280 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; 4281 SDValue Store = 4282 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, 4283 MachinePointerInfo(&*FuncArg), ObjType); 4284 MemOps.push_back(Store); 4285 ++GPR_idx; 4286 } 4287 4288 ArgOffset += PtrByteSize; 4289 4290 continue; 4291 } 4292 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4293 // Store whatever pieces of the object are in registers 4294 // to memory. ArgOffset will be the address of the beginning 4295 // of the object. 4296 if (GPR_idx != Num_GPR_Regs) { 4297 unsigned VReg; 4298 if (isPPC64) 4299 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4300 else 4301 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4302 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4303 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4304 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4305 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, 4306 MachinePointerInfo(&*FuncArg, j)); 4307 MemOps.push_back(Store); 4308 ++GPR_idx; 4309 ArgOffset += PtrByteSize; 4310 } else { 4311 ArgOffset += ArgSize - (ArgOffset-CurArgOffset); 4312 break; 4313 } 4314 } 4315 continue; 4316 } 4317 4318 switch (ObjectVT.getSimpleVT().SimpleTy) { 4319 default: llvm_unreachable("Unhandled argument type!"); 4320 case MVT::i1: 4321 case MVT::i32: 4322 if (!isPPC64) { 4323 if (GPR_idx != Num_GPR_Regs) { 4324 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4325 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); 4326 4327 if (ObjectVT == MVT::i1) 4328 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); 4329 4330 ++GPR_idx; 4331 } else { 4332 needsLoad = true; 4333 ArgSize = PtrByteSize; 4334 } 4335 // All int arguments reserve stack space in the Darwin ABI. 4336 ArgOffset += PtrByteSize; 4337 break; 4338 } 4339 LLVM_FALLTHROUGH; 4340 case MVT::i64: // PPC64 4341 if (GPR_idx != Num_GPR_Regs) { 4342 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4343 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4344 4345 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4346 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4347 // value to MVT::i64 and then truncate to the correct register size. 4348 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4349 4350 ++GPR_idx; 4351 } else { 4352 needsLoad = true; 4353 ArgSize = PtrByteSize; 4354 } 4355 // All int arguments reserve stack space in the Darwin ABI. 4356 ArgOffset += 8; 4357 break; 4358 4359 case MVT::f32: 4360 case MVT::f64: 4361 // Every 4 bytes of argument space consumes one of the GPRs available for 4362 // argument passing. 4363 if (GPR_idx != Num_GPR_Regs) { 4364 ++GPR_idx; 4365 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) 4366 ++GPR_idx; 4367 } 4368 if (FPR_idx != Num_FPR_Regs) { 4369 unsigned VReg; 4370 4371 if (ObjectVT == MVT::f32) 4372 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); 4373 else 4374 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); 4375 4376 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4377 ++FPR_idx; 4378 } else { 4379 needsLoad = true; 4380 } 4381 4382 // All FP arguments reserve stack space in the Darwin ABI. 4383 ArgOffset += isPPC64 ? 8 : ObjSize; 4384 break; 4385 case MVT::v4f32: 4386 case MVT::v4i32: 4387 case MVT::v8i16: 4388 case MVT::v16i8: 4389 // Note that vector arguments in registers don't reserve stack space, 4390 // except in varargs functions. 4391 if (VR_idx != Num_VR_Regs) { 4392 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4393 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4394 if (isVarArg) { 4395 while ((ArgOffset % 16) != 0) { 4396 ArgOffset += PtrByteSize; 4397 if (GPR_idx != Num_GPR_Regs) 4398 GPR_idx++; 4399 } 4400 ArgOffset += 16; 4401 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? 4402 } 4403 ++VR_idx; 4404 } else { 4405 if (!isVarArg && !isPPC64) { 4406 // Vectors go after all the nonvectors. 4407 CurArgOffset = VecArgOffset; 4408 VecArgOffset += 16; 4409 } else { 4410 // Vectors are aligned. 4411 ArgOffset = ((ArgOffset+15)/16)*16; 4412 CurArgOffset = ArgOffset; 4413 ArgOffset += 16; 4414 } 4415 needsLoad = true; 4416 } 4417 break; 4418 } 4419 4420 // We need to load the argument to a virtual register if we determined above 4421 // that we ran out of physical registers of the appropriate type. 4422 if (needsLoad) { 4423 int FI = MFI.CreateFixedObject(ObjSize, 4424 CurArgOffset + (ArgSize - ObjSize), 4425 isImmutable); 4426 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4427 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4428 } 4429 4430 InVals.push_back(ArgVal); 4431 } 4432 4433 // Allow for Altivec parameters at the end, if needed. 4434 if (nAltivecParamsAtEnd) { 4435 MinReservedArea = ((MinReservedArea+15)/16)*16; 4436 MinReservedArea += 16*nAltivecParamsAtEnd; 4437 } 4438 4439 // Area that is at least reserved in the caller of this function. 4440 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); 4441 4442 // Set the size that is at least reserved in caller of this function. Tail 4443 // call optimized functions' reserved stack space needs to be aligned so that 4444 // taking the difference between two stack areas will result in an aligned 4445 // stack. 4446 MinReservedArea = 4447 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4448 FuncInfo->setMinReservedArea(MinReservedArea); 4449 4450 // If the function takes variable number of arguments, make a frame index for 4451 // the start of the first vararg value... for expansion of llvm.va_start. 4452 if (isVarArg) { 4453 int Depth = ArgOffset; 4454 4455 FuncInfo->setVarArgsFrameIndex( 4456 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4457 Depth, true)); 4458 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4459 4460 // If this function is vararg, store any remaining integer argument regs 4461 // to their spots on the stack so that they may be loaded by dereferencing 4462 // the result of va_next. 4463 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { 4464 unsigned VReg; 4465 4466 if (isPPC64) 4467 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4468 else 4469 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); 4470 4471 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4472 SDValue Store = 4473 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4474 MemOps.push_back(Store); 4475 // Increment the address by four for the next argument to store 4476 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4477 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4478 } 4479 } 4480 4481 if (!MemOps.empty()) 4482 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4483 4484 return Chain; 4485 } 4486 4487 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4488 /// adjusted to accommodate the arguments for the tailcall. 4489 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4490 unsigned ParamSize) { 4491 4492 if (!isTailCall) return 0; 4493 4494 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4495 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4496 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4497 // Remember only if the new adjustment is bigger. 4498 if (SPDiff < FI->getTailCallSPDelta()) 4499 FI->setTailCallSPDelta(SPDiff); 4500 4501 return SPDiff; 4502 } 4503 4504 static bool isFunctionGlobalAddress(SDValue Callee); 4505 4506 static bool 4507 callsShareTOCBase(const Function *Caller, SDValue Callee, 4508 const TargetMachine &TM) { 4509 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4510 // don't have enough information to determine if the caller and calle share 4511 // the same TOC base, so we have to pessimistically assume they don't for 4512 // correctness. 4513 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4514 if (!G) 4515 return false; 4516 4517 const GlobalValue *GV = G->getGlobal(); 4518 // The medium and large code models are expected to provide a sufficiently 4519 // large TOC to provide all data addressing needs of a module with a 4520 // single TOC. Since each module will be addressed with a single TOC then we 4521 // only need to check that caller and callee don't cross dso boundaries. 4522 if (CodeModel::Medium == TM.getCodeModel() || 4523 CodeModel::Large == TM.getCodeModel()) 4524 return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV); 4525 4526 // Otherwise we need to ensure callee and caller are in the same section, 4527 // since the linker may allocate multiple TOCs, and we don't know which 4528 // sections will belong to the same TOC base. 4529 4530 if (!GV->isStrongDefinitionForLinker()) 4531 return false; 4532 4533 // Any explicitly-specified sections and section prefixes must also match. 4534 // Also, if we're using -ffunction-sections, then each function is always in 4535 // a different section (the same is true for COMDAT functions). 4536 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4537 GV->getSection() != Caller->getSection()) 4538 return false; 4539 if (const auto *F = dyn_cast<Function>(GV)) { 4540 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4541 return false; 4542 } 4543 4544 // If the callee might be interposed, then we can't assume the ultimate call 4545 // target will be in the same section. Even in cases where we can assume that 4546 // interposition won't happen, in any case where the linker might insert a 4547 // stub to allow for interposition, we must generate code as though 4548 // interposition might occur. To understand why this matters, consider a 4549 // situation where: a -> b -> c where the arrows indicate calls. b and c are 4550 // in the same section, but a is in a different module (i.e. has a different 4551 // TOC base pointer). If the linker allows for interposition between b and c, 4552 // then it will generate a stub for the call edge between b and c which will 4553 // save the TOC pointer into the designated stack slot allocated by b. If we 4554 // return true here, and therefore allow a tail call between b and c, that 4555 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base 4556 // pointer into the stack slot allocated by a (where the a -> b stub saved 4557 // a's TOC base pointer). If we're not considering a tail call, but rather, 4558 // whether a nop is needed after the call instruction in b, because the linker 4559 // will insert a stub, it might complain about a missing nop if we omit it 4560 // (although many don't complain in this case). 4561 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4562 return false; 4563 4564 return true; 4565 } 4566 4567 static bool 4568 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4569 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4570 assert(Subtarget.is64BitELFABI()); 4571 4572 const unsigned PtrByteSize = 8; 4573 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4574 4575 static const MCPhysReg GPR[] = { 4576 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4577 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4578 }; 4579 static const MCPhysReg VR[] = { 4580 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4581 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4582 }; 4583 4584 const unsigned NumGPRs = array_lengthof(GPR); 4585 const unsigned NumFPRs = 13; 4586 const unsigned NumVRs = array_lengthof(VR); 4587 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4588 4589 unsigned NumBytes = LinkageSize; 4590 unsigned AvailableFPRs = NumFPRs; 4591 unsigned AvailableVRs = NumVRs; 4592 4593 for (const ISD::OutputArg& Param : Outs) { 4594 if (Param.Flags.isNest()) continue; 4595 4596 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, 4597 PtrByteSize, LinkageSize, ParamAreaSize, 4598 NumBytes, AvailableFPRs, AvailableVRs, 4599 Subtarget.hasQPX())) 4600 return true; 4601 } 4602 return false; 4603 } 4604 4605 static bool 4606 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) { 4607 if (CS.arg_size() != CallerFn->arg_size()) 4608 return false; 4609 4610 ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin(); 4611 ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end(); 4612 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4613 4614 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4615 const Value* CalleeArg = *CalleeArgIter; 4616 const Value* CallerArg = &(*CallerArgIter); 4617 if (CalleeArg == CallerArg) 4618 continue; 4619 4620 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4621 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4622 // } 4623 // 1st argument of callee is undef and has the same type as caller. 4624 if (CalleeArg->getType() == CallerArg->getType() && 4625 isa<UndefValue>(CalleeArg)) 4626 continue; 4627 4628 return false; 4629 } 4630 4631 return true; 4632 } 4633 4634 // Returns true if TCO is possible between the callers and callees 4635 // calling conventions. 4636 static bool 4637 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4638 CallingConv::ID CalleeCC) { 4639 // Tail calls are possible with fastcc and ccc. 4640 auto isTailCallableCC = [] (CallingConv::ID CC){ 4641 return CC == CallingConv::C || CC == CallingConv::Fast; 4642 }; 4643 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4644 return false; 4645 4646 // We can safely tail call both fastcc and ccc callees from a c calling 4647 // convention caller. If the caller is fastcc, we may have less stack space 4648 // than a non-fastcc caller with the same signature so disable tail-calls in 4649 // that case. 4650 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4651 } 4652 4653 bool 4654 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4655 SDValue Callee, 4656 CallingConv::ID CalleeCC, 4657 ImmutableCallSite CS, 4658 bool isVarArg, 4659 const SmallVectorImpl<ISD::OutputArg> &Outs, 4660 const SmallVectorImpl<ISD::InputArg> &Ins, 4661 SelectionDAG& DAG) const { 4662 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4663 4664 if (DisableSCO && !TailCallOpt) return false; 4665 4666 // Variadic argument functions are not supported. 4667 if (isVarArg) return false; 4668 4669 auto &Caller = DAG.getMachineFunction().getFunction(); 4670 // Check that the calling conventions are compatible for tco. 4671 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4672 return false; 4673 4674 // Caller contains any byval parameter is not supported. 4675 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4676 return false; 4677 4678 // Callee contains any byval parameter is not supported, too. 4679 // Note: This is a quick work around, because in some cases, e.g. 4680 // caller's stack size > callee's stack size, we are still able to apply 4681 // sibling call optimization. For example, gcc is able to do SCO for caller1 4682 // in the following example, but not for caller2. 4683 // struct test { 4684 // long int a; 4685 // char ary[56]; 4686 // } gTest; 4687 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4688 // b->a = v.a; 4689 // return 0; 4690 // } 4691 // void caller1(struct test a, struct test c, struct test *b) { 4692 // callee(gTest, b); } 4693 // void caller2(struct test *b) { callee(gTest, b); } 4694 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4695 return false; 4696 4697 // If callee and caller use different calling conventions, we cannot pass 4698 // parameters on stack since offsets for the parameter area may be different. 4699 if (Caller.getCallingConv() != CalleeCC && 4700 needStackSlotPassParameters(Subtarget, Outs)) 4701 return false; 4702 4703 // No TCO/SCO on indirect call because Caller have to restore its TOC 4704 if (!isFunctionGlobalAddress(Callee) && 4705 !isa<ExternalSymbolSDNode>(Callee)) 4706 return false; 4707 4708 // If the caller and callee potentially have different TOC bases then we 4709 // cannot tail call since we need to restore the TOC pointer after the call. 4710 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4711 if (!callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4712 return false; 4713 4714 // TCO allows altering callee ABI, so we don't have to check further. 4715 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4716 return true; 4717 4718 if (DisableSCO) return false; 4719 4720 // If callee use the same argument list that caller is using, then we can 4721 // apply SCO on this case. If it is not, then we need to check if callee needs 4722 // stack for passing arguments. 4723 if (!hasSameArgumentList(&Caller, CS) && 4724 needStackSlotPassParameters(Subtarget, Outs)) { 4725 return false; 4726 } 4727 4728 return true; 4729 } 4730 4731 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4732 /// for tail call optimization. Targets which want to do tail call 4733 /// optimization should implement this function. 4734 bool 4735 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4736 CallingConv::ID CalleeCC, 4737 bool isVarArg, 4738 const SmallVectorImpl<ISD::InputArg> &Ins, 4739 SelectionDAG& DAG) const { 4740 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4741 return false; 4742 4743 // Variable argument functions are not supported. 4744 if (isVarArg) 4745 return false; 4746 4747 MachineFunction &MF = DAG.getMachineFunction(); 4748 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4749 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4750 // Functions containing by val parameters are not supported. 4751 for (unsigned i = 0; i != Ins.size(); i++) { 4752 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4753 if (Flags.isByVal()) return false; 4754 } 4755 4756 // Non-PIC/GOT tail calls are supported. 4757 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4758 return true; 4759 4760 // At the moment we can only do local tail calls (in same module, hidden 4761 // or protected) if we are generating PIC. 4762 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4763 return G->getGlobal()->hasHiddenVisibility() 4764 || G->getGlobal()->hasProtectedVisibility(); 4765 } 4766 4767 return false; 4768 } 4769 4770 /// isCallCompatibleAddress - Return the immediate to use if the specified 4771 /// 32-bit value is representable in the immediate field of a BxA instruction. 4772 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4774 if (!C) return nullptr; 4775 4776 int Addr = C->getZExtValue(); 4777 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4778 SignExtend32<26>(Addr) != Addr) 4779 return nullptr; // Top 6 bits have to be sext of immediate. 4780 4781 return DAG 4782 .getConstant( 4783 (int)C->getZExtValue() >> 2, SDLoc(Op), 4784 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4785 .getNode(); 4786 } 4787 4788 namespace { 4789 4790 struct TailCallArgumentInfo { 4791 SDValue Arg; 4792 SDValue FrameIdxOp; 4793 int FrameIdx = 0; 4794 4795 TailCallArgumentInfo() = default; 4796 }; 4797 4798 } // end anonymous namespace 4799 4800 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 4801 static void StoreTailCallArgumentsToStackSlot( 4802 SelectionDAG &DAG, SDValue Chain, 4803 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 4804 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 4805 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 4806 SDValue Arg = TailCallArgs[i].Arg; 4807 SDValue FIN = TailCallArgs[i].FrameIdxOp; 4808 int FI = TailCallArgs[i].FrameIdx; 4809 // Store relative to framepointer. 4810 MemOpChains.push_back(DAG.getStore( 4811 Chain, dl, Arg, FIN, 4812 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 4813 } 4814 } 4815 4816 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 4817 /// the appropriate stack slot for the tail call optimized function call. 4818 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 4819 SDValue OldRetAddr, SDValue OldFP, 4820 int SPDiff, const SDLoc &dl) { 4821 if (SPDiff) { 4822 // Calculate the new stack slot for the return address. 4823 MachineFunction &MF = DAG.getMachineFunction(); 4824 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 4825 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 4826 bool isPPC64 = Subtarget.isPPC64(); 4827 int SlotSize = isPPC64 ? 8 : 4; 4828 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 4829 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 4830 NewRetAddrLoc, true); 4831 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4832 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 4833 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 4834 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 4835 } 4836 return Chain; 4837 } 4838 4839 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 4840 /// the position of the argument. 4841 static void 4842 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 4843 SDValue Arg, int SPDiff, unsigned ArgOffset, 4844 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 4845 int Offset = ArgOffset + SPDiff; 4846 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 4847 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4848 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 4849 SDValue FIN = DAG.getFrameIndex(FI, VT); 4850 TailCallArgumentInfo Info; 4851 Info.Arg = Arg; 4852 Info.FrameIdxOp = FIN; 4853 Info.FrameIdx = FI; 4854 TailCallArguments.push_back(Info); 4855 } 4856 4857 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 4858 /// stack slot. Returns the chain as result and the loaded frame pointers in 4859 /// LROpOut/FPOpout. Used when tail calling. 4860 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 4861 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 4862 SDValue &FPOpOut, const SDLoc &dl) const { 4863 if (SPDiff) { 4864 // Load the LR and FP stack slot for later adjusting. 4865 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 4866 LROpOut = getReturnAddrFrameIndex(DAG); 4867 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 4868 Chain = SDValue(LROpOut.getNode(), 1); 4869 } 4870 return Chain; 4871 } 4872 4873 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 4874 /// by "Src" to address "Dst" of size "Size". Alignment information is 4875 /// specified by the specific parameter attribute. The copy will be passed as 4876 /// a byval function parameter. 4877 /// Sometimes what we are copying is the end of a larger object, the part that 4878 /// does not fit in registers. 4879 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 4880 SDValue Chain, ISD::ArgFlagsTy Flags, 4881 SelectionDAG &DAG, const SDLoc &dl) { 4882 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 4883 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 4884 Flags.getNonZeroByValAlign(), false, false, false, 4885 MachinePointerInfo(), MachinePointerInfo()); 4886 } 4887 4888 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 4889 /// tail calls. 4890 static void LowerMemOpCallTo( 4891 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 4892 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 4893 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 4894 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 4895 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 4896 if (!isTailCall) { 4897 if (isVector) { 4898 SDValue StackPtr; 4899 if (isPPC64) 4900 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 4901 else 4902 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 4903 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 4904 DAG.getConstant(ArgOffset, dl, PtrVT)); 4905 } 4906 MemOpChains.push_back( 4907 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 4908 // Calculate and remember argument location. 4909 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 4910 TailCallArguments); 4911 } 4912 4913 static void 4914 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 4915 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 4916 SDValue FPOp, 4917 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 4918 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 4919 // might overwrite each other in case of tail call optimization. 4920 SmallVector<SDValue, 8> MemOpChains2; 4921 // Do not flag preceding copytoreg stuff together with the following stuff. 4922 InFlag = SDValue(); 4923 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 4924 MemOpChains2, dl); 4925 if (!MemOpChains2.empty()) 4926 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 4927 4928 // Store the return address to the appropriate stack slot. 4929 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 4930 4931 // Emit callseq_end just before tailcall node. 4932 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 4933 DAG.getIntPtrConstant(0, dl, true), InFlag, dl); 4934 InFlag = Chain.getValue(1); 4935 } 4936 4937 // Is this global address that of a function that can be called by name? (as 4938 // opposed to something that must hold a descriptor for an indirect call). 4939 static bool isFunctionGlobalAddress(SDValue Callee) { 4940 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4941 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 4942 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 4943 return false; 4944 4945 return G->getGlobal()->getValueType()->isFunctionTy(); 4946 } 4947 4948 return false; 4949 } 4950 4951 SDValue PPCTargetLowering::LowerCallResult( 4952 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 4953 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4954 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4955 SmallVector<CCValAssign, 16> RVLocs; 4956 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4957 *DAG.getContext()); 4958 4959 CCRetInfo.AnalyzeCallResult( 4960 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 4961 ? RetCC_PPC_Cold 4962 : RetCC_PPC); 4963 4964 // Copy all of the result registers out of their specified physreg. 4965 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 4966 CCValAssign &VA = RVLocs[i]; 4967 assert(VA.isRegLoc() && "Can only return in registers!"); 4968 4969 SDValue Val; 4970 4971 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 4972 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4973 InFlag); 4974 Chain = Lo.getValue(1); 4975 InFlag = Lo.getValue(2); 4976 VA = RVLocs[++i]; // skip ahead to next loc 4977 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 4978 InFlag); 4979 Chain = Hi.getValue(1); 4980 InFlag = Hi.getValue(2); 4981 if (!Subtarget.isLittleEndian()) 4982 std::swap (Lo, Hi); 4983 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 4984 } else { 4985 Val = DAG.getCopyFromReg(Chain, dl, 4986 VA.getLocReg(), VA.getLocVT(), InFlag); 4987 Chain = Val.getValue(1); 4988 InFlag = Val.getValue(2); 4989 } 4990 4991 switch (VA.getLocInfo()) { 4992 default: llvm_unreachable("Unknown loc info!"); 4993 case CCValAssign::Full: break; 4994 case CCValAssign::AExt: 4995 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 4996 break; 4997 case CCValAssign::ZExt: 4998 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 4999 DAG.getValueType(VA.getValVT())); 5000 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5001 break; 5002 case CCValAssign::SExt: 5003 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5004 DAG.getValueType(VA.getValVT())); 5005 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5006 break; 5007 } 5008 5009 InVals.push_back(Val); 5010 } 5011 5012 return Chain; 5013 } 5014 5015 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5016 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5017 // PatchPoint calls are not indirect. 5018 if (isPatchPoint) 5019 return false; 5020 5021 if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee)) 5022 return false; 5023 5024 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5025 // becuase the immediate function pointer points to a descriptor instead of 5026 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5027 // pointer immediate points to the global entry point, while the BLA would 5028 // need to jump to the local entry point (see rL211174). 5029 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5030 isBLACompatibleAddress(Callee, DAG)) 5031 return false; 5032 5033 return true; 5034 } 5035 5036 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5037 const Function &Caller, 5038 const SDValue &Callee, 5039 const PPCSubtarget &Subtarget, 5040 const TargetMachine &TM) { 5041 if (CFlags.IsTailCall) 5042 return PPCISD::TC_RETURN; 5043 5044 // This is a call through a function pointer. 5045 if (CFlags.IsIndirect) { 5046 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5047 // indirect calls. The save of the caller's TOC pointer to the stack will be 5048 // inserted into the DAG as part of call lowering. The restore of the TOC 5049 // pointer is modeled by using a pseudo instruction for the call opcode that 5050 // represents the 2 instruction sequence of an indirect branch and link, 5051 // immediately followed by a load of the TOC pointer from the the stack save 5052 // slot into gpr2. 5053 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5054 return PPCISD::BCTRL_LOAD_TOC; 5055 5056 // An indirect call that does not need a TOC restore. 5057 return PPCISD::BCTRL; 5058 } 5059 5060 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5061 // immediately following the call instruction if the caller and callee may 5062 // have different TOC bases. At link time if the linker determines the calls 5063 // may not share a TOC base, the call is redirected to a trampoline inserted 5064 // by the linker. The trampoline will (among other things) save the callers 5065 // TOC pointer at an ABI designated offset in the linkage area and the linker 5066 // will rewrite the nop to be a load of the TOC pointer from the linkage area 5067 // into gpr2. 5068 if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5069 return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5070 : PPCISD::CALL_NOP; 5071 5072 return PPCISD::CALL; 5073 } 5074 5075 static bool isValidAIXExternalSymSDNode(StringRef SymName) { 5076 return StringSwitch<bool>(SymName) 5077 .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf", 5078 "__moddi3", "__udivdi3", "__umoddi3", true) 5079 .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true) 5080 .Default(false); 5081 } 5082 5083 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5084 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5085 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5086 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5087 return SDValue(Dest, 0); 5088 5089 // Returns true if the callee is local, and false otherwise. 5090 auto isLocalCallee = [&]() { 5091 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5092 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5093 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5094 5095 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5096 !dyn_cast_or_null<GlobalIFunc>(GV); 5097 }; 5098 5099 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5100 // a static relocation model causes some versions of GNU LD (2.17.50, at 5101 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5102 // built with secure-PLT. 5103 bool UsePlt = 5104 Subtarget.is32BitELFABI() && !isLocalCallee() && 5105 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5106 5107 // On AIX, direct function calls reference the symbol for the function's 5108 // entry point, which is named by prepending a "." before the function's 5109 // C-linkage name. 5110 const auto getAIXFuncEntryPointSymbolSDNode = 5111 [&](StringRef FuncName, bool IsDeclaration, 5112 const XCOFF::StorageClass &SC) { 5113 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5114 5115 MCSymbolXCOFF *S = cast<MCSymbolXCOFF>( 5116 Context.getOrCreateSymbol(Twine(".") + Twine(FuncName))); 5117 5118 if (IsDeclaration && !S->hasContainingCsect()) { 5119 // On AIX, an undefined symbol needs to be associated with a 5120 // MCSectionXCOFF to get the correct storage mapping class. 5121 // In this case, XCOFF::XMC_PR. 5122 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5123 S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC, 5124 SectionKind::getMetadata()); 5125 S->setContainingCsect(Sec); 5126 } 5127 5128 MVT PtrVT = 5129 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5130 return DAG.getMCSymbol(S, PtrVT); 5131 }; 5132 5133 if (isFunctionGlobalAddress(Callee)) { 5134 const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); 5135 const GlobalValue *GV = G->getGlobal(); 5136 5137 if (!Subtarget.isAIXABI()) 5138 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5139 UsePlt ? PPCII::MO_PLT : 0); 5140 5141 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5142 const GlobalObject *GO = cast<GlobalObject>(GV); 5143 const XCOFF::StorageClass SC = 5144 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 5145 return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(), 5146 SC); 5147 } 5148 5149 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5150 const char *SymName = S->getSymbol(); 5151 if (!Subtarget.isAIXABI()) 5152 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5153 UsePlt ? PPCII::MO_PLT : 0); 5154 5155 // If there exists a user-declared function whose name is the same as the 5156 // ExternalSymbol's, then we pick up the user-declared version. 5157 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5158 if (const Function *F = 5159 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) { 5160 const XCOFF::StorageClass SC = 5161 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F); 5162 return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(), 5163 SC); 5164 } 5165 5166 // TODO: Remove this when the support for ExternalSymbolSDNode is complete. 5167 if (isValidAIXExternalSymSDNode(SymName)) { 5168 return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT); 5169 } 5170 5171 report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName)); 5172 } 5173 5174 // No transformation needed. 5175 assert(Callee.getNode() && "What no callee?"); 5176 return Callee; 5177 } 5178 5179 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5180 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5181 "Expected a CALLSEQ_STARTSDNode."); 5182 5183 // The last operand is the chain, except when the node has glue. If the node 5184 // has glue, then the last operand is the glue, and the chain is the second 5185 // last operand. 5186 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5187 if (LastValue.getValueType() != MVT::Glue) 5188 return LastValue; 5189 5190 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5191 } 5192 5193 // Creates the node that moves a functions address into the count register 5194 // to prepare for an indirect call instruction. 5195 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5196 SDValue &Glue, SDValue &Chain, 5197 const SDLoc &dl) { 5198 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5199 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5200 Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2), 5201 makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5202 // The glue is the second value produced. 5203 Glue = Chain.getValue(1); 5204 } 5205 5206 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5207 SDValue &Glue, SDValue &Chain, 5208 SDValue CallSeqStart, 5209 ImmutableCallSite CS, const SDLoc &dl, 5210 bool hasNest, 5211 const PPCSubtarget &Subtarget) { 5212 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5213 // entry point, but to the function descriptor (the function entry point 5214 // address is part of the function descriptor though). 5215 // The function descriptor is a three doubleword structure with the 5216 // following fields: function entry point, TOC base address and 5217 // environment pointer. 5218 // Thus for a call through a function pointer, the following actions need 5219 // to be performed: 5220 // 1. Save the TOC of the caller in the TOC save area of its stack 5221 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5222 // 2. Load the address of the function entry point from the function 5223 // descriptor. 5224 // 3. Load the TOC of the callee from the function descriptor into r2. 5225 // 4. Load the environment pointer from the function descriptor into 5226 // r11. 5227 // 5. Branch to the function entry point address. 5228 // 6. On return of the callee, the TOC of the caller needs to be 5229 // restored (this is done in FinishCall()). 5230 // 5231 // The loads are scheduled at the beginning of the call sequence, and the 5232 // register copies are flagged together to ensure that no other 5233 // operations can be scheduled in between. E.g. without flagging the 5234 // copies together, a TOC access in the caller could be scheduled between 5235 // the assignment of the callee TOC and the branch to the callee, which leads 5236 // to incorrect code. 5237 5238 // Start by loading the function address from the descriptor. 5239 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5240 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5241 ? (MachineMemOperand::MODereferenceable | 5242 MachineMemOperand::MOInvariant) 5243 : MachineMemOperand::MONone; 5244 5245 MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr); 5246 5247 // Registers used in building the DAG. 5248 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5249 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5250 5251 // Offsets of descriptor members. 5252 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5253 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5254 5255 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5256 const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4; 5257 5258 // One load for the functions entry point address. 5259 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5260 Alignment, MMOFlags); 5261 5262 // One for loading the TOC anchor for the module that contains the called 5263 // function. 5264 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5265 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5266 SDValue TOCPtr = 5267 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5268 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5269 5270 // One for loading the environment pointer. 5271 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5272 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5273 SDValue LoadEnvPtr = 5274 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5275 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5276 5277 5278 // Then copy the newly loaded TOC anchor to the TOC pointer. 5279 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5280 Chain = TOCVal.getValue(0); 5281 Glue = TOCVal.getValue(1); 5282 5283 // If the function call has an explicit 'nest' parameter, it takes the 5284 // place of the environment pointer. 5285 assert((!hasNest || !Subtarget.isAIXABI()) && 5286 "Nest parameter is not supported on AIX."); 5287 if (!hasNest) { 5288 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5289 Chain = EnvVal.getValue(0); 5290 Glue = EnvVal.getValue(1); 5291 } 5292 5293 // The rest of the indirect call sequence is the same as the non-descriptor 5294 // DAG. 5295 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5296 } 5297 5298 static void 5299 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5300 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5301 SelectionDAG &DAG, 5302 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5303 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5304 const PPCSubtarget &Subtarget) { 5305 const bool IsPPC64 = Subtarget.isPPC64(); 5306 // MVT for a general purpose register. 5307 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5308 5309 // First operand is always the chain. 5310 Ops.push_back(Chain); 5311 5312 // If it's a direct call pass the callee as the second operand. 5313 if (!CFlags.IsIndirect) 5314 Ops.push_back(Callee); 5315 else { 5316 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5317 5318 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5319 // on the stack (this would have been done in `LowerCall_64SVR4` or 5320 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5321 // represents both the indirect branch and a load that restores the TOC 5322 // pointer from the linkage area. The operand for the TOC restore is an add 5323 // of the TOC save offset to the stack pointer. This must be the second 5324 // operand: after the chain input but before any other variadic arguments. 5325 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 5326 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5327 5328 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5329 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5330 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5331 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5332 Ops.push_back(AddTOC); 5333 } 5334 5335 // Add the register used for the environment pointer. 5336 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5337 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5338 RegVT)); 5339 5340 5341 // Add CTR register as callee so a bctr can be emitted later. 5342 if (CFlags.IsTailCall) 5343 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5344 } 5345 5346 // If this is a tail call add stack pointer delta. 5347 if (CFlags.IsTailCall) 5348 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5349 5350 // Add argument registers to the end of the list so that they are known live 5351 // into the call. 5352 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5353 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5354 RegsToPass[i].second.getValueType())); 5355 5356 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5357 // no way to mark dependencies as implicit here. 5358 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5359 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5360 !CFlags.IsPatchPoint) 5361 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5362 5363 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5364 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5365 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5366 5367 // Add a register mask operand representing the call-preserved registers. 5368 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5369 const uint32_t *Mask = 5370 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5371 assert(Mask && "Missing call preserved mask for calling convention"); 5372 Ops.push_back(DAG.getRegisterMask(Mask)); 5373 5374 // If the glue is valid, it is the last operand. 5375 if (Glue.getNode()) 5376 Ops.push_back(Glue); 5377 } 5378 5379 SDValue PPCTargetLowering::FinishCall( 5380 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5381 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5382 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5383 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5384 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const { 5385 5386 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) 5387 setUsesTOCBasePtr(DAG); 5388 5389 unsigned CallOpc = 5390 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5391 Subtarget, DAG.getTarget()); 5392 5393 if (!CFlags.IsIndirect) 5394 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5395 else if (Subtarget.usesFunctionDescriptors()) 5396 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS, 5397 dl, CFlags.HasNest, Subtarget); 5398 else 5399 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5400 5401 // Build the operand list for the call instruction. 5402 SmallVector<SDValue, 8> Ops; 5403 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5404 SPDiff, Subtarget); 5405 5406 // Emit tail call. 5407 if (CFlags.IsTailCall) { 5408 assert(((Callee.getOpcode() == ISD::Register && 5409 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5410 Callee.getOpcode() == ISD::TargetExternalSymbol || 5411 Callee.getOpcode() == ISD::TargetGlobalAddress || 5412 isa<ConstantSDNode>(Callee)) && 5413 "Expecting a global address, external symbol, absolute value or " 5414 "register"); 5415 assert(CallOpc == PPCISD::TC_RETURN && 5416 "Unexpected call opcode for a tail call."); 5417 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5418 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5419 } 5420 5421 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5422 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5423 Glue = Chain.getValue(1); 5424 5425 // When performing tail call optimization the callee pops its arguments off 5426 // the stack. Account for this here so these bytes can be pushed back on in 5427 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5428 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5429 getTargetMachine().Options.GuaranteedTailCallOpt) 5430 ? NumBytes 5431 : 0; 5432 5433 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), 5434 DAG.getIntPtrConstant(BytesCalleePops, dl, true), 5435 Glue, dl); 5436 Glue = Chain.getValue(1); 5437 5438 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5439 DAG, InVals); 5440 } 5441 5442 SDValue 5443 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5444 SmallVectorImpl<SDValue> &InVals) const { 5445 SelectionDAG &DAG = CLI.DAG; 5446 SDLoc &dl = CLI.DL; 5447 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5448 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5449 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5450 SDValue Chain = CLI.Chain; 5451 SDValue Callee = CLI.Callee; 5452 bool &isTailCall = CLI.IsTailCall; 5453 CallingConv::ID CallConv = CLI.CallConv; 5454 bool isVarArg = CLI.IsVarArg; 5455 bool isPatchPoint = CLI.IsPatchPoint; 5456 ImmutableCallSite CS = CLI.CS; 5457 5458 if (isTailCall) { 5459 if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall())) 5460 isTailCall = false; 5461 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5462 isTailCall = 5463 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS, 5464 isVarArg, Outs, Ins, DAG); 5465 else 5466 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5467 Ins, DAG); 5468 if (isTailCall) { 5469 ++NumTailCalls; 5470 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5471 ++NumSiblingCalls; 5472 5473 assert(isa<GlobalAddressSDNode>(Callee) && 5474 "Callee should be an llvm::Function object."); 5475 LLVM_DEBUG( 5476 const GlobalValue *GV = 5477 cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5478 const unsigned Width = 5479 80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0"); 5480 dbgs() << "TCO caller: " 5481 << left_justify(DAG.getMachineFunction().getName(), Width) 5482 << ", callee linkage: " << GV->getVisibility() << ", " 5483 << GV->getLinkage() << "\n"); 5484 } 5485 } 5486 5487 if (!isTailCall && CS && CS.isMustTailCall()) 5488 report_fatal_error("failed to perform tail call elimination on a call " 5489 "site marked musttail"); 5490 5491 // When long calls (i.e. indirect calls) are always used, calls are always 5492 // made via function pointer. If we have a function name, first translate it 5493 // into a pointer. 5494 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5495 !isTailCall) 5496 Callee = LowerGlobalAddress(Callee, DAG); 5497 5498 CallFlags CFlags( 5499 CallConv, isTailCall, isVarArg, isPatchPoint, 5500 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5501 // hasNest 5502 Subtarget.is64BitELFABI() && 5503 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); })); 5504 5505 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5506 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5507 InVals, CS); 5508 5509 if (Subtarget.isSVR4ABI()) 5510 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5511 InVals, CS); 5512 5513 if (Subtarget.isAIXABI()) 5514 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5515 InVals, CS); 5516 5517 return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5518 InVals, CS); 5519 } 5520 5521 SDValue PPCTargetLowering::LowerCall_32SVR4( 5522 SDValue Chain, SDValue Callee, CallFlags CFlags, 5523 const SmallVectorImpl<ISD::OutputArg> &Outs, 5524 const SmallVectorImpl<SDValue> &OutVals, 5525 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5526 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5527 ImmutableCallSite CS) const { 5528 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5529 // of the 32-bit SVR4 ABI stack frame layout. 5530 5531 const CallingConv::ID CallConv = CFlags.CallConv; 5532 const bool IsVarArg = CFlags.IsVarArg; 5533 const bool IsTailCall = CFlags.IsTailCall; 5534 5535 assert((CallConv == CallingConv::C || 5536 CallConv == CallingConv::Cold || 5537 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5538 5539 unsigned PtrByteSize = 4; 5540 5541 MachineFunction &MF = DAG.getMachineFunction(); 5542 5543 // Mark this function as potentially containing a function that contains a 5544 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5545 // and restoring the callers stack pointer in this functions epilog. This is 5546 // done because by tail calling the called function might overwrite the value 5547 // in this function's (MF) stack pointer stack slot 0(SP). 5548 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5549 CallConv == CallingConv::Fast) 5550 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5551 5552 // Count how many bytes are to be pushed on the stack, including the linkage 5553 // area, parameter list area and the part of the local variable space which 5554 // contains copies of aggregates which are passed by value. 5555 5556 // Assign locations to all of the outgoing arguments. 5557 SmallVector<CCValAssign, 16> ArgLocs; 5558 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5559 5560 // Reserve space for the linkage area on the stack. 5561 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5562 PtrByteSize); 5563 if (useSoftFloat()) 5564 CCInfo.PreAnalyzeCallOperands(Outs); 5565 5566 if (IsVarArg) { 5567 // Handle fixed and variable vector arguments differently. 5568 // Fixed vector arguments go into registers as long as registers are 5569 // available. Variable vector arguments always go into memory. 5570 unsigned NumArgs = Outs.size(); 5571 5572 for (unsigned i = 0; i != NumArgs; ++i) { 5573 MVT ArgVT = Outs[i].VT; 5574 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5575 bool Result; 5576 5577 if (Outs[i].IsFixed) { 5578 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5579 CCInfo); 5580 } else { 5581 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5582 ArgFlags, CCInfo); 5583 } 5584 5585 if (Result) { 5586 #ifndef NDEBUG 5587 errs() << "Call operand #" << i << " has unhandled type " 5588 << EVT(ArgVT).getEVTString() << "\n"; 5589 #endif 5590 llvm_unreachable(nullptr); 5591 } 5592 } 5593 } else { 5594 // All arguments are treated the same. 5595 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5596 } 5597 CCInfo.clearWasPPCF128(); 5598 5599 // Assign locations to all of the outgoing aggregate by value arguments. 5600 SmallVector<CCValAssign, 16> ByValArgLocs; 5601 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5602 5603 // Reserve stack space for the allocations in CCInfo. 5604 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); 5605 5606 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5607 5608 // Size of the linkage area, parameter list area and the part of the local 5609 // space variable where copies of aggregates which are passed by value are 5610 // stored. 5611 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5612 5613 // Calculate by how many bytes the stack has to be adjusted in case of tail 5614 // call optimization. 5615 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5616 5617 // Adjust the stack pointer for the new arguments... 5618 // These operations are automatically eliminated by the prolog/epilog pass 5619 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5620 SDValue CallSeqStart = Chain; 5621 5622 // Load the return address and frame pointer so it can be moved somewhere else 5623 // later. 5624 SDValue LROp, FPOp; 5625 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5626 5627 // Set up a copy of the stack pointer for use loading and storing any 5628 // arguments that may not fit in the registers available for argument 5629 // passing. 5630 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5631 5632 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5633 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5634 SmallVector<SDValue, 8> MemOpChains; 5635 5636 bool seenFloatArg = false; 5637 // Walk the register/memloc assignments, inserting copies/loads. 5638 // i - Tracks the index into the list of registers allocated for the call 5639 // RealArgIdx - Tracks the index into the list of actual function arguments 5640 // j - Tracks the index into the list of byval arguments 5641 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5642 i != e; 5643 ++i, ++RealArgIdx) { 5644 CCValAssign &VA = ArgLocs[i]; 5645 SDValue Arg = OutVals[RealArgIdx]; 5646 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5647 5648 if (Flags.isByVal()) { 5649 // Argument is an aggregate which is passed by value, thus we need to 5650 // create a copy of it in the local variable space of the current stack 5651 // frame (which is the stack frame of the caller) and pass the address of 5652 // this copy to the callee. 5653 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5654 CCValAssign &ByValVA = ByValArgLocs[j++]; 5655 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5656 5657 // Memory reserved in the local variable space of the callers stack frame. 5658 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5659 5660 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5661 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5662 StackPtr, PtrOff); 5663 5664 // Create a copy of the argument in the local area of the current 5665 // stack frame. 5666 SDValue MemcpyCall = 5667 CreateCopyOfByValArgument(Arg, PtrOff, 5668 CallSeqStart.getNode()->getOperand(0), 5669 Flags, DAG, dl); 5670 5671 // This must go outside the CALLSEQ_START..END. 5672 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5673 SDLoc(MemcpyCall)); 5674 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5675 NewCallSeqStart.getNode()); 5676 Chain = CallSeqStart = NewCallSeqStart; 5677 5678 // Pass the address of the aggregate copy on the stack either in a 5679 // physical register or in the parameter list area of the current stack 5680 // frame to the callee. 5681 Arg = PtrOff; 5682 } 5683 5684 // When useCRBits() is true, there can be i1 arguments. 5685 // It is because getRegisterType(MVT::i1) => MVT::i1, 5686 // and for other integer types getRegisterType() => MVT::i32. 5687 // Extend i1 and ensure callee will get i32. 5688 if (Arg.getValueType() == MVT::i1) 5689 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5690 dl, MVT::i32, Arg); 5691 5692 if (VA.isRegLoc()) { 5693 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5694 // Put argument in a physical register. 5695 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5696 bool IsLE = Subtarget.isLittleEndian(); 5697 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5698 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5699 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5700 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5701 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5702 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5703 SVal.getValue(0))); 5704 } else 5705 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5706 } else { 5707 // Put argument in the parameter list area of the current stack frame. 5708 assert(VA.isMemLoc()); 5709 unsigned LocMemOffset = VA.getLocMemOffset(); 5710 5711 if (!IsTailCall) { 5712 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5713 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5714 StackPtr, PtrOff); 5715 5716 MemOpChains.push_back( 5717 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5718 } else { 5719 // Calculate and remember argument location. 5720 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5721 TailCallArguments); 5722 } 5723 } 5724 } 5725 5726 if (!MemOpChains.empty()) 5727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5728 5729 // Build a sequence of copy-to-reg nodes chained together with token chain 5730 // and flag operands which copy the outgoing args into the appropriate regs. 5731 SDValue InFlag; 5732 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5733 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5734 RegsToPass[i].second, InFlag); 5735 InFlag = Chain.getValue(1); 5736 } 5737 5738 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5739 // registers. 5740 if (IsVarArg) { 5741 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5742 SDValue Ops[] = { Chain, InFlag }; 5743 5744 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, 5745 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5746 5747 InFlag = Chain.getValue(1); 5748 } 5749 5750 if (IsTailCall) 5751 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5752 TailCallArguments); 5753 5754 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5755 Callee, SPDiff, NumBytes, Ins, InVals, CS); 5756 } 5757 5758 // Copy an argument into memory, being careful to do this outside the 5759 // call sequence for the call to which the argument belongs. 5760 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5761 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5762 SelectionDAG &DAG, const SDLoc &dl) const { 5763 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5764 CallSeqStart.getNode()->getOperand(0), 5765 Flags, DAG, dl); 5766 // The MEMCPY must go outside the CALLSEQ_START..END. 5767 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5768 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5769 SDLoc(MemcpyCall)); 5770 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5771 NewCallSeqStart.getNode()); 5772 return NewCallSeqStart; 5773 } 5774 5775 SDValue PPCTargetLowering::LowerCall_64SVR4( 5776 SDValue Chain, SDValue Callee, CallFlags CFlags, 5777 const SmallVectorImpl<ISD::OutputArg> &Outs, 5778 const SmallVectorImpl<SDValue> &OutVals, 5779 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5780 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5781 ImmutableCallSite CS) const { 5782 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5783 bool isLittleEndian = Subtarget.isLittleEndian(); 5784 unsigned NumOps = Outs.size(); 5785 bool IsSibCall = false; 5786 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5787 5788 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5789 unsigned PtrByteSize = 8; 5790 5791 MachineFunction &MF = DAG.getMachineFunction(); 5792 5793 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5794 IsSibCall = true; 5795 5796 // Mark this function as potentially containing a function that contains a 5797 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5798 // and restoring the callers stack pointer in this functions epilog. This is 5799 // done because by tail calling the called function might overwrite the value 5800 // in this function's (MF) stack pointer stack slot 0(SP). 5801 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5802 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5803 5804 assert(!(IsFastCall && CFlags.IsVarArg) && 5805 "fastcc not supported on varargs functions"); 5806 5807 // Count how many bytes are to be pushed on the stack, including the linkage 5808 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 5809 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 5810 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 5811 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 5812 unsigned NumBytes = LinkageSize; 5813 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 5814 unsigned &QFPR_idx = FPR_idx; 5815 5816 static const MCPhysReg GPR[] = { 5817 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 5818 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 5819 }; 5820 static const MCPhysReg VR[] = { 5821 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 5822 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 5823 }; 5824 5825 const unsigned NumGPRs = array_lengthof(GPR); 5826 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 5827 const unsigned NumVRs = array_lengthof(VR); 5828 const unsigned NumQFPRs = NumFPRs; 5829 5830 // On ELFv2, we can avoid allocating the parameter area if all the arguments 5831 // can be passed to the callee in registers. 5832 // For the fast calling convention, there is another check below. 5833 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 5834 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 5835 if (!HasParameterArea) { 5836 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 5837 unsigned AvailableFPRs = NumFPRs; 5838 unsigned AvailableVRs = NumVRs; 5839 unsigned NumBytesTmp = NumBytes; 5840 for (unsigned i = 0; i != NumOps; ++i) { 5841 if (Outs[i].Flags.isNest()) continue; 5842 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 5843 PtrByteSize, LinkageSize, ParamAreaSize, 5844 NumBytesTmp, AvailableFPRs, AvailableVRs, 5845 Subtarget.hasQPX())) 5846 HasParameterArea = true; 5847 } 5848 } 5849 5850 // When using the fast calling convention, we don't provide backing for 5851 // arguments that will be in registers. 5852 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 5853 5854 // Avoid allocating parameter area for fastcc functions if all the arguments 5855 // can be passed in the registers. 5856 if (IsFastCall) 5857 HasParameterArea = false; 5858 5859 // Add up all the space actually used. 5860 for (unsigned i = 0; i != NumOps; ++i) { 5861 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5862 EVT ArgVT = Outs[i].VT; 5863 EVT OrigVT = Outs[i].ArgVT; 5864 5865 if (Flags.isNest()) 5866 continue; 5867 5868 if (IsFastCall) { 5869 if (Flags.isByVal()) { 5870 NumGPRsUsed += (Flags.getByValSize()+7)/8; 5871 if (NumGPRsUsed > NumGPRs) 5872 HasParameterArea = true; 5873 } else { 5874 switch (ArgVT.getSimpleVT().SimpleTy) { 5875 default: llvm_unreachable("Unexpected ValueType for argument!"); 5876 case MVT::i1: 5877 case MVT::i32: 5878 case MVT::i64: 5879 if (++NumGPRsUsed <= NumGPRs) 5880 continue; 5881 break; 5882 case MVT::v4i32: 5883 case MVT::v8i16: 5884 case MVT::v16i8: 5885 case MVT::v2f64: 5886 case MVT::v2i64: 5887 case MVT::v1i128: 5888 case MVT::f128: 5889 if (++NumVRsUsed <= NumVRs) 5890 continue; 5891 break; 5892 case MVT::v4f32: 5893 // When using QPX, this is handled like a FP register, otherwise, it 5894 // is an Altivec register. 5895 if (Subtarget.hasQPX()) { 5896 if (++NumFPRsUsed <= NumFPRs) 5897 continue; 5898 } else { 5899 if (++NumVRsUsed <= NumVRs) 5900 continue; 5901 } 5902 break; 5903 case MVT::f32: 5904 case MVT::f64: 5905 case MVT::v4f64: // QPX 5906 case MVT::v4i1: // QPX 5907 if (++NumFPRsUsed <= NumFPRs) 5908 continue; 5909 break; 5910 } 5911 HasParameterArea = true; 5912 } 5913 } 5914 5915 /* Respect alignment of argument on the stack. */ 5916 auto Alignement = 5917 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5918 NumBytes = alignTo(NumBytes, Alignement); 5919 5920 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 5921 if (Flags.isInConsecutiveRegsLast()) 5922 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 5923 } 5924 5925 unsigned NumBytesActuallyUsed = NumBytes; 5926 5927 // In the old ELFv1 ABI, 5928 // the prolog code of the callee may store up to 8 GPR argument registers to 5929 // the stack, allowing va_start to index over them in memory if its varargs. 5930 // Because we cannot tell if this is needed on the caller side, we have to 5931 // conservatively assume that it is needed. As such, make sure we have at 5932 // least enough stack space for the caller to store the 8 GPRs. 5933 // In the ELFv2 ABI, we allocate the parameter area iff a callee 5934 // really requires memory operands, e.g. a vararg function. 5935 if (HasParameterArea) 5936 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 5937 else 5938 NumBytes = LinkageSize; 5939 5940 // Tail call needs the stack to be aligned. 5941 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 5942 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 5943 5944 int SPDiff = 0; 5945 5946 // Calculate by how many bytes the stack has to be adjusted in case of tail 5947 // call optimization. 5948 if (!IsSibCall) 5949 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 5950 5951 // To protect arguments on the stack from being clobbered in a tail call, 5952 // force all the loads to happen before doing any other lowering. 5953 if (CFlags.IsTailCall) 5954 Chain = DAG.getStackArgumentTokenFactor(Chain); 5955 5956 // Adjust the stack pointer for the new arguments... 5957 // These operations are automatically eliminated by the prolog/epilog pass 5958 if (!IsSibCall) 5959 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5960 SDValue CallSeqStart = Chain; 5961 5962 // Load the return address and frame pointer so it can be move somewhere else 5963 // later. 5964 SDValue LROp, FPOp; 5965 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5966 5967 // Set up a copy of the stack pointer for use loading and storing any 5968 // arguments that may not fit in the registers available for argument 5969 // passing. 5970 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5971 5972 // Figure out which arguments are going to go in registers, and which in 5973 // memory. Also, if this is a vararg function, floating point operations 5974 // must be stored to our stack, and loaded into integer regs as well, if 5975 // any integer regs are available for argument passing. 5976 unsigned ArgOffset = LinkageSize; 5977 5978 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5979 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5980 5981 SmallVector<SDValue, 8> MemOpChains; 5982 for (unsigned i = 0; i != NumOps; ++i) { 5983 SDValue Arg = OutVals[i]; 5984 ISD::ArgFlagsTy Flags = Outs[i].Flags; 5985 EVT ArgVT = Outs[i].VT; 5986 EVT OrigVT = Outs[i].ArgVT; 5987 5988 // PtrOff will be used to store the current argument to the stack if a 5989 // register cannot be found for it. 5990 SDValue PtrOff; 5991 5992 // We re-align the argument offset for each argument, except when using the 5993 // fast calling convention, when we need to make sure we do that only when 5994 // we'll actually use a stack slot. 5995 auto ComputePtrOff = [&]() { 5996 /* Respect alignment of argument on the stack. */ 5997 auto Alignment = 5998 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 5999 ArgOffset = alignTo(ArgOffset, Alignment); 6000 6001 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6002 6003 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6004 }; 6005 6006 if (!IsFastCall) { 6007 ComputePtrOff(); 6008 6009 /* Compute GPR index associated with argument offset. */ 6010 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6011 GPR_idx = std::min(GPR_idx, NumGPRs); 6012 } 6013 6014 // Promote integers to 64-bit values. 6015 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6016 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6017 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6018 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6019 } 6020 6021 // FIXME memcpy is used way more than necessary. Correctness first. 6022 // Note: "by value" is code for passing a structure by value, not 6023 // basic types. 6024 if (Flags.isByVal()) { 6025 // Note: Size includes alignment padding, so 6026 // struct x { short a; char b; } 6027 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6028 // These are the proper values we need for right-justifying the 6029 // aggregate in a parameter register. 6030 unsigned Size = Flags.getByValSize(); 6031 6032 // An empty aggregate parameter takes up no storage and no 6033 // registers. 6034 if (Size == 0) 6035 continue; 6036 6037 if (IsFastCall) 6038 ComputePtrOff(); 6039 6040 // All aggregates smaller than 8 bytes must be passed right-justified. 6041 if (Size==1 || Size==2 || Size==4) { 6042 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6043 if (GPR_idx != NumGPRs) { 6044 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6045 MachinePointerInfo(), VT); 6046 MemOpChains.push_back(Load.getValue(1)); 6047 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6048 6049 ArgOffset += PtrByteSize; 6050 continue; 6051 } 6052 } 6053 6054 if (GPR_idx == NumGPRs && Size < 8) { 6055 SDValue AddPtr = PtrOff; 6056 if (!isLittleEndian) { 6057 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6058 PtrOff.getValueType()); 6059 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6060 } 6061 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6062 CallSeqStart, 6063 Flags, DAG, dl); 6064 ArgOffset += PtrByteSize; 6065 continue; 6066 } 6067 // Copy entire object into memory. There are cases where gcc-generated 6068 // code assumes it is there, even if it could be put entirely into 6069 // registers. (This is not what the doc says.) 6070 6071 // FIXME: The above statement is likely due to a misunderstanding of the 6072 // documents. All arguments must be copied into the parameter area BY 6073 // THE CALLEE in the event that the callee takes the address of any 6074 // formal argument. That has not yet been implemented. However, it is 6075 // reasonable to use the stack area as a staging area for the register 6076 // load. 6077 6078 // Skip this for small aggregates, as we will use the same slot for a 6079 // right-justified copy, below. 6080 if (Size >= 8) 6081 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6082 CallSeqStart, 6083 Flags, DAG, dl); 6084 6085 // When a register is available, pass a small aggregate right-justified. 6086 if (Size < 8 && GPR_idx != NumGPRs) { 6087 // The easiest way to get this right-justified in a register 6088 // is to copy the structure into the rightmost portion of a 6089 // local variable slot, then load the whole slot into the 6090 // register. 6091 // FIXME: The memcpy seems to produce pretty awful code for 6092 // small aggregates, particularly for packed ones. 6093 // FIXME: It would be preferable to use the slot in the 6094 // parameter save area instead of a new local variable. 6095 SDValue AddPtr = PtrOff; 6096 if (!isLittleEndian) { 6097 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6098 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6099 } 6100 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6101 CallSeqStart, 6102 Flags, DAG, dl); 6103 6104 // Load the slot into the register. 6105 SDValue Load = 6106 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6107 MemOpChains.push_back(Load.getValue(1)); 6108 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6109 6110 // Done with this argument. 6111 ArgOffset += PtrByteSize; 6112 continue; 6113 } 6114 6115 // For aggregates larger than PtrByteSize, copy the pieces of the 6116 // object that fit into registers from the parameter save area. 6117 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6118 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6119 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6120 if (GPR_idx != NumGPRs) { 6121 SDValue Load = 6122 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6123 MemOpChains.push_back(Load.getValue(1)); 6124 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6125 ArgOffset += PtrByteSize; 6126 } else { 6127 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6128 break; 6129 } 6130 } 6131 continue; 6132 } 6133 6134 switch (Arg.getSimpleValueType().SimpleTy) { 6135 default: llvm_unreachable("Unexpected ValueType for argument!"); 6136 case MVT::i1: 6137 case MVT::i32: 6138 case MVT::i64: 6139 if (Flags.isNest()) { 6140 // The 'nest' parameter, if any, is passed in R11. 6141 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6142 break; 6143 } 6144 6145 // These can be scalar arguments or elements of an integer array type 6146 // passed directly. Clang may use those instead of "byval" aggregate 6147 // types to avoid forcing arguments to memory unnecessarily. 6148 if (GPR_idx != NumGPRs) { 6149 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6150 } else { 6151 if (IsFastCall) 6152 ComputePtrOff(); 6153 6154 assert(HasParameterArea && 6155 "Parameter area must exist to pass an argument in memory."); 6156 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6157 true, CFlags.IsTailCall, false, MemOpChains, 6158 TailCallArguments, dl); 6159 if (IsFastCall) 6160 ArgOffset += PtrByteSize; 6161 } 6162 if (!IsFastCall) 6163 ArgOffset += PtrByteSize; 6164 break; 6165 case MVT::f32: 6166 case MVT::f64: { 6167 // These can be scalar arguments or elements of a float array type 6168 // passed directly. The latter are used to implement ELFv2 homogenous 6169 // float aggregates. 6170 6171 // Named arguments go into FPRs first, and once they overflow, the 6172 // remaining arguments go into GPRs and then the parameter save area. 6173 // Unnamed arguments for vararg functions always go to GPRs and 6174 // then the parameter save area. For now, put all arguments to vararg 6175 // routines always in both locations (FPR *and* GPR or stack slot). 6176 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6177 bool NeededLoad = false; 6178 6179 // First load the argument into the next available FPR. 6180 if (FPR_idx != NumFPRs) 6181 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6182 6183 // Next, load the argument into GPR or stack slot if needed. 6184 if (!NeedGPROrStack) 6185 ; 6186 else if (GPR_idx != NumGPRs && !IsFastCall) { 6187 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6188 // once we support fp <-> gpr moves. 6189 6190 // In the non-vararg case, this can only ever happen in the 6191 // presence of f32 array types, since otherwise we never run 6192 // out of FPRs before running out of GPRs. 6193 SDValue ArgVal; 6194 6195 // Double values are always passed in a single GPR. 6196 if (Arg.getValueType() != MVT::f32) { 6197 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6198 6199 // Non-array float values are extended and passed in a GPR. 6200 } else if (!Flags.isInConsecutiveRegs()) { 6201 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6202 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6203 6204 // If we have an array of floats, we collect every odd element 6205 // together with its predecessor into one GPR. 6206 } else if (ArgOffset % PtrByteSize != 0) { 6207 SDValue Lo, Hi; 6208 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6209 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6210 if (!isLittleEndian) 6211 std::swap(Lo, Hi); 6212 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6213 6214 // The final element, if even, goes into the first half of a GPR. 6215 } else if (Flags.isInConsecutiveRegsLast()) { 6216 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6217 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6218 if (!isLittleEndian) 6219 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6220 DAG.getConstant(32, dl, MVT::i32)); 6221 6222 // Non-final even elements are skipped; they will be handled 6223 // together the with subsequent argument on the next go-around. 6224 } else 6225 ArgVal = SDValue(); 6226 6227 if (ArgVal.getNode()) 6228 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6229 } else { 6230 if (IsFastCall) 6231 ComputePtrOff(); 6232 6233 // Single-precision floating-point values are mapped to the 6234 // second (rightmost) word of the stack doubleword. 6235 if (Arg.getValueType() == MVT::f32 && 6236 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6237 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6238 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6239 } 6240 6241 assert(HasParameterArea && 6242 "Parameter area must exist to pass an argument in memory."); 6243 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6244 true, CFlags.IsTailCall, false, MemOpChains, 6245 TailCallArguments, dl); 6246 6247 NeededLoad = true; 6248 } 6249 // When passing an array of floats, the array occupies consecutive 6250 // space in the argument area; only round up to the next doubleword 6251 // at the end of the array. Otherwise, each float takes 8 bytes. 6252 if (!IsFastCall || NeededLoad) { 6253 ArgOffset += (Arg.getValueType() == MVT::f32 && 6254 Flags.isInConsecutiveRegs()) ? 4 : 8; 6255 if (Flags.isInConsecutiveRegsLast()) 6256 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6257 } 6258 break; 6259 } 6260 case MVT::v4f32: 6261 case MVT::v4i32: 6262 case MVT::v8i16: 6263 case MVT::v16i8: 6264 case MVT::v2f64: 6265 case MVT::v2i64: 6266 case MVT::v1i128: 6267 case MVT::f128: 6268 if (!Subtarget.hasQPX()) { 6269 // These can be scalar arguments or elements of a vector array type 6270 // passed directly. The latter are used to implement ELFv2 homogenous 6271 // vector aggregates. 6272 6273 // For a varargs call, named arguments go into VRs or on the stack as 6274 // usual; unnamed arguments always go to the stack or the corresponding 6275 // GPRs when within range. For now, we always put the value in both 6276 // locations (or even all three). 6277 if (CFlags.IsVarArg) { 6278 assert(HasParameterArea && 6279 "Parameter area must exist if we have a varargs call."); 6280 // We could elide this store in the case where the object fits 6281 // entirely in R registers. Maybe later. 6282 SDValue Store = 6283 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6284 MemOpChains.push_back(Store); 6285 if (VR_idx != NumVRs) { 6286 SDValue Load = 6287 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6288 MemOpChains.push_back(Load.getValue(1)); 6289 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6290 } 6291 ArgOffset += 16; 6292 for (unsigned i=0; i<16; i+=PtrByteSize) { 6293 if (GPR_idx == NumGPRs) 6294 break; 6295 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6296 DAG.getConstant(i, dl, PtrVT)); 6297 SDValue Load = 6298 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6299 MemOpChains.push_back(Load.getValue(1)); 6300 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6301 } 6302 break; 6303 } 6304 6305 // Non-varargs Altivec params go into VRs or on the stack. 6306 if (VR_idx != NumVRs) { 6307 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6308 } else { 6309 if (IsFastCall) 6310 ComputePtrOff(); 6311 6312 assert(HasParameterArea && 6313 "Parameter area must exist to pass an argument in memory."); 6314 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6315 true, CFlags.IsTailCall, true, MemOpChains, 6316 TailCallArguments, dl); 6317 if (IsFastCall) 6318 ArgOffset += 16; 6319 } 6320 6321 if (!IsFastCall) 6322 ArgOffset += 16; 6323 break; 6324 } // not QPX 6325 6326 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && 6327 "Invalid QPX parameter type"); 6328 6329 LLVM_FALLTHROUGH; 6330 case MVT::v4f64: 6331 case MVT::v4i1: { 6332 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; 6333 if (CFlags.IsVarArg) { 6334 assert(HasParameterArea && 6335 "Parameter area must exist if we have a varargs call."); 6336 // We could elide this store in the case where the object fits 6337 // entirely in R registers. Maybe later. 6338 SDValue Store = 6339 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6340 MemOpChains.push_back(Store); 6341 if (QFPR_idx != NumQFPRs) { 6342 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, 6343 PtrOff, MachinePointerInfo()); 6344 MemOpChains.push_back(Load.getValue(1)); 6345 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); 6346 } 6347 ArgOffset += (IsF32 ? 16 : 32); 6348 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { 6349 if (GPR_idx == NumGPRs) 6350 break; 6351 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6352 DAG.getConstant(i, dl, PtrVT)); 6353 SDValue Load = 6354 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6355 MemOpChains.push_back(Load.getValue(1)); 6356 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6357 } 6358 break; 6359 } 6360 6361 // Non-varargs QPX params go into registers or on the stack. 6362 if (QFPR_idx != NumQFPRs) { 6363 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); 6364 } else { 6365 if (IsFastCall) 6366 ComputePtrOff(); 6367 6368 assert(HasParameterArea && 6369 "Parameter area must exist to pass an argument in memory."); 6370 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6371 true, CFlags.IsTailCall, true, MemOpChains, 6372 TailCallArguments, dl); 6373 if (IsFastCall) 6374 ArgOffset += (IsF32 ? 16 : 32); 6375 } 6376 6377 if (!IsFastCall) 6378 ArgOffset += (IsF32 ? 16 : 32); 6379 break; 6380 } 6381 } 6382 } 6383 6384 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6385 "mismatch in size of parameter area"); 6386 (void)NumBytesActuallyUsed; 6387 6388 if (!MemOpChains.empty()) 6389 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6390 6391 // Check if this is an indirect call (MTCTR/BCTRL). 6392 // See prepareDescriptorIndirectCall and buildCallOperands for more 6393 // information about calls through function pointers in the 64-bit SVR4 ABI. 6394 if (CFlags.IsIndirect) { 6395 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6396 // Load r2 into a virtual register and store it to the TOC save area. 6397 setUsesTOCBasePtr(DAG); 6398 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6399 // TOC save area offset. 6400 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6401 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6402 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6403 Chain = DAG.getStore( 6404 Val.getValue(1), dl, Val, AddPtr, 6405 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 6406 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6407 // This does not mean the MTCTR instruction must use R12; it's easier 6408 // to model this as an extra parameter, so do that. 6409 if (isELFv2ABI && !CFlags.IsPatchPoint) 6410 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6411 } 6412 6413 // Build a sequence of copy-to-reg nodes chained together with token chain 6414 // and flag operands which copy the outgoing args into the appropriate regs. 6415 SDValue InFlag; 6416 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6417 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6418 RegsToPass[i].second, InFlag); 6419 InFlag = Chain.getValue(1); 6420 } 6421 6422 if (CFlags.IsTailCall && !IsSibCall) 6423 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6424 TailCallArguments); 6425 6426 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6427 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6428 } 6429 6430 SDValue PPCTargetLowering::LowerCall_Darwin( 6431 SDValue Chain, SDValue Callee, CallFlags CFlags, 6432 const SmallVectorImpl<ISD::OutputArg> &Outs, 6433 const SmallVectorImpl<SDValue> &OutVals, 6434 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6435 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 6436 ImmutableCallSite CS) const { 6437 unsigned NumOps = Outs.size(); 6438 6439 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6440 bool isPPC64 = PtrVT == MVT::i64; 6441 unsigned PtrByteSize = isPPC64 ? 8 : 4; 6442 6443 MachineFunction &MF = DAG.getMachineFunction(); 6444 6445 // Mark this function as potentially containing a function that contains a 6446 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6447 // and restoring the callers stack pointer in this functions epilog. This is 6448 // done because by tail calling the called function might overwrite the value 6449 // in this function's (MF) stack pointer stack slot 0(SP). 6450 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6451 CFlags.CallConv == CallingConv::Fast) 6452 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6453 6454 // Count how many bytes are to be pushed on the stack, including the linkage 6455 // area, and parameter passing area. We start with 24/48 bytes, which is 6456 // prereserved space for [SP][CR][LR][3 x unused]. 6457 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6458 unsigned NumBytes = LinkageSize; 6459 6460 // Add up all the space actually used. 6461 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually 6462 // they all go in registers, but we must reserve stack space for them for 6463 // possible use by the caller. In varargs or 64-bit calls, parameters are 6464 // assigned stack space in order, with padding so Altivec parameters are 6465 // 16-byte aligned. 6466 unsigned nAltivecParamsAtEnd = 0; 6467 for (unsigned i = 0; i != NumOps; ++i) { 6468 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6469 EVT ArgVT = Outs[i].VT; 6470 // Varargs Altivec parameters are padded to a 16 byte boundary. 6471 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 6472 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 6473 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { 6474 if (!CFlags.IsVarArg && !isPPC64) { 6475 // Non-varargs Altivec parameters go after all the non-Altivec 6476 // parameters; handle those later so we know how much padding we need. 6477 nAltivecParamsAtEnd++; 6478 continue; 6479 } 6480 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. 6481 NumBytes = ((NumBytes+15)/16)*16; 6482 } 6483 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6484 } 6485 6486 // Allow for Altivec parameters at the end, if needed. 6487 if (nAltivecParamsAtEnd) { 6488 NumBytes = ((NumBytes+15)/16)*16; 6489 NumBytes += 16*nAltivecParamsAtEnd; 6490 } 6491 6492 // The prolog code of the callee may store up to 8 GPR argument registers to 6493 // the stack, allowing va_start to index over them in memory if its varargs. 6494 // Because we cannot tell if this is needed on the caller side, we have to 6495 // conservatively assume that it is needed. As such, make sure we have at 6496 // least enough stack space for the caller to store the 8 GPRs. 6497 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6498 6499 // Tail call needs the stack to be aligned. 6500 if (getTargetMachine().Options.GuaranteedTailCallOpt && 6501 CFlags.CallConv == CallingConv::Fast) 6502 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6503 6504 // Calculate by how many bytes the stack has to be adjusted in case of tail 6505 // call optimization. 6506 int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6507 6508 // To protect arguments on the stack from being clobbered in a tail call, 6509 // force all the loads to happen before doing any other lowering. 6510 if (CFlags.IsTailCall) 6511 Chain = DAG.getStackArgumentTokenFactor(Chain); 6512 6513 // Adjust the stack pointer for the new arguments... 6514 // These operations are automatically eliminated by the prolog/epilog pass 6515 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6516 SDValue CallSeqStart = Chain; 6517 6518 // Load the return address and frame pointer so it can be move somewhere else 6519 // later. 6520 SDValue LROp, FPOp; 6521 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6522 6523 // Set up a copy of the stack pointer for use loading and storing any 6524 // arguments that may not fit in the registers available for argument 6525 // passing. 6526 SDValue StackPtr; 6527 if (isPPC64) 6528 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6529 else 6530 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 6531 6532 // Figure out which arguments are going to go in registers, and which in 6533 // memory. Also, if this is a vararg function, floating point operations 6534 // must be stored to our stack, and loaded into integer regs as well, if 6535 // any integer regs are available for argument passing. 6536 unsigned ArgOffset = LinkageSize; 6537 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6538 6539 static const MCPhysReg GPR_32[] = { // 32-bit registers. 6540 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6541 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 6542 }; 6543 static const MCPhysReg GPR_64[] = { // 64-bit registers. 6544 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6545 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6546 }; 6547 static const MCPhysReg VR[] = { 6548 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6549 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6550 }; 6551 const unsigned NumGPRs = array_lengthof(GPR_32); 6552 const unsigned NumFPRs = 13; 6553 const unsigned NumVRs = array_lengthof(VR); 6554 6555 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; 6556 6557 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6558 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6559 6560 SmallVector<SDValue, 8> MemOpChains; 6561 for (unsigned i = 0; i != NumOps; ++i) { 6562 SDValue Arg = OutVals[i]; 6563 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6564 6565 // PtrOff will be used to store the current argument to the stack if a 6566 // register cannot be found for it. 6567 SDValue PtrOff; 6568 6569 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6570 6571 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6572 6573 // On PPC64, promote integers to 64-bit values. 6574 if (isPPC64 && Arg.getValueType() == MVT::i32) { 6575 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6576 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6577 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6578 } 6579 6580 // FIXME memcpy is used way more than necessary. Correctness first. 6581 // Note: "by value" is code for passing a structure by value, not 6582 // basic types. 6583 if (Flags.isByVal()) { 6584 unsigned Size = Flags.getByValSize(); 6585 // Very small objects are passed right-justified. Everything else is 6586 // passed left-justified. 6587 if (Size==1 || Size==2) { 6588 EVT VT = (Size==1) ? MVT::i8 : MVT::i16; 6589 if (GPR_idx != NumGPRs) { 6590 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6591 MachinePointerInfo(), VT); 6592 MemOpChains.push_back(Load.getValue(1)); 6593 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6594 6595 ArgOffset += PtrByteSize; 6596 } else { 6597 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6598 PtrOff.getValueType()); 6599 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6600 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6601 CallSeqStart, 6602 Flags, DAG, dl); 6603 ArgOffset += PtrByteSize; 6604 } 6605 continue; 6606 } 6607 // Copy entire object into memory. There are cases where gcc-generated 6608 // code assumes it is there, even if it could be put entirely into 6609 // registers. (This is not what the doc says.) 6610 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6611 CallSeqStart, 6612 Flags, DAG, dl); 6613 6614 // For small aggregates (Darwin only) and aggregates >= PtrByteSize, 6615 // copy the pieces of the object that fit into registers from the 6616 // parameter save area. 6617 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6618 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6619 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6620 if (GPR_idx != NumGPRs) { 6621 SDValue Load = 6622 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo()); 6623 MemOpChains.push_back(Load.getValue(1)); 6624 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6625 ArgOffset += PtrByteSize; 6626 } else { 6627 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6628 break; 6629 } 6630 } 6631 continue; 6632 } 6633 6634 switch (Arg.getSimpleValueType().SimpleTy) { 6635 default: llvm_unreachable("Unexpected ValueType for argument!"); 6636 case MVT::i1: 6637 case MVT::i32: 6638 case MVT::i64: 6639 if (GPR_idx != NumGPRs) { 6640 if (Arg.getValueType() == MVT::i1) 6641 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); 6642 6643 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6644 } else { 6645 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6646 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6647 TailCallArguments, dl); 6648 } 6649 ArgOffset += PtrByteSize; 6650 break; 6651 case MVT::f32: 6652 case MVT::f64: 6653 if (FPR_idx != NumFPRs) { 6654 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6655 6656 if (CFlags.IsVarArg) { 6657 SDValue Store = 6658 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6659 MemOpChains.push_back(Store); 6660 6661 // Float varargs are always shadowed in available integer registers 6662 if (GPR_idx != NumGPRs) { 6663 SDValue Load = 6664 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6665 MemOpChains.push_back(Load.getValue(1)); 6666 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6667 } 6668 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ 6669 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6670 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6671 SDValue Load = 6672 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo()); 6673 MemOpChains.push_back(Load.getValue(1)); 6674 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6675 } 6676 } else { 6677 // If we have any FPRs remaining, we may also have GPRs remaining. 6678 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available 6679 // GPRs. 6680 if (GPR_idx != NumGPRs) 6681 ++GPR_idx; 6682 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && 6683 !isPPC64) // PPC64 has 64-bit GPR's obviously :) 6684 ++GPR_idx; 6685 } 6686 } else 6687 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6688 isPPC64, CFlags.IsTailCall, false, MemOpChains, 6689 TailCallArguments, dl); 6690 if (isPPC64) 6691 ArgOffset += 8; 6692 else 6693 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; 6694 break; 6695 case MVT::v4f32: 6696 case MVT::v4i32: 6697 case MVT::v8i16: 6698 case MVT::v16i8: 6699 if (CFlags.IsVarArg) { 6700 // These go aligned on the stack, or in the corresponding R registers 6701 // when within range. The Darwin PPC ABI doc claims they also go in 6702 // V registers; in fact gcc does this only for arguments that are 6703 // prototyped, not for those that match the ... We do it for all 6704 // arguments, seems to work. 6705 while (ArgOffset % 16 !=0) { 6706 ArgOffset += PtrByteSize; 6707 if (GPR_idx != NumGPRs) 6708 GPR_idx++; 6709 } 6710 // We could elide this store in the case where the object fits 6711 // entirely in R registers. Maybe later. 6712 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 6713 DAG.getConstant(ArgOffset, dl, PtrVT)); 6714 SDValue Store = 6715 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6716 MemOpChains.push_back(Store); 6717 if (VR_idx != NumVRs) { 6718 SDValue Load = 6719 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6720 MemOpChains.push_back(Load.getValue(1)); 6721 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6722 } 6723 ArgOffset += 16; 6724 for (unsigned i=0; i<16; i+=PtrByteSize) { 6725 if (GPR_idx == NumGPRs) 6726 break; 6727 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6728 DAG.getConstant(i, dl, PtrVT)); 6729 SDValue Load = 6730 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6731 MemOpChains.push_back(Load.getValue(1)); 6732 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6733 } 6734 break; 6735 } 6736 6737 // Non-varargs Altivec params generally go in registers, but have 6738 // stack space allocated at the end. 6739 if (VR_idx != NumVRs) { 6740 // Doesn't have GPR space allocated. 6741 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6742 } else if (nAltivecParamsAtEnd==0) { 6743 // We are emitting Altivec params in order. 6744 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6745 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6746 TailCallArguments, dl); 6747 ArgOffset += 16; 6748 } 6749 break; 6750 } 6751 } 6752 // If all Altivec parameters fit in registers, as they usually do, 6753 // they get stack space following the non-Altivec parameters. We 6754 // don't track this here because nobody below needs it. 6755 // If there are more Altivec parameters than fit in registers emit 6756 // the stores here. 6757 if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) { 6758 unsigned j = 0; 6759 // Offset is aligned; skip 1st 12 params which go in V registers. 6760 ArgOffset = ((ArgOffset+15)/16)*16; 6761 ArgOffset += 12*16; 6762 for (unsigned i = 0; i != NumOps; ++i) { 6763 SDValue Arg = OutVals[i]; 6764 EVT ArgType = Outs[i].VT; 6765 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || 6766 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { 6767 if (++j > NumVRs) { 6768 SDValue PtrOff; 6769 // We are emitting Altivec params in order. 6770 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6771 isPPC64, CFlags.IsTailCall, true, MemOpChains, 6772 TailCallArguments, dl); 6773 ArgOffset += 16; 6774 } 6775 } 6776 } 6777 } 6778 6779 if (!MemOpChains.empty()) 6780 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6781 6782 // On Darwin, R12 must contain the address of an indirect callee. This does 6783 // not mean the MTCTR instruction must use R12; it's easier to model this as 6784 // an extra parameter, so do that. 6785 if (CFlags.IsIndirect) { 6786 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 6787 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : 6788 PPC::R12), Callee)); 6789 } 6790 6791 // Build a sequence of copy-to-reg nodes chained together with token chain 6792 // and flag operands which copy the outgoing args into the appropriate regs. 6793 SDValue InFlag; 6794 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6795 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6796 RegsToPass[i].second, InFlag); 6797 InFlag = Chain.getValue(1); 6798 } 6799 6800 if (CFlags.IsTailCall) 6801 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6802 TailCallArguments); 6803 6804 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6805 Callee, SPDiff, NumBytes, Ins, InVals, CS); 6806 } 6807 6808 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6809 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6810 CCState &State) { 6811 6812 if (ValVT == MVT::f128) 6813 report_fatal_error("f128 is unimplemented on AIX."); 6814 6815 if (ArgFlags.isByVal()) 6816 report_fatal_error("Passing structure by value is unimplemented."); 6817 6818 if (ArgFlags.isNest()) 6819 report_fatal_error("Nest arguments are unimplemented."); 6820 6821 if (ValVT.isVector() || LocVT.isVector()) 6822 report_fatal_error("Vector arguments are unimplemented on AIX."); 6823 6824 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6825 State.getMachineFunction().getSubtarget()); 6826 const bool IsPPC64 = Subtarget.isPPC64(); 6827 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6828 6829 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6830 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6831 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6832 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6833 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6834 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6835 6836 // Arguments always reserve parameter save area. 6837 switch (ValVT.SimpleTy) { 6838 default: 6839 report_fatal_error("Unhandled value type for argument."); 6840 case MVT::i64: 6841 // i64 arguments should have been split to i32 for PPC32. 6842 assert(IsPPC64 && "PPC32 should have split i64 values."); 6843 LLVM_FALLTHROUGH; 6844 case MVT::i1: 6845 case MVT::i32: { 6846 const unsigned Offset = State.AllocateStack(PtrByteSize, PtrByteSize); 6847 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6848 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6849 // Promote integers if needed. 6850 if (ValVT.getSizeInBits() < RegVT.getSizeInBits()) 6851 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6852 : CCValAssign::LocInfo::ZExt; 6853 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6854 } 6855 else 6856 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6857 6858 return false; 6859 } 6860 case MVT::f32: 6861 case MVT::f64: { 6862 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6863 const unsigned StoreSize = LocVT.getStoreSize(); 6864 // Floats are always 4-byte aligned in the PSA on AIX. 6865 // This includes f64 in 64-bit mode for ABI compatibility. 6866 const unsigned Offset = State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4); 6867 unsigned FReg = State.AllocateReg(FPR); 6868 if (FReg) 6869 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6870 6871 // Reserve and initialize GPRs or initialize the PSA as required. 6872 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6873 for (unsigned I = 0; I < StoreSize; I += PtrByteSize) { 6874 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6875 assert(FReg && "An FPR should be available when a GPR is reserved."); 6876 if (State.isVarArg()) { 6877 // Successfully reserved GPRs are only initialized for vararg calls. 6878 // Custom handling is required for: 6879 // f64 in PPC32 needs to be split into 2 GPRs. 6880 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6881 State.addLoc( 6882 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6883 } 6884 } else { 6885 // If there are insufficient GPRs, the PSA needs to be initialized. 6886 // Initialization occurs even if an FPR was initialized for 6887 // compatibility with the AIX XL compiler. The full memory for the 6888 // argument will be initialized even if a prior word is saved in GPR. 6889 // A custom memLoc is used when the argument also passes in FPR so 6890 // that the callee handling can skip over it easily. 6891 State.addLoc( 6892 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6893 LocInfo) 6894 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6895 break; 6896 } 6897 } 6898 6899 return false; 6900 } 6901 } 6902 return true; 6903 } 6904 6905 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6906 bool IsPPC64) { 6907 assert((IsPPC64 || SVT != MVT::i64) && 6908 "i64 should have been split for 32-bit codegen."); 6909 6910 switch (SVT) { 6911 default: 6912 report_fatal_error("Unexpected value type for formal argument"); 6913 case MVT::i1: 6914 case MVT::i32: 6915 case MVT::i64: 6916 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6917 case MVT::f32: 6918 return &PPC::F4RCRegClass; 6919 case MVT::f64: 6920 return &PPC::F8RCRegClass; 6921 } 6922 } 6923 6924 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6925 SelectionDAG &DAG, SDValue ArgValue, 6926 MVT LocVT, const SDLoc &dl) { 6927 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6928 assert(ValVT.getSizeInBits() < LocVT.getSizeInBits()); 6929 6930 if (Flags.isSExt()) 6931 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6932 DAG.getValueType(ValVT)); 6933 else if (Flags.isZExt()) 6934 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6935 DAG.getValueType(ValVT)); 6936 6937 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6938 } 6939 6940 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6941 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6942 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6943 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6944 6945 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6946 CallConv == CallingConv::Fast) && 6947 "Unexpected calling convention!"); 6948 6949 if (isVarArg) 6950 report_fatal_error("This call type is unimplemented on AIX."); 6951 6952 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6953 report_fatal_error("Tail call support is unimplemented on AIX."); 6954 6955 if (useSoftFloat()) 6956 report_fatal_error("Soft float support is unimplemented on AIX."); 6957 6958 const PPCSubtarget &Subtarget = 6959 static_cast<const PPCSubtarget &>(DAG.getSubtarget()); 6960 if (Subtarget.hasQPX()) 6961 report_fatal_error("QPX support is not supported on AIX."); 6962 6963 const bool IsPPC64 = Subtarget.isPPC64(); 6964 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6965 6966 // Assign locations to all of the incoming arguments. 6967 SmallVector<CCValAssign, 16> ArgLocs; 6968 MachineFunction &MF = DAG.getMachineFunction(); 6969 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6970 6971 // Reserve space for the linkage area on the stack. 6972 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6973 // On AIX a minimum of 8 words is saved to the parameter save area. 6974 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 6975 CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize); 6976 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6977 6978 for (CCValAssign &VA : ArgLocs) { 6979 6980 if (VA.isMemLoc()) { 6981 // For compatibility with the AIX XL compiler, the float args in the 6982 // parameter save area are initialized even if the argument is available 6983 // in register. The caller is required to initialize both the register 6984 // and memory, however, the callee can choose to expect it in either. The 6985 // memloc is dismissed here because the argument is retrieved from the 6986 // register. 6987 if (VA.needsCustom()) 6988 continue; 6989 report_fatal_error( 6990 "Handling of formal arguments on the stack is unimplemented!"); 6991 } 6992 6993 assert(VA.isRegLoc() && "Unexpected argument location."); 6994 6995 EVT ValVT = VA.getValVT(); 6996 MVT LocVT = VA.getLocVT(); 6997 MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy; 6998 unsigned VReg = 6999 MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64)); 7000 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7001 if (ValVT.isScalarInteger() && 7002 (ValVT.getSizeInBits() < LocVT.getSizeInBits())) { 7003 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 7004 ArgValue = 7005 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7006 } 7007 InVals.push_back(ArgValue); 7008 } 7009 7010 // Area that is at least reserved in the caller of this function. 7011 unsigned MinReservedArea = CCInfo.getNextStackOffset(); 7012 7013 // Set the size that is at least reserved in caller of this function. Tail 7014 // call optimized function's reserved stack space needs to be aligned so 7015 // that taking the difference between two stack areas will result in an 7016 // aligned stack. 7017 MinReservedArea = 7018 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 7019 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 7020 FuncInfo->setMinReservedArea(MinReservedArea); 7021 7022 return Chain; 7023 } 7024 7025 SDValue PPCTargetLowering::LowerCall_AIX( 7026 SDValue Chain, SDValue Callee, CallFlags CFlags, 7027 const SmallVectorImpl<ISD::OutputArg> &Outs, 7028 const SmallVectorImpl<SDValue> &OutVals, 7029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7031 ImmutableCallSite CS) const { 7032 7033 assert((CFlags.CallConv == CallingConv::C || 7034 CFlags.CallConv == CallingConv::Cold || 7035 CFlags.CallConv == CallingConv::Fast) && 7036 "Unexpected calling convention!"); 7037 7038 if (CFlags.IsPatchPoint) 7039 report_fatal_error("This call type is unimplemented on AIX."); 7040 7041 const PPCSubtarget& Subtarget = 7042 static_cast<const PPCSubtarget&>(DAG.getSubtarget()); 7043 if (Subtarget.hasQPX()) 7044 report_fatal_error("QPX is not supported on AIX."); 7045 if (Subtarget.hasAltivec()) 7046 report_fatal_error("Altivec support is unimplemented on AIX."); 7047 7048 MachineFunction &MF = DAG.getMachineFunction(); 7049 SmallVector<CCValAssign, 16> ArgLocs; 7050 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7051 *DAG.getContext()); 7052 7053 // Reserve space for the linkage save area (LSA) on the stack. 7054 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7055 // [SP][CR][LR][2 x reserved][TOC]. 7056 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7057 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7058 const bool IsPPC64 = Subtarget.isPPC64(); 7059 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7060 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7061 CCInfo.AllocateStack(LinkageSize, PtrByteSize); 7062 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7063 7064 // The prolog code of the callee may store up to 8 GPR argument registers to 7065 // the stack, allowing va_start to index over them in memory if the callee 7066 // is variadic. 7067 // Because we cannot tell if this is needed on the caller side, we have to 7068 // conservatively assume that it is needed. As such, make sure we have at 7069 // least enough stack space for the caller to store the 8 GPRs. 7070 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7071 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7072 CCInfo.getNextStackOffset()); 7073 7074 // Adjust the stack pointer for the new arguments... 7075 // These operations are automatically eliminated by the prolog/epilog pass. 7076 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7077 SDValue CallSeqStart = Chain; 7078 7079 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7080 SmallVector<SDValue, 8> MemOpChains; 7081 7082 // Set up a copy of the stack pointer for loading and storing any 7083 // arguments that may not fit in the registers available for argument 7084 // passing. 7085 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7086 : DAG.getRegister(PPC::R1, MVT::i32); 7087 7088 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7089 CCValAssign &VA = ArgLocs[I++]; 7090 7091 SDValue Arg = OutVals[VA.getValNo()]; 7092 7093 if (!VA.isRegLoc() && !VA.isMemLoc()) 7094 report_fatal_error("Unexpected location for function call argument."); 7095 7096 if (VA.isRegLoc() && !VA.needsCustom()) { 7097 switch (VA.getLocInfo()) { 7098 default: 7099 report_fatal_error("Unexpected argument extension type."); 7100 case CCValAssign::Full: 7101 break; 7102 case CCValAssign::ZExt: 7103 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7104 break; 7105 case CCValAssign::SExt: 7106 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7107 break; 7108 } 7109 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7110 7111 continue; 7112 } 7113 7114 if (VA.isMemLoc()) { 7115 SDValue PtrOff = 7116 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7117 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7118 MemOpChains.push_back( 7119 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7120 7121 continue; 7122 } 7123 7124 // Custom handling is used for GPR initializations for vararg float 7125 // arguments. 7126 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7127 VA.getValVT().isFloatingPoint() && VA.getLocVT().isInteger() && 7128 "Unexpected register handling for calling convention."); 7129 7130 SDValue ArgAsInt = 7131 DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg); 7132 7133 if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize()) 7134 // f32 in 32-bit GPR 7135 // f64 in 64-bit GPR 7136 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7137 else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits()) 7138 // f32 in 64-bit GPR. 7139 RegsToPass.push_back(std::make_pair( 7140 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT()))); 7141 else { 7142 // f64 in two 32-bit GPRs 7143 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7144 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7145 "Unexpected custom register for argument!"); 7146 CCValAssign &GPR1 = VA; 7147 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7148 DAG.getConstant(32, dl, MVT::i8)); 7149 RegsToPass.push_back(std::make_pair( 7150 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7151 7152 if (I != E) { 7153 // If only 1 GPR was available, there will only be one custom GPR and 7154 // the argument will also pass in memory. 7155 CCValAssign &PeekArg = ArgLocs[I]; 7156 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7157 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7158 CCValAssign &GPR2 = ArgLocs[I++]; 7159 RegsToPass.push_back(std::make_pair( 7160 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7161 } 7162 } 7163 } 7164 } 7165 7166 if (!MemOpChains.empty()) 7167 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7168 7169 // For indirect calls, we need to save the TOC base to the stack for 7170 // restoration after the call. 7171 if (CFlags.IsIndirect) { 7172 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7173 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7174 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7175 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7176 const unsigned TOCSaveOffset = 7177 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7178 7179 setUsesTOCBasePtr(DAG); 7180 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7181 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7182 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7183 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7184 Chain = DAG.getStore( 7185 Val.getValue(1), dl, Val, AddPtr, 7186 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7187 } 7188 7189 // Build a sequence of copy-to-reg nodes chained together with token chain 7190 // and flag operands which copy the outgoing args into the appropriate regs. 7191 SDValue InFlag; 7192 for (auto Reg : RegsToPass) { 7193 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7194 InFlag = Chain.getValue(1); 7195 } 7196 7197 const int SPDiff = 0; 7198 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7199 Callee, SPDiff, NumBytes, Ins, InVals, CS); 7200 } 7201 7202 bool 7203 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7204 MachineFunction &MF, bool isVarArg, 7205 const SmallVectorImpl<ISD::OutputArg> &Outs, 7206 LLVMContext &Context) const { 7207 SmallVector<CCValAssign, 16> RVLocs; 7208 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7209 return CCInfo.CheckReturn( 7210 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7211 ? RetCC_PPC_Cold 7212 : RetCC_PPC); 7213 } 7214 7215 SDValue 7216 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7217 bool isVarArg, 7218 const SmallVectorImpl<ISD::OutputArg> &Outs, 7219 const SmallVectorImpl<SDValue> &OutVals, 7220 const SDLoc &dl, SelectionDAG &DAG) const { 7221 SmallVector<CCValAssign, 16> RVLocs; 7222 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7223 *DAG.getContext()); 7224 CCInfo.AnalyzeReturn(Outs, 7225 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7226 ? RetCC_PPC_Cold 7227 : RetCC_PPC); 7228 7229 SDValue Flag; 7230 SmallVector<SDValue, 4> RetOps(1, Chain); 7231 7232 // Copy the result values into the output registers. 7233 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7234 CCValAssign &VA = RVLocs[i]; 7235 assert(VA.isRegLoc() && "Can only return in registers!"); 7236 7237 SDValue Arg = OutVals[RealResIdx]; 7238 7239 switch (VA.getLocInfo()) { 7240 default: llvm_unreachable("Unknown loc info!"); 7241 case CCValAssign::Full: break; 7242 case CCValAssign::AExt: 7243 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7244 break; 7245 case CCValAssign::ZExt: 7246 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7247 break; 7248 case CCValAssign::SExt: 7249 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7250 break; 7251 } 7252 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7253 bool isLittleEndian = Subtarget.isLittleEndian(); 7254 // Legalize ret f64 -> ret 2 x i32. 7255 SDValue SVal = 7256 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7257 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7258 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7259 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7260 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7261 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7262 Flag = Chain.getValue(1); 7263 VA = RVLocs[++i]; // skip ahead to next loc 7264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7265 } else 7266 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7267 Flag = Chain.getValue(1); 7268 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7269 } 7270 7271 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 7272 const MCPhysReg *I = 7273 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 7274 if (I) { 7275 for (; *I; ++I) { 7276 7277 if (PPC::G8RCRegClass.contains(*I)) 7278 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 7279 else if (PPC::F8RCRegClass.contains(*I)) 7280 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 7281 else if (PPC::CRRCRegClass.contains(*I)) 7282 RetOps.push_back(DAG.getRegister(*I, MVT::i1)); 7283 else if (PPC::VRRCRegClass.contains(*I)) 7284 RetOps.push_back(DAG.getRegister(*I, MVT::Other)); 7285 else 7286 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 7287 } 7288 } 7289 7290 RetOps[0] = Chain; // Update chain. 7291 7292 // Add the flag if we have it. 7293 if (Flag.getNode()) 7294 RetOps.push_back(Flag); 7295 7296 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7297 } 7298 7299 SDValue 7300 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7301 SelectionDAG &DAG) const { 7302 SDLoc dl(Op); 7303 7304 // Get the correct type for integers. 7305 EVT IntVT = Op.getValueType(); 7306 7307 // Get the inputs. 7308 SDValue Chain = Op.getOperand(0); 7309 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7310 // Build a DYNAREAOFFSET node. 7311 SDValue Ops[2] = {Chain, FPSIdx}; 7312 SDVTList VTs = DAG.getVTList(IntVT); 7313 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7314 } 7315 7316 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7317 SelectionDAG &DAG) const { 7318 // When we pop the dynamic allocation we need to restore the SP link. 7319 SDLoc dl(Op); 7320 7321 // Get the correct type for pointers. 7322 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7323 7324 // Construct the stack pointer operand. 7325 bool isPPC64 = Subtarget.isPPC64(); 7326 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7327 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7328 7329 // Get the operands for the STACKRESTORE. 7330 SDValue Chain = Op.getOperand(0); 7331 SDValue SaveSP = Op.getOperand(1); 7332 7333 // Load the old link SP. 7334 SDValue LoadLinkSP = 7335 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7336 7337 // Restore the stack pointer. 7338 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7339 7340 // Store the old link SP. 7341 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7342 } 7343 7344 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7345 MachineFunction &MF = DAG.getMachineFunction(); 7346 bool isPPC64 = Subtarget.isPPC64(); 7347 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7348 7349 // Get current frame pointer save index. The users of this index will be 7350 // primarily DYNALLOC instructions. 7351 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7352 int RASI = FI->getReturnAddrSaveIndex(); 7353 7354 // If the frame pointer save index hasn't been defined yet. 7355 if (!RASI) { 7356 // Find out what the fix offset of the frame pointer save area. 7357 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7358 // Allocate the frame index for frame pointer save area. 7359 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7360 // Save the result. 7361 FI->setReturnAddrSaveIndex(RASI); 7362 } 7363 return DAG.getFrameIndex(RASI, PtrVT); 7364 } 7365 7366 SDValue 7367 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7368 MachineFunction &MF = DAG.getMachineFunction(); 7369 bool isPPC64 = Subtarget.isPPC64(); 7370 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7371 7372 // Get current frame pointer save index. The users of this index will be 7373 // primarily DYNALLOC instructions. 7374 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7375 int FPSI = FI->getFramePointerSaveIndex(); 7376 7377 // If the frame pointer save index hasn't been defined yet. 7378 if (!FPSI) { 7379 // Find out what the fix offset of the frame pointer save area. 7380 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7381 // Allocate the frame index for frame pointer save area. 7382 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7383 // Save the result. 7384 FI->setFramePointerSaveIndex(FPSI); 7385 } 7386 return DAG.getFrameIndex(FPSI, PtrVT); 7387 } 7388 7389 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7390 SelectionDAG &DAG) const { 7391 // Get the inputs. 7392 SDValue Chain = Op.getOperand(0); 7393 SDValue Size = Op.getOperand(1); 7394 SDLoc dl(Op); 7395 7396 // Get the correct type for pointers. 7397 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7398 // Negate the size. 7399 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7400 DAG.getConstant(0, dl, PtrVT), Size); 7401 // Construct a node for the frame pointer save index. 7402 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7403 // Build a DYNALLOC node. 7404 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7405 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7406 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7407 } 7408 7409 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7410 SelectionDAG &DAG) const { 7411 MachineFunction &MF = DAG.getMachineFunction(); 7412 7413 bool isPPC64 = Subtarget.isPPC64(); 7414 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7415 7416 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7417 return DAG.getFrameIndex(FI, PtrVT); 7418 } 7419 7420 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7421 SelectionDAG &DAG) const { 7422 SDLoc DL(Op); 7423 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7424 DAG.getVTList(MVT::i32, MVT::Other), 7425 Op.getOperand(0), Op.getOperand(1)); 7426 } 7427 7428 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7429 SelectionDAG &DAG) const { 7430 SDLoc DL(Op); 7431 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7432 Op.getOperand(0), Op.getOperand(1)); 7433 } 7434 7435 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7436 if (Op.getValueType().isVector()) 7437 return LowerVectorLoad(Op, DAG); 7438 7439 assert(Op.getValueType() == MVT::i1 && 7440 "Custom lowering only for i1 loads"); 7441 7442 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7443 7444 SDLoc dl(Op); 7445 LoadSDNode *LD = cast<LoadSDNode>(Op); 7446 7447 SDValue Chain = LD->getChain(); 7448 SDValue BasePtr = LD->getBasePtr(); 7449 MachineMemOperand *MMO = LD->getMemOperand(); 7450 7451 SDValue NewLD = 7452 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7453 BasePtr, MVT::i8, MMO); 7454 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7455 7456 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7457 return DAG.getMergeValues(Ops, dl); 7458 } 7459 7460 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7461 if (Op.getOperand(1).getValueType().isVector()) 7462 return LowerVectorStore(Op, DAG); 7463 7464 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7465 "Custom lowering only for i1 stores"); 7466 7467 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7468 7469 SDLoc dl(Op); 7470 StoreSDNode *ST = cast<StoreSDNode>(Op); 7471 7472 SDValue Chain = ST->getChain(); 7473 SDValue BasePtr = ST->getBasePtr(); 7474 SDValue Value = ST->getValue(); 7475 MachineMemOperand *MMO = ST->getMemOperand(); 7476 7477 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7478 Value); 7479 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7480 } 7481 7482 // FIXME: Remove this once the ANDI glue bug is fixed: 7483 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7484 assert(Op.getValueType() == MVT::i1 && 7485 "Custom lowering only for i1 results"); 7486 7487 SDLoc DL(Op); 7488 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7489 } 7490 7491 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7492 SelectionDAG &DAG) const { 7493 7494 // Implements a vector truncate that fits in a vector register as a shuffle. 7495 // We want to legalize vector truncates down to where the source fits in 7496 // a vector register (and target is therefore smaller than vector register 7497 // size). At that point legalization will try to custom lower the sub-legal 7498 // result and get here - where we can contain the truncate as a single target 7499 // operation. 7500 7501 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7502 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7503 // 7504 // We will implement it for big-endian ordering as this (where x denotes 7505 // undefined): 7506 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7507 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7508 // 7509 // The same operation in little-endian ordering will be: 7510 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7511 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7512 7513 assert(Op.getValueType().isVector() && "Vector type expected."); 7514 7515 SDLoc DL(Op); 7516 SDValue N1 = Op.getOperand(0); 7517 unsigned SrcSize = N1.getValueType().getSizeInBits(); 7518 assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector"); 7519 SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7520 7521 EVT TrgVT = Op.getValueType(); 7522 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7523 EVT EltVT = TrgVT.getVectorElementType(); 7524 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7525 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7526 7527 // First list the elements we want to keep. 7528 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7529 SmallVector<int, 16> ShuffV; 7530 if (Subtarget.isLittleEndian()) 7531 for (unsigned i = 0; i < TrgNumElts; ++i) 7532 ShuffV.push_back(i * SizeMult); 7533 else 7534 for (unsigned i = 1; i <= TrgNumElts; ++i) 7535 ShuffV.push_back(i * SizeMult - 1); 7536 7537 // Populate the remaining elements with undefs. 7538 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7539 // ShuffV.push_back(i + WideNumElts); 7540 ShuffV.push_back(WideNumElts + 1); 7541 7542 SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc); 7543 return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV); 7544 } 7545 7546 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7547 /// possible. 7548 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7549 // Not FP? Not a fsel. 7550 if (!Op.getOperand(0).getValueType().isFloatingPoint() || 7551 !Op.getOperand(2).getValueType().isFloatingPoint()) 7552 return Op; 7553 7554 bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath; 7555 bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath; 7556 // We might be able to do better than this under some circumstances, but in 7557 // general, fsel-based lowering of select is a finite-math-only optimization. 7558 // For more information, see section F.3 of the 2.06 ISA specification. 7559 // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the 7560 // presence of infinities. 7561 if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs)) 7562 return Op; 7563 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7564 7565 EVT ResVT = Op.getValueType(); 7566 EVT CmpVT = Op.getOperand(0).getValueType(); 7567 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7568 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7569 SDLoc dl(Op); 7570 7571 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7572 switch (CC) { 7573 default: 7574 // Not a min/max but with finite math, we may still be able to use fsel. 7575 if (HasNoInfs && HasNoNaNs) 7576 break; 7577 return Op; 7578 case ISD::SETOGT: 7579 case ISD::SETGT: 7580 return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS); 7581 case ISD::SETOLT: 7582 case ISD::SETLT: 7583 return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS); 7584 } 7585 } 7586 7587 // TODO: Propagate flags from the select rather than global settings. 7588 SDNodeFlags Flags; 7589 Flags.setNoInfs(true); 7590 Flags.setNoNaNs(true); 7591 7592 // If the RHS of the comparison is a 0.0, we don't need to do the 7593 // subtraction at all. 7594 SDValue Sel1; 7595 if (isFloatingPointZero(RHS)) 7596 switch (CC) { 7597 default: break; // SETUO etc aren't handled by fsel. 7598 case ISD::SETNE: 7599 std::swap(TV, FV); 7600 LLVM_FALLTHROUGH; 7601 case ISD::SETEQ: 7602 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7603 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7604 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7605 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7606 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7607 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7608 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7609 case ISD::SETULT: 7610 case ISD::SETLT: 7611 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7612 LLVM_FALLTHROUGH; 7613 case ISD::SETOGE: 7614 case ISD::SETGE: 7615 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7616 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7617 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7618 case ISD::SETUGT: 7619 case ISD::SETGT: 7620 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7621 LLVM_FALLTHROUGH; 7622 case ISD::SETOLE: 7623 case ISD::SETLE: 7624 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7625 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7626 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7627 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7628 } 7629 7630 SDValue Cmp; 7631 switch (CC) { 7632 default: break; // SETUO etc aren't handled by fsel. 7633 case ISD::SETNE: 7634 std::swap(TV, FV); 7635 LLVM_FALLTHROUGH; 7636 case ISD::SETEQ: 7637 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7638 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7639 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7640 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7641 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7642 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7643 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7644 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 7645 case ISD::SETULT: 7646 case ISD::SETLT: 7647 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7648 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7649 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7650 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7651 case ISD::SETOGE: 7652 case ISD::SETGE: 7653 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 7654 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7655 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7656 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7657 case ISD::SETUGT: 7658 case ISD::SETGT: 7659 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7660 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7661 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7662 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 7663 case ISD::SETOLE: 7664 case ISD::SETLE: 7665 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 7666 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 7667 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 7668 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 7669 } 7670 return Op; 7671 } 7672 7673 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 7674 SelectionDAG &DAG, 7675 const SDLoc &dl) const { 7676 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7677 SDValue Src = Op.getOperand(0); 7678 if (Src.getValueType() == MVT::f32) 7679 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7680 7681 SDValue Tmp; 7682 switch (Op.getSimpleValueType().SimpleTy) { 7683 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7684 case MVT::i32: 7685 Tmp = DAG.getNode( 7686 Op.getOpcode() == ISD::FP_TO_SINT 7687 ? PPCISD::FCTIWZ 7688 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7689 dl, MVT::f64, Src); 7690 break; 7691 case MVT::i64: 7692 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7693 "i64 FP_TO_UINT is supported only with FPCVT"); 7694 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7695 PPCISD::FCTIDUZ, 7696 dl, MVT::f64, Src); 7697 break; 7698 } 7699 7700 // Convert the FP value to an int value through memory. 7701 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 7702 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); 7703 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 7704 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 7705 MachinePointerInfo MPI = 7706 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 7707 7708 // Emit a store to the stack slot. 7709 SDValue Chain; 7710 if (i32Stack) { 7711 MachineFunction &MF = DAG.getMachineFunction(); 7712 MachineMemOperand *MMO = 7713 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); 7714 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; 7715 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 7716 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 7717 } else 7718 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI); 7719 7720 // Result is a load from the stack slot. If loading 4 bytes, make sure to 7721 // add in a bias on big endian. 7722 if (Op.getValueType() == MVT::i32 && !i32Stack) { 7723 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 7724 DAG.getConstant(4, dl, FIPtr.getValueType())); 7725 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 7726 } 7727 7728 RLI.Chain = Chain; 7729 RLI.Ptr = FIPtr; 7730 RLI.MPI = MPI; 7731 } 7732 7733 /// Custom lowers floating point to integer conversions to use 7734 /// the direct move instructions available in ISA 2.07 to avoid the 7735 /// need for load/store combinations. 7736 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 7737 SelectionDAG &DAG, 7738 const SDLoc &dl) const { 7739 assert(Op.getOperand(0).getValueType().isFloatingPoint()); 7740 SDValue Src = Op.getOperand(0); 7741 7742 if (Src.getValueType() == MVT::f32) 7743 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 7744 7745 SDValue Tmp; 7746 switch (Op.getSimpleValueType().SimpleTy) { 7747 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 7748 case MVT::i32: 7749 Tmp = DAG.getNode( 7750 Op.getOpcode() == ISD::FP_TO_SINT 7751 ? PPCISD::FCTIWZ 7752 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), 7753 dl, MVT::f64, Src); 7754 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); 7755 break; 7756 case MVT::i64: 7757 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && 7758 "i64 FP_TO_UINT is supported only with FPCVT"); 7759 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 7760 PPCISD::FCTIDUZ, 7761 dl, MVT::f64, Src); 7762 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); 7763 break; 7764 } 7765 return Tmp; 7766 } 7767 7768 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 7769 const SDLoc &dl) const { 7770 7771 // FP to INT conversions are legal for f128. 7772 if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128)) 7773 return Op; 7774 7775 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 7776 // PPC (the libcall is not available). 7777 if (Op.getOperand(0).getValueType() == MVT::ppcf128) { 7778 if (Op.getValueType() == MVT::i32) { 7779 if (Op.getOpcode() == ISD::FP_TO_SINT) { 7780 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7781 MVT::f64, Op.getOperand(0), 7782 DAG.getIntPtrConstant(0, dl)); 7783 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, 7784 MVT::f64, Op.getOperand(0), 7785 DAG.getIntPtrConstant(1, dl)); 7786 7787 // Add the two halves of the long double in round-to-zero mode. 7788 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 7789 7790 // Now use a smaller FP_TO_SINT. 7791 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 7792 } 7793 if (Op.getOpcode() == ISD::FP_TO_UINT) { 7794 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 7795 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 7796 SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128); 7797 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 7798 // FIXME: generated code sucks. 7799 // TODO: Are there fast-math-flags to propagate to this FSUB? 7800 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, 7801 Op.getOperand(0), Tmp); 7802 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 7803 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, 7804 DAG.getConstant(0x80000000, dl, MVT::i32)); 7805 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, 7806 Op.getOperand(0)); 7807 return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False, 7808 ISD::SETGE); 7809 } 7810 } 7811 7812 return SDValue(); 7813 } 7814 7815 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 7816 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 7817 7818 ReuseLoadInfo RLI; 7819 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7820 7821 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 7822 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 7823 } 7824 7825 // We're trying to insert a regular store, S, and then a load, L. If the 7826 // incoming value, O, is a load, we might just be able to have our load use the 7827 // address used by O. However, we don't know if anything else will store to 7828 // that address before we can load from it. To prevent this situation, we need 7829 // to insert our load, L, into the chain as a peer of O. To do this, we give L 7830 // the same chain operand as O, we create a token factor from the chain results 7831 // of O and L, and we replace all uses of O's chain result with that token 7832 // factor (see spliceIntoChain below for this last part). 7833 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 7834 ReuseLoadInfo &RLI, 7835 SelectionDAG &DAG, 7836 ISD::LoadExtType ET) const { 7837 SDLoc dl(Op); 7838 if (ET == ISD::NON_EXTLOAD && 7839 (Op.getOpcode() == ISD::FP_TO_UINT || 7840 Op.getOpcode() == ISD::FP_TO_SINT) && 7841 isOperationLegalOrCustom(Op.getOpcode(), 7842 Op.getOperand(0).getValueType())) { 7843 7844 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 7845 return true; 7846 } 7847 7848 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 7849 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 7850 LD->isNonTemporal()) 7851 return false; 7852 if (LD->getMemoryVT() != MemVT) 7853 return false; 7854 7855 RLI.Ptr = LD->getBasePtr(); 7856 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 7857 assert(LD->getAddressingMode() == ISD::PRE_INC && 7858 "Non-pre-inc AM on PPC?"); 7859 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 7860 LD->getOffset()); 7861 } 7862 7863 RLI.Chain = LD->getChain(); 7864 RLI.MPI = LD->getPointerInfo(); 7865 RLI.IsDereferenceable = LD->isDereferenceable(); 7866 RLI.IsInvariant = LD->isInvariant(); 7867 RLI.Alignment = LD->getAlignment(); 7868 RLI.AAInfo = LD->getAAInfo(); 7869 RLI.Ranges = LD->getRanges(); 7870 7871 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 7872 return true; 7873 } 7874 7875 // Given the head of the old chain, ResChain, insert a token factor containing 7876 // it and NewResChain, and make users of ResChain now be users of that token 7877 // factor. 7878 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 7879 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 7880 SDValue NewResChain, 7881 SelectionDAG &DAG) const { 7882 if (!ResChain) 7883 return; 7884 7885 SDLoc dl(NewResChain); 7886 7887 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7888 NewResChain, DAG.getUNDEF(MVT::Other)); 7889 assert(TF.getNode() != NewResChain.getNode() && 7890 "A new TF really is required here"); 7891 7892 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 7893 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 7894 } 7895 7896 /// Analyze profitability of direct move 7897 /// prefer float load to int load plus direct move 7898 /// when there is no integer use of int load 7899 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 7900 SDNode *Origin = Op.getOperand(0).getNode(); 7901 if (Origin->getOpcode() != ISD::LOAD) 7902 return true; 7903 7904 // If there is no LXSIBZX/LXSIHZX, like Power8, 7905 // prefer direct move if the memory size is 1 or 2 bytes. 7906 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 7907 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 7908 return true; 7909 7910 for (SDNode::use_iterator UI = Origin->use_begin(), 7911 UE = Origin->use_end(); 7912 UI != UE; ++UI) { 7913 7914 // Only look at the users of the loaded value. 7915 if (UI.getUse().get().getResNo() != 0) 7916 continue; 7917 7918 if (UI->getOpcode() != ISD::SINT_TO_FP && 7919 UI->getOpcode() != ISD::UINT_TO_FP) 7920 return true; 7921 } 7922 7923 return false; 7924 } 7925 7926 /// Custom lowers integer to floating point conversions to use 7927 /// the direct move instructions available in ISA 2.07 to avoid the 7928 /// need for load/store combinations. 7929 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 7930 SelectionDAG &DAG, 7931 const SDLoc &dl) const { 7932 assert((Op.getValueType() == MVT::f32 || 7933 Op.getValueType() == MVT::f64) && 7934 "Invalid floating point type as target of conversion"); 7935 assert(Subtarget.hasFPCVT() && 7936 "Int to FP conversions with direct moves require FPCVT"); 7937 SDValue FP; 7938 SDValue Src = Op.getOperand(0); 7939 bool SinglePrec = Op.getValueType() == MVT::f32; 7940 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 7941 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; 7942 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : 7943 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); 7944 7945 if (WordInt) { 7946 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, 7947 dl, MVT::f64, Src); 7948 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7949 } 7950 else { 7951 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); 7952 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); 7953 } 7954 7955 return FP; 7956 } 7957 7958 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 7959 7960 EVT VecVT = Vec.getValueType(); 7961 assert(VecVT.isVector() && "Expected a vector type."); 7962 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 7963 7964 EVT EltVT = VecVT.getVectorElementType(); 7965 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7966 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7967 7968 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 7969 SmallVector<SDValue, 16> Ops(NumConcat); 7970 Ops[0] = Vec; 7971 SDValue UndefVec = DAG.getUNDEF(VecVT); 7972 for (unsigned i = 1; i < NumConcat; ++i) 7973 Ops[i] = UndefVec; 7974 7975 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 7976 } 7977 7978 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 7979 const SDLoc &dl) const { 7980 7981 unsigned Opc = Op.getOpcode(); 7982 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) && 7983 "Unexpected conversion type"); 7984 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 7985 "Supports conversions to v2f64/v4f32 only."); 7986 7987 bool SignedConv = Opc == ISD::SINT_TO_FP; 7988 bool FourEltRes = Op.getValueType() == MVT::v4f32; 7989 7990 SDValue Wide = widenVec(DAG, Op.getOperand(0), dl); 7991 EVT WideVT = Wide.getValueType(); 7992 unsigned WideNumElts = WideVT.getVectorNumElements(); 7993 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 7994 7995 SmallVector<int, 16> ShuffV; 7996 for (unsigned i = 0; i < WideNumElts; ++i) 7997 ShuffV.push_back(i + WideNumElts); 7998 7999 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8000 int SaveElts = FourEltRes ? 4 : 2; 8001 if (Subtarget.isLittleEndian()) 8002 for (int i = 0; i < SaveElts; i++) 8003 ShuffV[i * Stride] = i; 8004 else 8005 for (int i = 1; i <= SaveElts; i++) 8006 ShuffV[i * Stride - 1] = i - 1; 8007 8008 SDValue ShuffleSrc2 = 8009 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8010 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8011 unsigned ExtendOp = 8012 SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST; 8013 8014 SDValue Extend; 8015 if (!Subtarget.hasP9Altivec() && SignedConv) { 8016 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8017 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8018 DAG.getValueType(Op.getOperand(0).getValueType())); 8019 } else 8020 Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange); 8021 8022 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8023 } 8024 8025 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8026 SelectionDAG &DAG) const { 8027 SDLoc dl(Op); 8028 8029 EVT InVT = Op.getOperand(0).getValueType(); 8030 EVT OutVT = Op.getValueType(); 8031 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8032 isOperationCustom(Op.getOpcode(), InVT)) 8033 return LowerINT_TO_FPVector(Op, DAG, dl); 8034 8035 // Conversions to f128 are legal. 8036 if (EnableQuadPrecision && (Op.getValueType() == MVT::f128)) 8037 return Op; 8038 8039 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { 8040 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) 8041 return SDValue(); 8042 8043 SDValue Value = Op.getOperand(0); 8044 // The values are now known to be -1 (false) or 1 (true). To convert this 8045 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 8046 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 8047 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 8048 8049 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 8050 8051 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 8052 8053 if (Op.getValueType() != MVT::v4f64) 8054 Value = DAG.getNode(ISD::FP_ROUND, dl, 8055 Op.getValueType(), Value, 8056 DAG.getIntPtrConstant(1, dl)); 8057 return Value; 8058 } 8059 8060 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8061 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8062 return SDValue(); 8063 8064 if (Op.getOperand(0).getValueType() == MVT::i1) 8065 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), 8066 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8067 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8068 8069 // If we have direct moves, we can do all the conversion, skip the store/load 8070 // however, without FPCVT we can't do most conversions. 8071 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8072 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8073 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8074 8075 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 8076 "UINT_TO_FP is supported only with FPCVT"); 8077 8078 // If we have FCFIDS, then use it when converting to single-precision. 8079 // Otherwise, convert to double-precision and then round. 8080 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8081 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 8082 : PPCISD::FCFIDS) 8083 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 8084 : PPCISD::FCFID); 8085 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 8086 ? MVT::f32 8087 : MVT::f64; 8088 8089 if (Op.getOperand(0).getValueType() == MVT::i64) { 8090 SDValue SINT = Op.getOperand(0); 8091 // When converting to single-precision, we actually need to convert 8092 // to double-precision first and then round to single-precision. 8093 // To avoid double-rounding effects during that operation, we have 8094 // to prepare the input operand. Bits that might be truncated when 8095 // converting to double-precision are replaced by a bit that won't 8096 // be lost at this stage, but is below the single-precision rounding 8097 // position. 8098 // 8099 // However, if -enable-unsafe-fp-math is in effect, accept double 8100 // rounding to avoid the extra overhead. 8101 if (Op.getValueType() == MVT::f32 && 8102 !Subtarget.hasFPCVT() && 8103 !DAG.getTarget().Options.UnsafeFPMath) { 8104 8105 // Twiddle input to make sure the low 11 bits are zero. (If this 8106 // is the case, we are guaranteed the value will fit into the 53 bit 8107 // mantissa of an IEEE double-precision value without rounding.) 8108 // If any of those low 11 bits were not zero originally, make sure 8109 // bit 12 (value 2048) is set instead, so that the final rounding 8110 // to single-precision gets the correct result. 8111 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8112 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8113 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8114 Round, DAG.getConstant(2047, dl, MVT::i64)); 8115 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8116 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8117 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8118 8119 // However, we cannot use that value unconditionally: if the magnitude 8120 // of the input value is small, the bit-twiddling we did above might 8121 // end up visibly changing the output. Fortunately, in that case, we 8122 // don't need to twiddle bits since the original input will convert 8123 // exactly to double-precision floating-point already. Therefore, 8124 // construct a conditional to use the original value if the top 11 8125 // bits are all sign-bit copies, and use the rounded value computed 8126 // above otherwise. 8127 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8128 SINT, DAG.getConstant(53, dl, MVT::i32)); 8129 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8130 Cond, DAG.getConstant(1, dl, MVT::i64)); 8131 Cond = DAG.getSetCC(dl, MVT::i32, 8132 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8133 8134 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8135 } 8136 8137 ReuseLoadInfo RLI; 8138 SDValue Bits; 8139 8140 MachineFunction &MF = DAG.getMachineFunction(); 8141 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8142 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8143 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8144 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8145 } else if (Subtarget.hasLFIWAX() && 8146 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8147 MachineMemOperand *MMO = 8148 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8149 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8150 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8151 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8152 DAG.getVTList(MVT::f64, MVT::Other), 8153 Ops, MVT::i32, MMO); 8154 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8155 } else if (Subtarget.hasFPCVT() && 8156 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8157 MachineMemOperand *MMO = 8158 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8159 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8160 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8161 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8162 DAG.getVTList(MVT::f64, MVT::Other), 8163 Ops, MVT::i32, MMO); 8164 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8165 } else if (((Subtarget.hasLFIWAX() && 8166 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8167 (Subtarget.hasFPCVT() && 8168 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8169 SINT.getOperand(0).getValueType() == MVT::i32) { 8170 MachineFrameInfo &MFI = MF.getFrameInfo(); 8171 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8172 8173 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8174 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8175 8176 SDValue Store = 8177 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, 8178 MachinePointerInfo::getFixedStack( 8179 DAG.getMachineFunction(), FrameIdx)); 8180 8181 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8182 "Expected an i32 store"); 8183 8184 RLI.Ptr = FIdx; 8185 RLI.Chain = Store; 8186 RLI.MPI = 8187 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8188 RLI.Alignment = 4; 8189 8190 MachineMemOperand *MMO = 8191 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8192 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8193 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8194 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8195 PPCISD::LFIWZX : PPCISD::LFIWAX, 8196 dl, DAG.getVTList(MVT::f64, MVT::Other), 8197 Ops, MVT::i32, MMO); 8198 } else 8199 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8200 8201 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); 8202 8203 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8204 FP = DAG.getNode(ISD::FP_ROUND, dl, 8205 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 8206 return FP; 8207 } 8208 8209 assert(Op.getOperand(0).getValueType() == MVT::i32 && 8210 "Unhandled INT_TO_FP type in custom expander!"); 8211 // Since we only generate this in 64-bit mode, we can take advantage of 8212 // 64-bit registers. In particular, sign extend the input value into the 8213 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8214 // then lfd it and fcfid it. 8215 MachineFunction &MF = DAG.getMachineFunction(); 8216 MachineFrameInfo &MFI = MF.getFrameInfo(); 8217 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8218 8219 SDValue Ld; 8220 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8221 ReuseLoadInfo RLI; 8222 bool ReusingLoad; 8223 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, 8224 DAG))) { 8225 int FrameIdx = MFI.CreateStackObject(4, 4, false); 8226 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8227 8228 SDValue Store = 8229 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 8230 MachinePointerInfo::getFixedStack( 8231 DAG.getMachineFunction(), FrameIdx)); 8232 8233 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8234 "Expected an i32 store"); 8235 8236 RLI.Ptr = FIdx; 8237 RLI.Chain = Store; 8238 RLI.MPI = 8239 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8240 RLI.Alignment = 4; 8241 } 8242 8243 MachineMemOperand *MMO = 8244 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8245 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8246 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8247 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? 8248 PPCISD::LFIWZX : PPCISD::LFIWAX, 8249 dl, DAG.getVTList(MVT::f64, MVT::Other), 8250 Ops, MVT::i32, MMO); 8251 if (ReusingLoad) 8252 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8253 } else { 8254 assert(Subtarget.isPPC64() && 8255 "i32->FP without LFIWAX supported only on PPC64"); 8256 8257 int FrameIdx = MFI.CreateStackObject(8, 8, false); 8258 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8259 8260 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, 8261 Op.getOperand(0)); 8262 8263 // STD the extended value into the stack slot. 8264 SDValue Store = DAG.getStore( 8265 DAG.getEntryNode(), dl, Ext64, FIdx, 8266 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8267 8268 // Load the value as a double. 8269 Ld = DAG.getLoad( 8270 MVT::f64, dl, Store, FIdx, 8271 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8272 } 8273 8274 // FCFID it and return it. 8275 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); 8276 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) 8277 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8278 DAG.getIntPtrConstant(0, dl)); 8279 return FP; 8280 } 8281 8282 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, 8283 SelectionDAG &DAG) const { 8284 SDLoc dl(Op); 8285 /* 8286 The rounding mode is in bits 30:31 of FPSR, and has the following 8287 settings: 8288 00 Round to nearest 8289 01 Round to 0 8290 10 Round to +inf 8291 11 Round to -inf 8292 8293 FLT_ROUNDS, on the other hand, expects the following: 8294 -1 Undefined 8295 0 Round to 0 8296 1 Round to nearest 8297 2 Round to +inf 8298 3 Round to -inf 8299 8300 To perform the conversion, we do: 8301 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8302 */ 8303 8304 MachineFunction &MF = DAG.getMachineFunction(); 8305 EVT VT = Op.getValueType(); 8306 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8307 8308 // Save FP Control Word to register 8309 EVT NodeTys[] = { 8310 MVT::f64, // return register 8311 MVT::Glue // unused in this context 8312 }; 8313 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); 8314 8315 // Save FP register to stack slot 8316 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false); 8317 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8318 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, 8319 MachinePointerInfo()); 8320 8321 // Load FP Control Word from low 32 bits of stack slot. 8322 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8323 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8324 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo()); 8325 8326 // Transform as necessary 8327 SDValue CWD1 = 8328 DAG.getNode(ISD::AND, dl, MVT::i32, 8329 CWD, DAG.getConstant(3, dl, MVT::i32)); 8330 SDValue CWD2 = 8331 DAG.getNode(ISD::SRL, dl, MVT::i32, 8332 DAG.getNode(ISD::AND, dl, MVT::i32, 8333 DAG.getNode(ISD::XOR, dl, MVT::i32, 8334 CWD, DAG.getConstant(3, dl, MVT::i32)), 8335 DAG.getConstant(3, dl, MVT::i32)), 8336 DAG.getConstant(1, dl, MVT::i32)); 8337 8338 SDValue RetVal = 8339 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8340 8341 return DAG.getNode((VT.getSizeInBits() < 16 ? 8342 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); 8343 } 8344 8345 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8346 EVT VT = Op.getValueType(); 8347 unsigned BitWidth = VT.getSizeInBits(); 8348 SDLoc dl(Op); 8349 assert(Op.getNumOperands() == 3 && 8350 VT == Op.getOperand(1).getValueType() && 8351 "Unexpected SHL!"); 8352 8353 // Expand into a bunch of logical ops. Note that these ops 8354 // depend on the PPC behavior for oversized shift amounts. 8355 SDValue Lo = Op.getOperand(0); 8356 SDValue Hi = Op.getOperand(1); 8357 SDValue Amt = Op.getOperand(2); 8358 EVT AmtVT = Amt.getValueType(); 8359 8360 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8361 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8362 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8363 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8364 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8365 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8366 DAG.getConstant(-BitWidth, dl, AmtVT)); 8367 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8368 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8369 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8370 SDValue OutOps[] = { OutLo, OutHi }; 8371 return DAG.getMergeValues(OutOps, dl); 8372 } 8373 8374 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8375 EVT VT = Op.getValueType(); 8376 SDLoc dl(Op); 8377 unsigned BitWidth = VT.getSizeInBits(); 8378 assert(Op.getNumOperands() == 3 && 8379 VT == Op.getOperand(1).getValueType() && 8380 "Unexpected SRL!"); 8381 8382 // Expand into a bunch of logical ops. Note that these ops 8383 // depend on the PPC behavior for oversized shift amounts. 8384 SDValue Lo = Op.getOperand(0); 8385 SDValue Hi = Op.getOperand(1); 8386 SDValue Amt = Op.getOperand(2); 8387 EVT AmtVT = Amt.getValueType(); 8388 8389 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8390 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8391 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8392 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8393 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8394 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8395 DAG.getConstant(-BitWidth, dl, AmtVT)); 8396 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8397 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8398 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8399 SDValue OutOps[] = { OutLo, OutHi }; 8400 return DAG.getMergeValues(OutOps, dl); 8401 } 8402 8403 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8404 SDLoc dl(Op); 8405 EVT VT = Op.getValueType(); 8406 unsigned BitWidth = VT.getSizeInBits(); 8407 assert(Op.getNumOperands() == 3 && 8408 VT == Op.getOperand(1).getValueType() && 8409 "Unexpected SRA!"); 8410 8411 // Expand into a bunch of logical ops, followed by a select_cc. 8412 SDValue Lo = Op.getOperand(0); 8413 SDValue Hi = Op.getOperand(1); 8414 SDValue Amt = Op.getOperand(2); 8415 EVT AmtVT = Amt.getValueType(); 8416 8417 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8418 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8419 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8420 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8421 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8422 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8423 DAG.getConstant(-BitWidth, dl, AmtVT)); 8424 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8425 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8426 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8427 Tmp4, Tmp6, ISD::SETLE); 8428 SDValue OutOps[] = { OutLo, OutHi }; 8429 return DAG.getMergeValues(OutOps, dl); 8430 } 8431 8432 //===----------------------------------------------------------------------===// 8433 // Vector related lowering. 8434 // 8435 8436 /// BuildSplatI - Build a canonical splati of Val with an element size of 8437 /// SplatSize. Cast the result to VT. 8438 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, 8439 SelectionDAG &DAG, const SDLoc &dl) { 8440 static const MVT VTys[] = { // canonical VT to use for each size. 8441 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8442 }; 8443 8444 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8445 8446 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. 8447 if (Val == -1) 8448 SplatSize = 1; 8449 8450 EVT CanonicalVT = VTys[SplatSize-1]; 8451 8452 // Build a canonical splat for this value. 8453 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8454 } 8455 8456 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8457 /// specified intrinsic ID. 8458 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8459 const SDLoc &dl, EVT DestVT = MVT::Other) { 8460 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8461 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8462 DAG.getConstant(IID, dl, MVT::i32), Op); 8463 } 8464 8465 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8466 /// specified intrinsic ID. 8467 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8468 SelectionDAG &DAG, const SDLoc &dl, 8469 EVT DestVT = MVT::Other) { 8470 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8471 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8472 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8473 } 8474 8475 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8476 /// specified intrinsic ID. 8477 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8478 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8479 EVT DestVT = MVT::Other) { 8480 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 8481 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8482 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 8483 } 8484 8485 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 8486 /// amount. The result has the specified value type. 8487 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 8488 SelectionDAG &DAG, const SDLoc &dl) { 8489 // Force LHS/RHS to be the right type. 8490 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 8491 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 8492 8493 int Ops[16]; 8494 for (unsigned i = 0; i != 16; ++i) 8495 Ops[i] = i + Amt; 8496 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 8497 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8498 } 8499 8500 /// Do we have an efficient pattern in a .td file for this node? 8501 /// 8502 /// \param V - pointer to the BuildVectorSDNode being matched 8503 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 8504 /// 8505 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 8506 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 8507 /// the opposite is true (expansion is beneficial) are: 8508 /// - The node builds a vector out of integers that are not 32 or 64-bits 8509 /// - The node builds a vector out of constants 8510 /// - The node is a "load-and-splat" 8511 /// In all other cases, we will choose to keep the BUILD_VECTOR. 8512 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 8513 bool HasDirectMove, 8514 bool HasP8Vector) { 8515 EVT VecVT = V->getValueType(0); 8516 bool RightType = VecVT == MVT::v2f64 || 8517 (HasP8Vector && VecVT == MVT::v4f32) || 8518 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 8519 if (!RightType) 8520 return false; 8521 8522 bool IsSplat = true; 8523 bool IsLoad = false; 8524 SDValue Op0 = V->getOperand(0); 8525 8526 // This function is called in a block that confirms the node is not a constant 8527 // splat. So a constant BUILD_VECTOR here means the vector is built out of 8528 // different constants. 8529 if (V->isConstant()) 8530 return false; 8531 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 8532 if (V->getOperand(i).isUndef()) 8533 return false; 8534 // We want to expand nodes that represent load-and-splat even if the 8535 // loaded value is a floating point truncation or conversion to int. 8536 if (V->getOperand(i).getOpcode() == ISD::LOAD || 8537 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 8538 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8539 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 8540 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 8541 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 8542 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 8543 IsLoad = true; 8544 // If the operands are different or the input is not a load and has more 8545 // uses than just this BV node, then it isn't a splat. 8546 if (V->getOperand(i) != Op0 || 8547 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 8548 IsSplat = false; 8549 } 8550 return !(IsSplat && IsLoad); 8551 } 8552 8553 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 8554 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 8555 8556 SDLoc dl(Op); 8557 SDValue Op0 = Op->getOperand(0); 8558 8559 if (!EnableQuadPrecision || 8560 (Op.getValueType() != MVT::f128 ) || 8561 (Op0.getOpcode() != ISD::BUILD_PAIR) || 8562 (Op0.getOperand(0).getValueType() != MVT::i64) || 8563 (Op0.getOperand(1).getValueType() != MVT::i64)) 8564 return SDValue(); 8565 8566 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 8567 Op0.getOperand(1)); 8568 } 8569 8570 static const SDValue *getNormalLoadInput(const SDValue &Op) { 8571 const SDValue *InputLoad = &Op; 8572 if (InputLoad->getOpcode() == ISD::BITCAST) 8573 InputLoad = &InputLoad->getOperand(0); 8574 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR) 8575 InputLoad = &InputLoad->getOperand(0); 8576 if (InputLoad->getOpcode() != ISD::LOAD) 8577 return nullptr; 8578 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8579 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 8580 } 8581 8582 // If this is a case we can't handle, return null and let the default 8583 // expansion code take care of it. If we CAN select this case, and if it 8584 // selects to a single instruction, return Op. Otherwise, if we can codegen 8585 // this case more efficiently than a constant pool load, lower it to the 8586 // sequence of ops that should be used. 8587 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 8588 SelectionDAG &DAG) const { 8589 SDLoc dl(Op); 8590 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8591 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 8592 8593 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { 8594 // We first build an i32 vector, load it into a QPX register, 8595 // then convert it to a floating-point vector and compare it 8596 // to a zero vector to get the boolean result. 8597 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 8598 int FrameIdx = MFI.CreateStackObject(16, 16, false); 8599 MachinePointerInfo PtrInfo = 8600 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8601 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8602 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8603 8604 assert(BVN->getNumOperands() == 4 && 8605 "BUILD_VECTOR for v4i1 does not have 4 operands"); 8606 8607 bool IsConst = true; 8608 for (unsigned i = 0; i < 4; ++i) { 8609 if (BVN->getOperand(i).isUndef()) continue; 8610 if (!isa<ConstantSDNode>(BVN->getOperand(i))) { 8611 IsConst = false; 8612 break; 8613 } 8614 } 8615 8616 if (IsConst) { 8617 Constant *One = 8618 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); 8619 Constant *NegOne = 8620 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); 8621 8622 Constant *CV[4]; 8623 for (unsigned i = 0; i < 4; ++i) { 8624 if (BVN->getOperand(i).isUndef()) 8625 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); 8626 else if (isNullConstant(BVN->getOperand(i))) 8627 CV[i] = NegOne; 8628 else 8629 CV[i] = One; 8630 } 8631 8632 Constant *CP = ConstantVector::get(CV); 8633 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 8634 16 /* alignment */); 8635 8636 SDValue Ops[] = {DAG.getEntryNode(), CPIdx}; 8637 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other}); 8638 return DAG.getMemIntrinsicNode( 8639 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, 8640 MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); 8641 } 8642 8643 SmallVector<SDValue, 4> Stores; 8644 for (unsigned i = 0; i < 4; ++i) { 8645 if (BVN->getOperand(i).isUndef()) continue; 8646 8647 unsigned Offset = 4*i; 8648 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 8649 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 8650 8651 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); 8652 if (StoreSize > 4) { 8653 Stores.push_back( 8654 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, 8655 PtrInfo.getWithOffset(Offset), MVT::i32)); 8656 } else { 8657 SDValue StoreValue = BVN->getOperand(i); 8658 if (StoreSize < 4) 8659 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); 8660 8661 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, 8662 PtrInfo.getWithOffset(Offset))); 8663 } 8664 } 8665 8666 SDValue StoreChain; 8667 if (!Stores.empty()) 8668 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 8669 else 8670 StoreChain = DAG.getEntryNode(); 8671 8672 // Now load from v4i32 into the QPX register; this will extend it to 8673 // v4i64 but not yet convert it to a floating point. Nevertheless, this 8674 // is typed as v4f64 because the QPX register integer states are not 8675 // explicitly represented. 8676 8677 SDValue Ops[] = {StoreChain, 8678 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32), 8679 FIdx}; 8680 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other}); 8681 8682 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, 8683 dl, VTs, Ops, MVT::v4i32, PtrInfo); 8684 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 8685 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), 8686 LoadedVect); 8687 8688 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64); 8689 8690 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); 8691 } 8692 8693 // All other QPX vectors are handled by generic code. 8694 if (Subtarget.hasQPX()) 8695 return SDValue(); 8696 8697 // Check if this is a splat of a constant value. 8698 APInt APSplatBits, APSplatUndef; 8699 unsigned SplatBitSize; 8700 bool HasAnyUndefs; 8701 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 8702 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 8703 SplatBitSize > 32) { 8704 8705 const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0)); 8706 // Handle load-and-splat patterns as we have instructions that will do this 8707 // in one go. 8708 if (InputLoad && DAG.isSplatValue(Op, true)) { 8709 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 8710 8711 // We have handling for 4 and 8 byte elements. 8712 unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits(); 8713 8714 // Checking for a single use of this load, we have to check for vector 8715 // width (128 bits) / ElementSize uses (since each operand of the 8716 // BUILD_VECTOR is a separate use of the value. 8717 if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) && 8718 ((Subtarget.hasVSX() && ElementSize == 64) || 8719 (Subtarget.hasP9Vector() && ElementSize == 32))) { 8720 SDValue Ops[] = { 8721 LD->getChain(), // Chain 8722 LD->getBasePtr(), // Ptr 8723 DAG.getValueType(Op.getValueType()) // VT 8724 }; 8725 return 8726 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, 8727 DAG.getVTList(Op.getValueType(), MVT::Other), 8728 Ops, LD->getMemoryVT(), LD->getMemOperand()); 8729 } 8730 } 8731 8732 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be 8733 // lowered to VSX instructions under certain conditions. 8734 // Without VSX, there is no pattern more efficient than expanding the node. 8735 if (Subtarget.hasVSX() && 8736 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 8737 Subtarget.hasP8Vector())) 8738 return Op; 8739 return SDValue(); 8740 } 8741 8742 unsigned SplatBits = APSplatBits.getZExtValue(); 8743 unsigned SplatUndef = APSplatUndef.getZExtValue(); 8744 unsigned SplatSize = SplatBitSize / 8; 8745 8746 // First, handle single instruction cases. 8747 8748 // All zeros? 8749 if (SplatBits == 0) { 8750 // Canonicalize all zero vectors to be v4i32. 8751 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 8752 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 8753 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 8754 } 8755 return Op; 8756 } 8757 8758 // We have XXSPLTIB for constant splats one byte wide 8759 // FIXME: SplatBits is an unsigned int being cast to an int while passing it 8760 // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here. 8761 if (Subtarget.hasP9Vector() && SplatSize == 1) 8762 return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl); 8763 8764 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 8765 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 8766 (32-SplatBitSize)); 8767 if (SextVal >= -16 && SextVal <= 15) 8768 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); 8769 8770 // Two instruction sequences. 8771 8772 // If this value is in the range [-32,30] and is even, use: 8773 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 8774 // If this value is in the range [17,31] and is odd, use: 8775 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 8776 // If this value is in the range [-31,-17] and is odd, use: 8777 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 8778 // Note the last two are three-instruction sequences. 8779 if (SextVal >= -32 && SextVal <= 31) { 8780 // To avoid having these optimizations undone by constant folding, 8781 // we convert to a pseudo that will be expanded later into one of 8782 // the above forms. 8783 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 8784 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 8785 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 8786 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 8787 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 8788 if (VT == Op.getValueType()) 8789 return RetVal; 8790 else 8791 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 8792 } 8793 8794 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 8795 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 8796 // for fneg/fabs. 8797 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 8798 // Make -1 and vspltisw -1: 8799 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); 8800 8801 // Make the VSLW intrinsic, computing 0x8000_0000. 8802 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 8803 OnesV, DAG, dl); 8804 8805 // xor by OnesV to invert it. 8806 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 8807 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8808 } 8809 8810 // Check to see if this is a wide variety of vsplti*, binop self cases. 8811 static const signed char SplatCsts[] = { 8812 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 8813 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 8814 }; 8815 8816 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { 8817 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 8818 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 8819 int i = SplatCsts[idx]; 8820 8821 // Figure out what shift amount will be used by altivec if shifted by i in 8822 // this splat size. 8823 unsigned TypeShiftAmt = i & (SplatBitSize-1); 8824 8825 // vsplti + shl self. 8826 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 8827 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8828 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8829 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 8830 Intrinsic::ppc_altivec_vslw 8831 }; 8832 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8833 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8834 } 8835 8836 // vsplti + srl self. 8837 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8838 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8839 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8840 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 8841 Intrinsic::ppc_altivec_vsrw 8842 }; 8843 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8844 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8845 } 8846 8847 // vsplti + sra self. 8848 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 8849 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8850 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8851 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, 8852 Intrinsic::ppc_altivec_vsraw 8853 }; 8854 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8855 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8856 } 8857 8858 // vsplti + rol self. 8859 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 8860 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 8861 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); 8862 static const unsigned IIDs[] = { // Intrinsic to use for each size. 8863 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 8864 Intrinsic::ppc_altivec_vrlw 8865 }; 8866 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 8867 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 8868 } 8869 8870 // t = vsplti c, result = vsldoi t, t, 1 8871 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 8872 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8873 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 8874 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8875 } 8876 // t = vsplti c, result = vsldoi t, t, 2 8877 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 8878 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8879 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 8880 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8881 } 8882 // t = vsplti c, result = vsldoi t, t, 3 8883 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 8884 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); 8885 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 8886 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 8887 } 8888 } 8889 8890 return SDValue(); 8891 } 8892 8893 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 8894 /// the specified operations to build the shuffle. 8895 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 8896 SDValue RHS, SelectionDAG &DAG, 8897 const SDLoc &dl) { 8898 unsigned OpNum = (PFEntry >> 26) & 0x0F; 8899 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 8900 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 8901 8902 enum { 8903 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 8904 OP_VMRGHW, 8905 OP_VMRGLW, 8906 OP_VSPLTISW0, 8907 OP_VSPLTISW1, 8908 OP_VSPLTISW2, 8909 OP_VSPLTISW3, 8910 OP_VSLDOI4, 8911 OP_VSLDOI8, 8912 OP_VSLDOI12 8913 }; 8914 8915 if (OpNum == OP_COPY) { 8916 if (LHSID == (1*9+2)*9+3) return LHS; 8917 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 8918 return RHS; 8919 } 8920 8921 SDValue OpLHS, OpRHS; 8922 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 8923 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 8924 8925 int ShufIdxs[16]; 8926 switch (OpNum) { 8927 default: llvm_unreachable("Unknown i32 permute!"); 8928 case OP_VMRGHW: 8929 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 8930 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 8931 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 8932 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 8933 break; 8934 case OP_VMRGLW: 8935 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 8936 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 8937 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 8938 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 8939 break; 8940 case OP_VSPLTISW0: 8941 for (unsigned i = 0; i != 16; ++i) 8942 ShufIdxs[i] = (i&3)+0; 8943 break; 8944 case OP_VSPLTISW1: 8945 for (unsigned i = 0; i != 16; ++i) 8946 ShufIdxs[i] = (i&3)+4; 8947 break; 8948 case OP_VSPLTISW2: 8949 for (unsigned i = 0; i != 16; ++i) 8950 ShufIdxs[i] = (i&3)+8; 8951 break; 8952 case OP_VSPLTISW3: 8953 for (unsigned i = 0; i != 16; ++i) 8954 ShufIdxs[i] = (i&3)+12; 8955 break; 8956 case OP_VSLDOI4: 8957 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 8958 case OP_VSLDOI8: 8959 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 8960 case OP_VSLDOI12: 8961 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 8962 } 8963 EVT VT = OpLHS.getValueType(); 8964 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 8965 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 8966 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 8967 return DAG.getNode(ISD::BITCAST, dl, VT, T); 8968 } 8969 8970 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 8971 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 8972 /// SDValue. 8973 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 8974 SelectionDAG &DAG) const { 8975 const unsigned BytesInVector = 16; 8976 bool IsLE = Subtarget.isLittleEndian(); 8977 SDLoc dl(N); 8978 SDValue V1 = N->getOperand(0); 8979 SDValue V2 = N->getOperand(1); 8980 unsigned ShiftElts = 0, InsertAtByte = 0; 8981 bool Swap = false; 8982 8983 // Shifts required to get the byte we want at element 7. 8984 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 8985 0, 15, 14, 13, 12, 11, 10, 9}; 8986 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 8987 1, 2, 3, 4, 5, 6, 7, 8}; 8988 8989 ArrayRef<int> Mask = N->getMask(); 8990 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 8991 8992 // For each mask element, find out if we're just inserting something 8993 // from V2 into V1 or vice versa. 8994 // Possible permutations inserting an element from V2 into V1: 8995 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8996 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 8997 // ... 8998 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 8999 // Inserting from V1 into V2 will be similar, except mask range will be 9000 // [16,31]. 9001 9002 bool FoundCandidate = false; 9003 // If both vector operands for the shuffle are the same vector, the mask 9004 // will contain only elements from the first one and the second one will be 9005 // undef. 9006 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9007 // Go through the mask of half-words to find an element that's being moved 9008 // from one vector to the other. 9009 for (unsigned i = 0; i < BytesInVector; ++i) { 9010 unsigned CurrentElement = Mask[i]; 9011 // If 2nd operand is undefined, we should only look for element 7 in the 9012 // Mask. 9013 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9014 continue; 9015 9016 bool OtherElementsInOrder = true; 9017 // Examine the other elements in the Mask to see if they're in original 9018 // order. 9019 for (unsigned j = 0; j < BytesInVector; ++j) { 9020 if (j == i) 9021 continue; 9022 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9023 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9024 // in which we always assume we're always picking from the 1st operand. 9025 int MaskOffset = 9026 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9027 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9028 OtherElementsInOrder = false; 9029 break; 9030 } 9031 } 9032 // If other elements are in original order, we record the number of shifts 9033 // we need to get the element we want into element 7. Also record which byte 9034 // in the vector we should insert into. 9035 if (OtherElementsInOrder) { 9036 // If 2nd operand is undefined, we assume no shifts and no swapping. 9037 if (V2.isUndef()) { 9038 ShiftElts = 0; 9039 Swap = false; 9040 } else { 9041 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9042 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9043 : BigEndianShifts[CurrentElement & 0xF]; 9044 Swap = CurrentElement < BytesInVector; 9045 } 9046 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9047 FoundCandidate = true; 9048 break; 9049 } 9050 } 9051 9052 if (!FoundCandidate) 9053 return SDValue(); 9054 9055 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9056 // optionally with VECSHL if shift is required. 9057 if (Swap) 9058 std::swap(V1, V2); 9059 if (V2.isUndef()) 9060 V2 = V1; 9061 if (ShiftElts) { 9062 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9063 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9064 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9065 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9066 } 9067 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9068 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9069 } 9070 9071 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9072 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9073 /// SDValue. 9074 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9075 SelectionDAG &DAG) const { 9076 const unsigned NumHalfWords = 8; 9077 const unsigned BytesInVector = NumHalfWords * 2; 9078 // Check that the shuffle is on half-words. 9079 if (!isNByteElemShuffleMask(N, 2, 1)) 9080 return SDValue(); 9081 9082 bool IsLE = Subtarget.isLittleEndian(); 9083 SDLoc dl(N); 9084 SDValue V1 = N->getOperand(0); 9085 SDValue V2 = N->getOperand(1); 9086 unsigned ShiftElts = 0, InsertAtByte = 0; 9087 bool Swap = false; 9088 9089 // Shifts required to get the half-word we want at element 3. 9090 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9091 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9092 9093 uint32_t Mask = 0; 9094 uint32_t OriginalOrderLow = 0x1234567; 9095 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9096 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9097 // 32-bit space, only need 4-bit nibbles per element. 9098 for (unsigned i = 0; i < NumHalfWords; ++i) { 9099 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9100 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9101 } 9102 9103 // For each mask element, find out if we're just inserting something 9104 // from V2 into V1 or vice versa. Possible permutations inserting an element 9105 // from V2 into V1: 9106 // X, 1, 2, 3, 4, 5, 6, 7 9107 // 0, X, 2, 3, 4, 5, 6, 7 9108 // 0, 1, X, 3, 4, 5, 6, 7 9109 // 0, 1, 2, X, 4, 5, 6, 7 9110 // 0, 1, 2, 3, X, 5, 6, 7 9111 // 0, 1, 2, 3, 4, X, 6, 7 9112 // 0, 1, 2, 3, 4, 5, X, 7 9113 // 0, 1, 2, 3, 4, 5, 6, X 9114 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9115 9116 bool FoundCandidate = false; 9117 // Go through the mask of half-words to find an element that's being moved 9118 // from one vector to the other. 9119 for (unsigned i = 0; i < NumHalfWords; ++i) { 9120 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9121 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9122 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9123 uint32_t TargetOrder = 0x0; 9124 9125 // If both vector operands for the shuffle are the same vector, the mask 9126 // will contain only elements from the first one and the second one will be 9127 // undef. 9128 if (V2.isUndef()) { 9129 ShiftElts = 0; 9130 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9131 TargetOrder = OriginalOrderLow; 9132 Swap = false; 9133 // Skip if not the correct element or mask of other elements don't equal 9134 // to our expected order. 9135 if (MaskOneElt == VINSERTHSrcElem && 9136 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9137 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9138 FoundCandidate = true; 9139 break; 9140 } 9141 } else { // If both operands are defined. 9142 // Target order is [8,15] if the current mask is between [0,7]. 9143 TargetOrder = 9144 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9145 // Skip if mask of other elements don't equal our expected order. 9146 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9147 // We only need the last 3 bits for the number of shifts. 9148 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9149 : BigEndianShifts[MaskOneElt & 0x7]; 9150 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9151 Swap = MaskOneElt < NumHalfWords; 9152 FoundCandidate = true; 9153 break; 9154 } 9155 } 9156 } 9157 9158 if (!FoundCandidate) 9159 return SDValue(); 9160 9161 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9162 // optionally with VECSHL if shift is required. 9163 if (Swap) 9164 std::swap(V1, V2); 9165 if (V2.isUndef()) 9166 V2 = V1; 9167 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9168 if (ShiftElts) { 9169 // Double ShiftElts because we're left shifting on v16i8 type. 9170 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9171 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9172 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9173 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9174 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9175 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9176 } 9177 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9178 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9179 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9180 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9181 } 9182 9183 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9184 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9185 /// return the code it can be lowered into. Worst case, it can always be 9186 /// lowered into a vperm. 9187 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9188 SelectionDAG &DAG) const { 9189 SDLoc dl(Op); 9190 SDValue V1 = Op.getOperand(0); 9191 SDValue V2 = Op.getOperand(1); 9192 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9193 EVT VT = Op.getValueType(); 9194 bool isLittleEndian = Subtarget.isLittleEndian(); 9195 9196 unsigned ShiftElts, InsertAtByte; 9197 bool Swap = false; 9198 9199 // If this is a load-and-splat, we can do that with a single instruction 9200 // in some cases. However if the load has multiple uses, we don't want to 9201 // combine it because that will just produce multiple loads. 9202 const SDValue *InputLoad = getNormalLoadInput(V1); 9203 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9204 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9205 InputLoad->hasOneUse()) { 9206 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9207 int SplatIdx = 9208 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9209 9210 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9211 // For 4-byte load-and-splat, we need Power9. 9212 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9213 uint64_t Offset = 0; 9214 if (IsFourByte) 9215 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9216 else 9217 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9218 SDValue BasePtr = LD->getBasePtr(); 9219 if (Offset != 0) 9220 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9221 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9222 SDValue Ops[] = { 9223 LD->getChain(), // Chain 9224 BasePtr, // BasePtr 9225 DAG.getValueType(Op.getValueType()) // VT 9226 }; 9227 SDVTList VTL = 9228 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9229 SDValue LdSplt = 9230 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9231 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9232 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9233 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9234 return LdSplt; 9235 } 9236 } 9237 if (Subtarget.hasP9Vector() && 9238 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9239 isLittleEndian)) { 9240 if (Swap) 9241 std::swap(V1, V2); 9242 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9243 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9244 if (ShiftElts) { 9245 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9246 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9247 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9248 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9249 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9250 } 9251 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9252 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9253 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9254 } 9255 9256 if (Subtarget.hasP9Altivec()) { 9257 SDValue NewISDNode; 9258 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9259 return NewISDNode; 9260 9261 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9262 return NewISDNode; 9263 } 9264 9265 if (Subtarget.hasVSX() && 9266 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9267 if (Swap) 9268 std::swap(V1, V2); 9269 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9270 SDValue Conv2 = 9271 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 9272 9273 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 9274 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9275 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 9276 } 9277 9278 if (Subtarget.hasVSX() && 9279 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 9280 if (Swap) 9281 std::swap(V1, V2); 9282 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9283 SDValue Conv2 = 9284 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 9285 9286 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 9287 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9288 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 9289 } 9290 9291 if (Subtarget.hasP9Vector()) { 9292 if (PPC::isXXBRHShuffleMask(SVOp)) { 9293 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9294 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 9295 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 9296 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 9297 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9298 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 9299 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 9300 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 9301 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 9302 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 9303 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 9304 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 9305 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 9306 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 9307 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 9308 } 9309 } 9310 9311 if (Subtarget.hasVSX()) { 9312 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 9313 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 9314 9315 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9316 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 9317 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9318 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 9319 } 9320 9321 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 9322 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 9323 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 9324 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 9325 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 9326 } 9327 } 9328 9329 if (Subtarget.hasQPX()) { 9330 if (VT.getVectorNumElements() != 4) 9331 return SDValue(); 9332 9333 if (V2.isUndef()) V2 = V1; 9334 9335 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); 9336 if (AlignIdx != -1) { 9337 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, 9338 DAG.getConstant(AlignIdx, dl, MVT::i32)); 9339 } else if (SVOp->isSplat()) { 9340 int SplatIdx = SVOp->getSplatIndex(); 9341 if (SplatIdx >= 4) { 9342 std::swap(V1, V2); 9343 SplatIdx -= 4; 9344 } 9345 9346 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, 9347 DAG.getConstant(SplatIdx, dl, MVT::i32)); 9348 } 9349 9350 // Lower this into a qvgpci/qvfperm pair. 9351 9352 // Compute the qvgpci literal 9353 unsigned idx = 0; 9354 for (unsigned i = 0; i < 4; ++i) { 9355 int m = SVOp->getMaskElt(i); 9356 unsigned mm = m >= 0 ? (unsigned) m : i; 9357 idx |= mm << (3-i)*3; 9358 } 9359 9360 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, 9361 DAG.getConstant(idx, dl, MVT::i32)); 9362 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); 9363 } 9364 9365 // Cases that are handled by instructions that take permute immediates 9366 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 9367 // selected by the instruction selector. 9368 if (V2.isUndef()) { 9369 if (PPC::isSplatShuffleMask(SVOp, 1) || 9370 PPC::isSplatShuffleMask(SVOp, 2) || 9371 PPC::isSplatShuffleMask(SVOp, 4) || 9372 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 9373 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 9374 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 9375 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 9376 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 9377 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 9378 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 9379 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 9380 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 9381 (Subtarget.hasP8Altivec() && ( 9382 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 9383 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 9384 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 9385 return Op; 9386 } 9387 } 9388 9389 // Altivec has a variety of "shuffle immediates" that take two vector inputs 9390 // and produce a fixed permutation. If any of these match, do not lower to 9391 // VPERM. 9392 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 9393 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 9394 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 9395 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 9396 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9397 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9398 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9399 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 9400 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 9401 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 9402 (Subtarget.hasP8Altivec() && ( 9403 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 9404 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 9405 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 9406 return Op; 9407 9408 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 9409 // perfect shuffle table to emit an optimal matching sequence. 9410 ArrayRef<int> PermMask = SVOp->getMask(); 9411 9412 unsigned PFIndexes[4]; 9413 bool isFourElementShuffle = true; 9414 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number 9415 unsigned EltNo = 8; // Start out undef. 9416 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 9417 if (PermMask[i*4+j] < 0) 9418 continue; // Undef, ignore it. 9419 9420 unsigned ByteSource = PermMask[i*4+j]; 9421 if ((ByteSource & 3) != j) { 9422 isFourElementShuffle = false; 9423 break; 9424 } 9425 9426 if (EltNo == 8) { 9427 EltNo = ByteSource/4; 9428 } else if (EltNo != ByteSource/4) { 9429 isFourElementShuffle = false; 9430 break; 9431 } 9432 } 9433 PFIndexes[i] = EltNo; 9434 } 9435 9436 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 9437 // perfect shuffle vector to determine if it is cost effective to do this as 9438 // discrete instructions, or whether we should use a vperm. 9439 // For now, we skip this for little endian until such time as we have a 9440 // little-endian perfect shuffle table. 9441 if (isFourElementShuffle && !isLittleEndian) { 9442 // Compute the index in the perfect shuffle table. 9443 unsigned PFTableIndex = 9444 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; 9445 9446 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 9447 unsigned Cost = (PFEntry >> 30); 9448 9449 // Determining when to avoid vperm is tricky. Many things affect the cost 9450 // of vperm, particularly how many times the perm mask needs to be computed. 9451 // For example, if the perm mask can be hoisted out of a loop or is already 9452 // used (perhaps because there are multiple permutes with the same shuffle 9453 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of 9454 // the loop requires an extra register. 9455 // 9456 // As a compromise, we only emit discrete instructions if the shuffle can be 9457 // generated in 3 or fewer operations. When we have loop information 9458 // available, if this block is within a loop, we should avoid using vperm 9459 // for 3-operation perms and use a constant pool load instead. 9460 if (Cost < 3) 9461 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 9462 } 9463 9464 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 9465 // vector that will get spilled to the constant pool. 9466 if (V2.isUndef()) V2 = V1; 9467 9468 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 9469 // that it is in input element units, not in bytes. Convert now. 9470 9471 // For little endian, the order of the input vectors is reversed, and 9472 // the permutation mask is complemented with respect to 31. This is 9473 // necessary to produce proper semantics with the big-endian-biased vperm 9474 // instruction. 9475 EVT EltVT = V1.getValueType().getVectorElementType(); 9476 unsigned BytesPerElement = EltVT.getSizeInBits()/8; 9477 9478 SmallVector<SDValue, 16> ResultMask; 9479 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 9480 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 9481 9482 for (unsigned j = 0; j != BytesPerElement; ++j) 9483 if (isLittleEndian) 9484 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), 9485 dl, MVT::i32)); 9486 else 9487 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, 9488 MVT::i32)); 9489 } 9490 9491 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 9492 if (isLittleEndian) 9493 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9494 V2, V1, VPermMask); 9495 else 9496 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), 9497 V1, V2, VPermMask); 9498 } 9499 9500 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 9501 /// vector comparison. If it is, return true and fill in Opc/isDot with 9502 /// information about the intrinsic. 9503 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 9504 bool &isDot, const PPCSubtarget &Subtarget) { 9505 unsigned IntrinsicID = 9506 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 9507 CompareOpc = -1; 9508 isDot = false; 9509 switch (IntrinsicID) { 9510 default: 9511 return false; 9512 // Comparison predicates. 9513 case Intrinsic::ppc_altivec_vcmpbfp_p: 9514 CompareOpc = 966; 9515 isDot = true; 9516 break; 9517 case Intrinsic::ppc_altivec_vcmpeqfp_p: 9518 CompareOpc = 198; 9519 isDot = true; 9520 break; 9521 case Intrinsic::ppc_altivec_vcmpequb_p: 9522 CompareOpc = 6; 9523 isDot = true; 9524 break; 9525 case Intrinsic::ppc_altivec_vcmpequh_p: 9526 CompareOpc = 70; 9527 isDot = true; 9528 break; 9529 case Intrinsic::ppc_altivec_vcmpequw_p: 9530 CompareOpc = 134; 9531 isDot = true; 9532 break; 9533 case Intrinsic::ppc_altivec_vcmpequd_p: 9534 if (Subtarget.hasP8Altivec()) { 9535 CompareOpc = 199; 9536 isDot = true; 9537 } else 9538 return false; 9539 break; 9540 case Intrinsic::ppc_altivec_vcmpneb_p: 9541 case Intrinsic::ppc_altivec_vcmpneh_p: 9542 case Intrinsic::ppc_altivec_vcmpnew_p: 9543 case Intrinsic::ppc_altivec_vcmpnezb_p: 9544 case Intrinsic::ppc_altivec_vcmpnezh_p: 9545 case Intrinsic::ppc_altivec_vcmpnezw_p: 9546 if (Subtarget.hasP9Altivec()) { 9547 switch (IntrinsicID) { 9548 default: 9549 llvm_unreachable("Unknown comparison intrinsic."); 9550 case Intrinsic::ppc_altivec_vcmpneb_p: 9551 CompareOpc = 7; 9552 break; 9553 case Intrinsic::ppc_altivec_vcmpneh_p: 9554 CompareOpc = 71; 9555 break; 9556 case Intrinsic::ppc_altivec_vcmpnew_p: 9557 CompareOpc = 135; 9558 break; 9559 case Intrinsic::ppc_altivec_vcmpnezb_p: 9560 CompareOpc = 263; 9561 break; 9562 case Intrinsic::ppc_altivec_vcmpnezh_p: 9563 CompareOpc = 327; 9564 break; 9565 case Intrinsic::ppc_altivec_vcmpnezw_p: 9566 CompareOpc = 391; 9567 break; 9568 } 9569 isDot = true; 9570 } else 9571 return false; 9572 break; 9573 case Intrinsic::ppc_altivec_vcmpgefp_p: 9574 CompareOpc = 454; 9575 isDot = true; 9576 break; 9577 case Intrinsic::ppc_altivec_vcmpgtfp_p: 9578 CompareOpc = 710; 9579 isDot = true; 9580 break; 9581 case Intrinsic::ppc_altivec_vcmpgtsb_p: 9582 CompareOpc = 774; 9583 isDot = true; 9584 break; 9585 case Intrinsic::ppc_altivec_vcmpgtsh_p: 9586 CompareOpc = 838; 9587 isDot = true; 9588 break; 9589 case Intrinsic::ppc_altivec_vcmpgtsw_p: 9590 CompareOpc = 902; 9591 isDot = true; 9592 break; 9593 case Intrinsic::ppc_altivec_vcmpgtsd_p: 9594 if (Subtarget.hasP8Altivec()) { 9595 CompareOpc = 967; 9596 isDot = true; 9597 } else 9598 return false; 9599 break; 9600 case Intrinsic::ppc_altivec_vcmpgtub_p: 9601 CompareOpc = 518; 9602 isDot = true; 9603 break; 9604 case Intrinsic::ppc_altivec_vcmpgtuh_p: 9605 CompareOpc = 582; 9606 isDot = true; 9607 break; 9608 case Intrinsic::ppc_altivec_vcmpgtuw_p: 9609 CompareOpc = 646; 9610 isDot = true; 9611 break; 9612 case Intrinsic::ppc_altivec_vcmpgtud_p: 9613 if (Subtarget.hasP8Altivec()) { 9614 CompareOpc = 711; 9615 isDot = true; 9616 } else 9617 return false; 9618 break; 9619 9620 // VSX predicate comparisons use the same infrastructure 9621 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9622 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9623 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9624 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9625 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9626 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9627 if (Subtarget.hasVSX()) { 9628 switch (IntrinsicID) { 9629 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 9630 CompareOpc = 99; 9631 break; 9632 case Intrinsic::ppc_vsx_xvcmpgedp_p: 9633 CompareOpc = 115; 9634 break; 9635 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 9636 CompareOpc = 107; 9637 break; 9638 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 9639 CompareOpc = 67; 9640 break; 9641 case Intrinsic::ppc_vsx_xvcmpgesp_p: 9642 CompareOpc = 83; 9643 break; 9644 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 9645 CompareOpc = 75; 9646 break; 9647 } 9648 isDot = true; 9649 } else 9650 return false; 9651 break; 9652 9653 // Normal Comparisons. 9654 case Intrinsic::ppc_altivec_vcmpbfp: 9655 CompareOpc = 966; 9656 break; 9657 case Intrinsic::ppc_altivec_vcmpeqfp: 9658 CompareOpc = 198; 9659 break; 9660 case Intrinsic::ppc_altivec_vcmpequb: 9661 CompareOpc = 6; 9662 break; 9663 case Intrinsic::ppc_altivec_vcmpequh: 9664 CompareOpc = 70; 9665 break; 9666 case Intrinsic::ppc_altivec_vcmpequw: 9667 CompareOpc = 134; 9668 break; 9669 case Intrinsic::ppc_altivec_vcmpequd: 9670 if (Subtarget.hasP8Altivec()) 9671 CompareOpc = 199; 9672 else 9673 return false; 9674 break; 9675 case Intrinsic::ppc_altivec_vcmpneb: 9676 case Intrinsic::ppc_altivec_vcmpneh: 9677 case Intrinsic::ppc_altivec_vcmpnew: 9678 case Intrinsic::ppc_altivec_vcmpnezb: 9679 case Intrinsic::ppc_altivec_vcmpnezh: 9680 case Intrinsic::ppc_altivec_vcmpnezw: 9681 if (Subtarget.hasP9Altivec()) 9682 switch (IntrinsicID) { 9683 default: 9684 llvm_unreachable("Unknown comparison intrinsic."); 9685 case Intrinsic::ppc_altivec_vcmpneb: 9686 CompareOpc = 7; 9687 break; 9688 case Intrinsic::ppc_altivec_vcmpneh: 9689 CompareOpc = 71; 9690 break; 9691 case Intrinsic::ppc_altivec_vcmpnew: 9692 CompareOpc = 135; 9693 break; 9694 case Intrinsic::ppc_altivec_vcmpnezb: 9695 CompareOpc = 263; 9696 break; 9697 case Intrinsic::ppc_altivec_vcmpnezh: 9698 CompareOpc = 327; 9699 break; 9700 case Intrinsic::ppc_altivec_vcmpnezw: 9701 CompareOpc = 391; 9702 break; 9703 } 9704 else 9705 return false; 9706 break; 9707 case Intrinsic::ppc_altivec_vcmpgefp: 9708 CompareOpc = 454; 9709 break; 9710 case Intrinsic::ppc_altivec_vcmpgtfp: 9711 CompareOpc = 710; 9712 break; 9713 case Intrinsic::ppc_altivec_vcmpgtsb: 9714 CompareOpc = 774; 9715 break; 9716 case Intrinsic::ppc_altivec_vcmpgtsh: 9717 CompareOpc = 838; 9718 break; 9719 case Intrinsic::ppc_altivec_vcmpgtsw: 9720 CompareOpc = 902; 9721 break; 9722 case Intrinsic::ppc_altivec_vcmpgtsd: 9723 if (Subtarget.hasP8Altivec()) 9724 CompareOpc = 967; 9725 else 9726 return false; 9727 break; 9728 case Intrinsic::ppc_altivec_vcmpgtub: 9729 CompareOpc = 518; 9730 break; 9731 case Intrinsic::ppc_altivec_vcmpgtuh: 9732 CompareOpc = 582; 9733 break; 9734 case Intrinsic::ppc_altivec_vcmpgtuw: 9735 CompareOpc = 646; 9736 break; 9737 case Intrinsic::ppc_altivec_vcmpgtud: 9738 if (Subtarget.hasP8Altivec()) 9739 CompareOpc = 711; 9740 else 9741 return false; 9742 break; 9743 } 9744 return true; 9745 } 9746 9747 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 9748 /// lower, do it, otherwise return null. 9749 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 9750 SelectionDAG &DAG) const { 9751 unsigned IntrinsicID = 9752 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9753 9754 SDLoc dl(Op); 9755 9756 if (IntrinsicID == Intrinsic::thread_pointer) { 9757 // Reads the thread pointer register, used for __builtin_thread_pointer. 9758 if (Subtarget.isPPC64()) 9759 return DAG.getRegister(PPC::X13, MVT::i64); 9760 return DAG.getRegister(PPC::R2, MVT::i32); 9761 } 9762 9763 // If this is a lowered altivec predicate compare, CompareOpc is set to the 9764 // opcode number of the comparison. 9765 int CompareOpc; 9766 bool isDot; 9767 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 9768 return SDValue(); // Don't custom lower most intrinsics. 9769 9770 // If this is a non-dot comparison, make the VCMP node and we are done. 9771 if (!isDot) { 9772 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 9773 Op.getOperand(1), Op.getOperand(2), 9774 DAG.getConstant(CompareOpc, dl, MVT::i32)); 9775 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 9776 } 9777 9778 // Create the PPCISD altivec 'dot' comparison node. 9779 SDValue Ops[] = { 9780 Op.getOperand(2), // LHS 9781 Op.getOperand(3), // RHS 9782 DAG.getConstant(CompareOpc, dl, MVT::i32) 9783 }; 9784 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 9785 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 9786 9787 // Now that we have the comparison, emit a copy from the CR to a GPR. 9788 // This is flagged to the above dot comparison. 9789 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 9790 DAG.getRegister(PPC::CR6, MVT::i32), 9791 CompNode.getValue(1)); 9792 9793 // Unpack the result based on how the target uses it. 9794 unsigned BitNo; // Bit # of CR6. 9795 bool InvertBit; // Invert result? 9796 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 9797 default: // Can't happen, don't crash on invalid number though. 9798 case 0: // Return the value of the EQ bit of CR6. 9799 BitNo = 0; InvertBit = false; 9800 break; 9801 case 1: // Return the inverted value of the EQ bit of CR6. 9802 BitNo = 0; InvertBit = true; 9803 break; 9804 case 2: // Return the value of the LT bit of CR6. 9805 BitNo = 2; InvertBit = false; 9806 break; 9807 case 3: // Return the inverted value of the LT bit of CR6. 9808 BitNo = 2; InvertBit = true; 9809 break; 9810 } 9811 9812 // Shift the bit into the low position. 9813 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 9814 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 9815 // Isolate the bit. 9816 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 9817 DAG.getConstant(1, dl, MVT::i32)); 9818 9819 // If we are supposed to, toggle the bit. 9820 if (InvertBit) 9821 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 9822 DAG.getConstant(1, dl, MVT::i32)); 9823 return Flags; 9824 } 9825 9826 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 9827 SelectionDAG &DAG) const { 9828 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 9829 // the beginning of the argument list. 9830 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 9831 SDLoc DL(Op); 9832 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 9833 case Intrinsic::ppc_cfence: { 9834 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 9835 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 9836 return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 9837 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, 9838 Op.getOperand(ArgStart + 1)), 9839 Op.getOperand(0)), 9840 0); 9841 } 9842 default: 9843 break; 9844 } 9845 return SDValue(); 9846 } 9847 9848 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const { 9849 // Check for a DIV with the same operands as this REM. 9850 for (auto UI : Op.getOperand(1)->uses()) { 9851 if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) || 9852 (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV)) 9853 if (UI->getOperand(0) == Op.getOperand(0) && 9854 UI->getOperand(1) == Op.getOperand(1)) 9855 return SDValue(); 9856 } 9857 return Op; 9858 } 9859 9860 // Lower scalar BSWAP64 to xxbrd. 9861 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 9862 SDLoc dl(Op); 9863 // MTVSRDD 9864 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 9865 Op.getOperand(0)); 9866 // XXBRD 9867 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 9868 // MFVSRD 9869 int VectorIndex = 0; 9870 if (Subtarget.isLittleEndian()) 9871 VectorIndex = 1; 9872 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 9873 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 9874 return Op; 9875 } 9876 9877 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 9878 // compared to a value that is atomically loaded (atomic loads zero-extend). 9879 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 9880 SelectionDAG &DAG) const { 9881 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 9882 "Expecting an atomic compare-and-swap here."); 9883 SDLoc dl(Op); 9884 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 9885 EVT MemVT = AtomicNode->getMemoryVT(); 9886 if (MemVT.getSizeInBits() >= 32) 9887 return Op; 9888 9889 SDValue CmpOp = Op.getOperand(2); 9890 // If this is already correctly zero-extended, leave it alone. 9891 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 9892 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 9893 return Op; 9894 9895 // Clear the high bits of the compare operand. 9896 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 9897 SDValue NewCmpOp = 9898 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 9899 DAG.getConstant(MaskVal, dl, MVT::i32)); 9900 9901 // Replace the existing compare operand with the properly zero-extended one. 9902 SmallVector<SDValue, 4> Ops; 9903 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 9904 Ops.push_back(AtomicNode->getOperand(i)); 9905 Ops[2] = NewCmpOp; 9906 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 9907 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 9908 auto NodeTy = 9909 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 9910 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 9911 } 9912 9913 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 9914 SelectionDAG &DAG) const { 9915 SDLoc dl(Op); 9916 // Create a stack slot that is 16-byte aligned. 9917 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9918 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9919 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9920 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9921 9922 // Store the input value into Value#0 of the stack slot. 9923 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 9924 MachinePointerInfo()); 9925 // Load it out. 9926 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 9927 } 9928 9929 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 9930 SelectionDAG &DAG) const { 9931 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 9932 "Should only be called for ISD::INSERT_VECTOR_ELT"); 9933 9934 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 9935 // We have legal lowering for constant indices but not for variable ones. 9936 if (!C) 9937 return SDValue(); 9938 9939 EVT VT = Op.getValueType(); 9940 SDLoc dl(Op); 9941 SDValue V1 = Op.getOperand(0); 9942 SDValue V2 = Op.getOperand(1); 9943 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 9944 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 9945 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 9946 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 9947 unsigned InsertAtElement = C->getZExtValue(); 9948 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 9949 if (Subtarget.isLittleEndian()) { 9950 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 9951 } 9952 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 9953 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9954 } 9955 return Op; 9956 } 9957 9958 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 9959 SelectionDAG &DAG) const { 9960 SDLoc dl(Op); 9961 SDNode *N = Op.getNode(); 9962 9963 assert(N->getOperand(0).getValueType() == MVT::v4i1 && 9964 "Unknown extract_vector_elt type"); 9965 9966 SDValue Value = N->getOperand(0); 9967 9968 // The first part of this is like the store lowering except that we don't 9969 // need to track the chain. 9970 9971 // The values are now known to be -1 (false) or 1 (true). To convert this 9972 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 9973 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 9974 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 9975 9976 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 9977 // understand how to form the extending load. 9978 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 9979 9980 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 9981 9982 // Now convert to an integer and store. 9983 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 9984 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 9985 Value); 9986 9987 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 9988 int FrameIdx = MFI.CreateStackObject(16, 16, false); 9989 MachinePointerInfo PtrInfo = 9990 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 9991 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 9992 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 9993 9994 SDValue StoreChain = DAG.getEntryNode(); 9995 SDValue Ops[] = {StoreChain, 9996 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 9997 Value, FIdx}; 9998 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 9999 10000 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10001 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10002 10003 // Extract the value requested. 10004 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10005 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10006 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10007 10008 SDValue IntVal = 10009 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset)); 10010 10011 if (!Subtarget.useCRBits()) 10012 return IntVal; 10013 10014 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); 10015 } 10016 10017 /// Lowering for QPX v4i1 loads 10018 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 10019 SelectionDAG &DAG) const { 10020 SDLoc dl(Op); 10021 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 10022 SDValue LoadChain = LN->getChain(); 10023 SDValue BasePtr = LN->getBasePtr(); 10024 10025 if (Op.getValueType() == MVT::v4f64 || 10026 Op.getValueType() == MVT::v4f32) { 10027 EVT MemVT = LN->getMemoryVT(); 10028 unsigned Alignment = LN->getAlignment(); 10029 10030 // If this load is properly aligned, then it is legal. 10031 if (Alignment >= MemVT.getStoreSize()) 10032 return Op; 10033 10034 EVT ScalarVT = Op.getValueType().getScalarType(), 10035 ScalarMemVT = MemVT.getScalarType(); 10036 unsigned Stride = ScalarMemVT.getStoreSize(); 10037 10038 SDValue Vals[4], LoadChains[4]; 10039 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10040 SDValue Load; 10041 if (ScalarVT != ScalarMemVT) 10042 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, 10043 BasePtr, 10044 LN->getPointerInfo().getWithOffset(Idx * Stride), 10045 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10046 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10047 else 10048 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, 10049 LN->getPointerInfo().getWithOffset(Idx * Stride), 10050 MinAlign(Alignment, Idx * Stride), 10051 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10052 10053 if (Idx == 0 && LN->isIndexed()) { 10054 assert(LN->getAddressingMode() == ISD::PRE_INC && 10055 "Unknown addressing mode on vector load"); 10056 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), 10057 LN->getAddressingMode()); 10058 } 10059 10060 Vals[Idx] = Load; 10061 LoadChains[Idx] = Load.getValue(1); 10062 10063 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10064 DAG.getConstant(Stride, dl, 10065 BasePtr.getValueType())); 10066 } 10067 10068 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10069 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals); 10070 10071 if (LN->isIndexed()) { 10072 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; 10073 return DAG.getMergeValues(RetOps, dl); 10074 } 10075 10076 SDValue RetOps[] = { Value, TF }; 10077 return DAG.getMergeValues(RetOps, dl); 10078 } 10079 10080 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); 10081 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); 10082 10083 // To lower v4i1 from a byte array, we load the byte elements of the 10084 // vector and then reuse the BUILD_VECTOR logic. 10085 10086 SDValue VectElmts[4], VectElmtChains[4]; 10087 for (unsigned i = 0; i < 4; ++i) { 10088 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10089 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10090 10091 VectElmts[i] = DAG.getExtLoad( 10092 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, 10093 LN->getPointerInfo().getWithOffset(i), MVT::i8, 10094 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo()); 10095 VectElmtChains[i] = VectElmts[i].getValue(1); 10096 } 10097 10098 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); 10099 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts); 10100 10101 SDValue RVals[] = { Value, LoadChain }; 10102 return DAG.getMergeValues(RVals, dl); 10103 } 10104 10105 /// Lowering for QPX v4i1 stores 10106 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 10107 SelectionDAG &DAG) const { 10108 SDLoc dl(Op); 10109 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 10110 SDValue StoreChain = SN->getChain(); 10111 SDValue BasePtr = SN->getBasePtr(); 10112 SDValue Value = SN->getValue(); 10113 10114 if (Value.getValueType() == MVT::v4f64 || 10115 Value.getValueType() == MVT::v4f32) { 10116 EVT MemVT = SN->getMemoryVT(); 10117 unsigned Alignment = SN->getAlignment(); 10118 10119 // If this store is properly aligned, then it is legal. 10120 if (Alignment >= MemVT.getStoreSize()) 10121 return Op; 10122 10123 EVT ScalarVT = Value.getValueType().getScalarType(), 10124 ScalarMemVT = MemVT.getScalarType(); 10125 unsigned Stride = ScalarMemVT.getStoreSize(); 10126 10127 SDValue Stores[4]; 10128 for (unsigned Idx = 0; Idx < 4; ++Idx) { 10129 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, 10130 DAG.getVectorIdxConstant(Idx, dl)); 10131 SDValue Store; 10132 if (ScalarVT != ScalarMemVT) 10133 Store = 10134 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, 10135 SN->getPointerInfo().getWithOffset(Idx * Stride), 10136 ScalarMemVT, MinAlign(Alignment, Idx * Stride), 10137 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10138 else 10139 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, 10140 SN->getPointerInfo().getWithOffset(Idx * Stride), 10141 MinAlign(Alignment, Idx * Stride), 10142 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 10143 10144 if (Idx == 0 && SN->isIndexed()) { 10145 assert(SN->getAddressingMode() == ISD::PRE_INC && 10146 "Unknown addressing mode on vector store"); 10147 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), 10148 SN->getAddressingMode()); 10149 } 10150 10151 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 10152 DAG.getConstant(Stride, dl, 10153 BasePtr.getValueType())); 10154 Stores[Idx] = Store; 10155 } 10156 10157 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10158 10159 if (SN->isIndexed()) { 10160 SDValue RetOps[] = { TF, Stores[0].getValue(1) }; 10161 return DAG.getMergeValues(RetOps, dl); 10162 } 10163 10164 return TF; 10165 } 10166 10167 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); 10168 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); 10169 10170 // The values are now known to be -1 (false) or 1 (true). To convert this 10171 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). 10172 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 10173 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); 10174 10175 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to 10176 // understand how to form the extending load. 10177 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64); 10178 10179 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 10180 10181 // Now convert to an integer and store. 10182 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, 10183 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), 10184 Value); 10185 10186 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10187 int FrameIdx = MFI.CreateStackObject(16, 16, false); 10188 MachinePointerInfo PtrInfo = 10189 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 10190 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10191 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10192 10193 SDValue Ops[] = {StoreChain, 10194 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32), 10195 Value, FIdx}; 10196 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other); 10197 10198 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, 10199 dl, VTs, Ops, MVT::v4i32, PtrInfo); 10200 10201 // Move data into the byte array. 10202 SDValue Loads[4], LoadChains[4]; 10203 for (unsigned i = 0; i < 4; ++i) { 10204 unsigned Offset = 4*i; 10205 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); 10206 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); 10207 10208 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, 10209 PtrInfo.getWithOffset(Offset)); 10210 LoadChains[i] = Loads[i].getValue(1); 10211 } 10212 10213 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 10214 10215 SDValue Stores[4]; 10216 for (unsigned i = 0; i < 4; ++i) { 10217 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); 10218 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); 10219 10220 Stores[i] = DAG.getTruncStore( 10221 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), 10222 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(), 10223 SN->getAAInfo()); 10224 } 10225 10226 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 10227 10228 return StoreChain; 10229 } 10230 10231 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 10232 SDLoc dl(Op); 10233 if (Op.getValueType() == MVT::v4i32) { 10234 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10235 10236 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); 10237 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. 10238 10239 SDValue RHSSwap = // = vrlw RHS, 16 10240 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 10241 10242 // Shrinkify inputs to v8i16. 10243 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 10244 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 10245 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 10246 10247 // Low parts multiplied together, generating 32-bit results (we ignore the 10248 // top parts). 10249 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 10250 LHS, RHS, DAG, dl, MVT::v4i32); 10251 10252 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 10253 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 10254 // Shift the high parts up 16 bits. 10255 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 10256 Neg16, DAG, dl); 10257 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 10258 } else if (Op.getValueType() == MVT::v8i16) { 10259 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10260 10261 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); 10262 10263 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, 10264 LHS, RHS, Zero, DAG, dl); 10265 } else if (Op.getValueType() == MVT::v16i8) { 10266 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 10267 bool isLittleEndian = Subtarget.isLittleEndian(); 10268 10269 // Multiply the even 8-bit parts, producing 16-bit sums. 10270 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 10271 LHS, RHS, DAG, dl, MVT::v8i16); 10272 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 10273 10274 // Multiply the odd 8-bit parts, producing 16-bit sums. 10275 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 10276 LHS, RHS, DAG, dl, MVT::v8i16); 10277 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 10278 10279 // Merge the results together. Because vmuleub and vmuloub are 10280 // instructions with a big-endian bias, we must reverse the 10281 // element numbering and reverse the meaning of "odd" and "even" 10282 // when generating little endian code. 10283 int Ops[16]; 10284 for (unsigned i = 0; i != 8; ++i) { 10285 if (isLittleEndian) { 10286 Ops[i*2 ] = 2*i; 10287 Ops[i*2+1] = 2*i+16; 10288 } else { 10289 Ops[i*2 ] = 2*i+1; 10290 Ops[i*2+1] = 2*i+1+16; 10291 } 10292 } 10293 if (isLittleEndian) 10294 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 10295 else 10296 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 10297 } else { 10298 llvm_unreachable("Unknown mul to lower!"); 10299 } 10300 } 10301 10302 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const { 10303 10304 assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS"); 10305 10306 EVT VT = Op.getValueType(); 10307 assert(VT.isVector() && 10308 "Only set vector abs as custom, scalar abs shouldn't reach here!"); 10309 assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 || 10310 VT == MVT::v16i8) && 10311 "Unexpected vector element type!"); 10312 assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) && 10313 "Current subtarget doesn't support smax v2i64!"); 10314 10315 // For vector abs, it can be lowered to: 10316 // abs x 10317 // ==> 10318 // y = -x 10319 // smax(x, y) 10320 10321 SDLoc dl(Op); 10322 SDValue X = Op.getOperand(0); 10323 SDValue Zero = DAG.getConstant(0, dl, VT); 10324 SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X); 10325 10326 // SMAX patch https://reviews.llvm.org/D47332 10327 // hasn't landed yet, so use intrinsic first here. 10328 // TODO: Should use SMAX directly once SMAX patch landed 10329 Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw; 10330 if (VT == MVT::v2i64) 10331 BifID = Intrinsic::ppc_altivec_vmaxsd; 10332 else if (VT == MVT::v8i16) 10333 BifID = Intrinsic::ppc_altivec_vmaxsh; 10334 else if (VT == MVT::v16i8) 10335 BifID = Intrinsic::ppc_altivec_vmaxsb; 10336 10337 return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT); 10338 } 10339 10340 // Custom lowering for fpext vf32 to v2f64 10341 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 10342 10343 assert(Op.getOpcode() == ISD::FP_EXTEND && 10344 "Should only be called for ISD::FP_EXTEND"); 10345 10346 // We only want to custom lower an extend from v2f32 to v2f64. 10347 if (Op.getValueType() != MVT::v2f64 || 10348 Op.getOperand(0).getValueType() != MVT::v2f32) 10349 return SDValue(); 10350 10351 SDLoc dl(Op); 10352 SDValue Op0 = Op.getOperand(0); 10353 10354 switch (Op0.getOpcode()) { 10355 default: 10356 return SDValue(); 10357 case ISD::EXTRACT_SUBVECTOR: { 10358 assert(Op0.getNumOperands() == 2 && 10359 isa<ConstantSDNode>(Op0->getOperand(1)) && 10360 "Node should have 2 operands with second one being a constant!"); 10361 10362 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 10363 return SDValue(); 10364 10365 // Custom lower is only done for high or low doubleword. 10366 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 10367 if (Idx % 2 != 0) 10368 return SDValue(); 10369 10370 // Since input is v4f32, at this point Idx is either 0 or 2. 10371 // Shift to get the doubleword position we want. 10372 int DWord = Idx >> 1; 10373 10374 // High and low word positions are different on little endian. 10375 if (Subtarget.isLittleEndian()) 10376 DWord ^= 0x1; 10377 10378 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 10379 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 10380 } 10381 case ISD::FADD: 10382 case ISD::FMUL: 10383 case ISD::FSUB: { 10384 SDValue NewLoad[2]; 10385 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 10386 // Ensure both input are loads. 10387 SDValue LdOp = Op0.getOperand(i); 10388 if (LdOp.getOpcode() != ISD::LOAD) 10389 return SDValue(); 10390 // Generate new load node. 10391 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 10392 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10393 NewLoad[i] = DAG.getMemIntrinsicNode( 10394 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10395 LD->getMemoryVT(), LD->getMemOperand()); 10396 } 10397 SDValue NewOp = 10398 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 10399 NewLoad[1], Op0.getNode()->getFlags()); 10400 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 10401 DAG.getConstant(0, dl, MVT::i32)); 10402 } 10403 case ISD::LOAD: { 10404 LoadSDNode *LD = cast<LoadSDNode>(Op0); 10405 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 10406 SDValue NewLd = DAG.getMemIntrinsicNode( 10407 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 10408 LD->getMemoryVT(), LD->getMemOperand()); 10409 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 10410 DAG.getConstant(0, dl, MVT::i32)); 10411 } 10412 } 10413 llvm_unreachable("ERROR:Should return for all cases within swtich."); 10414 } 10415 10416 /// LowerOperation - Provide custom lowering hooks for some operations. 10417 /// 10418 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 10419 switch (Op.getOpcode()) { 10420 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 10421 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 10422 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 10423 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 10424 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 10425 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 10426 case ISD::SETCC: return LowerSETCC(Op, DAG); 10427 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 10428 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 10429 10430 // Variable argument lowering. 10431 case ISD::VASTART: return LowerVASTART(Op, DAG); 10432 case ISD::VAARG: return LowerVAARG(Op, DAG); 10433 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 10434 10435 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 10436 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 10437 case ISD::GET_DYNAMIC_AREA_OFFSET: 10438 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 10439 10440 // Exception handling lowering. 10441 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 10442 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 10443 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 10444 10445 case ISD::LOAD: return LowerLOAD(Op, DAG); 10446 case ISD::STORE: return LowerSTORE(Op, DAG); 10447 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 10448 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 10449 case ISD::FP_TO_UINT: 10450 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 10451 case ISD::UINT_TO_FP: 10452 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 10453 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); 10454 10455 // Lower 64-bit shifts. 10456 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 10457 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 10458 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 10459 10460 // Vector-related lowering. 10461 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 10462 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 10463 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 10464 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 10465 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); 10466 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 10467 case ISD::MUL: return LowerMUL(Op, DAG); 10468 case ISD::ABS: return LowerABS(Op, DAG); 10469 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 10470 10471 // For counter-based loop handling. 10472 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 10473 10474 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 10475 10476 // Frame & Return address. 10477 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 10478 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 10479 10480 case ISD::INTRINSIC_VOID: 10481 return LowerINTRINSIC_VOID(Op, DAG); 10482 case ISD::SREM: 10483 case ISD::UREM: 10484 return LowerREM(Op, DAG); 10485 case ISD::BSWAP: 10486 return LowerBSWAP(Op, DAG); 10487 case ISD::ATOMIC_CMP_SWAP: 10488 return LowerATOMIC_CMP_SWAP(Op, DAG); 10489 } 10490 } 10491 10492 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 10493 SmallVectorImpl<SDValue>&Results, 10494 SelectionDAG &DAG) const { 10495 SDLoc dl(N); 10496 switch (N->getOpcode()) { 10497 default: 10498 llvm_unreachable("Do not know how to custom type legalize this operation!"); 10499 case ISD::READCYCLECOUNTER: { 10500 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 10501 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 10502 10503 Results.push_back( 10504 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 10505 Results.push_back(RTB.getValue(2)); 10506 break; 10507 } 10508 case ISD::INTRINSIC_W_CHAIN: { 10509 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 10510 Intrinsic::loop_decrement) 10511 break; 10512 10513 assert(N->getValueType(0) == MVT::i1 && 10514 "Unexpected result type for CTR decrement intrinsic"); 10515 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 10516 N->getValueType(0)); 10517 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 10518 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 10519 N->getOperand(1)); 10520 10521 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 10522 Results.push_back(NewInt.getValue(1)); 10523 break; 10524 } 10525 case ISD::VAARG: { 10526 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 10527 return; 10528 10529 EVT VT = N->getValueType(0); 10530 10531 if (VT == MVT::i64) { 10532 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 10533 10534 Results.push_back(NewNode); 10535 Results.push_back(NewNode.getValue(1)); 10536 } 10537 return; 10538 } 10539 case ISD::FP_TO_SINT: 10540 case ISD::FP_TO_UINT: 10541 // LowerFP_TO_INT() can only handle f32 and f64. 10542 if (N->getOperand(0).getValueType() == MVT::ppcf128) 10543 return; 10544 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); 10545 return; 10546 case ISD::TRUNCATE: { 10547 EVT TrgVT = N->getValueType(0); 10548 EVT OpVT = N->getOperand(0).getValueType(); 10549 if (TrgVT.isVector() && 10550 isOperationCustom(N->getOpcode(), TrgVT) && 10551 OpVT.getSizeInBits() <= 128 && 10552 isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits())) 10553 Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG)); 10554 return; 10555 } 10556 case ISD::BITCAST: 10557 // Don't handle bitcast here. 10558 return; 10559 } 10560 } 10561 10562 //===----------------------------------------------------------------------===// 10563 // Other Lowering Code 10564 //===----------------------------------------------------------------------===// 10565 10566 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { 10567 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10568 Function *Func = Intrinsic::getDeclaration(M, Id); 10569 return Builder.CreateCall(Func, {}); 10570 } 10571 10572 // The mappings for emitLeading/TrailingFence is taken from 10573 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 10574 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, 10575 Instruction *Inst, 10576 AtomicOrdering Ord) const { 10577 if (Ord == AtomicOrdering::SequentiallyConsistent) 10578 return callIntrinsic(Builder, Intrinsic::ppc_sync); 10579 if (isReleaseOrStronger(Ord)) 10580 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10581 return nullptr; 10582 } 10583 10584 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, 10585 Instruction *Inst, 10586 AtomicOrdering Ord) const { 10587 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 10588 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 10589 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 10590 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 10591 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 10592 return Builder.CreateCall( 10593 Intrinsic::getDeclaration( 10594 Builder.GetInsertBlock()->getParent()->getParent(), 10595 Intrinsic::ppc_cfence, {Inst->getType()}), 10596 {Inst}); 10597 // FIXME: Can use isync for rmw operation. 10598 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 10599 } 10600 return nullptr; 10601 } 10602 10603 MachineBasicBlock * 10604 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 10605 unsigned AtomicSize, 10606 unsigned BinOpcode, 10607 unsigned CmpOpcode, 10608 unsigned CmpPred) const { 10609 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10610 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10611 10612 auto LoadMnemonic = PPC::LDARX; 10613 auto StoreMnemonic = PPC::STDCX; 10614 switch (AtomicSize) { 10615 default: 10616 llvm_unreachable("Unexpected size of atomic entity"); 10617 case 1: 10618 LoadMnemonic = PPC::LBARX; 10619 StoreMnemonic = PPC::STBCX; 10620 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10621 break; 10622 case 2: 10623 LoadMnemonic = PPC::LHARX; 10624 StoreMnemonic = PPC::STHCX; 10625 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 10626 break; 10627 case 4: 10628 LoadMnemonic = PPC::LWARX; 10629 StoreMnemonic = PPC::STWCX; 10630 break; 10631 case 8: 10632 LoadMnemonic = PPC::LDARX; 10633 StoreMnemonic = PPC::STDCX; 10634 break; 10635 } 10636 10637 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10638 MachineFunction *F = BB->getParent(); 10639 MachineFunction::iterator It = ++BB->getIterator(); 10640 10641 Register dest = MI.getOperand(0).getReg(); 10642 Register ptrA = MI.getOperand(1).getReg(); 10643 Register ptrB = MI.getOperand(2).getReg(); 10644 Register incr = MI.getOperand(3).getReg(); 10645 DebugLoc dl = MI.getDebugLoc(); 10646 10647 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10648 MachineBasicBlock *loop2MBB = 10649 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10650 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10651 F->insert(It, loopMBB); 10652 if (CmpOpcode) 10653 F->insert(It, loop2MBB); 10654 F->insert(It, exitMBB); 10655 exitMBB->splice(exitMBB->begin(), BB, 10656 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10657 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10658 10659 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10660 Register TmpReg = (!BinOpcode) ? incr : 10661 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 10662 : &PPC::GPRCRegClass); 10663 10664 // thisMBB: 10665 // ... 10666 // fallthrough --> loopMBB 10667 BB->addSuccessor(loopMBB); 10668 10669 // loopMBB: 10670 // l[wd]arx dest, ptr 10671 // add r0, dest, incr 10672 // st[wd]cx. r0, ptr 10673 // bne- loopMBB 10674 // fallthrough --> exitMBB 10675 10676 // For max/min... 10677 // loopMBB: 10678 // l[wd]arx dest, ptr 10679 // cmpl?[wd] incr, dest 10680 // bgt exitMBB 10681 // loop2MBB: 10682 // st[wd]cx. dest, ptr 10683 // bne- loopMBB 10684 // fallthrough --> exitMBB 10685 10686 BB = loopMBB; 10687 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 10688 .addReg(ptrA).addReg(ptrB); 10689 if (BinOpcode) 10690 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 10691 if (CmpOpcode) { 10692 // Signed comparisons of byte or halfword values must be sign-extended. 10693 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 10694 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 10695 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 10696 ExtReg).addReg(dest); 10697 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10698 .addReg(incr).addReg(ExtReg); 10699 } else 10700 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10701 .addReg(incr).addReg(dest); 10702 10703 BuildMI(BB, dl, TII->get(PPC::BCC)) 10704 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB); 10705 BB->addSuccessor(loop2MBB); 10706 BB->addSuccessor(exitMBB); 10707 BB = loop2MBB; 10708 } 10709 BuildMI(BB, dl, TII->get(StoreMnemonic)) 10710 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 10711 BuildMI(BB, dl, TII->get(PPC::BCC)) 10712 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 10713 BB->addSuccessor(loopMBB); 10714 BB->addSuccessor(exitMBB); 10715 10716 // exitMBB: 10717 // ... 10718 BB = exitMBB; 10719 return BB; 10720 } 10721 10722 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 10723 MachineInstr &MI, MachineBasicBlock *BB, 10724 bool is8bit, // operation 10725 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 10726 // If we support part-word atomic mnemonics, just use them 10727 if (Subtarget.hasPartwordAtomics()) 10728 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 10729 CmpPred); 10730 10731 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 10732 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10733 // In 64 bit mode we have to use 64 bits for addresses, even though the 10734 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 10735 // registers without caring whether they're 32 or 64, but here we're 10736 // doing actual arithmetic on the addresses. 10737 bool is64bit = Subtarget.isPPC64(); 10738 bool isLittleEndian = Subtarget.isLittleEndian(); 10739 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 10740 10741 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10742 MachineFunction *F = BB->getParent(); 10743 MachineFunction::iterator It = ++BB->getIterator(); 10744 10745 Register dest = MI.getOperand(0).getReg(); 10746 Register ptrA = MI.getOperand(1).getReg(); 10747 Register ptrB = MI.getOperand(2).getReg(); 10748 Register incr = MI.getOperand(3).getReg(); 10749 DebugLoc dl = MI.getDebugLoc(); 10750 10751 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 10752 MachineBasicBlock *loop2MBB = 10753 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 10754 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 10755 F->insert(It, loopMBB); 10756 if (CmpOpcode) 10757 F->insert(It, loop2MBB); 10758 F->insert(It, exitMBB); 10759 exitMBB->splice(exitMBB->begin(), BB, 10760 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 10761 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 10762 10763 MachineRegisterInfo &RegInfo = F->getRegInfo(); 10764 const TargetRegisterClass *RC = 10765 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 10766 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 10767 10768 Register PtrReg = RegInfo.createVirtualRegister(RC); 10769 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 10770 Register ShiftReg = 10771 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 10772 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 10773 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 10774 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 10775 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 10776 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 10777 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 10778 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 10779 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 10780 Register Ptr1Reg; 10781 Register TmpReg = 10782 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 10783 10784 // thisMBB: 10785 // ... 10786 // fallthrough --> loopMBB 10787 BB->addSuccessor(loopMBB); 10788 10789 // The 4-byte load must be aligned, while a char or short may be 10790 // anywhere in the word. Hence all this nasty bookkeeping code. 10791 // add ptr1, ptrA, ptrB [copy if ptrA==0] 10792 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 10793 // xori shift, shift1, 24 [16] 10794 // rlwinm ptr, ptr1, 0, 0, 29 10795 // slw incr2, incr, shift 10796 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 10797 // slw mask, mask2, shift 10798 // loopMBB: 10799 // lwarx tmpDest, ptr 10800 // add tmp, tmpDest, incr2 10801 // andc tmp2, tmpDest, mask 10802 // and tmp3, tmp, mask 10803 // or tmp4, tmp3, tmp2 10804 // stwcx. tmp4, ptr 10805 // bne- loopMBB 10806 // fallthrough --> exitMBB 10807 // srw dest, tmpDest, shift 10808 if (ptrA != ZeroReg) { 10809 Ptr1Reg = RegInfo.createVirtualRegister(RC); 10810 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 10811 .addReg(ptrA) 10812 .addReg(ptrB); 10813 } else { 10814 Ptr1Reg = ptrB; 10815 } 10816 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 10817 // mode. 10818 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 10819 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 10820 .addImm(3) 10821 .addImm(27) 10822 .addImm(is8bit ? 28 : 27); 10823 if (!isLittleEndian) 10824 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 10825 .addReg(Shift1Reg) 10826 .addImm(is8bit ? 24 : 16); 10827 if (is64bit) 10828 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 10829 .addReg(Ptr1Reg) 10830 .addImm(0) 10831 .addImm(61); 10832 else 10833 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 10834 .addReg(Ptr1Reg) 10835 .addImm(0) 10836 .addImm(0) 10837 .addImm(29); 10838 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 10839 if (is8bit) 10840 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 10841 else { 10842 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 10843 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 10844 .addReg(Mask3Reg) 10845 .addImm(65535); 10846 } 10847 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 10848 .addReg(Mask2Reg) 10849 .addReg(ShiftReg); 10850 10851 BB = loopMBB; 10852 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 10853 .addReg(ZeroReg) 10854 .addReg(PtrReg); 10855 if (BinOpcode) 10856 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 10857 .addReg(Incr2Reg) 10858 .addReg(TmpDestReg); 10859 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 10860 .addReg(TmpDestReg) 10861 .addReg(MaskReg); 10862 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 10863 if (CmpOpcode) { 10864 // For unsigned comparisons, we can directly compare the shifted values. 10865 // For signed comparisons we shift and sign extend. 10866 Register SReg = RegInfo.createVirtualRegister(GPRC); 10867 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 10868 .addReg(TmpDestReg) 10869 .addReg(MaskReg); 10870 unsigned ValueReg = SReg; 10871 unsigned CmpReg = Incr2Reg; 10872 if (CmpOpcode == PPC::CMPW) { 10873 ValueReg = RegInfo.createVirtualRegister(GPRC); 10874 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 10875 .addReg(SReg) 10876 .addReg(ShiftReg); 10877 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 10878 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 10879 .addReg(ValueReg); 10880 ValueReg = ValueSReg; 10881 CmpReg = incr; 10882 } 10883 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0) 10884 .addReg(CmpReg) 10885 .addReg(ValueReg); 10886 BuildMI(BB, dl, TII->get(PPC::BCC)) 10887 .addImm(CmpPred) 10888 .addReg(PPC::CR0) 10889 .addMBB(exitMBB); 10890 BB->addSuccessor(loop2MBB); 10891 BB->addSuccessor(exitMBB); 10892 BB = loop2MBB; 10893 } 10894 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 10895 BuildMI(BB, dl, TII->get(PPC::STWCX)) 10896 .addReg(Tmp4Reg) 10897 .addReg(ZeroReg) 10898 .addReg(PtrReg); 10899 BuildMI(BB, dl, TII->get(PPC::BCC)) 10900 .addImm(PPC::PRED_NE) 10901 .addReg(PPC::CR0) 10902 .addMBB(loopMBB); 10903 BB->addSuccessor(loopMBB); 10904 BB->addSuccessor(exitMBB); 10905 10906 // exitMBB: 10907 // ... 10908 BB = exitMBB; 10909 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 10910 .addReg(TmpDestReg) 10911 .addReg(ShiftReg); 10912 return BB; 10913 } 10914 10915 llvm::MachineBasicBlock * 10916 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 10917 MachineBasicBlock *MBB) const { 10918 DebugLoc DL = MI.getDebugLoc(); 10919 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 10920 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10921 10922 MachineFunction *MF = MBB->getParent(); 10923 MachineRegisterInfo &MRI = MF->getRegInfo(); 10924 10925 const BasicBlock *BB = MBB->getBasicBlock(); 10926 MachineFunction::iterator I = ++MBB->getIterator(); 10927 10928 Register DstReg = MI.getOperand(0).getReg(); 10929 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 10930 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 10931 Register mainDstReg = MRI.createVirtualRegister(RC); 10932 Register restoreDstReg = MRI.createVirtualRegister(RC); 10933 10934 MVT PVT = getPointerTy(MF->getDataLayout()); 10935 assert((PVT == MVT::i64 || PVT == MVT::i32) && 10936 "Invalid Pointer Size!"); 10937 // For v = setjmp(buf), we generate 10938 // 10939 // thisMBB: 10940 // SjLjSetup mainMBB 10941 // bl mainMBB 10942 // v_restore = 1 10943 // b sinkMBB 10944 // 10945 // mainMBB: 10946 // buf[LabelOffset] = LR 10947 // v_main = 0 10948 // 10949 // sinkMBB: 10950 // v = phi(main, restore) 10951 // 10952 10953 MachineBasicBlock *thisMBB = MBB; 10954 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 10955 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 10956 MF->insert(I, mainMBB); 10957 MF->insert(I, sinkMBB); 10958 10959 MachineInstrBuilder MIB; 10960 10961 // Transfer the remainder of BB and its successor edges to sinkMBB. 10962 sinkMBB->splice(sinkMBB->begin(), MBB, 10963 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 10964 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 10965 10966 // Note that the structure of the jmp_buf used here is not compatible 10967 // with that used by libc, and is not designed to be. Specifically, it 10968 // stores only those 'reserved' registers that LLVM does not otherwise 10969 // understand how to spill. Also, by convention, by the time this 10970 // intrinsic is called, Clang has already stored the frame address in the 10971 // first slot of the buffer and stack address in the third. Following the 10972 // X86 target code, we'll store the jump address in the second slot. We also 10973 // need to save the TOC pointer (R2) to handle jumps between shared 10974 // libraries, and that will be stored in the fourth slot. The thread 10975 // identifier (R13) is not affected. 10976 10977 // thisMBB: 10978 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 10979 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 10980 const int64_t BPOffset = 4 * PVT.getStoreSize(); 10981 10982 // Prepare IP either in reg. 10983 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 10984 Register LabelReg = MRI.createVirtualRegister(PtrRC); 10985 Register BufReg = MI.getOperand(1).getReg(); 10986 10987 if (Subtarget.is64BitELFABI()) { 10988 setUsesTOCBasePtr(*MBB->getParent()); 10989 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 10990 .addReg(PPC::X2) 10991 .addImm(TOCOffset) 10992 .addReg(BufReg) 10993 .cloneMemRefs(MI); 10994 } 10995 10996 // Naked functions never have a base pointer, and so we use r1. For all 10997 // other functions, this decision must be delayed until during PEI. 10998 unsigned BaseReg; 10999 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 11000 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 11001 else 11002 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 11003 11004 MIB = BuildMI(*thisMBB, MI, DL, 11005 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 11006 .addReg(BaseReg) 11007 .addImm(BPOffset) 11008 .addReg(BufReg) 11009 .cloneMemRefs(MI); 11010 11011 // Setup 11012 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 11013 MIB.addRegMask(TRI->getNoPreservedMask()); 11014 11015 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 11016 11017 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 11018 .addMBB(mainMBB); 11019 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 11020 11021 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 11022 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 11023 11024 // mainMBB: 11025 // mainDstReg = 0 11026 MIB = 11027 BuildMI(mainMBB, DL, 11028 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 11029 11030 // Store IP 11031 if (Subtarget.isPPC64()) { 11032 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 11033 .addReg(LabelReg) 11034 .addImm(LabelOffset) 11035 .addReg(BufReg); 11036 } else { 11037 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 11038 .addReg(LabelReg) 11039 .addImm(LabelOffset) 11040 .addReg(BufReg); 11041 } 11042 MIB.cloneMemRefs(MI); 11043 11044 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 11045 mainMBB->addSuccessor(sinkMBB); 11046 11047 // sinkMBB: 11048 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 11049 TII->get(PPC::PHI), DstReg) 11050 .addReg(mainDstReg).addMBB(mainMBB) 11051 .addReg(restoreDstReg).addMBB(thisMBB); 11052 11053 MI.eraseFromParent(); 11054 return sinkMBB; 11055 } 11056 11057 MachineBasicBlock * 11058 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 11059 MachineBasicBlock *MBB) const { 11060 DebugLoc DL = MI.getDebugLoc(); 11061 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11062 11063 MachineFunction *MF = MBB->getParent(); 11064 MachineRegisterInfo &MRI = MF->getRegInfo(); 11065 11066 MVT PVT = getPointerTy(MF->getDataLayout()); 11067 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11068 "Invalid Pointer Size!"); 11069 11070 const TargetRegisterClass *RC = 11071 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11072 Register Tmp = MRI.createVirtualRegister(RC); 11073 // Since FP is only updated here but NOT referenced, it's treated as GPR. 11074 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 11075 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 11076 unsigned BP = 11077 (PVT == MVT::i64) 11078 ? PPC::X30 11079 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 11080 : PPC::R30); 11081 11082 MachineInstrBuilder MIB; 11083 11084 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11085 const int64_t SPOffset = 2 * PVT.getStoreSize(); 11086 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11087 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11088 11089 Register BufReg = MI.getOperand(0).getReg(); 11090 11091 // Reload FP (the jumped-to function may not have had a 11092 // frame pointer, and if so, then its r31 will be restored 11093 // as necessary). 11094 if (PVT == MVT::i64) { 11095 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 11096 .addImm(0) 11097 .addReg(BufReg); 11098 } else { 11099 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 11100 .addImm(0) 11101 .addReg(BufReg); 11102 } 11103 MIB.cloneMemRefs(MI); 11104 11105 // Reload IP 11106 if (PVT == MVT::i64) { 11107 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 11108 .addImm(LabelOffset) 11109 .addReg(BufReg); 11110 } else { 11111 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 11112 .addImm(LabelOffset) 11113 .addReg(BufReg); 11114 } 11115 MIB.cloneMemRefs(MI); 11116 11117 // Reload SP 11118 if (PVT == MVT::i64) { 11119 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 11120 .addImm(SPOffset) 11121 .addReg(BufReg); 11122 } else { 11123 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 11124 .addImm(SPOffset) 11125 .addReg(BufReg); 11126 } 11127 MIB.cloneMemRefs(MI); 11128 11129 // Reload BP 11130 if (PVT == MVT::i64) { 11131 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 11132 .addImm(BPOffset) 11133 .addReg(BufReg); 11134 } else { 11135 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 11136 .addImm(BPOffset) 11137 .addReg(BufReg); 11138 } 11139 MIB.cloneMemRefs(MI); 11140 11141 // Reload TOC 11142 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 11143 setUsesTOCBasePtr(*MBB->getParent()); 11144 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 11145 .addImm(TOCOffset) 11146 .addReg(BufReg) 11147 .cloneMemRefs(MI); 11148 } 11149 11150 // Jump 11151 BuildMI(*MBB, MI, DL, 11152 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 11153 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 11154 11155 MI.eraseFromParent(); 11156 return MBB; 11157 } 11158 11159 MachineBasicBlock * 11160 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 11161 MachineBasicBlock *BB) const { 11162 if (MI.getOpcode() == TargetOpcode::STACKMAP || 11163 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11164 if (Subtarget.is64BitELFABI() && 11165 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 11166 // Call lowering should have added an r2 operand to indicate a dependence 11167 // on the TOC base pointer value. It can't however, because there is no 11168 // way to mark the dependence as implicit there, and so the stackmap code 11169 // will confuse it with a regular operand. Instead, add the dependence 11170 // here. 11171 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 11172 } 11173 11174 return emitPatchPoint(MI, BB); 11175 } 11176 11177 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 11178 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 11179 return emitEHSjLjSetJmp(MI, BB); 11180 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 11181 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 11182 return emitEHSjLjLongJmp(MI, BB); 11183 } 11184 11185 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11186 11187 // To "insert" these instructions we actually have to insert their 11188 // control-flow patterns. 11189 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11190 MachineFunction::iterator It = ++BB->getIterator(); 11191 11192 MachineFunction *F = BB->getParent(); 11193 11194 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11195 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 11196 MI.getOpcode() == PPC::SELECT_I8) { 11197 SmallVector<MachineOperand, 2> Cond; 11198 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 11199 MI.getOpcode() == PPC::SELECT_CC_I8) 11200 Cond.push_back(MI.getOperand(4)); 11201 else 11202 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 11203 Cond.push_back(MI.getOperand(1)); 11204 11205 DebugLoc dl = MI.getDebugLoc(); 11206 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 11207 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 11208 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 11209 MI.getOpcode() == PPC::SELECT_CC_F8 || 11210 MI.getOpcode() == PPC::SELECT_CC_F16 || 11211 MI.getOpcode() == PPC::SELECT_CC_QFRC || 11212 MI.getOpcode() == PPC::SELECT_CC_QSRC || 11213 MI.getOpcode() == PPC::SELECT_CC_QBRC || 11214 MI.getOpcode() == PPC::SELECT_CC_VRRC || 11215 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 11216 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 11217 MI.getOpcode() == PPC::SELECT_CC_VSRC || 11218 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 11219 MI.getOpcode() == PPC::SELECT_CC_SPE || 11220 MI.getOpcode() == PPC::SELECT_F4 || 11221 MI.getOpcode() == PPC::SELECT_F8 || 11222 MI.getOpcode() == PPC::SELECT_F16 || 11223 MI.getOpcode() == PPC::SELECT_QFRC || 11224 MI.getOpcode() == PPC::SELECT_QSRC || 11225 MI.getOpcode() == PPC::SELECT_QBRC || 11226 MI.getOpcode() == PPC::SELECT_SPE || 11227 MI.getOpcode() == PPC::SELECT_SPE4 || 11228 MI.getOpcode() == PPC::SELECT_VRRC || 11229 MI.getOpcode() == PPC::SELECT_VSFRC || 11230 MI.getOpcode() == PPC::SELECT_VSSRC || 11231 MI.getOpcode() == PPC::SELECT_VSRC) { 11232 // The incoming instruction knows the destination vreg to set, the 11233 // condition code register to branch on, the true/false values to 11234 // select between, and a branch opcode to use. 11235 11236 // thisMBB: 11237 // ... 11238 // TrueVal = ... 11239 // cmpTY ccX, r1, r2 11240 // bCC copy1MBB 11241 // fallthrough --> copy0MBB 11242 MachineBasicBlock *thisMBB = BB; 11243 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 11244 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11245 DebugLoc dl = MI.getDebugLoc(); 11246 F->insert(It, copy0MBB); 11247 F->insert(It, sinkMBB); 11248 11249 // Transfer the remainder of BB and its successor edges to sinkMBB. 11250 sinkMBB->splice(sinkMBB->begin(), BB, 11251 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11252 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11253 11254 // Next, add the true and fallthrough blocks as its successors. 11255 BB->addSuccessor(copy0MBB); 11256 BB->addSuccessor(sinkMBB); 11257 11258 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 11259 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 11260 MI.getOpcode() == PPC::SELECT_F16 || 11261 MI.getOpcode() == PPC::SELECT_SPE4 || 11262 MI.getOpcode() == PPC::SELECT_SPE || 11263 MI.getOpcode() == PPC::SELECT_QFRC || 11264 MI.getOpcode() == PPC::SELECT_QSRC || 11265 MI.getOpcode() == PPC::SELECT_QBRC || 11266 MI.getOpcode() == PPC::SELECT_VRRC || 11267 MI.getOpcode() == PPC::SELECT_VSFRC || 11268 MI.getOpcode() == PPC::SELECT_VSSRC || 11269 MI.getOpcode() == PPC::SELECT_VSRC) { 11270 BuildMI(BB, dl, TII->get(PPC::BC)) 11271 .addReg(MI.getOperand(1).getReg()) 11272 .addMBB(sinkMBB); 11273 } else { 11274 unsigned SelectPred = MI.getOperand(4).getImm(); 11275 BuildMI(BB, dl, TII->get(PPC::BCC)) 11276 .addImm(SelectPred) 11277 .addReg(MI.getOperand(1).getReg()) 11278 .addMBB(sinkMBB); 11279 } 11280 11281 // copy0MBB: 11282 // %FalseValue = ... 11283 // # fallthrough to sinkMBB 11284 BB = copy0MBB; 11285 11286 // Update machine-CFG edges 11287 BB->addSuccessor(sinkMBB); 11288 11289 // sinkMBB: 11290 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 11291 // ... 11292 BB = sinkMBB; 11293 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 11294 .addReg(MI.getOperand(3).getReg()) 11295 .addMBB(copy0MBB) 11296 .addReg(MI.getOperand(2).getReg()) 11297 .addMBB(thisMBB); 11298 } else if (MI.getOpcode() == PPC::ReadTB) { 11299 // To read the 64-bit time-base register on a 32-bit target, we read the 11300 // two halves. Should the counter have wrapped while it was being read, we 11301 // need to try again. 11302 // ... 11303 // readLoop: 11304 // mfspr Rx,TBU # load from TBU 11305 // mfspr Ry,TB # load from TB 11306 // mfspr Rz,TBU # load from TBU 11307 // cmpw crX,Rx,Rz # check if 'old'='new' 11308 // bne readLoop # branch if they're not equal 11309 // ... 11310 11311 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 11312 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 11313 DebugLoc dl = MI.getDebugLoc(); 11314 F->insert(It, readMBB); 11315 F->insert(It, sinkMBB); 11316 11317 // Transfer the remainder of BB and its successor edges to sinkMBB. 11318 sinkMBB->splice(sinkMBB->begin(), BB, 11319 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11320 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 11321 11322 BB->addSuccessor(readMBB); 11323 BB = readMBB; 11324 11325 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11326 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11327 Register LoReg = MI.getOperand(0).getReg(); 11328 Register HiReg = MI.getOperand(1).getReg(); 11329 11330 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 11331 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 11332 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 11333 11334 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11335 11336 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 11337 .addReg(HiReg) 11338 .addReg(ReadAgainReg); 11339 BuildMI(BB, dl, TII->get(PPC::BCC)) 11340 .addImm(PPC::PRED_NE) 11341 .addReg(CmpReg) 11342 .addMBB(readMBB); 11343 11344 BB->addSuccessor(readMBB); 11345 BB->addSuccessor(sinkMBB); 11346 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 11347 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 11348 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 11349 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 11350 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 11351 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 11352 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 11353 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 11354 11355 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 11356 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 11357 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 11358 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 11359 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 11360 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 11361 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 11362 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 11363 11364 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 11365 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 11366 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 11367 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 11368 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 11369 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 11370 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 11371 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 11372 11373 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 11374 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 11375 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 11376 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 11377 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 11378 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 11379 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 11380 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 11381 11382 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 11383 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 11384 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 11385 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 11386 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 11387 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 11388 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 11389 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 11390 11391 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 11392 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 11393 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 11394 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 11395 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 11396 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 11397 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 11398 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 11399 11400 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 11401 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE); 11402 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 11403 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE); 11404 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 11405 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE); 11406 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 11407 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE); 11408 11409 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 11410 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE); 11411 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 11412 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE); 11413 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 11414 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE); 11415 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 11416 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE); 11417 11418 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 11419 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE); 11420 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 11421 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE); 11422 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 11423 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE); 11424 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 11425 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE); 11426 11427 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 11428 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE); 11429 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 11430 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE); 11431 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 11432 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE); 11433 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 11434 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE); 11435 11436 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 11437 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 11438 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 11439 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 11440 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 11441 BB = EmitAtomicBinary(MI, BB, 4, 0); 11442 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 11443 BB = EmitAtomicBinary(MI, BB, 8, 0); 11444 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 11445 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 11446 (Subtarget.hasPartwordAtomics() && 11447 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 11448 (Subtarget.hasPartwordAtomics() && 11449 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 11450 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 11451 11452 auto LoadMnemonic = PPC::LDARX; 11453 auto StoreMnemonic = PPC::STDCX; 11454 switch (MI.getOpcode()) { 11455 default: 11456 llvm_unreachable("Compare and swap of unknown size"); 11457 case PPC::ATOMIC_CMP_SWAP_I8: 11458 LoadMnemonic = PPC::LBARX; 11459 StoreMnemonic = PPC::STBCX; 11460 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11461 break; 11462 case PPC::ATOMIC_CMP_SWAP_I16: 11463 LoadMnemonic = PPC::LHARX; 11464 StoreMnemonic = PPC::STHCX; 11465 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 11466 break; 11467 case PPC::ATOMIC_CMP_SWAP_I32: 11468 LoadMnemonic = PPC::LWARX; 11469 StoreMnemonic = PPC::STWCX; 11470 break; 11471 case PPC::ATOMIC_CMP_SWAP_I64: 11472 LoadMnemonic = PPC::LDARX; 11473 StoreMnemonic = PPC::STDCX; 11474 break; 11475 } 11476 Register dest = MI.getOperand(0).getReg(); 11477 Register ptrA = MI.getOperand(1).getReg(); 11478 Register ptrB = MI.getOperand(2).getReg(); 11479 Register oldval = MI.getOperand(3).getReg(); 11480 Register newval = MI.getOperand(4).getReg(); 11481 DebugLoc dl = MI.getDebugLoc(); 11482 11483 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11484 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11485 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11486 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11487 F->insert(It, loop1MBB); 11488 F->insert(It, loop2MBB); 11489 F->insert(It, midMBB); 11490 F->insert(It, exitMBB); 11491 exitMBB->splice(exitMBB->begin(), BB, 11492 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11493 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11494 11495 // thisMBB: 11496 // ... 11497 // fallthrough --> loopMBB 11498 BB->addSuccessor(loop1MBB); 11499 11500 // loop1MBB: 11501 // l[bhwd]arx dest, ptr 11502 // cmp[wd] dest, oldval 11503 // bne- midMBB 11504 // loop2MBB: 11505 // st[bhwd]cx. newval, ptr 11506 // bne- loopMBB 11507 // b exitBB 11508 // midMBB: 11509 // st[bhwd]cx. dest, ptr 11510 // exitBB: 11511 BB = loop1MBB; 11512 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 11513 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) 11514 .addReg(oldval) 11515 .addReg(dest); 11516 BuildMI(BB, dl, TII->get(PPC::BCC)) 11517 .addImm(PPC::PRED_NE) 11518 .addReg(PPC::CR0) 11519 .addMBB(midMBB); 11520 BB->addSuccessor(loop2MBB); 11521 BB->addSuccessor(midMBB); 11522 11523 BB = loop2MBB; 11524 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11525 .addReg(newval) 11526 .addReg(ptrA) 11527 .addReg(ptrB); 11528 BuildMI(BB, dl, TII->get(PPC::BCC)) 11529 .addImm(PPC::PRED_NE) 11530 .addReg(PPC::CR0) 11531 .addMBB(loop1MBB); 11532 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11533 BB->addSuccessor(loop1MBB); 11534 BB->addSuccessor(exitMBB); 11535 11536 BB = midMBB; 11537 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11538 .addReg(dest) 11539 .addReg(ptrA) 11540 .addReg(ptrB); 11541 BB->addSuccessor(exitMBB); 11542 11543 // exitMBB: 11544 // ... 11545 BB = exitMBB; 11546 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 11547 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 11548 // We must use 64-bit registers for addresses when targeting 64-bit, 11549 // since we're actually doing arithmetic on them. Other registers 11550 // can be 32-bit. 11551 bool is64bit = Subtarget.isPPC64(); 11552 bool isLittleEndian = Subtarget.isLittleEndian(); 11553 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 11554 11555 Register dest = MI.getOperand(0).getReg(); 11556 Register ptrA = MI.getOperand(1).getReg(); 11557 Register ptrB = MI.getOperand(2).getReg(); 11558 Register oldval = MI.getOperand(3).getReg(); 11559 Register newval = MI.getOperand(4).getReg(); 11560 DebugLoc dl = MI.getDebugLoc(); 11561 11562 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 11563 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 11564 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); 11565 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11566 F->insert(It, loop1MBB); 11567 F->insert(It, loop2MBB); 11568 F->insert(It, midMBB); 11569 F->insert(It, exitMBB); 11570 exitMBB->splice(exitMBB->begin(), BB, 11571 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11572 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11573 11574 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11575 const TargetRegisterClass *RC = 11576 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11577 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11578 11579 Register PtrReg = RegInfo.createVirtualRegister(RC); 11580 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11581 Register ShiftReg = 11582 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11583 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 11584 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 11585 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 11586 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 11587 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11588 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11589 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11590 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11591 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11592 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11593 Register Ptr1Reg; 11594 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 11595 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11596 // thisMBB: 11597 // ... 11598 // fallthrough --> loopMBB 11599 BB->addSuccessor(loop1MBB); 11600 11601 // The 4-byte load must be aligned, while a char or short may be 11602 // anywhere in the word. Hence all this nasty bookkeeping code. 11603 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11604 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11605 // xori shift, shift1, 24 [16] 11606 // rlwinm ptr, ptr1, 0, 0, 29 11607 // slw newval2, newval, shift 11608 // slw oldval2, oldval,shift 11609 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11610 // slw mask, mask2, shift 11611 // and newval3, newval2, mask 11612 // and oldval3, oldval2, mask 11613 // loop1MBB: 11614 // lwarx tmpDest, ptr 11615 // and tmp, tmpDest, mask 11616 // cmpw tmp, oldval3 11617 // bne- midMBB 11618 // loop2MBB: 11619 // andc tmp2, tmpDest, mask 11620 // or tmp4, tmp2, newval3 11621 // stwcx. tmp4, ptr 11622 // bne- loop1MBB 11623 // b exitBB 11624 // midMBB: 11625 // stwcx. tmpDest, ptr 11626 // exitBB: 11627 // srw dest, tmpDest, shift 11628 if (ptrA != ZeroReg) { 11629 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11630 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11631 .addReg(ptrA) 11632 .addReg(ptrB); 11633 } else { 11634 Ptr1Reg = ptrB; 11635 } 11636 11637 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11638 // mode. 11639 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11640 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11641 .addImm(3) 11642 .addImm(27) 11643 .addImm(is8bit ? 28 : 27); 11644 if (!isLittleEndian) 11645 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11646 .addReg(Shift1Reg) 11647 .addImm(is8bit ? 24 : 16); 11648 if (is64bit) 11649 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11650 .addReg(Ptr1Reg) 11651 .addImm(0) 11652 .addImm(61); 11653 else 11654 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11655 .addReg(Ptr1Reg) 11656 .addImm(0) 11657 .addImm(0) 11658 .addImm(29); 11659 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 11660 .addReg(newval) 11661 .addReg(ShiftReg); 11662 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 11663 .addReg(oldval) 11664 .addReg(ShiftReg); 11665 if (is8bit) 11666 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11667 else { 11668 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11669 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11670 .addReg(Mask3Reg) 11671 .addImm(65535); 11672 } 11673 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11674 .addReg(Mask2Reg) 11675 .addReg(ShiftReg); 11676 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 11677 .addReg(NewVal2Reg) 11678 .addReg(MaskReg); 11679 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 11680 .addReg(OldVal2Reg) 11681 .addReg(MaskReg); 11682 11683 BB = loop1MBB; 11684 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11685 .addReg(ZeroReg) 11686 .addReg(PtrReg); 11687 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 11688 .addReg(TmpDestReg) 11689 .addReg(MaskReg); 11690 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) 11691 .addReg(TmpReg) 11692 .addReg(OldVal3Reg); 11693 BuildMI(BB, dl, TII->get(PPC::BCC)) 11694 .addImm(PPC::PRED_NE) 11695 .addReg(PPC::CR0) 11696 .addMBB(midMBB); 11697 BB->addSuccessor(loop2MBB); 11698 BB->addSuccessor(midMBB); 11699 11700 BB = loop2MBB; 11701 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11702 .addReg(TmpDestReg) 11703 .addReg(MaskReg); 11704 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 11705 .addReg(Tmp2Reg) 11706 .addReg(NewVal3Reg); 11707 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11708 .addReg(Tmp4Reg) 11709 .addReg(ZeroReg) 11710 .addReg(PtrReg); 11711 BuildMI(BB, dl, TII->get(PPC::BCC)) 11712 .addImm(PPC::PRED_NE) 11713 .addReg(PPC::CR0) 11714 .addMBB(loop1MBB); 11715 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 11716 BB->addSuccessor(loop1MBB); 11717 BB->addSuccessor(exitMBB); 11718 11719 BB = midMBB; 11720 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11721 .addReg(TmpDestReg) 11722 .addReg(ZeroReg) 11723 .addReg(PtrReg); 11724 BB->addSuccessor(exitMBB); 11725 11726 // exitMBB: 11727 // ... 11728 BB = exitMBB; 11729 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 11730 .addReg(TmpReg) 11731 .addReg(ShiftReg); 11732 } else if (MI.getOpcode() == PPC::FADDrtz) { 11733 // This pseudo performs an FADD with rounding mode temporarily forced 11734 // to round-to-zero. We emit this via custom inserter since the FPSCR 11735 // is not modeled at the SelectionDAG level. 11736 Register Dest = MI.getOperand(0).getReg(); 11737 Register Src1 = MI.getOperand(1).getReg(); 11738 Register Src2 = MI.getOperand(2).getReg(); 11739 DebugLoc dl = MI.getDebugLoc(); 11740 11741 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11742 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11743 11744 // Save FPSCR value. 11745 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 11746 11747 // Set rounding mode to round-to-zero. 11748 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); 11749 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); 11750 11751 // Perform addition. 11752 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); 11753 11754 // Restore FPSCR value. 11755 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 11756 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11757 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 11758 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11759 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 11760 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 11761 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 11762 ? PPC::ANDI8_rec 11763 : PPC::ANDI_rec; 11764 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 11765 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 11766 11767 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11768 Register Dest = RegInfo.createVirtualRegister( 11769 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 11770 11771 DebugLoc Dl = MI.getDebugLoc(); 11772 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 11773 .addReg(MI.getOperand(1).getReg()) 11774 .addImm(1); 11775 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11776 MI.getOperand(0).getReg()) 11777 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 11778 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 11779 DebugLoc Dl = MI.getDebugLoc(); 11780 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11781 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11782 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 11783 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11784 MI.getOperand(0).getReg()) 11785 .addReg(CRReg); 11786 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 11787 DebugLoc Dl = MI.getDebugLoc(); 11788 unsigned Imm = MI.getOperand(1).getImm(); 11789 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 11790 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 11791 MI.getOperand(0).getReg()) 11792 .addReg(PPC::CR0EQ); 11793 } else if (MI.getOpcode() == PPC::SETRNDi) { 11794 DebugLoc dl = MI.getDebugLoc(); 11795 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11796 11797 // Save FPSCR value. 11798 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11799 11800 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 11801 // the following settings: 11802 // 00 Round to nearest 11803 // 01 Round to 0 11804 // 10 Round to +inf 11805 // 11 Round to -inf 11806 11807 // When the operand is immediate, using the two least significant bits of 11808 // the immediate to set the bits 62:63 of FPSCR. 11809 unsigned Mode = MI.getOperand(1).getImm(); 11810 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 11811 .addImm(31); 11812 11813 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 11814 .addImm(30); 11815 } else if (MI.getOpcode() == PPC::SETRND) { 11816 DebugLoc dl = MI.getDebugLoc(); 11817 11818 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 11819 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 11820 // If the target doesn't have DirectMove, we should use stack to do the 11821 // conversion, because the target doesn't have the instructions like mtvsrd 11822 // or mfvsrd to do this conversion directly. 11823 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 11824 if (Subtarget.hasDirectMove()) { 11825 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 11826 .addReg(SrcReg); 11827 } else { 11828 // Use stack to do the register copy. 11829 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 11830 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11831 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 11832 if (RC == &PPC::F8RCRegClass) { 11833 // Copy register from F8RCRegClass to G8RCRegclass. 11834 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 11835 "Unsupported RegClass."); 11836 11837 StoreOp = PPC::STFD; 11838 LoadOp = PPC::LD; 11839 } else { 11840 // Copy register from G8RCRegClass to F8RCRegclass. 11841 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 11842 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 11843 "Unsupported RegClass."); 11844 } 11845 11846 MachineFrameInfo &MFI = F->getFrameInfo(); 11847 int FrameIdx = MFI.CreateStackObject(8, 8, false); 11848 11849 MachineMemOperand *MMOStore = F->getMachineMemOperand( 11850 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11851 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 11852 MFI.getObjectAlignment(FrameIdx)); 11853 11854 // Store the SrcReg into the stack. 11855 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 11856 .addReg(SrcReg) 11857 .addImm(0) 11858 .addFrameIndex(FrameIdx) 11859 .addMemOperand(MMOStore); 11860 11861 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 11862 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 11863 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 11864 MFI.getObjectAlignment(FrameIdx)); 11865 11866 // Load from the stack where SrcReg is stored, and save to DestReg, 11867 // so we have done the RegClass conversion from RegClass::SrcReg to 11868 // RegClass::DestReg. 11869 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 11870 .addImm(0) 11871 .addFrameIndex(FrameIdx) 11872 .addMemOperand(MMOLoad); 11873 } 11874 }; 11875 11876 Register OldFPSCRReg = MI.getOperand(0).getReg(); 11877 11878 // Save FPSCR value. 11879 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 11880 11881 // When the operand is gprc register, use two least significant bits of the 11882 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 11883 // 11884 // copy OldFPSCRTmpReg, OldFPSCRReg 11885 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 11886 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 11887 // copy NewFPSCRReg, NewFPSCRTmpReg 11888 // mtfsf 255, NewFPSCRReg 11889 MachineOperand SrcOp = MI.getOperand(1); 11890 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11891 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11892 11893 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 11894 11895 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11896 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11897 11898 // The first operand of INSERT_SUBREG should be a register which has 11899 // subregisters, we only care about its RegClass, so we should use an 11900 // IMPLICIT_DEF register. 11901 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 11902 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 11903 .addReg(ImDefReg) 11904 .add(SrcOp) 11905 .addImm(1); 11906 11907 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 11908 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 11909 .addReg(OldFPSCRTmpReg) 11910 .addReg(ExtSrcReg) 11911 .addImm(0) 11912 .addImm(62); 11913 11914 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 11915 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 11916 11917 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 11918 // bits of FPSCR. 11919 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 11920 .addImm(255) 11921 .addReg(NewFPSCRReg) 11922 .addImm(0) 11923 .addImm(0); 11924 } else { 11925 llvm_unreachable("Unexpected instr type to insert"); 11926 } 11927 11928 MI.eraseFromParent(); // The pseudo instruction is gone now. 11929 return BB; 11930 } 11931 11932 //===----------------------------------------------------------------------===// 11933 // Target Optimization Hooks 11934 //===----------------------------------------------------------------------===// 11935 11936 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 11937 // For the estimates, convergence is quadratic, so we essentially double the 11938 // number of digits correct after every iteration. For both FRE and FRSQRTE, 11939 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 11940 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 11941 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 11942 if (VT.getScalarType() == MVT::f64) 11943 RefinementSteps++; 11944 return RefinementSteps; 11945 } 11946 11947 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 11948 int Enabled, int &RefinementSteps, 11949 bool &UseOneConstNR, 11950 bool Reciprocal) const { 11951 EVT VT = Operand.getValueType(); 11952 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 11953 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 11954 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11955 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11956 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11957 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11958 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11959 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11960 11961 // The Newton-Raphson computation with a single constant does not provide 11962 // enough accuracy on some CPUs. 11963 UseOneConstNR = !Subtarget.needsTwoConstNR(); 11964 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 11965 } 11966 return SDValue(); 11967 } 11968 11969 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 11970 int Enabled, 11971 int &RefinementSteps) const { 11972 EVT VT = Operand.getValueType(); 11973 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 11974 (VT == MVT::f64 && Subtarget.hasFRE()) || 11975 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 11976 (VT == MVT::v2f64 && Subtarget.hasVSX()) || 11977 (VT == MVT::v4f32 && Subtarget.hasQPX()) || 11978 (VT == MVT::v4f64 && Subtarget.hasQPX())) { 11979 if (RefinementSteps == ReciprocalEstimate::Unspecified) 11980 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 11981 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 11982 } 11983 return SDValue(); 11984 } 11985 11986 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 11987 // Note: This functionality is used only when unsafe-fp-math is enabled, and 11988 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 11989 // enabled for division), this functionality is redundant with the default 11990 // combiner logic (once the division -> reciprocal/multiply transformation 11991 // has taken place). As a result, this matters more for older cores than for 11992 // newer ones. 11993 11994 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11995 // reciprocal if there are two or more FDIVs (for embedded cores with only 11996 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 11997 switch (Subtarget.getCPUDirective()) { 11998 default: 11999 return 3; 12000 case PPC::DIR_440: 12001 case PPC::DIR_A2: 12002 case PPC::DIR_E500: 12003 case PPC::DIR_E500mc: 12004 case PPC::DIR_E5500: 12005 return 2; 12006 } 12007 } 12008 12009 // isConsecutiveLSLoc needs to work even if all adds have not yet been 12010 // collapsed, and so we need to look through chains of them. 12011 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 12012 int64_t& Offset, SelectionDAG &DAG) { 12013 if (DAG.isBaseWithConstantOffset(Loc)) { 12014 Base = Loc.getOperand(0); 12015 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 12016 12017 // The base might itself be a base plus an offset, and if so, accumulate 12018 // that as well. 12019 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 12020 } 12021 } 12022 12023 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 12024 unsigned Bytes, int Dist, 12025 SelectionDAG &DAG) { 12026 if (VT.getSizeInBits() / 8 != Bytes) 12027 return false; 12028 12029 SDValue BaseLoc = Base->getBasePtr(); 12030 if (Loc.getOpcode() == ISD::FrameIndex) { 12031 if (BaseLoc.getOpcode() != ISD::FrameIndex) 12032 return false; 12033 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 12034 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 12035 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 12036 int FS = MFI.getObjectSize(FI); 12037 int BFS = MFI.getObjectSize(BFI); 12038 if (FS != BFS || FS != (int)Bytes) return false; 12039 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 12040 } 12041 12042 SDValue Base1 = Loc, Base2 = BaseLoc; 12043 int64_t Offset1 = 0, Offset2 = 0; 12044 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 12045 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 12046 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 12047 return true; 12048 12049 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12050 const GlobalValue *GV1 = nullptr; 12051 const GlobalValue *GV2 = nullptr; 12052 Offset1 = 0; 12053 Offset2 = 0; 12054 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 12055 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 12056 if (isGA1 && isGA2 && GV1 == GV2) 12057 return Offset1 == (Offset2 + Dist*Bytes); 12058 return false; 12059 } 12060 12061 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 12062 // not enforce equality of the chain operands. 12063 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 12064 unsigned Bytes, int Dist, 12065 SelectionDAG &DAG) { 12066 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 12067 EVT VT = LS->getMemoryVT(); 12068 SDValue Loc = LS->getBasePtr(); 12069 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 12070 } 12071 12072 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 12073 EVT VT; 12074 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12075 default: return false; 12076 case Intrinsic::ppc_qpx_qvlfd: 12077 case Intrinsic::ppc_qpx_qvlfda: 12078 VT = MVT::v4f64; 12079 break; 12080 case Intrinsic::ppc_qpx_qvlfs: 12081 case Intrinsic::ppc_qpx_qvlfsa: 12082 VT = MVT::v4f32; 12083 break; 12084 case Intrinsic::ppc_qpx_qvlfcd: 12085 case Intrinsic::ppc_qpx_qvlfcda: 12086 VT = MVT::v2f64; 12087 break; 12088 case Intrinsic::ppc_qpx_qvlfcs: 12089 case Intrinsic::ppc_qpx_qvlfcsa: 12090 VT = MVT::v2f32; 12091 break; 12092 case Intrinsic::ppc_qpx_qvlfiwa: 12093 case Intrinsic::ppc_qpx_qvlfiwz: 12094 case Intrinsic::ppc_altivec_lvx: 12095 case Intrinsic::ppc_altivec_lvxl: 12096 case Intrinsic::ppc_vsx_lxvw4x: 12097 case Intrinsic::ppc_vsx_lxvw4x_be: 12098 VT = MVT::v4i32; 12099 break; 12100 case Intrinsic::ppc_vsx_lxvd2x: 12101 case Intrinsic::ppc_vsx_lxvd2x_be: 12102 VT = MVT::v2f64; 12103 break; 12104 case Intrinsic::ppc_altivec_lvebx: 12105 VT = MVT::i8; 12106 break; 12107 case Intrinsic::ppc_altivec_lvehx: 12108 VT = MVT::i16; 12109 break; 12110 case Intrinsic::ppc_altivec_lvewx: 12111 VT = MVT::i32; 12112 break; 12113 } 12114 12115 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 12116 } 12117 12118 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 12119 EVT VT; 12120 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 12121 default: return false; 12122 case Intrinsic::ppc_qpx_qvstfd: 12123 case Intrinsic::ppc_qpx_qvstfda: 12124 VT = MVT::v4f64; 12125 break; 12126 case Intrinsic::ppc_qpx_qvstfs: 12127 case Intrinsic::ppc_qpx_qvstfsa: 12128 VT = MVT::v4f32; 12129 break; 12130 case Intrinsic::ppc_qpx_qvstfcd: 12131 case Intrinsic::ppc_qpx_qvstfcda: 12132 VT = MVT::v2f64; 12133 break; 12134 case Intrinsic::ppc_qpx_qvstfcs: 12135 case Intrinsic::ppc_qpx_qvstfcsa: 12136 VT = MVT::v2f32; 12137 break; 12138 case Intrinsic::ppc_qpx_qvstfiw: 12139 case Intrinsic::ppc_qpx_qvstfiwa: 12140 case Intrinsic::ppc_altivec_stvx: 12141 case Intrinsic::ppc_altivec_stvxl: 12142 case Intrinsic::ppc_vsx_stxvw4x: 12143 VT = MVT::v4i32; 12144 break; 12145 case Intrinsic::ppc_vsx_stxvd2x: 12146 VT = MVT::v2f64; 12147 break; 12148 case Intrinsic::ppc_vsx_stxvw4x_be: 12149 VT = MVT::v4i32; 12150 break; 12151 case Intrinsic::ppc_vsx_stxvd2x_be: 12152 VT = MVT::v2f64; 12153 break; 12154 case Intrinsic::ppc_altivec_stvebx: 12155 VT = MVT::i8; 12156 break; 12157 case Intrinsic::ppc_altivec_stvehx: 12158 VT = MVT::i16; 12159 break; 12160 case Intrinsic::ppc_altivec_stvewx: 12161 VT = MVT::i32; 12162 break; 12163 } 12164 12165 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 12166 } 12167 12168 return false; 12169 } 12170 12171 // Return true is there is a nearyby consecutive load to the one provided 12172 // (regardless of alignment). We search up and down the chain, looking though 12173 // token factors and other loads (but nothing else). As a result, a true result 12174 // indicates that it is safe to create a new consecutive load adjacent to the 12175 // load provided. 12176 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 12177 SDValue Chain = LD->getChain(); 12178 EVT VT = LD->getMemoryVT(); 12179 12180 SmallSet<SDNode *, 16> LoadRoots; 12181 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 12182 SmallSet<SDNode *, 16> Visited; 12183 12184 // First, search up the chain, branching to follow all token-factor operands. 12185 // If we find a consecutive load, then we're done, otherwise, record all 12186 // nodes just above the top-level loads and token factors. 12187 while (!Queue.empty()) { 12188 SDNode *ChainNext = Queue.pop_back_val(); 12189 if (!Visited.insert(ChainNext).second) 12190 continue; 12191 12192 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 12193 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12194 return true; 12195 12196 if (!Visited.count(ChainLD->getChain().getNode())) 12197 Queue.push_back(ChainLD->getChain().getNode()); 12198 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 12199 for (const SDUse &O : ChainNext->ops()) 12200 if (!Visited.count(O.getNode())) 12201 Queue.push_back(O.getNode()); 12202 } else 12203 LoadRoots.insert(ChainNext); 12204 } 12205 12206 // Second, search down the chain, starting from the top-level nodes recorded 12207 // in the first phase. These top-level nodes are the nodes just above all 12208 // loads and token factors. Starting with their uses, recursively look though 12209 // all loads (just the chain uses) and token factors to find a consecutive 12210 // load. 12211 Visited.clear(); 12212 Queue.clear(); 12213 12214 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), 12215 IE = LoadRoots.end(); I != IE; ++I) { 12216 Queue.push_back(*I); 12217 12218 while (!Queue.empty()) { 12219 SDNode *LoadRoot = Queue.pop_back_val(); 12220 if (!Visited.insert(LoadRoot).second) 12221 continue; 12222 12223 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 12224 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 12225 return true; 12226 12227 for (SDNode::use_iterator UI = LoadRoot->use_begin(), 12228 UE = LoadRoot->use_end(); UI != UE; ++UI) 12229 if (((isa<MemSDNode>(*UI) && 12230 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || 12231 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) 12232 Queue.push_back(*UI); 12233 } 12234 } 12235 12236 return false; 12237 } 12238 12239 /// This function is called when we have proved that a SETCC node can be replaced 12240 /// by subtraction (and other supporting instructions) so that the result of 12241 /// comparison is kept in a GPR instead of CR. This function is purely for 12242 /// codegen purposes and has some flags to guide the codegen process. 12243 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 12244 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 12245 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12246 12247 // Zero extend the operands to the largest legal integer. Originally, they 12248 // must be of a strictly smaller size. 12249 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 12250 DAG.getConstant(Size, DL, MVT::i32)); 12251 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 12252 DAG.getConstant(Size, DL, MVT::i32)); 12253 12254 // Swap if needed. Depends on the condition code. 12255 if (Swap) 12256 std::swap(Op0, Op1); 12257 12258 // Subtract extended integers. 12259 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 12260 12261 // Move the sign bit to the least significant position and zero out the rest. 12262 // Now the least significant bit carries the result of original comparison. 12263 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 12264 DAG.getConstant(Size - 1, DL, MVT::i32)); 12265 auto Final = Shifted; 12266 12267 // Complement the result if needed. Based on the condition code. 12268 if (Complement) 12269 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 12270 DAG.getConstant(1, DL, MVT::i64)); 12271 12272 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 12273 } 12274 12275 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 12276 DAGCombinerInfo &DCI) const { 12277 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 12278 12279 SelectionDAG &DAG = DCI.DAG; 12280 SDLoc DL(N); 12281 12282 // Size of integers being compared has a critical role in the following 12283 // analysis, so we prefer to do this when all types are legal. 12284 if (!DCI.isAfterLegalizeDAG()) 12285 return SDValue(); 12286 12287 // If all users of SETCC extend its value to a legal integer type 12288 // then we replace SETCC with a subtraction 12289 for (SDNode::use_iterator UI = N->use_begin(), 12290 UE = N->use_end(); UI != UE; ++UI) { 12291 if (UI->getOpcode() != ISD::ZERO_EXTEND) 12292 return SDValue(); 12293 } 12294 12295 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12296 auto OpSize = N->getOperand(0).getValueSizeInBits(); 12297 12298 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 12299 12300 if (OpSize < Size) { 12301 switch (CC) { 12302 default: break; 12303 case ISD::SETULT: 12304 return generateEquivalentSub(N, Size, false, false, DL, DAG); 12305 case ISD::SETULE: 12306 return generateEquivalentSub(N, Size, true, true, DL, DAG); 12307 case ISD::SETUGT: 12308 return generateEquivalentSub(N, Size, false, true, DL, DAG); 12309 case ISD::SETUGE: 12310 return generateEquivalentSub(N, Size, true, false, DL, DAG); 12311 } 12312 } 12313 12314 return SDValue(); 12315 } 12316 12317 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 12318 DAGCombinerInfo &DCI) const { 12319 SelectionDAG &DAG = DCI.DAG; 12320 SDLoc dl(N); 12321 12322 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 12323 // If we're tracking CR bits, we need to be careful that we don't have: 12324 // trunc(binary-ops(zext(x), zext(y))) 12325 // or 12326 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 12327 // such that we're unnecessarily moving things into GPRs when it would be 12328 // better to keep them in CR bits. 12329 12330 // Note that trunc here can be an actual i1 trunc, or can be the effective 12331 // truncation that comes from a setcc or select_cc. 12332 if (N->getOpcode() == ISD::TRUNCATE && 12333 N->getValueType(0) != MVT::i1) 12334 return SDValue(); 12335 12336 if (N->getOperand(0).getValueType() != MVT::i32 && 12337 N->getOperand(0).getValueType() != MVT::i64) 12338 return SDValue(); 12339 12340 if (N->getOpcode() == ISD::SETCC || 12341 N->getOpcode() == ISD::SELECT_CC) { 12342 // If we're looking at a comparison, then we need to make sure that the 12343 // high bits (all except for the first) don't matter the result. 12344 ISD::CondCode CC = 12345 cast<CondCodeSDNode>(N->getOperand( 12346 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 12347 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 12348 12349 if (ISD::isSignedIntSetCC(CC)) { 12350 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 12351 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 12352 return SDValue(); 12353 } else if (ISD::isUnsignedIntSetCC(CC)) { 12354 if (!DAG.MaskedValueIsZero(N->getOperand(0), 12355 APInt::getHighBitsSet(OpBits, OpBits-1)) || 12356 !DAG.MaskedValueIsZero(N->getOperand(1), 12357 APInt::getHighBitsSet(OpBits, OpBits-1))) 12358 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 12359 : SDValue()); 12360 } else { 12361 // This is neither a signed nor an unsigned comparison, just make sure 12362 // that the high bits are equal. 12363 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 12364 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 12365 12366 // We don't really care about what is known about the first bit (if 12367 // anything), so clear it in all masks prior to comparing them. 12368 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0); 12369 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0); 12370 12371 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One) 12372 return SDValue(); 12373 } 12374 } 12375 12376 // We now know that the higher-order bits are irrelevant, we just need to 12377 // make sure that all of the intermediate operations are bit operations, and 12378 // all inputs are extensions. 12379 if (N->getOperand(0).getOpcode() != ISD::AND && 12380 N->getOperand(0).getOpcode() != ISD::OR && 12381 N->getOperand(0).getOpcode() != ISD::XOR && 12382 N->getOperand(0).getOpcode() != ISD::SELECT && 12383 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 12384 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 12385 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 12386 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 12387 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 12388 return SDValue(); 12389 12390 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 12391 N->getOperand(1).getOpcode() != ISD::AND && 12392 N->getOperand(1).getOpcode() != ISD::OR && 12393 N->getOperand(1).getOpcode() != ISD::XOR && 12394 N->getOperand(1).getOpcode() != ISD::SELECT && 12395 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 12396 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 12397 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 12398 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 12399 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 12400 return SDValue(); 12401 12402 SmallVector<SDValue, 4> Inputs; 12403 SmallVector<SDValue, 8> BinOps, PromOps; 12404 SmallPtrSet<SDNode *, 16> Visited; 12405 12406 for (unsigned i = 0; i < 2; ++i) { 12407 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12408 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12409 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12410 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12411 isa<ConstantSDNode>(N->getOperand(i))) 12412 Inputs.push_back(N->getOperand(i)); 12413 else 12414 BinOps.push_back(N->getOperand(i)); 12415 12416 if (N->getOpcode() == ISD::TRUNCATE) 12417 break; 12418 } 12419 12420 // Visit all inputs, collect all binary operations (and, or, xor and 12421 // select) that are all fed by extensions. 12422 while (!BinOps.empty()) { 12423 SDValue BinOp = BinOps.back(); 12424 BinOps.pop_back(); 12425 12426 if (!Visited.insert(BinOp.getNode()).second) 12427 continue; 12428 12429 PromOps.push_back(BinOp); 12430 12431 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12432 // The condition of the select is not promoted. 12433 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12434 continue; 12435 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12436 continue; 12437 12438 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12439 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12440 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 12441 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 12442 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12443 Inputs.push_back(BinOp.getOperand(i)); 12444 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12445 BinOp.getOperand(i).getOpcode() == ISD::OR || 12446 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12447 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12448 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 12449 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12450 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 12451 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 12452 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 12453 BinOps.push_back(BinOp.getOperand(i)); 12454 } else { 12455 // We have an input that is not an extension or another binary 12456 // operation; we'll abort this transformation. 12457 return SDValue(); 12458 } 12459 } 12460 } 12461 12462 // Make sure that this is a self-contained cluster of operations (which 12463 // is not quite the same thing as saying that everything has only one 12464 // use). 12465 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12466 if (isa<ConstantSDNode>(Inputs[i])) 12467 continue; 12468 12469 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12470 UE = Inputs[i].getNode()->use_end(); 12471 UI != UE; ++UI) { 12472 SDNode *User = *UI; 12473 if (User != N && !Visited.count(User)) 12474 return SDValue(); 12475 12476 // Make sure that we're not going to promote the non-output-value 12477 // operand(s) or SELECT or SELECT_CC. 12478 // FIXME: Although we could sometimes handle this, and it does occur in 12479 // practice that one of the condition inputs to the select is also one of 12480 // the outputs, we currently can't deal with this. 12481 if (User->getOpcode() == ISD::SELECT) { 12482 if (User->getOperand(0) == Inputs[i]) 12483 return SDValue(); 12484 } else if (User->getOpcode() == ISD::SELECT_CC) { 12485 if (User->getOperand(0) == Inputs[i] || 12486 User->getOperand(1) == Inputs[i]) 12487 return SDValue(); 12488 } 12489 } 12490 } 12491 12492 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12493 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12494 UE = PromOps[i].getNode()->use_end(); 12495 UI != UE; ++UI) { 12496 SDNode *User = *UI; 12497 if (User != N && !Visited.count(User)) 12498 return SDValue(); 12499 12500 // Make sure that we're not going to promote the non-output-value 12501 // operand(s) or SELECT or SELECT_CC. 12502 // FIXME: Although we could sometimes handle this, and it does occur in 12503 // practice that one of the condition inputs to the select is also one of 12504 // the outputs, we currently can't deal with this. 12505 if (User->getOpcode() == ISD::SELECT) { 12506 if (User->getOperand(0) == PromOps[i]) 12507 return SDValue(); 12508 } else if (User->getOpcode() == ISD::SELECT_CC) { 12509 if (User->getOperand(0) == PromOps[i] || 12510 User->getOperand(1) == PromOps[i]) 12511 return SDValue(); 12512 } 12513 } 12514 } 12515 12516 // Replace all inputs with the extension operand. 12517 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12518 // Constants may have users outside the cluster of to-be-promoted nodes, 12519 // and so we need to replace those as we do the promotions. 12520 if (isa<ConstantSDNode>(Inputs[i])) 12521 continue; 12522 else 12523 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 12524 } 12525 12526 std::list<HandleSDNode> PromOpHandles; 12527 for (auto &PromOp : PromOps) 12528 PromOpHandles.emplace_back(PromOp); 12529 12530 // Replace all operations (these are all the same, but have a different 12531 // (i1) return type). DAG.getNode will validate that the types of 12532 // a binary operator match, so go through the list in reverse so that 12533 // we've likely promoted both operands first. Any intermediate truncations or 12534 // extensions disappear. 12535 while (!PromOpHandles.empty()) { 12536 SDValue PromOp = PromOpHandles.back().getValue(); 12537 PromOpHandles.pop_back(); 12538 12539 if (PromOp.getOpcode() == ISD::TRUNCATE || 12540 PromOp.getOpcode() == ISD::SIGN_EXTEND || 12541 PromOp.getOpcode() == ISD::ZERO_EXTEND || 12542 PromOp.getOpcode() == ISD::ANY_EXTEND) { 12543 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 12544 PromOp.getOperand(0).getValueType() != MVT::i1) { 12545 // The operand is not yet ready (see comment below). 12546 PromOpHandles.emplace_front(PromOp); 12547 continue; 12548 } 12549 12550 SDValue RepValue = PromOp.getOperand(0); 12551 if (isa<ConstantSDNode>(RepValue)) 12552 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 12553 12554 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 12555 continue; 12556 } 12557 12558 unsigned C; 12559 switch (PromOp.getOpcode()) { 12560 default: C = 0; break; 12561 case ISD::SELECT: C = 1; break; 12562 case ISD::SELECT_CC: C = 2; break; 12563 } 12564 12565 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12566 PromOp.getOperand(C).getValueType() != MVT::i1) || 12567 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12568 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 12569 // The to-be-promoted operands of this node have not yet been 12570 // promoted (this should be rare because we're going through the 12571 // list backward, but if one of the operands has several users in 12572 // this cluster of to-be-promoted nodes, it is possible). 12573 PromOpHandles.emplace_front(PromOp); 12574 continue; 12575 } 12576 12577 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12578 PromOp.getNode()->op_end()); 12579 12580 // If there are any constant inputs, make sure they're replaced now. 12581 for (unsigned i = 0; i < 2; ++i) 12582 if (isa<ConstantSDNode>(Ops[C+i])) 12583 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 12584 12585 DAG.ReplaceAllUsesOfValueWith(PromOp, 12586 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 12587 } 12588 12589 // Now we're left with the initial truncation itself. 12590 if (N->getOpcode() == ISD::TRUNCATE) 12591 return N->getOperand(0); 12592 12593 // Otherwise, this is a comparison. The operands to be compared have just 12594 // changed type (to i1), but everything else is the same. 12595 return SDValue(N, 0); 12596 } 12597 12598 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 12599 DAGCombinerInfo &DCI) const { 12600 SelectionDAG &DAG = DCI.DAG; 12601 SDLoc dl(N); 12602 12603 // If we're tracking CR bits, we need to be careful that we don't have: 12604 // zext(binary-ops(trunc(x), trunc(y))) 12605 // or 12606 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 12607 // such that we're unnecessarily moving things into CR bits that can more 12608 // efficiently stay in GPRs. Note that if we're not certain that the high 12609 // bits are set as required by the final extension, we still may need to do 12610 // some masking to get the proper behavior. 12611 12612 // This same functionality is important on PPC64 when dealing with 12613 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 12614 // the return values of functions. Because it is so similar, it is handled 12615 // here as well. 12616 12617 if (N->getValueType(0) != MVT::i32 && 12618 N->getValueType(0) != MVT::i64) 12619 return SDValue(); 12620 12621 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 12622 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 12623 return SDValue(); 12624 12625 if (N->getOperand(0).getOpcode() != ISD::AND && 12626 N->getOperand(0).getOpcode() != ISD::OR && 12627 N->getOperand(0).getOpcode() != ISD::XOR && 12628 N->getOperand(0).getOpcode() != ISD::SELECT && 12629 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 12630 return SDValue(); 12631 12632 SmallVector<SDValue, 4> Inputs; 12633 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 12634 SmallPtrSet<SDNode *, 16> Visited; 12635 12636 // Visit all inputs, collect all binary operations (and, or, xor and 12637 // select) that are all fed by truncations. 12638 while (!BinOps.empty()) { 12639 SDValue BinOp = BinOps.back(); 12640 BinOps.pop_back(); 12641 12642 if (!Visited.insert(BinOp.getNode()).second) 12643 continue; 12644 12645 PromOps.push_back(BinOp); 12646 12647 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 12648 // The condition of the select is not promoted. 12649 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 12650 continue; 12651 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 12652 continue; 12653 12654 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 12655 isa<ConstantSDNode>(BinOp.getOperand(i))) { 12656 Inputs.push_back(BinOp.getOperand(i)); 12657 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 12658 BinOp.getOperand(i).getOpcode() == ISD::OR || 12659 BinOp.getOperand(i).getOpcode() == ISD::XOR || 12660 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 12661 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 12662 BinOps.push_back(BinOp.getOperand(i)); 12663 } else { 12664 // We have an input that is not a truncation or another binary 12665 // operation; we'll abort this transformation. 12666 return SDValue(); 12667 } 12668 } 12669 } 12670 12671 // The operands of a select that must be truncated when the select is 12672 // promoted because the operand is actually part of the to-be-promoted set. 12673 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 12674 12675 // Make sure that this is a self-contained cluster of operations (which 12676 // is not quite the same thing as saying that everything has only one 12677 // use). 12678 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12679 if (isa<ConstantSDNode>(Inputs[i])) 12680 continue; 12681 12682 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), 12683 UE = Inputs[i].getNode()->use_end(); 12684 UI != UE; ++UI) { 12685 SDNode *User = *UI; 12686 if (User != N && !Visited.count(User)) 12687 return SDValue(); 12688 12689 // If we're going to promote the non-output-value operand(s) or SELECT or 12690 // SELECT_CC, record them for truncation. 12691 if (User->getOpcode() == ISD::SELECT) { 12692 if (User->getOperand(0) == Inputs[i]) 12693 SelectTruncOp[0].insert(std::make_pair(User, 12694 User->getOperand(0).getValueType())); 12695 } else if (User->getOpcode() == ISD::SELECT_CC) { 12696 if (User->getOperand(0) == Inputs[i]) 12697 SelectTruncOp[0].insert(std::make_pair(User, 12698 User->getOperand(0).getValueType())); 12699 if (User->getOperand(1) == Inputs[i]) 12700 SelectTruncOp[1].insert(std::make_pair(User, 12701 User->getOperand(1).getValueType())); 12702 } 12703 } 12704 } 12705 12706 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 12707 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), 12708 UE = PromOps[i].getNode()->use_end(); 12709 UI != UE; ++UI) { 12710 SDNode *User = *UI; 12711 if (User != N && !Visited.count(User)) 12712 return SDValue(); 12713 12714 // If we're going to promote the non-output-value operand(s) or SELECT or 12715 // SELECT_CC, record them for truncation. 12716 if (User->getOpcode() == ISD::SELECT) { 12717 if (User->getOperand(0) == PromOps[i]) 12718 SelectTruncOp[0].insert(std::make_pair(User, 12719 User->getOperand(0).getValueType())); 12720 } else if (User->getOpcode() == ISD::SELECT_CC) { 12721 if (User->getOperand(0) == PromOps[i]) 12722 SelectTruncOp[0].insert(std::make_pair(User, 12723 User->getOperand(0).getValueType())); 12724 if (User->getOperand(1) == PromOps[i]) 12725 SelectTruncOp[1].insert(std::make_pair(User, 12726 User->getOperand(1).getValueType())); 12727 } 12728 } 12729 } 12730 12731 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 12732 bool ReallyNeedsExt = false; 12733 if (N->getOpcode() != ISD::ANY_EXTEND) { 12734 // If all of the inputs are not already sign/zero extended, then 12735 // we'll still need to do that at the end. 12736 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12737 if (isa<ConstantSDNode>(Inputs[i])) 12738 continue; 12739 12740 unsigned OpBits = 12741 Inputs[i].getOperand(0).getValueSizeInBits(); 12742 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 12743 12744 if ((N->getOpcode() == ISD::ZERO_EXTEND && 12745 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 12746 APInt::getHighBitsSet(OpBits, 12747 OpBits-PromBits))) || 12748 (N->getOpcode() == ISD::SIGN_EXTEND && 12749 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 12750 (OpBits-(PromBits-1)))) { 12751 ReallyNeedsExt = true; 12752 break; 12753 } 12754 } 12755 } 12756 12757 // Replace all inputs, either with the truncation operand, or a 12758 // truncation or extension to the final output type. 12759 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 12760 // Constant inputs need to be replaced with the to-be-promoted nodes that 12761 // use them because they might have users outside of the cluster of 12762 // promoted nodes. 12763 if (isa<ConstantSDNode>(Inputs[i])) 12764 continue; 12765 12766 SDValue InSrc = Inputs[i].getOperand(0); 12767 if (Inputs[i].getValueType() == N->getValueType(0)) 12768 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 12769 else if (N->getOpcode() == ISD::SIGN_EXTEND) 12770 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12771 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 12772 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12773 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12774 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 12775 else 12776 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 12777 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 12778 } 12779 12780 std::list<HandleSDNode> PromOpHandles; 12781 for (auto &PromOp : PromOps) 12782 PromOpHandles.emplace_back(PromOp); 12783 12784 // Replace all operations (these are all the same, but have a different 12785 // (promoted) return type). DAG.getNode will validate that the types of 12786 // a binary operator match, so go through the list in reverse so that 12787 // we've likely promoted both operands first. 12788 while (!PromOpHandles.empty()) { 12789 SDValue PromOp = PromOpHandles.back().getValue(); 12790 PromOpHandles.pop_back(); 12791 12792 unsigned C; 12793 switch (PromOp.getOpcode()) { 12794 default: C = 0; break; 12795 case ISD::SELECT: C = 1; break; 12796 case ISD::SELECT_CC: C = 2; break; 12797 } 12798 12799 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 12800 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 12801 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 12802 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 12803 // The to-be-promoted operands of this node have not yet been 12804 // promoted (this should be rare because we're going through the 12805 // list backward, but if one of the operands has several users in 12806 // this cluster of to-be-promoted nodes, it is possible). 12807 PromOpHandles.emplace_front(PromOp); 12808 continue; 12809 } 12810 12811 // For SELECT and SELECT_CC nodes, we do a similar check for any 12812 // to-be-promoted comparison inputs. 12813 if (PromOp.getOpcode() == ISD::SELECT || 12814 PromOp.getOpcode() == ISD::SELECT_CC) { 12815 if ((SelectTruncOp[0].count(PromOp.getNode()) && 12816 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 12817 (SelectTruncOp[1].count(PromOp.getNode()) && 12818 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 12819 PromOpHandles.emplace_front(PromOp); 12820 continue; 12821 } 12822 } 12823 12824 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 12825 PromOp.getNode()->op_end()); 12826 12827 // If this node has constant inputs, then they'll need to be promoted here. 12828 for (unsigned i = 0; i < 2; ++i) { 12829 if (!isa<ConstantSDNode>(Ops[C+i])) 12830 continue; 12831 if (Ops[C+i].getValueType() == N->getValueType(0)) 12832 continue; 12833 12834 if (N->getOpcode() == ISD::SIGN_EXTEND) 12835 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12836 else if (N->getOpcode() == ISD::ZERO_EXTEND) 12837 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12838 else 12839 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 12840 } 12841 12842 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 12843 // truncate them again to the original value type. 12844 if (PromOp.getOpcode() == ISD::SELECT || 12845 PromOp.getOpcode() == ISD::SELECT_CC) { 12846 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 12847 if (SI0 != SelectTruncOp[0].end()) 12848 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 12849 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 12850 if (SI1 != SelectTruncOp[1].end()) 12851 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 12852 } 12853 12854 DAG.ReplaceAllUsesOfValueWith(PromOp, 12855 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 12856 } 12857 12858 // Now we're left with the initial extension itself. 12859 if (!ReallyNeedsExt) 12860 return N->getOperand(0); 12861 12862 // To zero extend, just mask off everything except for the first bit (in the 12863 // i1 case). 12864 if (N->getOpcode() == ISD::ZERO_EXTEND) 12865 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 12866 DAG.getConstant(APInt::getLowBitsSet( 12867 N->getValueSizeInBits(0), PromBits), 12868 dl, N->getValueType(0))); 12869 12870 assert(N->getOpcode() == ISD::SIGN_EXTEND && 12871 "Invalid extension type"); 12872 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 12873 SDValue ShiftCst = 12874 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 12875 return DAG.getNode( 12876 ISD::SRA, dl, N->getValueType(0), 12877 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 12878 ShiftCst); 12879 } 12880 12881 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 12882 DAGCombinerInfo &DCI) const { 12883 assert(N->getOpcode() == ISD::SETCC && 12884 "Should be called with a SETCC node"); 12885 12886 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 12887 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 12888 SDValue LHS = N->getOperand(0); 12889 SDValue RHS = N->getOperand(1); 12890 12891 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 12892 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 12893 LHS.hasOneUse()) 12894 std::swap(LHS, RHS); 12895 12896 // x == 0-y --> x+y == 0 12897 // x != 0-y --> x+y != 0 12898 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 12899 RHS.hasOneUse()) { 12900 SDLoc DL(N); 12901 SelectionDAG &DAG = DCI.DAG; 12902 EVT VT = N->getValueType(0); 12903 EVT OpVT = LHS.getValueType(); 12904 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 12905 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 12906 } 12907 } 12908 12909 return DAGCombineTruncBoolExt(N, DCI); 12910 } 12911 12912 // Is this an extending load from an f32 to an f64? 12913 static bool isFPExtLoad(SDValue Op) { 12914 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 12915 return LD->getExtensionType() == ISD::EXTLOAD && 12916 Op.getValueType() == MVT::f64; 12917 return false; 12918 } 12919 12920 /// Reduces the number of fp-to-int conversion when building a vector. 12921 /// 12922 /// If this vector is built out of floating to integer conversions, 12923 /// transform it to a vector built out of floating point values followed by a 12924 /// single floating to integer conversion of the vector. 12925 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 12926 /// becomes (fptosi (build_vector ($A, $B, ...))) 12927 SDValue PPCTargetLowering:: 12928 combineElementTruncationToVectorTruncation(SDNode *N, 12929 DAGCombinerInfo &DCI) const { 12930 assert(N->getOpcode() == ISD::BUILD_VECTOR && 12931 "Should be called with a BUILD_VECTOR node"); 12932 12933 SelectionDAG &DAG = DCI.DAG; 12934 SDLoc dl(N); 12935 12936 SDValue FirstInput = N->getOperand(0); 12937 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 12938 "The input operand must be an fp-to-int conversion."); 12939 12940 // This combine happens after legalization so the fp_to_[su]i nodes are 12941 // already converted to PPCSISD nodes. 12942 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 12943 if (FirstConversion == PPCISD::FCTIDZ || 12944 FirstConversion == PPCISD::FCTIDUZ || 12945 FirstConversion == PPCISD::FCTIWZ || 12946 FirstConversion == PPCISD::FCTIWUZ) { 12947 bool IsSplat = true; 12948 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 12949 FirstConversion == PPCISD::FCTIWUZ; 12950 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 12951 SmallVector<SDValue, 4> Ops; 12952 EVT TargetVT = N->getValueType(0); 12953 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12954 SDValue NextOp = N->getOperand(i); 12955 if (NextOp.getOpcode() != PPCISD::MFVSR) 12956 return SDValue(); 12957 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 12958 if (NextConversion != FirstConversion) 12959 return SDValue(); 12960 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 12961 // This is not valid if the input was originally double precision. It is 12962 // also not profitable to do unless this is an extending load in which 12963 // case doing this combine will allow us to combine consecutive loads. 12964 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 12965 return SDValue(); 12966 if (N->getOperand(i) != FirstInput) 12967 IsSplat = false; 12968 } 12969 12970 // If this is a splat, we leave it as-is since there will be only a single 12971 // fp-to-int conversion followed by a splat of the integer. This is better 12972 // for 32-bit and smaller ints and neutral for 64-bit ints. 12973 if (IsSplat) 12974 return SDValue(); 12975 12976 // Now that we know we have the right type of node, get its operands 12977 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 12978 SDValue In = N->getOperand(i).getOperand(0); 12979 if (Is32Bit) { 12980 // For 32-bit values, we need to add an FP_ROUND node (if we made it 12981 // here, we know that all inputs are extending loads so this is safe). 12982 if (In.isUndef()) 12983 Ops.push_back(DAG.getUNDEF(SrcVT)); 12984 else { 12985 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl, 12986 MVT::f32, In.getOperand(0), 12987 DAG.getIntPtrConstant(1, dl)); 12988 Ops.push_back(Trunc); 12989 } 12990 } else 12991 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 12992 } 12993 12994 unsigned Opcode; 12995 if (FirstConversion == PPCISD::FCTIDZ || 12996 FirstConversion == PPCISD::FCTIWZ) 12997 Opcode = ISD::FP_TO_SINT; 12998 else 12999 Opcode = ISD::FP_TO_UINT; 13000 13001 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 13002 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 13003 return DAG.getNode(Opcode, dl, TargetVT, BV); 13004 } 13005 return SDValue(); 13006 } 13007 13008 /// Reduce the number of loads when building a vector. 13009 /// 13010 /// Building a vector out of multiple loads can be converted to a load 13011 /// of the vector type if the loads are consecutive. If the loads are 13012 /// consecutive but in descending order, a shuffle is added at the end 13013 /// to reorder the vector. 13014 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 13015 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13016 "Should be called with a BUILD_VECTOR node"); 13017 13018 SDLoc dl(N); 13019 13020 // Return early for non byte-sized type, as they can't be consecutive. 13021 if (!N->getValueType(0).getVectorElementType().isByteSized()) 13022 return SDValue(); 13023 13024 bool InputsAreConsecutiveLoads = true; 13025 bool InputsAreReverseConsecutive = true; 13026 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 13027 SDValue FirstInput = N->getOperand(0); 13028 bool IsRoundOfExtLoad = false; 13029 13030 if (FirstInput.getOpcode() == ISD::FP_ROUND && 13031 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 13032 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0)); 13033 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD; 13034 } 13035 // Not a build vector of (possibly fp_rounded) loads. 13036 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 13037 N->getNumOperands() == 1) 13038 return SDValue(); 13039 13040 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 13041 // If any inputs are fp_round(extload), they all must be. 13042 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 13043 return SDValue(); 13044 13045 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 13046 N->getOperand(i); 13047 if (NextInput.getOpcode() != ISD::LOAD) 13048 return SDValue(); 13049 13050 SDValue PreviousInput = 13051 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 13052 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput); 13053 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput); 13054 13055 // If any inputs are fp_round(extload), they all must be. 13056 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 13057 return SDValue(); 13058 13059 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG)) 13060 InputsAreConsecutiveLoads = false; 13061 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG)) 13062 InputsAreReverseConsecutive = false; 13063 13064 // Exit early if the loads are neither consecutive nor reverse consecutive. 13065 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 13066 return SDValue(); 13067 } 13068 13069 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 13070 "The loads cannot be both consecutive and reverse consecutive."); 13071 13072 SDValue FirstLoadOp = 13073 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput; 13074 SDValue LastLoadOp = 13075 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) : 13076 N->getOperand(N->getNumOperands()-1); 13077 13078 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp); 13079 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp); 13080 if (InputsAreConsecutiveLoads) { 13081 assert(LD1 && "Input needs to be a LoadSDNode."); 13082 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(), 13083 LD1->getBasePtr(), LD1->getPointerInfo(), 13084 LD1->getAlignment()); 13085 } 13086 if (InputsAreReverseConsecutive) { 13087 assert(LDL && "Input needs to be a LoadSDNode."); 13088 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(), 13089 LDL->getBasePtr(), LDL->getPointerInfo(), 13090 LDL->getAlignment()); 13091 SmallVector<int, 16> Ops; 13092 for (int i = N->getNumOperands() - 1; i >= 0; i--) 13093 Ops.push_back(i); 13094 13095 return DAG.getVectorShuffle(N->getValueType(0), dl, Load, 13096 DAG.getUNDEF(N->getValueType(0)), Ops); 13097 } 13098 return SDValue(); 13099 } 13100 13101 // This function adds the required vector_shuffle needed to get 13102 // the elements of the vector extract in the correct position 13103 // as specified by the CorrectElems encoding. 13104 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 13105 SDValue Input, uint64_t Elems, 13106 uint64_t CorrectElems) { 13107 SDLoc dl(N); 13108 13109 unsigned NumElems = Input.getValueType().getVectorNumElements(); 13110 SmallVector<int, 16> ShuffleMask(NumElems, -1); 13111 13112 // Knowing the element indices being extracted from the original 13113 // vector and the order in which they're being inserted, just put 13114 // them at element indices required for the instruction. 13115 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13116 if (DAG.getDataLayout().isLittleEndian()) 13117 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 13118 else 13119 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 13120 CorrectElems = CorrectElems >> 8; 13121 Elems = Elems >> 8; 13122 } 13123 13124 SDValue Shuffle = 13125 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 13126 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 13127 13128 EVT Ty = N->getValueType(0); 13129 SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle); 13130 return BV; 13131 } 13132 13133 // Look for build vector patterns where input operands come from sign 13134 // extended vector_extract elements of specific indices. If the correct indices 13135 // aren't used, add a vector shuffle to fix up the indices and create a new 13136 // PPCISD:SExtVElems node which selects the vector sign extend instructions 13137 // during instruction selection. 13138 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 13139 // This array encodes the indices that the vector sign extend instructions 13140 // extract from when extending from one type to another for both BE and LE. 13141 // The right nibble of each byte corresponds to the LE incides. 13142 // and the left nibble of each byte corresponds to the BE incides. 13143 // For example: 0x3074B8FC byte->word 13144 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 13145 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 13146 // For example: 0x000070F8 byte->double word 13147 // For LE: the allowed indices are: 0x0,0x8 13148 // For BE: the allowed indices are: 0x7,0xF 13149 uint64_t TargetElems[] = { 13150 0x3074B8FC, // b->w 13151 0x000070F8, // b->d 13152 0x10325476, // h->w 13153 0x00003074, // h->d 13154 0x00001032, // w->d 13155 }; 13156 13157 uint64_t Elems = 0; 13158 int Index; 13159 SDValue Input; 13160 13161 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 13162 if (!Op) 13163 return false; 13164 if (Op.getOpcode() != ISD::SIGN_EXTEND && 13165 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 13166 return false; 13167 13168 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 13169 // of the right width. 13170 SDValue Extract = Op.getOperand(0); 13171 if (Extract.getOpcode() == ISD::ANY_EXTEND) 13172 Extract = Extract.getOperand(0); 13173 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13174 return false; 13175 13176 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 13177 if (!ExtOp) 13178 return false; 13179 13180 Index = ExtOp->getZExtValue(); 13181 if (Input && Input != Extract.getOperand(0)) 13182 return false; 13183 13184 if (!Input) 13185 Input = Extract.getOperand(0); 13186 13187 Elems = Elems << 8; 13188 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 13189 Elems |= Index; 13190 13191 return true; 13192 }; 13193 13194 // If the build vector operands aren't sign extended vector extracts, 13195 // of the same input vector, then return. 13196 for (unsigned i = 0; i < N->getNumOperands(); i++) { 13197 if (!isSExtOfVecExtract(N->getOperand(i))) { 13198 return SDValue(); 13199 } 13200 } 13201 13202 // If the vector extract indicies are not correct, add the appropriate 13203 // vector_shuffle. 13204 int TgtElemArrayIdx; 13205 int InputSize = Input.getValueType().getScalarSizeInBits(); 13206 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 13207 if (InputSize + OutputSize == 40) 13208 TgtElemArrayIdx = 0; 13209 else if (InputSize + OutputSize == 72) 13210 TgtElemArrayIdx = 1; 13211 else if (InputSize + OutputSize == 48) 13212 TgtElemArrayIdx = 2; 13213 else if (InputSize + OutputSize == 80) 13214 TgtElemArrayIdx = 3; 13215 else if (InputSize + OutputSize == 96) 13216 TgtElemArrayIdx = 4; 13217 else 13218 return SDValue(); 13219 13220 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 13221 CorrectElems = DAG.getDataLayout().isLittleEndian() 13222 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 13223 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 13224 if (Elems != CorrectElems) { 13225 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 13226 } 13227 13228 // Regular lowering will catch cases where a shuffle is not needed. 13229 return SDValue(); 13230 } 13231 13232 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 13233 DAGCombinerInfo &DCI) const { 13234 assert(N->getOpcode() == ISD::BUILD_VECTOR && 13235 "Should be called with a BUILD_VECTOR node"); 13236 13237 SelectionDAG &DAG = DCI.DAG; 13238 SDLoc dl(N); 13239 13240 if (!Subtarget.hasVSX()) 13241 return SDValue(); 13242 13243 // The target independent DAG combiner will leave a build_vector of 13244 // float-to-int conversions intact. We can generate MUCH better code for 13245 // a float-to-int conversion of a vector of floats. 13246 SDValue FirstInput = N->getOperand(0); 13247 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 13248 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 13249 if (Reduced) 13250 return Reduced; 13251 } 13252 13253 // If we're building a vector out of consecutive loads, just load that 13254 // vector type. 13255 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 13256 if (Reduced) 13257 return Reduced; 13258 13259 // If we're building a vector out of extended elements from another vector 13260 // we have P9 vector integer extend instructions. The code assumes legal 13261 // input types (i.e. it can't handle things like v4i16) so do not run before 13262 // legalization. 13263 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 13264 Reduced = combineBVOfVecSExt(N, DAG); 13265 if (Reduced) 13266 return Reduced; 13267 } 13268 13269 13270 if (N->getValueType(0) != MVT::v2f64) 13271 return SDValue(); 13272 13273 // Looking for: 13274 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 13275 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 13276 FirstInput.getOpcode() != ISD::UINT_TO_FP) 13277 return SDValue(); 13278 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 13279 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 13280 return SDValue(); 13281 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 13282 return SDValue(); 13283 13284 SDValue Ext1 = FirstInput.getOperand(0); 13285 SDValue Ext2 = N->getOperand(1).getOperand(0); 13286 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 13287 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 13288 return SDValue(); 13289 13290 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 13291 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 13292 if (!Ext1Op || !Ext2Op) 13293 return SDValue(); 13294 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 13295 Ext1.getOperand(0) != Ext2.getOperand(0)) 13296 return SDValue(); 13297 13298 int FirstElem = Ext1Op->getZExtValue(); 13299 int SecondElem = Ext2Op->getZExtValue(); 13300 int SubvecIdx; 13301 if (FirstElem == 0 && SecondElem == 1) 13302 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 13303 else if (FirstElem == 2 && SecondElem == 3) 13304 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 13305 else 13306 return SDValue(); 13307 13308 SDValue SrcVec = Ext1.getOperand(0); 13309 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 13310 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 13311 return DAG.getNode(NodeType, dl, MVT::v2f64, 13312 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 13313 } 13314 13315 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 13316 DAGCombinerInfo &DCI) const { 13317 assert((N->getOpcode() == ISD::SINT_TO_FP || 13318 N->getOpcode() == ISD::UINT_TO_FP) && 13319 "Need an int -> FP conversion node here"); 13320 13321 if (useSoftFloat() || !Subtarget.has64BitSupport()) 13322 return SDValue(); 13323 13324 SelectionDAG &DAG = DCI.DAG; 13325 SDLoc dl(N); 13326 SDValue Op(N, 0); 13327 13328 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 13329 // from the hardware. 13330 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 13331 return SDValue(); 13332 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 13333 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 13334 return SDValue(); 13335 13336 SDValue FirstOperand(Op.getOperand(0)); 13337 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 13338 (FirstOperand.getValueType() == MVT::i8 || 13339 FirstOperand.getValueType() == MVT::i16); 13340 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 13341 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 13342 bool DstDouble = Op.getValueType() == MVT::f64; 13343 unsigned ConvOp = Signed ? 13344 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 13345 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 13346 SDValue WidthConst = 13347 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 13348 dl, false); 13349 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 13350 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 13351 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 13352 DAG.getVTList(MVT::f64, MVT::Other), 13353 Ops, MVT::i8, LDN->getMemOperand()); 13354 13355 // For signed conversion, we need to sign-extend the value in the VSR 13356 if (Signed) { 13357 SDValue ExtOps[] = { Ld, WidthConst }; 13358 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 13359 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 13360 } else 13361 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 13362 } 13363 13364 13365 // For i32 intermediate values, unfortunately, the conversion functions 13366 // leave the upper 32 bits of the value are undefined. Within the set of 13367 // scalar instructions, we have no method for zero- or sign-extending the 13368 // value. Thus, we cannot handle i32 intermediate values here. 13369 if (Op.getOperand(0).getValueType() == MVT::i32) 13370 return SDValue(); 13371 13372 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 13373 "UINT_TO_FP is supported only with FPCVT"); 13374 13375 // If we have FCFIDS, then use it when converting to single-precision. 13376 // Otherwise, convert to double-precision and then round. 13377 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13378 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 13379 : PPCISD::FCFIDS) 13380 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 13381 : PPCISD::FCFID); 13382 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 13383 ? MVT::f32 13384 : MVT::f64; 13385 13386 // If we're converting from a float, to an int, and back to a float again, 13387 // then we don't need the store/load pair at all. 13388 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 13389 Subtarget.hasFPCVT()) || 13390 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 13391 SDValue Src = Op.getOperand(0).getOperand(0); 13392 if (Src.getValueType() == MVT::f32) { 13393 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 13394 DCI.AddToWorklist(Src.getNode()); 13395 } else if (Src.getValueType() != MVT::f64) { 13396 // Make sure that we don't pick up a ppc_fp128 source value. 13397 return SDValue(); 13398 } 13399 13400 unsigned FCTOp = 13401 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 13402 PPCISD::FCTIDUZ; 13403 13404 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 13405 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 13406 13407 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 13408 FP = DAG.getNode(ISD::FP_ROUND, dl, 13409 MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); 13410 DCI.AddToWorklist(FP.getNode()); 13411 } 13412 13413 return FP; 13414 } 13415 13416 return SDValue(); 13417 } 13418 13419 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 13420 // builtins) into loads with swaps. 13421 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 13422 DAGCombinerInfo &DCI) const { 13423 SelectionDAG &DAG = DCI.DAG; 13424 SDLoc dl(N); 13425 SDValue Chain; 13426 SDValue Base; 13427 MachineMemOperand *MMO; 13428 13429 switch (N->getOpcode()) { 13430 default: 13431 llvm_unreachable("Unexpected opcode for little endian VSX load"); 13432 case ISD::LOAD: { 13433 LoadSDNode *LD = cast<LoadSDNode>(N); 13434 Chain = LD->getChain(); 13435 Base = LD->getBasePtr(); 13436 MMO = LD->getMemOperand(); 13437 // If the MMO suggests this isn't a load of a full vector, leave 13438 // things alone. For a built-in, we have to make the change for 13439 // correctness, so if there is a size problem that will be a bug. 13440 if (MMO->getSize() < 16) 13441 return SDValue(); 13442 break; 13443 } 13444 case ISD::INTRINSIC_W_CHAIN: { 13445 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13446 Chain = Intrin->getChain(); 13447 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 13448 // us what we want. Get operand 2 instead. 13449 Base = Intrin->getOperand(2); 13450 MMO = Intrin->getMemOperand(); 13451 break; 13452 } 13453 } 13454 13455 MVT VecTy = N->getValueType(0).getSimpleVT(); 13456 13457 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is 13458 // aligned and the type is a vector with elements up to 4 bytes 13459 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13460 && VecTy.getScalarSizeInBits() <= 32 ) { 13461 return SDValue(); 13462 } 13463 13464 SDValue LoadOps[] = { Chain, Base }; 13465 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 13466 DAG.getVTList(MVT::v2f64, MVT::Other), 13467 LoadOps, MVT::v2f64, MMO); 13468 13469 DCI.AddToWorklist(Load.getNode()); 13470 Chain = Load.getValue(1); 13471 SDValue Swap = DAG.getNode( 13472 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 13473 DCI.AddToWorklist(Swap.getNode()); 13474 13475 // Add a bitcast if the resulting load type doesn't match v2f64. 13476 if (VecTy != MVT::v2f64) { 13477 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 13478 DCI.AddToWorklist(N.getNode()); 13479 // Package {bitcast value, swap's chain} to match Load's shape. 13480 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 13481 N, Swap.getValue(1)); 13482 } 13483 13484 return Swap; 13485 } 13486 13487 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 13488 // builtins) into stores with swaps. 13489 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 13490 DAGCombinerInfo &DCI) const { 13491 SelectionDAG &DAG = DCI.DAG; 13492 SDLoc dl(N); 13493 SDValue Chain; 13494 SDValue Base; 13495 unsigned SrcOpnd; 13496 MachineMemOperand *MMO; 13497 13498 switch (N->getOpcode()) { 13499 default: 13500 llvm_unreachable("Unexpected opcode for little endian VSX store"); 13501 case ISD::STORE: { 13502 StoreSDNode *ST = cast<StoreSDNode>(N); 13503 Chain = ST->getChain(); 13504 Base = ST->getBasePtr(); 13505 MMO = ST->getMemOperand(); 13506 SrcOpnd = 1; 13507 // If the MMO suggests this isn't a store of a full vector, leave 13508 // things alone. For a built-in, we have to make the change for 13509 // correctness, so if there is a size problem that will be a bug. 13510 if (MMO->getSize() < 16) 13511 return SDValue(); 13512 break; 13513 } 13514 case ISD::INTRINSIC_VOID: { 13515 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 13516 Chain = Intrin->getChain(); 13517 // Intrin->getBasePtr() oddly does not get what we want. 13518 Base = Intrin->getOperand(3); 13519 MMO = Intrin->getMemOperand(); 13520 SrcOpnd = 2; 13521 break; 13522 } 13523 } 13524 13525 SDValue Src = N->getOperand(SrcOpnd); 13526 MVT VecTy = Src.getValueType().getSimpleVT(); 13527 13528 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is 13529 // aligned and the type is a vector with elements up to 4 bytes 13530 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16) 13531 && VecTy.getScalarSizeInBits() <= 32 ) { 13532 return SDValue(); 13533 } 13534 13535 // All stores are done as v2f64 and possible bit cast. 13536 if (VecTy != MVT::v2f64) { 13537 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 13538 DCI.AddToWorklist(Src.getNode()); 13539 } 13540 13541 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 13542 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 13543 DCI.AddToWorklist(Swap.getNode()); 13544 Chain = Swap.getValue(1); 13545 SDValue StoreOps[] = { Chain, Swap, Base }; 13546 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 13547 DAG.getVTList(MVT::Other), 13548 StoreOps, VecTy, MMO); 13549 DCI.AddToWorklist(Store.getNode()); 13550 return Store; 13551 } 13552 13553 // Handle DAG combine for STORE (FP_TO_INT F). 13554 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 13555 DAGCombinerInfo &DCI) const { 13556 13557 SelectionDAG &DAG = DCI.DAG; 13558 SDLoc dl(N); 13559 unsigned Opcode = N->getOperand(1).getOpcode(); 13560 13561 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 13562 && "Not a FP_TO_INT Instruction!"); 13563 13564 SDValue Val = N->getOperand(1).getOperand(0); 13565 EVT Op1VT = N->getOperand(1).getValueType(); 13566 EVT ResVT = Val.getValueType(); 13567 13568 // Floating point types smaller than 32 bits are not legal on Power. 13569 if (ResVT.getScalarSizeInBits() < 32) 13570 return SDValue(); 13571 13572 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 13573 bool ValidTypeForStoreFltAsInt = 13574 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 13575 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 13576 13577 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() || 13578 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 13579 return SDValue(); 13580 13581 // Extend f32 values to f64 13582 if (ResVT.getScalarSizeInBits() == 32) { 13583 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 13584 DCI.AddToWorklist(Val.getNode()); 13585 } 13586 13587 // Set signed or unsigned conversion opcode. 13588 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 13589 PPCISD::FP_TO_SINT_IN_VSR : 13590 PPCISD::FP_TO_UINT_IN_VSR; 13591 13592 Val = DAG.getNode(ConvOpcode, 13593 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 13594 DCI.AddToWorklist(Val.getNode()); 13595 13596 // Set number of bytes being converted. 13597 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 13598 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 13599 DAG.getIntPtrConstant(ByteSize, dl, false), 13600 DAG.getValueType(Op1VT) }; 13601 13602 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 13603 DAG.getVTList(MVT::Other), Ops, 13604 cast<StoreSDNode>(N)->getMemoryVT(), 13605 cast<StoreSDNode>(N)->getMemOperand()); 13606 13607 DCI.AddToWorklist(Val.getNode()); 13608 return Val; 13609 } 13610 13611 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 13612 LSBaseSDNode *LSBase, 13613 DAGCombinerInfo &DCI) const { 13614 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 13615 "Not a reverse memop pattern!"); 13616 13617 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 13618 auto Mask = SVN->getMask(); 13619 int i = 0; 13620 auto I = Mask.rbegin(); 13621 auto E = Mask.rend(); 13622 13623 for (; I != E; ++I) { 13624 if (*I != i) 13625 return false; 13626 i++; 13627 } 13628 return true; 13629 }; 13630 13631 SelectionDAG &DAG = DCI.DAG; 13632 EVT VT = SVN->getValueType(0); 13633 13634 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 13635 return SDValue(); 13636 13637 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 13638 // See comment in PPCVSXSwapRemoval.cpp. 13639 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 13640 if (!Subtarget.hasP9Vector()) 13641 return SDValue(); 13642 13643 if(!IsElementReverse(SVN)) 13644 return SDValue(); 13645 13646 if (LSBase->getOpcode() == ISD::LOAD) { 13647 SDLoc dl(SVN); 13648 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 13649 return DAG.getMemIntrinsicNode( 13650 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 13651 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13652 } 13653 13654 if (LSBase->getOpcode() == ISD::STORE) { 13655 SDLoc dl(LSBase); 13656 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 13657 LSBase->getBasePtr()}; 13658 return DAG.getMemIntrinsicNode( 13659 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 13660 LSBase->getMemoryVT(), LSBase->getMemOperand()); 13661 } 13662 13663 llvm_unreachable("Expected a load or store node here"); 13664 } 13665 13666 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 13667 DAGCombinerInfo &DCI) const { 13668 SelectionDAG &DAG = DCI.DAG; 13669 SDLoc dl(N); 13670 switch (N->getOpcode()) { 13671 default: break; 13672 case ISD::ADD: 13673 return combineADD(N, DCI); 13674 case ISD::SHL: 13675 return combineSHL(N, DCI); 13676 case ISD::SRA: 13677 return combineSRA(N, DCI); 13678 case ISD::SRL: 13679 return combineSRL(N, DCI); 13680 case ISD::MUL: 13681 return combineMUL(N, DCI); 13682 case PPCISD::SHL: 13683 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 13684 return N->getOperand(0); 13685 break; 13686 case PPCISD::SRL: 13687 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 13688 return N->getOperand(0); 13689 break; 13690 case PPCISD::SRA: 13691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 13692 if (C->isNullValue() || // 0 >>s V -> 0. 13693 C->isAllOnesValue()) // -1 >>s V -> -1. 13694 return N->getOperand(0); 13695 } 13696 break; 13697 case ISD::SIGN_EXTEND: 13698 case ISD::ZERO_EXTEND: 13699 case ISD::ANY_EXTEND: 13700 return DAGCombineExtBoolTrunc(N, DCI); 13701 case ISD::TRUNCATE: 13702 return combineTRUNCATE(N, DCI); 13703 case ISD::SETCC: 13704 if (SDValue CSCC = combineSetCC(N, DCI)) 13705 return CSCC; 13706 LLVM_FALLTHROUGH; 13707 case ISD::SELECT_CC: 13708 return DAGCombineTruncBoolExt(N, DCI); 13709 case ISD::SINT_TO_FP: 13710 case ISD::UINT_TO_FP: 13711 return combineFPToIntToFP(N, DCI); 13712 case ISD::VECTOR_SHUFFLE: 13713 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 13714 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 13715 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 13716 } 13717 break; 13718 case ISD::STORE: { 13719 13720 EVT Op1VT = N->getOperand(1).getValueType(); 13721 unsigned Opcode = N->getOperand(1).getOpcode(); 13722 13723 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 13724 SDValue Val= combineStoreFPToInt(N, DCI); 13725 if (Val) 13726 return Val; 13727 } 13728 13729 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 13730 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 13731 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 13732 if (Val) 13733 return Val; 13734 } 13735 13736 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 13737 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 13738 N->getOperand(1).getNode()->hasOneUse() && 13739 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 13740 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 13741 13742 // STBRX can only handle simple types and it makes no sense to store less 13743 // two bytes in byte-reversed order. 13744 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 13745 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 13746 break; 13747 13748 SDValue BSwapOp = N->getOperand(1).getOperand(0); 13749 // Do an any-extend to 32-bits if this is a half-word input. 13750 if (BSwapOp.getValueType() == MVT::i16) 13751 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 13752 13753 // If the type of BSWAP operand is wider than stored memory width 13754 // it need to be shifted to the right side before STBRX. 13755 if (Op1VT.bitsGT(mVT)) { 13756 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 13757 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 13758 DAG.getConstant(Shift, dl, MVT::i32)); 13759 // Need to truncate if this is a bswap of i64 stored as i32/i16. 13760 if (Op1VT == MVT::i64) 13761 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 13762 } 13763 13764 SDValue Ops[] = { 13765 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 13766 }; 13767 return 13768 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 13769 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 13770 cast<StoreSDNode>(N)->getMemOperand()); 13771 } 13772 13773 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 13774 // So it can increase the chance of CSE constant construction. 13775 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 13776 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 13777 // Need to sign-extended to 64-bits to handle negative values. 13778 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 13779 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 13780 MemVT.getSizeInBits()); 13781 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 13782 13783 // DAG.getTruncStore() can't be used here because it doesn't accept 13784 // the general (base + offset) addressing mode. 13785 // So we use UpdateNodeOperands and setTruncatingStore instead. 13786 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 13787 N->getOperand(3)); 13788 cast<StoreSDNode>(N)->setTruncatingStore(true); 13789 return SDValue(N, 0); 13790 } 13791 13792 // For little endian, VSX stores require generating xxswapd/lxvd2x. 13793 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 13794 if (Op1VT.isSimple()) { 13795 MVT StoreVT = Op1VT.getSimpleVT(); 13796 if (Subtarget.needsSwapsForVSXMemOps() && 13797 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 13798 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 13799 return expandVSXStoreForLE(N, DCI); 13800 } 13801 break; 13802 } 13803 case ISD::LOAD: { 13804 LoadSDNode *LD = cast<LoadSDNode>(N); 13805 EVT VT = LD->getValueType(0); 13806 13807 // For little endian, VSX loads require generating lxvd2x/xxswapd. 13808 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 13809 if (VT.isSimple()) { 13810 MVT LoadVT = VT.getSimpleVT(); 13811 if (Subtarget.needsSwapsForVSXMemOps() && 13812 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 13813 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 13814 return expandVSXLoadForLE(N, DCI); 13815 } 13816 13817 // We sometimes end up with a 64-bit integer load, from which we extract 13818 // two single-precision floating-point numbers. This happens with 13819 // std::complex<float>, and other similar structures, because of the way we 13820 // canonicalize structure copies. However, if we lack direct moves, 13821 // then the final bitcasts from the extracted integer values to the 13822 // floating-point numbers turn into store/load pairs. Even with direct moves, 13823 // just loading the two floating-point numbers is likely better. 13824 auto ReplaceTwoFloatLoad = [&]() { 13825 if (VT != MVT::i64) 13826 return false; 13827 13828 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 13829 LD->isVolatile()) 13830 return false; 13831 13832 // We're looking for a sequence like this: 13833 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 13834 // t16: i64 = srl t13, Constant:i32<32> 13835 // t17: i32 = truncate t16 13836 // t18: f32 = bitcast t17 13837 // t19: i32 = truncate t13 13838 // t20: f32 = bitcast t19 13839 13840 if (!LD->hasNUsesOfValue(2, 0)) 13841 return false; 13842 13843 auto UI = LD->use_begin(); 13844 while (UI.getUse().getResNo() != 0) ++UI; 13845 SDNode *Trunc = *UI++; 13846 while (UI.getUse().getResNo() != 0) ++UI; 13847 SDNode *RightShift = *UI; 13848 if (Trunc->getOpcode() != ISD::TRUNCATE) 13849 std::swap(Trunc, RightShift); 13850 13851 if (Trunc->getOpcode() != ISD::TRUNCATE || 13852 Trunc->getValueType(0) != MVT::i32 || 13853 !Trunc->hasOneUse()) 13854 return false; 13855 if (RightShift->getOpcode() != ISD::SRL || 13856 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 13857 RightShift->getConstantOperandVal(1) != 32 || 13858 !RightShift->hasOneUse()) 13859 return false; 13860 13861 SDNode *Trunc2 = *RightShift->use_begin(); 13862 if (Trunc2->getOpcode() != ISD::TRUNCATE || 13863 Trunc2->getValueType(0) != MVT::i32 || 13864 !Trunc2->hasOneUse()) 13865 return false; 13866 13867 SDNode *Bitcast = *Trunc->use_begin(); 13868 SDNode *Bitcast2 = *Trunc2->use_begin(); 13869 13870 if (Bitcast->getOpcode() != ISD::BITCAST || 13871 Bitcast->getValueType(0) != MVT::f32) 13872 return false; 13873 if (Bitcast2->getOpcode() != ISD::BITCAST || 13874 Bitcast2->getValueType(0) != MVT::f32) 13875 return false; 13876 13877 if (Subtarget.isLittleEndian()) 13878 std::swap(Bitcast, Bitcast2); 13879 13880 // Bitcast has the second float (in memory-layout order) and Bitcast2 13881 // has the first one. 13882 13883 SDValue BasePtr = LD->getBasePtr(); 13884 if (LD->isIndexed()) { 13885 assert(LD->getAddressingMode() == ISD::PRE_INC && 13886 "Non-pre-inc AM on PPC?"); 13887 BasePtr = 13888 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 13889 LD->getOffset()); 13890 } 13891 13892 auto MMOFlags = 13893 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 13894 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 13895 LD->getPointerInfo(), LD->getAlignment(), 13896 MMOFlags, LD->getAAInfo()); 13897 SDValue AddPtr = 13898 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 13899 BasePtr, DAG.getIntPtrConstant(4, dl)); 13900 SDValue FloatLoad2 = DAG.getLoad( 13901 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 13902 LD->getPointerInfo().getWithOffset(4), 13903 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo()); 13904 13905 if (LD->isIndexed()) { 13906 // Note that DAGCombine should re-form any pre-increment load(s) from 13907 // what is produced here if that makes sense. 13908 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 13909 } 13910 13911 DCI.CombineTo(Bitcast2, FloatLoad); 13912 DCI.CombineTo(Bitcast, FloatLoad2); 13913 13914 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 13915 SDValue(FloatLoad2.getNode(), 1)); 13916 return true; 13917 }; 13918 13919 if (ReplaceTwoFloatLoad()) 13920 return SDValue(N, 0); 13921 13922 EVT MemVT = LD->getMemoryVT(); 13923 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 13924 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); 13925 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); 13926 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); 13927 if (LD->isUnindexed() && VT.isVector() && 13928 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 13929 // P8 and later hardware should just use LOAD. 13930 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || 13931 VT == MVT::v4i32 || VT == MVT::v4f32)) || 13932 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && 13933 LD->getAlignment() >= ScalarABIAlignment)) && 13934 LD->getAlignment() < ABIAlignment) { 13935 // This is a type-legal unaligned Altivec or QPX load. 13936 SDValue Chain = LD->getChain(); 13937 SDValue Ptr = LD->getBasePtr(); 13938 bool isLittleEndian = Subtarget.isLittleEndian(); 13939 13940 // This implements the loading of unaligned vectors as described in 13941 // the venerable Apple Velocity Engine overview. Specifically: 13942 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 13943 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 13944 // 13945 // The general idea is to expand a sequence of one or more unaligned 13946 // loads into an alignment-based permutation-control instruction (lvsl 13947 // or lvsr), a series of regular vector loads (which always truncate 13948 // their input address to an aligned address), and a series of 13949 // permutations. The results of these permutations are the requested 13950 // loaded values. The trick is that the last "extra" load is not taken 13951 // from the address you might suspect (sizeof(vector) bytes after the 13952 // last requested load), but rather sizeof(vector) - 1 bytes after the 13953 // last requested vector. The point of this is to avoid a page fault if 13954 // the base address happened to be aligned. This works because if the 13955 // base address is aligned, then adding less than a full vector length 13956 // will cause the last vector in the sequence to be (re)loaded. 13957 // Otherwise, the next vector will be fetched as you might suspect was 13958 // necessary. 13959 13960 // We might be able to reuse the permutation generation from 13961 // a different base address offset from this one by an aligned amount. 13962 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 13963 // optimization later. 13964 Intrinsic::ID Intr, IntrLD, IntrPerm; 13965 MVT PermCntlTy, PermTy, LDTy; 13966 if (Subtarget.hasAltivec()) { 13967 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : 13968 Intrinsic::ppc_altivec_lvsl; 13969 IntrLD = Intrinsic::ppc_altivec_lvx; 13970 IntrPerm = Intrinsic::ppc_altivec_vperm; 13971 PermCntlTy = MVT::v16i8; 13972 PermTy = MVT::v4i32; 13973 LDTy = MVT::v4i32; 13974 } else { 13975 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : 13976 Intrinsic::ppc_qpx_qvlpcls; 13977 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : 13978 Intrinsic::ppc_qpx_qvlfs; 13979 IntrPerm = Intrinsic::ppc_qpx_qvfperm; 13980 PermCntlTy = MVT::v4f64; 13981 PermTy = MVT::v4f64; 13982 LDTy = MemVT.getSimpleVT(); 13983 } 13984 13985 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 13986 13987 // Create the new MMO for the new base load. It is like the original MMO, 13988 // but represents an area in memory almost twice the vector size centered 13989 // on the original address. If the address is unaligned, we might start 13990 // reading up to (sizeof(vector)-1) bytes below the address of the 13991 // original unaligned load. 13992 MachineFunction &MF = DAG.getMachineFunction(); 13993 MachineMemOperand *BaseMMO = 13994 MF.getMachineMemOperand(LD->getMemOperand(), 13995 -(long)MemVT.getStoreSize()+1, 13996 2*MemVT.getStoreSize()-1); 13997 13998 // Create the new base load. 13999 SDValue LDXIntID = 14000 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 14001 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 14002 SDValue BaseLoad = 14003 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14004 DAG.getVTList(PermTy, MVT::Other), 14005 BaseLoadOps, LDTy, BaseMMO); 14006 14007 // Note that the value of IncOffset (which is provided to the next 14008 // load's pointer info offset value, and thus used to calculate the 14009 // alignment), and the value of IncValue (which is actually used to 14010 // increment the pointer value) are different! This is because we 14011 // require the next load to appear to be aligned, even though it 14012 // is actually offset from the base pointer by a lesser amount. 14013 int IncOffset = VT.getSizeInBits() / 8; 14014 int IncValue = IncOffset; 14015 14016 // Walk (both up and down) the chain looking for another load at the real 14017 // (aligned) offset (the alignment of the other load does not matter in 14018 // this case). If found, then do not use the offset reduction trick, as 14019 // that will prevent the loads from being later combined (as they would 14020 // otherwise be duplicates). 14021 if (!findConsecutiveLoad(LD, DAG)) 14022 --IncValue; 14023 14024 SDValue Increment = 14025 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 14026 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 14027 14028 MachineMemOperand *ExtraMMO = 14029 MF.getMachineMemOperand(LD->getMemOperand(), 14030 1, 2*MemVT.getStoreSize()-1); 14031 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 14032 SDValue ExtraLoad = 14033 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 14034 DAG.getVTList(PermTy, MVT::Other), 14035 ExtraLoadOps, LDTy, ExtraMMO); 14036 14037 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 14038 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 14039 14040 // Because vperm has a big-endian bias, we must reverse the order 14041 // of the input vectors and complement the permute control vector 14042 // when generating little endian code. We have already handled the 14043 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 14044 // and ExtraLoad here. 14045 SDValue Perm; 14046 if (isLittleEndian) 14047 Perm = BuildIntrinsicOp(IntrPerm, 14048 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 14049 else 14050 Perm = BuildIntrinsicOp(IntrPerm, 14051 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 14052 14053 if (VT != PermTy) 14054 Perm = Subtarget.hasAltivec() ? 14055 DAG.getNode(ISD::BITCAST, dl, VT, Perm) : 14056 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX 14057 DAG.getTargetConstant(1, dl, MVT::i64)); 14058 // second argument is 1 because this rounding 14059 // is always exact. 14060 14061 // The output of the permutation is our loaded result, the TokenFactor is 14062 // our new chain. 14063 DCI.CombineTo(N, Perm, TF); 14064 return SDValue(N, 0); 14065 } 14066 } 14067 break; 14068 case ISD::INTRINSIC_WO_CHAIN: { 14069 bool isLittleEndian = Subtarget.isLittleEndian(); 14070 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 14071 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 14072 : Intrinsic::ppc_altivec_lvsl); 14073 if ((IID == Intr || 14074 IID == Intrinsic::ppc_qpx_qvlpcld || 14075 IID == Intrinsic::ppc_qpx_qvlpcls) && 14076 N->getOperand(1)->getOpcode() == ISD::ADD) { 14077 SDValue Add = N->getOperand(1); 14078 14079 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 14080 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; 14081 14082 if (DAG.MaskedValueIsZero(Add->getOperand(1), 14083 APInt::getAllOnesValue(Bits /* alignment */) 14084 .zext(Add.getScalarValueSizeInBits()))) { 14085 SDNode *BasePtr = Add->getOperand(0).getNode(); 14086 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14087 UE = BasePtr->use_end(); 14088 UI != UE; ++UI) { 14089 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14090 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { 14091 // We've found another LVSL/LVSR, and this address is an aligned 14092 // multiple of that one. The results will be the same, so use the 14093 // one we've just found instead. 14094 14095 return SDValue(*UI, 0); 14096 } 14097 } 14098 } 14099 14100 if (isa<ConstantSDNode>(Add->getOperand(1))) { 14101 SDNode *BasePtr = Add->getOperand(0).getNode(); 14102 for (SDNode::use_iterator UI = BasePtr->use_begin(), 14103 UE = BasePtr->use_end(); UI != UE; ++UI) { 14104 if (UI->getOpcode() == ISD::ADD && 14105 isa<ConstantSDNode>(UI->getOperand(1)) && 14106 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 14107 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % 14108 (1ULL << Bits) == 0) { 14109 SDNode *OtherAdd = *UI; 14110 for (SDNode::use_iterator VI = OtherAdd->use_begin(), 14111 VE = OtherAdd->use_end(); VI != VE; ++VI) { 14112 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14113 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { 14114 return SDValue(*VI, 0); 14115 } 14116 } 14117 } 14118 } 14119 } 14120 } 14121 14122 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 14123 // Expose the vabsduw/h/b opportunity for down stream 14124 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 14125 (IID == Intrinsic::ppc_altivec_vmaxsw || 14126 IID == Intrinsic::ppc_altivec_vmaxsh || 14127 IID == Intrinsic::ppc_altivec_vmaxsb)) { 14128 SDValue V1 = N->getOperand(1); 14129 SDValue V2 = N->getOperand(2); 14130 if ((V1.getSimpleValueType() == MVT::v4i32 || 14131 V1.getSimpleValueType() == MVT::v8i16 || 14132 V1.getSimpleValueType() == MVT::v16i8) && 14133 V1.getSimpleValueType() == V2.getSimpleValueType()) { 14134 // (0-a, a) 14135 if (V1.getOpcode() == ISD::SUB && 14136 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 14137 V1.getOperand(1) == V2) { 14138 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 14139 } 14140 // (a, 0-a) 14141 if (V2.getOpcode() == ISD::SUB && 14142 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 14143 V2.getOperand(1) == V1) { 14144 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14145 } 14146 // (x-y, y-x) 14147 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 14148 V1.getOperand(0) == V2.getOperand(1) && 14149 V1.getOperand(1) == V2.getOperand(0)) { 14150 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 14151 } 14152 } 14153 } 14154 } 14155 14156 break; 14157 case ISD::INTRINSIC_W_CHAIN: 14158 // For little endian, VSX loads require generating lxvd2x/xxswapd. 14159 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 14160 if (Subtarget.needsSwapsForVSXMemOps()) { 14161 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14162 default: 14163 break; 14164 case Intrinsic::ppc_vsx_lxvw4x: 14165 case Intrinsic::ppc_vsx_lxvd2x: 14166 return expandVSXLoadForLE(N, DCI); 14167 } 14168 } 14169 break; 14170 case ISD::INTRINSIC_VOID: 14171 // For little endian, VSX stores require generating xxswapd/stxvd2x. 14172 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 14173 if (Subtarget.needsSwapsForVSXMemOps()) { 14174 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 14175 default: 14176 break; 14177 case Intrinsic::ppc_vsx_stxvw4x: 14178 case Intrinsic::ppc_vsx_stxvd2x: 14179 return expandVSXStoreForLE(N, DCI); 14180 } 14181 } 14182 break; 14183 case ISD::BSWAP: 14184 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 14185 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && 14186 N->getOperand(0).hasOneUse() && 14187 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 14188 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && 14189 N->getValueType(0) == MVT::i64))) { 14190 SDValue Load = N->getOperand(0); 14191 LoadSDNode *LD = cast<LoadSDNode>(Load); 14192 // Create the byte-swapping load. 14193 SDValue Ops[] = { 14194 LD->getChain(), // Chain 14195 LD->getBasePtr(), // Ptr 14196 DAG.getValueType(N->getValueType(0)) // VT 14197 }; 14198 SDValue BSLoad = 14199 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 14200 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 14201 MVT::i64 : MVT::i32, MVT::Other), 14202 Ops, LD->getMemoryVT(), LD->getMemOperand()); 14203 14204 // If this is an i16 load, insert the truncate. 14205 SDValue ResVal = BSLoad; 14206 if (N->getValueType(0) == MVT::i16) 14207 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 14208 14209 // First, combine the bswap away. This makes the value produced by the 14210 // load dead. 14211 DCI.CombineTo(N, ResVal); 14212 14213 // Next, combine the load away, we give it a bogus result value but a real 14214 // chain result. The result value is dead because the bswap is dead. 14215 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 14216 14217 // Return N so it doesn't get rechecked! 14218 return SDValue(N, 0); 14219 } 14220 break; 14221 case PPCISD::VCMP: 14222 // If a VCMPo node already exists with exactly the same operands as this 14223 // node, use its result instead of this node (VCMPo computes both a CR6 and 14224 // a normal output). 14225 // 14226 if (!N->getOperand(0).hasOneUse() && 14227 !N->getOperand(1).hasOneUse() && 14228 !N->getOperand(2).hasOneUse()) { 14229 14230 // Scan all of the users of the LHS, looking for VCMPo's that match. 14231 SDNode *VCMPoNode = nullptr; 14232 14233 SDNode *LHSN = N->getOperand(0).getNode(); 14234 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 14235 UI != E; ++UI) 14236 if (UI->getOpcode() == PPCISD::VCMPo && 14237 UI->getOperand(1) == N->getOperand(1) && 14238 UI->getOperand(2) == N->getOperand(2) && 14239 UI->getOperand(0) == N->getOperand(0)) { 14240 VCMPoNode = *UI; 14241 break; 14242 } 14243 14244 // If there is no VCMPo node, or if the flag value has a single use, don't 14245 // transform this. 14246 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) 14247 break; 14248 14249 // Look at the (necessarily single) use of the flag value. If it has a 14250 // chain, this transformation is more complex. Note that multiple things 14251 // could use the value result, which we should ignore. 14252 SDNode *FlagUser = nullptr; 14253 for (SDNode::use_iterator UI = VCMPoNode->use_begin(); 14254 FlagUser == nullptr; ++UI) { 14255 assert(UI != VCMPoNode->use_end() && "Didn't find user!"); 14256 SDNode *User = *UI; 14257 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 14258 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { 14259 FlagUser = User; 14260 break; 14261 } 14262 } 14263 } 14264 14265 // If the user is a MFOCRF instruction, we know this is safe. 14266 // Otherwise we give up for right now. 14267 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 14268 return SDValue(VCMPoNode, 0); 14269 } 14270 break; 14271 case ISD::BRCOND: { 14272 SDValue Cond = N->getOperand(1); 14273 SDValue Target = N->getOperand(2); 14274 14275 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14276 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == 14277 Intrinsic::loop_decrement) { 14278 14279 // We now need to make the intrinsic dead (it cannot be instruction 14280 // selected). 14281 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); 14282 assert(Cond.getNode()->hasOneUse() && 14283 "Counter decrement has more than one use"); 14284 14285 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, 14286 N->getOperand(0), Target); 14287 } 14288 } 14289 break; 14290 case ISD::BR_CC: { 14291 // If this is a branch on an altivec predicate comparison, lower this so 14292 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 14293 // lowering is done pre-legalize, because the legalizer lowers the predicate 14294 // compare down to code that is difficult to reassemble. 14295 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 14296 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 14297 14298 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero 14299 // value. If so, pass-through the AND to get to the intrinsic. 14300 if (LHS.getOpcode() == ISD::AND && 14301 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && 14302 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == 14303 Intrinsic::loop_decrement && 14304 isa<ConstantSDNode>(LHS.getOperand(1)) && 14305 !isNullConstant(LHS.getOperand(1))) 14306 LHS = LHS.getOperand(0); 14307 14308 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 14309 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == 14310 Intrinsic::loop_decrement && 14311 isa<ConstantSDNode>(RHS)) { 14312 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 14313 "Counter decrement comparison is not EQ or NE"); 14314 14315 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14316 bool isBDNZ = (CC == ISD::SETEQ && Val) || 14317 (CC == ISD::SETNE && !Val); 14318 14319 // We now need to make the intrinsic dead (it cannot be instruction 14320 // selected). 14321 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); 14322 assert(LHS.getNode()->hasOneUse() && 14323 "Counter decrement has more than one use"); 14324 14325 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, 14326 N->getOperand(0), N->getOperand(4)); 14327 } 14328 14329 int CompareOpc; 14330 bool isDot; 14331 14332 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 14333 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && 14334 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 14335 assert(isDot && "Can't compare against a vector result!"); 14336 14337 // If this is a comparison against something other than 0/1, then we know 14338 // that the condition is never/always true. 14339 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); 14340 if (Val != 0 && Val != 1) { 14341 if (CC == ISD::SETEQ) // Cond never true, remove branch. 14342 return N->getOperand(0); 14343 // Always !=, turn it into an unconditional branch. 14344 return DAG.getNode(ISD::BR, dl, MVT::Other, 14345 N->getOperand(0), N->getOperand(4)); 14346 } 14347 14348 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 14349 14350 // Create the PPCISD altivec 'dot' comparison node. 14351 SDValue Ops[] = { 14352 LHS.getOperand(2), // LHS of compare 14353 LHS.getOperand(3), // RHS of compare 14354 DAG.getConstant(CompareOpc, dl, MVT::i32) 14355 }; 14356 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 14357 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); 14358 14359 // Unpack the result based on how the target uses it. 14360 PPC::Predicate CompOpc; 14361 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 14362 default: // Can't happen, don't crash on invalid number though. 14363 case 0: // Branch on the value of the EQ bit of CR6. 14364 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 14365 break; 14366 case 1: // Branch on the inverted value of the EQ bit of CR6. 14367 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 14368 break; 14369 case 2: // Branch on the value of the LT bit of CR6. 14370 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 14371 break; 14372 case 3: // Branch on the inverted value of the LT bit of CR6. 14373 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 14374 break; 14375 } 14376 14377 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 14378 DAG.getConstant(CompOpc, dl, MVT::i32), 14379 DAG.getRegister(PPC::CR6, MVT::i32), 14380 N->getOperand(4), CompNode.getValue(1)); 14381 } 14382 break; 14383 } 14384 case ISD::BUILD_VECTOR: 14385 return DAGCombineBuildVector(N, DCI); 14386 case ISD::ABS: 14387 return combineABS(N, DCI); 14388 case ISD::VSELECT: 14389 return combineVSelect(N, DCI); 14390 } 14391 14392 return SDValue(); 14393 } 14394 14395 SDValue 14396 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 14397 SelectionDAG &DAG, 14398 SmallVectorImpl<SDNode *> &Created) const { 14399 // fold (sdiv X, pow2) 14400 EVT VT = N->getValueType(0); 14401 if (VT == MVT::i64 && !Subtarget.isPPC64()) 14402 return SDValue(); 14403 if ((VT != MVT::i32 && VT != MVT::i64) || 14404 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 14405 return SDValue(); 14406 14407 SDLoc DL(N); 14408 SDValue N0 = N->getOperand(0); 14409 14410 bool IsNegPow2 = (-Divisor).isPowerOf2(); 14411 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 14412 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 14413 14414 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 14415 Created.push_back(Op.getNode()); 14416 14417 if (IsNegPow2) { 14418 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 14419 Created.push_back(Op.getNode()); 14420 } 14421 14422 return Op; 14423 } 14424 14425 //===----------------------------------------------------------------------===// 14426 // Inline Assembly Support 14427 //===----------------------------------------------------------------------===// 14428 14429 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 14430 KnownBits &Known, 14431 const APInt &DemandedElts, 14432 const SelectionDAG &DAG, 14433 unsigned Depth) const { 14434 Known.resetAll(); 14435 switch (Op.getOpcode()) { 14436 default: break; 14437 case PPCISD::LBRX: { 14438 // lhbrx is known to have the top bits cleared out. 14439 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 14440 Known.Zero = 0xFFFF0000; 14441 break; 14442 } 14443 case ISD::INTRINSIC_WO_CHAIN: { 14444 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 14445 default: break; 14446 case Intrinsic::ppc_altivec_vcmpbfp_p: 14447 case Intrinsic::ppc_altivec_vcmpeqfp_p: 14448 case Intrinsic::ppc_altivec_vcmpequb_p: 14449 case Intrinsic::ppc_altivec_vcmpequh_p: 14450 case Intrinsic::ppc_altivec_vcmpequw_p: 14451 case Intrinsic::ppc_altivec_vcmpequd_p: 14452 case Intrinsic::ppc_altivec_vcmpgefp_p: 14453 case Intrinsic::ppc_altivec_vcmpgtfp_p: 14454 case Intrinsic::ppc_altivec_vcmpgtsb_p: 14455 case Intrinsic::ppc_altivec_vcmpgtsh_p: 14456 case Intrinsic::ppc_altivec_vcmpgtsw_p: 14457 case Intrinsic::ppc_altivec_vcmpgtsd_p: 14458 case Intrinsic::ppc_altivec_vcmpgtub_p: 14459 case Intrinsic::ppc_altivec_vcmpgtuh_p: 14460 case Intrinsic::ppc_altivec_vcmpgtuw_p: 14461 case Intrinsic::ppc_altivec_vcmpgtud_p: 14462 Known.Zero = ~1U; // All bits but the low one are known to be zero. 14463 break; 14464 } 14465 } 14466 } 14467 } 14468 14469 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 14470 switch (Subtarget.getCPUDirective()) { 14471 default: break; 14472 case PPC::DIR_970: 14473 case PPC::DIR_PWR4: 14474 case PPC::DIR_PWR5: 14475 case PPC::DIR_PWR5X: 14476 case PPC::DIR_PWR6: 14477 case PPC::DIR_PWR6X: 14478 case PPC::DIR_PWR7: 14479 case PPC::DIR_PWR8: 14480 case PPC::DIR_PWR9: 14481 case PPC::DIR_PWR_FUTURE: { 14482 if (!ML) 14483 break; 14484 14485 if (!DisableInnermostLoopAlign32) { 14486 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 14487 // so that we can decrease cache misses and branch-prediction misses. 14488 // Actual alignment of the loop will depend on the hotness check and other 14489 // logic in alignBlocks. 14490 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 14491 return Align(32); 14492 } 14493 14494 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 14495 14496 // For small loops (between 5 and 8 instructions), align to a 32-byte 14497 // boundary so that the entire loop fits in one instruction-cache line. 14498 uint64_t LoopSize = 0; 14499 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 14500 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { 14501 LoopSize += TII->getInstSizeInBytes(*J); 14502 if (LoopSize > 32) 14503 break; 14504 } 14505 14506 if (LoopSize > 16 && LoopSize <= 32) 14507 return Align(32); 14508 14509 break; 14510 } 14511 } 14512 14513 return TargetLowering::getPrefLoopAlignment(ML); 14514 } 14515 14516 /// getConstraintType - Given a constraint, return the type of 14517 /// constraint it is for this target. 14518 PPCTargetLowering::ConstraintType 14519 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 14520 if (Constraint.size() == 1) { 14521 switch (Constraint[0]) { 14522 default: break; 14523 case 'b': 14524 case 'r': 14525 case 'f': 14526 case 'd': 14527 case 'v': 14528 case 'y': 14529 return C_RegisterClass; 14530 case 'Z': 14531 // FIXME: While Z does indicate a memory constraint, it specifically 14532 // indicates an r+r address (used in conjunction with the 'y' modifier 14533 // in the replacement string). Currently, we're forcing the base 14534 // register to be r0 in the asm printer (which is interpreted as zero) 14535 // and forming the complete address in the second register. This is 14536 // suboptimal. 14537 return C_Memory; 14538 } 14539 } else if (Constraint == "wc") { // individual CR bits. 14540 return C_RegisterClass; 14541 } else if (Constraint == "wa" || Constraint == "wd" || 14542 Constraint == "wf" || Constraint == "ws" || 14543 Constraint == "wi" || Constraint == "ww") { 14544 return C_RegisterClass; // VSX registers. 14545 } 14546 return TargetLowering::getConstraintType(Constraint); 14547 } 14548 14549 /// Examine constraint type and operand type and determine a weight value. 14550 /// This object must already have been set up with the operand type 14551 /// and the current alternative constraint selected. 14552 TargetLowering::ConstraintWeight 14553 PPCTargetLowering::getSingleConstraintMatchWeight( 14554 AsmOperandInfo &info, const char *constraint) const { 14555 ConstraintWeight weight = CW_Invalid; 14556 Value *CallOperandVal = info.CallOperandVal; 14557 // If we don't have a value, we can't do a match, 14558 // but allow it at the lowest weight. 14559 if (!CallOperandVal) 14560 return CW_Default; 14561 Type *type = CallOperandVal->getType(); 14562 14563 // Look at the constraint type. 14564 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 14565 return CW_Register; // an individual CR bit. 14566 else if ((StringRef(constraint) == "wa" || 14567 StringRef(constraint) == "wd" || 14568 StringRef(constraint) == "wf") && 14569 type->isVectorTy()) 14570 return CW_Register; 14571 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 14572 return CW_Register; // just hold 64-bit integers data. 14573 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 14574 return CW_Register; 14575 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 14576 return CW_Register; 14577 14578 switch (*constraint) { 14579 default: 14580 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 14581 break; 14582 case 'b': 14583 if (type->isIntegerTy()) 14584 weight = CW_Register; 14585 break; 14586 case 'f': 14587 if (type->isFloatTy()) 14588 weight = CW_Register; 14589 break; 14590 case 'd': 14591 if (type->isDoubleTy()) 14592 weight = CW_Register; 14593 break; 14594 case 'v': 14595 if (type->isVectorTy()) 14596 weight = CW_Register; 14597 break; 14598 case 'y': 14599 weight = CW_Register; 14600 break; 14601 case 'Z': 14602 weight = CW_Memory; 14603 break; 14604 } 14605 return weight; 14606 } 14607 14608 std::pair<unsigned, const TargetRegisterClass *> 14609 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 14610 StringRef Constraint, 14611 MVT VT) const { 14612 if (Constraint.size() == 1) { 14613 // GCC RS6000 Constraint Letters 14614 switch (Constraint[0]) { 14615 case 'b': // R1-R31 14616 if (VT == MVT::i64 && Subtarget.isPPC64()) 14617 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 14618 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 14619 case 'r': // R0-R31 14620 if (VT == MVT::i64 && Subtarget.isPPC64()) 14621 return std::make_pair(0U, &PPC::G8RCRegClass); 14622 return std::make_pair(0U, &PPC::GPRCRegClass); 14623 // 'd' and 'f' constraints are both defined to be "the floating point 14624 // registers", where one is for 32-bit and the other for 64-bit. We don't 14625 // really care overly much here so just give them all the same reg classes. 14626 case 'd': 14627 case 'f': 14628 if (Subtarget.hasSPE()) { 14629 if (VT == MVT::f32 || VT == MVT::i32) 14630 return std::make_pair(0U, &PPC::GPRCRegClass); 14631 if (VT == MVT::f64 || VT == MVT::i64) 14632 return std::make_pair(0U, &PPC::SPERCRegClass); 14633 } else { 14634 if (VT == MVT::f32 || VT == MVT::i32) 14635 return std::make_pair(0U, &PPC::F4RCRegClass); 14636 if (VT == MVT::f64 || VT == MVT::i64) 14637 return std::make_pair(0U, &PPC::F8RCRegClass); 14638 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14639 return std::make_pair(0U, &PPC::QFRCRegClass); 14640 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14641 return std::make_pair(0U, &PPC::QSRCRegClass); 14642 } 14643 break; 14644 case 'v': 14645 if (VT == MVT::v4f64 && Subtarget.hasQPX()) 14646 return std::make_pair(0U, &PPC::QFRCRegClass); 14647 if (VT == MVT::v4f32 && Subtarget.hasQPX()) 14648 return std::make_pair(0U, &PPC::QSRCRegClass); 14649 if (Subtarget.hasAltivec()) 14650 return std::make_pair(0U, &PPC::VRRCRegClass); 14651 break; 14652 case 'y': // crrc 14653 return std::make_pair(0U, &PPC::CRRCRegClass); 14654 } 14655 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 14656 // An individual CR bit. 14657 return std::make_pair(0U, &PPC::CRBITRCRegClass); 14658 } else if ((Constraint == "wa" || Constraint == "wd" || 14659 Constraint == "wf" || Constraint == "wi") && 14660 Subtarget.hasVSX()) { 14661 return std::make_pair(0U, &PPC::VSRCRegClass); 14662 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 14663 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 14664 return std::make_pair(0U, &PPC::VSSRCRegClass); 14665 else 14666 return std::make_pair(0U, &PPC::VSFRCRegClass); 14667 } 14668 14669 // If we name a VSX register, we can't defer to the base class because it 14670 // will not recognize the correct register (their names will be VSL{0-31} 14671 // and V{0-31} so they won't match). So we match them here. 14672 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 14673 int VSNum = atoi(Constraint.data() + 3); 14674 assert(VSNum >= 0 && VSNum <= 63 && 14675 "Attempted to access a vsr out of range"); 14676 if (VSNum < 32) 14677 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 14678 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 14679 } 14680 std::pair<unsigned, const TargetRegisterClass *> R = 14681 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 14682 14683 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 14684 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 14685 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 14686 // register. 14687 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 14688 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 14689 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 14690 PPC::GPRCRegClass.contains(R.first)) 14691 return std::make_pair(TRI->getMatchingSuperReg(R.first, 14692 PPC::sub_32, &PPC::G8RCRegClass), 14693 &PPC::G8RCRegClass); 14694 14695 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 14696 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { 14697 R.first = PPC::CR0; 14698 R.second = &PPC::CRRCRegClass; 14699 } 14700 14701 return R; 14702 } 14703 14704 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 14705 /// vector. If it is invalid, don't add anything to Ops. 14706 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 14707 std::string &Constraint, 14708 std::vector<SDValue>&Ops, 14709 SelectionDAG &DAG) const { 14710 SDValue Result; 14711 14712 // Only support length 1 constraints. 14713 if (Constraint.length() > 1) return; 14714 14715 char Letter = Constraint[0]; 14716 switch (Letter) { 14717 default: break; 14718 case 'I': 14719 case 'J': 14720 case 'K': 14721 case 'L': 14722 case 'M': 14723 case 'N': 14724 case 'O': 14725 case 'P': { 14726 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 14727 if (!CST) return; // Must be an immediate to match. 14728 SDLoc dl(Op); 14729 int64_t Value = CST->getSExtValue(); 14730 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 14731 // numbers are printed as such. 14732 switch (Letter) { 14733 default: llvm_unreachable("Unknown constraint letter!"); 14734 case 'I': // "I" is a signed 16-bit constant. 14735 if (isInt<16>(Value)) 14736 Result = DAG.getTargetConstant(Value, dl, TCVT); 14737 break; 14738 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 14739 if (isShiftedUInt<16, 16>(Value)) 14740 Result = DAG.getTargetConstant(Value, dl, TCVT); 14741 break; 14742 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 14743 if (isShiftedInt<16, 16>(Value)) 14744 Result = DAG.getTargetConstant(Value, dl, TCVT); 14745 break; 14746 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 14747 if (isUInt<16>(Value)) 14748 Result = DAG.getTargetConstant(Value, dl, TCVT); 14749 break; 14750 case 'M': // "M" is a constant that is greater than 31. 14751 if (Value > 31) 14752 Result = DAG.getTargetConstant(Value, dl, TCVT); 14753 break; 14754 case 'N': // "N" is a positive constant that is an exact power of two. 14755 if (Value > 0 && isPowerOf2_64(Value)) 14756 Result = DAG.getTargetConstant(Value, dl, TCVT); 14757 break; 14758 case 'O': // "O" is the constant zero. 14759 if (Value == 0) 14760 Result = DAG.getTargetConstant(Value, dl, TCVT); 14761 break; 14762 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 14763 if (isInt<16>(-Value)) 14764 Result = DAG.getTargetConstant(Value, dl, TCVT); 14765 break; 14766 } 14767 break; 14768 } 14769 } 14770 14771 if (Result.getNode()) { 14772 Ops.push_back(Result); 14773 return; 14774 } 14775 14776 // Handle standard constraint letters. 14777 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 14778 } 14779 14780 // isLegalAddressingMode - Return true if the addressing mode represented 14781 // by AM is legal for this target, for a load/store of the specified type. 14782 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 14783 const AddrMode &AM, Type *Ty, 14784 unsigned AS, Instruction *I) const { 14785 // PPC does not allow r+i addressing modes for vectors! 14786 if (Ty->isVectorTy() && AM.BaseOffs != 0) 14787 return false; 14788 14789 // PPC allows a sign-extended 16-bit immediate field. 14790 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 14791 return false; 14792 14793 // No global is ever allowed as a base. 14794 if (AM.BaseGV) 14795 return false; 14796 14797 // PPC only support r+r, 14798 switch (AM.Scale) { 14799 case 0: // "r+i" or just "i", depending on HasBaseReg. 14800 break; 14801 case 1: 14802 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 14803 return false; 14804 // Otherwise we have r+r or r+i. 14805 break; 14806 case 2: 14807 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 14808 return false; 14809 // Allow 2*r as r+r. 14810 break; 14811 default: 14812 // No other scales are supported. 14813 return false; 14814 } 14815 14816 return true; 14817 } 14818 14819 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 14820 SelectionDAG &DAG) const { 14821 MachineFunction &MF = DAG.getMachineFunction(); 14822 MachineFrameInfo &MFI = MF.getFrameInfo(); 14823 MFI.setReturnAddressIsTaken(true); 14824 14825 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 14826 return SDValue(); 14827 14828 SDLoc dl(Op); 14829 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14830 14831 // Make sure the function does not optimize away the store of the RA to 14832 // the stack. 14833 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 14834 FuncInfo->setLRStoreRequired(); 14835 bool isPPC64 = Subtarget.isPPC64(); 14836 auto PtrVT = getPointerTy(MF.getDataLayout()); 14837 14838 if (Depth > 0) { 14839 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 14840 SDValue Offset = 14841 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 14842 isPPC64 ? MVT::i64 : MVT::i32); 14843 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 14844 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 14845 MachinePointerInfo()); 14846 } 14847 14848 // Just load the return address off the stack. 14849 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 14850 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 14851 MachinePointerInfo()); 14852 } 14853 14854 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 14855 SelectionDAG &DAG) const { 14856 SDLoc dl(Op); 14857 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 14858 14859 MachineFunction &MF = DAG.getMachineFunction(); 14860 MachineFrameInfo &MFI = MF.getFrameInfo(); 14861 MFI.setFrameAddressIsTaken(true); 14862 14863 EVT PtrVT = getPointerTy(MF.getDataLayout()); 14864 bool isPPC64 = PtrVT == MVT::i64; 14865 14866 // Naked functions never have a frame pointer, and so we use r1. For all 14867 // other functions, this decision must be delayed until during PEI. 14868 unsigned FrameReg; 14869 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 14870 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 14871 else 14872 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 14873 14874 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 14875 PtrVT); 14876 while (Depth--) 14877 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 14878 FrameAddr, MachinePointerInfo()); 14879 return FrameAddr; 14880 } 14881 14882 // FIXME? Maybe this could be a TableGen attribute on some registers and 14883 // this table could be generated automatically from RegInfo. 14884 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 14885 const MachineFunction &MF) const { 14886 bool isPPC64 = Subtarget.isPPC64(); 14887 14888 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 14889 if (!is64Bit && VT != LLT::scalar(32)) 14890 report_fatal_error("Invalid register global variable type"); 14891 14892 Register Reg = StringSwitch<Register>(RegName) 14893 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 14894 .Case("r2", isPPC64 ? Register() : PPC::R2) 14895 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 14896 .Default(Register()); 14897 14898 if (Reg) 14899 return Reg; 14900 report_fatal_error("Invalid register name global variable"); 14901 } 14902 14903 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 14904 // 32-bit SVR4 ABI access everything as got-indirect. 14905 if (Subtarget.is32BitELFABI()) 14906 return true; 14907 14908 // AIX accesses everything indirectly through the TOC, which is similar to 14909 // the GOT. 14910 if (Subtarget.isAIXABI()) 14911 return true; 14912 14913 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 14914 // If it is small or large code model, module locals are accessed 14915 // indirectly by loading their address from .toc/.got. 14916 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 14917 return true; 14918 14919 // JumpTable and BlockAddress are accessed as got-indirect. 14920 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 14921 return true; 14922 14923 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 14924 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 14925 14926 return false; 14927 } 14928 14929 bool 14930 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 14931 // The PowerPC target isn't yet aware of offsets. 14932 return false; 14933 } 14934 14935 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 14936 const CallInst &I, 14937 MachineFunction &MF, 14938 unsigned Intrinsic) const { 14939 switch (Intrinsic) { 14940 case Intrinsic::ppc_qpx_qvlfd: 14941 case Intrinsic::ppc_qpx_qvlfs: 14942 case Intrinsic::ppc_qpx_qvlfcd: 14943 case Intrinsic::ppc_qpx_qvlfcs: 14944 case Intrinsic::ppc_qpx_qvlfiwa: 14945 case Intrinsic::ppc_qpx_qvlfiwz: 14946 case Intrinsic::ppc_altivec_lvx: 14947 case Intrinsic::ppc_altivec_lvxl: 14948 case Intrinsic::ppc_altivec_lvebx: 14949 case Intrinsic::ppc_altivec_lvehx: 14950 case Intrinsic::ppc_altivec_lvewx: 14951 case Intrinsic::ppc_vsx_lxvd2x: 14952 case Intrinsic::ppc_vsx_lxvw4x: { 14953 EVT VT; 14954 switch (Intrinsic) { 14955 case Intrinsic::ppc_altivec_lvebx: 14956 VT = MVT::i8; 14957 break; 14958 case Intrinsic::ppc_altivec_lvehx: 14959 VT = MVT::i16; 14960 break; 14961 case Intrinsic::ppc_altivec_lvewx: 14962 VT = MVT::i32; 14963 break; 14964 case Intrinsic::ppc_vsx_lxvd2x: 14965 VT = MVT::v2f64; 14966 break; 14967 case Intrinsic::ppc_qpx_qvlfd: 14968 VT = MVT::v4f64; 14969 break; 14970 case Intrinsic::ppc_qpx_qvlfs: 14971 VT = MVT::v4f32; 14972 break; 14973 case Intrinsic::ppc_qpx_qvlfcd: 14974 VT = MVT::v2f64; 14975 break; 14976 case Intrinsic::ppc_qpx_qvlfcs: 14977 VT = MVT::v2f32; 14978 break; 14979 default: 14980 VT = MVT::v4i32; 14981 break; 14982 } 14983 14984 Info.opc = ISD::INTRINSIC_W_CHAIN; 14985 Info.memVT = VT; 14986 Info.ptrVal = I.getArgOperand(0); 14987 Info.offset = -VT.getStoreSize()+1; 14988 Info.size = 2*VT.getStoreSize()-1; 14989 Info.align = Align(1); 14990 Info.flags = MachineMemOperand::MOLoad; 14991 return true; 14992 } 14993 case Intrinsic::ppc_qpx_qvlfda: 14994 case Intrinsic::ppc_qpx_qvlfsa: 14995 case Intrinsic::ppc_qpx_qvlfcda: 14996 case Intrinsic::ppc_qpx_qvlfcsa: 14997 case Intrinsic::ppc_qpx_qvlfiwaa: 14998 case Intrinsic::ppc_qpx_qvlfiwza: { 14999 EVT VT; 15000 switch (Intrinsic) { 15001 case Intrinsic::ppc_qpx_qvlfda: 15002 VT = MVT::v4f64; 15003 break; 15004 case Intrinsic::ppc_qpx_qvlfsa: 15005 VT = MVT::v4f32; 15006 break; 15007 case Intrinsic::ppc_qpx_qvlfcda: 15008 VT = MVT::v2f64; 15009 break; 15010 case Intrinsic::ppc_qpx_qvlfcsa: 15011 VT = MVT::v2f32; 15012 break; 15013 default: 15014 VT = MVT::v4i32; 15015 break; 15016 } 15017 15018 Info.opc = ISD::INTRINSIC_W_CHAIN; 15019 Info.memVT = VT; 15020 Info.ptrVal = I.getArgOperand(0); 15021 Info.offset = 0; 15022 Info.size = VT.getStoreSize(); 15023 Info.align = Align(1); 15024 Info.flags = MachineMemOperand::MOLoad; 15025 return true; 15026 } 15027 case Intrinsic::ppc_qpx_qvstfd: 15028 case Intrinsic::ppc_qpx_qvstfs: 15029 case Intrinsic::ppc_qpx_qvstfcd: 15030 case Intrinsic::ppc_qpx_qvstfcs: 15031 case Intrinsic::ppc_qpx_qvstfiw: 15032 case Intrinsic::ppc_altivec_stvx: 15033 case Intrinsic::ppc_altivec_stvxl: 15034 case Intrinsic::ppc_altivec_stvebx: 15035 case Intrinsic::ppc_altivec_stvehx: 15036 case Intrinsic::ppc_altivec_stvewx: 15037 case Intrinsic::ppc_vsx_stxvd2x: 15038 case Intrinsic::ppc_vsx_stxvw4x: { 15039 EVT VT; 15040 switch (Intrinsic) { 15041 case Intrinsic::ppc_altivec_stvebx: 15042 VT = MVT::i8; 15043 break; 15044 case Intrinsic::ppc_altivec_stvehx: 15045 VT = MVT::i16; 15046 break; 15047 case Intrinsic::ppc_altivec_stvewx: 15048 VT = MVT::i32; 15049 break; 15050 case Intrinsic::ppc_vsx_stxvd2x: 15051 VT = MVT::v2f64; 15052 break; 15053 case Intrinsic::ppc_qpx_qvstfd: 15054 VT = MVT::v4f64; 15055 break; 15056 case Intrinsic::ppc_qpx_qvstfs: 15057 VT = MVT::v4f32; 15058 break; 15059 case Intrinsic::ppc_qpx_qvstfcd: 15060 VT = MVT::v2f64; 15061 break; 15062 case Intrinsic::ppc_qpx_qvstfcs: 15063 VT = MVT::v2f32; 15064 break; 15065 default: 15066 VT = MVT::v4i32; 15067 break; 15068 } 15069 15070 Info.opc = ISD::INTRINSIC_VOID; 15071 Info.memVT = VT; 15072 Info.ptrVal = I.getArgOperand(1); 15073 Info.offset = -VT.getStoreSize()+1; 15074 Info.size = 2*VT.getStoreSize()-1; 15075 Info.align = Align(1); 15076 Info.flags = MachineMemOperand::MOStore; 15077 return true; 15078 } 15079 case Intrinsic::ppc_qpx_qvstfda: 15080 case Intrinsic::ppc_qpx_qvstfsa: 15081 case Intrinsic::ppc_qpx_qvstfcda: 15082 case Intrinsic::ppc_qpx_qvstfcsa: 15083 case Intrinsic::ppc_qpx_qvstfiwa: { 15084 EVT VT; 15085 switch (Intrinsic) { 15086 case Intrinsic::ppc_qpx_qvstfda: 15087 VT = MVT::v4f64; 15088 break; 15089 case Intrinsic::ppc_qpx_qvstfsa: 15090 VT = MVT::v4f32; 15091 break; 15092 case Intrinsic::ppc_qpx_qvstfcda: 15093 VT = MVT::v2f64; 15094 break; 15095 case Intrinsic::ppc_qpx_qvstfcsa: 15096 VT = MVT::v2f32; 15097 break; 15098 default: 15099 VT = MVT::v4i32; 15100 break; 15101 } 15102 15103 Info.opc = ISD::INTRINSIC_VOID; 15104 Info.memVT = VT; 15105 Info.ptrVal = I.getArgOperand(1); 15106 Info.offset = 0; 15107 Info.size = VT.getStoreSize(); 15108 Info.align = Align(1); 15109 Info.flags = MachineMemOperand::MOStore; 15110 return true; 15111 } 15112 default: 15113 break; 15114 } 15115 15116 return false; 15117 } 15118 15119 /// It returns EVT::Other if the type should be determined using generic 15120 /// target-independent logic. 15121 EVT PPCTargetLowering::getOptimalMemOpType( 15122 const MemOp &Op, const AttributeList &FuncAttributes) const { 15123 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 15124 // When expanding a memset, require at least two QPX instructions to cover 15125 // the cost of loading the value to be stored from the constant pool. 15126 if (Subtarget.hasQPX() && Op.size() >= 32 && 15127 (Op.isMemcpy() || Op.size() >= 64) && Op.isAligned(Align(32)) && 15128 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) { 15129 return MVT::v4f64; 15130 } 15131 15132 // We should use Altivec/VSX loads and stores when available. For unaligned 15133 // addresses, unaligned VSX loads are only fast starting with the P8. 15134 if (Subtarget.hasAltivec() && Op.size() >= 16 && 15135 (Op.isAligned(Align(16)) || 15136 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 15137 return MVT::v4i32; 15138 } 15139 15140 if (Subtarget.isPPC64()) { 15141 return MVT::i64; 15142 } 15143 15144 return MVT::i32; 15145 } 15146 15147 /// Returns true if it is beneficial to convert a load of a constant 15148 /// to just the constant itself. 15149 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 15150 Type *Ty) const { 15151 assert(Ty->isIntegerTy()); 15152 15153 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 15154 return !(BitSize == 0 || BitSize > 64); 15155 } 15156 15157 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 15158 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 15159 return false; 15160 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 15161 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 15162 return NumBits1 == 64 && NumBits2 == 32; 15163 } 15164 15165 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 15166 if (!VT1.isInteger() || !VT2.isInteger()) 15167 return false; 15168 unsigned NumBits1 = VT1.getSizeInBits(); 15169 unsigned NumBits2 = VT2.getSizeInBits(); 15170 return NumBits1 == 64 && NumBits2 == 32; 15171 } 15172 15173 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 15174 // Generally speaking, zexts are not free, but they are free when they can be 15175 // folded with other operations. 15176 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 15177 EVT MemVT = LD->getMemoryVT(); 15178 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 15179 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 15180 (LD->getExtensionType() == ISD::NON_EXTLOAD || 15181 LD->getExtensionType() == ISD::ZEXTLOAD)) 15182 return true; 15183 } 15184 15185 // FIXME: Add other cases... 15186 // - 32-bit shifts with a zext to i64 15187 // - zext after ctlz, bswap, etc. 15188 // - zext after and by a constant mask 15189 15190 return TargetLowering::isZExtFree(Val, VT2); 15191 } 15192 15193 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 15194 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 15195 "invalid fpext types"); 15196 // Extending to float128 is not free. 15197 if (DestVT == MVT::f128) 15198 return false; 15199 return true; 15200 } 15201 15202 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 15203 return isInt<16>(Imm) || isUInt<16>(Imm); 15204 } 15205 15206 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 15207 return isInt<16>(Imm) || isUInt<16>(Imm); 15208 } 15209 15210 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 15211 unsigned, 15212 unsigned, 15213 MachineMemOperand::Flags, 15214 bool *Fast) const { 15215 if (DisablePPCUnaligned) 15216 return false; 15217 15218 // PowerPC supports unaligned memory access for simple non-vector types. 15219 // Although accessing unaligned addresses is not as efficient as accessing 15220 // aligned addresses, it is generally more efficient than manual expansion, 15221 // and generally only traps for software emulation when crossing page 15222 // boundaries. 15223 15224 if (!VT.isSimple()) 15225 return false; 15226 15227 if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess()) 15228 return false; 15229 15230 if (VT.getSimpleVT().isVector()) { 15231 if (Subtarget.hasVSX()) { 15232 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 15233 VT != MVT::v4f32 && VT != MVT::v4i32) 15234 return false; 15235 } else { 15236 return false; 15237 } 15238 } 15239 15240 if (VT == MVT::ppcf128) 15241 return false; 15242 15243 if (Fast) 15244 *Fast = true; 15245 15246 return true; 15247 } 15248 15249 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 15250 EVT VT) const { 15251 VT = VT.getScalarType(); 15252 15253 if (!VT.isSimple()) 15254 return false; 15255 15256 switch (VT.getSimpleVT().SimpleTy) { 15257 case MVT::f32: 15258 case MVT::f64: 15259 return true; 15260 case MVT::f128: 15261 return (EnableQuadPrecision && Subtarget.hasP9Vector()); 15262 default: 15263 break; 15264 } 15265 15266 return false; 15267 } 15268 15269 const MCPhysReg * 15270 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 15271 // LR is a callee-save register, but we must treat it as clobbered by any call 15272 // site. Hence we include LR in the scratch registers, which are in turn added 15273 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 15274 // to CTR, which is used by any indirect call. 15275 static const MCPhysReg ScratchRegs[] = { 15276 PPC::X12, PPC::LR8, PPC::CTR8, 0 15277 }; 15278 15279 return ScratchRegs; 15280 } 15281 15282 unsigned PPCTargetLowering::getExceptionPointerRegister( 15283 const Constant *PersonalityFn) const { 15284 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 15285 } 15286 15287 unsigned PPCTargetLowering::getExceptionSelectorRegister( 15288 const Constant *PersonalityFn) const { 15289 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 15290 } 15291 15292 bool 15293 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 15294 EVT VT , unsigned DefinedValues) const { 15295 if (VT == MVT::v2i64) 15296 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 15297 15298 if (Subtarget.hasVSX() || Subtarget.hasQPX()) 15299 return true; 15300 15301 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 15302 } 15303 15304 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 15305 if (DisableILPPref || Subtarget.enableMachineScheduler()) 15306 return TargetLowering::getSchedulingPreference(N); 15307 15308 return Sched::ILP; 15309 } 15310 15311 // Create a fast isel object. 15312 FastISel * 15313 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 15314 const TargetLibraryInfo *LibInfo) const { 15315 return PPC::createFastISel(FuncInfo, LibInfo); 15316 } 15317 15318 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 15319 if (!Subtarget.isPPC64()) return; 15320 15321 // Update IsSplitCSR in PPCFunctionInfo 15322 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>(); 15323 PFI->setIsSplitCSR(true); 15324 } 15325 15326 void PPCTargetLowering::insertCopiesSplitCSR( 15327 MachineBasicBlock *Entry, 15328 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 15329 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 15330 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 15331 if (!IStart) 15332 return; 15333 15334 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 15335 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 15336 MachineBasicBlock::iterator MBBI = Entry->begin(); 15337 for (const MCPhysReg *I = IStart; *I; ++I) { 15338 const TargetRegisterClass *RC = nullptr; 15339 if (PPC::G8RCRegClass.contains(*I)) 15340 RC = &PPC::G8RCRegClass; 15341 else if (PPC::F8RCRegClass.contains(*I)) 15342 RC = &PPC::F8RCRegClass; 15343 else if (PPC::CRRCRegClass.contains(*I)) 15344 RC = &PPC::CRRCRegClass; 15345 else if (PPC::VRRCRegClass.contains(*I)) 15346 RC = &PPC::VRRCRegClass; 15347 else 15348 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 15349 15350 Register NewVR = MRI->createVirtualRegister(RC); 15351 // Create copy from CSR to a virtual register. 15352 // FIXME: this currently does not emit CFI pseudo-instructions, it works 15353 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 15354 // nounwind. If we want to generalize this later, we may need to emit 15355 // CFI pseudo-instructions. 15356 assert(Entry->getParent()->getFunction().hasFnAttribute( 15357 Attribute::NoUnwind) && 15358 "Function should be nounwind in insertCopiesSplitCSR!"); 15359 Entry->addLiveIn(*I); 15360 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 15361 .addReg(*I); 15362 15363 // Insert the copy-back instructions right before the terminator. 15364 for (auto *Exit : Exits) 15365 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 15366 TII->get(TargetOpcode::COPY), *I) 15367 .addReg(NewVR); 15368 } 15369 } 15370 15371 // Override to enable LOAD_STACK_GUARD lowering on Linux. 15372 bool PPCTargetLowering::useLoadStackGuardNode() const { 15373 if (!Subtarget.isTargetLinux()) 15374 return TargetLowering::useLoadStackGuardNode(); 15375 return true; 15376 } 15377 15378 // Override to disable global variable loading on Linux. 15379 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 15380 if (!Subtarget.isTargetLinux()) 15381 return TargetLowering::insertSSPDeclarations(M); 15382 } 15383 15384 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 15385 bool ForCodeSize) const { 15386 if (!VT.isSimple() || !Subtarget.hasVSX()) 15387 return false; 15388 15389 switch(VT.getSimpleVT().SimpleTy) { 15390 default: 15391 // For FP types that are currently not supported by PPC backend, return 15392 // false. Examples: f16, f80. 15393 return false; 15394 case MVT::f32: 15395 case MVT::f64: 15396 case MVT::ppcf128: 15397 return Imm.isPosZero(); 15398 } 15399 } 15400 15401 // For vector shift operation op, fold 15402 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 15403 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 15404 SelectionDAG &DAG) { 15405 SDValue N0 = N->getOperand(0); 15406 SDValue N1 = N->getOperand(1); 15407 EVT VT = N0.getValueType(); 15408 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 15409 unsigned Opcode = N->getOpcode(); 15410 unsigned TargetOpcode; 15411 15412 switch (Opcode) { 15413 default: 15414 llvm_unreachable("Unexpected shift operation"); 15415 case ISD::SHL: 15416 TargetOpcode = PPCISD::SHL; 15417 break; 15418 case ISD::SRL: 15419 TargetOpcode = PPCISD::SRL; 15420 break; 15421 case ISD::SRA: 15422 TargetOpcode = PPCISD::SRA; 15423 break; 15424 } 15425 15426 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 15427 N1->getOpcode() == ISD::AND) 15428 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 15429 if (Mask->getZExtValue() == OpSizeInBits - 1) 15430 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 15431 15432 return SDValue(); 15433 } 15434 15435 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 15436 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15437 return Value; 15438 15439 SDValue N0 = N->getOperand(0); 15440 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 15441 if (!Subtarget.isISA3_0() || 15442 N0.getOpcode() != ISD::SIGN_EXTEND || 15443 N0.getOperand(0).getValueType() != MVT::i32 || 15444 CN1 == nullptr || N->getValueType(0) != MVT::i64) 15445 return SDValue(); 15446 15447 // We can't save an operation here if the value is already extended, and 15448 // the existing shift is easier to combine. 15449 SDValue ExtsSrc = N0.getOperand(0); 15450 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 15451 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 15452 return SDValue(); 15453 15454 SDLoc DL(N0); 15455 SDValue ShiftBy = SDValue(CN1, 0); 15456 // We want the shift amount to be i32 on the extswli, but the shift could 15457 // have an i64. 15458 if (ShiftBy.getValueType() == MVT::i64) 15459 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 15460 15461 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 15462 ShiftBy); 15463 } 15464 15465 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 15466 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15467 return Value; 15468 15469 return SDValue(); 15470 } 15471 15472 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 15473 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 15474 return Value; 15475 15476 return SDValue(); 15477 } 15478 15479 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 15480 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 15481 // When C is zero, the equation (addi Z, -C) can be simplified to Z 15482 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 15483 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 15484 const PPCSubtarget &Subtarget) { 15485 if (!Subtarget.isPPC64()) 15486 return SDValue(); 15487 15488 SDValue LHS = N->getOperand(0); 15489 SDValue RHS = N->getOperand(1); 15490 15491 auto isZextOfCompareWithConstant = [](SDValue Op) { 15492 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 15493 Op.getValueType() != MVT::i64) 15494 return false; 15495 15496 SDValue Cmp = Op.getOperand(0); 15497 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 15498 Cmp.getOperand(0).getValueType() != MVT::i64) 15499 return false; 15500 15501 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 15502 int64_t NegConstant = 0 - Constant->getSExtValue(); 15503 // Due to the limitations of the addi instruction, 15504 // -C is required to be [-32768, 32767]. 15505 return isInt<16>(NegConstant); 15506 } 15507 15508 return false; 15509 }; 15510 15511 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 15512 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 15513 15514 // If there is a pattern, canonicalize a zext operand to the RHS. 15515 if (LHSHasPattern && !RHSHasPattern) 15516 std::swap(LHS, RHS); 15517 else if (!LHSHasPattern && !RHSHasPattern) 15518 return SDValue(); 15519 15520 SDLoc DL(N); 15521 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 15522 SDValue Cmp = RHS.getOperand(0); 15523 SDValue Z = Cmp.getOperand(0); 15524 auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1)); 15525 15526 assert(Constant && "Constant Should not be a null pointer."); 15527 int64_t NegConstant = 0 - Constant->getSExtValue(); 15528 15529 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 15530 default: break; 15531 case ISD::SETNE: { 15532 // when C == 0 15533 // --> addze X, (addic Z, -1).carry 15534 // / 15535 // add X, (zext(setne Z, C))-- 15536 // \ when -32768 <= -C <= 32767 && C != 0 15537 // --> addze X, (addic (addi Z, -C), -1).carry 15538 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15539 DAG.getConstant(NegConstant, DL, MVT::i64)); 15540 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15541 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15542 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 15543 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15544 SDValue(Addc.getNode(), 1)); 15545 } 15546 case ISD::SETEQ: { 15547 // when C == 0 15548 // --> addze X, (subfic Z, 0).carry 15549 // / 15550 // add X, (zext(sete Z, C))-- 15551 // \ when -32768 <= -C <= 32767 && C != 0 15552 // --> addze X, (subfic (addi Z, -C), 0).carry 15553 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 15554 DAG.getConstant(NegConstant, DL, MVT::i64)); 15555 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 15556 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 15557 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 15558 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 15559 SDValue(Subc.getNode(), 1)); 15560 } 15561 } 15562 15563 return SDValue(); 15564 } 15565 15566 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 15567 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 15568 return Value; 15569 15570 return SDValue(); 15571 } 15572 15573 // Detect TRUNCATE operations on bitcasts of float128 values. 15574 // What we are looking for here is the situtation where we extract a subset 15575 // of bits from a 128 bit float. 15576 // This can be of two forms: 15577 // 1) BITCAST of f128 feeding TRUNCATE 15578 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 15579 // The reason this is required is because we do not have a legal i128 type 15580 // and so we want to prevent having to store the f128 and then reload part 15581 // of it. 15582 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 15583 DAGCombinerInfo &DCI) const { 15584 // If we are using CRBits then try that first. 15585 if (Subtarget.useCRBits()) { 15586 // Check if CRBits did anything and return that if it did. 15587 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 15588 return CRTruncValue; 15589 } 15590 15591 SDLoc dl(N); 15592 SDValue Op0 = N->getOperand(0); 15593 15594 // Looking for a truncate of i128 to i64. 15595 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 15596 return SDValue(); 15597 15598 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 15599 15600 // SRL feeding TRUNCATE. 15601 if (Op0.getOpcode() == ISD::SRL) { 15602 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 15603 // The right shift has to be by 64 bits. 15604 if (!ConstNode || ConstNode->getZExtValue() != 64) 15605 return SDValue(); 15606 15607 // Switch the element number to extract. 15608 EltToExtract = EltToExtract ? 0 : 1; 15609 // Update Op0 past the SRL. 15610 Op0 = Op0.getOperand(0); 15611 } 15612 15613 // BITCAST feeding a TRUNCATE possibly via SRL. 15614 if (Op0.getOpcode() == ISD::BITCAST && 15615 Op0.getValueType() == MVT::i128 && 15616 Op0.getOperand(0).getValueType() == MVT::f128) { 15617 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 15618 return DCI.DAG.getNode( 15619 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 15620 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 15621 } 15622 return SDValue(); 15623 } 15624 15625 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 15626 SelectionDAG &DAG = DCI.DAG; 15627 15628 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 15629 if (!ConstOpOrElement) 15630 return SDValue(); 15631 15632 // An imul is usually smaller than the alternative sequence for legal type. 15633 if (DAG.getMachineFunction().getFunction().hasMinSize() && 15634 isOperationLegal(ISD::MUL, N->getValueType(0))) 15635 return SDValue(); 15636 15637 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 15638 switch (this->Subtarget.getCPUDirective()) { 15639 default: 15640 // TODO: enhance the condition for subtarget before pwr8 15641 return false; 15642 case PPC::DIR_PWR8: 15643 // type mul add shl 15644 // scalar 4 1 1 15645 // vector 7 2 2 15646 return true; 15647 case PPC::DIR_PWR9: 15648 case PPC::DIR_PWR_FUTURE: 15649 // type mul add shl 15650 // scalar 5 2 2 15651 // vector 7 2 2 15652 15653 // The cycle RATIO of related operations are showed as a table above. 15654 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 15655 // scalar and vector type. For 2 instrs patterns, add/sub + shl 15656 // are 4, it is always profitable; but for 3 instrs patterns 15657 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 15658 // So we should only do it for vector type. 15659 return IsAddOne && IsNeg ? VT.isVector() : true; 15660 } 15661 }; 15662 15663 EVT VT = N->getValueType(0); 15664 SDLoc DL(N); 15665 15666 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 15667 bool IsNeg = MulAmt.isNegative(); 15668 APInt MulAmtAbs = MulAmt.abs(); 15669 15670 if ((MulAmtAbs - 1).isPowerOf2()) { 15671 // (mul x, 2^N + 1) => (add (shl x, N), x) 15672 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 15673 15674 if (!IsProfitable(IsNeg, true, VT)) 15675 return SDValue(); 15676 15677 SDValue Op0 = N->getOperand(0); 15678 SDValue Op1 = 15679 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15680 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 15681 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 15682 15683 if (!IsNeg) 15684 return Res; 15685 15686 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 15687 } else if ((MulAmtAbs + 1).isPowerOf2()) { 15688 // (mul x, 2^N - 1) => (sub (shl x, N), x) 15689 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 15690 15691 if (!IsProfitable(IsNeg, false, VT)) 15692 return SDValue(); 15693 15694 SDValue Op0 = N->getOperand(0); 15695 SDValue Op1 = 15696 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 15697 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 15698 15699 if (!IsNeg) 15700 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 15701 else 15702 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 15703 15704 } else { 15705 return SDValue(); 15706 } 15707 } 15708 15709 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 15710 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 15711 if (!Subtarget.is64BitELFABI()) 15712 return false; 15713 15714 // If not a tail call then no need to proceed. 15715 if (!CI->isTailCall()) 15716 return false; 15717 15718 // If sibling calls have been disabled and tail-calls aren't guaranteed 15719 // there is no reason to duplicate. 15720 auto &TM = getTargetMachine(); 15721 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 15722 return false; 15723 15724 // Can't tail call a function called indirectly, or if it has variadic args. 15725 const Function *Callee = CI->getCalledFunction(); 15726 if (!Callee || Callee->isVarArg()) 15727 return false; 15728 15729 // Make sure the callee and caller calling conventions are eligible for tco. 15730 const Function *Caller = CI->getParent()->getParent(); 15731 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 15732 CI->getCallingConv())) 15733 return false; 15734 15735 // If the function is local then we have a good chance at tail-calling it 15736 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 15737 } 15738 15739 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 15740 if (!Subtarget.hasVSX()) 15741 return false; 15742 if (Subtarget.hasP9Vector() && VT == MVT::f128) 15743 return true; 15744 return VT == MVT::f32 || VT == MVT::f64 || 15745 VT == MVT::v4f32 || VT == MVT::v2f64; 15746 } 15747 15748 bool PPCTargetLowering:: 15749 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 15750 const Value *Mask = AndI.getOperand(1); 15751 // If the mask is suitable for andi. or andis. we should sink the and. 15752 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 15753 // Can't handle constants wider than 64-bits. 15754 if (CI->getBitWidth() > 64) 15755 return false; 15756 int64_t ConstVal = CI->getZExtValue(); 15757 return isUInt<16>(ConstVal) || 15758 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 15759 } 15760 15761 // For non-constant masks, we can always use the record-form and. 15762 return true; 15763 } 15764 15765 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0) 15766 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0) 15767 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0) 15768 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0) 15769 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32 15770 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const { 15771 assert((N->getOpcode() == ISD::ABS) && "Need ABS node here"); 15772 assert(Subtarget.hasP9Altivec() && 15773 "Only combine this when P9 altivec supported!"); 15774 EVT VT = N->getValueType(0); 15775 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15776 return SDValue(); 15777 15778 SelectionDAG &DAG = DCI.DAG; 15779 SDLoc dl(N); 15780 if (N->getOperand(0).getOpcode() == ISD::SUB) { 15781 // Even for signed integers, if it's known to be positive (as signed 15782 // integer) due to zero-extended inputs. 15783 unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode(); 15784 unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode(); 15785 if ((SubOpcd0 == ISD::ZERO_EXTEND || 15786 SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) && 15787 (SubOpcd1 == ISD::ZERO_EXTEND || 15788 SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) { 15789 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15790 N->getOperand(0)->getOperand(0), 15791 N->getOperand(0)->getOperand(1), 15792 DAG.getTargetConstant(0, dl, MVT::i32)); 15793 } 15794 15795 // For type v4i32, it can be optimized with xvnegsp + vabsduw 15796 if (N->getOperand(0).getValueType() == MVT::v4i32 && 15797 N->getOperand(0).hasOneUse()) { 15798 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(), 15799 N->getOperand(0)->getOperand(0), 15800 N->getOperand(0)->getOperand(1), 15801 DAG.getTargetConstant(1, dl, MVT::i32)); 15802 } 15803 } 15804 15805 return SDValue(); 15806 } 15807 15808 // For type v4i32/v8ii16/v16i8, transform 15809 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b) 15810 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b) 15811 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b) 15812 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b) 15813 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 15814 DAGCombinerInfo &DCI) const { 15815 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 15816 assert(Subtarget.hasP9Altivec() && 15817 "Only combine this when P9 altivec supported!"); 15818 15819 SelectionDAG &DAG = DCI.DAG; 15820 SDLoc dl(N); 15821 SDValue Cond = N->getOperand(0); 15822 SDValue TrueOpnd = N->getOperand(1); 15823 SDValue FalseOpnd = N->getOperand(2); 15824 EVT VT = N->getOperand(1).getValueType(); 15825 15826 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 15827 FalseOpnd.getOpcode() != ISD::SUB) 15828 return SDValue(); 15829 15830 // ABSD only available for type v4i32/v8i16/v16i8 15831 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 15832 return SDValue(); 15833 15834 // At least to save one more dependent computation 15835 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 15836 return SDValue(); 15837 15838 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 15839 15840 // Can only handle unsigned comparison here 15841 switch (CC) { 15842 default: 15843 return SDValue(); 15844 case ISD::SETUGT: 15845 case ISD::SETUGE: 15846 break; 15847 case ISD::SETULT: 15848 case ISD::SETULE: 15849 std::swap(TrueOpnd, FalseOpnd); 15850 break; 15851 } 15852 15853 SDValue CmpOpnd1 = Cond.getOperand(0); 15854 SDValue CmpOpnd2 = Cond.getOperand(1); 15855 15856 // SETCC CmpOpnd1 CmpOpnd2 cond 15857 // TrueOpnd = CmpOpnd1 - CmpOpnd2 15858 // FalseOpnd = CmpOpnd2 - CmpOpnd1 15859 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 15860 TrueOpnd.getOperand(1) == CmpOpnd2 && 15861 FalseOpnd.getOperand(0) == CmpOpnd2 && 15862 FalseOpnd.getOperand(1) == CmpOpnd1) { 15863 return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(), 15864 CmpOpnd1, CmpOpnd2, 15865 DAG.getTargetConstant(0, dl, MVT::i32)); 15866 } 15867 15868 return SDValue(); 15869 } 15870