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/STLExtras.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/SmallVector.h" 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/ADT/StringRef.h" 35 #include "llvm/ADT/StringSwitch.h" 36 #include "llvm/CodeGen/CallingConvLower.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineInstr.h" 42 #include "llvm/CodeGen/MachineInstrBuilder.h" 43 #include "llvm/CodeGen/MachineJumpTableInfo.h" 44 #include "llvm/CodeGen/MachineLoopInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/CallingConv.h" 58 #include "llvm/IR/Constant.h" 59 #include "llvm/IR/Constants.h" 60 #include "llvm/IR/DataLayout.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DerivedTypes.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/Intrinsics.h" 68 #include "llvm/IR/IntrinsicsPowerPC.h" 69 #include "llvm/IR/Module.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/MC/MCContext.h" 74 #include "llvm/MC/MCExpr.h" 75 #include "llvm/MC/MCRegisterInfo.h" 76 #include "llvm/MC/MCSectionXCOFF.h" 77 #include "llvm/MC/MCSymbolXCOFF.h" 78 #include "llvm/Support/AtomicOrdering.h" 79 #include "llvm/Support/BranchProbability.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/CodeGen.h" 82 #include "llvm/Support/CommandLine.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/Debug.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/KnownBits.h" 88 #include "llvm/Support/MachineValueType.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Target/TargetMachine.h" 92 #include "llvm/Target/TargetOptions.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <list> 98 #include <optional> 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> UseAbsoluteJumpTables("ppc-use-absolute-jumptables", 122 cl::desc("use absolute jump tables on ppc"), cl::Hidden); 123 124 static cl::opt<bool> EnableQuadwordAtomics( 125 "ppc-quadword-atomics", 126 cl::desc("enable quadword lock-free atomic operations"), cl::init(false), 127 cl::Hidden); 128 129 static cl::opt<bool> 130 DisablePerfectShuffle("ppc-disable-perfect-shuffle", 131 cl::desc("disable vector permute decomposition"), 132 cl::init(true), cl::Hidden); 133 134 cl::opt<bool> DisableAutoPairedVecSt( 135 "disable-auto-paired-vec-st", 136 cl::desc("disable automatically generated 32byte paired vector stores"), 137 cl::init(true), cl::Hidden); 138 139 STATISTIC(NumTailCalls, "Number of tail calls"); 140 STATISTIC(NumSiblingCalls, "Number of sibling calls"); 141 STATISTIC(ShufflesHandledWithVPERM, 142 "Number of shuffles lowered to a VPERM or XXPERM"); 143 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed"); 144 145 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int); 146 147 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl); 148 149 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word"; 150 151 // FIXME: Remove this once the bug has been fixed! 152 extern cl::opt<bool> ANDIGlueBug; 153 154 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, 155 const PPCSubtarget &STI) 156 : TargetLowering(TM), Subtarget(STI) { 157 // Initialize map that relates the PPC addressing modes to the computed flags 158 // of a load/store instruction. The map is used to determine the optimal 159 // addressing mode when selecting load and stores. 160 initializeAddrModeMap(); 161 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all 162 // arguments are at least 4/8 bytes aligned. 163 bool isPPC64 = Subtarget.isPPC64(); 164 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4)); 165 166 // Set up the register classes. 167 addRegisterClass(MVT::i32, &PPC::GPRCRegClass); 168 if (!useSoftFloat()) { 169 if (hasSPE()) { 170 addRegisterClass(MVT::f32, &PPC::GPRCRegClass); 171 // EFPU2 APU only supports f32 172 if (!Subtarget.hasEFPU2()) 173 addRegisterClass(MVT::f64, &PPC::SPERCRegClass); 174 } else { 175 addRegisterClass(MVT::f32, &PPC::F4RCRegClass); 176 addRegisterClass(MVT::f64, &PPC::F8RCRegClass); 177 } 178 } 179 180 // Match BITREVERSE to customized fast code sequence in the td file. 181 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 182 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 183 184 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended. 185 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 186 187 // Custom lower inline assembly to check for special registers. 188 setOperationAction(ISD::INLINEASM, MVT::Other, Custom); 189 setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom); 190 191 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD. 192 for (MVT VT : MVT::integer_valuetypes()) { 193 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 194 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); 195 } 196 197 if (Subtarget.isISA3_0()) { 198 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal); 199 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal); 200 setTruncStoreAction(MVT::f64, MVT::f16, Legal); 201 setTruncStoreAction(MVT::f32, MVT::f16, Legal); 202 } else { 203 // No extending loads from f16 or HW conversions back and forth. 204 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 205 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand); 206 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand); 207 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 208 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand); 209 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand); 210 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 211 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 212 } 213 214 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 215 216 // PowerPC has pre-inc load and store's. 217 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); 218 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); 219 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); 220 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); 221 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); 222 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); 223 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); 224 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); 225 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); 226 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); 227 if (!Subtarget.hasSPE()) { 228 setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); 229 setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); 230 setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); 231 setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); 232 } 233 234 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry. 235 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 }; 236 for (MVT VT : ScalarIntVTs) { 237 setOperationAction(ISD::ADDC, VT, Legal); 238 setOperationAction(ISD::ADDE, VT, Legal); 239 setOperationAction(ISD::SUBC, VT, Legal); 240 setOperationAction(ISD::SUBE, VT, Legal); 241 } 242 243 if (Subtarget.useCRBits()) { 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 245 246 if (isPPC64 || Subtarget.hasFPCVT()) { 247 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote); 248 AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1, 249 isPPC64 ? MVT::i64 : MVT::i32); 250 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote); 251 AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1, 252 isPPC64 ? MVT::i64 : MVT::i32); 253 254 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); 255 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, 256 isPPC64 ? MVT::i64 : MVT::i32); 257 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); 258 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, 259 isPPC64 ? MVT::i64 : MVT::i32); 260 261 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote); 262 AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1, 263 isPPC64 ? MVT::i64 : MVT::i32); 264 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote); 265 AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1, 266 isPPC64 ? MVT::i64 : MVT::i32); 267 268 setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote); 269 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, 270 isPPC64 ? MVT::i64 : MVT::i32); 271 setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote); 272 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, 273 isPPC64 ? MVT::i64 : MVT::i32); 274 } else { 275 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom); 276 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom); 277 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); 278 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); 279 } 280 281 // PowerPC does not support direct load/store of condition registers. 282 setOperationAction(ISD::LOAD, MVT::i1, Custom); 283 setOperationAction(ISD::STORE, MVT::i1, Custom); 284 285 // FIXME: Remove this once the ANDI glue bug is fixed: 286 if (ANDIGlueBug) 287 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); 288 289 for (MVT VT : MVT::integer_valuetypes()) { 290 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 291 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 292 setTruncStoreAction(VT, MVT::i1, Expand); 293 } 294 295 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); 296 } 297 298 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 299 // PPC (the libcall is not available). 300 setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom); 301 setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom); 302 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom); 303 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom); 304 305 // We do not currently implement these libm ops for PowerPC. 306 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); 307 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); 308 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); 309 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); 310 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); 311 setOperationAction(ISD::FREM, MVT::ppcf128, Expand); 312 313 // PowerPC has no SREM/UREM instructions unless we are on P9 314 // On P9 we may use a hardware instruction to compute the remainder. 315 // When the result of both the remainder and the division is required it is 316 // more efficient to compute the remainder from the result of the division 317 // rather than use the remainder instruction. The instructions are legalized 318 // directly because the DivRemPairsPass performs the transformation at the IR 319 // level. 320 if (Subtarget.isISA3_0()) { 321 setOperationAction(ISD::SREM, MVT::i32, Legal); 322 setOperationAction(ISD::UREM, MVT::i32, Legal); 323 setOperationAction(ISD::SREM, MVT::i64, Legal); 324 setOperationAction(ISD::UREM, MVT::i64, Legal); 325 } else { 326 setOperationAction(ISD::SREM, MVT::i32, Expand); 327 setOperationAction(ISD::UREM, MVT::i32, Expand); 328 setOperationAction(ISD::SREM, MVT::i64, Expand); 329 setOperationAction(ISD::UREM, MVT::i64, Expand); 330 } 331 332 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. 333 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); 334 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); 335 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 336 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 337 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 338 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 339 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 340 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 341 342 // Handle constrained floating-point operations of scalar. 343 // TODO: Handle SPE specific operation. 344 setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal); 345 setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal); 346 setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal); 347 setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal); 348 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 349 350 setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal); 352 setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal); 353 setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal); 354 355 if (!Subtarget.hasSPE()) { 356 setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal); 357 setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal); 358 } 359 360 if (Subtarget.hasVSX()) { 361 setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal); 363 } 364 365 if (Subtarget.hasFSQRT()) { 366 setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal); 367 setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal); 368 } 369 370 if (Subtarget.hasFPRND()) { 371 setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal); 372 setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal); 373 setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal); 374 setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal); 375 376 setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal); 377 setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal); 378 setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal); 379 setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal); 380 } 381 382 // We don't support sin/cos/sqrt/fmod/pow 383 setOperationAction(ISD::FSIN , MVT::f64, Expand); 384 setOperationAction(ISD::FCOS , MVT::f64, Expand); 385 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 386 setOperationAction(ISD::FREM , MVT::f64, Expand); 387 setOperationAction(ISD::FPOW , MVT::f64, Expand); 388 setOperationAction(ISD::FSIN , MVT::f32, Expand); 389 setOperationAction(ISD::FCOS , MVT::f32, Expand); 390 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 391 setOperationAction(ISD::FREM , MVT::f32, Expand); 392 setOperationAction(ISD::FPOW , MVT::f32, Expand); 393 394 // MASS transformation for LLVM intrinsics with replicating fast-math flag 395 // to be consistent to PPCGenScalarMASSEntries pass 396 if (TM.getOptLevel() == CodeGenOpt::Aggressive) { 397 setOperationAction(ISD::FSIN , MVT::f64, Custom); 398 setOperationAction(ISD::FCOS , MVT::f64, Custom); 399 setOperationAction(ISD::FPOW , MVT::f64, Custom); 400 setOperationAction(ISD::FLOG, MVT::f64, Custom); 401 setOperationAction(ISD::FLOG10, MVT::f64, Custom); 402 setOperationAction(ISD::FEXP, MVT::f64, Custom); 403 setOperationAction(ISD::FSIN , MVT::f32, Custom); 404 setOperationAction(ISD::FCOS , MVT::f32, Custom); 405 setOperationAction(ISD::FPOW , MVT::f32, Custom); 406 setOperationAction(ISD::FLOG, MVT::f32, Custom); 407 setOperationAction(ISD::FLOG10, MVT::f32, Custom); 408 setOperationAction(ISD::FEXP, MVT::f32, Custom); 409 } 410 411 if (Subtarget.hasSPE()) { 412 setOperationAction(ISD::FMA , MVT::f64, Expand); 413 setOperationAction(ISD::FMA , MVT::f32, Expand); 414 } else { 415 setOperationAction(ISD::FMA , MVT::f64, Legal); 416 setOperationAction(ISD::FMA , MVT::f32, Legal); 417 } 418 419 if (Subtarget.hasSPE()) 420 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 421 422 setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom); 423 424 // If we're enabling GP optimizations, use hardware square root 425 if (!Subtarget.hasFSQRT() && 426 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && 427 Subtarget.hasFRE())) 428 setOperationAction(ISD::FSQRT, MVT::f64, Expand); 429 430 if (!Subtarget.hasFSQRT() && 431 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && 432 Subtarget.hasFRES())) 433 setOperationAction(ISD::FSQRT, MVT::f32, Expand); 434 435 if (Subtarget.hasFCPSGN()) { 436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); 437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); 438 } else { 439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 441 } 442 443 if (Subtarget.hasFPRND()) { 444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 445 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 446 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 447 setOperationAction(ISD::FROUND, MVT::f64, Legal); 448 449 setOperationAction(ISD::FFLOOR, MVT::f32, Legal); 450 setOperationAction(ISD::FCEIL, MVT::f32, Legal); 451 setOperationAction(ISD::FTRUNC, MVT::f32, Legal); 452 setOperationAction(ISD::FROUND, MVT::f32, Legal); 453 } 454 455 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP 456 // instruction xxbrd to speed up scalar BSWAP64. 457 if (Subtarget.isISA3_1()) { 458 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 459 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 460 } else { 461 setOperationAction(ISD::BSWAP, MVT::i32, Expand); 462 setOperationAction( 463 ISD::BSWAP, MVT::i64, 464 (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand); 465 } 466 467 // CTPOP or CTTZ were introduced in P8/P9 respectively 468 if (Subtarget.isISA3_0()) { 469 setOperationAction(ISD::CTTZ , MVT::i32 , Legal); 470 setOperationAction(ISD::CTTZ , MVT::i64 , Legal); 471 } else { 472 setOperationAction(ISD::CTTZ , MVT::i32 , Expand); 473 setOperationAction(ISD::CTTZ , MVT::i64 , Expand); 474 } 475 476 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) { 477 setOperationAction(ISD::CTPOP, MVT::i32 , Legal); 478 setOperationAction(ISD::CTPOP, MVT::i64 , Legal); 479 } else { 480 setOperationAction(ISD::CTPOP, MVT::i32 , Expand); 481 setOperationAction(ISD::CTPOP, MVT::i64 , Expand); 482 } 483 484 // PowerPC does not have ROTR 485 setOperationAction(ISD::ROTR, MVT::i32 , Expand); 486 setOperationAction(ISD::ROTR, MVT::i64 , Expand); 487 488 if (!Subtarget.useCRBits()) { 489 // PowerPC does not have Select 490 setOperationAction(ISD::SELECT, MVT::i32, Expand); 491 setOperationAction(ISD::SELECT, MVT::i64, Expand); 492 setOperationAction(ISD::SELECT, MVT::f32, Expand); 493 setOperationAction(ISD::SELECT, MVT::f64, Expand); 494 } 495 496 // PowerPC wants to turn select_cc of FP into fsel when possible. 497 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 498 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 499 500 // PowerPC wants to optimize integer setcc a bit 501 if (!Subtarget.useCRBits()) 502 setOperationAction(ISD::SETCC, MVT::i32, Custom); 503 504 if (Subtarget.hasFPU()) { 505 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal); 506 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal); 507 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal); 508 509 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 510 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 511 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal); 512 } 513 514 // PowerPC does not have BRCOND which requires SetCC 515 if (!Subtarget.useCRBits()) 516 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 517 518 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 519 520 if (Subtarget.hasSPE()) { 521 // SPE has built-in conversions 522 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal); 523 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal); 524 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal); 525 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal); 526 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal); 527 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal); 528 529 // SPE supports signaling compare of f32/f64. 530 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal); 531 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal); 532 } else { 533 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. 534 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 535 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 536 537 // PowerPC does not have [U|S]INT_TO_FP 538 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand); 539 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand); 540 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); 541 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); 542 } 543 544 if (Subtarget.hasDirectMove() && isPPC64) { 545 setOperationAction(ISD::BITCAST, MVT::f32, Legal); 546 setOperationAction(ISD::BITCAST, MVT::i32, Legal); 547 setOperationAction(ISD::BITCAST, MVT::i64, Legal); 548 setOperationAction(ISD::BITCAST, MVT::f64, Legal); 549 if (TM.Options.UnsafeFPMath) { 550 setOperationAction(ISD::LRINT, MVT::f64, Legal); 551 setOperationAction(ISD::LRINT, MVT::f32, Legal); 552 setOperationAction(ISD::LLRINT, MVT::f64, Legal); 553 setOperationAction(ISD::LLRINT, MVT::f32, Legal); 554 setOperationAction(ISD::LROUND, MVT::f64, Legal); 555 setOperationAction(ISD::LROUND, MVT::f32, Legal); 556 setOperationAction(ISD::LLROUND, MVT::f64, Legal); 557 setOperationAction(ISD::LLROUND, MVT::f32, Legal); 558 } 559 } else { 560 setOperationAction(ISD::BITCAST, MVT::f32, Expand); 561 setOperationAction(ISD::BITCAST, MVT::i32, Expand); 562 setOperationAction(ISD::BITCAST, MVT::i64, Expand); 563 setOperationAction(ISD::BITCAST, MVT::f64, Expand); 564 } 565 566 // We cannot sextinreg(i1). Expand to shifts. 567 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 568 569 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support 570 // SjLj exception handling but a light-weight setjmp/longjmp replacement to 571 // support continuation, user-level threading, and etc.. As a result, no 572 // other SjLj exception interfaces are implemented and please don't build 573 // your own exception handling based on them. 574 // LLVM/Clang supports zero-cost DWARF exception handling. 575 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 576 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 577 578 // We want to legalize GlobalAddress and ConstantPool nodes into the 579 // appropriate instructions to materialize the address. 580 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 581 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); 582 setOperationAction(ISD::BlockAddress, MVT::i32, Custom); 583 setOperationAction(ISD::ConstantPool, MVT::i32, Custom); 584 setOperationAction(ISD::JumpTable, MVT::i32, Custom); 585 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 586 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 587 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 588 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 589 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 590 591 // TRAP is legal. 592 setOperationAction(ISD::TRAP, MVT::Other, Legal); 593 594 // TRAMPOLINE is custom lowered. 595 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); 596 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); 597 598 // VASTART needs to be custom lowered to use the VarArgsFrameIndex 599 setOperationAction(ISD::VASTART , MVT::Other, Custom); 600 601 if (Subtarget.is64BitELFABI()) { 602 // VAARG always uses double-word chunks, so promote anything smaller. 603 setOperationAction(ISD::VAARG, MVT::i1, Promote); 604 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64); 605 setOperationAction(ISD::VAARG, MVT::i8, Promote); 606 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64); 607 setOperationAction(ISD::VAARG, MVT::i16, Promote); 608 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64); 609 setOperationAction(ISD::VAARG, MVT::i32, Promote); 610 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64); 611 setOperationAction(ISD::VAARG, MVT::Other, Expand); 612 } else if (Subtarget.is32BitELFABI()) { 613 // VAARG is custom lowered with the 32-bit SVR4 ABI. 614 setOperationAction(ISD::VAARG, MVT::Other, Custom); 615 setOperationAction(ISD::VAARG, MVT::i64, Custom); 616 } else 617 setOperationAction(ISD::VAARG, MVT::Other, Expand); 618 619 // VACOPY is custom lowered with the 32-bit SVR4 ABI. 620 if (Subtarget.is32BitELFABI()) 621 setOperationAction(ISD::VACOPY , MVT::Other, Custom); 622 else 623 setOperationAction(ISD::VACOPY , MVT::Other, Expand); 624 625 // Use the default implementation. 626 setOperationAction(ISD::VAEND , MVT::Other, Expand); 627 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); 628 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); 629 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); 630 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); 631 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); 632 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); 633 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 634 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 635 636 // We want to custom lower some of our intrinsics. 637 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 638 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom); 639 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom); 640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 641 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom); 642 643 // To handle counter-based loop conditions. 644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); 645 646 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 647 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 648 setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom); 649 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 650 651 // Comparisons that require checking two conditions. 652 if (Subtarget.hasSPE()) { 653 setCondCodeAction(ISD::SETO, MVT::f32, Expand); 654 setCondCodeAction(ISD::SETO, MVT::f64, Expand); 655 setCondCodeAction(ISD::SETUO, MVT::f32, Expand); 656 setCondCodeAction(ISD::SETUO, MVT::f64, Expand); 657 } 658 setCondCodeAction(ISD::SETULT, MVT::f32, Expand); 659 setCondCodeAction(ISD::SETULT, MVT::f64, Expand); 660 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); 661 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); 662 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); 663 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); 664 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); 665 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); 666 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); 667 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); 668 setCondCodeAction(ISD::SETONE, MVT::f32, Expand); 669 setCondCodeAction(ISD::SETONE, MVT::f64, Expand); 670 671 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 672 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 673 674 if (Subtarget.has64BitSupport()) { 675 // They also have instructions for converting between i64 and fp. 676 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 677 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand); 678 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 679 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand); 680 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 681 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 682 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 683 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 684 // This is just the low 32 bits of a (signed) fp->i64 conversion. 685 // We cannot do this with Promote because i64 is not a legal type. 686 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 687 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 688 689 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) { 690 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 691 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 692 } 693 } else { 694 // PowerPC does not have FP_TO_UINT on 32-bit implementations. 695 if (Subtarget.hasSPE()) { 696 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal); 697 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal); 698 } else { 699 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand); 700 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); 701 } 702 } 703 704 // With the instructions enabled under FPCVT, we can do everything. 705 if (Subtarget.hasFPCVT()) { 706 if (Subtarget.has64BitSupport()) { 707 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 708 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 709 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 710 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 711 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 712 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 713 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 714 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 715 } 716 717 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 718 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 719 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 720 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 721 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 722 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 723 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 724 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 725 } 726 727 if (Subtarget.use64BitRegs()) { 728 // 64-bit PowerPC implementations can support i64 types directly 729 addRegisterClass(MVT::i64, &PPC::G8RCRegClass); 730 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or 731 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 732 // 64-bit PowerPC wants to expand i128 shifts itself. 733 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 734 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 735 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 736 } else { 737 // 32-bit PowerPC wants to expand i64 shifts itself. 738 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); 739 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); 740 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); 741 } 742 743 // PowerPC has better expansions for funnel shifts than the generic 744 // TargetLowering::expandFunnelShift. 745 if (Subtarget.has64BitSupport()) { 746 setOperationAction(ISD::FSHL, MVT::i64, Custom); 747 setOperationAction(ISD::FSHR, MVT::i64, Custom); 748 } 749 setOperationAction(ISD::FSHL, MVT::i32, Custom); 750 setOperationAction(ISD::FSHR, MVT::i32, Custom); 751 752 if (Subtarget.hasVSX()) { 753 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 754 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 755 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 756 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 757 } 758 759 if (Subtarget.hasAltivec()) { 760 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) { 761 setOperationAction(ISD::SADDSAT, VT, Legal); 762 setOperationAction(ISD::SSUBSAT, VT, Legal); 763 setOperationAction(ISD::UADDSAT, VT, Legal); 764 setOperationAction(ISD::USUBSAT, VT, Legal); 765 } 766 // First set operation action for all vector types to expand. Then we 767 // will selectively turn on ones that can be effectively codegen'd. 768 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 769 // add/sub are legal for all supported vector VT's. 770 setOperationAction(ISD::ADD, VT, Legal); 771 setOperationAction(ISD::SUB, VT, Legal); 772 773 // For v2i64, these are only valid with P8Vector. This is corrected after 774 // the loop. 775 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) { 776 setOperationAction(ISD::SMAX, VT, Legal); 777 setOperationAction(ISD::SMIN, VT, Legal); 778 setOperationAction(ISD::UMAX, VT, Legal); 779 setOperationAction(ISD::UMIN, VT, Legal); 780 } 781 else { 782 setOperationAction(ISD::SMAX, VT, Expand); 783 setOperationAction(ISD::SMIN, VT, Expand); 784 setOperationAction(ISD::UMAX, VT, Expand); 785 setOperationAction(ISD::UMIN, VT, Expand); 786 } 787 788 if (Subtarget.hasVSX()) { 789 setOperationAction(ISD::FMAXNUM, VT, Legal); 790 setOperationAction(ISD::FMINNUM, VT, Legal); 791 } 792 793 // Vector instructions introduced in P8 794 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { 795 setOperationAction(ISD::CTPOP, VT, Legal); 796 setOperationAction(ISD::CTLZ, VT, Legal); 797 } 798 else { 799 setOperationAction(ISD::CTPOP, VT, Expand); 800 setOperationAction(ISD::CTLZ, VT, Expand); 801 } 802 803 // Vector instructions introduced in P9 804 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128)) 805 setOperationAction(ISD::CTTZ, VT, Legal); 806 else 807 setOperationAction(ISD::CTTZ, VT, Expand); 808 809 // We promote all shuffles to v16i8. 810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); 811 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); 812 813 // We promote all non-typed operations to v4i32. 814 setOperationAction(ISD::AND , VT, Promote); 815 AddPromotedToType (ISD::AND , VT, MVT::v4i32); 816 setOperationAction(ISD::OR , VT, Promote); 817 AddPromotedToType (ISD::OR , VT, MVT::v4i32); 818 setOperationAction(ISD::XOR , VT, Promote); 819 AddPromotedToType (ISD::XOR , VT, MVT::v4i32); 820 setOperationAction(ISD::LOAD , VT, Promote); 821 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); 822 setOperationAction(ISD::SELECT, VT, Promote); 823 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); 824 setOperationAction(ISD::VSELECT, VT, Legal); 825 setOperationAction(ISD::SELECT_CC, VT, Promote); 826 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); 827 setOperationAction(ISD::STORE, VT, Promote); 828 AddPromotedToType (ISD::STORE, VT, MVT::v4i32); 829 830 // No other operations are legal. 831 setOperationAction(ISD::MUL , VT, Expand); 832 setOperationAction(ISD::SDIV, VT, Expand); 833 setOperationAction(ISD::SREM, VT, Expand); 834 setOperationAction(ISD::UDIV, VT, Expand); 835 setOperationAction(ISD::UREM, VT, Expand); 836 setOperationAction(ISD::FDIV, VT, Expand); 837 setOperationAction(ISD::FREM, VT, Expand); 838 setOperationAction(ISD::FNEG, VT, Expand); 839 setOperationAction(ISD::FSQRT, VT, Expand); 840 setOperationAction(ISD::FLOG, VT, Expand); 841 setOperationAction(ISD::FLOG10, VT, Expand); 842 setOperationAction(ISD::FLOG2, VT, Expand); 843 setOperationAction(ISD::FEXP, VT, Expand); 844 setOperationAction(ISD::FEXP2, VT, Expand); 845 setOperationAction(ISD::FSIN, VT, Expand); 846 setOperationAction(ISD::FCOS, VT, Expand); 847 setOperationAction(ISD::FABS, VT, Expand); 848 setOperationAction(ISD::FFLOOR, VT, Expand); 849 setOperationAction(ISD::FCEIL, VT, Expand); 850 setOperationAction(ISD::FTRUNC, VT, Expand); 851 setOperationAction(ISD::FRINT, VT, Expand); 852 setOperationAction(ISD::FNEARBYINT, VT, Expand); 853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); 854 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); 855 setOperationAction(ISD::BUILD_VECTOR, VT, Expand); 856 setOperationAction(ISD::MULHU, VT, Expand); 857 setOperationAction(ISD::MULHS, VT, Expand); 858 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 859 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 860 setOperationAction(ISD::UDIVREM, VT, Expand); 861 setOperationAction(ISD::SDIVREM, VT, Expand); 862 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); 863 setOperationAction(ISD::FPOW, VT, Expand); 864 setOperationAction(ISD::BSWAP, VT, Expand); 865 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 866 setOperationAction(ISD::ROTL, VT, Expand); 867 setOperationAction(ISD::ROTR, VT, Expand); 868 869 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 870 setTruncStoreAction(VT, InnerVT, Expand); 871 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 872 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 873 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 874 } 875 } 876 setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand); 877 if (!Subtarget.hasP8Vector()) { 878 setOperationAction(ISD::SMAX, MVT::v2i64, Expand); 879 setOperationAction(ISD::SMIN, MVT::v2i64, Expand); 880 setOperationAction(ISD::UMAX, MVT::v2i64, Expand); 881 setOperationAction(ISD::UMIN, MVT::v2i64, Expand); 882 } 883 884 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle 885 // with merges, splats, etc. 886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); 887 888 // Vector truncates to sub-word integer that fit in an Altivec/VSX register 889 // are cheap, so handle them before they get expanded to scalar. 890 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom); 891 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom); 892 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom); 893 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom); 894 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom); 895 896 setOperationAction(ISD::AND , MVT::v4i32, Legal); 897 setOperationAction(ISD::OR , MVT::v4i32, Legal); 898 setOperationAction(ISD::XOR , MVT::v4i32, Legal); 899 setOperationAction(ISD::LOAD , MVT::v4i32, Legal); 900 setOperationAction(ISD::SELECT, MVT::v4i32, 901 Subtarget.useCRBits() ? Legal : Expand); 902 setOperationAction(ISD::STORE , MVT::v4i32, Legal); 903 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal); 904 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal); 905 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal); 906 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal); 907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); 908 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); 909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); 910 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); 911 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); 912 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); 913 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); 914 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 915 916 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8. 917 setOperationAction(ISD::ROTL, MVT::v1i128, Custom); 918 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w). 919 if (Subtarget.hasAltivec()) 920 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8}) 921 setOperationAction(ISD::ROTL, VT, Legal); 922 // With hasP8Altivec set, we can lower ISD::ROTL to vrld. 923 if (Subtarget.hasP8Altivec()) 924 setOperationAction(ISD::ROTL, MVT::v2i64, Legal); 925 926 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); 927 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); 928 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); 929 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); 930 931 setOperationAction(ISD::MUL, MVT::v4f32, Legal); 932 setOperationAction(ISD::FMA, MVT::v4f32, Legal); 933 934 if (Subtarget.hasVSX()) { 935 setOperationAction(ISD::FDIV, MVT::v4f32, Legal); 936 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); 937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom); 938 } 939 940 if (Subtarget.hasP8Altivec()) 941 setOperationAction(ISD::MUL, MVT::v4i32, Legal); 942 else 943 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 944 945 if (Subtarget.isISA3_1()) { 946 setOperationAction(ISD::MUL, MVT::v2i64, Legal); 947 setOperationAction(ISD::MULHS, MVT::v2i64, Legal); 948 setOperationAction(ISD::MULHU, MVT::v2i64, Legal); 949 setOperationAction(ISD::MULHS, MVT::v4i32, Legal); 950 setOperationAction(ISD::MULHU, MVT::v4i32, Legal); 951 setOperationAction(ISD::UDIV, MVT::v2i64, Legal); 952 setOperationAction(ISD::SDIV, MVT::v2i64, Legal); 953 setOperationAction(ISD::UDIV, MVT::v4i32, Legal); 954 setOperationAction(ISD::SDIV, MVT::v4i32, Legal); 955 setOperationAction(ISD::UREM, MVT::v2i64, Legal); 956 setOperationAction(ISD::SREM, MVT::v2i64, Legal); 957 setOperationAction(ISD::UREM, MVT::v4i32, Legal); 958 setOperationAction(ISD::SREM, MVT::v4i32, Legal); 959 setOperationAction(ISD::UREM, MVT::v1i128, Legal); 960 setOperationAction(ISD::SREM, MVT::v1i128, Legal); 961 setOperationAction(ISD::UDIV, MVT::v1i128, Legal); 962 setOperationAction(ISD::SDIV, MVT::v1i128, Legal); 963 setOperationAction(ISD::ROTL, MVT::v1i128, Legal); 964 } 965 966 setOperationAction(ISD::MUL, MVT::v8i16, Legal); 967 setOperationAction(ISD::MUL, MVT::v16i8, Custom); 968 969 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); 970 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); 971 972 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); 973 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); 974 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); 975 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); 976 977 // Altivec does not contain unordered floating-point compare instructions 978 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); 979 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); 980 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); 981 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); 982 983 if (Subtarget.hasVSX()) { 984 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); 985 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 986 if (Subtarget.hasP8Vector()) { 987 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); 988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); 989 } 990 if (Subtarget.hasDirectMove() && isPPC64) { 991 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); 992 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); 993 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); 994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); 995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); 996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); 997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); 998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); 999 } 1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); 1001 1002 // The nearbyint variants are not allowed to raise the inexact exception 1003 // so we can only code-gen them with unsafe math. 1004 if (TM.Options.UnsafeFPMath) { 1005 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal); 1006 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal); 1007 } 1008 1009 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); 1010 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); 1011 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); 1012 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); 1013 setOperationAction(ISD::FRINT, MVT::v2f64, Legal); 1014 setOperationAction(ISD::FROUND, MVT::v2f64, Legal); 1015 setOperationAction(ISD::FROUND, MVT::f64, Legal); 1016 setOperationAction(ISD::FRINT, MVT::f64, Legal); 1017 1018 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); 1019 setOperationAction(ISD::FRINT, MVT::v4f32, Legal); 1020 setOperationAction(ISD::FROUND, MVT::v4f32, Legal); 1021 setOperationAction(ISD::FROUND, MVT::f32, Legal); 1022 setOperationAction(ISD::FRINT, MVT::f32, Legal); 1023 1024 setOperationAction(ISD::MUL, MVT::v2f64, Legal); 1025 setOperationAction(ISD::FMA, MVT::v2f64, Legal); 1026 1027 setOperationAction(ISD::FDIV, MVT::v2f64, Legal); 1028 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); 1029 1030 // Share the Altivec comparison restrictions. 1031 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); 1032 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); 1033 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); 1034 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); 1035 1036 setOperationAction(ISD::LOAD, MVT::v2f64, Legal); 1037 setOperationAction(ISD::STORE, MVT::v2f64, Legal); 1038 1039 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom); 1040 1041 if (Subtarget.hasP8Vector()) 1042 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); 1043 1044 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); 1045 1046 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); 1047 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); 1048 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); 1049 1050 if (Subtarget.hasP8Altivec()) { 1051 setOperationAction(ISD::SHL, MVT::v2i64, Legal); 1052 setOperationAction(ISD::SRA, MVT::v2i64, Legal); 1053 setOperationAction(ISD::SRL, MVT::v2i64, Legal); 1054 1055 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1056 // SRL, but not for SRA because of the instructions available: 1057 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth 1058 // doing 1059 setOperationAction(ISD::SHL, MVT::v1i128, Expand); 1060 setOperationAction(ISD::SRL, MVT::v1i128, Expand); 1061 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1062 1063 setOperationAction(ISD::SETCC, MVT::v2i64, Legal); 1064 } 1065 else { 1066 setOperationAction(ISD::SHL, MVT::v2i64, Expand); 1067 setOperationAction(ISD::SRA, MVT::v2i64, Expand); 1068 setOperationAction(ISD::SRL, MVT::v2i64, Expand); 1069 1070 setOperationAction(ISD::SETCC, MVT::v2i64, Custom); 1071 1072 // VSX v2i64 only supports non-arithmetic operations. 1073 setOperationAction(ISD::ADD, MVT::v2i64, Expand); 1074 setOperationAction(ISD::SUB, MVT::v2i64, Expand); 1075 } 1076 1077 if (Subtarget.isISA3_1()) 1078 setOperationAction(ISD::SETCC, MVT::v1i128, Legal); 1079 else 1080 setOperationAction(ISD::SETCC, MVT::v1i128, Expand); 1081 1082 setOperationAction(ISD::LOAD, MVT::v2i64, Promote); 1083 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); 1084 setOperationAction(ISD::STORE, MVT::v2i64, Promote); 1085 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); 1086 1087 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom); 1088 1089 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal); 1090 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal); 1091 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal); 1092 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal); 1093 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); 1094 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); 1095 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); 1096 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); 1097 1098 // Custom handling for partial vectors of integers converted to 1099 // floating point. We already have optimal handling for v2i32 through 1100 // the DAG combine, so those aren't necessary. 1101 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom); 1102 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom); 1103 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom); 1104 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom); 1105 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom); 1106 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom); 1107 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom); 1108 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom); 1109 setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom); 1110 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom); 1111 setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom); 1112 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 1113 setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom); 1114 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom); 1115 setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom); 1116 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 1117 1118 setOperationAction(ISD::FNEG, MVT::v4f32, Legal); 1119 setOperationAction(ISD::FNEG, MVT::v2f64, Legal); 1120 setOperationAction(ISD::FABS, MVT::v4f32, Legal); 1121 setOperationAction(ISD::FABS, MVT::v2f64, Legal); 1122 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); 1123 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal); 1124 1125 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom); 1126 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom); 1127 1128 // Handle constrained floating-point operations of vector. 1129 // The predictor is `hasVSX` because altivec instruction has 1130 // no exception but VSX vector instruction has. 1131 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal); 1132 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal); 1133 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal); 1134 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal); 1135 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal); 1136 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal); 1137 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal); 1138 setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal); 1139 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal); 1140 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal); 1141 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal); 1142 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal); 1143 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal); 1144 1145 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal); 1146 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal); 1147 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal); 1148 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal); 1149 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal); 1150 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal); 1151 setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal); 1152 setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal); 1153 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal); 1154 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal); 1155 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal); 1156 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal); 1157 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal); 1158 1159 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); 1160 addRegisterClass(MVT::f128, &PPC::VRRCRegClass); 1161 1162 for (MVT FPT : MVT::fp_valuetypes()) 1163 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand); 1164 1165 // Expand the SELECT to SELECT_CC 1166 setOperationAction(ISD::SELECT, MVT::f128, Expand); 1167 1168 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 1169 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 1170 1171 // No implementation for these ops for PowerPC. 1172 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 1173 setOperationAction(ISD::FSIN, MVT::f128, Expand); 1174 setOperationAction(ISD::FCOS, MVT::f128, Expand); 1175 setOperationAction(ISD::FPOW, MVT::f128, Expand); 1176 setOperationAction(ISD::FPOWI, MVT::f128, Expand); 1177 setOperationAction(ISD::FREM, MVT::f128, Expand); 1178 } 1179 1180 if (Subtarget.hasP8Altivec()) { 1181 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); 1182 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); 1183 } 1184 1185 if (Subtarget.hasP9Vector()) { 1186 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom); 1187 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom); 1188 1189 // 128 bit shifts can be accomplished via 3 instructions for SHL and 1190 // SRL, but not for SRA because of the instructions available: 1191 // VS{RL} and VS{RL}O. 1192 setOperationAction(ISD::SHL, MVT::v1i128, Legal); 1193 setOperationAction(ISD::SRL, MVT::v1i128, Legal); 1194 setOperationAction(ISD::SRA, MVT::v1i128, Expand); 1195 1196 setOperationAction(ISD::FADD, MVT::f128, Legal); 1197 setOperationAction(ISD::FSUB, MVT::f128, Legal); 1198 setOperationAction(ISD::FDIV, MVT::f128, Legal); 1199 setOperationAction(ISD::FMUL, MVT::f128, Legal); 1200 setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal); 1201 1202 setOperationAction(ISD::FMA, MVT::f128, Legal); 1203 setCondCodeAction(ISD::SETULT, MVT::f128, Expand); 1204 setCondCodeAction(ISD::SETUGT, MVT::f128, Expand); 1205 setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand); 1206 setCondCodeAction(ISD::SETOGE, MVT::f128, Expand); 1207 setCondCodeAction(ISD::SETOLE, MVT::f128, Expand); 1208 setCondCodeAction(ISD::SETONE, MVT::f128, Expand); 1209 1210 setOperationAction(ISD::FTRUNC, MVT::f128, Legal); 1211 setOperationAction(ISD::FRINT, MVT::f128, Legal); 1212 setOperationAction(ISD::FFLOOR, MVT::f128, Legal); 1213 setOperationAction(ISD::FCEIL, MVT::f128, Legal); 1214 setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal); 1215 setOperationAction(ISD::FROUND, MVT::f128, Legal); 1216 1217 setOperationAction(ISD::FP_ROUND, MVT::f64, Legal); 1218 setOperationAction(ISD::FP_ROUND, MVT::f32, Legal); 1219 setOperationAction(ISD::BITCAST, MVT::i128, Custom); 1220 1221 // Handle constrained floating-point operations of fp128 1222 setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal); 1223 setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal); 1224 setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal); 1225 setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal); 1226 setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal); 1227 setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal); 1228 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal); 1229 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal); 1230 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 1231 setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal); 1232 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal); 1233 setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal); 1234 setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal); 1235 setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal); 1236 setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal); 1237 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom); 1238 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal); 1239 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal); 1240 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal); 1241 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal); 1242 } else if (Subtarget.hasVSX()) { 1243 setOperationAction(ISD::LOAD, MVT::f128, Promote); 1244 setOperationAction(ISD::STORE, MVT::f128, Promote); 1245 1246 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32); 1247 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32); 1248 1249 // Set FADD/FSUB as libcall to avoid the legalizer to expand the 1250 // fp_to_uint and int_to_fp. 1251 setOperationAction(ISD::FADD, MVT::f128, LibCall); 1252 setOperationAction(ISD::FSUB, MVT::f128, LibCall); 1253 1254 setOperationAction(ISD::FMUL, MVT::f128, Expand); 1255 setOperationAction(ISD::FDIV, MVT::f128, Expand); 1256 setOperationAction(ISD::FNEG, MVT::f128, Expand); 1257 setOperationAction(ISD::FABS, MVT::f128, Expand); 1258 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 1259 setOperationAction(ISD::FMA, MVT::f128, Expand); 1260 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 1261 1262 // Expand the fp_extend if the target type is fp128. 1263 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand); 1264 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand); 1265 1266 // Expand the fp_round if the source type is fp128. 1267 for (MVT VT : {MVT::f32, MVT::f64}) { 1268 setOperationAction(ISD::FP_ROUND, VT, Custom); 1269 setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom); 1270 } 1271 1272 setOperationAction(ISD::SETCC, MVT::f128, Custom); 1273 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 1274 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 1275 setOperationAction(ISD::BR_CC, MVT::f128, Expand); 1276 1277 // Lower following f128 select_cc pattern: 1278 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE 1279 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1280 1281 // We need to handle f128 SELECT_CC with integer result type. 1282 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 1283 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand); 1284 } 1285 1286 if (Subtarget.hasP9Altivec()) { 1287 if (Subtarget.isISA3_1()) { 1288 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal); 1289 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal); 1290 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal); 1291 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal); 1292 } else { 1293 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom); 1294 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom); 1295 } 1296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal); 1297 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal); 1298 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal); 1299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal); 1300 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal); 1301 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); 1302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); 1303 1304 setOperationAction(ISD::ABDU, MVT::v16i8, Legal); 1305 setOperationAction(ISD::ABDU, MVT::v8i16, Legal); 1306 setOperationAction(ISD::ABDU, MVT::v4i32, Legal); 1307 setOperationAction(ISD::ABDS, MVT::v4i32, Legal); 1308 } 1309 1310 if (Subtarget.hasP10Vector()) { 1311 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 1312 } 1313 } 1314 1315 if (Subtarget.pairedVectorMemops()) { 1316 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass); 1317 setOperationAction(ISD::LOAD, MVT::v256i1, Custom); 1318 setOperationAction(ISD::STORE, MVT::v256i1, Custom); 1319 } 1320 if (Subtarget.hasMMA()) { 1321 if (Subtarget.isISAFuture()) 1322 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass); 1323 else 1324 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass); 1325 setOperationAction(ISD::LOAD, MVT::v512i1, Custom); 1326 setOperationAction(ISD::STORE, MVT::v512i1, Custom); 1327 setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom); 1328 } 1329 1330 if (Subtarget.has64BitSupport()) 1331 setOperationAction(ISD::PREFETCH, MVT::Other, Legal); 1332 1333 if (Subtarget.isISA3_1()) 1334 setOperationAction(ISD::SRA, MVT::v1i128, Legal); 1335 1336 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); 1337 1338 if (!isPPC64) { 1339 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); 1340 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); 1341 } 1342 1343 if (shouldInlineQuadwordAtomics()) { 1344 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom); 1345 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom); 1346 setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom); 1347 } 1348 1349 setBooleanContents(ZeroOrOneBooleanContent); 1350 1351 if (Subtarget.hasAltivec()) { 1352 // Altivec instructions set fields to all zeros or all ones. 1353 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 1354 } 1355 1356 setLibcallName(RTLIB::MULO_I128, nullptr); 1357 if (!isPPC64) { 1358 // These libcalls are not available in 32-bit. 1359 setLibcallName(RTLIB::SHL_I128, nullptr); 1360 setLibcallName(RTLIB::SRL_I128, nullptr); 1361 setLibcallName(RTLIB::SRA_I128, nullptr); 1362 setLibcallName(RTLIB::MUL_I128, nullptr); 1363 setLibcallName(RTLIB::MULO_I64, nullptr); 1364 } 1365 1366 if (!isPPC64) 1367 setMaxAtomicSizeInBitsSupported(32); 1368 else if (shouldInlineQuadwordAtomics()) 1369 setMaxAtomicSizeInBitsSupported(128); 1370 else 1371 setMaxAtomicSizeInBitsSupported(64); 1372 1373 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); 1374 1375 // We have target-specific dag combine patterns for the following nodes: 1376 setTargetDAGCombine({ISD::ADD, ISD::SHL, ISD::SRA, ISD::SRL, ISD::MUL, 1377 ISD::FMA, ISD::SINT_TO_FP, ISD::BUILD_VECTOR}); 1378 if (Subtarget.hasFPCVT()) 1379 setTargetDAGCombine(ISD::UINT_TO_FP); 1380 setTargetDAGCombine({ISD::LOAD, ISD::STORE, ISD::BR_CC}); 1381 if (Subtarget.useCRBits()) 1382 setTargetDAGCombine(ISD::BRCOND); 1383 setTargetDAGCombine({ISD::BSWAP, ISD::INTRINSIC_WO_CHAIN, 1384 ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}); 1385 1386 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND, ISD::ANY_EXTEND}); 1387 1388 setTargetDAGCombine({ISD::TRUNCATE, ISD::VECTOR_SHUFFLE}); 1389 1390 if (Subtarget.useCRBits()) { 1391 setTargetDAGCombine({ISD::TRUNCATE, ISD::SETCC, ISD::SELECT_CC}); 1392 } 1393 1394 if (Subtarget.hasP9Altivec()) { 1395 setTargetDAGCombine({ISD::VSELECT}); 1396 } 1397 1398 setLibcallName(RTLIB::LOG_F128, "logf128"); 1399 setLibcallName(RTLIB::LOG2_F128, "log2f128"); 1400 setLibcallName(RTLIB::LOG10_F128, "log10f128"); 1401 setLibcallName(RTLIB::EXP_F128, "expf128"); 1402 setLibcallName(RTLIB::EXP2_F128, "exp2f128"); 1403 setLibcallName(RTLIB::SIN_F128, "sinf128"); 1404 setLibcallName(RTLIB::COS_F128, "cosf128"); 1405 setLibcallName(RTLIB::SINCOS_F128, "sincosf128"); 1406 setLibcallName(RTLIB::POW_F128, "powf128"); 1407 setLibcallName(RTLIB::FMIN_F128, "fminf128"); 1408 setLibcallName(RTLIB::FMAX_F128, "fmaxf128"); 1409 setLibcallName(RTLIB::REM_F128, "fmodf128"); 1410 setLibcallName(RTLIB::SQRT_F128, "sqrtf128"); 1411 setLibcallName(RTLIB::CEIL_F128, "ceilf128"); 1412 setLibcallName(RTLIB::FLOOR_F128, "floorf128"); 1413 setLibcallName(RTLIB::TRUNC_F128, "truncf128"); 1414 setLibcallName(RTLIB::ROUND_F128, "roundf128"); 1415 setLibcallName(RTLIB::LROUND_F128, "lroundf128"); 1416 setLibcallName(RTLIB::LLROUND_F128, "llroundf128"); 1417 setLibcallName(RTLIB::RINT_F128, "rintf128"); 1418 setLibcallName(RTLIB::LRINT_F128, "lrintf128"); 1419 setLibcallName(RTLIB::LLRINT_F128, "llrintf128"); 1420 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128"); 1421 setLibcallName(RTLIB::FMA_F128, "fmaf128"); 1422 1423 // With 32 condition bits, we don't need to sink (and duplicate) compares 1424 // aggressively in CodeGenPrep. 1425 if (Subtarget.useCRBits()) { 1426 setHasMultipleConditionRegisters(); 1427 setJumpIsExpensive(); 1428 } 1429 1430 setMinFunctionAlignment(Align(4)); 1431 1432 switch (Subtarget.getCPUDirective()) { 1433 default: break; 1434 case PPC::DIR_970: 1435 case PPC::DIR_A2: 1436 case PPC::DIR_E500: 1437 case PPC::DIR_E500mc: 1438 case PPC::DIR_E5500: 1439 case PPC::DIR_PWR4: 1440 case PPC::DIR_PWR5: 1441 case PPC::DIR_PWR5X: 1442 case PPC::DIR_PWR6: 1443 case PPC::DIR_PWR6X: 1444 case PPC::DIR_PWR7: 1445 case PPC::DIR_PWR8: 1446 case PPC::DIR_PWR9: 1447 case PPC::DIR_PWR10: 1448 case PPC::DIR_PWR_FUTURE: 1449 setPrefLoopAlignment(Align(16)); 1450 setPrefFunctionAlignment(Align(16)); 1451 break; 1452 } 1453 1454 if (Subtarget.enableMachineScheduler()) 1455 setSchedulingPreference(Sched::Source); 1456 else 1457 setSchedulingPreference(Sched::Hybrid); 1458 1459 computeRegisterProperties(STI.getRegisterInfo()); 1460 1461 // The Freescale cores do better with aggressive inlining of memcpy and 1462 // friends. GCC uses same threshold of 128 bytes (= 32 word stores). 1463 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc || 1464 Subtarget.getCPUDirective() == PPC::DIR_E5500) { 1465 MaxStoresPerMemset = 32; 1466 MaxStoresPerMemsetOptSize = 16; 1467 MaxStoresPerMemcpy = 32; 1468 MaxStoresPerMemcpyOptSize = 8; 1469 MaxStoresPerMemmove = 32; 1470 MaxStoresPerMemmoveOptSize = 8; 1471 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) { 1472 // The A2 also benefits from (very) aggressive inlining of memcpy and 1473 // friends. The overhead of a the function call, even when warm, can be 1474 // over one hundred cycles. 1475 MaxStoresPerMemset = 128; 1476 MaxStoresPerMemcpy = 128; 1477 MaxStoresPerMemmove = 128; 1478 MaxLoadsPerMemcmp = 128; 1479 } else { 1480 MaxLoadsPerMemcmp = 8; 1481 MaxLoadsPerMemcmpOptSize = 4; 1482 } 1483 1484 IsStrictFPEnabled = true; 1485 1486 // Let the subtarget (CPU) decide if a predictable select is more expensive 1487 // than the corresponding branch. This information is used in CGP to decide 1488 // when to convert selects into branches. 1489 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive(); 1490 } 1491 1492 // *********************************** NOTE ************************************ 1493 // For selecting load and store instructions, the addressing modes are defined 1494 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD 1495 // patterns to match the load the store instructions. 1496 // 1497 // The TD definitions for the addressing modes correspond to their respective 1498 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely 1499 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the 1500 // address mode flags of a particular node. Afterwards, the computed address 1501 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal 1502 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement 1503 // accordingly, based on the preferred addressing mode. 1504 // 1505 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode. 1506 // MemOpFlags contains all the possible flags that can be used to compute the 1507 // optimal addressing mode for load and store instructions. 1508 // AddrMode contains all the possible load and store addressing modes available 1509 // on Power (such as DForm, DSForm, DQForm, XForm, etc.) 1510 // 1511 // When adding new load and store instructions, it is possible that new address 1512 // flags may need to be added into MemOpFlags, and a new addressing mode will 1513 // need to be added to AddrMode. An entry of the new addressing mode (consisting 1514 // of the minimal and main distinguishing address flags for the new load/store 1515 // instructions) will need to be added into initializeAddrModeMap() below. 1516 // Finally, when adding new addressing modes, the getAddrModeForFlags() will 1517 // need to be updated to account for selecting the optimal addressing mode. 1518 // ***************************************************************************** 1519 /// Initialize the map that relates the different addressing modes of the load 1520 /// and store instructions to a set of flags. This ensures the load/store 1521 /// instruction is correctly matched during instruction selection. 1522 void PPCTargetLowering::initializeAddrModeMap() { 1523 AddrModesMap[PPC::AM_DForm] = { 1524 // LWZ, STW 1525 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt, 1526 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt, 1527 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1528 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1529 // LBZ, LHZ, STB, STH 1530 PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1531 PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1532 PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1533 PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1534 // LHA 1535 PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt, 1536 PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt, 1537 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt, 1538 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt, 1539 // LFS, LFD, STFS, STFD 1540 PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1541 PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1542 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1543 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9, 1544 }; 1545 AddrModesMap[PPC::AM_DSForm] = { 1546 // LWA 1547 PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt, 1548 PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt, 1549 PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt, 1550 // LD, STD 1551 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt, 1552 PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt, 1553 PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt, 1554 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64 1555 PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1556 PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1557 PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9, 1558 }; 1559 AddrModesMap[PPC::AM_DQForm] = { 1560 // LXV, STXV 1561 PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1562 PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1563 PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9, 1564 }; 1565 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 | 1566 PPC::MOF_SubtargetP10}; 1567 // TODO: Add mapping for quadword load/store. 1568 } 1569 1570 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine 1571 /// the desired ByVal argument alignment. 1572 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) { 1573 if (MaxAlign == MaxMaxAlign) 1574 return; 1575 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1576 if (MaxMaxAlign >= 32 && 1577 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256) 1578 MaxAlign = Align(32); 1579 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 && 1580 MaxAlign < 16) 1581 MaxAlign = Align(16); 1582 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1583 Align EltAlign; 1584 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); 1585 if (EltAlign > MaxAlign) 1586 MaxAlign = EltAlign; 1587 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 1588 for (auto *EltTy : STy->elements()) { 1589 Align EltAlign; 1590 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); 1591 if (EltAlign > MaxAlign) 1592 MaxAlign = EltAlign; 1593 if (MaxAlign == MaxMaxAlign) 1594 break; 1595 } 1596 } 1597 } 1598 1599 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 1600 /// function arguments in the caller parameter area. 1601 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty, 1602 const DataLayout &DL) const { 1603 // 16byte and wider vectors are passed on 16byte boundary. 1604 // The rest is 8 on PPC64 and 4 on PPC32 boundary. 1605 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 1606 if (Subtarget.hasAltivec()) 1607 getMaxByValAlign(Ty, Alignment, Align(16)); 1608 return Alignment.value(); 1609 } 1610 1611 bool PPCTargetLowering::useSoftFloat() const { 1612 return Subtarget.useSoftFloat(); 1613 } 1614 1615 bool PPCTargetLowering::hasSPE() const { 1616 return Subtarget.hasSPE(); 1617 } 1618 1619 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 1620 return VT.isScalarInteger(); 1621 } 1622 1623 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { 1624 switch ((PPCISD::NodeType)Opcode) { 1625 case PPCISD::FIRST_NUMBER: break; 1626 case PPCISD::FSEL: return "PPCISD::FSEL"; 1627 case PPCISD::XSMAXC: return "PPCISD::XSMAXC"; 1628 case PPCISD::XSMINC: return "PPCISD::XSMINC"; 1629 case PPCISD::FCFID: return "PPCISD::FCFID"; 1630 case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; 1631 case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; 1632 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; 1633 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; 1634 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; 1635 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; 1636 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; 1637 case PPCISD::FP_TO_UINT_IN_VSR: 1638 return "PPCISD::FP_TO_UINT_IN_VSR,"; 1639 case PPCISD::FP_TO_SINT_IN_VSR: 1640 return "PPCISD::FP_TO_SINT_IN_VSR"; 1641 case PPCISD::FRE: return "PPCISD::FRE"; 1642 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; 1643 case PPCISD::FTSQRT: 1644 return "PPCISD::FTSQRT"; 1645 case PPCISD::FSQRT: 1646 return "PPCISD::FSQRT"; 1647 case PPCISD::STFIWX: return "PPCISD::STFIWX"; 1648 case PPCISD::VPERM: return "PPCISD::VPERM"; 1649 case PPCISD::XXSPLT: return "PPCISD::XXSPLT"; 1650 case PPCISD::XXSPLTI_SP_TO_DP: 1651 return "PPCISD::XXSPLTI_SP_TO_DP"; 1652 case PPCISD::XXSPLTI32DX: 1653 return "PPCISD::XXSPLTI32DX"; 1654 case PPCISD::VECINSERT: return "PPCISD::VECINSERT"; 1655 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI"; 1656 case PPCISD::XXPERM: 1657 return "PPCISD::XXPERM"; 1658 case PPCISD::VECSHL: return "PPCISD::VECSHL"; 1659 case PPCISD::CMPB: return "PPCISD::CMPB"; 1660 case PPCISD::Hi: return "PPCISD::Hi"; 1661 case PPCISD::Lo: return "PPCISD::Lo"; 1662 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; 1663 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8"; 1664 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16"; 1665 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; 1666 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; 1667 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA"; 1668 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; 1669 case PPCISD::SRL: return "PPCISD::SRL"; 1670 case PPCISD::SRA: return "PPCISD::SRA"; 1671 case PPCISD::SHL: return "PPCISD::SHL"; 1672 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; 1673 case PPCISD::CALL: return "PPCISD::CALL"; 1674 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; 1675 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC"; 1676 case PPCISD::CALL_RM: 1677 return "PPCISD::CALL_RM"; 1678 case PPCISD::CALL_NOP_RM: 1679 return "PPCISD::CALL_NOP_RM"; 1680 case PPCISD::CALL_NOTOC_RM: 1681 return "PPCISD::CALL_NOTOC_RM"; 1682 case PPCISD::MTCTR: return "PPCISD::MTCTR"; 1683 case PPCISD::BCTRL: return "PPCISD::BCTRL"; 1684 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; 1685 case PPCISD::BCTRL_RM: 1686 return "PPCISD::BCTRL_RM"; 1687 case PPCISD::BCTRL_LOAD_TOC_RM: 1688 return "PPCISD::BCTRL_LOAD_TOC_RM"; 1689 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; 1690 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; 1691 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; 1692 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; 1693 case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; 1694 case PPCISD::MFVSR: return "PPCISD::MFVSR"; 1695 case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; 1696 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; 1697 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP"; 1698 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP"; 1699 case PPCISD::SCALAR_TO_VECTOR_PERMUTED: 1700 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED"; 1701 case PPCISD::ANDI_rec_1_EQ_BIT: 1702 return "PPCISD::ANDI_rec_1_EQ_BIT"; 1703 case PPCISD::ANDI_rec_1_GT_BIT: 1704 return "PPCISD::ANDI_rec_1_GT_BIT"; 1705 case PPCISD::VCMP: return "PPCISD::VCMP"; 1706 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec"; 1707 case PPCISD::LBRX: return "PPCISD::LBRX"; 1708 case PPCISD::STBRX: return "PPCISD::STBRX"; 1709 case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; 1710 case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; 1711 case PPCISD::LXSIZX: return "PPCISD::LXSIZX"; 1712 case PPCISD::STXSIX: return "PPCISD::STXSIX"; 1713 case PPCISD::VEXTS: return "PPCISD::VEXTS"; 1714 case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; 1715 case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; 1716 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE"; 1717 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE"; 1718 case PPCISD::ST_VSR_SCAL_INT: 1719 return "PPCISD::ST_VSR_SCAL_INT"; 1720 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; 1721 case PPCISD::BDNZ: return "PPCISD::BDNZ"; 1722 case PPCISD::BDZ: return "PPCISD::BDZ"; 1723 case PPCISD::MFFS: return "PPCISD::MFFS"; 1724 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; 1725 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; 1726 case PPCISD::CR6SET: return "PPCISD::CR6SET"; 1727 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; 1728 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; 1729 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; 1730 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; 1731 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; 1732 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; 1733 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; 1734 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; 1735 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; 1736 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; 1737 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX"; 1738 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; 1739 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; 1740 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; 1741 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; 1742 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; 1743 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; 1744 case PPCISD::PADDI_DTPREL: 1745 return "PPCISD::PADDI_DTPREL"; 1746 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; 1747 case PPCISD::SC: return "PPCISD::SC"; 1748 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; 1749 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; 1750 case PPCISD::RFEBB: return "PPCISD::RFEBB"; 1751 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; 1752 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN"; 1753 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128"; 1754 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64"; 1755 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE"; 1756 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI"; 1757 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH"; 1758 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF"; 1759 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR"; 1760 case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR: 1761 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR"; 1762 case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR: 1763 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR"; 1764 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD"; 1765 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD"; 1766 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG"; 1767 case PPCISD::XXMFACC: return "PPCISD::XXMFACC"; 1768 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT"; 1769 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT"; 1770 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT"; 1771 case PPCISD::FNMSUB: return "PPCISD::FNMSUB"; 1772 case PPCISD::STRICT_FADDRTZ: 1773 return "PPCISD::STRICT_FADDRTZ"; 1774 case PPCISD::STRICT_FCTIDZ: 1775 return "PPCISD::STRICT_FCTIDZ"; 1776 case PPCISD::STRICT_FCTIWZ: 1777 return "PPCISD::STRICT_FCTIWZ"; 1778 case PPCISD::STRICT_FCTIDUZ: 1779 return "PPCISD::STRICT_FCTIDUZ"; 1780 case PPCISD::STRICT_FCTIWUZ: 1781 return "PPCISD::STRICT_FCTIWUZ"; 1782 case PPCISD::STRICT_FCFID: 1783 return "PPCISD::STRICT_FCFID"; 1784 case PPCISD::STRICT_FCFIDU: 1785 return "PPCISD::STRICT_FCFIDU"; 1786 case PPCISD::STRICT_FCFIDS: 1787 return "PPCISD::STRICT_FCFIDS"; 1788 case PPCISD::STRICT_FCFIDUS: 1789 return "PPCISD::STRICT_FCFIDUS"; 1790 case PPCISD::LXVRZX: return "PPCISD::LXVRZX"; 1791 case PPCISD::STORE_COND: 1792 return "PPCISD::STORE_COND"; 1793 } 1794 return nullptr; 1795 } 1796 1797 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, 1798 EVT VT) const { 1799 if (!VT.isVector()) 1800 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; 1801 1802 return VT.changeVectorElementTypeToInteger(); 1803 } 1804 1805 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { 1806 assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); 1807 return true; 1808 } 1809 1810 //===----------------------------------------------------------------------===// 1811 // Node matching predicates, for use by the tblgen matching code. 1812 //===----------------------------------------------------------------------===// 1813 1814 /// isFloatingPointZero - Return true if this is 0.0 or -0.0. 1815 static bool isFloatingPointZero(SDValue Op) { 1816 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) 1817 return CFP->getValueAPF().isZero(); 1818 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { 1819 // Maybe this has already been legalized into the constant pool? 1820 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) 1821 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) 1822 return CFP->getValueAPF().isZero(); 1823 } 1824 return false; 1825 } 1826 1827 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return 1828 /// true if Op is undef or if it matches the specified value. 1829 static bool isConstantOrUndef(int Op, int Val) { 1830 return Op < 0 || Op == Val; 1831 } 1832 1833 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a 1834 /// VPKUHUM instruction. 1835 /// The ShuffleKind distinguishes between big-endian operations with 1836 /// two different inputs (0), either-endian operations with two identical 1837 /// inputs (1), and little-endian operations with two different inputs (2). 1838 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1839 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1840 SelectionDAG &DAG) { 1841 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1842 if (ShuffleKind == 0) { 1843 if (IsLE) 1844 return false; 1845 for (unsigned i = 0; i != 16; ++i) 1846 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) 1847 return false; 1848 } else if (ShuffleKind == 2) { 1849 if (!IsLE) 1850 return false; 1851 for (unsigned i = 0; i != 16; ++i) 1852 if (!isConstantOrUndef(N->getMaskElt(i), i*2)) 1853 return false; 1854 } else if (ShuffleKind == 1) { 1855 unsigned j = IsLE ? 0 : 1; 1856 for (unsigned i = 0; i != 8; ++i) 1857 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || 1858 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) 1859 return false; 1860 } 1861 return true; 1862 } 1863 1864 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a 1865 /// VPKUWUM instruction. 1866 /// The ShuffleKind distinguishes between big-endian operations with 1867 /// two different inputs (0), either-endian operations with two identical 1868 /// inputs (1), and little-endian operations with two different inputs (2). 1869 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1870 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1871 SelectionDAG &DAG) { 1872 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1873 if (ShuffleKind == 0) { 1874 if (IsLE) 1875 return false; 1876 for (unsigned i = 0; i != 16; i += 2) 1877 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || 1878 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) 1879 return false; 1880 } else if (ShuffleKind == 2) { 1881 if (!IsLE) 1882 return false; 1883 for (unsigned i = 0; i != 16; i += 2) 1884 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1885 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) 1886 return false; 1887 } else if (ShuffleKind == 1) { 1888 unsigned j = IsLE ? 0 : 2; 1889 for (unsigned i = 0; i != 8; i += 2) 1890 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1891 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1892 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1893 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) 1894 return false; 1895 } 1896 return true; 1897 } 1898 1899 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a 1900 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the 1901 /// current subtarget. 1902 /// 1903 /// The ShuffleKind distinguishes between big-endian operations with 1904 /// two different inputs (0), either-endian operations with two identical 1905 /// inputs (1), and little-endian operations with two different inputs (2). 1906 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). 1907 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, 1908 SelectionDAG &DAG) { 1909 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 1910 if (!Subtarget.hasP8Vector()) 1911 return false; 1912 1913 bool IsLE = DAG.getDataLayout().isLittleEndian(); 1914 if (ShuffleKind == 0) { 1915 if (IsLE) 1916 return false; 1917 for (unsigned i = 0; i != 16; i += 4) 1918 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || 1919 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || 1920 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || 1921 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) 1922 return false; 1923 } else if (ShuffleKind == 2) { 1924 if (!IsLE) 1925 return false; 1926 for (unsigned i = 0; i != 16; i += 4) 1927 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || 1928 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || 1929 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || 1930 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) 1931 return false; 1932 } else if (ShuffleKind == 1) { 1933 unsigned j = IsLE ? 0 : 4; 1934 for (unsigned i = 0; i != 8; i += 4) 1935 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || 1936 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || 1937 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || 1938 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || 1939 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || 1940 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || 1941 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || 1942 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) 1943 return false; 1944 } 1945 return true; 1946 } 1947 1948 /// isVMerge - Common function, used to match vmrg* shuffles. 1949 /// 1950 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, 1951 unsigned LHSStart, unsigned RHSStart) { 1952 if (N->getValueType(0) != MVT::v16i8) 1953 return false; 1954 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && 1955 "Unsupported merge size!"); 1956 1957 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units 1958 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit 1959 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), 1960 LHSStart+j+i*UnitSize) || 1961 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), 1962 RHSStart+j+i*UnitSize)) 1963 return false; 1964 } 1965 return true; 1966 } 1967 1968 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for 1969 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). 1970 /// The ShuffleKind distinguishes between big-endian merges with two 1971 /// different inputs (0), either-endian merges with two identical inputs (1), 1972 /// and little-endian merges with two different inputs (2). For the latter, 1973 /// the input operands are swapped (see PPCInstrAltivec.td). 1974 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 1975 unsigned ShuffleKind, SelectionDAG &DAG) { 1976 if (DAG.getDataLayout().isLittleEndian()) { 1977 if (ShuffleKind == 1) // unary 1978 return isVMerge(N, UnitSize, 0, 0); 1979 else if (ShuffleKind == 2) // swapped 1980 return isVMerge(N, UnitSize, 0, 16); 1981 else 1982 return false; 1983 } else { 1984 if (ShuffleKind == 1) // unary 1985 return isVMerge(N, UnitSize, 8, 8); 1986 else if (ShuffleKind == 0) // normal 1987 return isVMerge(N, UnitSize, 8, 24); 1988 else 1989 return false; 1990 } 1991 } 1992 1993 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for 1994 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). 1995 /// The ShuffleKind distinguishes between big-endian merges with two 1996 /// different inputs (0), either-endian merges with two identical inputs (1), 1997 /// and little-endian merges with two different inputs (2). For the latter, 1998 /// the input operands are swapped (see PPCInstrAltivec.td). 1999 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, 2000 unsigned ShuffleKind, SelectionDAG &DAG) { 2001 if (DAG.getDataLayout().isLittleEndian()) { 2002 if (ShuffleKind == 1) // unary 2003 return isVMerge(N, UnitSize, 8, 8); 2004 else if (ShuffleKind == 2) // swapped 2005 return isVMerge(N, UnitSize, 8, 24); 2006 else 2007 return false; 2008 } else { 2009 if (ShuffleKind == 1) // unary 2010 return isVMerge(N, UnitSize, 0, 0); 2011 else if (ShuffleKind == 0) // normal 2012 return isVMerge(N, UnitSize, 0, 16); 2013 else 2014 return false; 2015 } 2016 } 2017 2018 /** 2019 * Common function used to match vmrgew and vmrgow shuffles 2020 * 2021 * The indexOffset determines whether to look for even or odd words in 2022 * the shuffle mask. This is based on the of the endianness of the target 2023 * machine. 2024 * - Little Endian: 2025 * - Use offset of 0 to check for odd elements 2026 * - Use offset of 4 to check for even elements 2027 * - Big Endian: 2028 * - Use offset of 0 to check for even elements 2029 * - Use offset of 4 to check for odd elements 2030 * A detailed description of the vector element ordering for little endian and 2031 * big endian can be found at 2032 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html 2033 * Targeting your applications - what little endian and big endian IBM XL C/C++ 2034 * compiler differences mean to you 2035 * 2036 * The mask to the shuffle vector instruction specifies the indices of the 2037 * elements from the two input vectors to place in the result. The elements are 2038 * numbered in array-access order, starting with the first vector. These vectors 2039 * are always of type v16i8, thus each vector will contain 16 elements of size 2040 * 8. More info on the shuffle vector can be found in the 2041 * http://llvm.org/docs/LangRef.html#shufflevector-instruction 2042 * Language Reference. 2043 * 2044 * The RHSStartValue indicates whether the same input vectors are used (unary) 2045 * or two different input vectors are used, based on the following: 2046 * - If the instruction uses the same vector for both inputs, the range of the 2047 * indices will be 0 to 15. In this case, the RHSStart value passed should 2048 * be 0. 2049 * - If the instruction has two different vectors then the range of the 2050 * indices will be 0 to 31. In this case, the RHSStart value passed should 2051 * be 16 (indices 0-15 specify elements in the first vector while indices 16 2052 * to 31 specify elements in the second vector). 2053 * 2054 * \param[in] N The shuffle vector SD Node to analyze 2055 * \param[in] IndexOffset Specifies whether to look for even or odd elements 2056 * \param[in] RHSStartValue Specifies the starting index for the righthand input 2057 * vector to the shuffle_vector instruction 2058 * \return true iff this shuffle vector represents an even or odd word merge 2059 */ 2060 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, 2061 unsigned RHSStartValue) { 2062 if (N->getValueType(0) != MVT::v16i8) 2063 return false; 2064 2065 for (unsigned i = 0; i < 2; ++i) 2066 for (unsigned j = 0; j < 4; ++j) 2067 if (!isConstantOrUndef(N->getMaskElt(i*4+j), 2068 i*RHSStartValue+j+IndexOffset) || 2069 !isConstantOrUndef(N->getMaskElt(i*4+j+8), 2070 i*RHSStartValue+j+IndexOffset+8)) 2071 return false; 2072 return true; 2073 } 2074 2075 /** 2076 * Determine if the specified shuffle mask is suitable for the vmrgew or 2077 * vmrgow instructions. 2078 * 2079 * \param[in] N The shuffle vector SD Node to analyze 2080 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) 2081 * \param[in] ShuffleKind Identify the type of merge: 2082 * - 0 = big-endian merge with two different inputs; 2083 * - 1 = either-endian merge with two identical inputs; 2084 * - 2 = little-endian merge with two different inputs (inputs are swapped for 2085 * little-endian merges). 2086 * \param[in] DAG The current SelectionDAG 2087 * \return true iff this shuffle mask 2088 */ 2089 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, 2090 unsigned ShuffleKind, SelectionDAG &DAG) { 2091 if (DAG.getDataLayout().isLittleEndian()) { 2092 unsigned indexOffset = CheckEven ? 4 : 0; 2093 if (ShuffleKind == 1) // Unary 2094 return isVMerge(N, indexOffset, 0); 2095 else if (ShuffleKind == 2) // swapped 2096 return isVMerge(N, indexOffset, 16); 2097 else 2098 return false; 2099 } 2100 else { 2101 unsigned indexOffset = CheckEven ? 0 : 4; 2102 if (ShuffleKind == 1) // Unary 2103 return isVMerge(N, indexOffset, 0); 2104 else if (ShuffleKind == 0) // Normal 2105 return isVMerge(N, indexOffset, 16); 2106 else 2107 return false; 2108 } 2109 return false; 2110 } 2111 2112 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift 2113 /// amount, otherwise return -1. 2114 /// The ShuffleKind distinguishes between big-endian operations with two 2115 /// different inputs (0), either-endian operations with two identical inputs 2116 /// (1), and little-endian operations with two different inputs (2). For the 2117 /// latter, the input operands are swapped (see PPCInstrAltivec.td). 2118 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, 2119 SelectionDAG &DAG) { 2120 if (N->getValueType(0) != MVT::v16i8) 2121 return -1; 2122 2123 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2124 2125 // Find the first non-undef value in the shuffle mask. 2126 unsigned i; 2127 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) 2128 /*search*/; 2129 2130 if (i == 16) return -1; // all undef. 2131 2132 // Otherwise, check to see if the rest of the elements are consecutively 2133 // numbered from this value. 2134 unsigned ShiftAmt = SVOp->getMaskElt(i); 2135 if (ShiftAmt < i) return -1; 2136 2137 ShiftAmt -= i; 2138 bool isLE = DAG.getDataLayout().isLittleEndian(); 2139 2140 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { 2141 // Check the rest of the elements to see if they are consecutive. 2142 for (++i; i != 16; ++i) 2143 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) 2144 return -1; 2145 } else if (ShuffleKind == 1) { 2146 // Check the rest of the elements to see if they are consecutive. 2147 for (++i; i != 16; ++i) 2148 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) 2149 return -1; 2150 } else 2151 return -1; 2152 2153 if (isLE) 2154 ShiftAmt = 16 - ShiftAmt; 2155 2156 return ShiftAmt; 2157 } 2158 2159 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand 2160 /// specifies a splat of a single element that is suitable for input to 2161 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.). 2162 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { 2163 EVT VT = N->getValueType(0); 2164 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2165 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1); 2166 2167 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) && 2168 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes"); 2169 2170 // The consecutive indices need to specify an element, not part of two 2171 // different elements. So abandon ship early if this isn't the case. 2172 if (N->getMaskElt(0) % EltSize != 0) 2173 return false; 2174 2175 // This is a splat operation if each element of the permute is the same, and 2176 // if the value doesn't reference the second vector. 2177 unsigned ElementBase = N->getMaskElt(0); 2178 2179 // FIXME: Handle UNDEF elements too! 2180 if (ElementBase >= 16) 2181 return false; 2182 2183 // Check that the indices are consecutive, in the case of a multi-byte element 2184 // splatted with a v16i8 mask. 2185 for (unsigned i = 1; i != EltSize; ++i) 2186 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) 2187 return false; 2188 2189 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { 2190 if (N->getMaskElt(i) < 0) continue; 2191 for (unsigned j = 0; j != EltSize; ++j) 2192 if (N->getMaskElt(i+j) != N->getMaskElt(j)) 2193 return false; 2194 } 2195 return true; 2196 } 2197 2198 /// Check that the mask is shuffling N byte elements. Within each N byte 2199 /// element of the mask, the indices could be either in increasing or 2200 /// decreasing order as long as they are consecutive. 2201 /// \param[in] N the shuffle vector SD Node to analyze 2202 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/ 2203 /// Word/DoubleWord/QuadWord). 2204 /// \param[in] StepLen the delta indices number among the N byte element, if 2205 /// the mask is in increasing/decreasing order then it is 1/-1. 2206 /// \return true iff the mask is shuffling N byte elements. 2207 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width, 2208 int StepLen) { 2209 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) && 2210 "Unexpected element width."); 2211 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width."); 2212 2213 unsigned NumOfElem = 16 / Width; 2214 unsigned MaskVal[16]; // Width is never greater than 16 2215 for (unsigned i = 0; i < NumOfElem; ++i) { 2216 MaskVal[0] = N->getMaskElt(i * Width); 2217 if ((StepLen == 1) && (MaskVal[0] % Width)) { 2218 return false; 2219 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) { 2220 return false; 2221 } 2222 2223 for (unsigned int j = 1; j < Width; ++j) { 2224 MaskVal[j] = N->getMaskElt(i * Width + j); 2225 if (MaskVal[j] != MaskVal[j-1] + StepLen) { 2226 return false; 2227 } 2228 } 2229 } 2230 2231 return true; 2232 } 2233 2234 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2235 unsigned &InsertAtByte, bool &Swap, bool IsLE) { 2236 if (!isNByteElemShuffleMask(N, 4, 1)) 2237 return false; 2238 2239 // Now we look at mask elements 0,4,8,12 2240 unsigned M0 = N->getMaskElt(0) / 4; 2241 unsigned M1 = N->getMaskElt(4) / 4; 2242 unsigned M2 = N->getMaskElt(8) / 4; 2243 unsigned M3 = N->getMaskElt(12) / 4; 2244 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 }; 2245 unsigned BigEndianShifts[] = { 3, 0, 1, 2 }; 2246 2247 // Below, let H and L be arbitrary elements of the shuffle mask 2248 // where H is in the range [4,7] and L is in the range [0,3]. 2249 // H, 1, 2, 3 or L, 5, 6, 7 2250 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) || 2251 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) { 2252 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3]; 2253 InsertAtByte = IsLE ? 12 : 0; 2254 Swap = M0 < 4; 2255 return true; 2256 } 2257 // 0, H, 2, 3 or 4, L, 6, 7 2258 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) || 2259 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) { 2260 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3]; 2261 InsertAtByte = IsLE ? 8 : 4; 2262 Swap = M1 < 4; 2263 return true; 2264 } 2265 // 0, 1, H, 3 or 4, 5, L, 7 2266 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) || 2267 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) { 2268 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3]; 2269 InsertAtByte = IsLE ? 4 : 8; 2270 Swap = M2 < 4; 2271 return true; 2272 } 2273 // 0, 1, 2, H or 4, 5, 6, L 2274 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) || 2275 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) { 2276 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3]; 2277 InsertAtByte = IsLE ? 0 : 12; 2278 Swap = M3 < 4; 2279 return true; 2280 } 2281 2282 // If both vector operands for the shuffle are the same vector, the mask will 2283 // contain only elements from the first one and the second one will be undef. 2284 if (N->getOperand(1).isUndef()) { 2285 ShiftElts = 0; 2286 Swap = true; 2287 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1; 2288 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) { 2289 InsertAtByte = IsLE ? 12 : 0; 2290 return true; 2291 } 2292 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) { 2293 InsertAtByte = IsLE ? 8 : 4; 2294 return true; 2295 } 2296 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) { 2297 InsertAtByte = IsLE ? 4 : 8; 2298 return true; 2299 } 2300 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) { 2301 InsertAtByte = IsLE ? 0 : 12; 2302 return true; 2303 } 2304 } 2305 2306 return false; 2307 } 2308 2309 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, 2310 bool &Swap, bool IsLE) { 2311 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2312 // Ensure each byte index of the word is consecutive. 2313 if (!isNByteElemShuffleMask(N, 4, 1)) 2314 return false; 2315 2316 // Now we look at mask elements 0,4,8,12, which are the beginning of words. 2317 unsigned M0 = N->getMaskElt(0) / 4; 2318 unsigned M1 = N->getMaskElt(4) / 4; 2319 unsigned M2 = N->getMaskElt(8) / 4; 2320 unsigned M3 = N->getMaskElt(12) / 4; 2321 2322 // If both vector operands for the shuffle are the same vector, the mask will 2323 // contain only elements from the first one and the second one will be undef. 2324 if (N->getOperand(1).isUndef()) { 2325 assert(M0 < 4 && "Indexing into an undef vector?"); 2326 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4) 2327 return false; 2328 2329 ShiftElts = IsLE ? (4 - M0) % 4 : M0; 2330 Swap = false; 2331 return true; 2332 } 2333 2334 // Ensure each word index of the ShuffleVector Mask is consecutive. 2335 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8) 2336 return false; 2337 2338 if (IsLE) { 2339 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) { 2340 // Input vectors don't need to be swapped if the leading element 2341 // of the result is one of the 3 left elements of the second vector 2342 // (or if there is no shift to be done at all). 2343 Swap = false; 2344 ShiftElts = (8 - M0) % 8; 2345 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) { 2346 // Input vectors need to be swapped if the leading element 2347 // of the result is one of the 3 left elements of the first vector 2348 // (or if we're shifting by 4 - thereby simply swapping the vectors). 2349 Swap = true; 2350 ShiftElts = (4 - M0) % 4; 2351 } 2352 2353 return true; 2354 } else { // BE 2355 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) { 2356 // Input vectors don't need to be swapped if the leading element 2357 // of the result is one of the 4 elements of the first vector. 2358 Swap = false; 2359 ShiftElts = M0; 2360 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) { 2361 // Input vectors need to be swapped if the leading element 2362 // of the result is one of the 4 elements of the right vector. 2363 Swap = true; 2364 ShiftElts = M0 - 4; 2365 } 2366 2367 return true; 2368 } 2369 } 2370 2371 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) { 2372 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2373 2374 if (!isNByteElemShuffleMask(N, Width, -1)) 2375 return false; 2376 2377 for (int i = 0; i < 16; i += Width) 2378 if (N->getMaskElt(i) != i + Width - 1) 2379 return false; 2380 2381 return true; 2382 } 2383 2384 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) { 2385 return isXXBRShuffleMaskHelper(N, 2); 2386 } 2387 2388 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) { 2389 return isXXBRShuffleMaskHelper(N, 4); 2390 } 2391 2392 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) { 2393 return isXXBRShuffleMaskHelper(N, 8); 2394 } 2395 2396 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) { 2397 return isXXBRShuffleMaskHelper(N, 16); 2398 } 2399 2400 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap 2401 /// if the inputs to the instruction should be swapped and set \p DM to the 2402 /// value for the immediate. 2403 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI 2404 /// AND element 0 of the result comes from the first input (LE) or second input 2405 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered. 2406 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle 2407 /// mask. 2408 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM, 2409 bool &Swap, bool IsLE) { 2410 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8"); 2411 2412 // Ensure each byte index of the double word is consecutive. 2413 if (!isNByteElemShuffleMask(N, 8, 1)) 2414 return false; 2415 2416 unsigned M0 = N->getMaskElt(0) / 8; 2417 unsigned M1 = N->getMaskElt(8) / 8; 2418 assert(((M0 | M1) < 4) && "A mask element out of bounds?"); 2419 2420 // If both vector operands for the shuffle are the same vector, the mask will 2421 // contain only elements from the first one and the second one will be undef. 2422 if (N->getOperand(1).isUndef()) { 2423 if ((M0 | M1) < 2) { 2424 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1); 2425 Swap = false; 2426 return true; 2427 } else 2428 return false; 2429 } 2430 2431 if (IsLE) { 2432 if (M0 > 1 && M1 < 2) { 2433 Swap = false; 2434 } else if (M0 < 2 && M1 > 1) { 2435 M0 = (M0 + 2) % 4; 2436 M1 = (M1 + 2) % 4; 2437 Swap = true; 2438 } else 2439 return false; 2440 2441 // Note: if control flow comes here that means Swap is already set above 2442 DM = (((~M1) & 1) << 1) + ((~M0) & 1); 2443 return true; 2444 } else { // BE 2445 if (M0 < 2 && M1 > 1) { 2446 Swap = false; 2447 } else if (M0 > 1 && M1 < 2) { 2448 M0 = (M0 + 2) % 4; 2449 M1 = (M1 + 2) % 4; 2450 Swap = true; 2451 } else 2452 return false; 2453 2454 // Note: if control flow comes here that means Swap is already set above 2455 DM = (M0 << 1) + (M1 & 1); 2456 return true; 2457 } 2458 } 2459 2460 2461 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is 2462 /// appropriate for PPC mnemonics (which have a big endian bias - namely 2463 /// elements are counted from the left of the vector register). 2464 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, 2465 SelectionDAG &DAG) { 2466 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); 2467 assert(isSplatShuffleMask(SVOp, EltSize)); 2468 EVT VT = SVOp->getValueType(0); 2469 2470 if (VT == MVT::v2i64 || VT == MVT::v2f64) 2471 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0) 2472 : SVOp->getMaskElt(0); 2473 2474 if (DAG.getDataLayout().isLittleEndian()) 2475 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); 2476 else 2477 return SVOp->getMaskElt(0) / EltSize; 2478 } 2479 2480 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed 2481 /// by using a vspltis[bhw] instruction of the specified element size, return 2482 /// the constant being splatted. The ByteSize field indicates the number of 2483 /// bytes of each element [124] -> [bhw]. 2484 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { 2485 SDValue OpVal; 2486 2487 // If ByteSize of the splat is bigger than the element size of the 2488 // build_vector, then we have a case where we are checking for a splat where 2489 // multiple elements of the buildvector are folded together into a single 2490 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). 2491 unsigned EltSize = 16/N->getNumOperands(); 2492 if (EltSize < ByteSize) { 2493 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. 2494 SDValue UniquedVals[4]; 2495 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); 2496 2497 // See if all of the elements in the buildvector agree across. 2498 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2499 if (N->getOperand(i).isUndef()) continue; 2500 // If the element isn't a constant, bail fully out. 2501 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); 2502 2503 if (!UniquedVals[i&(Multiple-1)].getNode()) 2504 UniquedVals[i&(Multiple-1)] = N->getOperand(i); 2505 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) 2506 return SDValue(); // no match. 2507 } 2508 2509 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains 2510 // either constant or undef values that are identical for each chunk. See 2511 // if these chunks can form into a larger vspltis*. 2512 2513 // Check to see if all of the leading entries are either 0 or -1. If 2514 // neither, then this won't fit into the immediate field. 2515 bool LeadingZero = true; 2516 bool LeadingOnes = true; 2517 for (unsigned i = 0; i != Multiple-1; ++i) { 2518 if (!UniquedVals[i].getNode()) continue; // Must have been undefs. 2519 2520 LeadingZero &= isNullConstant(UniquedVals[i]); 2521 LeadingOnes &= isAllOnesConstant(UniquedVals[i]); 2522 } 2523 // Finally, check the least significant entry. 2524 if (LeadingZero) { 2525 if (!UniquedVals[Multiple-1].getNode()) 2526 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef 2527 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); 2528 if (Val < 16) // 0,0,0,4 -> vspltisw(4) 2529 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2530 } 2531 if (LeadingOnes) { 2532 if (!UniquedVals[Multiple-1].getNode()) 2533 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef 2534 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); 2535 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) 2536 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); 2537 } 2538 2539 return SDValue(); 2540 } 2541 2542 // Check to see if this buildvec has a single non-undef value in its elements. 2543 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 2544 if (N->getOperand(i).isUndef()) continue; 2545 if (!OpVal.getNode()) 2546 OpVal = N->getOperand(i); 2547 else if (OpVal != N->getOperand(i)) 2548 return SDValue(); 2549 } 2550 2551 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. 2552 2553 unsigned ValSizeInBytes = EltSize; 2554 uint64_t Value = 0; 2555 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { 2556 Value = CN->getZExtValue(); 2557 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { 2558 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); 2559 Value = FloatToBits(CN->getValueAPF().convertToFloat()); 2560 } 2561 2562 // If the splat value is larger than the element value, then we can never do 2563 // this splat. The only case that we could fit the replicated bits into our 2564 // immediate field for would be zero, and we prefer to use vxor for it. 2565 if (ValSizeInBytes < ByteSize) return SDValue(); 2566 2567 // If the element value is larger than the splat value, check if it consists 2568 // of a repeated bit pattern of size ByteSize. 2569 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) 2570 return SDValue(); 2571 2572 // Properly sign extend the value. 2573 int MaskVal = SignExtend32(Value, ByteSize * 8); 2574 2575 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. 2576 if (MaskVal == 0) return SDValue(); 2577 2578 // Finally, if this value fits in a 5 bit sext field, return it 2579 if (SignExtend32<5>(MaskVal) == MaskVal) 2580 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); 2581 return SDValue(); 2582 } 2583 2584 //===----------------------------------------------------------------------===// 2585 // Addressing Mode Selection 2586 //===----------------------------------------------------------------------===// 2587 2588 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 2589 /// or 64-bit immediate, and if the value can be accurately represented as a 2590 /// sign extension from a 16-bit value. If so, this returns true and the 2591 /// immediate. 2592 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) { 2593 if (!isa<ConstantSDNode>(N)) 2594 return false; 2595 2596 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue(); 2597 if (N->getValueType(0) == MVT::i32) 2598 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 2599 else 2600 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2601 } 2602 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) { 2603 return isIntS16Immediate(Op.getNode(), Imm); 2604 } 2605 2606 /// Used when computing address flags for selecting loads and stores. 2607 /// If we have an OR, check if the LHS and RHS are provably disjoint. 2608 /// An OR of two provably disjoint values is equivalent to an ADD. 2609 /// Most PPC load/store instructions compute the effective address as a sum, 2610 /// so doing this conversion is useful. 2611 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) { 2612 if (N.getOpcode() != ISD::OR) 2613 return false; 2614 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2615 if (!LHSKnown.Zero.getBoolValue()) 2616 return false; 2617 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2618 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0); 2619 } 2620 2621 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can 2622 /// be represented as an indexed [r+r] operation. 2623 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base, 2624 SDValue &Index, 2625 SelectionDAG &DAG) const { 2626 for (SDNode *U : N->uses()) { 2627 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) { 2628 if (Memop->getMemoryVT() == MVT::f64) { 2629 Base = N.getOperand(0); 2630 Index = N.getOperand(1); 2631 return true; 2632 } 2633 } 2634 } 2635 return false; 2636 } 2637 2638 /// isIntS34Immediate - This method tests if value of node given can be 2639 /// accurately represented as a sign extension from a 34-bit value. If so, 2640 /// this returns true and the immediate. 2641 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) { 2642 if (!isa<ConstantSDNode>(N)) 2643 return false; 2644 2645 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 2646 return isInt<34>(Imm); 2647 } 2648 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) { 2649 return isIntS34Immediate(Op.getNode(), Imm); 2650 } 2651 2652 /// SelectAddressRegReg - Given the specified addressed, check to see if it 2653 /// can be represented as an indexed [r+r] operation. Returns false if it 2654 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is 2655 /// non-zero and N can be represented by a base register plus a signed 16-bit 2656 /// displacement, make a more precise judgement by checking (displacement % \p 2657 /// EncodingAlignment). 2658 bool PPCTargetLowering::SelectAddressRegReg( 2659 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, 2660 MaybeAlign EncodingAlignment) const { 2661 // If we have a PC Relative target flag don't select as [reg+reg]. It will be 2662 // a [pc+imm]. 2663 if (SelectAddressPCRel(N, Base)) 2664 return false; 2665 2666 int16_t Imm = 0; 2667 if (N.getOpcode() == ISD::ADD) { 2668 // Is there any SPE load/store (f64), which can't handle 16bit offset? 2669 // SPE load/store can only handle 8-bit offsets. 2670 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG)) 2671 return true; 2672 if (isIntS16Immediate(N.getOperand(1), Imm) && 2673 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2674 return false; // r+i 2675 if (N.getOperand(1).getOpcode() == PPCISD::Lo) 2676 return false; // r+i 2677 2678 Base = N.getOperand(0); 2679 Index = N.getOperand(1); 2680 return true; 2681 } else if (N.getOpcode() == ISD::OR) { 2682 if (isIntS16Immediate(N.getOperand(1), Imm) && 2683 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) 2684 return false; // r+i can fold it if we can. 2685 2686 // If this is an or of disjoint bitfields, we can codegen this as an add 2687 // (for better address arithmetic) if the LHS and RHS of the OR are provably 2688 // disjoint. 2689 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2690 2691 if (LHSKnown.Zero.getBoolValue()) { 2692 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1)); 2693 // If all of the bits are known zero on the LHS or RHS, the add won't 2694 // carry. 2695 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) { 2696 Base = N.getOperand(0); 2697 Index = N.getOperand(1); 2698 return true; 2699 } 2700 } 2701 } 2702 2703 return false; 2704 } 2705 2706 // If we happen to be doing an i64 load or store into a stack slot that has 2707 // less than a 4-byte alignment, then the frame-index elimination may need to 2708 // use an indexed load or store instruction (because the offset may not be a 2709 // multiple of 4). The extra register needed to hold the offset comes from the 2710 // register scavenger, and it is possible that the scavenger will need to use 2711 // an emergency spill slot. As a result, we need to make sure that a spill slot 2712 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned 2713 // stack slot. 2714 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { 2715 // FIXME: This does not handle the LWA case. 2716 if (VT != MVT::i64) 2717 return; 2718 2719 // NOTE: We'll exclude negative FIs here, which come from argument 2720 // lowering, because there are no known test cases triggering this problem 2721 // using packed structures (or similar). We can remove this exclusion if 2722 // we find such a test case. The reason why this is so test-case driven is 2723 // because this entire 'fixup' is only to prevent crashes (from the 2724 // register scavenger) on not-really-valid inputs. For example, if we have: 2725 // %a = alloca i1 2726 // %b = bitcast i1* %a to i64* 2727 // store i64* a, i64 b 2728 // then the store should really be marked as 'align 1', but is not. If it 2729 // were marked as 'align 1' then the indexed form would have been 2730 // instruction-selected initially, and the problem this 'fixup' is preventing 2731 // won't happen regardless. 2732 if (FrameIdx < 0) 2733 return; 2734 2735 MachineFunction &MF = DAG.getMachineFunction(); 2736 MachineFrameInfo &MFI = MF.getFrameInfo(); 2737 2738 if (MFI.getObjectAlign(FrameIdx) >= Align(4)) 2739 return; 2740 2741 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 2742 FuncInfo->setHasNonRISpills(); 2743 } 2744 2745 /// Returns true if the address N can be represented by a base register plus 2746 /// a signed 16-bit displacement [r+imm], and if it is not better 2747 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept 2748 /// displacements that are multiples of that value. 2749 bool PPCTargetLowering::SelectAddressRegImm( 2750 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, 2751 MaybeAlign EncodingAlignment) const { 2752 // FIXME dl should come from parent load or store, not from address 2753 SDLoc dl(N); 2754 2755 // If we have a PC Relative target flag don't select as [reg+imm]. It will be 2756 // a [pc+imm]. 2757 if (SelectAddressPCRel(N, Base)) 2758 return false; 2759 2760 // If this can be more profitably realized as r+r, fail. 2761 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment)) 2762 return false; 2763 2764 if (N.getOpcode() == ISD::ADD) { 2765 int16_t imm = 0; 2766 if (isIntS16Immediate(N.getOperand(1), imm) && 2767 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2768 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2769 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2770 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2771 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2772 } else { 2773 Base = N.getOperand(0); 2774 } 2775 return true; // [r+i] 2776 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { 2777 // Match LOAD (ADD (X, Lo(G))). 2778 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() 2779 && "Cannot handle constant offsets yet!"); 2780 Disp = N.getOperand(1).getOperand(0); // The global address. 2781 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 2782 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 2783 Disp.getOpcode() == ISD::TargetConstantPool || 2784 Disp.getOpcode() == ISD::TargetJumpTable); 2785 Base = N.getOperand(0); 2786 return true; // [&g+r] 2787 } 2788 } else if (N.getOpcode() == ISD::OR) { 2789 int16_t imm = 0; 2790 if (isIntS16Immediate(N.getOperand(1), imm) && 2791 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) { 2792 // If this is an or of disjoint bitfields, we can codegen this as an add 2793 // (for better address arithmetic) if the LHS and RHS of the OR are 2794 // provably disjoint. 2795 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2796 2797 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { 2798 // If all of the bits are known zero on the LHS or RHS, the add won't 2799 // carry. 2800 if (FrameIndexSDNode *FI = 2801 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { 2802 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2803 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2804 } else { 2805 Base = N.getOperand(0); 2806 } 2807 Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); 2808 return true; 2809 } 2810 } 2811 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 2812 // Loading from a constant address. 2813 2814 // If this address fits entirely in a 16-bit sext immediate field, codegen 2815 // this as "d, 0" 2816 int16_t Imm; 2817 if (isIntS16Immediate(CN, Imm) && 2818 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) { 2819 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); 2820 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2821 CN->getValueType(0)); 2822 return true; 2823 } 2824 2825 // Handle 32-bit sext immediates with LIS + addr mode. 2826 if ((CN->getValueType(0) == MVT::i32 || 2827 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && 2828 (!EncodingAlignment || 2829 isAligned(*EncodingAlignment, CN->getZExtValue()))) { 2830 int Addr = (int)CN->getZExtValue(); 2831 2832 // Otherwise, break this down into an LIS + disp. 2833 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); 2834 2835 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, 2836 MVT::i32); 2837 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; 2838 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); 2839 return true; 2840 } 2841 } 2842 2843 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); 2844 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 2845 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2846 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 2847 } else 2848 Base = N; 2849 return true; // [r+0] 2850 } 2851 2852 /// Similar to the 16-bit case but for instructions that take a 34-bit 2853 /// displacement field (prefixed loads/stores). 2854 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp, 2855 SDValue &Base, 2856 SelectionDAG &DAG) const { 2857 // Only on 64-bit targets. 2858 if (N.getValueType() != MVT::i64) 2859 return false; 2860 2861 SDLoc dl(N); 2862 int64_t Imm = 0; 2863 2864 if (N.getOpcode() == ISD::ADD) { 2865 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2866 return false; 2867 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2868 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2869 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2870 else 2871 Base = N.getOperand(0); 2872 return true; 2873 } 2874 2875 if (N.getOpcode() == ISD::OR) { 2876 if (!isIntS34Immediate(N.getOperand(1), Imm)) 2877 return false; 2878 // If this is an or of disjoint bitfields, we can codegen this as an add 2879 // (for better address arithmetic) if the LHS and RHS of the OR are 2880 // provably disjoint. 2881 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0)); 2882 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL) 2883 return false; 2884 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 2885 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 2886 else 2887 Base = N.getOperand(0); 2888 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2889 return true; 2890 } 2891 2892 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const. 2893 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType()); 2894 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 2895 return true; 2896 } 2897 2898 return false; 2899 } 2900 2901 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be 2902 /// represented as an indexed [r+r] operation. 2903 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, 2904 SDValue &Index, 2905 SelectionDAG &DAG) const { 2906 // Check to see if we can easily represent this as an [r+r] address. This 2907 // will fail if it thinks that the address is more profitably represented as 2908 // reg+imm, e.g. where imm = 0. 2909 if (SelectAddressRegReg(N, Base, Index, DAG)) 2910 return true; 2911 2912 // If the address is the result of an add, we will utilize the fact that the 2913 // address calculation includes an implicit add. However, we can reduce 2914 // register pressure if we do not materialize a constant just for use as the 2915 // index register. We only get rid of the add if it is not an add of a 2916 // value and a 16-bit signed constant and both have a single use. 2917 int16_t imm = 0; 2918 if (N.getOpcode() == ISD::ADD && 2919 (!isIntS16Immediate(N.getOperand(1), imm) || 2920 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 2921 Base = N.getOperand(0); 2922 Index = N.getOperand(1); 2923 return true; 2924 } 2925 2926 // Otherwise, do it the hard way, using R0 as the base register. 2927 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 2928 N.getValueType()); 2929 Index = N; 2930 return true; 2931 } 2932 2933 template <typename Ty> static bool isValidPCRelNode(SDValue N) { 2934 Ty *PCRelCand = dyn_cast<Ty>(N); 2935 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG); 2936 } 2937 2938 /// Returns true if this address is a PC Relative address. 2939 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG 2940 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR. 2941 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const { 2942 // This is a materialize PC Relative node. Always select this as PC Relative. 2943 Base = N; 2944 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR) 2945 return true; 2946 if (isValidPCRelNode<ConstantPoolSDNode>(N) || 2947 isValidPCRelNode<GlobalAddressSDNode>(N) || 2948 isValidPCRelNode<JumpTableSDNode>(N) || 2949 isValidPCRelNode<BlockAddressSDNode>(N)) 2950 return true; 2951 return false; 2952 } 2953 2954 /// Returns true if we should use a direct load into vector instruction 2955 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence. 2956 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) { 2957 2958 // If there are any other uses other than scalar to vector, then we should 2959 // keep it as a scalar load -> direct move pattern to prevent multiple 2960 // loads. 2961 LoadSDNode *LD = dyn_cast<LoadSDNode>(N); 2962 if (!LD) 2963 return false; 2964 2965 EVT MemVT = LD->getMemoryVT(); 2966 if (!MemVT.isSimple()) 2967 return false; 2968 switch(MemVT.getSimpleVT().SimpleTy) { 2969 case MVT::i64: 2970 break; 2971 case MVT::i32: 2972 if (!ST.hasP8Vector()) 2973 return false; 2974 break; 2975 case MVT::i16: 2976 case MVT::i8: 2977 if (!ST.hasP9Vector()) 2978 return false; 2979 break; 2980 default: 2981 return false; 2982 } 2983 2984 SDValue LoadedVal(N, 0); 2985 if (!LoadedVal.hasOneUse()) 2986 return false; 2987 2988 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); 2989 UI != UE; ++UI) 2990 if (UI.getUse().get().getResNo() == 0 && 2991 UI->getOpcode() != ISD::SCALAR_TO_VECTOR && 2992 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED) 2993 return false; 2994 2995 return true; 2996 } 2997 2998 /// getPreIndexedAddressParts - returns true by value, base pointer and 2999 /// offset pointer and addressing mode by reference if the node's address 3000 /// can be legally represented as pre-indexed load / store address. 3001 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 3002 SDValue &Offset, 3003 ISD::MemIndexedMode &AM, 3004 SelectionDAG &DAG) const { 3005 if (DisablePPCPreinc) return false; 3006 3007 bool isLoad = true; 3008 SDValue Ptr; 3009 EVT VT; 3010 Align Alignment; 3011 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3012 Ptr = LD->getBasePtr(); 3013 VT = LD->getMemoryVT(); 3014 Alignment = LD->getAlign(); 3015 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 3016 Ptr = ST->getBasePtr(); 3017 VT = ST->getMemoryVT(); 3018 Alignment = ST->getAlign(); 3019 isLoad = false; 3020 } else 3021 return false; 3022 3023 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector 3024 // instructions because we can fold these into a more efficient instruction 3025 // instead, (such as LXSD). 3026 if (isLoad && usePartialVectorLoads(N, Subtarget)) { 3027 return false; 3028 } 3029 3030 // PowerPC doesn't have preinc load/store instructions for vectors 3031 if (VT.isVector()) 3032 return false; 3033 3034 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { 3035 // Common code will reject creating a pre-inc form if the base pointer 3036 // is a frame index, or if N is a store and the base pointer is either 3037 // the same as or a predecessor of the value being stored. Check for 3038 // those situations here, and try with swapped Base/Offset instead. 3039 bool Swap = false; 3040 3041 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) 3042 Swap = true; 3043 else if (!isLoad) { 3044 SDValue Val = cast<StoreSDNode>(N)->getValue(); 3045 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) 3046 Swap = true; 3047 } 3048 3049 if (Swap) 3050 std::swap(Base, Offset); 3051 3052 AM = ISD::PRE_INC; 3053 return true; 3054 } 3055 3056 // LDU/STU can only handle immediates that are a multiple of 4. 3057 if (VT != MVT::i64) { 3058 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt)) 3059 return false; 3060 } else { 3061 // LDU/STU need an address with at least 4-byte alignment. 3062 if (Alignment < Align(4)) 3063 return false; 3064 3065 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4))) 3066 return false; 3067 } 3068 3069 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 3070 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of 3071 // sext i32 to i64 when addr mode is r+i. 3072 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && 3073 LD->getExtensionType() == ISD::SEXTLOAD && 3074 isa<ConstantSDNode>(Offset)) 3075 return false; 3076 } 3077 3078 AM = ISD::PRE_INC; 3079 return true; 3080 } 3081 3082 //===----------------------------------------------------------------------===// 3083 // LowerOperation implementation 3084 //===----------------------------------------------------------------------===// 3085 3086 /// Return true if we should reference labels using a PICBase, set the HiOpFlags 3087 /// and LoOpFlags to the target MO flags. 3088 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, 3089 unsigned &HiOpFlags, unsigned &LoOpFlags, 3090 const GlobalValue *GV = nullptr) { 3091 HiOpFlags = PPCII::MO_HA; 3092 LoOpFlags = PPCII::MO_LO; 3093 3094 // Don't use the pic base if not in PIC relocation model. 3095 if (IsPIC) { 3096 HiOpFlags |= PPCII::MO_PIC_FLAG; 3097 LoOpFlags |= PPCII::MO_PIC_FLAG; 3098 } 3099 } 3100 3101 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, 3102 SelectionDAG &DAG) { 3103 SDLoc DL(HiPart); 3104 EVT PtrVT = HiPart.getValueType(); 3105 SDValue Zero = DAG.getConstant(0, DL, PtrVT); 3106 3107 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); 3108 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); 3109 3110 // With PIC, the first instruction is actually "GR+hi(&G)". 3111 if (isPIC) 3112 Hi = DAG.getNode(ISD::ADD, DL, PtrVT, 3113 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); 3114 3115 // Generate non-pic code that has direct accesses to the constant pool. 3116 // The address of the global is just (hi(&g)+lo(&g)). 3117 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); 3118 } 3119 3120 static void setUsesTOCBasePtr(MachineFunction &MF) { 3121 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3122 FuncInfo->setUsesTOCBasePtr(); 3123 } 3124 3125 static void setUsesTOCBasePtr(SelectionDAG &DAG) { 3126 setUsesTOCBasePtr(DAG.getMachineFunction()); 3127 } 3128 3129 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, 3130 SDValue GA) const { 3131 const bool Is64Bit = Subtarget.isPPC64(); 3132 EVT VT = Is64Bit ? MVT::i64 : MVT::i32; 3133 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) 3134 : Subtarget.isAIXABI() 3135 ? DAG.getRegister(PPC::R2, VT) 3136 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); 3137 SDValue Ops[] = { GA, Reg }; 3138 return DAG.getMemIntrinsicNode( 3139 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, 3140 MachinePointerInfo::getGOT(DAG.getMachineFunction()), std::nullopt, 3141 MachineMemOperand::MOLoad); 3142 } 3143 3144 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, 3145 SelectionDAG &DAG) const { 3146 EVT PtrVT = Op.getValueType(); 3147 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 3148 const Constant *C = CP->getConstVal(); 3149 3150 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3151 // The actual address of the GlobalValue is stored in the TOC. 3152 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3153 if (Subtarget.isUsingPCRelativeCalls()) { 3154 SDLoc DL(CP); 3155 EVT Ty = getPointerTy(DAG.getDataLayout()); 3156 SDValue ConstPool = DAG.getTargetConstantPool( 3157 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG); 3158 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool); 3159 } 3160 setUsesTOCBasePtr(DAG); 3161 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0); 3162 return getTOCEntry(DAG, SDLoc(CP), GA); 3163 } 3164 3165 unsigned MOHiFlag, MOLoFlag; 3166 bool IsPIC = isPositionIndependent(); 3167 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3168 3169 if (IsPIC && Subtarget.isSVR4ABI()) { 3170 SDValue GA = 3171 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG); 3172 return getTOCEntry(DAG, SDLoc(CP), GA); 3173 } 3174 3175 SDValue CPIHi = 3176 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag); 3177 SDValue CPILo = 3178 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag); 3179 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG); 3180 } 3181 3182 // For 64-bit PowerPC, prefer the more compact relative encodings. 3183 // This trades 32 bits per jump table entry for one or two instructions 3184 // on the jump site. 3185 unsigned PPCTargetLowering::getJumpTableEncoding() const { 3186 if (isJumpTableRelative()) 3187 return MachineJumpTableInfo::EK_LabelDifference32; 3188 3189 return TargetLowering::getJumpTableEncoding(); 3190 } 3191 3192 bool PPCTargetLowering::isJumpTableRelative() const { 3193 if (UseAbsoluteJumpTables) 3194 return false; 3195 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) 3196 return true; 3197 return TargetLowering::isJumpTableRelative(); 3198 } 3199 3200 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table, 3201 SelectionDAG &DAG) const { 3202 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3203 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3204 3205 switch (getTargetMachine().getCodeModel()) { 3206 case CodeModel::Small: 3207 case CodeModel::Medium: 3208 return TargetLowering::getPICJumpTableRelocBase(Table, DAG); 3209 default: 3210 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(), 3211 getPointerTy(DAG.getDataLayout())); 3212 } 3213 } 3214 3215 const MCExpr * 3216 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 3217 unsigned JTI, 3218 MCContext &Ctx) const { 3219 if (!Subtarget.isPPC64() || Subtarget.isAIXABI()) 3220 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3221 3222 switch (getTargetMachine().getCodeModel()) { 3223 case CodeModel::Small: 3224 case CodeModel::Medium: 3225 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx); 3226 default: 3227 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx); 3228 } 3229 } 3230 3231 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 3232 EVT PtrVT = Op.getValueType(); 3233 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 3234 3235 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3236 if (Subtarget.isUsingPCRelativeCalls()) { 3237 SDLoc DL(JT); 3238 EVT Ty = getPointerTy(DAG.getDataLayout()); 3239 SDValue GA = 3240 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG); 3241 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3242 return MatAddr; 3243 } 3244 3245 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3246 // The actual address of the GlobalValue is stored in the TOC. 3247 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3248 setUsesTOCBasePtr(DAG); 3249 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); 3250 return getTOCEntry(DAG, SDLoc(JT), GA); 3251 } 3252 3253 unsigned MOHiFlag, MOLoFlag; 3254 bool IsPIC = isPositionIndependent(); 3255 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3256 3257 if (IsPIC && Subtarget.isSVR4ABI()) { 3258 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 3259 PPCII::MO_PIC_FLAG); 3260 return getTOCEntry(DAG, SDLoc(GA), GA); 3261 } 3262 3263 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); 3264 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); 3265 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG); 3266 } 3267 3268 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, 3269 SelectionDAG &DAG) const { 3270 EVT PtrVT = Op.getValueType(); 3271 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); 3272 const BlockAddress *BA = BASDN->getBlockAddress(); 3273 3274 // isUsingPCRelativeCalls() returns true when PCRelative is enabled 3275 if (Subtarget.isUsingPCRelativeCalls()) { 3276 SDLoc DL(BASDN); 3277 EVT Ty = getPointerTy(DAG.getDataLayout()); 3278 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(), 3279 PPCII::MO_PCREL_FLAG); 3280 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3281 return MatAddr; 3282 } 3283 3284 // 64-bit SVR4 ABI and AIX ABI code are always position-independent. 3285 // The actual BlockAddress is stored in the TOC. 3286 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3287 setUsesTOCBasePtr(DAG); 3288 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); 3289 return getTOCEntry(DAG, SDLoc(BASDN), GA); 3290 } 3291 3292 // 32-bit position-independent ELF stores the BlockAddress in the .got. 3293 if (Subtarget.is32BitELFABI() && isPositionIndependent()) 3294 return getTOCEntry( 3295 DAG, SDLoc(BASDN), 3296 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset())); 3297 3298 unsigned MOHiFlag, MOLoFlag; 3299 bool IsPIC = isPositionIndependent(); 3300 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag); 3301 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); 3302 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); 3303 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG); 3304 } 3305 3306 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, 3307 SelectionDAG &DAG) const { 3308 if (Subtarget.isAIXABI()) 3309 return LowerGlobalTLSAddressAIX(Op, DAG); 3310 3311 return LowerGlobalTLSAddressLinux(Op, DAG); 3312 } 3313 3314 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op, 3315 SelectionDAG &DAG) const { 3316 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3317 3318 if (DAG.getTarget().useEmulatedTLS()) 3319 report_fatal_error("Emulated TLS is not yet supported on AIX"); 3320 3321 SDLoc dl(GA); 3322 const GlobalValue *GV = GA->getGlobal(); 3323 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3324 3325 // The general-dynamic model is the only access model supported for now, so 3326 // all the GlobalTLSAddress nodes are lowered with this model. 3327 // We need to generate two TOC entries, one for the variable offset, one for 3328 // the region handle. The global address for the TOC entry of the region 3329 // handle is created with the MO_TLSGDM_FLAG flag and the global address 3330 // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG. 3331 SDValue VariableOffsetTGA = 3332 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG); 3333 SDValue RegionHandleTGA = 3334 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG); 3335 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA); 3336 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA); 3337 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset, 3338 RegionHandle); 3339 } 3340 3341 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op, 3342 SelectionDAG &DAG) const { 3343 // FIXME: TLS addresses currently use medium model code sequences, 3344 // which is the most useful form. Eventually support for small and 3345 // large models could be added if users need it, at the cost of 3346 // additional complexity. 3347 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3348 if (DAG.getTarget().useEmulatedTLS()) 3349 return LowerToTLSEmulatedModel(GA, DAG); 3350 3351 SDLoc dl(GA); 3352 const GlobalValue *GV = GA->getGlobal(); 3353 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3354 bool is64bit = Subtarget.isPPC64(); 3355 const Module *M = DAG.getMachineFunction().getFunction().getParent(); 3356 PICLevel::Level picLevel = M->getPICLevel(); 3357 3358 const TargetMachine &TM = getTargetMachine(); 3359 TLSModel::Model Model = TM.getTLSModel(GV); 3360 3361 if (Model == TLSModel::LocalExec) { 3362 if (Subtarget.isUsingPCRelativeCalls()) { 3363 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64); 3364 SDValue TGA = DAG.getTargetGlobalAddress( 3365 GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG)); 3366 SDValue MatAddr = 3367 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA); 3368 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr); 3369 } 3370 3371 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3372 PPCII::MO_TPREL_HA); 3373 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3374 PPCII::MO_TPREL_LO); 3375 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64) 3376 : DAG.getRegister(PPC::R2, MVT::i32); 3377 3378 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); 3379 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); 3380 } 3381 3382 if (Model == TLSModel::InitialExec) { 3383 bool IsPCRel = Subtarget.isUsingPCRelativeCalls(); 3384 SDValue TGA = DAG.getTargetGlobalAddress( 3385 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0); 3386 SDValue TGATLS = DAG.getTargetGlobalAddress( 3387 GV, dl, PtrVT, 0, 3388 IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS); 3389 SDValue TPOffset; 3390 if (IsPCRel) { 3391 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA); 3392 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel, 3393 MachinePointerInfo()); 3394 } else { 3395 SDValue GOTPtr; 3396 if (is64bit) { 3397 setUsesTOCBasePtr(DAG); 3398 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3399 GOTPtr = 3400 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); 3401 } else { 3402 if (!TM.isPositionIndependent()) 3403 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); 3404 else if (picLevel == PICLevel::SmallPIC) 3405 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3406 else 3407 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3408 } 3409 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); 3410 } 3411 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); 3412 } 3413 3414 if (Model == TLSModel::GeneralDynamic) { 3415 if (Subtarget.isUsingPCRelativeCalls()) { 3416 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3417 PPCII::MO_GOT_TLSGD_PCREL_FLAG); 3418 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3419 } 3420 3421 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3422 SDValue GOTPtr; 3423 if (is64bit) { 3424 setUsesTOCBasePtr(DAG); 3425 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3426 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, 3427 GOTReg, TGA); 3428 } else { 3429 if (picLevel == PICLevel::SmallPIC) 3430 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3431 else 3432 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3433 } 3434 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, 3435 GOTPtr, TGA, TGA); 3436 } 3437 3438 if (Model == TLSModel::LocalDynamic) { 3439 if (Subtarget.isUsingPCRelativeCalls()) { 3440 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 3441 PPCII::MO_GOT_TLSLD_PCREL_FLAG); 3442 SDValue MatPCRel = 3443 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA); 3444 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA); 3445 } 3446 3447 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); 3448 SDValue GOTPtr; 3449 if (is64bit) { 3450 setUsesTOCBasePtr(DAG); 3451 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); 3452 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, 3453 GOTReg, TGA); 3454 } else { 3455 if (picLevel == PICLevel::SmallPIC) 3456 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); 3457 else 3458 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); 3459 } 3460 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, 3461 PtrVT, GOTPtr, TGA, TGA); 3462 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, 3463 PtrVT, TLSAddr, TGA); 3464 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); 3465 } 3466 3467 llvm_unreachable("Unknown TLS model!"); 3468 } 3469 3470 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, 3471 SelectionDAG &DAG) const { 3472 EVT PtrVT = Op.getValueType(); 3473 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); 3474 SDLoc DL(GSDN); 3475 const GlobalValue *GV = GSDN->getGlobal(); 3476 3477 // 64-bit SVR4 ABI & AIX ABI code is always position-independent. 3478 // The actual address of the GlobalValue is stored in the TOC. 3479 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) { 3480 if (Subtarget.isUsingPCRelativeCalls()) { 3481 EVT Ty = getPointerTy(DAG.getDataLayout()); 3482 if (isAccessedAsGotIndirect(Op)) { 3483 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3484 PPCII::MO_PCREL_FLAG | 3485 PPCII::MO_GOT_FLAG); 3486 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3487 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel, 3488 MachinePointerInfo()); 3489 return Load; 3490 } else { 3491 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(), 3492 PPCII::MO_PCREL_FLAG); 3493 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA); 3494 } 3495 } 3496 setUsesTOCBasePtr(DAG); 3497 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); 3498 return getTOCEntry(DAG, DL, GA); 3499 } 3500 3501 unsigned MOHiFlag, MOLoFlag; 3502 bool IsPIC = isPositionIndependent(); 3503 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV); 3504 3505 if (IsPIC && Subtarget.isSVR4ABI()) { 3506 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 3507 GSDN->getOffset(), 3508 PPCII::MO_PIC_FLAG); 3509 return getTOCEntry(DAG, DL, GA); 3510 } 3511 3512 SDValue GAHi = 3513 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); 3514 SDValue GALo = 3515 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); 3516 3517 return LowerLabelRef(GAHi, GALo, IsPIC, DAG); 3518 } 3519 3520 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3521 bool IsStrict = Op->isStrictFPOpcode(); 3522 ISD::CondCode CC = 3523 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get(); 3524 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0); 3525 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1); 3526 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 3527 EVT LHSVT = LHS.getValueType(); 3528 SDLoc dl(Op); 3529 3530 // Soften the setcc with libcall if it is fp128. 3531 if (LHSVT == MVT::f128) { 3532 assert(!Subtarget.hasP9Vector() && 3533 "SETCC for f128 is already legal under Power9!"); 3534 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain, 3535 Op->getOpcode() == ISD::STRICT_FSETCCS); 3536 if (RHS.getNode()) 3537 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS, 3538 DAG.getCondCode(CC)); 3539 if (IsStrict) 3540 return DAG.getMergeValues({LHS, Chain}, dl); 3541 return LHS; 3542 } 3543 3544 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!"); 3545 3546 if (Op.getValueType() == MVT::v2i64) { 3547 // When the operands themselves are v2i64 values, we need to do something 3548 // special because VSX has no underlying comparison operations for these. 3549 if (LHS.getValueType() == MVT::v2i64) { 3550 // Equality can be handled by casting to the legal type for Altivec 3551 // comparisons, everything else needs to be expanded. 3552 if (CC != ISD::SETEQ && CC != ISD::SETNE) 3553 return SDValue(); 3554 SDValue SetCC32 = DAG.getSetCC( 3555 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS), 3556 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC); 3557 int ShuffV[] = {1, 0, 3, 2}; 3558 SDValue Shuff = 3559 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV); 3560 return DAG.getBitcast(MVT::v2i64, 3561 DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR, 3562 dl, MVT::v4i32, Shuff, SetCC32)); 3563 } 3564 3565 // We handle most of these in the usual way. 3566 return Op; 3567 } 3568 3569 // If we're comparing for equality to zero, expose the fact that this is 3570 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can 3571 // fold the new nodes. 3572 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG)) 3573 return V; 3574 3575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) { 3576 // Leave comparisons against 0 and -1 alone for now, since they're usually 3577 // optimized. FIXME: revisit this when we can custom lower all setcc 3578 // optimizations. 3579 if (C->isAllOnes() || C->isZero()) 3580 return SDValue(); 3581 } 3582 3583 // If we have an integer seteq/setne, turn it into a compare against zero 3584 // by xor'ing the rhs with the lhs, which is faster than setting a 3585 // condition register, reading it back out, and masking the correct bit. The 3586 // normal approach here uses sub to do this instead of xor. Using xor exposes 3587 // the result to other bit-twiddling opportunities. 3588 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 3589 EVT VT = Op.getValueType(); 3590 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS); 3591 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); 3592 } 3593 return SDValue(); 3594 } 3595 3596 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 3597 SDNode *Node = Op.getNode(); 3598 EVT VT = Node->getValueType(0); 3599 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3600 SDValue InChain = Node->getOperand(0); 3601 SDValue VAListPtr = Node->getOperand(1); 3602 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 3603 SDLoc dl(Node); 3604 3605 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); 3606 3607 // gpr_index 3608 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3609 VAListPtr, MachinePointerInfo(SV), MVT::i8); 3610 InChain = GprIndex.getValue(1); 3611 3612 if (VT == MVT::i64) { 3613 // Check if GprIndex is even 3614 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, 3615 DAG.getConstant(1, dl, MVT::i32)); 3616 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, 3617 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); 3618 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, 3619 DAG.getConstant(1, dl, MVT::i32)); 3620 // Align GprIndex to be even if it isn't 3621 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, 3622 GprIndex); 3623 } 3624 3625 // fpr index is 1 byte after gpr 3626 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3627 DAG.getConstant(1, dl, MVT::i32)); 3628 3629 // fpr 3630 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, 3631 FprPtr, MachinePointerInfo(SV), MVT::i8); 3632 InChain = FprIndex.getValue(1); 3633 3634 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3635 DAG.getConstant(8, dl, MVT::i32)); 3636 3637 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, 3638 DAG.getConstant(4, dl, MVT::i32)); 3639 3640 // areas 3641 SDValue OverflowArea = 3642 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo()); 3643 InChain = OverflowArea.getValue(1); 3644 3645 SDValue RegSaveArea = 3646 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo()); 3647 InChain = RegSaveArea.getValue(1); 3648 3649 // select overflow_area if index > 8 3650 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, 3651 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); 3652 3653 // adjustment constant gpr_index * 4/8 3654 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, 3655 VT.isInteger() ? GprIndex : FprIndex, 3656 DAG.getConstant(VT.isInteger() ? 4 : 8, dl, 3657 MVT::i32)); 3658 3659 // OurReg = RegSaveArea + RegConstant 3660 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, 3661 RegConstant); 3662 3663 // Floating types are 32 bytes into RegSaveArea 3664 if (VT.isFloatingPoint()) 3665 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, 3666 DAG.getConstant(32, dl, MVT::i32)); 3667 3668 // increase {f,g}pr_index by 1 (or 2 if VT is i64) 3669 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, 3670 VT.isInteger() ? GprIndex : FprIndex, 3671 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, 3672 MVT::i32)); 3673 3674 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, 3675 VT.isInteger() ? VAListPtr : FprPtr, 3676 MachinePointerInfo(SV), MVT::i8); 3677 3678 // determine if we should load from reg_save_area or overflow_area 3679 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); 3680 3681 // increase overflow_area by 4/8 if gpr/fpr > 8 3682 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, 3683 DAG.getConstant(VT.isInteger() ? 4 : 8, 3684 dl, MVT::i32)); 3685 3686 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, 3687 OverflowAreaPlusN); 3688 3689 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, 3690 MachinePointerInfo(), MVT::i32); 3691 3692 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo()); 3693 } 3694 3695 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { 3696 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); 3697 3698 // We have to copy the entire va_list struct: 3699 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte 3700 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), 3701 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8), 3702 false, true, false, MachinePointerInfo(), 3703 MachinePointerInfo()); 3704 } 3705 3706 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, 3707 SelectionDAG &DAG) const { 3708 if (Subtarget.isAIXABI()) 3709 report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX."); 3710 3711 return Op.getOperand(0); 3712 } 3713 3714 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const { 3715 MachineFunction &MF = DAG.getMachineFunction(); 3716 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>(); 3717 3718 assert((Op.getOpcode() == ISD::INLINEASM || 3719 Op.getOpcode() == ISD::INLINEASM_BR) && 3720 "Expecting Inline ASM node."); 3721 3722 // If an LR store is already known to be required then there is not point in 3723 // checking this ASM as well. 3724 if (MFI.isLRStoreRequired()) 3725 return Op; 3726 3727 // Inline ASM nodes have an optional last operand that is an incoming Flag of 3728 // type MVT::Glue. We want to ignore this last operand if that is the case. 3729 unsigned NumOps = Op.getNumOperands(); 3730 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue) 3731 --NumOps; 3732 3733 // Check all operands that may contain the LR. 3734 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) { 3735 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue(); 3736 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 3737 ++i; // Skip the ID value. 3738 3739 switch (InlineAsm::getKind(Flags)) { 3740 default: 3741 llvm_unreachable("Bad flags!"); 3742 case InlineAsm::Kind_RegUse: 3743 case InlineAsm::Kind_Imm: 3744 case InlineAsm::Kind_Mem: 3745 i += NumVals; 3746 break; 3747 case InlineAsm::Kind_Clobber: 3748 case InlineAsm::Kind_RegDef: 3749 case InlineAsm::Kind_RegDefEarlyClobber: { 3750 for (; NumVals; --NumVals, ++i) { 3751 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg(); 3752 if (Reg != PPC::LR && Reg != PPC::LR8) 3753 continue; 3754 MFI.setLRStoreRequired(); 3755 return Op; 3756 } 3757 break; 3758 } 3759 } 3760 } 3761 3762 return Op; 3763 } 3764 3765 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, 3766 SelectionDAG &DAG) const { 3767 if (Subtarget.isAIXABI()) 3768 report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX."); 3769 3770 SDValue Chain = Op.getOperand(0); 3771 SDValue Trmp = Op.getOperand(1); // trampoline 3772 SDValue FPtr = Op.getOperand(2); // nested function 3773 SDValue Nest = Op.getOperand(3); // 'nest' parameter value 3774 SDLoc dl(Op); 3775 3776 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3777 bool isPPC64 = (PtrVT == MVT::i64); 3778 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 3779 3780 TargetLowering::ArgListTy Args; 3781 TargetLowering::ArgListEntry Entry; 3782 3783 Entry.Ty = IntPtrTy; 3784 Entry.Node = Trmp; Args.push_back(Entry); 3785 3786 // TrampSize == (isPPC64 ? 48 : 40); 3787 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, 3788 isPPC64 ? MVT::i64 : MVT::i32); 3789 Args.push_back(Entry); 3790 3791 Entry.Node = FPtr; Args.push_back(Entry); 3792 Entry.Node = Nest; Args.push_back(Entry); 3793 3794 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) 3795 TargetLowering::CallLoweringInfo CLI(DAG); 3796 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee( 3797 CallingConv::C, Type::getVoidTy(*DAG.getContext()), 3798 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args)); 3799 3800 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3801 return CallResult.second; 3802 } 3803 3804 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3805 MachineFunction &MF = DAG.getMachineFunction(); 3806 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 3807 EVT PtrVT = getPointerTy(MF.getDataLayout()); 3808 3809 SDLoc dl(Op); 3810 3811 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) { 3812 // vastart just stores the address of the VarArgsFrameIndex slot into the 3813 // memory location argument. 3814 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 3815 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3816 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), 3817 MachinePointerInfo(SV)); 3818 } 3819 3820 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. 3821 // We suppose the given va_list is already allocated. 3822 // 3823 // typedef struct { 3824 // char gpr; /* index into the array of 8 GPRs 3825 // * stored in the register save area 3826 // * gpr=0 corresponds to r3, 3827 // * gpr=1 to r4, etc. 3828 // */ 3829 // char fpr; /* index into the array of 8 FPRs 3830 // * stored in the register save area 3831 // * fpr=0 corresponds to f1, 3832 // * fpr=1 to f2, etc. 3833 // */ 3834 // char *overflow_arg_area; 3835 // /* location on stack that holds 3836 // * the next overflow argument 3837 // */ 3838 // char *reg_save_area; 3839 // /* where r3:r10 and f1:f8 (if saved) 3840 // * are stored 3841 // */ 3842 // } va_list[1]; 3843 3844 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); 3845 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); 3846 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), 3847 PtrVT); 3848 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3849 PtrVT); 3850 3851 uint64_t FrameOffset = PtrVT.getSizeInBits()/8; 3852 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); 3853 3854 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; 3855 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); 3856 3857 uint64_t FPROffset = 1; 3858 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); 3859 3860 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3861 3862 // Store first byte : number of int regs 3863 SDValue firstStore = 3864 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), 3865 MachinePointerInfo(SV), MVT::i8); 3866 uint64_t nextOffset = FPROffset; 3867 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), 3868 ConstFPROffset); 3869 3870 // Store second byte : number of float regs 3871 SDValue secondStore = 3872 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, 3873 MachinePointerInfo(SV, nextOffset), MVT::i8); 3874 nextOffset += StackOffset; 3875 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); 3876 3877 // Store second word : arguments given on stack 3878 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, 3879 MachinePointerInfo(SV, nextOffset)); 3880 nextOffset += FrameOffset; 3881 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); 3882 3883 // Store third word : arguments given in registers 3884 return DAG.getStore(thirdStore, dl, FR, nextPtr, 3885 MachinePointerInfo(SV, nextOffset)); 3886 } 3887 3888 /// FPR - The set of FP registers that should be allocated for arguments 3889 /// on Darwin and AIX. 3890 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, 3891 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, 3892 PPC::F11, PPC::F12, PPC::F13}; 3893 3894 /// CalculateStackSlotSize - Calculates the size reserved for this argument on 3895 /// the stack. 3896 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, 3897 unsigned PtrByteSize) { 3898 unsigned ArgSize = ArgVT.getStoreSize(); 3899 if (Flags.isByVal()) 3900 ArgSize = Flags.getByValSize(); 3901 3902 // Round up to multiples of the pointer size, except for array members, 3903 // which are always packed. 3904 if (!Flags.isInConsecutiveRegs()) 3905 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3906 3907 return ArgSize; 3908 } 3909 3910 /// CalculateStackSlotAlignment - Calculates the alignment of this argument 3911 /// on the stack. 3912 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, 3913 ISD::ArgFlagsTy Flags, 3914 unsigned PtrByteSize) { 3915 Align Alignment(PtrByteSize); 3916 3917 // Altivec parameters are padded to a 16 byte boundary. 3918 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3919 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3920 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3921 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3922 Alignment = Align(16); 3923 3924 // ByVal parameters are aligned as requested. 3925 if (Flags.isByVal()) { 3926 auto BVAlign = Flags.getNonZeroByValAlign(); 3927 if (BVAlign > PtrByteSize) { 3928 if (BVAlign.value() % PtrByteSize != 0) 3929 llvm_unreachable( 3930 "ByVal alignment is not a multiple of the pointer size"); 3931 3932 Alignment = BVAlign; 3933 } 3934 } 3935 3936 // Array members are always packed to their original alignment. 3937 if (Flags.isInConsecutiveRegs()) { 3938 // If the array member was split into multiple registers, the first 3939 // needs to be aligned to the size of the full type. (Except for 3940 // ppcf128, which is only aligned as its f64 components.) 3941 if (Flags.isSplit() && OrigVT != MVT::ppcf128) 3942 Alignment = Align(OrigVT.getStoreSize()); 3943 else 3944 Alignment = Align(ArgVT.getStoreSize()); 3945 } 3946 3947 return Alignment; 3948 } 3949 3950 /// CalculateStackSlotUsed - Return whether this argument will use its 3951 /// stack slot (instead of being passed in registers). ArgOffset, 3952 /// AvailableFPRs, and AvailableVRs must hold the current argument 3953 /// position, and will be updated to account for this argument. 3954 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, 3955 unsigned PtrByteSize, unsigned LinkageSize, 3956 unsigned ParamAreaSize, unsigned &ArgOffset, 3957 unsigned &AvailableFPRs, 3958 unsigned &AvailableVRs) { 3959 bool UseMemory = false; 3960 3961 // Respect alignment of argument on the stack. 3962 Align Alignment = 3963 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 3964 ArgOffset = alignTo(ArgOffset, Alignment); 3965 // If there's no space left in the argument save area, we must 3966 // use memory (this check also catches zero-sized arguments). 3967 if (ArgOffset >= LinkageSize + ParamAreaSize) 3968 UseMemory = true; 3969 3970 // Allocate argument on the stack. 3971 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 3972 if (Flags.isInConsecutiveRegsLast()) 3973 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 3974 // If we overran the argument save area, we must use memory 3975 // (this check catches arguments passed partially in memory) 3976 if (ArgOffset > LinkageSize + ParamAreaSize) 3977 UseMemory = true; 3978 3979 // However, if the argument is actually passed in an FPR or a VR, 3980 // we don't use memory after all. 3981 if (!Flags.isByVal()) { 3982 if (ArgVT == MVT::f32 || ArgVT == MVT::f64) 3983 if (AvailableFPRs > 0) { 3984 --AvailableFPRs; 3985 return false; 3986 } 3987 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || 3988 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || 3989 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || 3990 ArgVT == MVT::v1i128 || ArgVT == MVT::f128) 3991 if (AvailableVRs > 0) { 3992 --AvailableVRs; 3993 return false; 3994 } 3995 } 3996 3997 return UseMemory; 3998 } 3999 4000 /// EnsureStackAlignment - Round stack frame size up from NumBytes to 4001 /// ensure minimum alignment required for target. 4002 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, 4003 unsigned NumBytes) { 4004 return alignTo(NumBytes, Lowering->getStackAlign()); 4005 } 4006 4007 SDValue PPCTargetLowering::LowerFormalArguments( 4008 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4009 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4010 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4011 if (Subtarget.isAIXABI()) 4012 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG, 4013 InVals); 4014 if (Subtarget.is64BitELFABI()) 4015 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 4016 InVals); 4017 assert(Subtarget.is32BitELFABI()); 4018 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, 4019 InVals); 4020 } 4021 4022 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( 4023 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4024 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4025 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4026 4027 // 32-bit SVR4 ABI Stack Frame Layout: 4028 // +-----------------------------------+ 4029 // +--> | Back chain | 4030 // | +-----------------------------------+ 4031 // | | Floating-point register save area | 4032 // | +-----------------------------------+ 4033 // | | General register save area | 4034 // | +-----------------------------------+ 4035 // | | CR save word | 4036 // | +-----------------------------------+ 4037 // | | VRSAVE save word | 4038 // | +-----------------------------------+ 4039 // | | Alignment padding | 4040 // | +-----------------------------------+ 4041 // | | Vector register save area | 4042 // | +-----------------------------------+ 4043 // | | Local variable space | 4044 // | +-----------------------------------+ 4045 // | | Parameter list area | 4046 // | +-----------------------------------+ 4047 // | | LR save word | 4048 // | +-----------------------------------+ 4049 // SP--> +--- | Back chain | 4050 // +-----------------------------------+ 4051 // 4052 // Specifications: 4053 // System V Application Binary Interface PowerPC Processor Supplement 4054 // AltiVec Technology Programming Interface Manual 4055 4056 MachineFunction &MF = DAG.getMachineFunction(); 4057 MachineFrameInfo &MFI = MF.getFrameInfo(); 4058 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4059 4060 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4061 // Potential tail calls could cause overwriting of argument stack slots. 4062 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4063 (CallConv == CallingConv::Fast)); 4064 const Align PtrAlign(4); 4065 4066 // Assign locations to all of the incoming arguments. 4067 SmallVector<CCValAssign, 16> ArgLocs; 4068 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 4069 *DAG.getContext()); 4070 4071 // Reserve space for the linkage area on the stack. 4072 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4073 CCInfo.AllocateStack(LinkageSize, PtrAlign); 4074 if (useSoftFloat()) 4075 CCInfo.PreAnalyzeFormalArguments(Ins); 4076 4077 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); 4078 CCInfo.clearWasPPCF128(); 4079 4080 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4081 CCValAssign &VA = ArgLocs[i]; 4082 4083 // Arguments stored in registers. 4084 if (VA.isRegLoc()) { 4085 const TargetRegisterClass *RC; 4086 EVT ValVT = VA.getValVT(); 4087 4088 switch (ValVT.getSimpleVT().SimpleTy) { 4089 default: 4090 llvm_unreachable("ValVT not supported by formal arguments Lowering"); 4091 case MVT::i1: 4092 case MVT::i32: 4093 RC = &PPC::GPRCRegClass; 4094 break; 4095 case MVT::f32: 4096 if (Subtarget.hasP8Vector()) 4097 RC = &PPC::VSSRCRegClass; 4098 else if (Subtarget.hasSPE()) 4099 RC = &PPC::GPRCRegClass; 4100 else 4101 RC = &PPC::F4RCRegClass; 4102 break; 4103 case MVT::f64: 4104 if (Subtarget.hasVSX()) 4105 RC = &PPC::VSFRCRegClass; 4106 else if (Subtarget.hasSPE()) 4107 // SPE passes doubles in GPR pairs. 4108 RC = &PPC::GPRCRegClass; 4109 else 4110 RC = &PPC::F8RCRegClass; 4111 break; 4112 case MVT::v16i8: 4113 case MVT::v8i16: 4114 case MVT::v4i32: 4115 RC = &PPC::VRRCRegClass; 4116 break; 4117 case MVT::v4f32: 4118 RC = &PPC::VRRCRegClass; 4119 break; 4120 case MVT::v2f64: 4121 case MVT::v2i64: 4122 RC = &PPC::VRRCRegClass; 4123 break; 4124 } 4125 4126 SDValue ArgValue; 4127 // Transform the arguments stored in physical registers into 4128 // virtual ones. 4129 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) { 4130 assert(i + 1 < e && "No second half of double precision argument"); 4131 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC); 4132 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC); 4133 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32); 4134 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32); 4135 if (!Subtarget.isLittleEndian()) 4136 std::swap (ArgValueLo, ArgValueHi); 4137 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo, 4138 ArgValueHi); 4139 } else { 4140 Register Reg = MF.addLiveIn(VA.getLocReg(), RC); 4141 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, 4142 ValVT == MVT::i1 ? MVT::i32 : ValVT); 4143 if (ValVT == MVT::i1) 4144 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); 4145 } 4146 4147 InVals.push_back(ArgValue); 4148 } else { 4149 // Argument stored in memory. 4150 assert(VA.isMemLoc()); 4151 4152 // Get the extended size of the argument type in stack 4153 unsigned ArgSize = VA.getLocVT().getStoreSize(); 4154 // Get the actual size of the argument type 4155 unsigned ObjSize = VA.getValVT().getStoreSize(); 4156 unsigned ArgOffset = VA.getLocMemOffset(); 4157 // Stack objects in PPC32 are right justified. 4158 ArgOffset += ArgSize - ObjSize; 4159 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable); 4160 4161 // Create load nodes to retrieve arguments from the stack. 4162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4163 InVals.push_back( 4164 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo())); 4165 } 4166 } 4167 4168 // Assign locations to all of the incoming aggregate by value arguments. 4169 // Aggregates passed by value are stored in the local variable space of the 4170 // caller's stack frame, right above the parameter list area. 4171 SmallVector<CCValAssign, 16> ByValArgLocs; 4172 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), 4173 ByValArgLocs, *DAG.getContext()); 4174 4175 // Reserve stack space for the allocations in CCInfo. 4176 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 4177 4178 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); 4179 4180 // Area that is at least reserved in the caller of this function. 4181 unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); 4182 MinReservedArea = std::max(MinReservedArea, LinkageSize); 4183 4184 // Set the size that is at least reserved in caller of this function. Tail 4185 // call optimized function's reserved stack space needs to be aligned so that 4186 // taking the difference between two stack areas will result in an aligned 4187 // stack. 4188 MinReservedArea = 4189 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4190 FuncInfo->setMinReservedArea(MinReservedArea); 4191 4192 SmallVector<SDValue, 8> MemOps; 4193 4194 // If the function takes variable number of arguments, make a frame index for 4195 // the start of the first vararg value... for expansion of llvm.va_start. 4196 if (isVarArg) { 4197 static const MCPhysReg GPArgRegs[] = { 4198 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 4199 PPC::R7, PPC::R8, PPC::R9, PPC::R10, 4200 }; 4201 const unsigned NumGPArgRegs = std::size(GPArgRegs); 4202 4203 static const MCPhysReg FPArgRegs[] = { 4204 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, 4205 PPC::F8 4206 }; 4207 unsigned NumFPArgRegs = std::size(FPArgRegs); 4208 4209 if (useSoftFloat() || hasSPE()) 4210 NumFPArgRegs = 0; 4211 4212 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); 4213 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); 4214 4215 // Make room for NumGPArgRegs and NumFPArgRegs. 4216 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + 4217 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; 4218 4219 FuncInfo->setVarArgsStackOffset( 4220 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8, 4221 CCInfo.getNextStackOffset(), true)); 4222 4223 FuncInfo->setVarArgsFrameIndex( 4224 MFI.CreateStackObject(Depth, Align(8), false)); 4225 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4226 4227 // The fixed integer arguments of a variadic function are stored to the 4228 // VarArgsFrameIndex on the stack so that they may be loaded by 4229 // dereferencing the result of va_next. 4230 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { 4231 // Get an existing live-in vreg, or add a new one. 4232 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); 4233 if (!VReg) 4234 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); 4235 4236 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4237 SDValue Store = 4238 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4239 MemOps.push_back(Store); 4240 // Increment the address by four for the next argument to store 4241 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); 4242 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4243 } 4244 4245 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 4246 // is set. 4247 // The double arguments are stored to the VarArgsFrameIndex 4248 // on the stack. 4249 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { 4250 // Get an existing live-in vreg, or add a new one. 4251 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); 4252 if (!VReg) 4253 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); 4254 4255 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); 4256 SDValue Store = 4257 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4258 MemOps.push_back(Store); 4259 // Increment the address by eight for the next argument to store 4260 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, 4261 PtrVT); 4262 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4263 } 4264 } 4265 4266 if (!MemOps.empty()) 4267 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4268 4269 return Chain; 4270 } 4271 4272 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4273 // value to MVT::i64 and then truncate to the correct register size. 4274 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, 4275 EVT ObjectVT, SelectionDAG &DAG, 4276 SDValue ArgVal, 4277 const SDLoc &dl) const { 4278 if (Flags.isSExt()) 4279 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, 4280 DAG.getValueType(ObjectVT)); 4281 else if (Flags.isZExt()) 4282 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, 4283 DAG.getValueType(ObjectVT)); 4284 4285 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); 4286 } 4287 4288 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( 4289 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 4290 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 4291 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 4292 // TODO: add description of PPC stack frame format, or at least some docs. 4293 // 4294 bool isELFv2ABI = Subtarget.isELFv2ABI(); 4295 bool isLittleEndian = Subtarget.isLittleEndian(); 4296 MachineFunction &MF = DAG.getMachineFunction(); 4297 MachineFrameInfo &MFI = MF.getFrameInfo(); 4298 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 4299 4300 assert(!(CallConv == CallingConv::Fast && isVarArg) && 4301 "fastcc not supported on varargs functions"); 4302 4303 EVT PtrVT = getPointerTy(MF.getDataLayout()); 4304 // Potential tail calls could cause overwriting of argument stack slots. 4305 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && 4306 (CallConv == CallingConv::Fast)); 4307 unsigned PtrByteSize = 8; 4308 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4309 4310 static const MCPhysReg GPR[] = { 4311 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4312 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4313 }; 4314 static const MCPhysReg VR[] = { 4315 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4316 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4317 }; 4318 4319 const unsigned Num_GPR_Regs = std::size(GPR); 4320 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13; 4321 const unsigned Num_VR_Regs = std::size(VR); 4322 4323 // Do a first pass over the arguments to determine whether the ABI 4324 // guarantees that our caller has allocated the parameter save area 4325 // on its stack frame. In the ELFv1 ABI, this is always the case; 4326 // in the ELFv2 ABI, it is true if this is a vararg function or if 4327 // any parameter is located in a stack slot. 4328 4329 bool HasParameterArea = !isELFv2ABI || isVarArg; 4330 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; 4331 unsigned NumBytes = LinkageSize; 4332 unsigned AvailableFPRs = Num_FPR_Regs; 4333 unsigned AvailableVRs = Num_VR_Regs; 4334 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 4335 if (Ins[i].Flags.isNest()) 4336 continue; 4337 4338 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, 4339 PtrByteSize, LinkageSize, ParamAreaSize, 4340 NumBytes, AvailableFPRs, AvailableVRs)) 4341 HasParameterArea = true; 4342 } 4343 4344 // Add DAG nodes to load the arguments or copy them out of registers. On 4345 // entry to a function on PPC, the arguments start after the linkage area, 4346 // although the first ones are often in registers. 4347 4348 unsigned ArgOffset = LinkageSize; 4349 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 4350 SmallVector<SDValue, 8> MemOps; 4351 Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin(); 4352 unsigned CurArgIdx = 0; 4353 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { 4354 SDValue ArgVal; 4355 bool needsLoad = false; 4356 EVT ObjectVT = Ins[ArgNo].VT; 4357 EVT OrigVT = Ins[ArgNo].ArgVT; 4358 unsigned ObjSize = ObjectVT.getStoreSize(); 4359 unsigned ArgSize = ObjSize; 4360 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; 4361 if (Ins[ArgNo].isOrigArg()) { 4362 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); 4363 CurArgIdx = Ins[ArgNo].getOrigArgIndex(); 4364 } 4365 // We re-align the argument offset for each argument, except when using the 4366 // fast calling convention, when we need to make sure we do that only when 4367 // we'll actually use a stack slot. 4368 unsigned CurArgOffset; 4369 Align Alignment; 4370 auto ComputeArgOffset = [&]() { 4371 /* Respect alignment of argument on the stack. */ 4372 Alignment = 4373 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); 4374 ArgOffset = alignTo(ArgOffset, Alignment); 4375 CurArgOffset = ArgOffset; 4376 }; 4377 4378 if (CallConv != CallingConv::Fast) { 4379 ComputeArgOffset(); 4380 4381 /* Compute GPR index associated with argument offset. */ 4382 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4383 GPR_idx = std::min(GPR_idx, Num_GPR_Regs); 4384 } 4385 4386 // FIXME the codegen can be much improved in some cases. 4387 // We do not have to keep everything in memory. 4388 if (Flags.isByVal()) { 4389 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); 4390 4391 if (CallConv == CallingConv::Fast) 4392 ComputeArgOffset(); 4393 4394 // ObjSize is the true size, ArgSize rounded up to multiple of registers. 4395 ObjSize = Flags.getByValSize(); 4396 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4397 // Empty aggregate parameters do not take up registers. Examples: 4398 // struct { } a; 4399 // union { } b; 4400 // int c[0]; 4401 // etc. However, we have to provide a place-holder in InVals, so 4402 // pretend we have an 8-byte item at the current address for that 4403 // purpose. 4404 if (!ObjSize) { 4405 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true); 4406 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4407 InVals.push_back(FIN); 4408 continue; 4409 } 4410 4411 // Create a stack object covering all stack doublewords occupied 4412 // by the argument. If the argument is (fully or partially) on 4413 // the stack, or if the argument is fully in registers but the 4414 // caller has allocated the parameter save anyway, we can refer 4415 // directly to the caller's stack frame. Otherwise, create a 4416 // local copy in our own frame. 4417 int FI; 4418 if (HasParameterArea || 4419 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) 4420 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true); 4421 else 4422 FI = MFI.CreateStackObject(ArgSize, Alignment, false); 4423 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4424 4425 // Handle aggregates smaller than 8 bytes. 4426 if (ObjSize < PtrByteSize) { 4427 // The value of the object is its address, which differs from the 4428 // address of the enclosing doubleword on big-endian systems. 4429 SDValue Arg = FIN; 4430 if (!isLittleEndian) { 4431 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); 4432 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); 4433 } 4434 InVals.push_back(Arg); 4435 4436 if (GPR_idx != Num_GPR_Regs) { 4437 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4438 FuncInfo->addLiveInAttr(VReg, Flags); 4439 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4440 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8); 4441 SDValue Store = 4442 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, 4443 MachinePointerInfo(&*FuncArg), ObjType); 4444 MemOps.push_back(Store); 4445 } 4446 // Whether we copied from a register or not, advance the offset 4447 // into the parameter save area by a full doubleword. 4448 ArgOffset += PtrByteSize; 4449 continue; 4450 } 4451 4452 // The value of the object is its address, which is the address of 4453 // its first stack doubleword. 4454 InVals.push_back(FIN); 4455 4456 // Store whatever pieces of the object are in registers to memory. 4457 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { 4458 if (GPR_idx == Num_GPR_Regs) 4459 break; 4460 4461 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4462 FuncInfo->addLiveInAttr(VReg, Flags); 4463 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4464 SDValue Addr = FIN; 4465 if (j) { 4466 SDValue Off = DAG.getConstant(j, dl, PtrVT); 4467 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); 4468 } 4469 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8; 4470 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits); 4471 SDValue Store = 4472 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr, 4473 MachinePointerInfo(&*FuncArg, j), ObjType); 4474 MemOps.push_back(Store); 4475 ++GPR_idx; 4476 } 4477 ArgOffset += ArgSize; 4478 continue; 4479 } 4480 4481 switch (ObjectVT.getSimpleVT().SimpleTy) { 4482 default: llvm_unreachable("Unhandled argument type!"); 4483 case MVT::i1: 4484 case MVT::i32: 4485 case MVT::i64: 4486 if (Flags.isNest()) { 4487 // The 'nest' parameter, if any, is passed in R11. 4488 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); 4489 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4490 4491 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4492 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4493 4494 break; 4495 } 4496 4497 // These can be scalar arguments or elements of an integer array type 4498 // passed directly. Clang may use those instead of "byval" aggregate 4499 // types to avoid forcing arguments to memory unnecessarily. 4500 if (GPR_idx != Num_GPR_Regs) { 4501 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4502 FuncInfo->addLiveInAttr(VReg, Flags); 4503 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4504 4505 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) 4506 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote 4507 // value to MVT::i64 and then truncate to the correct register size. 4508 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); 4509 } else { 4510 if (CallConv == CallingConv::Fast) 4511 ComputeArgOffset(); 4512 4513 needsLoad = true; 4514 ArgSize = PtrByteSize; 4515 } 4516 if (CallConv != CallingConv::Fast || needsLoad) 4517 ArgOffset += 8; 4518 break; 4519 4520 case MVT::f32: 4521 case MVT::f64: 4522 // These can be scalar arguments or elements of a float array type 4523 // passed directly. The latter are used to implement ELFv2 homogenous 4524 // float aggregates. 4525 if (FPR_idx != Num_FPR_Regs) { 4526 unsigned VReg; 4527 4528 if (ObjectVT == MVT::f32) 4529 VReg = MF.addLiveIn(FPR[FPR_idx], 4530 Subtarget.hasP8Vector() 4531 ? &PPC::VSSRCRegClass 4532 : &PPC::F4RCRegClass); 4533 else 4534 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() 4535 ? &PPC::VSFRCRegClass 4536 : &PPC::F8RCRegClass); 4537 4538 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4539 ++FPR_idx; 4540 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { 4541 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 4542 // once we support fp <-> gpr moves. 4543 4544 // This can only ever happen in the presence of f32 array types, 4545 // since otherwise we never run out of FPRs before running out 4546 // of GPRs. 4547 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); 4548 FuncInfo->addLiveInAttr(VReg, Flags); 4549 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); 4550 4551 if (ObjectVT == MVT::f32) { 4552 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) 4553 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, 4554 DAG.getConstant(32, dl, MVT::i32)); 4555 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); 4556 } 4557 4558 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); 4559 } else { 4560 if (CallConv == CallingConv::Fast) 4561 ComputeArgOffset(); 4562 4563 needsLoad = true; 4564 } 4565 4566 // When passing an array of floats, the array occupies consecutive 4567 // space in the argument area; only round up to the next doubleword 4568 // at the end of the array. Otherwise, each float takes 8 bytes. 4569 if (CallConv != CallingConv::Fast || needsLoad) { 4570 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; 4571 ArgOffset += ArgSize; 4572 if (Flags.isInConsecutiveRegsLast()) 4573 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 4574 } 4575 break; 4576 case MVT::v4f32: 4577 case MVT::v4i32: 4578 case MVT::v8i16: 4579 case MVT::v16i8: 4580 case MVT::v2f64: 4581 case MVT::v2i64: 4582 case MVT::v1i128: 4583 case MVT::f128: 4584 // These can be scalar arguments or elements of a vector array type 4585 // passed directly. The latter are used to implement ELFv2 homogenous 4586 // vector aggregates. 4587 if (VR_idx != Num_VR_Regs) { 4588 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); 4589 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); 4590 ++VR_idx; 4591 } else { 4592 if (CallConv == CallingConv::Fast) 4593 ComputeArgOffset(); 4594 needsLoad = true; 4595 } 4596 if (CallConv != CallingConv::Fast || needsLoad) 4597 ArgOffset += 16; 4598 break; 4599 } 4600 4601 // We need to load the argument to a virtual register if we determined 4602 // above that we ran out of physical registers of the appropriate type. 4603 if (needsLoad) { 4604 if (ObjSize < ArgSize && !isLittleEndian) 4605 CurArgOffset += ArgSize - ObjSize; 4606 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable); 4607 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 4608 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo()); 4609 } 4610 4611 InVals.push_back(ArgVal); 4612 } 4613 4614 // Area that is at least reserved in the caller of this function. 4615 unsigned MinReservedArea; 4616 if (HasParameterArea) 4617 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); 4618 else 4619 MinReservedArea = LinkageSize; 4620 4621 // Set the size that is at least reserved in caller of this function. Tail 4622 // call optimized functions' reserved stack space needs to be aligned so that 4623 // taking the difference between two stack areas will result in an aligned 4624 // stack. 4625 MinReservedArea = 4626 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); 4627 FuncInfo->setMinReservedArea(MinReservedArea); 4628 4629 // If the function takes variable number of arguments, make a frame index for 4630 // the start of the first vararg value... for expansion of llvm.va_start. 4631 // On ELFv2ABI spec, it writes: 4632 // C programs that are intended to be *portable* across different compilers 4633 // and architectures must use the header file <stdarg.h> to deal with variable 4634 // argument lists. 4635 if (isVarArg && MFI.hasVAStart()) { 4636 int Depth = ArgOffset; 4637 4638 FuncInfo->setVarArgsFrameIndex( 4639 MFI.CreateFixedObject(PtrByteSize, Depth, true)); 4640 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 4641 4642 // If this function is vararg, store any remaining integer argument regs 4643 // to their spots on the stack so that they may be loaded by dereferencing 4644 // the result of va_next. 4645 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 4646 GPR_idx < Num_GPR_Regs; ++GPR_idx) { 4647 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); 4648 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 4649 SDValue Store = 4650 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 4651 MemOps.push_back(Store); 4652 // Increment the address by four for the next argument to store 4653 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 4654 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 4655 } 4656 } 4657 4658 if (!MemOps.empty()) 4659 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 4660 4661 return Chain; 4662 } 4663 4664 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be 4665 /// adjusted to accommodate the arguments for the tailcall. 4666 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, 4667 unsigned ParamSize) { 4668 4669 if (!isTailCall) return 0; 4670 4671 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); 4672 unsigned CallerMinReservedArea = FI->getMinReservedArea(); 4673 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; 4674 // Remember only if the new adjustment is bigger. 4675 if (SPDiff < FI->getTailCallSPDelta()) 4676 FI->setTailCallSPDelta(SPDiff); 4677 4678 return SPDiff; 4679 } 4680 4681 static bool isFunctionGlobalAddress(SDValue Callee); 4682 4683 static bool callsShareTOCBase(const Function *Caller, SDValue Callee, 4684 const TargetMachine &TM) { 4685 // It does not make sense to call callsShareTOCBase() with a caller that 4686 // is PC Relative since PC Relative callers do not have a TOC. 4687 #ifndef NDEBUG 4688 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller); 4689 assert(!STICaller->isUsingPCRelativeCalls() && 4690 "PC Relative callers do not have a TOC and cannot share a TOC Base"); 4691 #endif 4692 4693 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols 4694 // don't have enough information to determine if the caller and callee share 4695 // the same TOC base, so we have to pessimistically assume they don't for 4696 // correctness. 4697 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 4698 if (!G) 4699 return false; 4700 4701 const GlobalValue *GV = G->getGlobal(); 4702 4703 // If the callee is preemptable, then the static linker will use a plt-stub 4704 // which saves the toc to the stack, and needs a nop after the call 4705 // instruction to convert to a toc-restore. 4706 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV)) 4707 return false; 4708 4709 // Functions with PC Relative enabled may clobber the TOC in the same DSO. 4710 // We may need a TOC restore in the situation where the caller requires a 4711 // valid TOC but the callee is PC Relative and does not. 4712 const Function *F = dyn_cast<Function>(GV); 4713 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV); 4714 4715 // If we have an Alias we can try to get the function from there. 4716 if (Alias) { 4717 const GlobalObject *GlobalObj = Alias->getAliaseeObject(); 4718 F = dyn_cast<Function>(GlobalObj); 4719 } 4720 4721 // If we still have no valid function pointer we do not have enough 4722 // information to determine if the callee uses PC Relative calls so we must 4723 // assume that it does. 4724 if (!F) 4725 return false; 4726 4727 // If the callee uses PC Relative we cannot guarantee that the callee won't 4728 // clobber the TOC of the caller and so we must assume that the two 4729 // functions do not share a TOC base. 4730 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F); 4731 if (STICallee->isUsingPCRelativeCalls()) 4732 return false; 4733 4734 // If the GV is not a strong definition then we need to assume it can be 4735 // replaced by another function at link time. The function that replaces 4736 // it may not share the same TOC as the caller since the callee may be 4737 // replaced by a PC Relative version of the same function. 4738 if (!GV->isStrongDefinitionForLinker()) 4739 return false; 4740 4741 // The medium and large code models are expected to provide a sufficiently 4742 // large TOC to provide all data addressing needs of a module with a 4743 // single TOC. 4744 if (CodeModel::Medium == TM.getCodeModel() || 4745 CodeModel::Large == TM.getCodeModel()) 4746 return true; 4747 4748 // Any explicitly-specified sections and section prefixes must also match. 4749 // Also, if we're using -ffunction-sections, then each function is always in 4750 // a different section (the same is true for COMDAT functions). 4751 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() || 4752 GV->getSection() != Caller->getSection()) 4753 return false; 4754 if (const auto *F = dyn_cast<Function>(GV)) { 4755 if (F->getSectionPrefix() != Caller->getSectionPrefix()) 4756 return false; 4757 } 4758 4759 return true; 4760 } 4761 4762 static bool 4763 needStackSlotPassParameters(const PPCSubtarget &Subtarget, 4764 const SmallVectorImpl<ISD::OutputArg> &Outs) { 4765 assert(Subtarget.is64BitELFABI()); 4766 4767 const unsigned PtrByteSize = 8; 4768 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 4769 4770 static const MCPhysReg GPR[] = { 4771 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 4772 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 4773 }; 4774 static const MCPhysReg VR[] = { 4775 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 4776 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 4777 }; 4778 4779 const unsigned NumGPRs = std::size(GPR); 4780 const unsigned NumFPRs = 13; 4781 const unsigned NumVRs = std::size(VR); 4782 const unsigned ParamAreaSize = NumGPRs * PtrByteSize; 4783 4784 unsigned NumBytes = LinkageSize; 4785 unsigned AvailableFPRs = NumFPRs; 4786 unsigned AvailableVRs = NumVRs; 4787 4788 for (const ISD::OutputArg& Param : Outs) { 4789 if (Param.Flags.isNest()) continue; 4790 4791 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize, 4792 LinkageSize, ParamAreaSize, NumBytes, 4793 AvailableFPRs, AvailableVRs)) 4794 return true; 4795 } 4796 return false; 4797 } 4798 4799 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) { 4800 if (CB.arg_size() != CallerFn->arg_size()) 4801 return false; 4802 4803 auto CalleeArgIter = CB.arg_begin(); 4804 auto CalleeArgEnd = CB.arg_end(); 4805 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin(); 4806 4807 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) { 4808 const Value* CalleeArg = *CalleeArgIter; 4809 const Value* CallerArg = &(*CallerArgIter); 4810 if (CalleeArg == CallerArg) 4811 continue; 4812 4813 // e.g. @caller([4 x i64] %a, [4 x i64] %b) { 4814 // tail call @callee([4 x i64] undef, [4 x i64] %b) 4815 // } 4816 // 1st argument of callee is undef and has the same type as caller. 4817 if (CalleeArg->getType() == CallerArg->getType() && 4818 isa<UndefValue>(CalleeArg)) 4819 continue; 4820 4821 return false; 4822 } 4823 4824 return true; 4825 } 4826 4827 // Returns true if TCO is possible between the callers and callees 4828 // calling conventions. 4829 static bool 4830 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, 4831 CallingConv::ID CalleeCC) { 4832 // Tail calls are possible with fastcc and ccc. 4833 auto isTailCallableCC = [] (CallingConv::ID CC){ 4834 return CC == CallingConv::C || CC == CallingConv::Fast; 4835 }; 4836 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC)) 4837 return false; 4838 4839 // We can safely tail call both fastcc and ccc callees from a c calling 4840 // convention caller. If the caller is fastcc, we may have less stack space 4841 // than a non-fastcc caller with the same signature so disable tail-calls in 4842 // that case. 4843 return CallerCC == CallingConv::C || CallerCC == CalleeCC; 4844 } 4845 4846 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4( 4847 SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg, 4848 const SmallVectorImpl<ISD::OutputArg> &Outs, 4849 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 4850 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt; 4851 4852 if (DisableSCO && !TailCallOpt) return false; 4853 4854 // Variadic argument functions are not supported. 4855 if (isVarArg) return false; 4856 4857 auto &Caller = DAG.getMachineFunction().getFunction(); 4858 // Check that the calling conventions are compatible for tco. 4859 if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC)) 4860 return false; 4861 4862 // Caller contains any byval parameter is not supported. 4863 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); })) 4864 return false; 4865 4866 // Callee contains any byval parameter is not supported, too. 4867 // Note: This is a quick work around, because in some cases, e.g. 4868 // caller's stack size > callee's stack size, we are still able to apply 4869 // sibling call optimization. For example, gcc is able to do SCO for caller1 4870 // in the following example, but not for caller2. 4871 // struct test { 4872 // long int a; 4873 // char ary[56]; 4874 // } gTest; 4875 // __attribute__((noinline)) int callee(struct test v, struct test *b) { 4876 // b->a = v.a; 4877 // return 0; 4878 // } 4879 // void caller1(struct test a, struct test c, struct test *b) { 4880 // callee(gTest, b); } 4881 // void caller2(struct test *b) { callee(gTest, b); } 4882 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); })) 4883 return false; 4884 4885 // If callee and caller use different calling conventions, we cannot pass 4886 // parameters on stack since offsets for the parameter area may be different. 4887 if (Caller.getCallingConv() != CalleeCC && 4888 needStackSlotPassParameters(Subtarget, Outs)) 4889 return false; 4890 4891 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that 4892 // the caller and callee share the same TOC for TCO/SCO. If the caller and 4893 // callee potentially have different TOC bases then we cannot tail call since 4894 // we need to restore the TOC pointer after the call. 4895 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977 4896 // We cannot guarantee this for indirect calls or calls to external functions. 4897 // When PC-Relative addressing is used, the concept of the TOC is no longer 4898 // applicable so this check is not required. 4899 // Check first for indirect calls. 4900 if (!Subtarget.isUsingPCRelativeCalls() && 4901 !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) 4902 return false; 4903 4904 // Check if we share the TOC base. 4905 if (!Subtarget.isUsingPCRelativeCalls() && 4906 !callsShareTOCBase(&Caller, Callee, getTargetMachine())) 4907 return false; 4908 4909 // TCO allows altering callee ABI, so we don't have to check further. 4910 if (CalleeCC == CallingConv::Fast && TailCallOpt) 4911 return true; 4912 4913 if (DisableSCO) return false; 4914 4915 // If callee use the same argument list that caller is using, then we can 4916 // apply SCO on this case. If it is not, then we need to check if callee needs 4917 // stack for passing arguments. 4918 // PC Relative tail calls may not have a CallBase. 4919 // If there is no CallBase we cannot verify if we have the same argument 4920 // list so assume that we don't have the same argument list. 4921 if (CB && !hasSameArgumentList(&Caller, *CB) && 4922 needStackSlotPassParameters(Subtarget, Outs)) 4923 return false; 4924 else if (!CB && needStackSlotPassParameters(Subtarget, Outs)) 4925 return false; 4926 4927 return true; 4928 } 4929 4930 /// IsEligibleForTailCallOptimization - Check whether the call is eligible 4931 /// for tail call optimization. Targets which want to do tail call 4932 /// optimization should implement this function. 4933 bool 4934 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, 4935 CallingConv::ID CalleeCC, 4936 bool isVarArg, 4937 const SmallVectorImpl<ISD::InputArg> &Ins, 4938 SelectionDAG& DAG) const { 4939 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 4940 return false; 4941 4942 // Variable argument functions are not supported. 4943 if (isVarArg) 4944 return false; 4945 4946 MachineFunction &MF = DAG.getMachineFunction(); 4947 CallingConv::ID CallerCC = MF.getFunction().getCallingConv(); 4948 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { 4949 // Functions containing by val parameters are not supported. 4950 for (unsigned i = 0; i != Ins.size(); i++) { 4951 ISD::ArgFlagsTy Flags = Ins[i].Flags; 4952 if (Flags.isByVal()) return false; 4953 } 4954 4955 // Non-PIC/GOT tail calls are supported. 4956 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 4957 return true; 4958 4959 // At the moment we can only do local tail calls (in same module, hidden 4960 // or protected) if we are generating PIC. 4961 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) 4962 return G->getGlobal()->hasHiddenVisibility() 4963 || G->getGlobal()->hasProtectedVisibility(); 4964 } 4965 4966 return false; 4967 } 4968 4969 /// isCallCompatibleAddress - Return the immediate to use if the specified 4970 /// 32-bit value is representable in the immediate field of a BxA instruction. 4971 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { 4972 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4973 if (!C) return nullptr; 4974 4975 int Addr = C->getZExtValue(); 4976 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. 4977 SignExtend32<26>(Addr) != Addr) 4978 return nullptr; // Top 6 bits have to be sext of immediate. 4979 4980 return DAG 4981 .getConstant( 4982 (int)C->getZExtValue() >> 2, SDLoc(Op), 4983 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())) 4984 .getNode(); 4985 } 4986 4987 namespace { 4988 4989 struct TailCallArgumentInfo { 4990 SDValue Arg; 4991 SDValue FrameIdxOp; 4992 int FrameIdx = 0; 4993 4994 TailCallArgumentInfo() = default; 4995 }; 4996 4997 } // end anonymous namespace 4998 4999 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. 5000 static void StoreTailCallArgumentsToStackSlot( 5001 SelectionDAG &DAG, SDValue Chain, 5002 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, 5003 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) { 5004 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { 5005 SDValue Arg = TailCallArgs[i].Arg; 5006 SDValue FIN = TailCallArgs[i].FrameIdxOp; 5007 int FI = TailCallArgs[i].FrameIdx; 5008 // Store relative to framepointer. 5009 MemOpChains.push_back(DAG.getStore( 5010 Chain, dl, Arg, FIN, 5011 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI))); 5012 } 5013 } 5014 5015 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to 5016 /// the appropriate stack slot for the tail call optimized function call. 5017 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, 5018 SDValue OldRetAddr, SDValue OldFP, 5019 int SPDiff, const SDLoc &dl) { 5020 if (SPDiff) { 5021 // Calculate the new stack slot for the return address. 5022 MachineFunction &MF = DAG.getMachineFunction(); 5023 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>(); 5024 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 5025 bool isPPC64 = Subtarget.isPPC64(); 5026 int SlotSize = isPPC64 ? 8 : 4; 5027 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); 5028 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize, 5029 NewRetAddrLoc, true); 5030 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5031 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); 5032 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx, 5033 MachinePointerInfo::getFixedStack(MF, NewRetAddr)); 5034 } 5035 return Chain; 5036 } 5037 5038 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate 5039 /// the position of the argument. 5040 static void 5041 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, 5042 SDValue Arg, int SPDiff, unsigned ArgOffset, 5043 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { 5044 int Offset = ArgOffset + SPDiff; 5045 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8; 5046 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 5047 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5048 SDValue FIN = DAG.getFrameIndex(FI, VT); 5049 TailCallArgumentInfo Info; 5050 Info.Arg = Arg; 5051 Info.FrameIdxOp = FIN; 5052 Info.FrameIdx = FI; 5053 TailCallArguments.push_back(Info); 5054 } 5055 5056 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address 5057 /// stack slot. Returns the chain as result and the loaded frame pointers in 5058 /// LROpOut/FPOpout. Used when tail calling. 5059 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr( 5060 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, 5061 SDValue &FPOpOut, const SDLoc &dl) const { 5062 if (SPDiff) { 5063 // Load the LR and FP stack slot for later adjusting. 5064 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5065 LROpOut = getReturnAddrFrameIndex(DAG); 5066 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo()); 5067 Chain = SDValue(LROpOut.getNode(), 1); 5068 } 5069 return Chain; 5070 } 5071 5072 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified 5073 /// by "Src" to address "Dst" of size "Size". Alignment information is 5074 /// specified by the specific parameter attribute. The copy will be passed as 5075 /// a byval function parameter. 5076 /// Sometimes what we are copying is the end of a larger object, the part that 5077 /// does not fit in registers. 5078 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, 5079 SDValue Chain, ISD::ArgFlagsTy Flags, 5080 SelectionDAG &DAG, const SDLoc &dl) { 5081 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); 5082 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, 5083 Flags.getNonZeroByValAlign(), false, false, false, 5084 MachinePointerInfo(), MachinePointerInfo()); 5085 } 5086 5087 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of 5088 /// tail calls. 5089 static void LowerMemOpCallTo( 5090 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, 5091 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, 5092 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, 5093 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) { 5094 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5095 if (!isTailCall) { 5096 if (isVector) { 5097 SDValue StackPtr; 5098 if (isPPC64) 5099 StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 5100 else 5101 StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5102 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, 5103 DAG.getConstant(ArgOffset, dl, PtrVT)); 5104 } 5105 MemOpChains.push_back( 5106 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5107 // Calculate and remember argument location. 5108 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, 5109 TailCallArguments); 5110 } 5111 5112 static void 5113 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, 5114 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, 5115 SDValue FPOp, 5116 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { 5117 // Emit a sequence of copyto/copyfrom virtual registers for arguments that 5118 // might overwrite each other in case of tail call optimization. 5119 SmallVector<SDValue, 8> MemOpChains2; 5120 // Do not flag preceding copytoreg stuff together with the following stuff. 5121 InFlag = SDValue(); 5122 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, 5123 MemOpChains2, dl); 5124 if (!MemOpChains2.empty()) 5125 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); 5126 5127 // Store the return address to the appropriate stack slot. 5128 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl); 5129 5130 // Emit callseq_end just before tailcall node. 5131 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InFlag, dl); 5132 InFlag = Chain.getValue(1); 5133 } 5134 5135 // Is this global address that of a function that can be called by name? (as 5136 // opposed to something that must hold a descriptor for an indirect call). 5137 static bool isFunctionGlobalAddress(SDValue Callee) { 5138 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 5139 if (Callee.getOpcode() == ISD::GlobalTLSAddress || 5140 Callee.getOpcode() == ISD::TargetGlobalTLSAddress) 5141 return false; 5142 5143 return G->getGlobal()->getValueType()->isFunctionTy(); 5144 } 5145 5146 return false; 5147 } 5148 5149 SDValue PPCTargetLowering::LowerCallResult( 5150 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 5151 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5152 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 5153 SmallVector<CCValAssign, 16> RVLocs; 5154 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 5155 *DAG.getContext()); 5156 5157 CCRetInfo.AnalyzeCallResult( 5158 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 5159 ? RetCC_PPC_Cold 5160 : RetCC_PPC); 5161 5162 // Copy all of the result registers out of their specified physreg. 5163 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { 5164 CCValAssign &VA = RVLocs[i]; 5165 assert(VA.isRegLoc() && "Can only return in registers!"); 5166 5167 SDValue Val; 5168 5169 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 5170 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5171 InFlag); 5172 Chain = Lo.getValue(1); 5173 InFlag = Lo.getValue(2); 5174 VA = RVLocs[++i]; // skip ahead to next loc 5175 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 5176 InFlag); 5177 Chain = Hi.getValue(1); 5178 InFlag = Hi.getValue(2); 5179 if (!Subtarget.isLittleEndian()) 5180 std::swap (Lo, Hi); 5181 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi); 5182 } else { 5183 Val = DAG.getCopyFromReg(Chain, dl, 5184 VA.getLocReg(), VA.getLocVT(), InFlag); 5185 Chain = Val.getValue(1); 5186 InFlag = Val.getValue(2); 5187 } 5188 5189 switch (VA.getLocInfo()) { 5190 default: llvm_unreachable("Unknown loc info!"); 5191 case CCValAssign::Full: break; 5192 case CCValAssign::AExt: 5193 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5194 break; 5195 case CCValAssign::ZExt: 5196 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val, 5197 DAG.getValueType(VA.getValVT())); 5198 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5199 break; 5200 case CCValAssign::SExt: 5201 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val, 5202 DAG.getValueType(VA.getValVT())); 5203 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val); 5204 break; 5205 } 5206 5207 InVals.push_back(Val); 5208 } 5209 5210 return Chain; 5211 } 5212 5213 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG, 5214 const PPCSubtarget &Subtarget, bool isPatchPoint) { 5215 // PatchPoint calls are not indirect. 5216 if (isPatchPoint) 5217 return false; 5218 5219 if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee)) 5220 return false; 5221 5222 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not 5223 // becuase the immediate function pointer points to a descriptor instead of 5224 // a function entry point. The ELFv2 ABI cannot use a BLA because the function 5225 // pointer immediate points to the global entry point, while the BLA would 5226 // need to jump to the local entry point (see rL211174). 5227 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() && 5228 isBLACompatibleAddress(Callee, DAG)) 5229 return false; 5230 5231 return true; 5232 } 5233 5234 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls. 5235 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) { 5236 return Subtarget.isAIXABI() || 5237 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()); 5238 } 5239 5240 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags, 5241 const Function &Caller, const SDValue &Callee, 5242 const PPCSubtarget &Subtarget, 5243 const TargetMachine &TM, 5244 bool IsStrictFPCall = false) { 5245 if (CFlags.IsTailCall) 5246 return PPCISD::TC_RETURN; 5247 5248 unsigned RetOpc = 0; 5249 // This is a call through a function pointer. 5250 if (CFlags.IsIndirect) { 5251 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross 5252 // indirect calls. The save of the caller's TOC pointer to the stack will be 5253 // inserted into the DAG as part of call lowering. The restore of the TOC 5254 // pointer is modeled by using a pseudo instruction for the call opcode that 5255 // represents the 2 instruction sequence of an indirect branch and link, 5256 // immediately followed by a load of the TOC pointer from the the stack save 5257 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC 5258 // as it is not saved or used. 5259 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC 5260 : PPCISD::BCTRL; 5261 } else if (Subtarget.isUsingPCRelativeCalls()) { 5262 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI."); 5263 RetOpc = PPCISD::CALL_NOTOC; 5264 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) 5265 // The ABIs that maintain a TOC pointer accross calls need to have a nop 5266 // immediately following the call instruction if the caller and callee may 5267 // have different TOC bases. At link time if the linker determines the calls 5268 // may not share a TOC base, the call is redirected to a trampoline inserted 5269 // by the linker. The trampoline will (among other things) save the callers 5270 // TOC pointer at an ABI designated offset in the linkage area and the 5271 // linker will rewrite the nop to be a load of the TOC pointer from the 5272 // linkage area into gpr2. 5273 RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL 5274 : PPCISD::CALL_NOP; 5275 else 5276 RetOpc = PPCISD::CALL; 5277 if (IsStrictFPCall) { 5278 switch (RetOpc) { 5279 default: 5280 llvm_unreachable("Unknown call opcode"); 5281 case PPCISD::BCTRL_LOAD_TOC: 5282 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM; 5283 break; 5284 case PPCISD::BCTRL: 5285 RetOpc = PPCISD::BCTRL_RM; 5286 break; 5287 case PPCISD::CALL_NOTOC: 5288 RetOpc = PPCISD::CALL_NOTOC_RM; 5289 break; 5290 case PPCISD::CALL: 5291 RetOpc = PPCISD::CALL_RM; 5292 break; 5293 case PPCISD::CALL_NOP: 5294 RetOpc = PPCISD::CALL_NOP_RM; 5295 break; 5296 } 5297 } 5298 return RetOpc; 5299 } 5300 5301 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, 5302 const SDLoc &dl, const PPCSubtarget &Subtarget) { 5303 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI()) 5304 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) 5305 return SDValue(Dest, 0); 5306 5307 // Returns true if the callee is local, and false otherwise. 5308 auto isLocalCallee = [&]() { 5309 const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee); 5310 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5311 const GlobalValue *GV = G ? G->getGlobal() : nullptr; 5312 5313 return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) && 5314 !isa_and_nonnull<GlobalIFunc>(GV); 5315 }; 5316 5317 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in 5318 // a static relocation model causes some versions of GNU LD (2.17.50, at 5319 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are 5320 // built with secure-PLT. 5321 bool UsePlt = 5322 Subtarget.is32BitELFABI() && !isLocalCallee() && 5323 Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_; 5324 5325 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) { 5326 const TargetMachine &TM = Subtarget.getTargetMachine(); 5327 const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering(); 5328 MCSymbolXCOFF *S = 5329 cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM)); 5330 5331 MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 5332 return DAG.getMCSymbol(S, PtrVT); 5333 }; 5334 5335 if (isFunctionGlobalAddress(Callee)) { 5336 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal(); 5337 5338 if (Subtarget.isAIXABI()) { 5339 assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX."); 5340 return getAIXFuncEntryPointSymbolSDNode(GV); 5341 } 5342 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0, 5343 UsePlt ? PPCII::MO_PLT : 0); 5344 } 5345 5346 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 5347 const char *SymName = S->getSymbol(); 5348 if (Subtarget.isAIXABI()) { 5349 // If there exists a user-declared function whose name is the same as the 5350 // ExternalSymbol's, then we pick up the user-declared version. 5351 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 5352 if (const Function *F = 5353 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) 5354 return getAIXFuncEntryPointSymbolSDNode(F); 5355 5356 // On AIX, direct function calls reference the symbol for the function's 5357 // entry point, which is named by prepending a "." before the function's 5358 // C-linkage name. A Qualname is returned here because an external 5359 // function entry point is a csect with XTY_ER property. 5360 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) { 5361 auto &Context = DAG.getMachineFunction().getMMI().getContext(); 5362 MCSectionXCOFF *Sec = Context.getXCOFFSection( 5363 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(), 5364 XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER)); 5365 return Sec->getQualNameSymbol(); 5366 }; 5367 5368 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data(); 5369 } 5370 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(), 5371 UsePlt ? PPCII::MO_PLT : 0); 5372 } 5373 5374 // No transformation needed. 5375 assert(Callee.getNode() && "What no callee?"); 5376 return Callee; 5377 } 5378 5379 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) { 5380 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START && 5381 "Expected a CALLSEQ_STARTSDNode."); 5382 5383 // The last operand is the chain, except when the node has glue. If the node 5384 // has glue, then the last operand is the glue, and the chain is the second 5385 // last operand. 5386 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1); 5387 if (LastValue.getValueType() != MVT::Glue) 5388 return LastValue; 5389 5390 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2); 5391 } 5392 5393 // Creates the node that moves a functions address into the count register 5394 // to prepare for an indirect call instruction. 5395 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5396 SDValue &Glue, SDValue &Chain, 5397 const SDLoc &dl) { 5398 SDValue MTCTROps[] = {Chain, Callee, Glue}; 5399 EVT ReturnTypes[] = {MVT::Other, MVT::Glue}; 5400 Chain = DAG.getNode(PPCISD::MTCTR, dl, ArrayRef(ReturnTypes, 2), 5401 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2)); 5402 // The glue is the second value produced. 5403 Glue = Chain.getValue(1); 5404 } 5405 5406 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, 5407 SDValue &Glue, SDValue &Chain, 5408 SDValue CallSeqStart, 5409 const CallBase *CB, const SDLoc &dl, 5410 bool hasNest, 5411 const PPCSubtarget &Subtarget) { 5412 // Function pointers in the 64-bit SVR4 ABI do not point to the function 5413 // entry point, but to the function descriptor (the function entry point 5414 // address is part of the function descriptor though). 5415 // The function descriptor is a three doubleword structure with the 5416 // following fields: function entry point, TOC base address and 5417 // environment pointer. 5418 // Thus for a call through a function pointer, the following actions need 5419 // to be performed: 5420 // 1. Save the TOC of the caller in the TOC save area of its stack 5421 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). 5422 // 2. Load the address of the function entry point from the function 5423 // descriptor. 5424 // 3. Load the TOC of the callee from the function descriptor into r2. 5425 // 4. Load the environment pointer from the function descriptor into 5426 // r11. 5427 // 5. Branch to the function entry point address. 5428 // 6. On return of the callee, the TOC of the caller needs to be 5429 // restored (this is done in FinishCall()). 5430 // 5431 // The loads are scheduled at the beginning of the call sequence, and the 5432 // register copies are flagged together to ensure that no other 5433 // operations can be scheduled in between. E.g. without flagging the 5434 // copies together, a TOC access in the caller could be scheduled between 5435 // the assignment of the callee TOC and the branch to the callee, which leads 5436 // to incorrect code. 5437 5438 // Start by loading the function address from the descriptor. 5439 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart); 5440 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors() 5441 ? (MachineMemOperand::MODereferenceable | 5442 MachineMemOperand::MOInvariant) 5443 : MachineMemOperand::MONone; 5444 5445 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr); 5446 5447 // Registers used in building the DAG. 5448 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister(); 5449 const MCRegister TOCReg = Subtarget.getTOCPointerRegister(); 5450 5451 // Offsets of descriptor members. 5452 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset(); 5453 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset(); 5454 5455 const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 5456 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4); 5457 5458 // One load for the functions entry point address. 5459 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI, 5460 Alignment, MMOFlags); 5461 5462 // One for loading the TOC anchor for the module that contains the called 5463 // function. 5464 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl); 5465 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff); 5466 SDValue TOCPtr = 5467 DAG.getLoad(RegVT, dl, LDChain, AddTOC, 5468 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags); 5469 5470 // One for loading the environment pointer. 5471 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl); 5472 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff); 5473 SDValue LoadEnvPtr = 5474 DAG.getLoad(RegVT, dl, LDChain, AddPtr, 5475 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags); 5476 5477 5478 // Then copy the newly loaded TOC anchor to the TOC pointer. 5479 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue); 5480 Chain = TOCVal.getValue(0); 5481 Glue = TOCVal.getValue(1); 5482 5483 // If the function call has an explicit 'nest' parameter, it takes the 5484 // place of the environment pointer. 5485 assert((!hasNest || !Subtarget.isAIXABI()) && 5486 "Nest parameter is not supported on AIX."); 5487 if (!hasNest) { 5488 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue); 5489 Chain = EnvVal.getValue(0); 5490 Glue = EnvVal.getValue(1); 5491 } 5492 5493 // The rest of the indirect call sequence is the same as the non-descriptor 5494 // DAG. 5495 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl); 5496 } 5497 5498 static void 5499 buildCallOperands(SmallVectorImpl<SDValue> &Ops, 5500 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, 5501 SelectionDAG &DAG, 5502 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, 5503 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, 5504 const PPCSubtarget &Subtarget) { 5505 const bool IsPPC64 = Subtarget.isPPC64(); 5506 // MVT for a general purpose register. 5507 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 5508 5509 // First operand is always the chain. 5510 Ops.push_back(Chain); 5511 5512 // If it's a direct call pass the callee as the second operand. 5513 if (!CFlags.IsIndirect) 5514 Ops.push_back(Callee); 5515 else { 5516 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect."); 5517 5518 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area 5519 // on the stack (this would have been done in `LowerCall_64SVR4` or 5520 // `LowerCall_AIX`). The call instruction is a pseudo instruction that 5521 // represents both the indirect branch and a load that restores the TOC 5522 // pointer from the linkage area. The operand for the TOC restore is an add 5523 // of the TOC save offset to the stack pointer. This must be the second 5524 // operand: after the chain input but before any other variadic arguments. 5525 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not 5526 // saved or used. 5527 if (isTOCSaveRestoreRequired(Subtarget)) { 5528 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 5529 5530 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT); 5531 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 5532 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 5533 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff); 5534 Ops.push_back(AddTOC); 5535 } 5536 5537 // Add the register used for the environment pointer. 5538 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest) 5539 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(), 5540 RegVT)); 5541 5542 5543 // Add CTR register as callee so a bctr can be emitted later. 5544 if (CFlags.IsTailCall) 5545 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT)); 5546 } 5547 5548 // If this is a tail call add stack pointer delta. 5549 if (CFlags.IsTailCall) 5550 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); 5551 5552 // Add argument registers to the end of the list so that they are known live 5553 // into the call. 5554 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 5555 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 5556 RegsToPass[i].second.getValueType())); 5557 5558 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is 5559 // no way to mark dependencies as implicit here. 5560 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter. 5561 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && 5562 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls()) 5563 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT)); 5564 5565 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls 5566 if (CFlags.IsVarArg && Subtarget.is32BitELFABI()) 5567 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); 5568 5569 // Add a register mask operand representing the call-preserved registers. 5570 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5571 const uint32_t *Mask = 5572 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv); 5573 assert(Mask && "Missing call preserved mask for calling convention"); 5574 Ops.push_back(DAG.getRegisterMask(Mask)); 5575 5576 // If the glue is valid, it is the last operand. 5577 if (Glue.getNode()) 5578 Ops.push_back(Glue); 5579 } 5580 5581 SDValue PPCTargetLowering::FinishCall( 5582 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, 5583 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue, 5584 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, 5585 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, 5586 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const { 5587 5588 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) || 5589 Subtarget.isAIXABI()) 5590 setUsesTOCBasePtr(DAG); 5591 5592 unsigned CallOpc = 5593 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee, 5594 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false); 5595 5596 if (!CFlags.IsIndirect) 5597 Callee = transformCallee(Callee, DAG, dl, Subtarget); 5598 else if (Subtarget.usesFunctionDescriptors()) 5599 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, 5600 dl, CFlags.HasNest, Subtarget); 5601 else 5602 prepareIndirectCall(DAG, Callee, Glue, Chain, dl); 5603 5604 // Build the operand list for the call instruction. 5605 SmallVector<SDValue, 8> Ops; 5606 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee, 5607 SPDiff, Subtarget); 5608 5609 // Emit tail call. 5610 if (CFlags.IsTailCall) { 5611 // Indirect tail call when using PC Relative calls do not have the same 5612 // constraints. 5613 assert(((Callee.getOpcode() == ISD::Register && 5614 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || 5615 Callee.getOpcode() == ISD::TargetExternalSymbol || 5616 Callee.getOpcode() == ISD::TargetGlobalAddress || 5617 isa<ConstantSDNode>(Callee) || 5618 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) && 5619 "Expecting a global address, external symbol, absolute value, " 5620 "register or an indirect tail call when PC Relative calls are " 5621 "used."); 5622 // PC Relative calls also use TC_RETURN as the way to mark tail calls. 5623 assert(CallOpc == PPCISD::TC_RETURN && 5624 "Unexpected call opcode for a tail call."); 5625 DAG.getMachineFunction().getFrameInfo().setHasTailCall(); 5626 return DAG.getNode(CallOpc, dl, MVT::Other, Ops); 5627 } 5628 5629 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}}; 5630 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops); 5631 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge); 5632 Glue = Chain.getValue(1); 5633 5634 // When performing tail call optimization the callee pops its arguments off 5635 // the stack. Account for this here so these bytes can be pushed back on in 5636 // PPCFrameLowering::eliminateCallFramePseudoInstr. 5637 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast && 5638 getTargetMachine().Options.GuaranteedTailCallOpt) 5639 ? NumBytes 5640 : 0; 5641 5642 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl); 5643 Glue = Chain.getValue(1); 5644 5645 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl, 5646 DAG, InVals); 5647 } 5648 5649 SDValue 5650 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 5651 SmallVectorImpl<SDValue> &InVals) const { 5652 SelectionDAG &DAG = CLI.DAG; 5653 SDLoc &dl = CLI.DL; 5654 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 5655 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 5656 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 5657 SDValue Chain = CLI.Chain; 5658 SDValue Callee = CLI.Callee; 5659 bool &isTailCall = CLI.IsTailCall; 5660 CallingConv::ID CallConv = CLI.CallConv; 5661 bool isVarArg = CLI.IsVarArg; 5662 bool isPatchPoint = CLI.IsPatchPoint; 5663 const CallBase *CB = CLI.CB; 5664 5665 if (isTailCall) { 5666 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall())) 5667 isTailCall = false; 5668 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) 5669 isTailCall = IsEligibleForTailCallOptimization_64SVR4( 5670 Callee, CallConv, CB, isVarArg, Outs, Ins, DAG); 5671 else 5672 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, 5673 Ins, DAG); 5674 if (isTailCall) { 5675 ++NumTailCalls; 5676 if (!getTargetMachine().Options.GuaranteedTailCallOpt) 5677 ++NumSiblingCalls; 5678 5679 // PC Relative calls no longer guarantee that the callee is a Global 5680 // Address Node. The callee could be an indirect tail call in which 5681 // case the SDValue for the callee could be a load (to load the address 5682 // of a function pointer) or it may be a register copy (to move the 5683 // address of the callee from a function parameter into a virtual 5684 // register). It may also be an ExternalSymbolSDNode (ex memcopy). 5685 assert((Subtarget.isUsingPCRelativeCalls() || 5686 isa<GlobalAddressSDNode>(Callee)) && 5687 "Callee should be an llvm::Function object."); 5688 5689 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName() 5690 << "\nTCO callee: "); 5691 LLVM_DEBUG(Callee.dump()); 5692 } 5693 } 5694 5695 if (!isTailCall && CB && CB->isMustTailCall()) 5696 report_fatal_error("failed to perform tail call elimination on a call " 5697 "site marked musttail"); 5698 5699 // When long calls (i.e. indirect calls) are always used, calls are always 5700 // made via function pointer. If we have a function name, first translate it 5701 // into a pointer. 5702 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) && 5703 !isTailCall) 5704 Callee = LowerGlobalAddress(Callee, DAG); 5705 5706 CallFlags CFlags( 5707 CallConv, isTailCall, isVarArg, isPatchPoint, 5708 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint), 5709 // hasNest 5710 Subtarget.is64BitELFABI() && 5711 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }), 5712 CLI.NoMerge); 5713 5714 if (Subtarget.isAIXABI()) 5715 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5716 InVals, CB); 5717 5718 assert(Subtarget.isSVR4ABI()); 5719 if (Subtarget.isPPC64()) 5720 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5721 InVals, CB); 5722 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG, 5723 InVals, CB); 5724 } 5725 5726 SDValue PPCTargetLowering::LowerCall_32SVR4( 5727 SDValue Chain, SDValue Callee, CallFlags CFlags, 5728 const SmallVectorImpl<ISD::OutputArg> &Outs, 5729 const SmallVectorImpl<SDValue> &OutVals, 5730 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5731 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5732 const CallBase *CB) const { 5733 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description 5734 // of the 32-bit SVR4 ABI stack frame layout. 5735 5736 const CallingConv::ID CallConv = CFlags.CallConv; 5737 const bool IsVarArg = CFlags.IsVarArg; 5738 const bool IsTailCall = CFlags.IsTailCall; 5739 5740 assert((CallConv == CallingConv::C || 5741 CallConv == CallingConv::Cold || 5742 CallConv == CallingConv::Fast) && "Unknown calling convention!"); 5743 5744 const Align PtrAlign(4); 5745 5746 MachineFunction &MF = DAG.getMachineFunction(); 5747 5748 // Mark this function as potentially containing a function that contains a 5749 // tail call. As a consequence the frame pointer will be used for dynamicalloc 5750 // and restoring the callers stack pointer in this functions epilog. This is 5751 // done because by tail calling the called function might overwrite the value 5752 // in this function's (MF) stack pointer stack slot 0(SP). 5753 if (getTargetMachine().Options.GuaranteedTailCallOpt && 5754 CallConv == CallingConv::Fast) 5755 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 5756 5757 // Count how many bytes are to be pushed on the stack, including the linkage 5758 // area, parameter list area and the part of the local variable space which 5759 // contains copies of aggregates which are passed by value. 5760 5761 // Assign locations to all of the outgoing arguments. 5762 SmallVector<CCValAssign, 16> ArgLocs; 5763 PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 5764 5765 // Reserve space for the linkage area on the stack. 5766 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), 5767 PtrAlign); 5768 if (useSoftFloat()) 5769 CCInfo.PreAnalyzeCallOperands(Outs); 5770 5771 if (IsVarArg) { 5772 // Handle fixed and variable vector arguments differently. 5773 // Fixed vector arguments go into registers as long as registers are 5774 // available. Variable vector arguments always go into memory. 5775 unsigned NumArgs = Outs.size(); 5776 5777 for (unsigned i = 0; i != NumArgs; ++i) { 5778 MVT ArgVT = Outs[i].VT; 5779 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 5780 bool Result; 5781 5782 if (Outs[i].IsFixed) { 5783 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, 5784 CCInfo); 5785 } else { 5786 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, 5787 ArgFlags, CCInfo); 5788 } 5789 5790 if (Result) { 5791 #ifndef NDEBUG 5792 errs() << "Call operand #" << i << " has unhandled type " 5793 << EVT(ArgVT).getEVTString() << "\n"; 5794 #endif 5795 llvm_unreachable(nullptr); 5796 } 5797 } 5798 } else { 5799 // All arguments are treated the same. 5800 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); 5801 } 5802 CCInfo.clearWasPPCF128(); 5803 5804 // Assign locations to all of the outgoing aggregate by value arguments. 5805 SmallVector<CCValAssign, 16> ByValArgLocs; 5806 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext()); 5807 5808 // Reserve stack space for the allocations in CCInfo. 5809 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign); 5810 5811 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); 5812 5813 // Size of the linkage area, parameter list area and the part of the local 5814 // space variable where copies of aggregates which are passed by value are 5815 // stored. 5816 unsigned NumBytes = CCByValInfo.getNextStackOffset(); 5817 5818 // Calculate by how many bytes the stack has to be adjusted in case of tail 5819 // call optimization. 5820 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes); 5821 5822 // Adjust the stack pointer for the new arguments... 5823 // These operations are automatically eliminated by the prolog/epilog pass 5824 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 5825 SDValue CallSeqStart = Chain; 5826 5827 // Load the return address and frame pointer so it can be moved somewhere else 5828 // later. 5829 SDValue LROp, FPOp; 5830 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 5831 5832 // Set up a copy of the stack pointer for use loading and storing any 5833 // arguments that may not fit in the registers available for argument 5834 // passing. 5835 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); 5836 5837 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 5838 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 5839 SmallVector<SDValue, 8> MemOpChains; 5840 5841 bool seenFloatArg = false; 5842 // Walk the register/memloc assignments, inserting copies/loads. 5843 // i - Tracks the index into the list of registers allocated for the call 5844 // RealArgIdx - Tracks the index into the list of actual function arguments 5845 // j - Tracks the index into the list of byval arguments 5846 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size(); 5847 i != e; 5848 ++i, ++RealArgIdx) { 5849 CCValAssign &VA = ArgLocs[i]; 5850 SDValue Arg = OutVals[RealArgIdx]; 5851 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags; 5852 5853 if (Flags.isByVal()) { 5854 // Argument is an aggregate which is passed by value, thus we need to 5855 // create a copy of it in the local variable space of the current stack 5856 // frame (which is the stack frame of the caller) and pass the address of 5857 // this copy to the callee. 5858 assert((j < ByValArgLocs.size()) && "Index out of bounds!"); 5859 CCValAssign &ByValVA = ByValArgLocs[j++]; 5860 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); 5861 5862 // Memory reserved in the local variable space of the callers stack frame. 5863 unsigned LocMemOffset = ByValVA.getLocMemOffset(); 5864 5865 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5866 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5867 StackPtr, PtrOff); 5868 5869 // Create a copy of the argument in the local area of the current 5870 // stack frame. 5871 SDValue MemcpyCall = 5872 CreateCopyOfByValArgument(Arg, PtrOff, 5873 CallSeqStart.getNode()->getOperand(0), 5874 Flags, DAG, dl); 5875 5876 // This must go outside the CALLSEQ_START..END. 5877 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0, 5878 SDLoc(MemcpyCall)); 5879 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5880 NewCallSeqStart.getNode()); 5881 Chain = CallSeqStart = NewCallSeqStart; 5882 5883 // Pass the address of the aggregate copy on the stack either in a 5884 // physical register or in the parameter list area of the current stack 5885 // frame to the callee. 5886 Arg = PtrOff; 5887 } 5888 5889 // When useCRBits() is true, there can be i1 arguments. 5890 // It is because getRegisterType(MVT::i1) => MVT::i1, 5891 // and for other integer types getRegisterType() => MVT::i32. 5892 // Extend i1 and ensure callee will get i32. 5893 if (Arg.getValueType() == MVT::i1) 5894 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 5895 dl, MVT::i32, Arg); 5896 5897 if (VA.isRegLoc()) { 5898 seenFloatArg |= VA.getLocVT().isFloatingPoint(); 5899 // Put argument in a physical register. 5900 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) { 5901 bool IsLE = Subtarget.isLittleEndian(); 5902 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5903 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl)); 5904 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0))); 5905 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 5906 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl)); 5907 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(), 5908 SVal.getValue(0))); 5909 } else 5910 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 5911 } else { 5912 // Put argument in the parameter list area of the current stack frame. 5913 assert(VA.isMemLoc()); 5914 unsigned LocMemOffset = VA.getLocMemOffset(); 5915 5916 if (!IsTailCall) { 5917 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); 5918 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), 5919 StackPtr, PtrOff); 5920 5921 MemOpChains.push_back( 5922 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 5923 } else { 5924 // Calculate and remember argument location. 5925 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, 5926 TailCallArguments); 5927 } 5928 } 5929 } 5930 5931 if (!MemOpChains.empty()) 5932 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 5933 5934 // Build a sequence of copy-to-reg nodes chained together with token chain 5935 // and flag operands which copy the outgoing args into the appropriate regs. 5936 SDValue InFlag; 5937 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 5938 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 5939 RegsToPass[i].second, InFlag); 5940 InFlag = Chain.getValue(1); 5941 } 5942 5943 // Set CR bit 6 to true if this is a vararg call with floating args passed in 5944 // registers. 5945 if (IsVarArg) { 5946 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); 5947 SDValue Ops[] = { Chain, InFlag }; 5948 5949 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl, 5950 VTs, ArrayRef(Ops, InFlag.getNode() ? 2 : 1)); 5951 5952 InFlag = Chain.getValue(1); 5953 } 5954 5955 if (IsTailCall) 5956 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 5957 TailCallArguments); 5958 5959 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 5960 Callee, SPDiff, NumBytes, Ins, InVals, CB); 5961 } 5962 5963 // Copy an argument into memory, being careful to do this outside the 5964 // call sequence for the call to which the argument belongs. 5965 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq( 5966 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, 5967 SelectionDAG &DAG, const SDLoc &dl) const { 5968 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, 5969 CallSeqStart.getNode()->getOperand(0), 5970 Flags, DAG, dl); 5971 // The MEMCPY must go outside the CALLSEQ_START..END. 5972 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1); 5973 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0, 5974 SDLoc(MemcpyCall)); 5975 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), 5976 NewCallSeqStart.getNode()); 5977 return NewCallSeqStart; 5978 } 5979 5980 SDValue PPCTargetLowering::LowerCall_64SVR4( 5981 SDValue Chain, SDValue Callee, CallFlags CFlags, 5982 const SmallVectorImpl<ISD::OutputArg> &Outs, 5983 const SmallVectorImpl<SDValue> &OutVals, 5984 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 5985 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 5986 const CallBase *CB) const { 5987 bool isELFv2ABI = Subtarget.isELFv2ABI(); 5988 bool isLittleEndian = Subtarget.isLittleEndian(); 5989 unsigned NumOps = Outs.size(); 5990 bool IsSibCall = false; 5991 bool IsFastCall = CFlags.CallConv == CallingConv::Fast; 5992 5993 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5994 unsigned PtrByteSize = 8; 5995 5996 MachineFunction &MF = DAG.getMachineFunction(); 5997 5998 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt) 5999 IsSibCall = true; 6000 6001 // Mark this function as potentially containing a function that contains a 6002 // tail call. As a consequence the frame pointer will be used for dynamicalloc 6003 // and restoring the callers stack pointer in this functions epilog. This is 6004 // done because by tail calling the called function might overwrite the value 6005 // in this function's (MF) stack pointer stack slot 0(SP). 6006 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6007 MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); 6008 6009 assert(!(IsFastCall && CFlags.IsVarArg) && 6010 "fastcc not supported on varargs functions"); 6011 6012 // Count how many bytes are to be pushed on the stack, including the linkage 6013 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes 6014 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage 6015 // area is 32 bytes reserved space for [SP][CR][LR][TOC]. 6016 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6017 unsigned NumBytes = LinkageSize; 6018 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; 6019 6020 static const MCPhysReg GPR[] = { 6021 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6022 PPC::X7, PPC::X8, PPC::X9, PPC::X10, 6023 }; 6024 static const MCPhysReg VR[] = { 6025 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, 6026 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 6027 }; 6028 6029 const unsigned NumGPRs = std::size(GPR); 6030 const unsigned NumFPRs = useSoftFloat() ? 0 : 13; 6031 const unsigned NumVRs = std::size(VR); 6032 6033 // On ELFv2, we can avoid allocating the parameter area if all the arguments 6034 // can be passed to the callee in registers. 6035 // For the fast calling convention, there is another check below. 6036 // Note: We should keep consistent with LowerFormalArguments_64SVR4() 6037 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall; 6038 if (!HasParameterArea) { 6039 unsigned ParamAreaSize = NumGPRs * PtrByteSize; 6040 unsigned AvailableFPRs = NumFPRs; 6041 unsigned AvailableVRs = NumVRs; 6042 unsigned NumBytesTmp = NumBytes; 6043 for (unsigned i = 0; i != NumOps; ++i) { 6044 if (Outs[i].Flags.isNest()) continue; 6045 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags, 6046 PtrByteSize, LinkageSize, ParamAreaSize, 6047 NumBytesTmp, AvailableFPRs, AvailableVRs)) 6048 HasParameterArea = true; 6049 } 6050 } 6051 6052 // When using the fast calling convention, we don't provide backing for 6053 // arguments that will be in registers. 6054 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; 6055 6056 // Avoid allocating parameter area for fastcc functions if all the arguments 6057 // can be passed in the registers. 6058 if (IsFastCall) 6059 HasParameterArea = false; 6060 6061 // Add up all the space actually used. 6062 for (unsigned i = 0; i != NumOps; ++i) { 6063 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6064 EVT ArgVT = Outs[i].VT; 6065 EVT OrigVT = Outs[i].ArgVT; 6066 6067 if (Flags.isNest()) 6068 continue; 6069 6070 if (IsFastCall) { 6071 if (Flags.isByVal()) { 6072 NumGPRsUsed += (Flags.getByValSize()+7)/8; 6073 if (NumGPRsUsed > NumGPRs) 6074 HasParameterArea = true; 6075 } else { 6076 switch (ArgVT.getSimpleVT().SimpleTy) { 6077 default: llvm_unreachable("Unexpected ValueType for argument!"); 6078 case MVT::i1: 6079 case MVT::i32: 6080 case MVT::i64: 6081 if (++NumGPRsUsed <= NumGPRs) 6082 continue; 6083 break; 6084 case MVT::v4i32: 6085 case MVT::v8i16: 6086 case MVT::v16i8: 6087 case MVT::v2f64: 6088 case MVT::v2i64: 6089 case MVT::v1i128: 6090 case MVT::f128: 6091 if (++NumVRsUsed <= NumVRs) 6092 continue; 6093 break; 6094 case MVT::v4f32: 6095 if (++NumVRsUsed <= NumVRs) 6096 continue; 6097 break; 6098 case MVT::f32: 6099 case MVT::f64: 6100 if (++NumFPRsUsed <= NumFPRs) 6101 continue; 6102 break; 6103 } 6104 HasParameterArea = true; 6105 } 6106 } 6107 6108 /* Respect alignment of argument on the stack. */ 6109 auto Alignement = 6110 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6111 NumBytes = alignTo(NumBytes, Alignement); 6112 6113 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); 6114 if (Flags.isInConsecutiveRegsLast()) 6115 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6116 } 6117 6118 unsigned NumBytesActuallyUsed = NumBytes; 6119 6120 // In the old ELFv1 ABI, 6121 // the prolog code of the callee may store up to 8 GPR argument registers to 6122 // the stack, allowing va_start to index over them in memory if its varargs. 6123 // Because we cannot tell if this is needed on the caller side, we have to 6124 // conservatively assume that it is needed. As such, make sure we have at 6125 // least enough stack space for the caller to store the 8 GPRs. 6126 // In the ELFv2 ABI, we allocate the parameter area iff a callee 6127 // really requires memory operands, e.g. a vararg function. 6128 if (HasParameterArea) 6129 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); 6130 else 6131 NumBytes = LinkageSize; 6132 6133 // Tail call needs the stack to be aligned. 6134 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall) 6135 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); 6136 6137 int SPDiff = 0; 6138 6139 // Calculate by how many bytes the stack has to be adjusted in case of tail 6140 // call optimization. 6141 if (!IsSibCall) 6142 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes); 6143 6144 // To protect arguments on the stack from being clobbered in a tail call, 6145 // force all the loads to happen before doing any other lowering. 6146 if (CFlags.IsTailCall) 6147 Chain = DAG.getStackArgumentTokenFactor(Chain); 6148 6149 // Adjust the stack pointer for the new arguments... 6150 // These operations are automatically eliminated by the prolog/epilog pass 6151 if (!IsSibCall) 6152 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 6153 SDValue CallSeqStart = Chain; 6154 6155 // Load the return address and frame pointer so it can be move somewhere else 6156 // later. 6157 SDValue LROp, FPOp; 6158 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl); 6159 6160 // Set up a copy of the stack pointer for use loading and storing any 6161 // arguments that may not fit in the registers available for argument 6162 // passing. 6163 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); 6164 6165 // Figure out which arguments are going to go in registers, and which in 6166 // memory. Also, if this is a vararg function, floating point operations 6167 // must be stored to our stack, and loaded into integer regs as well, if 6168 // any integer regs are available for argument passing. 6169 unsigned ArgOffset = LinkageSize; 6170 6171 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 6172 SmallVector<TailCallArgumentInfo, 8> TailCallArguments; 6173 6174 SmallVector<SDValue, 8> MemOpChains; 6175 for (unsigned i = 0; i != NumOps; ++i) { 6176 SDValue Arg = OutVals[i]; 6177 ISD::ArgFlagsTy Flags = Outs[i].Flags; 6178 EVT ArgVT = Outs[i].VT; 6179 EVT OrigVT = Outs[i].ArgVT; 6180 6181 // PtrOff will be used to store the current argument to the stack if a 6182 // register cannot be found for it. 6183 SDValue PtrOff; 6184 6185 // We re-align the argument offset for each argument, except when using the 6186 // fast calling convention, when we need to make sure we do that only when 6187 // we'll actually use a stack slot. 6188 auto ComputePtrOff = [&]() { 6189 /* Respect alignment of argument on the stack. */ 6190 auto Alignment = 6191 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); 6192 ArgOffset = alignTo(ArgOffset, Alignment); 6193 6194 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); 6195 6196 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6197 }; 6198 6199 if (!IsFastCall) { 6200 ComputePtrOff(); 6201 6202 /* Compute GPR index associated with argument offset. */ 6203 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; 6204 GPR_idx = std::min(GPR_idx, NumGPRs); 6205 } 6206 6207 // Promote integers to 64-bit values. 6208 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { 6209 // FIXME: Should this use ANY_EXTEND if neither sext nor zext? 6210 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6211 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); 6212 } 6213 6214 // FIXME memcpy is used way more than necessary. Correctness first. 6215 // Note: "by value" is code for passing a structure by value, not 6216 // basic types. 6217 if (Flags.isByVal()) { 6218 // Note: Size includes alignment padding, so 6219 // struct x { short a; char b; } 6220 // will have Size = 4. With #pragma pack(1), it will have Size = 3. 6221 // These are the proper values we need for right-justifying the 6222 // aggregate in a parameter register. 6223 unsigned Size = Flags.getByValSize(); 6224 6225 // An empty aggregate parameter takes up no storage and no 6226 // registers. 6227 if (Size == 0) 6228 continue; 6229 6230 if (IsFastCall) 6231 ComputePtrOff(); 6232 6233 // All aggregates smaller than 8 bytes must be passed right-justified. 6234 if (Size==1 || Size==2 || Size==4) { 6235 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); 6236 if (GPR_idx != NumGPRs) { 6237 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, 6238 MachinePointerInfo(), VT); 6239 MemOpChains.push_back(Load.getValue(1)); 6240 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6241 6242 ArgOffset += PtrByteSize; 6243 continue; 6244 } 6245 } 6246 6247 if (GPR_idx == NumGPRs && Size < 8) { 6248 SDValue AddPtr = PtrOff; 6249 if (!isLittleEndian) { 6250 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, 6251 PtrOff.getValueType()); 6252 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6253 } 6254 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6255 CallSeqStart, 6256 Flags, DAG, dl); 6257 ArgOffset += PtrByteSize; 6258 continue; 6259 } 6260 // Copy the object to parameter save area if it can not be entirely passed 6261 // by registers. 6262 // FIXME: we only need to copy the parts which need to be passed in 6263 // parameter save area. For the parts passed by registers, we don't need 6264 // to copy them to the stack although we need to allocate space for them 6265 // in parameter save area. 6266 if ((NumGPRs - GPR_idx) * PtrByteSize < Size) 6267 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, 6268 CallSeqStart, 6269 Flags, DAG, dl); 6270 6271 // When a register is available, pass a small aggregate right-justified. 6272 if (Size < 8 && GPR_idx != NumGPRs) { 6273 // The easiest way to get this right-justified in a register 6274 // is to copy the structure into the rightmost portion of a 6275 // local variable slot, then load the whole slot into the 6276 // register. 6277 // FIXME: The memcpy seems to produce pretty awful code for 6278 // small aggregates, particularly for packed ones. 6279 // FIXME: It would be preferable to use the slot in the 6280 // parameter save area instead of a new local variable. 6281 SDValue AddPtr = PtrOff; 6282 if (!isLittleEndian) { 6283 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); 6284 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); 6285 } 6286 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, 6287 CallSeqStart, 6288 Flags, DAG, dl); 6289 6290 // Load the slot into the register. 6291 SDValue Load = 6292 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo()); 6293 MemOpChains.push_back(Load.getValue(1)); 6294 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6295 6296 // Done with this argument. 6297 ArgOffset += PtrByteSize; 6298 continue; 6299 } 6300 6301 // For aggregates larger than PtrByteSize, copy the pieces of the 6302 // object that fit into registers from the parameter save area. 6303 for (unsigned j=0; j<Size; j+=PtrByteSize) { 6304 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); 6305 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); 6306 if (GPR_idx != NumGPRs) { 6307 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8; 6308 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits); 6309 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg, 6310 MachinePointerInfo(), ObjType); 6311 6312 MemOpChains.push_back(Load.getValue(1)); 6313 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6314 ArgOffset += PtrByteSize; 6315 } else { 6316 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; 6317 break; 6318 } 6319 } 6320 continue; 6321 } 6322 6323 switch (Arg.getSimpleValueType().SimpleTy) { 6324 default: llvm_unreachable("Unexpected ValueType for argument!"); 6325 case MVT::i1: 6326 case MVT::i32: 6327 case MVT::i64: 6328 if (Flags.isNest()) { 6329 // The 'nest' parameter, if any, is passed in R11. 6330 RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); 6331 break; 6332 } 6333 6334 // These can be scalar arguments or elements of an integer array type 6335 // passed directly. Clang may use those instead of "byval" aggregate 6336 // types to avoid forcing arguments to memory unnecessarily. 6337 if (GPR_idx != NumGPRs) { 6338 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); 6339 } else { 6340 if (IsFastCall) 6341 ComputePtrOff(); 6342 6343 assert(HasParameterArea && 6344 "Parameter area must exist to pass an argument in memory."); 6345 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6346 true, CFlags.IsTailCall, false, MemOpChains, 6347 TailCallArguments, dl); 6348 if (IsFastCall) 6349 ArgOffset += PtrByteSize; 6350 } 6351 if (!IsFastCall) 6352 ArgOffset += PtrByteSize; 6353 break; 6354 case MVT::f32: 6355 case MVT::f64: { 6356 // These can be scalar arguments or elements of a float array type 6357 // passed directly. The latter are used to implement ELFv2 homogenous 6358 // float aggregates. 6359 6360 // Named arguments go into FPRs first, and once they overflow, the 6361 // remaining arguments go into GPRs and then the parameter save area. 6362 // Unnamed arguments for vararg functions always go to GPRs and 6363 // then the parameter save area. For now, put all arguments to vararg 6364 // routines always in both locations (FPR *and* GPR or stack slot). 6365 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs; 6366 bool NeededLoad = false; 6367 6368 // First load the argument into the next available FPR. 6369 if (FPR_idx != NumFPRs) 6370 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); 6371 6372 // Next, load the argument into GPR or stack slot if needed. 6373 if (!NeedGPROrStack) 6374 ; 6375 else if (GPR_idx != NumGPRs && !IsFastCall) { 6376 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 6377 // once we support fp <-> gpr moves. 6378 6379 // In the non-vararg case, this can only ever happen in the 6380 // presence of f32 array types, since otherwise we never run 6381 // out of FPRs before running out of GPRs. 6382 SDValue ArgVal; 6383 6384 // Double values are always passed in a single GPR. 6385 if (Arg.getValueType() != MVT::f32) { 6386 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); 6387 6388 // Non-array float values are extended and passed in a GPR. 6389 } else if (!Flags.isInConsecutiveRegs()) { 6390 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6391 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6392 6393 // If we have an array of floats, we collect every odd element 6394 // together with its predecessor into one GPR. 6395 } else if (ArgOffset % PtrByteSize != 0) { 6396 SDValue Lo, Hi; 6397 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); 6398 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6399 if (!isLittleEndian) 6400 std::swap(Lo, Hi); 6401 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 6402 6403 // The final element, if even, goes into the first half of a GPR. 6404 } else if (Flags.isInConsecutiveRegsLast()) { 6405 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); 6406 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); 6407 if (!isLittleEndian) 6408 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, 6409 DAG.getConstant(32, dl, MVT::i32)); 6410 6411 // Non-final even elements are skipped; they will be handled 6412 // together the with subsequent argument on the next go-around. 6413 } else 6414 ArgVal = SDValue(); 6415 6416 if (ArgVal.getNode()) 6417 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); 6418 } else { 6419 if (IsFastCall) 6420 ComputePtrOff(); 6421 6422 // Single-precision floating-point values are mapped to the 6423 // second (rightmost) word of the stack doubleword. 6424 if (Arg.getValueType() == MVT::f32 && 6425 !isLittleEndian && !Flags.isInConsecutiveRegs()) { 6426 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); 6427 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); 6428 } 6429 6430 assert(HasParameterArea && 6431 "Parameter area must exist to pass an argument in memory."); 6432 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6433 true, CFlags.IsTailCall, false, MemOpChains, 6434 TailCallArguments, dl); 6435 6436 NeededLoad = true; 6437 } 6438 // When passing an array of floats, the array occupies consecutive 6439 // space in the argument area; only round up to the next doubleword 6440 // at the end of the array. Otherwise, each float takes 8 bytes. 6441 if (!IsFastCall || NeededLoad) { 6442 ArgOffset += (Arg.getValueType() == MVT::f32 && 6443 Flags.isInConsecutiveRegs()) ? 4 : 8; 6444 if (Flags.isInConsecutiveRegsLast()) 6445 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; 6446 } 6447 break; 6448 } 6449 case MVT::v4f32: 6450 case MVT::v4i32: 6451 case MVT::v8i16: 6452 case MVT::v16i8: 6453 case MVT::v2f64: 6454 case MVT::v2i64: 6455 case MVT::v1i128: 6456 case MVT::f128: 6457 // These can be scalar arguments or elements of a vector array type 6458 // passed directly. The latter are used to implement ELFv2 homogenous 6459 // vector aggregates. 6460 6461 // For a varargs call, named arguments go into VRs or on the stack as 6462 // usual; unnamed arguments always go to the stack or the corresponding 6463 // GPRs when within range. For now, we always put the value in both 6464 // locations (or even all three). 6465 if (CFlags.IsVarArg) { 6466 assert(HasParameterArea && 6467 "Parameter area must exist if we have a varargs call."); 6468 // We could elide this store in the case where the object fits 6469 // entirely in R registers. Maybe later. 6470 SDValue Store = 6471 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 6472 MemOpChains.push_back(Store); 6473 if (VR_idx != NumVRs) { 6474 SDValue Load = 6475 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo()); 6476 MemOpChains.push_back(Load.getValue(1)); 6477 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); 6478 } 6479 ArgOffset += 16; 6480 for (unsigned i=0; i<16; i+=PtrByteSize) { 6481 if (GPR_idx == NumGPRs) 6482 break; 6483 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 6484 DAG.getConstant(i, dl, PtrVT)); 6485 SDValue Load = 6486 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo()); 6487 MemOpChains.push_back(Load.getValue(1)); 6488 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); 6489 } 6490 break; 6491 } 6492 6493 // Non-varargs Altivec params go into VRs or on the stack. 6494 if (VR_idx != NumVRs) { 6495 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); 6496 } else { 6497 if (IsFastCall) 6498 ComputePtrOff(); 6499 6500 assert(HasParameterArea && 6501 "Parameter area must exist to pass an argument in memory."); 6502 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, 6503 true, CFlags.IsTailCall, true, MemOpChains, 6504 TailCallArguments, dl); 6505 if (IsFastCall) 6506 ArgOffset += 16; 6507 } 6508 6509 if (!IsFastCall) 6510 ArgOffset += 16; 6511 break; 6512 } 6513 } 6514 6515 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) && 6516 "mismatch in size of parameter area"); 6517 (void)NumBytesActuallyUsed; 6518 6519 if (!MemOpChains.empty()) 6520 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 6521 6522 // Check if this is an indirect call (MTCTR/BCTRL). 6523 // See prepareDescriptorIndirectCall and buildCallOperands for more 6524 // information about calls through function pointers in the 64-bit SVR4 ABI. 6525 if (CFlags.IsIndirect) { 6526 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the 6527 // caller in the TOC save area. 6528 if (isTOCSaveRestoreRequired(Subtarget)) { 6529 assert(!CFlags.IsTailCall && "Indirect tails calls not supported"); 6530 // Load r2 into a virtual register and store it to the TOC save area. 6531 setUsesTOCBasePtr(DAG); 6532 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); 6533 // TOC save area offset. 6534 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 6535 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 6536 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 6537 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, 6538 MachinePointerInfo::getStack( 6539 DAG.getMachineFunction(), TOCSaveOffset)); 6540 } 6541 // In the ELFv2 ABI, R12 must contain the address of an indirect callee. 6542 // This does not mean the MTCTR instruction must use R12; it's easier 6543 // to model this as an extra parameter, so do that. 6544 if (isELFv2ABI && !CFlags.IsPatchPoint) 6545 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); 6546 } 6547 6548 // Build a sequence of copy-to-reg nodes chained together with token chain 6549 // and flag operands which copy the outgoing args into the appropriate regs. 6550 SDValue InFlag; 6551 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 6552 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 6553 RegsToPass[i].second, InFlag); 6554 InFlag = Chain.getValue(1); 6555 } 6556 6557 if (CFlags.IsTailCall && !IsSibCall) 6558 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp, 6559 TailCallArguments); 6560 6561 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 6562 Callee, SPDiff, NumBytes, Ins, InVals, CB); 6563 } 6564 6565 // Returns true when the shadow of a general purpose argument register 6566 // in the parameter save area is aligned to at least 'RequiredAlign'. 6567 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) { 6568 assert(RequiredAlign.value() <= 16 && 6569 "Required alignment greater than stack alignment."); 6570 switch (Reg) { 6571 default: 6572 report_fatal_error("called on invalid register."); 6573 case PPC::R5: 6574 case PPC::R9: 6575 case PPC::X3: 6576 case PPC::X5: 6577 case PPC::X7: 6578 case PPC::X9: 6579 // These registers are 16 byte aligned which is the most strict aligment 6580 // we can support. 6581 return true; 6582 case PPC::R3: 6583 case PPC::R7: 6584 case PPC::X4: 6585 case PPC::X6: 6586 case PPC::X8: 6587 case PPC::X10: 6588 // The shadow of these registers in the PSA is 8 byte aligned. 6589 return RequiredAlign <= 8; 6590 case PPC::R4: 6591 case PPC::R6: 6592 case PPC::R8: 6593 case PPC::R10: 6594 return RequiredAlign <= 4; 6595 } 6596 } 6597 6598 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, 6599 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, 6600 CCState &S) { 6601 AIXCCState &State = static_cast<AIXCCState &>(S); 6602 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>( 6603 State.getMachineFunction().getSubtarget()); 6604 const bool IsPPC64 = Subtarget.isPPC64(); 6605 const Align PtrAlign = IsPPC64 ? Align(8) : Align(4); 6606 const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32; 6607 6608 if (ValVT == MVT::f128) 6609 report_fatal_error("f128 is unimplemented on AIX."); 6610 6611 if (ArgFlags.isNest()) 6612 report_fatal_error("Nest arguments are unimplemented."); 6613 6614 static const MCPhysReg GPR_32[] = {// 32-bit registers. 6615 PPC::R3, PPC::R4, PPC::R5, PPC::R6, 6616 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 6617 static const MCPhysReg GPR_64[] = {// 64-bit registers. 6618 PPC::X3, PPC::X4, PPC::X5, PPC::X6, 6619 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 6620 6621 static const MCPhysReg VR[] = {// Vector registers. 6622 PPC::V2, PPC::V3, PPC::V4, PPC::V5, 6623 PPC::V6, PPC::V7, PPC::V8, PPC::V9, 6624 PPC::V10, PPC::V11, PPC::V12, PPC::V13}; 6625 6626 if (ArgFlags.isByVal()) { 6627 if (ArgFlags.getNonZeroByValAlign() > PtrAlign) 6628 report_fatal_error("Pass-by-value arguments with alignment greater than " 6629 "register width are not supported."); 6630 6631 const unsigned ByValSize = ArgFlags.getByValSize(); 6632 6633 // An empty aggregate parameter takes up no storage and no registers, 6634 // but needs a MemLoc for a stack slot for the formal arguments side. 6635 if (ByValSize == 0) { 6636 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6637 State.getNextStackOffset(), RegVT, 6638 LocInfo)); 6639 return false; 6640 } 6641 6642 const unsigned StackSize = alignTo(ByValSize, PtrAlign); 6643 unsigned Offset = State.AllocateStack(StackSize, PtrAlign); 6644 for (const unsigned E = Offset + StackSize; Offset < E; 6645 Offset += PtrAlign.value()) { 6646 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6647 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6648 else { 6649 State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE, 6650 Offset, MVT::INVALID_SIMPLE_VALUE_TYPE, 6651 LocInfo)); 6652 break; 6653 } 6654 } 6655 return false; 6656 } 6657 6658 // Arguments always reserve parameter save area. 6659 switch (ValVT.SimpleTy) { 6660 default: 6661 report_fatal_error("Unhandled value type for argument."); 6662 case MVT::i64: 6663 // i64 arguments should have been split to i32 for PPC32. 6664 assert(IsPPC64 && "PPC32 should have split i64 values."); 6665 [[fallthrough]]; 6666 case MVT::i1: 6667 case MVT::i32: { 6668 const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign); 6669 // AIX integer arguments are always passed in register width. 6670 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits()) 6671 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt 6672 : CCValAssign::LocInfo::ZExt; 6673 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) 6674 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6675 else 6676 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo)); 6677 6678 return false; 6679 } 6680 case MVT::f32: 6681 case MVT::f64: { 6682 // Parameter save area (PSA) is reserved even if the float passes in fpr. 6683 const unsigned StoreSize = LocVT.getStoreSize(); 6684 // Floats are always 4-byte aligned in the PSA on AIX. 6685 // This includes f64 in 64-bit mode for ABI compatibility. 6686 const unsigned Offset = 6687 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4)); 6688 unsigned FReg = State.AllocateReg(FPR); 6689 if (FReg) 6690 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo)); 6691 6692 // Reserve and initialize GPRs or initialize the PSA as required. 6693 for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) { 6694 if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) { 6695 assert(FReg && "An FPR should be available when a GPR is reserved."); 6696 if (State.isVarArg()) { 6697 // Successfully reserved GPRs are only initialized for vararg calls. 6698 // Custom handling is required for: 6699 // f64 in PPC32 needs to be split into 2 GPRs. 6700 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR. 6701 State.addLoc( 6702 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6703 } 6704 } else { 6705 // If there are insufficient GPRs, the PSA needs to be initialized. 6706 // Initialization occurs even if an FPR was initialized for 6707 // compatibility with the AIX XL compiler. The full memory for the 6708 // argument will be initialized even if a prior word is saved in GPR. 6709 // A custom memLoc is used when the argument also passes in FPR so 6710 // that the callee handling can skip over it easily. 6711 State.addLoc( 6712 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, 6713 LocInfo) 6714 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6715 break; 6716 } 6717 } 6718 6719 return false; 6720 } 6721 case MVT::v4f32: 6722 case MVT::v4i32: 6723 case MVT::v8i16: 6724 case MVT::v16i8: 6725 case MVT::v2i64: 6726 case MVT::v2f64: 6727 case MVT::v1i128: { 6728 const unsigned VecSize = 16; 6729 const Align VecAlign(VecSize); 6730 6731 if (!State.isVarArg()) { 6732 // If there are vector registers remaining we don't consume any stack 6733 // space. 6734 if (unsigned VReg = State.AllocateReg(VR)) { 6735 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6736 return false; 6737 } 6738 // Vectors passed on the stack do not shadow GPRs or FPRs even though they 6739 // might be allocated in the portion of the PSA that is shadowed by the 6740 // GPRs. 6741 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6742 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6743 return false; 6744 } 6745 6746 const unsigned PtrSize = IsPPC64 ? 8 : 4; 6747 ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32; 6748 6749 unsigned NextRegIndex = State.getFirstUnallocated(GPRs); 6750 // Burn any underaligned registers and their shadowed stack space until 6751 // we reach the required alignment. 6752 while (NextRegIndex != GPRs.size() && 6753 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) { 6754 // Shadow allocate register and its stack shadow. 6755 unsigned Reg = State.AllocateReg(GPRs); 6756 State.AllocateStack(PtrSize, PtrAlign); 6757 assert(Reg && "Allocating register unexpectedly failed."); 6758 (void)Reg; 6759 NextRegIndex = State.getFirstUnallocated(GPRs); 6760 } 6761 6762 // Vectors that are passed as fixed arguments are handled differently. 6763 // They are passed in VRs if any are available (unlike arguments passed 6764 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg 6765 // functions) 6766 if (State.isFixed(ValNo)) { 6767 if (unsigned VReg = State.AllocateReg(VR)) { 6768 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo)); 6769 // Shadow allocate GPRs and stack space even though we pass in a VR. 6770 for (unsigned I = 0; I != VecSize; I += PtrSize) 6771 State.AllocateReg(GPRs); 6772 State.AllocateStack(VecSize, VecAlign); 6773 return false; 6774 } 6775 // No vector registers remain so pass on the stack. 6776 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6777 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6778 return false; 6779 } 6780 6781 // If all GPRS are consumed then we pass the argument fully on the stack. 6782 if (NextRegIndex == GPRs.size()) { 6783 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6784 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6785 return false; 6786 } 6787 6788 // Corner case for 32-bit codegen. We have 2 registers to pass the first 6789 // half of the argument, and then need to pass the remaining half on the 6790 // stack. 6791 if (GPRs[NextRegIndex] == PPC::R9) { 6792 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6793 State.addLoc( 6794 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6795 6796 const unsigned FirstReg = State.AllocateReg(PPC::R9); 6797 const unsigned SecondReg = State.AllocateReg(PPC::R10); 6798 assert(FirstReg && SecondReg && 6799 "Allocating R9 or R10 unexpectedly failed."); 6800 State.addLoc( 6801 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo)); 6802 State.addLoc( 6803 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo)); 6804 return false; 6805 } 6806 6807 // We have enough GPRs to fully pass the vector argument, and we have 6808 // already consumed any underaligned registers. Start with the custom 6809 // MemLoc and then the custom RegLocs. 6810 const unsigned Offset = State.AllocateStack(VecSize, VecAlign); 6811 State.addLoc( 6812 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo)); 6813 for (unsigned I = 0; I != VecSize; I += PtrSize) { 6814 const unsigned Reg = State.AllocateReg(GPRs); 6815 assert(Reg && "Failed to allocated register for vararg vector argument"); 6816 State.addLoc( 6817 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo)); 6818 } 6819 return false; 6820 } 6821 } 6822 return true; 6823 } 6824 6825 // So far, this function is only used by LowerFormalArguments_AIX() 6826 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT, 6827 bool IsPPC64, 6828 bool HasP8Vector, 6829 bool HasVSX) { 6830 assert((IsPPC64 || SVT != MVT::i64) && 6831 "i64 should have been split for 32-bit codegen."); 6832 6833 switch (SVT) { 6834 default: 6835 report_fatal_error("Unexpected value type for formal argument"); 6836 case MVT::i1: 6837 case MVT::i32: 6838 case MVT::i64: 6839 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 6840 case MVT::f32: 6841 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass; 6842 case MVT::f64: 6843 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass; 6844 case MVT::v4f32: 6845 case MVT::v4i32: 6846 case MVT::v8i16: 6847 case MVT::v16i8: 6848 case MVT::v2i64: 6849 case MVT::v2f64: 6850 case MVT::v1i128: 6851 return &PPC::VRRCRegClass; 6852 } 6853 } 6854 6855 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, 6856 SelectionDAG &DAG, SDValue ArgValue, 6857 MVT LocVT, const SDLoc &dl) { 6858 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger()); 6859 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits()); 6860 6861 if (Flags.isSExt()) 6862 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue, 6863 DAG.getValueType(ValVT)); 6864 else if (Flags.isZExt()) 6865 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue, 6866 DAG.getValueType(ValVT)); 6867 6868 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue); 6869 } 6870 6871 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) { 6872 const unsigned LASize = FL->getLinkageSize(); 6873 6874 if (PPC::GPRCRegClass.contains(Reg)) { 6875 assert(Reg >= PPC::R3 && Reg <= PPC::R10 && 6876 "Reg must be a valid argument register!"); 6877 return LASize + 4 * (Reg - PPC::R3); 6878 } 6879 6880 if (PPC::G8RCRegClass.contains(Reg)) { 6881 assert(Reg >= PPC::X3 && Reg <= PPC::X10 && 6882 "Reg must be a valid argument register!"); 6883 return LASize + 8 * (Reg - PPC::X3); 6884 } 6885 6886 llvm_unreachable("Only general purpose registers expected."); 6887 } 6888 6889 // AIX ABI Stack Frame Layout: 6890 // 6891 // Low Memory +--------------------------------------------+ 6892 // SP +---> | Back chain | ---+ 6893 // | +--------------------------------------------+ | 6894 // | | Saved Condition Register | | 6895 // | +--------------------------------------------+ | 6896 // | | Saved Linkage Register | | 6897 // | +--------------------------------------------+ | Linkage Area 6898 // | | Reserved for compilers | | 6899 // | +--------------------------------------------+ | 6900 // | | Reserved for binders | | 6901 // | +--------------------------------------------+ | 6902 // | | Saved TOC pointer | ---+ 6903 // | +--------------------------------------------+ 6904 // | | Parameter save area | 6905 // | +--------------------------------------------+ 6906 // | | Alloca space | 6907 // | +--------------------------------------------+ 6908 // | | Local variable space | 6909 // | +--------------------------------------------+ 6910 // | | Float/int conversion temporary | 6911 // | +--------------------------------------------+ 6912 // | | Save area for AltiVec registers | 6913 // | +--------------------------------------------+ 6914 // | | AltiVec alignment padding | 6915 // | +--------------------------------------------+ 6916 // | | Save area for VRSAVE register | 6917 // | +--------------------------------------------+ 6918 // | | Save area for General Purpose registers | 6919 // | +--------------------------------------------+ 6920 // | | Save area for Floating Point registers | 6921 // | +--------------------------------------------+ 6922 // +---- | Back chain | 6923 // High Memory +--------------------------------------------+ 6924 // 6925 // Specifications: 6926 // AIX 7.2 Assembler Language Reference 6927 // Subroutine linkage convention 6928 6929 SDValue PPCTargetLowering::LowerFormalArguments_AIX( 6930 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 6931 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 6932 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 6933 6934 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold || 6935 CallConv == CallingConv::Fast) && 6936 "Unexpected calling convention!"); 6937 6938 if (getTargetMachine().Options.GuaranteedTailCallOpt) 6939 report_fatal_error("Tail call support is unimplemented on AIX."); 6940 6941 if (useSoftFloat()) 6942 report_fatal_error("Soft float support is unimplemented on AIX."); 6943 6944 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 6945 6946 const bool IsPPC64 = Subtarget.isPPC64(); 6947 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 6948 6949 // Assign locations to all of the incoming arguments. 6950 SmallVector<CCValAssign, 16> ArgLocs; 6951 MachineFunction &MF = DAG.getMachineFunction(); 6952 MachineFrameInfo &MFI = MF.getFrameInfo(); 6953 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 6954 AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext()); 6955 6956 const EVT PtrVT = getPointerTy(MF.getDataLayout()); 6957 // Reserve space for the linkage area on the stack. 6958 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 6959 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 6960 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX); 6961 6962 SmallVector<SDValue, 8> MemOps; 6963 6964 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) { 6965 CCValAssign &VA = ArgLocs[I++]; 6966 MVT LocVT = VA.getLocVT(); 6967 MVT ValVT = VA.getValVT(); 6968 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags; 6969 // For compatibility with the AIX XL compiler, the float args in the 6970 // parameter save area are initialized even if the argument is available 6971 // in register. The caller is required to initialize both the register 6972 // and memory, however, the callee can choose to expect it in either. 6973 // The memloc is dismissed here because the argument is retrieved from 6974 // the register. 6975 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint()) 6976 continue; 6977 6978 auto HandleMemLoc = [&]() { 6979 const unsigned LocSize = LocVT.getStoreSize(); 6980 const unsigned ValSize = ValVT.getStoreSize(); 6981 assert((ValSize <= LocSize) && 6982 "Object size is larger than size of MemLoc"); 6983 int CurArgOffset = VA.getLocMemOffset(); 6984 // Objects are right-justified because AIX is big-endian. 6985 if (LocSize > ValSize) 6986 CurArgOffset += LocSize - ValSize; 6987 // Potential tail calls could cause overwriting of argument stack slots. 6988 const bool IsImmutable = 6989 !(getTargetMachine().Options.GuaranteedTailCallOpt && 6990 (CallConv == CallingConv::Fast)); 6991 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable); 6992 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 6993 SDValue ArgValue = 6994 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo()); 6995 InVals.push_back(ArgValue); 6996 }; 6997 6998 // Vector arguments to VaArg functions are passed both on the stack, and 6999 // in any available GPRs. Load the value from the stack and add the GPRs 7000 // as live ins. 7001 if (VA.isMemLoc() && VA.needsCustom()) { 7002 assert(ValVT.isVector() && "Unexpected Custom MemLoc type."); 7003 assert(isVarArg && "Only use custom memloc for vararg."); 7004 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the 7005 // matching custom RegLocs. 7006 const unsigned OriginalValNo = VA.getValNo(); 7007 (void)OriginalValNo; 7008 7009 auto HandleCustomVecRegLoc = [&]() { 7010 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7011 "Missing custom RegLoc."); 7012 VA = ArgLocs[I++]; 7013 assert(VA.getValVT().isVector() && 7014 "Unexpected Val type for custom RegLoc."); 7015 assert(VA.getValNo() == OriginalValNo && 7016 "ValNo mismatch between custom MemLoc and RegLoc."); 7017 MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy; 7018 MF.addLiveIn(VA.getLocReg(), 7019 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7020 Subtarget.hasVSX())); 7021 }; 7022 7023 HandleMemLoc(); 7024 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7025 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7026 // R10. 7027 HandleCustomVecRegLoc(); 7028 HandleCustomVecRegLoc(); 7029 7030 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if 7031 // we passed the vector in R5, R6, R7 and R8. 7032 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) { 7033 assert(!IsPPC64 && 7034 "Only 2 custom RegLocs expected for 64-bit codegen."); 7035 HandleCustomVecRegLoc(); 7036 HandleCustomVecRegLoc(); 7037 } 7038 7039 continue; 7040 } 7041 7042 if (VA.isRegLoc()) { 7043 if (VA.getValVT().isScalarInteger()) 7044 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7045 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) { 7046 switch (VA.getValVT().SimpleTy) { 7047 default: 7048 report_fatal_error("Unhandled value type for argument."); 7049 case MVT::f32: 7050 FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint); 7051 break; 7052 case MVT::f64: 7053 FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint); 7054 break; 7055 } 7056 } else if (VA.getValVT().isVector()) { 7057 switch (VA.getValVT().SimpleTy) { 7058 default: 7059 report_fatal_error("Unhandled value type for argument."); 7060 case MVT::v16i8: 7061 FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar); 7062 break; 7063 case MVT::v8i16: 7064 FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort); 7065 break; 7066 case MVT::v4i32: 7067 case MVT::v2i64: 7068 case MVT::v1i128: 7069 FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt); 7070 break; 7071 case MVT::v4f32: 7072 case MVT::v2f64: 7073 FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat); 7074 break; 7075 } 7076 } 7077 } 7078 7079 if (Flags.isByVal() && VA.isMemLoc()) { 7080 const unsigned Size = 7081 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize, 7082 PtrByteSize); 7083 const int FI = MF.getFrameInfo().CreateFixedObject( 7084 Size, VA.getLocMemOffset(), /* IsImmutable */ false, 7085 /* IsAliased */ true); 7086 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7087 InVals.push_back(FIN); 7088 7089 continue; 7090 } 7091 7092 if (Flags.isByVal()) { 7093 assert(VA.isRegLoc() && "MemLocs should already be handled."); 7094 7095 const MCPhysReg ArgReg = VA.getLocReg(); 7096 const PPCFrameLowering *FL = Subtarget.getFrameLowering(); 7097 7098 if (Flags.getNonZeroByValAlign() > PtrByteSize) 7099 report_fatal_error("Over aligned byvals not supported yet."); 7100 7101 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize); 7102 const int FI = MF.getFrameInfo().CreateFixedObject( 7103 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false, 7104 /* IsAliased */ true); 7105 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 7106 InVals.push_back(FIN); 7107 7108 // Add live ins for all the RegLocs for the same ByVal. 7109 const TargetRegisterClass *RegClass = 7110 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 7111 7112 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg, 7113 unsigned Offset) { 7114 const Register VReg = MF.addLiveIn(PhysReg, RegClass); 7115 // Since the callers side has left justified the aggregate in the 7116 // register, we can simply store the entire register into the stack 7117 // slot. 7118 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7119 // The store to the fixedstack object is needed becuase accessing a 7120 // field of the ByVal will use a gep and load. Ideally we will optimize 7121 // to extracting the value from the register directly, and elide the 7122 // stores when the arguments address is not taken, but that will need to 7123 // be future work. 7124 SDValue Store = DAG.getStore( 7125 CopyFrom.getValue(1), dl, CopyFrom, 7126 DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)), 7127 MachinePointerInfo::getFixedStack(MF, FI, Offset)); 7128 7129 MemOps.push_back(Store); 7130 }; 7131 7132 unsigned Offset = 0; 7133 HandleRegLoc(VA.getLocReg(), Offset); 7134 Offset += PtrByteSize; 7135 for (; Offset != StackSize && ArgLocs[I].isRegLoc(); 7136 Offset += PtrByteSize) { 7137 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7138 "RegLocs should be for ByVal argument."); 7139 7140 const CCValAssign RL = ArgLocs[I++]; 7141 HandleRegLoc(RL.getLocReg(), Offset); 7142 FuncInfo->appendParameterType(PPCFunctionInfo::FixedType); 7143 } 7144 7145 if (Offset != StackSize) { 7146 assert(ArgLocs[I].getValNo() == VA.getValNo() && 7147 "Expected MemLoc for remaining bytes."); 7148 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes."); 7149 // Consume the MemLoc.The InVal has already been emitted, so nothing 7150 // more needs to be done. 7151 ++I; 7152 } 7153 7154 continue; 7155 } 7156 7157 if (VA.isRegLoc() && !VA.needsCustom()) { 7158 MVT::SimpleValueType SVT = ValVT.SimpleTy; 7159 Register VReg = 7160 MF.addLiveIn(VA.getLocReg(), 7161 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(), 7162 Subtarget.hasVSX())); 7163 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT); 7164 if (ValVT.isScalarInteger() && 7165 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) { 7166 ArgValue = 7167 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl); 7168 } 7169 InVals.push_back(ArgValue); 7170 continue; 7171 } 7172 if (VA.isMemLoc()) { 7173 HandleMemLoc(); 7174 continue; 7175 } 7176 } 7177 7178 // On AIX a minimum of 8 words is saved to the parameter save area. 7179 const unsigned MinParameterSaveArea = 8 * PtrByteSize; 7180 // Area that is at least reserved in the caller of this function. 7181 unsigned CallerReservedArea = 7182 std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea); 7183 7184 // Set the size that is at least reserved in caller of this function. Tail 7185 // call optimized function's reserved stack space needs to be aligned so 7186 // that taking the difference between two stack areas will result in an 7187 // aligned stack. 7188 CallerReservedArea = 7189 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea); 7190 FuncInfo->setMinReservedArea(CallerReservedArea); 7191 7192 if (isVarArg) { 7193 FuncInfo->setVarArgsFrameIndex( 7194 MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true)); 7195 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); 7196 7197 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6, 7198 PPC::R7, PPC::R8, PPC::R9, PPC::R10}; 7199 7200 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6, 7201 PPC::X7, PPC::X8, PPC::X9, PPC::X10}; 7202 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32); 7203 7204 // The fixed integer arguments of a variadic function are stored to the 7205 // VarArgsFrameIndex on the stack so that they may be loaded by 7206 // dereferencing the result of va_next. 7207 for (unsigned GPRIndex = 7208 (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize; 7209 GPRIndex < NumGPArgRegs; ++GPRIndex) { 7210 7211 const Register VReg = 7212 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass) 7213 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass); 7214 7215 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); 7216 SDValue Store = 7217 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo()); 7218 MemOps.push_back(Store); 7219 // Increment the address for the next argument to store. 7220 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); 7221 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); 7222 } 7223 } 7224 7225 if (!MemOps.empty()) 7226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); 7227 7228 return Chain; 7229 } 7230 7231 SDValue PPCTargetLowering::LowerCall_AIX( 7232 SDValue Chain, SDValue Callee, CallFlags CFlags, 7233 const SmallVectorImpl<ISD::OutputArg> &Outs, 7234 const SmallVectorImpl<SDValue> &OutVals, 7235 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, 7236 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, 7237 const CallBase *CB) const { 7238 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the 7239 // AIX ABI stack frame layout. 7240 7241 assert((CFlags.CallConv == CallingConv::C || 7242 CFlags.CallConv == CallingConv::Cold || 7243 CFlags.CallConv == CallingConv::Fast) && 7244 "Unexpected calling convention!"); 7245 7246 if (CFlags.IsPatchPoint) 7247 report_fatal_error("This call type is unimplemented on AIX."); 7248 7249 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>(); 7250 7251 MachineFunction &MF = DAG.getMachineFunction(); 7252 SmallVector<CCValAssign, 16> ArgLocs; 7253 AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs, 7254 *DAG.getContext()); 7255 7256 // Reserve space for the linkage save area (LSA) on the stack. 7257 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA: 7258 // [SP][CR][LR][2 x reserved][TOC]. 7259 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64. 7260 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); 7261 const bool IsPPC64 = Subtarget.isPPC64(); 7262 const EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7263 const unsigned PtrByteSize = IsPPC64 ? 8 : 4; 7264 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize)); 7265 CCInfo.AnalyzeCallOperands(Outs, CC_AIX); 7266 7267 // The prolog code of the callee may store up to 8 GPR argument registers to 7268 // the stack, allowing va_start to index over them in memory if the callee 7269 // is variadic. 7270 // Because we cannot tell if this is needed on the caller side, we have to 7271 // conservatively assume that it is needed. As such, make sure we have at 7272 // least enough stack space for the caller to store the 8 GPRs. 7273 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize; 7274 const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize, 7275 CCInfo.getNextStackOffset()); 7276 7277 // Adjust the stack pointer for the new arguments... 7278 // These operations are automatically eliminated by the prolog/epilog pass. 7279 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl); 7280 SDValue CallSeqStart = Chain; 7281 7282 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 7283 SmallVector<SDValue, 8> MemOpChains; 7284 7285 // Set up a copy of the stack pointer for loading and storing any 7286 // arguments that may not fit in the registers available for argument 7287 // passing. 7288 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64) 7289 : DAG.getRegister(PPC::R1, MVT::i32); 7290 7291 for (unsigned I = 0, E = ArgLocs.size(); I != E;) { 7292 const unsigned ValNo = ArgLocs[I].getValNo(); 7293 SDValue Arg = OutVals[ValNo]; 7294 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags; 7295 7296 if (Flags.isByVal()) { 7297 const unsigned ByValSize = Flags.getByValSize(); 7298 7299 // Nothing to do for zero-sized ByVals on the caller side. 7300 if (!ByValSize) { 7301 ++I; 7302 continue; 7303 } 7304 7305 auto GetLoad = [&](EVT VT, unsigned LoadOffset) { 7306 return DAG.getExtLoad( 7307 ISD::ZEXTLOAD, dl, PtrVT, Chain, 7308 (LoadOffset != 0) 7309 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7310 : Arg, 7311 MachinePointerInfo(), VT); 7312 }; 7313 7314 unsigned LoadOffset = 0; 7315 7316 // Initialize registers, which are fully occupied by the by-val argument. 7317 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) { 7318 SDValue Load = GetLoad(PtrVT, LoadOffset); 7319 MemOpChains.push_back(Load.getValue(1)); 7320 LoadOffset += PtrByteSize; 7321 const CCValAssign &ByValVA = ArgLocs[I++]; 7322 assert(ByValVA.getValNo() == ValNo && 7323 "Unexpected location for pass-by-value argument."); 7324 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load)); 7325 } 7326 7327 if (LoadOffset == ByValSize) 7328 continue; 7329 7330 // There must be one more loc to handle the remainder. 7331 assert(ArgLocs[I].getValNo() == ValNo && 7332 "Expected additional location for by-value argument."); 7333 7334 if (ArgLocs[I].isMemLoc()) { 7335 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg."); 7336 const CCValAssign &ByValVA = ArgLocs[I++]; 7337 ISD::ArgFlagsTy MemcpyFlags = Flags; 7338 // Only memcpy the bytes that don't pass in register. 7339 MemcpyFlags.setByValSize(ByValSize - LoadOffset); 7340 Chain = CallSeqStart = createMemcpyOutsideCallSeq( 7341 (LoadOffset != 0) 7342 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset)) 7343 : Arg, 7344 DAG.getObjectPtrOffset(dl, StackPtr, 7345 TypeSize::Fixed(ByValVA.getLocMemOffset())), 7346 CallSeqStart, MemcpyFlags, DAG, dl); 7347 continue; 7348 } 7349 7350 // Initialize the final register residue. 7351 // Any residue that occupies the final by-val arg register must be 7352 // left-justified on AIX. Loads must be a power-of-2 size and cannot be 7353 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4, 7354 // 2 and 1 byte loads. 7355 const unsigned ResidueBytes = ByValSize % PtrByteSize; 7356 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize && 7357 "Unexpected register residue for by-value argument."); 7358 SDValue ResidueVal; 7359 for (unsigned Bytes = 0; Bytes != ResidueBytes;) { 7360 const unsigned N = PowerOf2Floor(ResidueBytes - Bytes); 7361 const MVT VT = 7362 N == 1 ? MVT::i8 7363 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64)); 7364 SDValue Load = GetLoad(VT, LoadOffset); 7365 MemOpChains.push_back(Load.getValue(1)); 7366 LoadOffset += N; 7367 Bytes += N; 7368 7369 // By-val arguments are passed left-justfied in register. 7370 // Every load here needs to be shifted, otherwise a full register load 7371 // should have been used. 7372 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) && 7373 "Unexpected load emitted during handling of pass-by-value " 7374 "argument."); 7375 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8); 7376 EVT ShiftAmountTy = 7377 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout()); 7378 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy); 7379 SDValue ShiftedLoad = 7380 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt); 7381 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal, 7382 ShiftedLoad) 7383 : ShiftedLoad; 7384 } 7385 7386 const CCValAssign &ByValVA = ArgLocs[I++]; 7387 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal)); 7388 continue; 7389 } 7390 7391 CCValAssign &VA = ArgLocs[I++]; 7392 const MVT LocVT = VA.getLocVT(); 7393 const MVT ValVT = VA.getValVT(); 7394 7395 switch (VA.getLocInfo()) { 7396 default: 7397 report_fatal_error("Unexpected argument extension type."); 7398 case CCValAssign::Full: 7399 break; 7400 case CCValAssign::ZExt: 7401 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7402 break; 7403 case CCValAssign::SExt: 7404 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7405 break; 7406 } 7407 7408 if (VA.isRegLoc() && !VA.needsCustom()) { 7409 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 7410 continue; 7411 } 7412 7413 // Vector arguments passed to VarArg functions need custom handling when 7414 // they are passed (at least partially) in GPRs. 7415 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) { 7416 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args."); 7417 // Store value to its stack slot. 7418 SDValue PtrOff = 7419 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7420 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7421 SDValue Store = 7422 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()); 7423 MemOpChains.push_back(Store); 7424 const unsigned OriginalValNo = VA.getValNo(); 7425 // Then load the GPRs from the stack 7426 unsigned LoadOffset = 0; 7427 auto HandleCustomVecRegLoc = [&]() { 7428 assert(I != E && "Unexpected end of CCvalAssigns."); 7429 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7430 "Expected custom RegLoc."); 7431 CCValAssign RegVA = ArgLocs[I++]; 7432 assert(RegVA.getValNo() == OriginalValNo && 7433 "Custom MemLoc ValNo and custom RegLoc ValNo must match."); 7434 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, 7435 DAG.getConstant(LoadOffset, dl, PtrVT)); 7436 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo()); 7437 MemOpChains.push_back(Load.getValue(1)); 7438 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load)); 7439 LoadOffset += PtrByteSize; 7440 }; 7441 7442 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in 7443 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and 7444 // R10. 7445 HandleCustomVecRegLoc(); 7446 HandleCustomVecRegLoc(); 7447 7448 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() && 7449 ArgLocs[I].getValNo() == OriginalValNo) { 7450 assert(!IsPPC64 && 7451 "Only 2 custom RegLocs expected for 64-bit codegen."); 7452 HandleCustomVecRegLoc(); 7453 HandleCustomVecRegLoc(); 7454 } 7455 7456 continue; 7457 } 7458 7459 if (VA.isMemLoc()) { 7460 SDValue PtrOff = 7461 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType()); 7462 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7463 MemOpChains.push_back( 7464 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo())); 7465 7466 continue; 7467 } 7468 7469 if (!ValVT.isFloatingPoint()) 7470 report_fatal_error( 7471 "Unexpected register handling for calling convention."); 7472 7473 // Custom handling is used for GPR initializations for vararg float 7474 // arguments. 7475 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg && 7476 LocVT.isInteger() && 7477 "Custom register handling only expected for VarArg."); 7478 7479 SDValue ArgAsInt = 7480 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg); 7481 7482 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize()) 7483 // f32 in 32-bit GPR 7484 // f64 in 64-bit GPR 7485 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt)); 7486 else if (Arg.getValueType().getFixedSizeInBits() < 7487 LocVT.getFixedSizeInBits()) 7488 // f32 in 64-bit GPR. 7489 RegsToPass.push_back(std::make_pair( 7490 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT))); 7491 else { 7492 // f64 in two 32-bit GPRs 7493 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs. 7494 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 && 7495 "Unexpected custom register for argument!"); 7496 CCValAssign &GPR1 = VA; 7497 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt, 7498 DAG.getConstant(32, dl, MVT::i8)); 7499 RegsToPass.push_back(std::make_pair( 7500 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32))); 7501 7502 if (I != E) { 7503 // If only 1 GPR was available, there will only be one custom GPR and 7504 // the argument will also pass in memory. 7505 CCValAssign &PeekArg = ArgLocs[I]; 7506 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) { 7507 assert(PeekArg.needsCustom() && "A second custom GPR is expected."); 7508 CCValAssign &GPR2 = ArgLocs[I++]; 7509 RegsToPass.push_back(std::make_pair( 7510 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32))); 7511 } 7512 } 7513 } 7514 } 7515 7516 if (!MemOpChains.empty()) 7517 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); 7518 7519 // For indirect calls, we need to save the TOC base to the stack for 7520 // restoration after the call. 7521 if (CFlags.IsIndirect) { 7522 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported."); 7523 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister(); 7524 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister(); 7525 const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; 7526 const unsigned TOCSaveOffset = 7527 Subtarget.getFrameLowering()->getTOCSaveOffset(); 7528 7529 setUsesTOCBasePtr(DAG); 7530 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT); 7531 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); 7532 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT); 7533 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); 7534 Chain = DAG.getStore( 7535 Val.getValue(1), dl, Val, AddPtr, 7536 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset)); 7537 } 7538 7539 // Build a sequence of copy-to-reg nodes chained together with token chain 7540 // and flag operands which copy the outgoing args into the appropriate regs. 7541 SDValue InFlag; 7542 for (auto Reg : RegsToPass) { 7543 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag); 7544 InFlag = Chain.getValue(1); 7545 } 7546 7547 const int SPDiff = 0; 7548 return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart, 7549 Callee, SPDiff, NumBytes, Ins, InVals, CB); 7550 } 7551 7552 bool 7553 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, 7554 MachineFunction &MF, bool isVarArg, 7555 const SmallVectorImpl<ISD::OutputArg> &Outs, 7556 LLVMContext &Context) const { 7557 SmallVector<CCValAssign, 16> RVLocs; 7558 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 7559 return CCInfo.CheckReturn( 7560 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7561 ? RetCC_PPC_Cold 7562 : RetCC_PPC); 7563 } 7564 7565 SDValue 7566 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 7567 bool isVarArg, 7568 const SmallVectorImpl<ISD::OutputArg> &Outs, 7569 const SmallVectorImpl<SDValue> &OutVals, 7570 const SDLoc &dl, SelectionDAG &DAG) const { 7571 SmallVector<CCValAssign, 16> RVLocs; 7572 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 7573 *DAG.getContext()); 7574 CCInfo.AnalyzeReturn(Outs, 7575 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold) 7576 ? RetCC_PPC_Cold 7577 : RetCC_PPC); 7578 7579 SDValue Flag; 7580 SmallVector<SDValue, 4> RetOps(1, Chain); 7581 7582 // Copy the result values into the output registers. 7583 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) { 7584 CCValAssign &VA = RVLocs[i]; 7585 assert(VA.isRegLoc() && "Can only return in registers!"); 7586 7587 SDValue Arg = OutVals[RealResIdx]; 7588 7589 switch (VA.getLocInfo()) { 7590 default: llvm_unreachable("Unknown loc info!"); 7591 case CCValAssign::Full: break; 7592 case CCValAssign::AExt: 7593 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg); 7594 break; 7595 case CCValAssign::ZExt: 7596 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg); 7597 break; 7598 case CCValAssign::SExt: 7599 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg); 7600 break; 7601 } 7602 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) { 7603 bool isLittleEndian = Subtarget.isLittleEndian(); 7604 // Legalize ret f64 -> ret 2 x i32. 7605 SDValue SVal = 7606 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7607 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl)); 7608 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7609 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7610 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg, 7611 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl)); 7612 Flag = Chain.getValue(1); 7613 VA = RVLocs[++i]; // skip ahead to next loc 7614 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag); 7615 } else 7616 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); 7617 Flag = Chain.getValue(1); 7618 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 7619 } 7620 7621 RetOps[0] = Chain; // Update chain. 7622 7623 // Add the flag if we have it. 7624 if (Flag.getNode()) 7625 RetOps.push_back(Flag); 7626 7627 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); 7628 } 7629 7630 SDValue 7631 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op, 7632 SelectionDAG &DAG) const { 7633 SDLoc dl(Op); 7634 7635 // Get the correct type for integers. 7636 EVT IntVT = Op.getValueType(); 7637 7638 // Get the inputs. 7639 SDValue Chain = Op.getOperand(0); 7640 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7641 // Build a DYNAREAOFFSET node. 7642 SDValue Ops[2] = {Chain, FPSIdx}; 7643 SDVTList VTs = DAG.getVTList(IntVT); 7644 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); 7645 } 7646 7647 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, 7648 SelectionDAG &DAG) const { 7649 // When we pop the dynamic allocation we need to restore the SP link. 7650 SDLoc dl(Op); 7651 7652 // Get the correct type for pointers. 7653 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7654 7655 // Construct the stack pointer operand. 7656 bool isPPC64 = Subtarget.isPPC64(); 7657 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; 7658 SDValue StackPtr = DAG.getRegister(SP, PtrVT); 7659 7660 // Get the operands for the STACKRESTORE. 7661 SDValue Chain = Op.getOperand(0); 7662 SDValue SaveSP = Op.getOperand(1); 7663 7664 // Load the old link SP. 7665 SDValue LoadLinkSP = 7666 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo()); 7667 7668 // Restore the stack pointer. 7669 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); 7670 7671 // Store the old link SP. 7672 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo()); 7673 } 7674 7675 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { 7676 MachineFunction &MF = DAG.getMachineFunction(); 7677 bool isPPC64 = Subtarget.isPPC64(); 7678 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7679 7680 // Get current frame pointer save index. The users of this index will be 7681 // primarily DYNALLOC instructions. 7682 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7683 int RASI = FI->getReturnAddrSaveIndex(); 7684 7685 // If the frame pointer save index hasn't been defined yet. 7686 if (!RASI) { 7687 // Find out what the fix offset of the frame pointer save area. 7688 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); 7689 // Allocate the frame index for frame pointer save area. 7690 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false); 7691 // Save the result. 7692 FI->setReturnAddrSaveIndex(RASI); 7693 } 7694 return DAG.getFrameIndex(RASI, PtrVT); 7695 } 7696 7697 SDValue 7698 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { 7699 MachineFunction &MF = DAG.getMachineFunction(); 7700 bool isPPC64 = Subtarget.isPPC64(); 7701 EVT PtrVT = getPointerTy(MF.getDataLayout()); 7702 7703 // Get current frame pointer save index. The users of this index will be 7704 // primarily DYNALLOC instructions. 7705 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); 7706 int FPSI = FI->getFramePointerSaveIndex(); 7707 7708 // If the frame pointer save index hasn't been defined yet. 7709 if (!FPSI) { 7710 // Find out what the fix offset of the frame pointer save area. 7711 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); 7712 // Allocate the frame index for frame pointer save area. 7713 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); 7714 // Save the result. 7715 FI->setFramePointerSaveIndex(FPSI); 7716 } 7717 return DAG.getFrameIndex(FPSI, PtrVT); 7718 } 7719 7720 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7721 SelectionDAG &DAG) const { 7722 MachineFunction &MF = DAG.getMachineFunction(); 7723 // Get the inputs. 7724 SDValue Chain = Op.getOperand(0); 7725 SDValue Size = Op.getOperand(1); 7726 SDLoc dl(Op); 7727 7728 // Get the correct type for pointers. 7729 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7730 // Negate the size. 7731 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, 7732 DAG.getConstant(0, dl, PtrVT), Size); 7733 // Construct a node for the frame pointer save index. 7734 SDValue FPSIdx = getFramePointerFrameIndex(DAG); 7735 SDValue Ops[3] = { Chain, NegSize, FPSIdx }; 7736 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); 7737 if (hasInlineStackProbe(MF)) 7738 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops); 7739 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); 7740 } 7741 7742 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op, 7743 SelectionDAG &DAG) const { 7744 MachineFunction &MF = DAG.getMachineFunction(); 7745 7746 bool isPPC64 = Subtarget.isPPC64(); 7747 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7748 7749 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false); 7750 return DAG.getFrameIndex(FI, PtrVT); 7751 } 7752 7753 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 7754 SelectionDAG &DAG) const { 7755 SDLoc DL(Op); 7756 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, 7757 DAG.getVTList(MVT::i32, MVT::Other), 7758 Op.getOperand(0), Op.getOperand(1)); 7759 } 7760 7761 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 7762 SelectionDAG &DAG) const { 7763 SDLoc DL(Op); 7764 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, 7765 Op.getOperand(0), Op.getOperand(1)); 7766 } 7767 7768 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7769 if (Op.getValueType().isVector()) 7770 return LowerVectorLoad(Op, DAG); 7771 7772 assert(Op.getValueType() == MVT::i1 && 7773 "Custom lowering only for i1 loads"); 7774 7775 // First, load 8 bits into 32 bits, then truncate to 1 bit. 7776 7777 SDLoc dl(Op); 7778 LoadSDNode *LD = cast<LoadSDNode>(Op); 7779 7780 SDValue Chain = LD->getChain(); 7781 SDValue BasePtr = LD->getBasePtr(); 7782 MachineMemOperand *MMO = LD->getMemOperand(); 7783 7784 SDValue NewLD = 7785 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, 7786 BasePtr, MVT::i8, MMO); 7787 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); 7788 7789 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; 7790 return DAG.getMergeValues(Ops, dl); 7791 } 7792 7793 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7794 if (Op.getOperand(1).getValueType().isVector()) 7795 return LowerVectorStore(Op, DAG); 7796 7797 assert(Op.getOperand(1).getValueType() == MVT::i1 && 7798 "Custom lowering only for i1 stores"); 7799 7800 // First, zero extend to 32 bits, then use a truncating store to 8 bits. 7801 7802 SDLoc dl(Op); 7803 StoreSDNode *ST = cast<StoreSDNode>(Op); 7804 7805 SDValue Chain = ST->getChain(); 7806 SDValue BasePtr = ST->getBasePtr(); 7807 SDValue Value = ST->getValue(); 7808 MachineMemOperand *MMO = ST->getMemOperand(); 7809 7810 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), 7811 Value); 7812 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); 7813 } 7814 7815 // FIXME: Remove this once the ANDI glue bug is fixed: 7816 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { 7817 assert(Op.getValueType() == MVT::i1 && 7818 "Custom lowering only for i1 results"); 7819 7820 SDLoc DL(Op); 7821 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); 7822 } 7823 7824 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op, 7825 SelectionDAG &DAG) const { 7826 7827 // Implements a vector truncate that fits in a vector register as a shuffle. 7828 // We want to legalize vector truncates down to where the source fits in 7829 // a vector register (and target is therefore smaller than vector register 7830 // size). At that point legalization will try to custom lower the sub-legal 7831 // result and get here - where we can contain the truncate as a single target 7832 // operation. 7833 7834 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows: 7835 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2> 7836 // 7837 // We will implement it for big-endian ordering as this (where x denotes 7838 // undefined): 7839 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to 7840 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u> 7841 // 7842 // The same operation in little-endian ordering will be: 7843 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to 7844 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1> 7845 7846 EVT TrgVT = Op.getValueType(); 7847 assert(TrgVT.isVector() && "Vector type expected."); 7848 unsigned TrgNumElts = TrgVT.getVectorNumElements(); 7849 EVT EltVT = TrgVT.getVectorElementType(); 7850 if (!isOperationCustom(Op.getOpcode(), TrgVT) || 7851 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) || 7852 !isPowerOf2_32(EltVT.getSizeInBits())) 7853 return SDValue(); 7854 7855 SDValue N1 = Op.getOperand(0); 7856 EVT SrcVT = N1.getValueType(); 7857 unsigned SrcSize = SrcVT.getSizeInBits(); 7858 if (SrcSize > 256 || 7859 !isPowerOf2_32(SrcVT.getVectorNumElements()) || 7860 !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits())) 7861 return SDValue(); 7862 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2) 7863 return SDValue(); 7864 7865 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 7866 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 7867 7868 SDLoc DL(Op); 7869 SDValue Op1, Op2; 7870 if (SrcSize == 256) { 7871 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout()); 7872 EVT SplitVT = 7873 N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext()); 7874 unsigned SplitNumElts = SplitVT.getVectorNumElements(); 7875 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7876 DAG.getConstant(0, DL, VecIdxTy)); 7877 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1, 7878 DAG.getConstant(SplitNumElts, DL, VecIdxTy)); 7879 } 7880 else { 7881 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL); 7882 Op2 = DAG.getUNDEF(WideVT); 7883 } 7884 7885 // First list the elements we want to keep. 7886 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits(); 7887 SmallVector<int, 16> ShuffV; 7888 if (Subtarget.isLittleEndian()) 7889 for (unsigned i = 0; i < TrgNumElts; ++i) 7890 ShuffV.push_back(i * SizeMult); 7891 else 7892 for (unsigned i = 1; i <= TrgNumElts; ++i) 7893 ShuffV.push_back(i * SizeMult - 1); 7894 7895 // Populate the remaining elements with undefs. 7896 for (unsigned i = TrgNumElts; i < WideNumElts; ++i) 7897 // ShuffV.push_back(i + WideNumElts); 7898 ShuffV.push_back(WideNumElts + 1); 7899 7900 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1); 7901 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2); 7902 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV); 7903 } 7904 7905 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when 7906 /// possible. 7907 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { 7908 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 7909 EVT ResVT = Op.getValueType(); 7910 EVT CmpVT = Op.getOperand(0).getValueType(); 7911 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 7912 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); 7913 SDLoc dl(Op); 7914 7915 // Without power9-vector, we don't have native instruction for f128 comparison. 7916 // Following transformation to libcall is needed for setcc: 7917 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE 7918 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) { 7919 SDValue Z = DAG.getSetCC( 7920 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT), 7921 LHS, RHS, CC); 7922 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType()); 7923 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE); 7924 } 7925 7926 // Not FP, or using SPE? Not a fsel. 7927 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() || 7928 Subtarget.hasSPE()) 7929 return Op; 7930 7931 SDNodeFlags Flags = Op.getNode()->getFlags(); 7932 7933 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the 7934 // presence of infinities. 7935 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) { 7936 switch (CC) { 7937 default: 7938 break; 7939 case ISD::SETOGT: 7940 case ISD::SETGT: 7941 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS); 7942 case ISD::SETOLT: 7943 case ISD::SETLT: 7944 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS); 7945 } 7946 } 7947 7948 // We might be able to do better than this under some circumstances, but in 7949 // general, fsel-based lowering of select is a finite-math-only optimization. 7950 // For more information, see section F.3 of the 2.06 ISA specification. 7951 // With ISA 3.0 7952 if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) || 7953 (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs())) 7954 return Op; 7955 7956 // If the RHS of the comparison is a 0.0, we don't need to do the 7957 // subtraction at all. 7958 SDValue Sel1; 7959 if (isFloatingPointZero(RHS)) 7960 switch (CC) { 7961 default: break; // SETUO etc aren't handled by fsel. 7962 case ISD::SETNE: 7963 std::swap(TV, FV); 7964 [[fallthrough]]; 7965 case ISD::SETEQ: 7966 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7967 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7968 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7969 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 7970 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 7971 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7972 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); 7973 case ISD::SETULT: 7974 case ISD::SETLT: 7975 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7976 [[fallthrough]]; 7977 case ISD::SETOGE: 7978 case ISD::SETGE: 7979 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7980 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7981 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); 7982 case ISD::SETUGT: 7983 case ISD::SETGT: 7984 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt 7985 [[fallthrough]]; 7986 case ISD::SETOLE: 7987 case ISD::SETLE: 7988 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits 7989 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); 7990 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 7991 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); 7992 } 7993 7994 SDValue Cmp; 7995 switch (CC) { 7996 default: break; // SETUO etc aren't handled by fsel. 7997 case ISD::SETNE: 7998 std::swap(TV, FV); 7999 [[fallthrough]]; 8000 case ISD::SETEQ: 8001 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8002 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8003 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8004 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8005 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits 8006 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); 8007 return DAG.getNode(PPCISD::FSEL, dl, ResVT, 8008 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); 8009 case ISD::SETULT: 8010 case ISD::SETLT: 8011 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8012 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8013 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8014 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8015 case ISD::SETOGE: 8016 case ISD::SETGE: 8017 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags); 8018 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8019 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8020 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8021 case ISD::SETUGT: 8022 case ISD::SETGT: 8023 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8024 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8025 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8026 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); 8027 case ISD::SETOLE: 8028 case ISD::SETLE: 8029 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags); 8030 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits 8031 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); 8032 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); 8033 } 8034 return Op; 8035 } 8036 8037 static unsigned getPPCStrictOpcode(unsigned Opc) { 8038 switch (Opc) { 8039 default: 8040 llvm_unreachable("No strict version of this opcode!"); 8041 case PPCISD::FCTIDZ: 8042 return PPCISD::STRICT_FCTIDZ; 8043 case PPCISD::FCTIWZ: 8044 return PPCISD::STRICT_FCTIWZ; 8045 case PPCISD::FCTIDUZ: 8046 return PPCISD::STRICT_FCTIDUZ; 8047 case PPCISD::FCTIWUZ: 8048 return PPCISD::STRICT_FCTIWUZ; 8049 case PPCISD::FCFID: 8050 return PPCISD::STRICT_FCFID; 8051 case PPCISD::FCFIDU: 8052 return PPCISD::STRICT_FCFIDU; 8053 case PPCISD::FCFIDS: 8054 return PPCISD::STRICT_FCFIDS; 8055 case PPCISD::FCFIDUS: 8056 return PPCISD::STRICT_FCFIDUS; 8057 } 8058 } 8059 8060 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, 8061 const PPCSubtarget &Subtarget) { 8062 SDLoc dl(Op); 8063 bool IsStrict = Op->isStrictFPOpcode(); 8064 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8065 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8066 8067 // TODO: Any other flags to propagate? 8068 SDNodeFlags Flags; 8069 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8070 8071 // For strict nodes, source is the second operand. 8072 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8073 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 8074 assert(Src.getValueType().isFloatingPoint()); 8075 if (Src.getValueType() == MVT::f32) { 8076 if (IsStrict) { 8077 Src = 8078 DAG.getNode(ISD::STRICT_FP_EXTEND, dl, 8079 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags); 8080 Chain = Src.getValue(1); 8081 } else 8082 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 8083 } 8084 SDValue Conv; 8085 unsigned Opc = ISD::DELETED_NODE; 8086 switch (Op.getSimpleValueType().SimpleTy) { 8087 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); 8088 case MVT::i32: 8089 Opc = IsSigned ? PPCISD::FCTIWZ 8090 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ); 8091 break; 8092 case MVT::i64: 8093 assert((IsSigned || Subtarget.hasFPCVT()) && 8094 "i64 FP_TO_UINT is supported only with FPCVT"); 8095 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; 8096 } 8097 if (IsStrict) { 8098 Opc = getPPCStrictOpcode(Opc); 8099 Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other), 8100 {Chain, Src}, Flags); 8101 } else { 8102 Conv = DAG.getNode(Opc, dl, MVT::f64, Src); 8103 } 8104 return Conv; 8105 } 8106 8107 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, 8108 SelectionDAG &DAG, 8109 const SDLoc &dl) const { 8110 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget); 8111 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8112 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8113 bool IsStrict = Op->isStrictFPOpcode(); 8114 8115 // Convert the FP value to an int value through memory. 8116 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && 8117 (IsSigned || Subtarget.hasFPCVT()); 8118 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); 8119 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); 8120 MachinePointerInfo MPI = 8121 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 8122 8123 // Emit a store to the stack slot. 8124 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode(); 8125 Align Alignment(DAG.getEVTAlign(Tmp.getValueType())); 8126 if (i32Stack) { 8127 MachineFunction &MF = DAG.getMachineFunction(); 8128 Alignment = Align(4); 8129 MachineMemOperand *MMO = 8130 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment); 8131 SDValue Ops[] = { Chain, Tmp, FIPtr }; 8132 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, 8133 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); 8134 } else 8135 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment); 8136 8137 // Result is a load from the stack slot. If loading 4 bytes, make sure to 8138 // add in a bias on big endian. 8139 if (Op.getValueType() == MVT::i32 && !i32Stack) { 8140 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, 8141 DAG.getConstant(4, dl, FIPtr.getValueType())); 8142 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4); 8143 } 8144 8145 RLI.Chain = Chain; 8146 RLI.Ptr = FIPtr; 8147 RLI.MPI = MPI; 8148 RLI.Alignment = Alignment; 8149 } 8150 8151 /// Custom lowers floating point to integer conversions to use 8152 /// the direct move instructions available in ISA 2.07 to avoid the 8153 /// need for load/store combinations. 8154 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, 8155 SelectionDAG &DAG, 8156 const SDLoc &dl) const { 8157 SDValue Conv = convertFPToInt(Op, DAG, Subtarget); 8158 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv); 8159 if (Op->isStrictFPOpcode()) 8160 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl); 8161 else 8162 return Mov; 8163 } 8164 8165 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, 8166 const SDLoc &dl) const { 8167 bool IsStrict = Op->isStrictFPOpcode(); 8168 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT || 8169 Op.getOpcode() == ISD::STRICT_FP_TO_SINT; 8170 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8171 EVT SrcVT = Src.getValueType(); 8172 EVT DstVT = Op.getValueType(); 8173 8174 // FP to INT conversions are legal for f128. 8175 if (SrcVT == MVT::f128) 8176 return Subtarget.hasP9Vector() ? Op : SDValue(); 8177 8178 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on 8179 // PPC (the libcall is not available). 8180 if (SrcVT == MVT::ppcf128) { 8181 if (DstVT == MVT::i32) { 8182 // TODO: Conservatively pass only nofpexcept flag here. Need to check and 8183 // set other fast-math flags to FP operations in both strict and 8184 // non-strict cases. (FP_TO_SINT, FSUB) 8185 SDNodeFlags Flags; 8186 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8187 8188 if (IsSigned) { 8189 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8190 DAG.getIntPtrConstant(0, dl)); 8191 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src, 8192 DAG.getIntPtrConstant(1, dl)); 8193 8194 // Add the two halves of the long double in round-to-zero mode, and use 8195 // a smaller FP_TO_SINT. 8196 if (IsStrict) { 8197 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl, 8198 DAG.getVTList(MVT::f64, MVT::Other), 8199 {Op.getOperand(0), Lo, Hi}, Flags); 8200 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8201 DAG.getVTList(MVT::i32, MVT::Other), 8202 {Res.getValue(1), Res}, Flags); 8203 } else { 8204 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); 8205 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res); 8206 } 8207 } else { 8208 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0}; 8209 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31)); 8210 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 8211 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT); 8212 if (IsStrict) { 8213 // Sel = Src < 0x80000000 8214 // FltOfs = select Sel, 0.0, 0x80000000 8215 // IntOfs = select Sel, 0, 0x80000000 8216 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs 8217 SDValue Chain = Op.getOperand(0); 8218 EVT SetCCVT = 8219 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 8220 EVT DstSetCCVT = 8221 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT); 8222 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT, 8223 Chain, true); 8224 Chain = Sel.getValue(1); 8225 8226 SDValue FltOfs = DAG.getSelect( 8227 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst); 8228 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT); 8229 8230 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, 8231 DAG.getVTList(SrcVT, MVT::Other), 8232 {Chain, Src, FltOfs}, Flags); 8233 Chain = Val.getValue(1); 8234 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, 8235 DAG.getVTList(DstVT, MVT::Other), 8236 {Chain, Val}, Flags); 8237 Chain = SInt.getValue(1); 8238 SDValue IntOfs = DAG.getSelect( 8239 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask); 8240 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs); 8241 return DAG.getMergeValues({Result, Chain}, dl); 8242 } else { 8243 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X 8244 // FIXME: generated code sucks. 8245 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst); 8246 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True); 8247 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask); 8248 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src); 8249 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE); 8250 } 8251 } 8252 } 8253 8254 return SDValue(); 8255 } 8256 8257 if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) 8258 return LowerFP_TO_INTDirectMove(Op, DAG, dl); 8259 8260 ReuseLoadInfo RLI; 8261 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8262 8263 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8264 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8265 } 8266 8267 // We're trying to insert a regular store, S, and then a load, L. If the 8268 // incoming value, O, is a load, we might just be able to have our load use the 8269 // address used by O. However, we don't know if anything else will store to 8270 // that address before we can load from it. To prevent this situation, we need 8271 // to insert our load, L, into the chain as a peer of O. To do this, we give L 8272 // the same chain operand as O, we create a token factor from the chain results 8273 // of O and L, and we replace all uses of O's chain result with that token 8274 // factor (see spliceIntoChain below for this last part). 8275 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, 8276 ReuseLoadInfo &RLI, 8277 SelectionDAG &DAG, 8278 ISD::LoadExtType ET) const { 8279 // Conservatively skip reusing for constrained FP nodes. 8280 if (Op->isStrictFPOpcode()) 8281 return false; 8282 8283 SDLoc dl(Op); 8284 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT && 8285 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32); 8286 if (ET == ISD::NON_EXTLOAD && 8287 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) && 8288 isOperationLegalOrCustom(Op.getOpcode(), 8289 Op.getOperand(0).getValueType())) { 8290 8291 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); 8292 return true; 8293 } 8294 8295 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); 8296 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || 8297 LD->isNonTemporal()) 8298 return false; 8299 if (LD->getMemoryVT() != MemVT) 8300 return false; 8301 8302 // If the result of the load is an illegal type, then we can't build a 8303 // valid chain for reuse since the legalised loads and token factor node that 8304 // ties the legalised loads together uses a different output chain then the 8305 // illegal load. 8306 if (!isTypeLegal(LD->getValueType(0))) 8307 return false; 8308 8309 RLI.Ptr = LD->getBasePtr(); 8310 if (LD->isIndexed() && !LD->getOffset().isUndef()) { 8311 assert(LD->getAddressingMode() == ISD::PRE_INC && 8312 "Non-pre-inc AM on PPC?"); 8313 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, 8314 LD->getOffset()); 8315 } 8316 8317 RLI.Chain = LD->getChain(); 8318 RLI.MPI = LD->getPointerInfo(); 8319 RLI.IsDereferenceable = LD->isDereferenceable(); 8320 RLI.IsInvariant = LD->isInvariant(); 8321 RLI.Alignment = LD->getAlign(); 8322 RLI.AAInfo = LD->getAAInfo(); 8323 RLI.Ranges = LD->getRanges(); 8324 8325 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); 8326 return true; 8327 } 8328 8329 // Given the head of the old chain, ResChain, insert a token factor containing 8330 // it and NewResChain, and make users of ResChain now be users of that token 8331 // factor. 8332 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead. 8333 void PPCTargetLowering::spliceIntoChain(SDValue ResChain, 8334 SDValue NewResChain, 8335 SelectionDAG &DAG) const { 8336 if (!ResChain) 8337 return; 8338 8339 SDLoc dl(NewResChain); 8340 8341 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 8342 NewResChain, DAG.getUNDEF(MVT::Other)); 8343 assert(TF.getNode() != NewResChain.getNode() && 8344 "A new TF really is required here"); 8345 8346 DAG.ReplaceAllUsesOfValueWith(ResChain, TF); 8347 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); 8348 } 8349 8350 /// Analyze profitability of direct move 8351 /// prefer float load to int load plus direct move 8352 /// when there is no integer use of int load 8353 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const { 8354 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode(); 8355 if (Origin->getOpcode() != ISD::LOAD) 8356 return true; 8357 8358 // If there is no LXSIBZX/LXSIHZX, like Power8, 8359 // prefer direct move if the memory size is 1 or 2 bytes. 8360 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand(); 8361 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2) 8362 return true; 8363 8364 for (SDNode::use_iterator UI = Origin->use_begin(), 8365 UE = Origin->use_end(); 8366 UI != UE; ++UI) { 8367 8368 // Only look at the users of the loaded value. 8369 if (UI.getUse().get().getResNo() != 0) 8370 continue; 8371 8372 if (UI->getOpcode() != ISD::SINT_TO_FP && 8373 UI->getOpcode() != ISD::UINT_TO_FP && 8374 UI->getOpcode() != ISD::STRICT_SINT_TO_FP && 8375 UI->getOpcode() != ISD::STRICT_UINT_TO_FP) 8376 return true; 8377 } 8378 8379 return false; 8380 } 8381 8382 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, 8383 const PPCSubtarget &Subtarget, 8384 SDValue Chain = SDValue()) { 8385 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8386 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8387 SDLoc dl(Op); 8388 8389 // TODO: Any other flags to propagate? 8390 SDNodeFlags Flags; 8391 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8392 8393 // If we have FCFIDS, then use it when converting to single-precision. 8394 // Otherwise, convert to double-precision and then round. 8395 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT(); 8396 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS) 8397 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU); 8398 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64; 8399 if (Op->isStrictFPOpcode()) { 8400 if (!Chain) 8401 Chain = Op.getOperand(0); 8402 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, 8403 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags); 8404 } else 8405 return DAG.getNode(ConvOpc, dl, ConvTy, Src); 8406 } 8407 8408 /// Custom lowers integer to floating point conversions to use 8409 /// the direct move instructions available in ISA 2.07 to avoid the 8410 /// need for load/store combinations. 8411 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, 8412 SelectionDAG &DAG, 8413 const SDLoc &dl) const { 8414 assert((Op.getValueType() == MVT::f32 || 8415 Op.getValueType() == MVT::f64) && 8416 "Invalid floating point type as target of conversion"); 8417 assert(Subtarget.hasFPCVT() && 8418 "Int to FP conversions with direct moves require FPCVT"); 8419 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0); 8420 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; 8421 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP || 8422 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8423 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA; 8424 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src); 8425 return convertIntToFP(Op, Mov, DAG, Subtarget); 8426 } 8427 8428 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) { 8429 8430 EVT VecVT = Vec.getValueType(); 8431 assert(VecVT.isVector() && "Expected a vector type."); 8432 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width."); 8433 8434 EVT EltVT = VecVT.getVectorElementType(); 8435 unsigned WideNumElts = 128 / EltVT.getSizeInBits(); 8436 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts); 8437 8438 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements(); 8439 SmallVector<SDValue, 16> Ops(NumConcat); 8440 Ops[0] = Vec; 8441 SDValue UndefVec = DAG.getUNDEF(VecVT); 8442 for (unsigned i = 1; i < NumConcat; ++i) 8443 Ops[i] = UndefVec; 8444 8445 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops); 8446 } 8447 8448 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG, 8449 const SDLoc &dl) const { 8450 bool IsStrict = Op->isStrictFPOpcode(); 8451 unsigned Opc = Op.getOpcode(); 8452 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8453 assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP || 8454 Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) && 8455 "Unexpected conversion type"); 8456 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) && 8457 "Supports conversions to v2f64/v4f32 only."); 8458 8459 // TODO: Any other flags to propagate? 8460 SDNodeFlags Flags; 8461 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8462 8463 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP; 8464 bool FourEltRes = Op.getValueType() == MVT::v4f32; 8465 8466 SDValue Wide = widenVec(DAG, Src, dl); 8467 EVT WideVT = Wide.getValueType(); 8468 unsigned WideNumElts = WideVT.getVectorNumElements(); 8469 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64; 8470 8471 SmallVector<int, 16> ShuffV; 8472 for (unsigned i = 0; i < WideNumElts; ++i) 8473 ShuffV.push_back(i + WideNumElts); 8474 8475 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2; 8476 int SaveElts = FourEltRes ? 4 : 2; 8477 if (Subtarget.isLittleEndian()) 8478 for (int i = 0; i < SaveElts; i++) 8479 ShuffV[i * Stride] = i; 8480 else 8481 for (int i = 1; i <= SaveElts; i++) 8482 ShuffV[i * Stride - 1] = i - 1; 8483 8484 SDValue ShuffleSrc2 = 8485 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT); 8486 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV); 8487 8488 SDValue Extend; 8489 if (SignedConv) { 8490 Arrange = DAG.getBitcast(IntermediateVT, Arrange); 8491 EVT ExtVT = Src.getValueType(); 8492 if (Subtarget.hasP9Altivec()) 8493 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(), 8494 IntermediateVT.getVectorNumElements()); 8495 8496 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange, 8497 DAG.getValueType(ExtVT)); 8498 } else 8499 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange); 8500 8501 if (IsStrict) 8502 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other), 8503 {Op.getOperand(0), Extend}, Flags); 8504 8505 return DAG.getNode(Opc, dl, Op.getValueType(), Extend); 8506 } 8507 8508 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, 8509 SelectionDAG &DAG) const { 8510 SDLoc dl(Op); 8511 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP || 8512 Op.getOpcode() == ISD::STRICT_SINT_TO_FP; 8513 bool IsStrict = Op->isStrictFPOpcode(); 8514 SDValue Src = Op.getOperand(IsStrict ? 1 : 0); 8515 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode(); 8516 8517 // TODO: Any other flags to propagate? 8518 SDNodeFlags Flags; 8519 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept()); 8520 8521 EVT InVT = Src.getValueType(); 8522 EVT OutVT = Op.getValueType(); 8523 if (OutVT.isVector() && OutVT.isFloatingPoint() && 8524 isOperationCustom(Op.getOpcode(), InVT)) 8525 return LowerINT_TO_FPVector(Op, DAG, dl); 8526 8527 // Conversions to f128 are legal. 8528 if (Op.getValueType() == MVT::f128) 8529 return Subtarget.hasP9Vector() ? Op : SDValue(); 8530 8531 // Don't handle ppc_fp128 here; let it be lowered to a libcall. 8532 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 8533 return SDValue(); 8534 8535 if (Src.getValueType() == MVT::i1) { 8536 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src, 8537 DAG.getConstantFP(1.0, dl, Op.getValueType()), 8538 DAG.getConstantFP(0.0, dl, Op.getValueType())); 8539 if (IsStrict) 8540 return DAG.getMergeValues({Sel, Chain}, dl); 8541 else 8542 return Sel; 8543 } 8544 8545 // If we have direct moves, we can do all the conversion, skip the store/load 8546 // however, without FPCVT we can't do most conversions. 8547 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) && 8548 Subtarget.isPPC64() && Subtarget.hasFPCVT()) 8549 return LowerINT_TO_FPDirectMove(Op, DAG, dl); 8550 8551 assert((IsSigned || Subtarget.hasFPCVT()) && 8552 "UINT_TO_FP is supported only with FPCVT"); 8553 8554 if (Src.getValueType() == MVT::i64) { 8555 SDValue SINT = Src; 8556 // When converting to single-precision, we actually need to convert 8557 // to double-precision first and then round to single-precision. 8558 // To avoid double-rounding effects during that operation, we have 8559 // to prepare the input operand. Bits that might be truncated when 8560 // converting to double-precision are replaced by a bit that won't 8561 // be lost at this stage, but is below the single-precision rounding 8562 // position. 8563 // 8564 // However, if -enable-unsafe-fp-math is in effect, accept double 8565 // rounding to avoid the extra overhead. 8566 if (Op.getValueType() == MVT::f32 && 8567 !Subtarget.hasFPCVT() && 8568 !DAG.getTarget().Options.UnsafeFPMath) { 8569 8570 // Twiddle input to make sure the low 11 bits are zero. (If this 8571 // is the case, we are guaranteed the value will fit into the 53 bit 8572 // mantissa of an IEEE double-precision value without rounding.) 8573 // If any of those low 11 bits were not zero originally, make sure 8574 // bit 12 (value 2048) is set instead, so that the final rounding 8575 // to single-precision gets the correct result. 8576 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8577 SINT, DAG.getConstant(2047, dl, MVT::i64)); 8578 Round = DAG.getNode(ISD::ADD, dl, MVT::i64, 8579 Round, DAG.getConstant(2047, dl, MVT::i64)); 8580 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); 8581 Round = DAG.getNode(ISD::AND, dl, MVT::i64, 8582 Round, DAG.getConstant(-2048, dl, MVT::i64)); 8583 8584 // However, we cannot use that value unconditionally: if the magnitude 8585 // of the input value is small, the bit-twiddling we did above might 8586 // end up visibly changing the output. Fortunately, in that case, we 8587 // don't need to twiddle bits since the original input will convert 8588 // exactly to double-precision floating-point already. Therefore, 8589 // construct a conditional to use the original value if the top 11 8590 // bits are all sign-bit copies, and use the rounded value computed 8591 // above otherwise. 8592 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, 8593 SINT, DAG.getConstant(53, dl, MVT::i32)); 8594 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, 8595 Cond, DAG.getConstant(1, dl, MVT::i64)); 8596 Cond = DAG.getSetCC( 8597 dl, 8598 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64), 8599 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); 8600 8601 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); 8602 } 8603 8604 ReuseLoadInfo RLI; 8605 SDValue Bits; 8606 8607 MachineFunction &MF = DAG.getMachineFunction(); 8608 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { 8609 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, 8610 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges); 8611 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8612 } else if (Subtarget.hasLFIWAX() && 8613 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { 8614 MachineMemOperand *MMO = 8615 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8616 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8617 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8618 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, 8619 DAG.getVTList(MVT::f64, MVT::Other), 8620 Ops, MVT::i32, MMO); 8621 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8622 } else if (Subtarget.hasFPCVT() && 8623 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { 8624 MachineMemOperand *MMO = 8625 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8626 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8627 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8628 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, 8629 DAG.getVTList(MVT::f64, MVT::Other), 8630 Ops, MVT::i32, MMO); 8631 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); 8632 } else if (((Subtarget.hasLFIWAX() && 8633 SINT.getOpcode() == ISD::SIGN_EXTEND) || 8634 (Subtarget.hasFPCVT() && 8635 SINT.getOpcode() == ISD::ZERO_EXTEND)) && 8636 SINT.getOperand(0).getValueType() == MVT::i32) { 8637 MachineFrameInfo &MFI = MF.getFrameInfo(); 8638 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8639 8640 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8641 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8642 8643 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx, 8644 MachinePointerInfo::getFixedStack( 8645 DAG.getMachineFunction(), FrameIdx)); 8646 Chain = Store; 8647 8648 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8649 "Expected an i32 store"); 8650 8651 RLI.Ptr = FIdx; 8652 RLI.Chain = Chain; 8653 RLI.MPI = 8654 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8655 RLI.Alignment = Align(4); 8656 8657 MachineMemOperand *MMO = 8658 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8659 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8660 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8661 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? 8662 PPCISD::LFIWZX : PPCISD::LFIWAX, 8663 dl, DAG.getVTList(MVT::f64, MVT::Other), 8664 Ops, MVT::i32, MMO); 8665 Chain = Bits.getValue(1); 8666 } else 8667 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); 8668 8669 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain); 8670 if (IsStrict) 8671 Chain = FP.getValue(1); 8672 8673 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8674 if (IsStrict) 8675 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8676 DAG.getVTList(MVT::f32, MVT::Other), 8677 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8678 else 8679 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8680 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 8681 } 8682 return FP; 8683 } 8684 8685 assert(Src.getValueType() == MVT::i32 && 8686 "Unhandled INT_TO_FP type in custom expander!"); 8687 // Since we only generate this in 64-bit mode, we can take advantage of 8688 // 64-bit registers. In particular, sign extend the input value into the 8689 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack 8690 // then lfd it and fcfid it. 8691 MachineFunction &MF = DAG.getMachineFunction(); 8692 MachineFrameInfo &MFI = MF.getFrameInfo(); 8693 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8694 8695 SDValue Ld; 8696 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { 8697 ReuseLoadInfo RLI; 8698 bool ReusingLoad; 8699 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) { 8700 int FrameIdx = MFI.CreateStackObject(4, Align(4), false); 8701 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8702 8703 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx, 8704 MachinePointerInfo::getFixedStack( 8705 DAG.getMachineFunction(), FrameIdx)); 8706 Chain = Store; 8707 8708 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && 8709 "Expected an i32 store"); 8710 8711 RLI.Ptr = FIdx; 8712 RLI.Chain = Chain; 8713 RLI.MPI = 8714 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); 8715 RLI.Alignment = Align(4); 8716 } 8717 8718 MachineMemOperand *MMO = 8719 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, 8720 RLI.Alignment, RLI.AAInfo, RLI.Ranges); 8721 SDValue Ops[] = { RLI.Chain, RLI.Ptr }; 8722 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl, 8723 DAG.getVTList(MVT::f64, MVT::Other), Ops, 8724 MVT::i32, MMO); 8725 Chain = Ld.getValue(1); 8726 if (ReusingLoad) 8727 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); 8728 } else { 8729 assert(Subtarget.isPPC64() && 8730 "i32->FP without LFIWAX supported only on PPC64"); 8731 8732 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 8733 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 8734 8735 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src); 8736 8737 // STD the extended value into the stack slot. 8738 SDValue Store = DAG.getStore( 8739 Chain, dl, Ext64, FIdx, 8740 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8741 Chain = Store; 8742 8743 // Load the value as a double. 8744 Ld = DAG.getLoad( 8745 MVT::f64, dl, Chain, FIdx, 8746 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx)); 8747 Chain = Ld.getValue(1); 8748 } 8749 8750 // FCFID it and return it. 8751 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain); 8752 if (IsStrict) 8753 Chain = FP.getValue(1); 8754 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 8755 if (IsStrict) 8756 FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, 8757 DAG.getVTList(MVT::f32, MVT::Other), 8758 {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags); 8759 else 8760 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 8761 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 8762 } 8763 return FP; 8764 } 8765 8766 SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op, 8767 SelectionDAG &DAG) const { 8768 SDLoc dl(Op); 8769 /* 8770 The rounding mode is in bits 30:31 of FPSR, and has the following 8771 settings: 8772 00 Round to nearest 8773 01 Round to 0 8774 10 Round to +inf 8775 11 Round to -inf 8776 8777 GET_ROUNDING, on the other hand, expects the following: 8778 -1 Undefined 8779 0 Round to 0 8780 1 Round to nearest 8781 2 Round to +inf 8782 3 Round to -inf 8783 8784 To perform the conversion, we do: 8785 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) 8786 */ 8787 8788 MachineFunction &MF = DAG.getMachineFunction(); 8789 EVT VT = Op.getValueType(); 8790 EVT PtrVT = getPointerTy(MF.getDataLayout()); 8791 8792 // Save FP Control Word to register 8793 SDValue Chain = Op.getOperand(0); 8794 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain); 8795 Chain = MFFS.getValue(1); 8796 8797 SDValue CWD; 8798 if (isTypeLegal(MVT::i64)) { 8799 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, 8800 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS)); 8801 } else { 8802 // Save FP register to stack slot 8803 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false); 8804 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); 8805 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo()); 8806 8807 // Load FP Control Word from low 32 bits of stack slot. 8808 assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) && 8809 "Stack slot adjustment is valid only on big endian subtargets!"); 8810 SDValue Four = DAG.getConstant(4, dl, PtrVT); 8811 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); 8812 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo()); 8813 Chain = CWD.getValue(1); 8814 } 8815 8816 // Transform as necessary 8817 SDValue CWD1 = 8818 DAG.getNode(ISD::AND, dl, MVT::i32, 8819 CWD, DAG.getConstant(3, dl, MVT::i32)); 8820 SDValue CWD2 = 8821 DAG.getNode(ISD::SRL, dl, MVT::i32, 8822 DAG.getNode(ISD::AND, dl, MVT::i32, 8823 DAG.getNode(ISD::XOR, dl, MVT::i32, 8824 CWD, DAG.getConstant(3, dl, MVT::i32)), 8825 DAG.getConstant(3, dl, MVT::i32)), 8826 DAG.getConstant(1, dl, MVT::i32)); 8827 8828 SDValue RetVal = 8829 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); 8830 8831 RetVal = 8832 DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), 8833 dl, VT, RetVal); 8834 8835 return DAG.getMergeValues({RetVal, Chain}, dl); 8836 } 8837 8838 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8839 EVT VT = Op.getValueType(); 8840 unsigned BitWidth = VT.getSizeInBits(); 8841 SDLoc dl(Op); 8842 assert(Op.getNumOperands() == 3 && 8843 VT == Op.getOperand(1).getValueType() && 8844 "Unexpected SHL!"); 8845 8846 // Expand into a bunch of logical ops. Note that these ops 8847 // depend on the PPC behavior for oversized shift amounts. 8848 SDValue Lo = Op.getOperand(0); 8849 SDValue Hi = Op.getOperand(1); 8850 SDValue Amt = Op.getOperand(2); 8851 EVT AmtVT = Amt.getValueType(); 8852 8853 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8854 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8855 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); 8856 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); 8857 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); 8858 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8859 DAG.getConstant(-BitWidth, dl, AmtVT)); 8860 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); 8861 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8862 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); 8863 SDValue OutOps[] = { OutLo, OutHi }; 8864 return DAG.getMergeValues(OutOps, dl); 8865 } 8866 8867 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { 8868 EVT VT = Op.getValueType(); 8869 SDLoc dl(Op); 8870 unsigned BitWidth = VT.getSizeInBits(); 8871 assert(Op.getNumOperands() == 3 && 8872 VT == Op.getOperand(1).getValueType() && 8873 "Unexpected SRL!"); 8874 8875 // Expand into a bunch of logical ops. Note that these ops 8876 // depend on the PPC behavior for oversized shift amounts. 8877 SDValue Lo = Op.getOperand(0); 8878 SDValue Hi = Op.getOperand(1); 8879 SDValue Amt = Op.getOperand(2); 8880 EVT AmtVT = Amt.getValueType(); 8881 8882 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8883 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8884 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8885 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8886 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8887 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8888 DAG.getConstant(-BitWidth, dl, AmtVT)); 8889 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); 8890 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); 8891 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); 8892 SDValue OutOps[] = { OutLo, OutHi }; 8893 return DAG.getMergeValues(OutOps, dl); 8894 } 8895 8896 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { 8897 SDLoc dl(Op); 8898 EVT VT = Op.getValueType(); 8899 unsigned BitWidth = VT.getSizeInBits(); 8900 assert(Op.getNumOperands() == 3 && 8901 VT == Op.getOperand(1).getValueType() && 8902 "Unexpected SRA!"); 8903 8904 // Expand into a bunch of logical ops, followed by a select_cc. 8905 SDValue Lo = Op.getOperand(0); 8906 SDValue Hi = Op.getOperand(1); 8907 SDValue Amt = Op.getOperand(2); 8908 EVT AmtVT = Amt.getValueType(); 8909 8910 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, 8911 DAG.getConstant(BitWidth, dl, AmtVT), Amt); 8912 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); 8913 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); 8914 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); 8915 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, 8916 DAG.getConstant(-BitWidth, dl, AmtVT)); 8917 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); 8918 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); 8919 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), 8920 Tmp4, Tmp6, ISD::SETLE); 8921 SDValue OutOps[] = { OutLo, OutHi }; 8922 return DAG.getMergeValues(OutOps, dl); 8923 } 8924 8925 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op, 8926 SelectionDAG &DAG) const { 8927 SDLoc dl(Op); 8928 EVT VT = Op.getValueType(); 8929 unsigned BitWidth = VT.getSizeInBits(); 8930 8931 bool IsFSHL = Op.getOpcode() == ISD::FSHL; 8932 SDValue X = Op.getOperand(0); 8933 SDValue Y = Op.getOperand(1); 8934 SDValue Z = Op.getOperand(2); 8935 EVT AmtVT = Z.getValueType(); 8936 8937 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 8938 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 8939 // This is simpler than TargetLowering::expandFunnelShift because we can rely 8940 // on PowerPC shift by BW being well defined. 8941 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z, 8942 DAG.getConstant(BitWidth - 1, dl, AmtVT)); 8943 SDValue SubZ = 8944 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z); 8945 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ); 8946 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z); 8947 return DAG.getNode(ISD::OR, dl, VT, X, Y); 8948 } 8949 8950 //===----------------------------------------------------------------------===// 8951 // Vector related lowering. 8952 // 8953 8954 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an 8955 /// element size of SplatSize. Cast the result to VT. 8956 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, 8957 SelectionDAG &DAG, const SDLoc &dl) { 8958 static const MVT VTys[] = { // canonical VT to use for each size. 8959 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 8960 }; 8961 8962 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; 8963 8964 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize. 8965 if (Val == ((1LLU << (SplatSize * 8)) - 1)) { 8966 SplatSize = 1; 8967 Val = 0xFF; 8968 } 8969 8970 EVT CanonicalVT = VTys[SplatSize-1]; 8971 8972 // Build a canonical splat for this value. 8973 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT)); 8974 } 8975 8976 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the 8977 /// specified intrinsic ID. 8978 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, 8979 const SDLoc &dl, EVT DestVT = MVT::Other) { 8980 if (DestVT == MVT::Other) DestVT = Op.getValueType(); 8981 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8982 DAG.getConstant(IID, dl, MVT::i32), Op); 8983 } 8984 8985 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the 8986 /// specified intrinsic ID. 8987 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, 8988 SelectionDAG &DAG, const SDLoc &dl, 8989 EVT DestVT = MVT::Other) { 8990 if (DestVT == MVT::Other) DestVT = LHS.getValueType(); 8991 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 8992 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); 8993 } 8994 8995 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the 8996 /// specified intrinsic ID. 8997 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, 8998 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl, 8999 EVT DestVT = MVT::Other) { 9000 if (DestVT == MVT::Other) DestVT = Op0.getValueType(); 9001 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, 9002 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); 9003 } 9004 9005 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified 9006 /// amount. The result has the specified value type. 9007 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, 9008 SelectionDAG &DAG, const SDLoc &dl) { 9009 // Force LHS/RHS to be the right type. 9010 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); 9011 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); 9012 9013 int Ops[16]; 9014 for (unsigned i = 0; i != 16; ++i) 9015 Ops[i] = i + Amt; 9016 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); 9017 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9018 } 9019 9020 /// Do we have an efficient pattern in a .td file for this node? 9021 /// 9022 /// \param V - pointer to the BuildVectorSDNode being matched 9023 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves? 9024 /// 9025 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR 9026 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where 9027 /// the opposite is true (expansion is beneficial) are: 9028 /// - The node builds a vector out of integers that are not 32 or 64-bits 9029 /// - The node builds a vector out of constants 9030 /// - The node is a "load-and-splat" 9031 /// In all other cases, we will choose to keep the BUILD_VECTOR. 9032 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, 9033 bool HasDirectMove, 9034 bool HasP8Vector) { 9035 EVT VecVT = V->getValueType(0); 9036 bool RightType = VecVT == MVT::v2f64 || 9037 (HasP8Vector && VecVT == MVT::v4f32) || 9038 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32)); 9039 if (!RightType) 9040 return false; 9041 9042 bool IsSplat = true; 9043 bool IsLoad = false; 9044 SDValue Op0 = V->getOperand(0); 9045 9046 // This function is called in a block that confirms the node is not a constant 9047 // splat. So a constant BUILD_VECTOR here means the vector is built out of 9048 // different constants. 9049 if (V->isConstant()) 9050 return false; 9051 for (int i = 0, e = V->getNumOperands(); i < e; ++i) { 9052 if (V->getOperand(i).isUndef()) 9053 return false; 9054 // We want to expand nodes that represent load-and-splat even if the 9055 // loaded value is a floating point truncation or conversion to int. 9056 if (V->getOperand(i).getOpcode() == ISD::LOAD || 9057 (V->getOperand(i).getOpcode() == ISD::FP_ROUND && 9058 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9059 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT && 9060 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) || 9061 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT && 9062 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD)) 9063 IsLoad = true; 9064 // If the operands are different or the input is not a load and has more 9065 // uses than just this BV node, then it isn't a splat. 9066 if (V->getOperand(i) != Op0 || 9067 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode()))) 9068 IsSplat = false; 9069 } 9070 return !(IsSplat && IsLoad); 9071 } 9072 9073 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128. 9074 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const { 9075 9076 SDLoc dl(Op); 9077 SDValue Op0 = Op->getOperand(0); 9078 9079 if ((Op.getValueType() != MVT::f128) || 9080 (Op0.getOpcode() != ISD::BUILD_PAIR) || 9081 (Op0.getOperand(0).getValueType() != MVT::i64) || 9082 (Op0.getOperand(1).getValueType() != MVT::i64)) 9083 return SDValue(); 9084 9085 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0), 9086 Op0.getOperand(1)); 9087 } 9088 9089 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) { 9090 const SDValue *InputLoad = &Op; 9091 while (InputLoad->getOpcode() == ISD::BITCAST) 9092 InputLoad = &InputLoad->getOperand(0); 9093 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR || 9094 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) { 9095 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED; 9096 InputLoad = &InputLoad->getOperand(0); 9097 } 9098 if (InputLoad->getOpcode() != ISD::LOAD) 9099 return nullptr; 9100 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9101 return ISD::isNormalLoad(LD) ? InputLoad : nullptr; 9102 } 9103 9104 // Convert the argument APFloat to a single precision APFloat if there is no 9105 // loss in information during the conversion to single precision APFloat and the 9106 // resulting number is not a denormal number. Return true if successful. 9107 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) { 9108 APFloat APFloatToConvert = ArgAPFloat; 9109 bool LosesInfo = true; 9110 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9111 &LosesInfo); 9112 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal()); 9113 if (Success) 9114 ArgAPFloat = APFloatToConvert; 9115 return Success; 9116 } 9117 9118 // Bitcast the argument APInt to a double and convert it to a single precision 9119 // APFloat, bitcast the APFloat to an APInt and assign it to the original 9120 // argument if there is no loss in information during the conversion from 9121 // double to single precision APFloat and the resulting number is not a denormal 9122 // number. Return true if successful. 9123 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) { 9124 double DpValue = ArgAPInt.bitsToDouble(); 9125 APFloat APFloatDp(DpValue); 9126 bool Success = convertToNonDenormSingle(APFloatDp); 9127 if (Success) 9128 ArgAPInt = APFloatDp.bitcastToAPInt(); 9129 return Success; 9130 } 9131 9132 // Nondestructive check for convertTonNonDenormSingle. 9133 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) { 9134 // Only convert if it loses info, since XXSPLTIDP should 9135 // handle the other case. 9136 APFloat APFloatToConvert = ArgAPFloat; 9137 bool LosesInfo = true; 9138 APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, 9139 &LosesInfo); 9140 9141 return (!LosesInfo && !APFloatToConvert.isDenormal()); 9142 } 9143 9144 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, 9145 unsigned &Opcode) { 9146 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0)); 9147 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode)) 9148 return false; 9149 9150 EVT Ty = Op->getValueType(0); 9151 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending 9152 // as we cannot handle extending loads for these types. 9153 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) && 9154 ISD::isNON_EXTLoad(InputNode)) 9155 return true; 9156 9157 EVT MemVT = InputNode->getMemoryVT(); 9158 // For v8i16 and v16i8 types, extending loads can be handled as long as the 9159 // memory VT is the same vector element VT type. 9160 // The loads feeding into the v8i16 and v16i8 types will be extending because 9161 // scalar i8/i16 are not legal types. 9162 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) && 9163 (MemVT == Ty.getVectorElementType())) 9164 return true; 9165 9166 if (Ty == MVT::v2i64) { 9167 // Check the extend type, when the input type is i32, and the output vector 9168 // type is v2i64. 9169 if (MemVT == MVT::i32) { 9170 if (ISD::isZEXTLoad(InputNode)) 9171 Opcode = PPCISD::ZEXT_LD_SPLAT; 9172 if (ISD::isSEXTLoad(InputNode)) 9173 Opcode = PPCISD::SEXT_LD_SPLAT; 9174 } 9175 return true; 9176 } 9177 return false; 9178 } 9179 9180 // If this is a case we can't handle, return null and let the default 9181 // expansion code take care of it. If we CAN select this case, and if it 9182 // selects to a single instruction, return Op. Otherwise, if we can codegen 9183 // this case more efficiently than a constant pool load, lower it to the 9184 // sequence of ops that should be used. 9185 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, 9186 SelectionDAG &DAG) const { 9187 SDLoc dl(Op); 9188 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 9189 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); 9190 9191 // Check if this is a splat of a constant value. 9192 APInt APSplatBits, APSplatUndef; 9193 unsigned SplatBitSize; 9194 bool HasAnyUndefs; 9195 bool BVNIsConstantSplat = 9196 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, 9197 HasAnyUndefs, 0, !Subtarget.isLittleEndian()); 9198 9199 // If it is a splat of a double, check if we can shrink it to a 32 bit 9200 // non-denormal float which when converted back to double gives us the same 9201 // double. This is to exploit the XXSPLTIDP instruction. 9202 // If we lose precision, we use XXSPLTI32DX. 9203 if (BVNIsConstantSplat && (SplatBitSize == 64) && 9204 Subtarget.hasPrefixInstrs()) { 9205 // Check the type first to short-circuit so we don't modify APSplatBits if 9206 // this block isn't executed. 9207 if ((Op->getValueType(0) == MVT::v2f64) && 9208 convertToNonDenormSingle(APSplatBits)) { 9209 SDValue SplatNode = DAG.getNode( 9210 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64, 9211 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32)); 9212 return DAG.getBitcast(Op.getValueType(), SplatNode); 9213 } else { 9214 // We may lose precision, so we have to use XXSPLTI32DX. 9215 9216 uint32_t Hi = 9217 (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32); 9218 uint32_t Lo = 9219 (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF); 9220 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64); 9221 9222 if (!Hi || !Lo) 9223 // If either load is 0, then we should generate XXLXOR to set to 0. 9224 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64); 9225 9226 if (Hi) 9227 SplatNode = DAG.getNode( 9228 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9229 DAG.getTargetConstant(0, dl, MVT::i32), 9230 DAG.getTargetConstant(Hi, dl, MVT::i32)); 9231 9232 if (Lo) 9233 SplatNode = 9234 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode, 9235 DAG.getTargetConstant(1, dl, MVT::i32), 9236 DAG.getTargetConstant(Lo, dl, MVT::i32)); 9237 9238 return DAG.getBitcast(Op.getValueType(), SplatNode); 9239 } 9240 } 9241 9242 if (!BVNIsConstantSplat || SplatBitSize > 32) { 9243 unsigned NewOpcode = PPCISD::LD_SPLAT; 9244 9245 // Handle load-and-splat patterns as we have instructions that will do this 9246 // in one go. 9247 if (DAG.isSplatValue(Op, true) && 9248 isValidSplatLoad(Subtarget, Op, NewOpcode)) { 9249 const SDValue *InputLoad = &Op.getOperand(0); 9250 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9251 9252 // If the input load is an extending load, it will be an i32 -> i64 9253 // extending load and isValidSplatLoad() will update NewOpcode. 9254 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits(); 9255 unsigned ElementSize = 9256 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2); 9257 9258 assert(((ElementSize == 2 * MemorySize) 9259 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT || 9260 NewOpcode == PPCISD::SEXT_LD_SPLAT) 9261 : (NewOpcode == PPCISD::LD_SPLAT)) && 9262 "Unmatched element size and opcode!\n"); 9263 9264 // Checking for a single use of this load, we have to check for vector 9265 // width (128 bits) / ElementSize uses (since each operand of the 9266 // BUILD_VECTOR is a separate use of the value. 9267 unsigned NumUsesOfInputLD = 128 / ElementSize; 9268 for (SDValue BVInOp : Op->ops()) 9269 if (BVInOp.isUndef()) 9270 NumUsesOfInputLD--; 9271 9272 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector: 9273 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index 9274 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index 9275 // 15", but funciton IsValidSplatLoad() now will only return true when 9276 // the data at index 0 is not nullptr. So we will not get into trouble for 9277 // these cases. 9278 // 9279 // case 1 - lfiwzx/lfiwax 9280 // 1.1: load result is i32 and is sign/zero extend to i64; 9281 // 1.2: build a v2i64 vector type with above loaded value; 9282 // 1.3: the vector has only one value at index 0, others are all undef; 9283 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute. 9284 if (NumUsesOfInputLD == 1 && 9285 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT && 9286 !Subtarget.isLittleEndian() && Subtarget.hasVSX() && 9287 Subtarget.hasLFIWAX())) 9288 return SDValue(); 9289 9290 // case 2 - lxvr[hb]x 9291 // 2.1: load result is at most i16; 9292 // 2.2: build a vector with above loaded value; 9293 // 2.3: the vector has only one value at index 0, others are all undef; 9294 // 2.4: on LE target, so that lxvr[hb]x does not need any permute. 9295 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() && 9296 Subtarget.isISA3_1() && ElementSize <= 16) 9297 return SDValue(); 9298 9299 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?"); 9300 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) && 9301 Subtarget.hasVSX()) { 9302 SDValue Ops[] = { 9303 LD->getChain(), // Chain 9304 LD->getBasePtr(), // Ptr 9305 DAG.getValueType(Op.getValueType()) // VT 9306 }; 9307 SDValue LdSplt = DAG.getMemIntrinsicNode( 9308 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops, 9309 LD->getMemoryVT(), LD->getMemOperand()); 9310 // Replace all uses of the output chain of the original load with the 9311 // output chain of the new load. 9312 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), 9313 LdSplt.getValue(1)); 9314 return LdSplt; 9315 } 9316 } 9317 9318 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to 9319 // 32-bits can be lowered to VSX instructions under certain conditions. 9320 // Without VSX, there is no pattern more efficient than expanding the node. 9321 if (Subtarget.hasVSX() && Subtarget.isPPC64() && 9322 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(), 9323 Subtarget.hasP8Vector())) 9324 return Op; 9325 return SDValue(); 9326 } 9327 9328 uint64_t SplatBits = APSplatBits.getZExtValue(); 9329 uint64_t SplatUndef = APSplatUndef.getZExtValue(); 9330 unsigned SplatSize = SplatBitSize / 8; 9331 9332 // First, handle single instruction cases. 9333 9334 // All zeros? 9335 if (SplatBits == 0) { 9336 // Canonicalize all zero vectors to be v4i32. 9337 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { 9338 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32); 9339 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); 9340 } 9341 return Op; 9342 } 9343 9344 // We have XXSPLTIW for constant splats four bytes wide. 9345 // Given vector length is a multiple of 4, 2-byte splats can be replaced 9346 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to 9347 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be 9348 // turned into a 4-byte splat of 0xABABABAB. 9349 if (Subtarget.hasPrefixInstrs() && SplatSize == 2) 9350 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2, 9351 Op.getValueType(), DAG, dl); 9352 9353 if (Subtarget.hasPrefixInstrs() && SplatSize == 4) 9354 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9355 dl); 9356 9357 // We have XXSPLTIB for constant splats one byte wide. 9358 if (Subtarget.hasP9Vector() && SplatSize == 1) 9359 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG, 9360 dl); 9361 9362 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. 9363 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> 9364 (32-SplatBitSize)); 9365 if (SextVal >= -16 && SextVal <= 15) 9366 return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG, 9367 dl); 9368 9369 // Two instruction sequences. 9370 9371 // If this value is in the range [-32,30] and is even, use: 9372 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) 9373 // If this value is in the range [17,31] and is odd, use: 9374 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) 9375 // If this value is in the range [-31,-17] and is odd, use: 9376 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) 9377 // Note the last two are three-instruction sequences. 9378 if (SextVal >= -32 && SextVal <= 31) { 9379 // To avoid having these optimizations undone by constant folding, 9380 // we convert to a pseudo that will be expanded later into one of 9381 // the above forms. 9382 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); 9383 EVT VT = (SplatSize == 1 ? MVT::v16i8 : 9384 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); 9385 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); 9386 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); 9387 if (VT == Op.getValueType()) 9388 return RetVal; 9389 else 9390 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); 9391 } 9392 9393 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is 9394 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important 9395 // for fneg/fabs. 9396 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { 9397 // Make -1 and vspltisw -1: 9398 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl); 9399 9400 // Make the VSLW intrinsic, computing 0x8000_0000. 9401 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, 9402 OnesV, DAG, dl); 9403 9404 // xor by OnesV to invert it. 9405 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); 9406 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9407 } 9408 9409 // Check to see if this is a wide variety of vsplti*, binop self cases. 9410 static const signed char SplatCsts[] = { 9411 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, 9412 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 9413 }; 9414 9415 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) { 9416 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for 9417 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' 9418 int i = SplatCsts[idx]; 9419 9420 // Figure out what shift amount will be used by altivec if shifted by i in 9421 // this splat size. 9422 unsigned TypeShiftAmt = i & (SplatBitSize-1); 9423 9424 // vsplti + shl self. 9425 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { 9426 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9427 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9428 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, 9429 Intrinsic::ppc_altivec_vslw 9430 }; 9431 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9432 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9433 } 9434 9435 // vsplti + srl self. 9436 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { 9437 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9438 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9439 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, 9440 Intrinsic::ppc_altivec_vsrw 9441 }; 9442 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9443 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9444 } 9445 9446 // vsplti + rol self. 9447 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | 9448 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { 9449 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl); 9450 static const unsigned IIDs[] = { // Intrinsic to use for each size. 9451 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, 9452 Intrinsic::ppc_altivec_vrlw 9453 }; 9454 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); 9455 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); 9456 } 9457 9458 // t = vsplti c, result = vsldoi t, t, 1 9459 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { 9460 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9461 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; 9462 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9463 } 9464 // t = vsplti c, result = vsldoi t, t, 2 9465 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { 9466 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9467 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; 9468 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9469 } 9470 // t = vsplti c, result = vsldoi t, t, 3 9471 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { 9472 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl); 9473 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; 9474 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); 9475 } 9476 } 9477 9478 return SDValue(); 9479 } 9480 9481 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 9482 /// the specified operations to build the shuffle. 9483 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 9484 SDValue RHS, SelectionDAG &DAG, 9485 const SDLoc &dl) { 9486 unsigned OpNum = (PFEntry >> 26) & 0x0F; 9487 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); 9488 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); 9489 9490 enum { 9491 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 9492 OP_VMRGHW, 9493 OP_VMRGLW, 9494 OP_VSPLTISW0, 9495 OP_VSPLTISW1, 9496 OP_VSPLTISW2, 9497 OP_VSPLTISW3, 9498 OP_VSLDOI4, 9499 OP_VSLDOI8, 9500 OP_VSLDOI12 9501 }; 9502 9503 if (OpNum == OP_COPY) { 9504 if (LHSID == (1*9+2)*9+3) return LHS; 9505 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); 9506 return RHS; 9507 } 9508 9509 SDValue OpLHS, OpRHS; 9510 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 9511 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 9512 9513 int ShufIdxs[16]; 9514 switch (OpNum) { 9515 default: llvm_unreachable("Unknown i32 permute!"); 9516 case OP_VMRGHW: 9517 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; 9518 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; 9519 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; 9520 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; 9521 break; 9522 case OP_VMRGLW: 9523 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; 9524 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; 9525 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; 9526 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; 9527 break; 9528 case OP_VSPLTISW0: 9529 for (unsigned i = 0; i != 16; ++i) 9530 ShufIdxs[i] = (i&3)+0; 9531 break; 9532 case OP_VSPLTISW1: 9533 for (unsigned i = 0; i != 16; ++i) 9534 ShufIdxs[i] = (i&3)+4; 9535 break; 9536 case OP_VSPLTISW2: 9537 for (unsigned i = 0; i != 16; ++i) 9538 ShufIdxs[i] = (i&3)+8; 9539 break; 9540 case OP_VSPLTISW3: 9541 for (unsigned i = 0; i != 16; ++i) 9542 ShufIdxs[i] = (i&3)+12; 9543 break; 9544 case OP_VSLDOI4: 9545 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); 9546 case OP_VSLDOI8: 9547 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); 9548 case OP_VSLDOI12: 9549 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); 9550 } 9551 EVT VT = OpLHS.getValueType(); 9552 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); 9553 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); 9554 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); 9555 return DAG.getNode(ISD::BITCAST, dl, VT, T); 9556 } 9557 9558 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled 9559 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default 9560 /// SDValue. 9561 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N, 9562 SelectionDAG &DAG) const { 9563 const unsigned BytesInVector = 16; 9564 bool IsLE = Subtarget.isLittleEndian(); 9565 SDLoc dl(N); 9566 SDValue V1 = N->getOperand(0); 9567 SDValue V2 = N->getOperand(1); 9568 unsigned ShiftElts = 0, InsertAtByte = 0; 9569 bool Swap = false; 9570 9571 // Shifts required to get the byte we want at element 7. 9572 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1, 9573 0, 15, 14, 13, 12, 11, 10, 9}; 9574 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0, 9575 1, 2, 3, 4, 5, 6, 7, 8}; 9576 9577 ArrayRef<int> Mask = N->getMask(); 9578 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 9579 9580 // For each mask element, find out if we're just inserting something 9581 // from V2 into V1 or vice versa. 9582 // Possible permutations inserting an element from V2 into V1: 9583 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9584 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 9585 // ... 9586 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X 9587 // Inserting from V1 into V2 will be similar, except mask range will be 9588 // [16,31]. 9589 9590 bool FoundCandidate = false; 9591 // If both vector operands for the shuffle are the same vector, the mask 9592 // will contain only elements from the first one and the second one will be 9593 // undef. 9594 unsigned VINSERTBSrcElem = IsLE ? 8 : 7; 9595 // Go through the mask of half-words to find an element that's being moved 9596 // from one vector to the other. 9597 for (unsigned i = 0; i < BytesInVector; ++i) { 9598 unsigned CurrentElement = Mask[i]; 9599 // If 2nd operand is undefined, we should only look for element 7 in the 9600 // Mask. 9601 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem) 9602 continue; 9603 9604 bool OtherElementsInOrder = true; 9605 // Examine the other elements in the Mask to see if they're in original 9606 // order. 9607 for (unsigned j = 0; j < BytesInVector; ++j) { 9608 if (j == i) 9609 continue; 9610 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be 9611 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined, 9612 // in which we always assume we're always picking from the 1st operand. 9613 int MaskOffset = 9614 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0; 9615 if (Mask[j] != OriginalOrder[j] + MaskOffset) { 9616 OtherElementsInOrder = false; 9617 break; 9618 } 9619 } 9620 // If other elements are in original order, we record the number of shifts 9621 // we need to get the element we want into element 7. Also record which byte 9622 // in the vector we should insert into. 9623 if (OtherElementsInOrder) { 9624 // If 2nd operand is undefined, we assume no shifts and no swapping. 9625 if (V2.isUndef()) { 9626 ShiftElts = 0; 9627 Swap = false; 9628 } else { 9629 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4. 9630 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF] 9631 : BigEndianShifts[CurrentElement & 0xF]; 9632 Swap = CurrentElement < BytesInVector; 9633 } 9634 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i; 9635 FoundCandidate = true; 9636 break; 9637 } 9638 } 9639 9640 if (!FoundCandidate) 9641 return SDValue(); 9642 9643 // Candidate found, construct the proper SDAG sequence with VINSERTB, 9644 // optionally with VECSHL if shift is required. 9645 if (Swap) 9646 std::swap(V1, V2); 9647 if (V2.isUndef()) 9648 V2 = V1; 9649 if (ShiftElts) { 9650 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9651 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9652 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl, 9653 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9654 } 9655 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2, 9656 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9657 } 9658 9659 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled 9660 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default 9661 /// SDValue. 9662 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N, 9663 SelectionDAG &DAG) const { 9664 const unsigned NumHalfWords = 8; 9665 const unsigned BytesInVector = NumHalfWords * 2; 9666 // Check that the shuffle is on half-words. 9667 if (!isNByteElemShuffleMask(N, 2, 1)) 9668 return SDValue(); 9669 9670 bool IsLE = Subtarget.isLittleEndian(); 9671 SDLoc dl(N); 9672 SDValue V1 = N->getOperand(0); 9673 SDValue V2 = N->getOperand(1); 9674 unsigned ShiftElts = 0, InsertAtByte = 0; 9675 bool Swap = false; 9676 9677 // Shifts required to get the half-word we want at element 3. 9678 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5}; 9679 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4}; 9680 9681 uint32_t Mask = 0; 9682 uint32_t OriginalOrderLow = 0x1234567; 9683 uint32_t OriginalOrderHigh = 0x89ABCDEF; 9684 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a 9685 // 32-bit space, only need 4-bit nibbles per element. 9686 for (unsigned i = 0; i < NumHalfWords; ++i) { 9687 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9688 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift); 9689 } 9690 9691 // For each mask element, find out if we're just inserting something 9692 // from V2 into V1 or vice versa. Possible permutations inserting an element 9693 // from V2 into V1: 9694 // X, 1, 2, 3, 4, 5, 6, 7 9695 // 0, X, 2, 3, 4, 5, 6, 7 9696 // 0, 1, X, 3, 4, 5, 6, 7 9697 // 0, 1, 2, X, 4, 5, 6, 7 9698 // 0, 1, 2, 3, X, 5, 6, 7 9699 // 0, 1, 2, 3, 4, X, 6, 7 9700 // 0, 1, 2, 3, 4, 5, X, 7 9701 // 0, 1, 2, 3, 4, 5, 6, X 9702 // Inserting from V1 into V2 will be similar, except mask range will be [8,15]. 9703 9704 bool FoundCandidate = false; 9705 // Go through the mask of half-words to find an element that's being moved 9706 // from one vector to the other. 9707 for (unsigned i = 0; i < NumHalfWords; ++i) { 9708 unsigned MaskShift = (NumHalfWords - 1 - i) * 4; 9709 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF; 9710 uint32_t MaskOtherElts = ~(0xF << MaskShift); 9711 uint32_t TargetOrder = 0x0; 9712 9713 // If both vector operands for the shuffle are the same vector, the mask 9714 // will contain only elements from the first one and the second one will be 9715 // undef. 9716 if (V2.isUndef()) { 9717 ShiftElts = 0; 9718 unsigned VINSERTHSrcElem = IsLE ? 4 : 3; 9719 TargetOrder = OriginalOrderLow; 9720 Swap = false; 9721 // Skip if not the correct element or mask of other elements don't equal 9722 // to our expected order. 9723 if (MaskOneElt == VINSERTHSrcElem && 9724 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9725 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9726 FoundCandidate = true; 9727 break; 9728 } 9729 } else { // If both operands are defined. 9730 // Target order is [8,15] if the current mask is between [0,7]. 9731 TargetOrder = 9732 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow; 9733 // Skip if mask of other elements don't equal our expected order. 9734 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) { 9735 // We only need the last 3 bits for the number of shifts. 9736 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7] 9737 : BigEndianShifts[MaskOneElt & 0x7]; 9738 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2; 9739 Swap = MaskOneElt < NumHalfWords; 9740 FoundCandidate = true; 9741 break; 9742 } 9743 } 9744 } 9745 9746 if (!FoundCandidate) 9747 return SDValue(); 9748 9749 // Candidate found, construct the proper SDAG sequence with VINSERTH, 9750 // optionally with VECSHL if shift is required. 9751 if (Swap) 9752 std::swap(V1, V2); 9753 if (V2.isUndef()) 9754 V2 = V1; 9755 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 9756 if (ShiftElts) { 9757 // Double ShiftElts because we're left shifting on v16i8 type. 9758 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2, 9759 DAG.getConstant(2 * ShiftElts, dl, MVT::i32)); 9760 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl); 9761 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9762 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9763 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9764 } 9765 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2); 9766 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2, 9767 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9768 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9769 } 9770 9771 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be 9772 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise 9773 /// return the default SDValue. 9774 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN, 9775 SelectionDAG &DAG) const { 9776 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles 9777 // to v16i8. Peek through the bitcasts to get the actual operands. 9778 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0)); 9779 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1)); 9780 9781 auto ShuffleMask = SVN->getMask(); 9782 SDValue VecShuffle(SVN, 0); 9783 SDLoc DL(SVN); 9784 9785 // Check that we have a four byte shuffle. 9786 if (!isNByteElemShuffleMask(SVN, 4, 1)) 9787 return SDValue(); 9788 9789 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx. 9790 if (RHS->getOpcode() != ISD::BUILD_VECTOR) { 9791 std::swap(LHS, RHS); 9792 VecShuffle = peekThroughBitcasts(DAG.getCommutedVectorShuffle(*SVN)); 9793 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle); 9794 if (!CommutedSV) 9795 return SDValue(); 9796 ShuffleMask = CommutedSV->getMask(); 9797 } 9798 9799 // Ensure that the RHS is a vector of constants. 9800 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 9801 if (!BVN) 9802 return SDValue(); 9803 9804 // Check if RHS is a splat of 4-bytes (or smaller). 9805 APInt APSplatValue, APSplatUndef; 9806 unsigned SplatBitSize; 9807 bool HasAnyUndefs; 9808 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize, 9809 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || 9810 SplatBitSize > 32) 9811 return SDValue(); 9812 9813 // Check that the shuffle mask matches the semantics of XXSPLTI32DX. 9814 // The instruction splats a constant C into two words of the source vector 9815 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }. 9816 // Thus we check that the shuffle mask is the equivalent of 9817 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively. 9818 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes 9819 // within each word are consecutive, so we only need to check the first byte. 9820 SDValue Index; 9821 bool IsLE = Subtarget.isLittleEndian(); 9822 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) && 9823 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 && 9824 ShuffleMask[4] > 15 && ShuffleMask[12] > 15)) 9825 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32); 9826 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) && 9827 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 && 9828 ShuffleMask[0] > 15 && ShuffleMask[8] > 15)) 9829 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32); 9830 else 9831 return SDValue(); 9832 9833 // If the splat is narrower than 32-bits, we need to get the 32-bit value 9834 // for XXSPLTI32DX. 9835 unsigned SplatVal = APSplatValue.getZExtValue(); 9836 for (; SplatBitSize < 32; SplatBitSize <<= 1) 9837 SplatVal |= (SplatVal << SplatBitSize); 9838 9839 SDValue SplatNode = DAG.getNode( 9840 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS), 9841 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32)); 9842 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode); 9843 } 9844 9845 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8). 9846 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is 9847 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128) 9848 /// i.e (or (shl x, C1), (srl x, 128-C1)). 9849 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const { 9850 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL"); 9851 assert(Op.getValueType() == MVT::v1i128 && 9852 "Only set v1i128 as custom, other type shouldn't reach here!"); 9853 SDLoc dl(Op); 9854 SDValue N0 = peekThroughBitcasts(Op.getOperand(0)); 9855 SDValue N1 = peekThroughBitcasts(Op.getOperand(1)); 9856 unsigned SHLAmt = N1.getConstantOperandVal(0); 9857 if (SHLAmt % 8 == 0) { 9858 std::array<int, 16> Mask; 9859 std::iota(Mask.begin(), Mask.end(), 0); 9860 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end()); 9861 if (SDValue Shuffle = 9862 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0), 9863 DAG.getUNDEF(MVT::v16i8), Mask)) 9864 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle); 9865 } 9866 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0); 9867 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal, 9868 DAG.getConstant(SHLAmt, dl, MVT::i32)); 9869 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal, 9870 DAG.getConstant(128 - SHLAmt, dl, MVT::i32)); 9871 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp); 9872 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp); 9873 } 9874 9875 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this 9876 /// is a shuffle we can handle in a single instruction, return it. Otherwise, 9877 /// return the code it can be lowered into. Worst case, it can always be 9878 /// lowered into a vperm. 9879 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 9880 SelectionDAG &DAG) const { 9881 SDLoc dl(Op); 9882 SDValue V1 = Op.getOperand(0); 9883 SDValue V2 = Op.getOperand(1); 9884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 9885 9886 // Any nodes that were combined in the target-independent combiner prior 9887 // to vector legalization will not be sent to the target combine. Try to 9888 // combine it here. 9889 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) { 9890 if (!isa<ShuffleVectorSDNode>(NewShuffle)) 9891 return NewShuffle; 9892 Op = NewShuffle; 9893 SVOp = cast<ShuffleVectorSDNode>(Op); 9894 V1 = Op.getOperand(0); 9895 V2 = Op.getOperand(1); 9896 } 9897 EVT VT = Op.getValueType(); 9898 bool isLittleEndian = Subtarget.isLittleEndian(); 9899 9900 unsigned ShiftElts, InsertAtByte; 9901 bool Swap = false; 9902 9903 // If this is a load-and-splat, we can do that with a single instruction 9904 // in some cases. However if the load has multiple uses, we don't want to 9905 // combine it because that will just produce multiple loads. 9906 bool IsPermutedLoad = false; 9907 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad); 9908 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() && 9909 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) && 9910 InputLoad->hasOneUse()) { 9911 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4); 9912 int SplatIdx = 9913 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG); 9914 9915 // The splat index for permuted loads will be in the left half of the vector 9916 // which is strictly wider than the loaded value by 8 bytes. So we need to 9917 // adjust the splat index to point to the correct address in memory. 9918 if (IsPermutedLoad) { 9919 assert((isLittleEndian || IsFourByte) && 9920 "Unexpected size for permuted load on big endian target"); 9921 SplatIdx += IsFourByte ? 2 : 1; 9922 assert((SplatIdx < (IsFourByte ? 4 : 2)) && 9923 "Splat of a value outside of the loaded memory"); 9924 } 9925 9926 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad); 9927 // For 4-byte load-and-splat, we need Power9. 9928 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) { 9929 uint64_t Offset = 0; 9930 if (IsFourByte) 9931 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4; 9932 else 9933 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8; 9934 9935 // If the width of the load is the same as the width of the splat, 9936 // loading with an offset would load the wrong memory. 9937 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64)) 9938 Offset = 0; 9939 9940 SDValue BasePtr = LD->getBasePtr(); 9941 if (Offset != 0) 9942 BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()), 9943 BasePtr, DAG.getIntPtrConstant(Offset, dl)); 9944 SDValue Ops[] = { 9945 LD->getChain(), // Chain 9946 BasePtr, // BasePtr 9947 DAG.getValueType(Op.getValueType()) // VT 9948 }; 9949 SDVTList VTL = 9950 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other); 9951 SDValue LdSplt = 9952 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL, 9953 Ops, LD->getMemoryVT(), LD->getMemOperand()); 9954 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1)); 9955 if (LdSplt.getValueType() != SVOp->getValueType(0)) 9956 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt); 9957 return LdSplt; 9958 } 9959 } 9960 9961 // All v2i64 and v2f64 shuffles are legal 9962 if (VT == MVT::v2i64 || VT == MVT::v2f64) 9963 return Op; 9964 9965 if (Subtarget.hasP9Vector() && 9966 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap, 9967 isLittleEndian)) { 9968 if (Swap) 9969 std::swap(V1, V2); 9970 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 9971 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2); 9972 if (ShiftElts) { 9973 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2, 9974 DAG.getConstant(ShiftElts, dl, MVT::i32)); 9975 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl, 9976 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9977 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9978 } 9979 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2, 9980 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 9981 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins); 9982 } 9983 9984 if (Subtarget.hasPrefixInstrs()) { 9985 SDValue SplatInsertNode; 9986 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG))) 9987 return SplatInsertNode; 9988 } 9989 9990 if (Subtarget.hasP9Altivec()) { 9991 SDValue NewISDNode; 9992 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG))) 9993 return NewISDNode; 9994 9995 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG))) 9996 return NewISDNode; 9997 } 9998 9999 if (Subtarget.hasVSX() && 10000 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 10001 if (Swap) 10002 std::swap(V1, V2); 10003 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10004 SDValue Conv2 = 10005 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2); 10006 10007 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2, 10008 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10009 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl); 10010 } 10011 10012 if (Subtarget.hasVSX() && 10013 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) { 10014 if (Swap) 10015 std::swap(V1, V2); 10016 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10017 SDValue Conv2 = 10018 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2); 10019 10020 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2, 10021 DAG.getConstant(ShiftElts, dl, MVT::i32)); 10022 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI); 10023 } 10024 10025 if (Subtarget.hasP9Vector()) { 10026 if (PPC::isXXBRHShuffleMask(SVOp)) { 10027 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1); 10028 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv); 10029 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord); 10030 } else if (PPC::isXXBRWShuffleMask(SVOp)) { 10031 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10032 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv); 10033 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord); 10034 } else if (PPC::isXXBRDShuffleMask(SVOp)) { 10035 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1); 10036 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv); 10037 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord); 10038 } else if (PPC::isXXBRQShuffleMask(SVOp)) { 10039 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1); 10040 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv); 10041 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord); 10042 } 10043 } 10044 10045 if (Subtarget.hasVSX()) { 10046 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) { 10047 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG); 10048 10049 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1); 10050 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv, 10051 DAG.getConstant(SplatIdx, dl, MVT::i32)); 10052 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat); 10053 } 10054 10055 // Left shifts of 8 bytes are actually swaps. Convert accordingly. 10056 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) { 10057 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1); 10058 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv); 10059 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap); 10060 } 10061 } 10062 10063 // Cases that are handled by instructions that take permute immediates 10064 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be 10065 // selected by the instruction selector. 10066 if (V2.isUndef()) { 10067 if (PPC::isSplatShuffleMask(SVOp, 1) || 10068 PPC::isSplatShuffleMask(SVOp, 2) || 10069 PPC::isSplatShuffleMask(SVOp, 4) || 10070 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || 10071 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || 10072 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || 10073 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || 10074 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || 10075 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || 10076 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || 10077 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || 10078 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || 10079 (Subtarget.hasP8Altivec() && ( 10080 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || 10081 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || 10082 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { 10083 return Op; 10084 } 10085 } 10086 10087 // Altivec has a variety of "shuffle immediates" that take two vector inputs 10088 // and produce a fixed permutation. If any of these match, do not lower to 10089 // VPERM. 10090 unsigned int ShuffleKind = isLittleEndian ? 2 : 0; 10091 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || 10092 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || 10093 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || 10094 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10095 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10096 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10097 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || 10098 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || 10099 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || 10100 (Subtarget.hasP8Altivec() && ( 10101 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || 10102 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || 10103 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) 10104 return Op; 10105 10106 // Check to see if this is a shuffle of 4-byte values. If so, we can use our 10107 // perfect shuffle table to emit an optimal matching sequence. 10108 ArrayRef<int> PermMask = SVOp->getMask(); 10109 10110 if (!DisablePerfectShuffle && !isLittleEndian) { 10111 unsigned PFIndexes[4]; 10112 bool isFourElementShuffle = true; 10113 for (unsigned i = 0; i != 4 && isFourElementShuffle; 10114 ++i) { // Element number 10115 unsigned EltNo = 8; // Start out undef. 10116 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. 10117 if (PermMask[i * 4 + j] < 0) 10118 continue; // Undef, ignore it. 10119 10120 unsigned ByteSource = PermMask[i * 4 + j]; 10121 if ((ByteSource & 3) != j) { 10122 isFourElementShuffle = false; 10123 break; 10124 } 10125 10126 if (EltNo == 8) { 10127 EltNo = ByteSource / 4; 10128 } else if (EltNo != ByteSource / 4) { 10129 isFourElementShuffle = false; 10130 break; 10131 } 10132 } 10133 PFIndexes[i] = EltNo; 10134 } 10135 10136 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the 10137 // perfect shuffle vector to determine if it is cost effective to do this as 10138 // discrete instructions, or whether we should use a vperm. 10139 // For now, we skip this for little endian until such time as we have a 10140 // little-endian perfect shuffle table. 10141 if (isFourElementShuffle) { 10142 // Compute the index in the perfect shuffle table. 10143 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 10144 PFIndexes[2] * 9 + PFIndexes[3]; 10145 10146 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 10147 unsigned Cost = (PFEntry >> 30); 10148 10149 // Determining when to avoid vperm is tricky. Many things affect the cost 10150 // of vperm, particularly how many times the perm mask needs to be 10151 // computed. For example, if the perm mask can be hoisted out of a loop or 10152 // is already used (perhaps because there are multiple permutes with the 10153 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the 10154 // permute mask out of the loop requires an extra register. 10155 // 10156 // As a compromise, we only emit discrete instructions if the shuffle can 10157 // be generated in 3 or fewer operations. When we have loop information 10158 // available, if this block is within a loop, we should avoid using vperm 10159 // for 3-operation perms and use a constant pool load instead. 10160 if (Cost < 3) 10161 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 10162 } 10163 } 10164 10165 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant 10166 // vector that will get spilled to the constant pool. 10167 if (V2.isUndef()) V2 = V1; 10168 10169 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2); 10170 } 10171 10172 SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG, 10173 ArrayRef<int> PermMask, EVT VT, 10174 SDValue V1, SDValue V2) const { 10175 unsigned Opcode = PPCISD::VPERM; 10176 EVT ValType = V1.getValueType(); 10177 SDLoc dl(Op); 10178 bool NeedSwap = false; 10179 bool isLittleEndian = Subtarget.isLittleEndian(); 10180 bool isPPC64 = Subtarget.isPPC64(); 10181 10182 // Only need to place items backwards in LE, 10183 // the mask will be properly calculated. 10184 if (isLittleEndian) 10185 std::swap(V1, V2); 10186 10187 if (Subtarget.isISA3_0() && (V1->hasOneUse() || V2->hasOneUse())) { 10188 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using " 10189 "XXPERM instead\n"); 10190 Opcode = PPCISD::XXPERM; 10191 10192 // if V2 is dead, then we swap V1 and V2 so we can 10193 // use V2 as the destination instead. 10194 if (!V1->hasOneUse() && V2->hasOneUse()) { 10195 std::swap(V1, V2); 10196 NeedSwap = !NeedSwap; 10197 } 10198 } 10199 10200 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except 10201 // that it is in input element units, not in bytes. Convert now. 10202 10203 // For little endian, the order of the input vectors is reversed, and 10204 // the permutation mask is complemented with respect to 31. This is 10205 // necessary to produce proper semantics with the big-endian-based vperm 10206 // instruction. 10207 EVT EltVT = V1.getValueType().getVectorElementType(); 10208 unsigned BytesPerElement = EltVT.getSizeInBits() / 8; 10209 10210 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD; 10211 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD; 10212 10213 /* 10214 Vectors will be appended like so: [ V1 | v2 ] 10215 XXSWAPD on V1: 10216 [ A | B | C | D ] -> [ C | D | A | B ] 10217 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15 10218 i.e. index of A, B += 8, and index of C, D -= 8. 10219 XXSWAPD on V2: 10220 [ E | F | G | H ] -> [ G | H | E | F ] 10221 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31 10222 i.e. index of E, F += 8, index of G, H -= 8 10223 Swap V1 and V2: 10224 [ V1 | V2 ] -> [ V2 | V1 ] 10225 0-15 16-31 0-15 16-31 10226 i.e. index of V1 += 16, index of V2 -= 16 10227 */ 10228 10229 SmallVector<SDValue, 16> ResultMask; 10230 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 10231 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; 10232 10233 if (Opcode == PPCISD::XXPERM) { 10234 if (V1HasXXSWAPD) { 10235 if (SrcElt < 8) 10236 SrcElt += 8; 10237 else if (SrcElt < 16) 10238 SrcElt -= 8; 10239 } 10240 if (V2HasXXSWAPD) { 10241 if (SrcElt > 23) 10242 SrcElt -= 8; 10243 else if (SrcElt > 15) 10244 SrcElt += 8; 10245 } 10246 if (NeedSwap) { 10247 if (SrcElt < 16) 10248 SrcElt += 16; 10249 else 10250 SrcElt -= 16; 10251 } 10252 } 10253 10254 for (unsigned j = 0; j != BytesPerElement; ++j) 10255 if (isLittleEndian) 10256 ResultMask.push_back( 10257 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32)); 10258 else 10259 ResultMask.push_back( 10260 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32)); 10261 } 10262 10263 if (Opcode == PPCISD::XXPERM && (V1HasXXSWAPD || V2HasXXSWAPD)) { 10264 if (V1HasXXSWAPD) { 10265 dl = SDLoc(V1->getOperand(0)); 10266 V1 = V1->getOperand(0)->getOperand(1); 10267 } 10268 if (V2HasXXSWAPD) { 10269 dl = SDLoc(V2->getOperand(0)); 10270 V2 = V2->getOperand(0)->getOperand(1); 10271 } 10272 if (isPPC64 && ValType != MVT::v2f64) 10273 V1 = DAG.getBitcast(MVT::v2f64, V1); 10274 if (isPPC64 && V2.getValueType() != MVT::v2f64) 10275 V2 = DAG.getBitcast(MVT::v2f64, V2); 10276 } 10277 10278 ShufflesHandledWithVPERM++; 10279 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask); 10280 LLVM_DEBUG({ 10281 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); 10282 if (Opcode == PPCISD::XXPERM) { 10283 dbgs() << "Emitting a XXPERM for the following shuffle:\n"; 10284 } else { 10285 dbgs() << "Emitting a VPERM for the following shuffle:\n"; 10286 } 10287 SVOp->dump(); 10288 dbgs() << "With the following permute control vector:\n"; 10289 VPermMask.dump(); 10290 }); 10291 10292 if (Opcode == PPCISD::XXPERM) 10293 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask); 10294 10295 SDValue VPERMNode = 10296 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask); 10297 10298 VPERMNode = DAG.getBitcast(ValType, VPERMNode); 10299 return VPERMNode; 10300 } 10301 10302 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a 10303 /// vector comparison. If it is, return true and fill in Opc/isDot with 10304 /// information about the intrinsic. 10305 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, 10306 bool &isDot, const PPCSubtarget &Subtarget) { 10307 unsigned IntrinsicID = 10308 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); 10309 CompareOpc = -1; 10310 isDot = false; 10311 switch (IntrinsicID) { 10312 default: 10313 return false; 10314 // Comparison predicates. 10315 case Intrinsic::ppc_altivec_vcmpbfp_p: 10316 CompareOpc = 966; 10317 isDot = true; 10318 break; 10319 case Intrinsic::ppc_altivec_vcmpeqfp_p: 10320 CompareOpc = 198; 10321 isDot = true; 10322 break; 10323 case Intrinsic::ppc_altivec_vcmpequb_p: 10324 CompareOpc = 6; 10325 isDot = true; 10326 break; 10327 case Intrinsic::ppc_altivec_vcmpequh_p: 10328 CompareOpc = 70; 10329 isDot = true; 10330 break; 10331 case Intrinsic::ppc_altivec_vcmpequw_p: 10332 CompareOpc = 134; 10333 isDot = true; 10334 break; 10335 case Intrinsic::ppc_altivec_vcmpequd_p: 10336 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10337 CompareOpc = 199; 10338 isDot = true; 10339 } else 10340 return false; 10341 break; 10342 case Intrinsic::ppc_altivec_vcmpneb_p: 10343 case Intrinsic::ppc_altivec_vcmpneh_p: 10344 case Intrinsic::ppc_altivec_vcmpnew_p: 10345 case Intrinsic::ppc_altivec_vcmpnezb_p: 10346 case Intrinsic::ppc_altivec_vcmpnezh_p: 10347 case Intrinsic::ppc_altivec_vcmpnezw_p: 10348 if (Subtarget.hasP9Altivec()) { 10349 switch (IntrinsicID) { 10350 default: 10351 llvm_unreachable("Unknown comparison intrinsic."); 10352 case Intrinsic::ppc_altivec_vcmpneb_p: 10353 CompareOpc = 7; 10354 break; 10355 case Intrinsic::ppc_altivec_vcmpneh_p: 10356 CompareOpc = 71; 10357 break; 10358 case Intrinsic::ppc_altivec_vcmpnew_p: 10359 CompareOpc = 135; 10360 break; 10361 case Intrinsic::ppc_altivec_vcmpnezb_p: 10362 CompareOpc = 263; 10363 break; 10364 case Intrinsic::ppc_altivec_vcmpnezh_p: 10365 CompareOpc = 327; 10366 break; 10367 case Intrinsic::ppc_altivec_vcmpnezw_p: 10368 CompareOpc = 391; 10369 break; 10370 } 10371 isDot = true; 10372 } else 10373 return false; 10374 break; 10375 case Intrinsic::ppc_altivec_vcmpgefp_p: 10376 CompareOpc = 454; 10377 isDot = true; 10378 break; 10379 case Intrinsic::ppc_altivec_vcmpgtfp_p: 10380 CompareOpc = 710; 10381 isDot = true; 10382 break; 10383 case Intrinsic::ppc_altivec_vcmpgtsb_p: 10384 CompareOpc = 774; 10385 isDot = true; 10386 break; 10387 case Intrinsic::ppc_altivec_vcmpgtsh_p: 10388 CompareOpc = 838; 10389 isDot = true; 10390 break; 10391 case Intrinsic::ppc_altivec_vcmpgtsw_p: 10392 CompareOpc = 902; 10393 isDot = true; 10394 break; 10395 case Intrinsic::ppc_altivec_vcmpgtsd_p: 10396 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10397 CompareOpc = 967; 10398 isDot = true; 10399 } else 10400 return false; 10401 break; 10402 case Intrinsic::ppc_altivec_vcmpgtub_p: 10403 CompareOpc = 518; 10404 isDot = true; 10405 break; 10406 case Intrinsic::ppc_altivec_vcmpgtuh_p: 10407 CompareOpc = 582; 10408 isDot = true; 10409 break; 10410 case Intrinsic::ppc_altivec_vcmpgtuw_p: 10411 CompareOpc = 646; 10412 isDot = true; 10413 break; 10414 case Intrinsic::ppc_altivec_vcmpgtud_p: 10415 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) { 10416 CompareOpc = 711; 10417 isDot = true; 10418 } else 10419 return false; 10420 break; 10421 10422 case Intrinsic::ppc_altivec_vcmpequq: 10423 case Intrinsic::ppc_altivec_vcmpgtsq: 10424 case Intrinsic::ppc_altivec_vcmpgtuq: 10425 if (!Subtarget.isISA3_1()) 10426 return false; 10427 switch (IntrinsicID) { 10428 default: 10429 llvm_unreachable("Unknown comparison intrinsic."); 10430 case Intrinsic::ppc_altivec_vcmpequq: 10431 CompareOpc = 455; 10432 break; 10433 case Intrinsic::ppc_altivec_vcmpgtsq: 10434 CompareOpc = 903; 10435 break; 10436 case Intrinsic::ppc_altivec_vcmpgtuq: 10437 CompareOpc = 647; 10438 break; 10439 } 10440 break; 10441 10442 // VSX predicate comparisons use the same infrastructure 10443 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10444 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10445 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10446 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10447 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10448 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10449 if (Subtarget.hasVSX()) { 10450 switch (IntrinsicID) { 10451 case Intrinsic::ppc_vsx_xvcmpeqdp_p: 10452 CompareOpc = 99; 10453 break; 10454 case Intrinsic::ppc_vsx_xvcmpgedp_p: 10455 CompareOpc = 115; 10456 break; 10457 case Intrinsic::ppc_vsx_xvcmpgtdp_p: 10458 CompareOpc = 107; 10459 break; 10460 case Intrinsic::ppc_vsx_xvcmpeqsp_p: 10461 CompareOpc = 67; 10462 break; 10463 case Intrinsic::ppc_vsx_xvcmpgesp_p: 10464 CompareOpc = 83; 10465 break; 10466 case Intrinsic::ppc_vsx_xvcmpgtsp_p: 10467 CompareOpc = 75; 10468 break; 10469 } 10470 isDot = true; 10471 } else 10472 return false; 10473 break; 10474 10475 // Normal Comparisons. 10476 case Intrinsic::ppc_altivec_vcmpbfp: 10477 CompareOpc = 966; 10478 break; 10479 case Intrinsic::ppc_altivec_vcmpeqfp: 10480 CompareOpc = 198; 10481 break; 10482 case Intrinsic::ppc_altivec_vcmpequb: 10483 CompareOpc = 6; 10484 break; 10485 case Intrinsic::ppc_altivec_vcmpequh: 10486 CompareOpc = 70; 10487 break; 10488 case Intrinsic::ppc_altivec_vcmpequw: 10489 CompareOpc = 134; 10490 break; 10491 case Intrinsic::ppc_altivec_vcmpequd: 10492 if (Subtarget.hasP8Altivec()) 10493 CompareOpc = 199; 10494 else 10495 return false; 10496 break; 10497 case Intrinsic::ppc_altivec_vcmpneb: 10498 case Intrinsic::ppc_altivec_vcmpneh: 10499 case Intrinsic::ppc_altivec_vcmpnew: 10500 case Intrinsic::ppc_altivec_vcmpnezb: 10501 case Intrinsic::ppc_altivec_vcmpnezh: 10502 case Intrinsic::ppc_altivec_vcmpnezw: 10503 if (Subtarget.hasP9Altivec()) 10504 switch (IntrinsicID) { 10505 default: 10506 llvm_unreachable("Unknown comparison intrinsic."); 10507 case Intrinsic::ppc_altivec_vcmpneb: 10508 CompareOpc = 7; 10509 break; 10510 case Intrinsic::ppc_altivec_vcmpneh: 10511 CompareOpc = 71; 10512 break; 10513 case Intrinsic::ppc_altivec_vcmpnew: 10514 CompareOpc = 135; 10515 break; 10516 case Intrinsic::ppc_altivec_vcmpnezb: 10517 CompareOpc = 263; 10518 break; 10519 case Intrinsic::ppc_altivec_vcmpnezh: 10520 CompareOpc = 327; 10521 break; 10522 case Intrinsic::ppc_altivec_vcmpnezw: 10523 CompareOpc = 391; 10524 break; 10525 } 10526 else 10527 return false; 10528 break; 10529 case Intrinsic::ppc_altivec_vcmpgefp: 10530 CompareOpc = 454; 10531 break; 10532 case Intrinsic::ppc_altivec_vcmpgtfp: 10533 CompareOpc = 710; 10534 break; 10535 case Intrinsic::ppc_altivec_vcmpgtsb: 10536 CompareOpc = 774; 10537 break; 10538 case Intrinsic::ppc_altivec_vcmpgtsh: 10539 CompareOpc = 838; 10540 break; 10541 case Intrinsic::ppc_altivec_vcmpgtsw: 10542 CompareOpc = 902; 10543 break; 10544 case Intrinsic::ppc_altivec_vcmpgtsd: 10545 if (Subtarget.hasP8Altivec()) 10546 CompareOpc = 967; 10547 else 10548 return false; 10549 break; 10550 case Intrinsic::ppc_altivec_vcmpgtub: 10551 CompareOpc = 518; 10552 break; 10553 case Intrinsic::ppc_altivec_vcmpgtuh: 10554 CompareOpc = 582; 10555 break; 10556 case Intrinsic::ppc_altivec_vcmpgtuw: 10557 CompareOpc = 646; 10558 break; 10559 case Intrinsic::ppc_altivec_vcmpgtud: 10560 if (Subtarget.hasP8Altivec()) 10561 CompareOpc = 711; 10562 else 10563 return false; 10564 break; 10565 case Intrinsic::ppc_altivec_vcmpequq_p: 10566 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10567 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10568 if (!Subtarget.isISA3_1()) 10569 return false; 10570 switch (IntrinsicID) { 10571 default: 10572 llvm_unreachable("Unknown comparison intrinsic."); 10573 case Intrinsic::ppc_altivec_vcmpequq_p: 10574 CompareOpc = 455; 10575 break; 10576 case Intrinsic::ppc_altivec_vcmpgtsq_p: 10577 CompareOpc = 903; 10578 break; 10579 case Intrinsic::ppc_altivec_vcmpgtuq_p: 10580 CompareOpc = 647; 10581 break; 10582 } 10583 isDot = true; 10584 break; 10585 } 10586 return true; 10587 } 10588 10589 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom 10590 /// lower, do it, otherwise return null. 10591 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 10592 SelectionDAG &DAG) const { 10593 unsigned IntrinsicID = 10594 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 10595 10596 SDLoc dl(Op); 10597 10598 switch (IntrinsicID) { 10599 case Intrinsic::thread_pointer: 10600 // Reads the thread pointer register, used for __builtin_thread_pointer. 10601 if (Subtarget.isPPC64()) 10602 return DAG.getRegister(PPC::X13, MVT::i64); 10603 return DAG.getRegister(PPC::R2, MVT::i32); 10604 10605 case Intrinsic::ppc_mma_disassemble_acc: { 10606 if (Subtarget.isISAFuture()) { 10607 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1}; 10608 SDValue WideVec = SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, 10609 ArrayRef(ReturnTypes, 2), 10610 Op.getOperand(1)), 10611 0); 10612 SmallVector<SDValue, 4> RetOps; 10613 SDValue Value = SDValue(WideVec.getNode(), 0); 10614 SDValue Value2 = SDValue(WideVec.getNode(), 1); 10615 10616 SDValue Extract; 10617 Extract = DAG.getNode( 10618 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10619 Subtarget.isLittleEndian() ? Value2 : Value, 10620 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0, 10621 dl, getPointerTy(DAG.getDataLayout()))); 10622 RetOps.push_back(Extract); 10623 Extract = DAG.getNode( 10624 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10625 Subtarget.isLittleEndian() ? Value2 : Value, 10626 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1, 10627 dl, getPointerTy(DAG.getDataLayout()))); 10628 RetOps.push_back(Extract); 10629 Extract = DAG.getNode( 10630 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10631 Subtarget.isLittleEndian() ? Value : Value2, 10632 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0, 10633 dl, getPointerTy(DAG.getDataLayout()))); 10634 RetOps.push_back(Extract); 10635 Extract = DAG.getNode( 10636 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 10637 Subtarget.isLittleEndian() ? Value : Value2, 10638 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1, 10639 dl, getPointerTy(DAG.getDataLayout()))); 10640 RetOps.push_back(Extract); 10641 return DAG.getMergeValues(RetOps, dl); 10642 } 10643 LLVM_FALLTHROUGH; 10644 } 10645 case Intrinsic::ppc_vsx_disassemble_pair: { 10646 int NumVecs = 2; 10647 SDValue WideVec = Op.getOperand(1); 10648 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) { 10649 NumVecs = 4; 10650 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec); 10651 } 10652 SmallVector<SDValue, 4> RetOps; 10653 for (int VecNo = 0; VecNo < NumVecs; VecNo++) { 10654 SDValue Extract = DAG.getNode( 10655 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec, 10656 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo 10657 : VecNo, 10658 dl, getPointerTy(DAG.getDataLayout()))); 10659 RetOps.push_back(Extract); 10660 } 10661 return DAG.getMergeValues(RetOps, dl); 10662 } 10663 10664 case Intrinsic::ppc_unpack_longdouble: { 10665 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10666 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) && 10667 "Argument of long double unpack must be 0 or 1!"); 10668 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1), 10669 DAG.getConstant(!!(Idx->getSExtValue()), dl, 10670 Idx->getValueType(0))); 10671 } 10672 10673 case Intrinsic::ppc_compare_exp_lt: 10674 case Intrinsic::ppc_compare_exp_gt: 10675 case Intrinsic::ppc_compare_exp_eq: 10676 case Intrinsic::ppc_compare_exp_uo: { 10677 unsigned Pred; 10678 switch (IntrinsicID) { 10679 case Intrinsic::ppc_compare_exp_lt: 10680 Pred = PPC::PRED_LT; 10681 break; 10682 case Intrinsic::ppc_compare_exp_gt: 10683 Pred = PPC::PRED_GT; 10684 break; 10685 case Intrinsic::ppc_compare_exp_eq: 10686 Pred = PPC::PRED_EQ; 10687 break; 10688 case Intrinsic::ppc_compare_exp_uo: 10689 Pred = PPC::PRED_UN; 10690 break; 10691 } 10692 return SDValue( 10693 DAG.getMachineNode( 10694 PPC::SELECT_CC_I4, dl, MVT::i32, 10695 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32, 10696 Op.getOperand(1), Op.getOperand(2)), 10697 0), 10698 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10699 DAG.getTargetConstant(Pred, dl, MVT::i32)}), 10700 0); 10701 } 10702 case Intrinsic::ppc_test_data_class: { 10703 EVT OpVT = Op.getOperand(1).getValueType(); 10704 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP 10705 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP 10706 : PPC::XSTSTDCSP); 10707 return SDValue( 10708 DAG.getMachineNode( 10709 PPC::SELECT_CC_I4, dl, MVT::i32, 10710 {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2), 10711 Op.getOperand(1)), 10712 0), 10713 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32), 10714 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}), 10715 0); 10716 } 10717 case Intrinsic::ppc_fnmsub: { 10718 EVT VT = Op.getOperand(1).getValueType(); 10719 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128)) 10720 return DAG.getNode( 10721 ISD::FNEG, dl, VT, 10722 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2), 10723 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3)))); 10724 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1), 10725 Op.getOperand(2), Op.getOperand(3)); 10726 } 10727 case Intrinsic::ppc_convert_f128_to_ppcf128: 10728 case Intrinsic::ppc_convert_ppcf128_to_f128: { 10729 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128 10730 ? RTLIB::CONVERT_PPCF128_F128 10731 : RTLIB::CONVERT_F128_PPCF128; 10732 MakeLibCallOptions CallOptions; 10733 std::pair<SDValue, SDValue> Result = 10734 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions, 10735 dl, SDValue()); 10736 return Result.first; 10737 } 10738 case Intrinsic::ppc_maxfe: 10739 case Intrinsic::ppc_maxfl: 10740 case Intrinsic::ppc_maxfs: 10741 case Intrinsic::ppc_minfe: 10742 case Intrinsic::ppc_minfl: 10743 case Intrinsic::ppc_minfs: { 10744 EVT VT = Op.getValueType(); 10745 assert( 10746 all_of(Op->ops().drop_front(4), 10747 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) && 10748 "ppc_[max|min]f[e|l|s] must have uniform type arguments"); 10749 (void)VT; 10750 ISD::CondCode CC = ISD::SETGT; 10751 if (IntrinsicID == Intrinsic::ppc_minfe || 10752 IntrinsicID == Intrinsic::ppc_minfl || 10753 IntrinsicID == Intrinsic::ppc_minfs) 10754 CC = ISD::SETLT; 10755 unsigned I = Op.getNumOperands() - 2, Cnt = I; 10756 SDValue Res = Op.getOperand(I); 10757 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) { 10758 Res = 10759 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC); 10760 } 10761 return Res; 10762 } 10763 } 10764 10765 // If this is a lowered altivec predicate compare, CompareOpc is set to the 10766 // opcode number of the comparison. 10767 int CompareOpc; 10768 bool isDot; 10769 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) 10770 return SDValue(); // Don't custom lower most intrinsics. 10771 10772 // If this is a non-dot comparison, make the VCMP node and we are done. 10773 if (!isDot) { 10774 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), 10775 Op.getOperand(1), Op.getOperand(2), 10776 DAG.getConstant(CompareOpc, dl, MVT::i32)); 10777 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); 10778 } 10779 10780 // Create the PPCISD altivec 'dot' comparison node. 10781 SDValue Ops[] = { 10782 Op.getOperand(2), // LHS 10783 Op.getOperand(3), // RHS 10784 DAG.getConstant(CompareOpc, dl, MVT::i32) 10785 }; 10786 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; 10787 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 10788 10789 // Now that we have the comparison, emit a copy from the CR to a GPR. 10790 // This is flagged to the above dot comparison. 10791 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, 10792 DAG.getRegister(PPC::CR6, MVT::i32), 10793 CompNode.getValue(1)); 10794 10795 // Unpack the result based on how the target uses it. 10796 unsigned BitNo; // Bit # of CR6. 10797 bool InvertBit; // Invert result? 10798 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 10799 default: // Can't happen, don't crash on invalid number though. 10800 case 0: // Return the value of the EQ bit of CR6. 10801 BitNo = 0; InvertBit = false; 10802 break; 10803 case 1: // Return the inverted value of the EQ bit of CR6. 10804 BitNo = 0; InvertBit = true; 10805 break; 10806 case 2: // Return the value of the LT bit of CR6. 10807 BitNo = 2; InvertBit = false; 10808 break; 10809 case 3: // Return the inverted value of the LT bit of CR6. 10810 BitNo = 2; InvertBit = true; 10811 break; 10812 } 10813 10814 // Shift the bit into the low position. 10815 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, 10816 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); 10817 // Isolate the bit. 10818 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, 10819 DAG.getConstant(1, dl, MVT::i32)); 10820 10821 // If we are supposed to, toggle the bit. 10822 if (InvertBit) 10823 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, 10824 DAG.getConstant(1, dl, MVT::i32)); 10825 return Flags; 10826 } 10827 10828 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 10829 SelectionDAG &DAG) const { 10830 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to 10831 // the beginning of the argument list. 10832 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1; 10833 SDLoc DL(Op); 10834 switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) { 10835 case Intrinsic::ppc_cfence: { 10836 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument."); 10837 assert(Subtarget.isPPC64() && "Only 64-bit is supported for now."); 10838 SDValue Val = Op.getOperand(ArgStart + 1); 10839 EVT Ty = Val.getValueType(); 10840 if (Ty == MVT::i128) { 10841 // FIXME: Testing one of two paired registers is sufficient to guarantee 10842 // ordering? 10843 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val); 10844 } 10845 return SDValue( 10846 DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other, 10847 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val), 10848 Op.getOperand(0)), 10849 0); 10850 } 10851 default: 10852 break; 10853 } 10854 return SDValue(); 10855 } 10856 10857 // Lower scalar BSWAP64 to xxbrd. 10858 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const { 10859 SDLoc dl(Op); 10860 if (!Subtarget.isPPC64()) 10861 return Op; 10862 // MTVSRDD 10863 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0), 10864 Op.getOperand(0)); 10865 // XXBRD 10866 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op); 10867 // MFVSRD 10868 int VectorIndex = 0; 10869 if (Subtarget.isLittleEndian()) 10870 VectorIndex = 1; 10871 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op, 10872 DAG.getTargetConstant(VectorIndex, dl, MVT::i32)); 10873 return Op; 10874 } 10875 10876 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be 10877 // compared to a value that is atomically loaded (atomic loads zero-extend). 10878 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, 10879 SelectionDAG &DAG) const { 10880 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP && 10881 "Expecting an atomic compare-and-swap here."); 10882 SDLoc dl(Op); 10883 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode()); 10884 EVT MemVT = AtomicNode->getMemoryVT(); 10885 if (MemVT.getSizeInBits() >= 32) 10886 return Op; 10887 10888 SDValue CmpOp = Op.getOperand(2); 10889 // If this is already correctly zero-extended, leave it alone. 10890 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits()); 10891 if (DAG.MaskedValueIsZero(CmpOp, HighBits)) 10892 return Op; 10893 10894 // Clear the high bits of the compare operand. 10895 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1; 10896 SDValue NewCmpOp = 10897 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp, 10898 DAG.getConstant(MaskVal, dl, MVT::i32)); 10899 10900 // Replace the existing compare operand with the properly zero-extended one. 10901 SmallVector<SDValue, 4> Ops; 10902 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++) 10903 Ops.push_back(AtomicNode->getOperand(i)); 10904 Ops[2] = NewCmpOp; 10905 MachineMemOperand *MMO = AtomicNode->getMemOperand(); 10906 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other); 10907 auto NodeTy = 10908 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16; 10909 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO); 10910 } 10911 10912 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op, 10913 SelectionDAG &DAG) const { 10914 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode()); 10915 EVT MemVT = N->getMemoryVT(); 10916 assert(MemVT.getSimpleVT() == MVT::i128 && 10917 "Expect quadword atomic operations"); 10918 SDLoc dl(N); 10919 unsigned Opc = N->getOpcode(); 10920 switch (Opc) { 10921 case ISD::ATOMIC_LOAD: { 10922 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be 10923 // lowered to ppc instructions by pattern matching instruction selector. 10924 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other); 10925 SmallVector<SDValue, 4> Ops{ 10926 N->getOperand(0), 10927 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)}; 10928 for (int I = 1, E = N->getNumOperands(); I < E; ++I) 10929 Ops.push_back(N->getOperand(I)); 10930 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys, 10931 Ops, MemVT, N->getMemOperand()); 10932 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal); 10933 SDValue ValHi = 10934 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1)); 10935 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi, 10936 DAG.getConstant(64, dl, MVT::i32)); 10937 SDValue Val = 10938 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi}); 10939 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other}, 10940 {Val, LoadedVal.getValue(2)}); 10941 } 10942 case ISD::ATOMIC_STORE: { 10943 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be 10944 // lowered to ppc instructions by pattern matching instruction selector. 10945 SDVTList Tys = DAG.getVTList(MVT::Other); 10946 SmallVector<SDValue, 4> Ops{ 10947 N->getOperand(0), 10948 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)}; 10949 SDValue Val = N->getOperand(2); 10950 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val); 10951 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val, 10952 DAG.getConstant(64, dl, MVT::i32)); 10953 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi); 10954 Ops.push_back(ValLo); 10955 Ops.push_back(ValHi); 10956 Ops.push_back(N->getOperand(1)); 10957 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT, 10958 N->getMemOperand()); 10959 } 10960 default: 10961 llvm_unreachable("Unexpected atomic opcode"); 10962 } 10963 } 10964 10965 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, 10966 SelectionDAG &DAG) const { 10967 SDLoc dl(Op); 10968 // Create a stack slot that is 16-byte aligned. 10969 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 10970 int FrameIdx = MFI.CreateStackObject(16, Align(16), false); 10971 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10972 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); 10973 10974 // Store the input value into Value#0 of the stack slot. 10975 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, 10976 MachinePointerInfo()); 10977 // Load it out. 10978 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo()); 10979 } 10980 10981 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 10982 SelectionDAG &DAG) const { 10983 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && 10984 "Should only be called for ISD::INSERT_VECTOR_ELT"); 10985 10986 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 10987 10988 EVT VT = Op.getValueType(); 10989 SDLoc dl(Op); 10990 SDValue V1 = Op.getOperand(0); 10991 SDValue V2 = Op.getOperand(1); 10992 10993 if (VT == MVT::v2f64 && C) 10994 return Op; 10995 10996 if (Subtarget.hasP9Vector()) { 10997 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way 10998 // because on P10, it allows this specific insert_vector_elt load pattern to 10999 // utilize the refactored load and store infrastructure in order to exploit 11000 // prefixed loads. 11001 // On targets with inexpensive direct moves (Power9 and up), a 11002 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer 11003 // load since a single precision load will involve conversion to double 11004 // precision on the load followed by another conversion to single precision. 11005 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) && 11006 (isa<LoadSDNode>(V2))) { 11007 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1); 11008 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2); 11009 SDValue InsVecElt = 11010 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector, 11011 BitcastLoad, Op.getOperand(2)); 11012 return DAG.getBitcast(MVT::v4f32, InsVecElt); 11013 } 11014 } 11015 11016 if (Subtarget.isISA3_1()) { 11017 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64()) 11018 return SDValue(); 11019 // On P10, we have legal lowering for constant and variable indices for 11020 // all vectors. 11021 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 11022 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64) 11023 return Op; 11024 } 11025 11026 // Before P10, we have legal lowering for constant indices but not for 11027 // variable ones. 11028 if (!C) 11029 return SDValue(); 11030 11031 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types. 11032 if (VT == MVT::v8i16 || VT == MVT::v16i8) { 11033 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2); 11034 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8; 11035 unsigned InsertAtElement = C->getZExtValue(); 11036 unsigned InsertAtByte = InsertAtElement * BytesInEachElement; 11037 if (Subtarget.isLittleEndian()) { 11038 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte; 11039 } 11040 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz, 11041 DAG.getConstant(InsertAtByte, dl, MVT::i32)); 11042 } 11043 return Op; 11044 } 11045 11046 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, 11047 SelectionDAG &DAG) const { 11048 SDLoc dl(Op); 11049 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 11050 SDValue LoadChain = LN->getChain(); 11051 SDValue BasePtr = LN->getBasePtr(); 11052 EVT VT = Op.getValueType(); 11053 11054 if (VT != MVT::v256i1 && VT != MVT::v512i1) 11055 return Op; 11056 11057 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 11058 // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in 11059 // 2 or 4 vsx registers. 11060 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) && 11061 "Type unsupported without MMA"); 11062 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 11063 "Type unsupported without paired vector support"); 11064 Align Alignment = LN->getAlign(); 11065 SmallVector<SDValue, 4> Loads; 11066 SmallVector<SDValue, 4> LoadChains; 11067 unsigned NumVecs = VT.getSizeInBits() / 128; 11068 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 11069 SDValue Load = 11070 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr, 11071 LN->getPointerInfo().getWithOffset(Idx * 16), 11072 commonAlignment(Alignment, Idx * 16), 11073 LN->getMemOperand()->getFlags(), LN->getAAInfo()); 11074 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11075 DAG.getConstant(16, dl, BasePtr.getValueType())); 11076 Loads.push_back(Load); 11077 LoadChains.push_back(Load.getValue(1)); 11078 } 11079 if (Subtarget.isLittleEndian()) { 11080 std::reverse(Loads.begin(), Loads.end()); 11081 std::reverse(LoadChains.begin(), LoadChains.end()); 11082 } 11083 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 11084 SDValue Value = 11085 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD, 11086 dl, VT, Loads); 11087 SDValue RetOps[] = {Value, TF}; 11088 return DAG.getMergeValues(RetOps, dl); 11089 } 11090 11091 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, 11092 SelectionDAG &DAG) const { 11093 SDLoc dl(Op); 11094 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 11095 SDValue StoreChain = SN->getChain(); 11096 SDValue BasePtr = SN->getBasePtr(); 11097 SDValue Value = SN->getValue(); 11098 SDValue Value2 = SN->getValue(); 11099 EVT StoreVT = Value.getValueType(); 11100 11101 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1) 11102 return Op; 11103 11104 // Type v256i1 is used for pairs and v512i1 is used for accumulators. 11105 // Here we create 2 or 4 v16i8 stores to store the pair or accumulator 11106 // underlying registers individually. 11107 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) && 11108 "Type unsupported without MMA"); 11109 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) && 11110 "Type unsupported without paired vector support"); 11111 Align Alignment = SN->getAlign(); 11112 SmallVector<SDValue, 4> Stores; 11113 unsigned NumVecs = 2; 11114 if (StoreVT == MVT::v512i1) { 11115 if (Subtarget.isISAFuture()) { 11116 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1}; 11117 MachineSDNode *ExtNode = DAG.getMachineNode( 11118 PPC::DMXXEXTFDMR512, dl, ArrayRef(ReturnTypes, 2), Op.getOperand(1)); 11119 11120 Value = SDValue(ExtNode, 0); 11121 Value2 = SDValue(ExtNode, 1); 11122 } else 11123 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value); 11124 NumVecs = 4; 11125 } 11126 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) { 11127 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx; 11128 SDValue Elt; 11129 if (Subtarget.isISAFuture()) { 11130 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2); 11131 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, 11132 Idx > 1 ? Value2 : Value, 11133 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 11134 } else 11135 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value, 11136 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout()))); 11137 11138 SDValue Store = 11139 DAG.getStore(StoreChain, dl, Elt, BasePtr, 11140 SN->getPointerInfo().getWithOffset(Idx * 16), 11141 commonAlignment(Alignment, Idx * 16), 11142 SN->getMemOperand()->getFlags(), SN->getAAInfo()); 11143 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 11144 DAG.getConstant(16, dl, BasePtr.getValueType())); 11145 Stores.push_back(Store); 11146 } 11147 SDValue TF = DAG.getTokenFactor(dl, Stores); 11148 return TF; 11149 } 11150 11151 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { 11152 SDLoc dl(Op); 11153 if (Op.getValueType() == MVT::v4i32) { 11154 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 11155 11156 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl); 11157 // +16 as shift amt. 11158 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl); 11159 SDValue RHSSwap = // = vrlw RHS, 16 11160 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); 11161 11162 // Shrinkify inputs to v8i16. 11163 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); 11164 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); 11165 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); 11166 11167 // Low parts multiplied together, generating 32-bit results (we ignore the 11168 // top parts). 11169 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, 11170 LHS, RHS, DAG, dl, MVT::v4i32); 11171 11172 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, 11173 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); 11174 // Shift the high parts up 16 bits. 11175 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, 11176 Neg16, DAG, dl); 11177 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); 11178 } else if (Op.getValueType() == MVT::v16i8) { 11179 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); 11180 bool isLittleEndian = Subtarget.isLittleEndian(); 11181 11182 // Multiply the even 8-bit parts, producing 16-bit sums. 11183 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, 11184 LHS, RHS, DAG, dl, MVT::v8i16); 11185 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); 11186 11187 // Multiply the odd 8-bit parts, producing 16-bit sums. 11188 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, 11189 LHS, RHS, DAG, dl, MVT::v8i16); 11190 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); 11191 11192 // Merge the results together. Because vmuleub and vmuloub are 11193 // instructions with a big-endian bias, we must reverse the 11194 // element numbering and reverse the meaning of "odd" and "even" 11195 // when generating little endian code. 11196 int Ops[16]; 11197 for (unsigned i = 0; i != 8; ++i) { 11198 if (isLittleEndian) { 11199 Ops[i*2 ] = 2*i; 11200 Ops[i*2+1] = 2*i+16; 11201 } else { 11202 Ops[i*2 ] = 2*i+1; 11203 Ops[i*2+1] = 2*i+1+16; 11204 } 11205 } 11206 if (isLittleEndian) 11207 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); 11208 else 11209 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); 11210 } else { 11211 llvm_unreachable("Unknown mul to lower!"); 11212 } 11213 } 11214 11215 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 11216 bool IsStrict = Op->isStrictFPOpcode(); 11217 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 && 11218 !Subtarget.hasP9Vector()) 11219 return SDValue(); 11220 11221 return Op; 11222 } 11223 11224 // Custom lowering for fpext vf32 to v2f64 11225 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { 11226 11227 assert(Op.getOpcode() == ISD::FP_EXTEND && 11228 "Should only be called for ISD::FP_EXTEND"); 11229 11230 // FIXME: handle extends from half precision float vectors on P9. 11231 // We only want to custom lower an extend from v2f32 to v2f64. 11232 if (Op.getValueType() != MVT::v2f64 || 11233 Op.getOperand(0).getValueType() != MVT::v2f32) 11234 return SDValue(); 11235 11236 SDLoc dl(Op); 11237 SDValue Op0 = Op.getOperand(0); 11238 11239 switch (Op0.getOpcode()) { 11240 default: 11241 return SDValue(); 11242 case ISD::EXTRACT_SUBVECTOR: { 11243 assert(Op0.getNumOperands() == 2 && 11244 isa<ConstantSDNode>(Op0->getOperand(1)) && 11245 "Node should have 2 operands with second one being a constant!"); 11246 11247 if (Op0.getOperand(0).getValueType() != MVT::v4f32) 11248 return SDValue(); 11249 11250 // Custom lower is only done for high or low doubleword. 11251 int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue(); 11252 if (Idx % 2 != 0) 11253 return SDValue(); 11254 11255 // Since input is v4f32, at this point Idx is either 0 or 2. 11256 // Shift to get the doubleword position we want. 11257 int DWord = Idx >> 1; 11258 11259 // High and low word positions are different on little endian. 11260 if (Subtarget.isLittleEndian()) 11261 DWord ^= 0x1; 11262 11263 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, 11264 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32)); 11265 } 11266 case ISD::FADD: 11267 case ISD::FMUL: 11268 case ISD::FSUB: { 11269 SDValue NewLoad[2]; 11270 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) { 11271 // Ensure both input are loads. 11272 SDValue LdOp = Op0.getOperand(i); 11273 if (LdOp.getOpcode() != ISD::LOAD) 11274 return SDValue(); 11275 // Generate new load node. 11276 LoadSDNode *LD = cast<LoadSDNode>(LdOp); 11277 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11278 NewLoad[i] = DAG.getMemIntrinsicNode( 11279 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11280 LD->getMemoryVT(), LD->getMemOperand()); 11281 } 11282 SDValue NewOp = 11283 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0], 11284 NewLoad[1], Op0.getNode()->getFlags()); 11285 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp, 11286 DAG.getConstant(0, dl, MVT::i32)); 11287 } 11288 case ISD::LOAD: { 11289 LoadSDNode *LD = cast<LoadSDNode>(Op0); 11290 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()}; 11291 SDValue NewLd = DAG.getMemIntrinsicNode( 11292 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps, 11293 LD->getMemoryVT(), LD->getMemOperand()); 11294 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd, 11295 DAG.getConstant(0, dl, MVT::i32)); 11296 } 11297 } 11298 llvm_unreachable("ERROR:Should return for all cases within swtich."); 11299 } 11300 11301 /// LowerOperation - Provide custom lowering hooks for some operations. 11302 /// 11303 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 11304 switch (Op.getOpcode()) { 11305 default: llvm_unreachable("Wasn't expecting to be able to lower this!"); 11306 case ISD::FPOW: return lowerPow(Op, DAG); 11307 case ISD::FSIN: return lowerSin(Op, DAG); 11308 case ISD::FCOS: return lowerCos(Op, DAG); 11309 case ISD::FLOG: return lowerLog(Op, DAG); 11310 case ISD::FLOG10: return lowerLog10(Op, DAG); 11311 case ISD::FEXP: return lowerExp(Op, DAG); 11312 case ISD::ConstantPool: return LowerConstantPool(Op, DAG); 11313 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); 11314 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); 11315 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); 11316 case ISD::JumpTable: return LowerJumpTable(Op, DAG); 11317 case ISD::STRICT_FSETCC: 11318 case ISD::STRICT_FSETCCS: 11319 case ISD::SETCC: return LowerSETCC(Op, DAG); 11320 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); 11321 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); 11322 11323 case ISD::INLINEASM: 11324 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG); 11325 // Variable argument lowering. 11326 case ISD::VASTART: return LowerVASTART(Op, DAG); 11327 case ISD::VAARG: return LowerVAARG(Op, DAG); 11328 case ISD::VACOPY: return LowerVACOPY(Op, DAG); 11329 11330 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG); 11331 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); 11332 case ISD::GET_DYNAMIC_AREA_OFFSET: 11333 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG); 11334 11335 // Exception handling lowering. 11336 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG); 11337 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); 11338 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); 11339 11340 case ISD::LOAD: return LowerLOAD(Op, DAG); 11341 case ISD::STORE: return LowerSTORE(Op, DAG); 11342 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); 11343 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); 11344 case ISD::STRICT_FP_TO_UINT: 11345 case ISD::STRICT_FP_TO_SINT: 11346 case ISD::FP_TO_UINT: 11347 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); 11348 case ISD::STRICT_UINT_TO_FP: 11349 case ISD::STRICT_SINT_TO_FP: 11350 case ISD::UINT_TO_FP: 11351 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); 11352 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG); 11353 11354 // Lower 64-bit shifts. 11355 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); 11356 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); 11357 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); 11358 11359 case ISD::FSHL: return LowerFunnelShift(Op, DAG); 11360 case ISD::FSHR: return LowerFunnelShift(Op, DAG); 11361 11362 // Vector-related lowering. 11363 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); 11364 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); 11365 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 11366 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); 11367 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); 11368 case ISD::MUL: return LowerMUL(Op, DAG); 11369 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); 11370 case ISD::STRICT_FP_ROUND: 11371 case ISD::FP_ROUND: 11372 return LowerFP_ROUND(Op, DAG); 11373 case ISD::ROTL: return LowerROTL(Op, DAG); 11374 11375 // For counter-based loop handling. 11376 case ISD::INTRINSIC_W_CHAIN: return SDValue(); 11377 11378 case ISD::BITCAST: return LowerBITCAST(Op, DAG); 11379 11380 // Frame & Return address. 11381 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 11382 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); 11383 11384 case ISD::INTRINSIC_VOID: 11385 return LowerINTRINSIC_VOID(Op, DAG); 11386 case ISD::BSWAP: 11387 return LowerBSWAP(Op, DAG); 11388 case ISD::ATOMIC_CMP_SWAP: 11389 return LowerATOMIC_CMP_SWAP(Op, DAG); 11390 case ISD::ATOMIC_STORE: 11391 return LowerATOMIC_LOAD_STORE(Op, DAG); 11392 } 11393 } 11394 11395 void PPCTargetLowering::ReplaceNodeResults(SDNode *N, 11396 SmallVectorImpl<SDValue>&Results, 11397 SelectionDAG &DAG) const { 11398 SDLoc dl(N); 11399 switch (N->getOpcode()) { 11400 default: 11401 llvm_unreachable("Do not know how to custom type legalize this operation!"); 11402 case ISD::ATOMIC_LOAD: { 11403 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG); 11404 Results.push_back(Res); 11405 Results.push_back(Res.getValue(1)); 11406 break; 11407 } 11408 case ISD::READCYCLECOUNTER: { 11409 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 11410 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); 11411 11412 Results.push_back( 11413 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1))); 11414 Results.push_back(RTB.getValue(2)); 11415 break; 11416 } 11417 case ISD::INTRINSIC_W_CHAIN: { 11418 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 11419 Intrinsic::loop_decrement) 11420 break; 11421 11422 assert(N->getValueType(0) == MVT::i1 && 11423 "Unexpected result type for CTR decrement intrinsic"); 11424 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 11425 N->getValueType(0)); 11426 SDVTList VTs = DAG.getVTList(SVT, MVT::Other); 11427 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), 11428 N->getOperand(1)); 11429 11430 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt)); 11431 Results.push_back(NewInt.getValue(1)); 11432 break; 11433 } 11434 case ISD::INTRINSIC_WO_CHAIN: { 11435 switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) { 11436 case Intrinsic::ppc_pack_longdouble: 11437 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, 11438 N->getOperand(2), N->getOperand(1))); 11439 break; 11440 case Intrinsic::ppc_maxfe: 11441 case Intrinsic::ppc_minfe: 11442 case Intrinsic::ppc_fnmsub: 11443 case Intrinsic::ppc_convert_f128_to_ppcf128: 11444 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG)); 11445 break; 11446 } 11447 break; 11448 } 11449 case ISD::VAARG: { 11450 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) 11451 return; 11452 11453 EVT VT = N->getValueType(0); 11454 11455 if (VT == MVT::i64) { 11456 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG); 11457 11458 Results.push_back(NewNode); 11459 Results.push_back(NewNode.getValue(1)); 11460 } 11461 return; 11462 } 11463 case ISD::STRICT_FP_TO_SINT: 11464 case ISD::STRICT_FP_TO_UINT: 11465 case ISD::FP_TO_SINT: 11466 case ISD::FP_TO_UINT: { 11467 // LowerFP_TO_INT() can only handle f32 and f64. 11468 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() == 11469 MVT::ppcf128) 11470 return; 11471 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl); 11472 Results.push_back(LoweredValue); 11473 if (N->isStrictFPOpcode()) 11474 Results.push_back(LoweredValue.getValue(1)); 11475 return; 11476 } 11477 case ISD::TRUNCATE: { 11478 if (!N->getValueType(0).isVector()) 11479 return; 11480 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG); 11481 if (Lowered) 11482 Results.push_back(Lowered); 11483 return; 11484 } 11485 case ISD::FSHL: 11486 case ISD::FSHR: 11487 // Don't handle funnel shifts here. 11488 return; 11489 case ISD::BITCAST: 11490 // Don't handle bitcast here. 11491 return; 11492 case ISD::FP_EXTEND: 11493 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG); 11494 if (Lowered) 11495 Results.push_back(Lowered); 11496 return; 11497 } 11498 } 11499 11500 //===----------------------------------------------------------------------===// 11501 // Other Lowering Code 11502 //===----------------------------------------------------------------------===// 11503 11504 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) { 11505 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11506 Function *Func = Intrinsic::getDeclaration(M, Id); 11507 return Builder.CreateCall(Func, {}); 11508 } 11509 11510 // The mappings for emitLeading/TrailingFence is taken from 11511 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 11512 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11513 Instruction *Inst, 11514 AtomicOrdering Ord) const { 11515 if (Ord == AtomicOrdering::SequentiallyConsistent) 11516 return callIntrinsic(Builder, Intrinsic::ppc_sync); 11517 if (isReleaseOrStronger(Ord)) 11518 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11519 return nullptr; 11520 } 11521 11522 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11523 Instruction *Inst, 11524 AtomicOrdering Ord) const { 11525 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) { 11526 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and 11527 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html 11528 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. 11529 if (isa<LoadInst>(Inst) && Subtarget.isPPC64()) 11530 return Builder.CreateCall( 11531 Intrinsic::getDeclaration( 11532 Builder.GetInsertBlock()->getParent()->getParent(), 11533 Intrinsic::ppc_cfence, {Inst->getType()}), 11534 {Inst}); 11535 // FIXME: Can use isync for rmw operation. 11536 return callIntrinsic(Builder, Intrinsic::ppc_lwsync); 11537 } 11538 return nullptr; 11539 } 11540 11541 MachineBasicBlock * 11542 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB, 11543 unsigned AtomicSize, 11544 unsigned BinOpcode, 11545 unsigned CmpOpcode, 11546 unsigned CmpPred) const { 11547 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11548 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11549 11550 auto LoadMnemonic = PPC::LDARX; 11551 auto StoreMnemonic = PPC::STDCX; 11552 switch (AtomicSize) { 11553 default: 11554 llvm_unreachable("Unexpected size of atomic entity"); 11555 case 1: 11556 LoadMnemonic = PPC::LBARX; 11557 StoreMnemonic = PPC::STBCX; 11558 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11559 break; 11560 case 2: 11561 LoadMnemonic = PPC::LHARX; 11562 StoreMnemonic = PPC::STHCX; 11563 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); 11564 break; 11565 case 4: 11566 LoadMnemonic = PPC::LWARX; 11567 StoreMnemonic = PPC::STWCX; 11568 break; 11569 case 8: 11570 LoadMnemonic = PPC::LDARX; 11571 StoreMnemonic = PPC::STDCX; 11572 break; 11573 } 11574 11575 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11576 MachineFunction *F = BB->getParent(); 11577 MachineFunction::iterator It = ++BB->getIterator(); 11578 11579 Register dest = MI.getOperand(0).getReg(); 11580 Register ptrA = MI.getOperand(1).getReg(); 11581 Register ptrB = MI.getOperand(2).getReg(); 11582 Register incr = MI.getOperand(3).getReg(); 11583 DebugLoc dl = MI.getDebugLoc(); 11584 11585 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11586 MachineBasicBlock *loop2MBB = 11587 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11588 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11589 F->insert(It, loopMBB); 11590 if (CmpOpcode) 11591 F->insert(It, loop2MBB); 11592 F->insert(It, exitMBB); 11593 exitMBB->splice(exitMBB->begin(), BB, 11594 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11595 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11596 11597 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11598 Register TmpReg = (!BinOpcode) ? incr : 11599 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass 11600 : &PPC::GPRCRegClass); 11601 11602 // thisMBB: 11603 // ... 11604 // fallthrough --> loopMBB 11605 BB->addSuccessor(loopMBB); 11606 11607 // loopMBB: 11608 // l[wd]arx dest, ptr 11609 // add r0, dest, incr 11610 // st[wd]cx. r0, ptr 11611 // bne- loopMBB 11612 // fallthrough --> exitMBB 11613 11614 // For max/min... 11615 // loopMBB: 11616 // l[wd]arx dest, ptr 11617 // cmpl?[wd] dest, incr 11618 // bgt exitMBB 11619 // loop2MBB: 11620 // st[wd]cx. dest, ptr 11621 // bne- loopMBB 11622 // fallthrough --> exitMBB 11623 11624 BB = loopMBB; 11625 BuildMI(BB, dl, TII->get(LoadMnemonic), dest) 11626 .addReg(ptrA).addReg(ptrB); 11627 if (BinOpcode) 11628 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); 11629 if (CmpOpcode) { 11630 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11631 // Signed comparisons of byte or halfword values must be sign-extended. 11632 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) { 11633 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11634 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH), 11635 ExtReg).addReg(dest); 11636 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr); 11637 } else 11638 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr); 11639 11640 BuildMI(BB, dl, TII->get(PPC::BCC)) 11641 .addImm(CmpPred) 11642 .addReg(CrReg) 11643 .addMBB(exitMBB); 11644 BB->addSuccessor(loop2MBB); 11645 BB->addSuccessor(exitMBB); 11646 BB = loop2MBB; 11647 } 11648 BuildMI(BB, dl, TII->get(StoreMnemonic)) 11649 .addReg(TmpReg).addReg(ptrA).addReg(ptrB); 11650 BuildMI(BB, dl, TII->get(PPC::BCC)) 11651 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); 11652 BB->addSuccessor(loopMBB); 11653 BB->addSuccessor(exitMBB); 11654 11655 // exitMBB: 11656 // ... 11657 BB = exitMBB; 11658 return BB; 11659 } 11660 11661 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) { 11662 switch(MI.getOpcode()) { 11663 default: 11664 return false; 11665 case PPC::COPY: 11666 return TII->isSignExtended(MI.getOperand(1).getReg(), 11667 &MI.getMF()->getRegInfo()); 11668 case PPC::LHA: 11669 case PPC::LHA8: 11670 case PPC::LHAU: 11671 case PPC::LHAU8: 11672 case PPC::LHAUX: 11673 case PPC::LHAUX8: 11674 case PPC::LHAX: 11675 case PPC::LHAX8: 11676 case PPC::LWA: 11677 case PPC::LWAUX: 11678 case PPC::LWAX: 11679 case PPC::LWAX_32: 11680 case PPC::LWA_32: 11681 case PPC::PLHA: 11682 case PPC::PLHA8: 11683 case PPC::PLHA8pc: 11684 case PPC::PLHApc: 11685 case PPC::PLWA: 11686 case PPC::PLWA8: 11687 case PPC::PLWA8pc: 11688 case PPC::PLWApc: 11689 case PPC::EXTSB: 11690 case PPC::EXTSB8: 11691 case PPC::EXTSB8_32_64: 11692 case PPC::EXTSB8_rec: 11693 case PPC::EXTSB_rec: 11694 case PPC::EXTSH: 11695 case PPC::EXTSH8: 11696 case PPC::EXTSH8_32_64: 11697 case PPC::EXTSH8_rec: 11698 case PPC::EXTSH_rec: 11699 case PPC::EXTSW: 11700 case PPC::EXTSWSLI: 11701 case PPC::EXTSWSLI_32_64: 11702 case PPC::EXTSWSLI_32_64_rec: 11703 case PPC::EXTSWSLI_rec: 11704 case PPC::EXTSW_32: 11705 case PPC::EXTSW_32_64: 11706 case PPC::EXTSW_32_64_rec: 11707 case PPC::EXTSW_rec: 11708 case PPC::SRAW: 11709 case PPC::SRAWI: 11710 case PPC::SRAWI_rec: 11711 case PPC::SRAW_rec: 11712 return true; 11713 } 11714 return false; 11715 } 11716 11717 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary( 11718 MachineInstr &MI, MachineBasicBlock *BB, 11719 bool is8bit, // operation 11720 unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const { 11721 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. 11722 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 11723 11724 // If this is a signed comparison and the value being compared is not known 11725 // to be sign extended, sign extend it here. 11726 DebugLoc dl = MI.getDebugLoc(); 11727 MachineFunction *F = BB->getParent(); 11728 MachineRegisterInfo &RegInfo = F->getRegInfo(); 11729 Register incr = MI.getOperand(3).getReg(); 11730 bool IsSignExtended = 11731 incr.isVirtual() && isSignExtended(*RegInfo.getVRegDef(incr), TII); 11732 11733 if (CmpOpcode == PPC::CMPW && !IsSignExtended) { 11734 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 11735 BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg) 11736 .addReg(MI.getOperand(3).getReg()); 11737 MI.getOperand(3).setReg(ValueReg); 11738 } 11739 // If we support part-word atomic mnemonics, just use them 11740 if (Subtarget.hasPartwordAtomics()) 11741 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode, 11742 CmpPred); 11743 11744 // In 64 bit mode we have to use 64 bits for addresses, even though the 11745 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address 11746 // registers without caring whether they're 32 or 64, but here we're 11747 // doing actual arithmetic on the addresses. 11748 bool is64bit = Subtarget.isPPC64(); 11749 bool isLittleEndian = Subtarget.isLittleEndian(); 11750 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 11751 11752 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 11753 MachineFunction::iterator It = ++BB->getIterator(); 11754 11755 Register dest = MI.getOperand(0).getReg(); 11756 Register ptrA = MI.getOperand(1).getReg(); 11757 Register ptrB = MI.getOperand(2).getReg(); 11758 11759 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); 11760 MachineBasicBlock *loop2MBB = 11761 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr; 11762 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 11763 F->insert(It, loopMBB); 11764 if (CmpOpcode) 11765 F->insert(It, loop2MBB); 11766 F->insert(It, exitMBB); 11767 exitMBB->splice(exitMBB->begin(), BB, 11768 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 11769 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 11770 11771 const TargetRegisterClass *RC = 11772 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 11773 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 11774 11775 Register PtrReg = RegInfo.createVirtualRegister(RC); 11776 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 11777 Register ShiftReg = 11778 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 11779 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC); 11780 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 11781 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 11782 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 11783 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 11784 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC); 11785 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 11786 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 11787 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC); 11788 Register Ptr1Reg; 11789 Register TmpReg = 11790 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC); 11791 11792 // thisMBB: 11793 // ... 11794 // fallthrough --> loopMBB 11795 BB->addSuccessor(loopMBB); 11796 11797 // The 4-byte load must be aligned, while a char or short may be 11798 // anywhere in the word. Hence all this nasty bookkeeping code. 11799 // add ptr1, ptrA, ptrB [copy if ptrA==0] 11800 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 11801 // xori shift, shift1, 24 [16] 11802 // rlwinm ptr, ptr1, 0, 0, 29 11803 // slw incr2, incr, shift 11804 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 11805 // slw mask, mask2, shift 11806 // loopMBB: 11807 // lwarx tmpDest, ptr 11808 // add tmp, tmpDest, incr2 11809 // andc tmp2, tmpDest, mask 11810 // and tmp3, tmp, mask 11811 // or tmp4, tmp3, tmp2 11812 // stwcx. tmp4, ptr 11813 // bne- loopMBB 11814 // fallthrough --> exitMBB 11815 // srw SrwDest, tmpDest, shift 11816 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31 11817 if (ptrA != ZeroReg) { 11818 Ptr1Reg = RegInfo.createVirtualRegister(RC); 11819 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 11820 .addReg(ptrA) 11821 .addReg(ptrB); 11822 } else { 11823 Ptr1Reg = ptrB; 11824 } 11825 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 11826 // mode. 11827 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 11828 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 11829 .addImm(3) 11830 .addImm(27) 11831 .addImm(is8bit ? 28 : 27); 11832 if (!isLittleEndian) 11833 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 11834 .addReg(Shift1Reg) 11835 .addImm(is8bit ? 24 : 16); 11836 if (is64bit) 11837 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 11838 .addReg(Ptr1Reg) 11839 .addImm(0) 11840 .addImm(61); 11841 else 11842 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 11843 .addReg(Ptr1Reg) 11844 .addImm(0) 11845 .addImm(0) 11846 .addImm(29); 11847 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg); 11848 if (is8bit) 11849 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 11850 else { 11851 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 11852 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 11853 .addReg(Mask3Reg) 11854 .addImm(65535); 11855 } 11856 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 11857 .addReg(Mask2Reg) 11858 .addReg(ShiftReg); 11859 11860 BB = loopMBB; 11861 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 11862 .addReg(ZeroReg) 11863 .addReg(PtrReg); 11864 if (BinOpcode) 11865 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) 11866 .addReg(Incr2Reg) 11867 .addReg(TmpDestReg); 11868 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 11869 .addReg(TmpDestReg) 11870 .addReg(MaskReg); 11871 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg); 11872 if (CmpOpcode) { 11873 // For unsigned comparisons, we can directly compare the shifted values. 11874 // For signed comparisons we shift and sign extend. 11875 Register SReg = RegInfo.createVirtualRegister(GPRC); 11876 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 11877 BuildMI(BB, dl, TII->get(PPC::AND), SReg) 11878 .addReg(TmpDestReg) 11879 .addReg(MaskReg); 11880 unsigned ValueReg = SReg; 11881 unsigned CmpReg = Incr2Reg; 11882 if (CmpOpcode == PPC::CMPW) { 11883 ValueReg = RegInfo.createVirtualRegister(GPRC); 11884 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg) 11885 .addReg(SReg) 11886 .addReg(ShiftReg); 11887 Register ValueSReg = RegInfo.createVirtualRegister(GPRC); 11888 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg) 11889 .addReg(ValueReg); 11890 ValueReg = ValueSReg; 11891 CmpReg = incr; 11892 } 11893 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg); 11894 BuildMI(BB, dl, TII->get(PPC::BCC)) 11895 .addImm(CmpPred) 11896 .addReg(CrReg) 11897 .addMBB(exitMBB); 11898 BB->addSuccessor(loop2MBB); 11899 BB->addSuccessor(exitMBB); 11900 BB = loop2MBB; 11901 } 11902 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg); 11903 BuildMI(BB, dl, TII->get(PPC::STWCX)) 11904 .addReg(Tmp4Reg) 11905 .addReg(ZeroReg) 11906 .addReg(PtrReg); 11907 BuildMI(BB, dl, TII->get(PPC::BCC)) 11908 .addImm(PPC::PRED_NE) 11909 .addReg(PPC::CR0) 11910 .addMBB(loopMBB); 11911 BB->addSuccessor(loopMBB); 11912 BB->addSuccessor(exitMBB); 11913 11914 // exitMBB: 11915 // ... 11916 BB = exitMBB; 11917 // Since the shift amount is not a constant, we need to clear 11918 // the upper bits with a separate RLWINM. 11919 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest) 11920 .addReg(SrwDestReg) 11921 .addImm(0) 11922 .addImm(is8bit ? 24 : 16) 11923 .addImm(31); 11924 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg) 11925 .addReg(TmpDestReg) 11926 .addReg(ShiftReg); 11927 return BB; 11928 } 11929 11930 llvm::MachineBasicBlock * 11931 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 11932 MachineBasicBlock *MBB) const { 11933 DebugLoc DL = MI.getDebugLoc(); 11934 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 11935 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11936 11937 MachineFunction *MF = MBB->getParent(); 11938 MachineRegisterInfo &MRI = MF->getRegInfo(); 11939 11940 const BasicBlock *BB = MBB->getBasicBlock(); 11941 MachineFunction::iterator I = ++MBB->getIterator(); 11942 11943 Register DstReg = MI.getOperand(0).getReg(); 11944 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 11945 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 11946 Register mainDstReg = MRI.createVirtualRegister(RC); 11947 Register restoreDstReg = MRI.createVirtualRegister(RC); 11948 11949 MVT PVT = getPointerTy(MF->getDataLayout()); 11950 assert((PVT == MVT::i64 || PVT == MVT::i32) && 11951 "Invalid Pointer Size!"); 11952 // For v = setjmp(buf), we generate 11953 // 11954 // thisMBB: 11955 // SjLjSetup mainMBB 11956 // bl mainMBB 11957 // v_restore = 1 11958 // b sinkMBB 11959 // 11960 // mainMBB: 11961 // buf[LabelOffset] = LR 11962 // v_main = 0 11963 // 11964 // sinkMBB: 11965 // v = phi(main, restore) 11966 // 11967 11968 MachineBasicBlock *thisMBB = MBB; 11969 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); 11970 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); 11971 MF->insert(I, mainMBB); 11972 MF->insert(I, sinkMBB); 11973 11974 MachineInstrBuilder MIB; 11975 11976 // Transfer the remainder of BB and its successor edges to sinkMBB. 11977 sinkMBB->splice(sinkMBB->begin(), MBB, 11978 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 11979 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 11980 11981 // Note that the structure of the jmp_buf used here is not compatible 11982 // with that used by libc, and is not designed to be. Specifically, it 11983 // stores only those 'reserved' registers that LLVM does not otherwise 11984 // understand how to spill. Also, by convention, by the time this 11985 // intrinsic is called, Clang has already stored the frame address in the 11986 // first slot of the buffer and stack address in the third. Following the 11987 // X86 target code, we'll store the jump address in the second slot. We also 11988 // need to save the TOC pointer (R2) to handle jumps between shared 11989 // libraries, and that will be stored in the fourth slot. The thread 11990 // identifier (R13) is not affected. 11991 11992 // thisMBB: 11993 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 11994 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 11995 const int64_t BPOffset = 4 * PVT.getStoreSize(); 11996 11997 // Prepare IP either in reg. 11998 const TargetRegisterClass *PtrRC = getRegClassFor(PVT); 11999 Register LabelReg = MRI.createVirtualRegister(PtrRC); 12000 Register BufReg = MI.getOperand(1).getReg(); 12001 12002 if (Subtarget.is64BitELFABI()) { 12003 setUsesTOCBasePtr(*MBB->getParent()); 12004 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) 12005 .addReg(PPC::X2) 12006 .addImm(TOCOffset) 12007 .addReg(BufReg) 12008 .cloneMemRefs(MI); 12009 } 12010 12011 // Naked functions never have a base pointer, and so we use r1. For all 12012 // other functions, this decision must be delayed until during PEI. 12013 unsigned BaseReg; 12014 if (MF->getFunction().hasFnAttribute(Attribute::Naked)) 12015 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; 12016 else 12017 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; 12018 12019 MIB = BuildMI(*thisMBB, MI, DL, 12020 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) 12021 .addReg(BaseReg) 12022 .addImm(BPOffset) 12023 .addReg(BufReg) 12024 .cloneMemRefs(MI); 12025 12026 // Setup 12027 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); 12028 MIB.addRegMask(TRI->getNoPreservedMask()); 12029 12030 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); 12031 12032 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) 12033 .addMBB(mainMBB); 12034 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); 12035 12036 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); 12037 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); 12038 12039 // mainMBB: 12040 // mainDstReg = 0 12041 MIB = 12042 BuildMI(mainMBB, DL, 12043 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); 12044 12045 // Store IP 12046 if (Subtarget.isPPC64()) { 12047 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) 12048 .addReg(LabelReg) 12049 .addImm(LabelOffset) 12050 .addReg(BufReg); 12051 } else { 12052 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) 12053 .addReg(LabelReg) 12054 .addImm(LabelOffset) 12055 .addReg(BufReg); 12056 } 12057 MIB.cloneMemRefs(MI); 12058 12059 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); 12060 mainMBB->addSuccessor(sinkMBB); 12061 12062 // sinkMBB: 12063 BuildMI(*sinkMBB, sinkMBB->begin(), DL, 12064 TII->get(PPC::PHI), DstReg) 12065 .addReg(mainDstReg).addMBB(mainMBB) 12066 .addReg(restoreDstReg).addMBB(thisMBB); 12067 12068 MI.eraseFromParent(); 12069 return sinkMBB; 12070 } 12071 12072 MachineBasicBlock * 12073 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 12074 MachineBasicBlock *MBB) const { 12075 DebugLoc DL = MI.getDebugLoc(); 12076 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12077 12078 MachineFunction *MF = MBB->getParent(); 12079 MachineRegisterInfo &MRI = MF->getRegInfo(); 12080 12081 MVT PVT = getPointerTy(MF->getDataLayout()); 12082 assert((PVT == MVT::i64 || PVT == MVT::i32) && 12083 "Invalid Pointer Size!"); 12084 12085 const TargetRegisterClass *RC = 12086 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12087 Register Tmp = MRI.createVirtualRegister(RC); 12088 // Since FP is only updated here but NOT referenced, it's treated as GPR. 12089 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; 12090 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; 12091 unsigned BP = 12092 (PVT == MVT::i64) 12093 ? PPC::X30 12094 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29 12095 : PPC::R30); 12096 12097 MachineInstrBuilder MIB; 12098 12099 const int64_t LabelOffset = 1 * PVT.getStoreSize(); 12100 const int64_t SPOffset = 2 * PVT.getStoreSize(); 12101 const int64_t TOCOffset = 3 * PVT.getStoreSize(); 12102 const int64_t BPOffset = 4 * PVT.getStoreSize(); 12103 12104 Register BufReg = MI.getOperand(0).getReg(); 12105 12106 // Reload FP (the jumped-to function may not have had a 12107 // frame pointer, and if so, then its r31 will be restored 12108 // as necessary). 12109 if (PVT == MVT::i64) { 12110 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) 12111 .addImm(0) 12112 .addReg(BufReg); 12113 } else { 12114 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) 12115 .addImm(0) 12116 .addReg(BufReg); 12117 } 12118 MIB.cloneMemRefs(MI); 12119 12120 // Reload IP 12121 if (PVT == MVT::i64) { 12122 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) 12123 .addImm(LabelOffset) 12124 .addReg(BufReg); 12125 } else { 12126 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) 12127 .addImm(LabelOffset) 12128 .addReg(BufReg); 12129 } 12130 MIB.cloneMemRefs(MI); 12131 12132 // Reload SP 12133 if (PVT == MVT::i64) { 12134 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) 12135 .addImm(SPOffset) 12136 .addReg(BufReg); 12137 } else { 12138 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) 12139 .addImm(SPOffset) 12140 .addReg(BufReg); 12141 } 12142 MIB.cloneMemRefs(MI); 12143 12144 // Reload BP 12145 if (PVT == MVT::i64) { 12146 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) 12147 .addImm(BPOffset) 12148 .addReg(BufReg); 12149 } else { 12150 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) 12151 .addImm(BPOffset) 12152 .addReg(BufReg); 12153 } 12154 MIB.cloneMemRefs(MI); 12155 12156 // Reload TOC 12157 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { 12158 setUsesTOCBasePtr(*MBB->getParent()); 12159 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) 12160 .addImm(TOCOffset) 12161 .addReg(BufReg) 12162 .cloneMemRefs(MI); 12163 } 12164 12165 // Jump 12166 BuildMI(*MBB, MI, DL, 12167 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); 12168 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); 12169 12170 MI.eraseFromParent(); 12171 return MBB; 12172 } 12173 12174 bool PPCTargetLowering::hasInlineStackProbe(const MachineFunction &MF) const { 12175 // If the function specifically requests inline stack probes, emit them. 12176 if (MF.getFunction().hasFnAttribute("probe-stack")) 12177 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() == 12178 "inline-asm"; 12179 return false; 12180 } 12181 12182 unsigned PPCTargetLowering::getStackProbeSize(const MachineFunction &MF) const { 12183 const TargetFrameLowering *TFI = Subtarget.getFrameLowering(); 12184 unsigned StackAlign = TFI->getStackAlignment(); 12185 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) && 12186 "Unexpected stack alignment"); 12187 // The default stack probe size is 4096 if the function has no 12188 // stack-probe-size attribute. 12189 const Function &Fn = MF.getFunction(); 12190 unsigned StackProbeSize = 12191 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096); 12192 // Round down to the stack alignment. 12193 StackProbeSize &= ~(StackAlign - 1); 12194 return StackProbeSize ? StackProbeSize : StackAlign; 12195 } 12196 12197 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted 12198 // into three phases. In the first phase, it uses pseudo instruction 12199 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and 12200 // FinalStackPtr. In the second phase, it generates a loop for probing blocks. 12201 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of 12202 // MaxCallFrameSize so that it can calculate correct data area pointer. 12203 MachineBasicBlock * 12204 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI, 12205 MachineBasicBlock *MBB) const { 12206 const bool isPPC64 = Subtarget.isPPC64(); 12207 MachineFunction *MF = MBB->getParent(); 12208 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12209 DebugLoc DL = MI.getDebugLoc(); 12210 const unsigned ProbeSize = getStackProbeSize(*MF); 12211 const BasicBlock *ProbedBB = MBB->getBasicBlock(); 12212 MachineRegisterInfo &MRI = MF->getRegInfo(); 12213 // The CFG of probing stack looks as 12214 // +-----+ 12215 // | MBB | 12216 // +--+--+ 12217 // | 12218 // +----v----+ 12219 // +--->+ TestMBB +---+ 12220 // | +----+----+ | 12221 // | | | 12222 // | +-----v----+ | 12223 // +---+ BlockMBB | | 12224 // +----------+ | 12225 // | 12226 // +---------+ | 12227 // | TailMBB +<--+ 12228 // +---------+ 12229 // In MBB, calculate previous frame pointer and final stack pointer. 12230 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to 12231 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB. 12232 // TailMBB is spliced via \p MI. 12233 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB); 12234 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB); 12235 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB); 12236 12237 MachineFunction::iterator MBBIter = ++MBB->getIterator(); 12238 MF->insert(MBBIter, TestMBB); 12239 MF->insert(MBBIter, BlockMBB); 12240 MF->insert(MBBIter, TailMBB); 12241 12242 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass; 12243 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12244 12245 Register DstReg = MI.getOperand(0).getReg(); 12246 Register NegSizeReg = MI.getOperand(1).getReg(); 12247 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1; 12248 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12249 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12250 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12251 12252 // Since value of NegSizeReg might be realigned in prologepilog, insert a 12253 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and 12254 // NegSize. 12255 unsigned ProbeOpc; 12256 if (!MRI.hasOneNonDBGUse(NegSizeReg)) 12257 ProbeOpc = 12258 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32; 12259 else 12260 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg 12261 // and NegSizeReg will be allocated in the same phyreg to avoid 12262 // redundant copy when NegSizeReg has only one use which is current MI and 12263 // will be replaced by PREPARE_PROBED_ALLOCA then. 12264 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 12265 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32; 12266 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer) 12267 .addDef(ActualNegSizeReg) 12268 .addReg(NegSizeReg) 12269 .add(MI.getOperand(2)) 12270 .add(MI.getOperand(3)); 12271 12272 // Calculate final stack pointer, which equals to SP + ActualNegSize. 12273 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), 12274 FinalStackPtr) 12275 .addReg(SPReg) 12276 .addReg(ActualNegSizeReg); 12277 12278 // Materialize a scratch register for update. 12279 int64_t NegProbeSize = -(int64_t)ProbeSize; 12280 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!"); 12281 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12282 if (!isInt<16>(NegProbeSize)) { 12283 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12284 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg) 12285 .addImm(NegProbeSize >> 16); 12286 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI), 12287 ScratchReg) 12288 .addReg(TempReg) 12289 .addImm(NegProbeSize & 0xFFFF); 12290 } else 12291 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg) 12292 .addImm(NegProbeSize); 12293 12294 { 12295 // Probing leading residual part. 12296 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12297 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div) 12298 .addReg(ActualNegSizeReg) 12299 .addReg(ScratchReg); 12300 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12301 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul) 12302 .addReg(Div) 12303 .addReg(ScratchReg); 12304 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12305 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod) 12306 .addReg(Mul) 12307 .addReg(ActualNegSizeReg); 12308 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12309 .addReg(FramePointer) 12310 .addReg(SPReg) 12311 .addReg(NegMod); 12312 } 12313 12314 { 12315 // Remaining part should be multiple of ProbeSize. 12316 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass); 12317 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult) 12318 .addReg(SPReg) 12319 .addReg(FinalStackPtr); 12320 BuildMI(TestMBB, DL, TII->get(PPC::BCC)) 12321 .addImm(PPC::PRED_EQ) 12322 .addReg(CmpResult) 12323 .addMBB(TailMBB); 12324 TestMBB->addSuccessor(BlockMBB); 12325 TestMBB->addSuccessor(TailMBB); 12326 } 12327 12328 { 12329 // Touch the block. 12330 // |P...|P...|P... 12331 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg) 12332 .addReg(FramePointer) 12333 .addReg(SPReg) 12334 .addReg(ScratchReg); 12335 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB); 12336 BlockMBB->addSuccessor(TestMBB); 12337 } 12338 12339 // Calculation of MaxCallFrameSize is deferred to prologepilog, use 12340 // DYNAREAOFFSET pseudo instruction to get the future result. 12341 Register MaxCallFrameSizeReg = 12342 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC); 12343 BuildMI(TailMBB, DL, 12344 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET), 12345 MaxCallFrameSizeReg) 12346 .add(MI.getOperand(2)) 12347 .add(MI.getOperand(3)); 12348 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg) 12349 .addReg(SPReg) 12350 .addReg(MaxCallFrameSizeReg); 12351 12352 // Splice instructions after MI to TailMBB. 12353 TailMBB->splice(TailMBB->end(), MBB, 12354 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 12355 TailMBB->transferSuccessorsAndUpdatePHIs(MBB); 12356 MBB->addSuccessor(TestMBB); 12357 12358 // Delete the pseudo instruction. 12359 MI.eraseFromParent(); 12360 12361 ++NumDynamicAllocaProbed; 12362 return TailMBB; 12363 } 12364 12365 MachineBasicBlock * 12366 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 12367 MachineBasicBlock *BB) const { 12368 if (MI.getOpcode() == TargetOpcode::STACKMAP || 12369 MI.getOpcode() == TargetOpcode::PATCHPOINT) { 12370 if (Subtarget.is64BitELFABI() && 12371 MI.getOpcode() == TargetOpcode::PATCHPOINT && 12372 !Subtarget.isUsingPCRelativeCalls()) { 12373 // Call lowering should have added an r2 operand to indicate a dependence 12374 // on the TOC base pointer value. It can't however, because there is no 12375 // way to mark the dependence as implicit there, and so the stackmap code 12376 // will confuse it with a regular operand. Instead, add the dependence 12377 // here. 12378 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); 12379 } 12380 12381 return emitPatchPoint(MI, BB); 12382 } 12383 12384 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 || 12385 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) { 12386 return emitEHSjLjSetJmp(MI, BB); 12387 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 || 12388 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) { 12389 return emitEHSjLjLongJmp(MI, BB); 12390 } 12391 12392 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 12393 12394 // To "insert" these instructions we actually have to insert their 12395 // control-flow patterns. 12396 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 12397 MachineFunction::iterator It = ++BB->getIterator(); 12398 12399 MachineFunction *F = BB->getParent(); 12400 MachineRegisterInfo &MRI = F->getRegInfo(); 12401 12402 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12403 MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 || 12404 MI.getOpcode() == PPC::SELECT_I8) { 12405 SmallVector<MachineOperand, 2> Cond; 12406 if (MI.getOpcode() == PPC::SELECT_CC_I4 || 12407 MI.getOpcode() == PPC::SELECT_CC_I8) 12408 Cond.push_back(MI.getOperand(4)); 12409 else 12410 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 12411 Cond.push_back(MI.getOperand(1)); 12412 12413 DebugLoc dl = MI.getDebugLoc(); 12414 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond, 12415 MI.getOperand(2).getReg(), MI.getOperand(3).getReg()); 12416 } else if (MI.getOpcode() == PPC::SELECT_CC_F4 || 12417 MI.getOpcode() == PPC::SELECT_CC_F8 || 12418 MI.getOpcode() == PPC::SELECT_CC_F16 || 12419 MI.getOpcode() == PPC::SELECT_CC_VRRC || 12420 MI.getOpcode() == PPC::SELECT_CC_VSFRC || 12421 MI.getOpcode() == PPC::SELECT_CC_VSSRC || 12422 MI.getOpcode() == PPC::SELECT_CC_VSRC || 12423 MI.getOpcode() == PPC::SELECT_CC_SPE4 || 12424 MI.getOpcode() == PPC::SELECT_CC_SPE || 12425 MI.getOpcode() == PPC::SELECT_F4 || 12426 MI.getOpcode() == PPC::SELECT_F8 || 12427 MI.getOpcode() == PPC::SELECT_F16 || 12428 MI.getOpcode() == PPC::SELECT_SPE || 12429 MI.getOpcode() == PPC::SELECT_SPE4 || 12430 MI.getOpcode() == PPC::SELECT_VRRC || 12431 MI.getOpcode() == PPC::SELECT_VSFRC || 12432 MI.getOpcode() == PPC::SELECT_VSSRC || 12433 MI.getOpcode() == PPC::SELECT_VSRC) { 12434 // The incoming instruction knows the destination vreg to set, the 12435 // condition code register to branch on, the true/false values to 12436 // select between, and a branch opcode to use. 12437 12438 // thisMBB: 12439 // ... 12440 // TrueVal = ... 12441 // cmpTY ccX, r1, r2 12442 // bCC copy1MBB 12443 // fallthrough --> copy0MBB 12444 MachineBasicBlock *thisMBB = BB; 12445 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); 12446 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12447 DebugLoc dl = MI.getDebugLoc(); 12448 F->insert(It, copy0MBB); 12449 F->insert(It, sinkMBB); 12450 12451 // Transfer the remainder of BB and its successor edges to sinkMBB. 12452 sinkMBB->splice(sinkMBB->begin(), BB, 12453 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12454 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12455 12456 // Next, add the true and fallthrough blocks as its successors. 12457 BB->addSuccessor(copy0MBB); 12458 BB->addSuccessor(sinkMBB); 12459 12460 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 || 12461 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 || 12462 MI.getOpcode() == PPC::SELECT_F16 || 12463 MI.getOpcode() == PPC::SELECT_SPE4 || 12464 MI.getOpcode() == PPC::SELECT_SPE || 12465 MI.getOpcode() == PPC::SELECT_VRRC || 12466 MI.getOpcode() == PPC::SELECT_VSFRC || 12467 MI.getOpcode() == PPC::SELECT_VSSRC || 12468 MI.getOpcode() == PPC::SELECT_VSRC) { 12469 BuildMI(BB, dl, TII->get(PPC::BC)) 12470 .addReg(MI.getOperand(1).getReg()) 12471 .addMBB(sinkMBB); 12472 } else { 12473 unsigned SelectPred = MI.getOperand(4).getImm(); 12474 BuildMI(BB, dl, TII->get(PPC::BCC)) 12475 .addImm(SelectPred) 12476 .addReg(MI.getOperand(1).getReg()) 12477 .addMBB(sinkMBB); 12478 } 12479 12480 // copy0MBB: 12481 // %FalseValue = ... 12482 // # fallthrough to sinkMBB 12483 BB = copy0MBB; 12484 12485 // Update machine-CFG edges 12486 BB->addSuccessor(sinkMBB); 12487 12488 // sinkMBB: 12489 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] 12490 // ... 12491 BB = sinkMBB; 12492 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg()) 12493 .addReg(MI.getOperand(3).getReg()) 12494 .addMBB(copy0MBB) 12495 .addReg(MI.getOperand(2).getReg()) 12496 .addMBB(thisMBB); 12497 } else if (MI.getOpcode() == PPC::ReadTB) { 12498 // To read the 64-bit time-base register on a 32-bit target, we read the 12499 // two halves. Should the counter have wrapped while it was being read, we 12500 // need to try again. 12501 // ... 12502 // readLoop: 12503 // mfspr Rx,TBU # load from TBU 12504 // mfspr Ry,TB # load from TB 12505 // mfspr Rz,TBU # load from TBU 12506 // cmpw crX,Rx,Rz # check if 'old'='new' 12507 // bne readLoop # branch if they're not equal 12508 // ... 12509 12510 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); 12511 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 12512 DebugLoc dl = MI.getDebugLoc(); 12513 F->insert(It, readMBB); 12514 F->insert(It, sinkMBB); 12515 12516 // Transfer the remainder of BB and its successor edges to sinkMBB. 12517 sinkMBB->splice(sinkMBB->begin(), BB, 12518 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12519 sinkMBB->transferSuccessorsAndUpdatePHIs(BB); 12520 12521 BB->addSuccessor(readMBB); 12522 BB = readMBB; 12523 12524 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12525 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); 12526 Register LoReg = MI.getOperand(0).getReg(); 12527 Register HiReg = MI.getOperand(1).getReg(); 12528 12529 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); 12530 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); 12531 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); 12532 12533 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12534 12535 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) 12536 .addReg(HiReg) 12537 .addReg(ReadAgainReg); 12538 BuildMI(BB, dl, TII->get(PPC::BCC)) 12539 .addImm(PPC::PRED_NE) 12540 .addReg(CmpReg) 12541 .addMBB(readMBB); 12542 12543 BB->addSuccessor(readMBB); 12544 BB->addSuccessor(sinkMBB); 12545 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) 12546 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); 12547 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) 12548 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); 12549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) 12550 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); 12551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) 12552 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); 12553 12554 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8) 12555 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); 12556 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16) 12557 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); 12558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32) 12559 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); 12560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64) 12561 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); 12562 12563 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8) 12564 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); 12565 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16) 12566 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); 12567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32) 12568 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); 12569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64) 12570 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); 12571 12572 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) 12573 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); 12574 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) 12575 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); 12576 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) 12577 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); 12578 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) 12579 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); 12580 12581 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) 12582 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); 12583 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) 12584 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); 12585 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) 12586 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); 12587 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) 12588 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); 12589 12590 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) 12591 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); 12592 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) 12593 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); 12594 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) 12595 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); 12596 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) 12597 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); 12598 12599 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8) 12600 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LT); 12601 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16) 12602 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LT); 12603 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32) 12604 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LT); 12605 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64) 12606 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LT); 12607 12608 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8) 12609 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GT); 12610 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16) 12611 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GT); 12612 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32) 12613 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GT); 12614 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64) 12615 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GT); 12616 12617 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8) 12618 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LT); 12619 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16) 12620 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LT); 12621 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32) 12622 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LT); 12623 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64) 12624 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LT); 12625 12626 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8) 12627 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GT); 12628 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16) 12629 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GT); 12630 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32) 12631 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GT); 12632 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64) 12633 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GT); 12634 12635 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8) 12636 BB = EmitPartwordAtomicBinary(MI, BB, true, 0); 12637 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16) 12638 BB = EmitPartwordAtomicBinary(MI, BB, false, 0); 12639 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32) 12640 BB = EmitAtomicBinary(MI, BB, 4, 0); 12641 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64) 12642 BB = EmitAtomicBinary(MI, BB, 8, 0); 12643 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || 12644 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || 12645 (Subtarget.hasPartwordAtomics() && 12646 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || 12647 (Subtarget.hasPartwordAtomics() && 12648 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { 12649 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; 12650 12651 auto LoadMnemonic = PPC::LDARX; 12652 auto StoreMnemonic = PPC::STDCX; 12653 switch (MI.getOpcode()) { 12654 default: 12655 llvm_unreachable("Compare and swap of unknown size"); 12656 case PPC::ATOMIC_CMP_SWAP_I8: 12657 LoadMnemonic = PPC::LBARX; 12658 StoreMnemonic = PPC::STBCX; 12659 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12660 break; 12661 case PPC::ATOMIC_CMP_SWAP_I16: 12662 LoadMnemonic = PPC::LHARX; 12663 StoreMnemonic = PPC::STHCX; 12664 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); 12665 break; 12666 case PPC::ATOMIC_CMP_SWAP_I32: 12667 LoadMnemonic = PPC::LWARX; 12668 StoreMnemonic = PPC::STWCX; 12669 break; 12670 case PPC::ATOMIC_CMP_SWAP_I64: 12671 LoadMnemonic = PPC::LDARX; 12672 StoreMnemonic = PPC::STDCX; 12673 break; 12674 } 12675 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12676 Register dest = MI.getOperand(0).getReg(); 12677 Register ptrA = MI.getOperand(1).getReg(); 12678 Register ptrB = MI.getOperand(2).getReg(); 12679 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12680 Register oldval = MI.getOperand(3).getReg(); 12681 Register newval = MI.getOperand(4).getReg(); 12682 DebugLoc dl = MI.getDebugLoc(); 12683 12684 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12685 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12686 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12687 F->insert(It, loop1MBB); 12688 F->insert(It, loop2MBB); 12689 F->insert(It, exitMBB); 12690 exitMBB->splice(exitMBB->begin(), BB, 12691 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12692 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12693 12694 // thisMBB: 12695 // ... 12696 // fallthrough --> loopMBB 12697 BB->addSuccessor(loop1MBB); 12698 12699 // loop1MBB: 12700 // l[bhwd]arx dest, ptr 12701 // cmp[wd] dest, oldval 12702 // bne- exitBB 12703 // loop2MBB: 12704 // st[bhwd]cx. newval, ptr 12705 // bne- loopMBB 12706 // b exitBB 12707 // exitBB: 12708 BB = loop1MBB; 12709 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB); 12710 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg) 12711 .addReg(dest) 12712 .addReg(oldval); 12713 BuildMI(BB, dl, TII->get(PPC::BCC)) 12714 .addImm(PPC::PRED_NE) 12715 .addReg(CrReg) 12716 .addMBB(exitMBB); 12717 BB->addSuccessor(loop2MBB); 12718 BB->addSuccessor(exitMBB); 12719 12720 BB = loop2MBB; 12721 BuildMI(BB, dl, TII->get(StoreMnemonic)) 12722 .addReg(newval) 12723 .addReg(ptrA) 12724 .addReg(ptrB); 12725 BuildMI(BB, dl, TII->get(PPC::BCC)) 12726 .addImm(PPC::PRED_NE) 12727 .addReg(PPC::CR0) 12728 .addMBB(loop1MBB); 12729 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12730 BB->addSuccessor(loop1MBB); 12731 BB->addSuccessor(exitMBB); 12732 12733 // exitMBB: 12734 // ... 12735 BB = exitMBB; 12736 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || 12737 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { 12738 // We must use 64-bit registers for addresses when targeting 64-bit, 12739 // since we're actually doing arithmetic on them. Other registers 12740 // can be 32-bit. 12741 bool is64bit = Subtarget.isPPC64(); 12742 bool isLittleEndian = Subtarget.isLittleEndian(); 12743 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; 12744 12745 Register dest = MI.getOperand(0).getReg(); 12746 Register ptrA = MI.getOperand(1).getReg(); 12747 Register ptrB = MI.getOperand(2).getReg(); 12748 Register oldval = MI.getOperand(3).getReg(); 12749 Register newval = MI.getOperand(4).getReg(); 12750 DebugLoc dl = MI.getDebugLoc(); 12751 12752 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); 12753 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); 12754 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); 12755 F->insert(It, loop1MBB); 12756 F->insert(It, loop2MBB); 12757 F->insert(It, exitMBB); 12758 exitMBB->splice(exitMBB->begin(), BB, 12759 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 12760 exitMBB->transferSuccessorsAndUpdatePHIs(BB); 12761 12762 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12763 const TargetRegisterClass *RC = 12764 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; 12765 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass; 12766 12767 Register PtrReg = RegInfo.createVirtualRegister(RC); 12768 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC); 12769 Register ShiftReg = 12770 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC); 12771 Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC); 12772 Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC); 12773 Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC); 12774 Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC); 12775 Register MaskReg = RegInfo.createVirtualRegister(GPRC); 12776 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC); 12777 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC); 12778 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC); 12779 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC); 12780 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC); 12781 Register Ptr1Reg; 12782 Register TmpReg = RegInfo.createVirtualRegister(GPRC); 12783 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; 12784 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12785 // thisMBB: 12786 // ... 12787 // fallthrough --> loopMBB 12788 BB->addSuccessor(loop1MBB); 12789 12790 // The 4-byte load must be aligned, while a char or short may be 12791 // anywhere in the word. Hence all this nasty bookkeeping code. 12792 // add ptr1, ptrA, ptrB [copy if ptrA==0] 12793 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] 12794 // xori shift, shift1, 24 [16] 12795 // rlwinm ptr, ptr1, 0, 0, 29 12796 // slw newval2, newval, shift 12797 // slw oldval2, oldval,shift 12798 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] 12799 // slw mask, mask2, shift 12800 // and newval3, newval2, mask 12801 // and oldval3, oldval2, mask 12802 // loop1MBB: 12803 // lwarx tmpDest, ptr 12804 // and tmp, tmpDest, mask 12805 // cmpw tmp, oldval3 12806 // bne- exitBB 12807 // loop2MBB: 12808 // andc tmp2, tmpDest, mask 12809 // or tmp4, tmp2, newval3 12810 // stwcx. tmp4, ptr 12811 // bne- loop1MBB 12812 // b exitBB 12813 // exitBB: 12814 // srw dest, tmpDest, shift 12815 if (ptrA != ZeroReg) { 12816 Ptr1Reg = RegInfo.createVirtualRegister(RC); 12817 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) 12818 .addReg(ptrA) 12819 .addReg(ptrB); 12820 } else { 12821 Ptr1Reg = ptrB; 12822 } 12823 12824 // We need use 32-bit subregister to avoid mismatch register class in 64-bit 12825 // mode. 12826 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg) 12827 .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0) 12828 .addImm(3) 12829 .addImm(27) 12830 .addImm(is8bit ? 28 : 27); 12831 if (!isLittleEndian) 12832 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg) 12833 .addReg(Shift1Reg) 12834 .addImm(is8bit ? 24 : 16); 12835 if (is64bit) 12836 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) 12837 .addReg(Ptr1Reg) 12838 .addImm(0) 12839 .addImm(61); 12840 else 12841 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) 12842 .addReg(Ptr1Reg) 12843 .addImm(0) 12844 .addImm(0) 12845 .addImm(29); 12846 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) 12847 .addReg(newval) 12848 .addReg(ShiftReg); 12849 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) 12850 .addReg(oldval) 12851 .addReg(ShiftReg); 12852 if (is8bit) 12853 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); 12854 else { 12855 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); 12856 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) 12857 .addReg(Mask3Reg) 12858 .addImm(65535); 12859 } 12860 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) 12861 .addReg(Mask2Reg) 12862 .addReg(ShiftReg); 12863 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) 12864 .addReg(NewVal2Reg) 12865 .addReg(MaskReg); 12866 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) 12867 .addReg(OldVal2Reg) 12868 .addReg(MaskReg); 12869 12870 BB = loop1MBB; 12871 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) 12872 .addReg(ZeroReg) 12873 .addReg(PtrReg); 12874 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg) 12875 .addReg(TmpDestReg) 12876 .addReg(MaskReg); 12877 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg) 12878 .addReg(TmpReg) 12879 .addReg(OldVal3Reg); 12880 BuildMI(BB, dl, TII->get(PPC::BCC)) 12881 .addImm(PPC::PRED_NE) 12882 .addReg(CrReg) 12883 .addMBB(exitMBB); 12884 BB->addSuccessor(loop2MBB); 12885 BB->addSuccessor(exitMBB); 12886 12887 BB = loop2MBB; 12888 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg) 12889 .addReg(TmpDestReg) 12890 .addReg(MaskReg); 12891 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg) 12892 .addReg(Tmp2Reg) 12893 .addReg(NewVal3Reg); 12894 BuildMI(BB, dl, TII->get(PPC::STWCX)) 12895 .addReg(Tmp4Reg) 12896 .addReg(ZeroReg) 12897 .addReg(PtrReg); 12898 BuildMI(BB, dl, TII->get(PPC::BCC)) 12899 .addImm(PPC::PRED_NE) 12900 .addReg(PPC::CR0) 12901 .addMBB(loop1MBB); 12902 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); 12903 BB->addSuccessor(loop1MBB); 12904 BB->addSuccessor(exitMBB); 12905 12906 // exitMBB: 12907 // ... 12908 BB = exitMBB; 12909 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest) 12910 .addReg(TmpReg) 12911 .addReg(ShiftReg); 12912 } else if (MI.getOpcode() == PPC::FADDrtz) { 12913 // This pseudo performs an FADD with rounding mode temporarily forced 12914 // to round-to-zero. We emit this via custom inserter since the FPSCR 12915 // is not modeled at the SelectionDAG level. 12916 Register Dest = MI.getOperand(0).getReg(); 12917 Register Src1 = MI.getOperand(1).getReg(); 12918 Register Src2 = MI.getOperand(2).getReg(); 12919 DebugLoc dl = MI.getDebugLoc(); 12920 12921 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12922 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 12923 12924 // Save FPSCR value. 12925 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); 12926 12927 // Set rounding mode to round-to-zero. 12928 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)) 12929 .addImm(31) 12930 .addReg(PPC::RM, RegState::ImplicitDefine); 12931 12932 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)) 12933 .addImm(30) 12934 .addReg(PPC::RM, RegState::ImplicitDefine); 12935 12936 // Perform addition. 12937 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest) 12938 .addReg(Src1) 12939 .addReg(Src2); 12940 if (MI.getFlag(MachineInstr::NoFPExcept)) 12941 MIB.setMIFlag(MachineInstr::NoFPExcept); 12942 12943 // Restore FPSCR value. 12944 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); 12945 } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12946 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT || 12947 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12948 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) { 12949 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 || 12950 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) 12951 ? PPC::ANDI8_rec 12952 : PPC::ANDI_rec; 12953 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT || 12954 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8); 12955 12956 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12957 Register Dest = RegInfo.createVirtualRegister( 12958 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); 12959 12960 DebugLoc Dl = MI.getDebugLoc(); 12961 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest) 12962 .addReg(MI.getOperand(1).getReg()) 12963 .addImm(1); 12964 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12965 MI.getOperand(0).getReg()) 12966 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT); 12967 } else if (MI.getOpcode() == PPC::TCHECK_RET) { 12968 DebugLoc Dl = MI.getDebugLoc(); 12969 MachineRegisterInfo &RegInfo = F->getRegInfo(); 12970 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); 12971 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); 12972 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12973 MI.getOperand(0).getReg()) 12974 .addReg(CRReg); 12975 } else if (MI.getOpcode() == PPC::TBEGIN_RET) { 12976 DebugLoc Dl = MI.getDebugLoc(); 12977 unsigned Imm = MI.getOperand(1).getImm(); 12978 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm); 12979 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY), 12980 MI.getOperand(0).getReg()) 12981 .addReg(PPC::CR0EQ); 12982 } else if (MI.getOpcode() == PPC::SETRNDi) { 12983 DebugLoc dl = MI.getDebugLoc(); 12984 Register OldFPSCRReg = MI.getOperand(0).getReg(); 12985 12986 // Save FPSCR value. 12987 if (MRI.use_empty(OldFPSCRReg)) 12988 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 12989 else 12990 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 12991 12992 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has 12993 // the following settings: 12994 // 00 Round to nearest 12995 // 01 Round to 0 12996 // 10 Round to +inf 12997 // 11 Round to -inf 12998 12999 // When the operand is immediate, using the two least significant bits of 13000 // the immediate to set the bits 62:63 of FPSCR. 13001 unsigned Mode = MI.getOperand(1).getImm(); 13002 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0)) 13003 .addImm(31) 13004 .addReg(PPC::RM, RegState::ImplicitDefine); 13005 13006 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0)) 13007 .addImm(30) 13008 .addReg(PPC::RM, RegState::ImplicitDefine); 13009 } else if (MI.getOpcode() == PPC::SETRND) { 13010 DebugLoc dl = MI.getDebugLoc(); 13011 13012 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg 13013 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg. 13014 // If the target doesn't have DirectMove, we should use stack to do the 13015 // conversion, because the target doesn't have the instructions like mtvsrd 13016 // or mfvsrd to do this conversion directly. 13017 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) { 13018 if (Subtarget.hasDirectMove()) { 13019 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg) 13020 .addReg(SrcReg); 13021 } else { 13022 // Use stack to do the register copy. 13023 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD; 13024 MachineRegisterInfo &RegInfo = F->getRegInfo(); 13025 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg); 13026 if (RC == &PPC::F8RCRegClass) { 13027 // Copy register from F8RCRegClass to G8RCRegclass. 13028 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) && 13029 "Unsupported RegClass."); 13030 13031 StoreOp = PPC::STFD; 13032 LoadOp = PPC::LD; 13033 } else { 13034 // Copy register from G8RCRegClass to F8RCRegclass. 13035 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) && 13036 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) && 13037 "Unsupported RegClass."); 13038 } 13039 13040 MachineFrameInfo &MFI = F->getFrameInfo(); 13041 int FrameIdx = MFI.CreateStackObject(8, Align(8), false); 13042 13043 MachineMemOperand *MMOStore = F->getMachineMemOperand( 13044 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 13045 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 13046 MFI.getObjectAlign(FrameIdx)); 13047 13048 // Store the SrcReg into the stack. 13049 BuildMI(*BB, MI, dl, TII->get(StoreOp)) 13050 .addReg(SrcReg) 13051 .addImm(0) 13052 .addFrameIndex(FrameIdx) 13053 .addMemOperand(MMOStore); 13054 13055 MachineMemOperand *MMOLoad = F->getMachineMemOperand( 13056 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0), 13057 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 13058 MFI.getObjectAlign(FrameIdx)); 13059 13060 // Load from the stack where SrcReg is stored, and save to DestReg, 13061 // so we have done the RegClass conversion from RegClass::SrcReg to 13062 // RegClass::DestReg. 13063 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg) 13064 .addImm(0) 13065 .addFrameIndex(FrameIdx) 13066 .addMemOperand(MMOLoad); 13067 } 13068 }; 13069 13070 Register OldFPSCRReg = MI.getOperand(0).getReg(); 13071 13072 // Save FPSCR value. 13073 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg); 13074 13075 // When the operand is gprc register, use two least significant bits of the 13076 // register and mtfsf instruction to set the bits 62:63 of FPSCR. 13077 // 13078 // copy OldFPSCRTmpReg, OldFPSCRReg 13079 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1) 13080 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62 13081 // copy NewFPSCRReg, NewFPSCRTmpReg 13082 // mtfsf 255, NewFPSCRReg 13083 MachineOperand SrcOp = MI.getOperand(1); 13084 MachineRegisterInfo &RegInfo = F->getRegInfo(); 13085 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13086 13087 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg); 13088 13089 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13090 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13091 13092 // The first operand of INSERT_SUBREG should be a register which has 13093 // subregisters, we only care about its RegClass, so we should use an 13094 // IMPLICIT_DEF register. 13095 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg); 13096 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg) 13097 .addReg(ImDefReg) 13098 .add(SrcOp) 13099 .addImm(1); 13100 13101 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass); 13102 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg) 13103 .addReg(OldFPSCRTmpReg) 13104 .addReg(ExtSrcReg) 13105 .addImm(0) 13106 .addImm(62); 13107 13108 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); 13109 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg); 13110 13111 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63 13112 // bits of FPSCR. 13113 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)) 13114 .addImm(255) 13115 .addReg(NewFPSCRReg) 13116 .addImm(0) 13117 .addImm(0); 13118 } else if (MI.getOpcode() == PPC::SETFLM) { 13119 DebugLoc Dl = MI.getDebugLoc(); 13120 13121 // Result of setflm is previous FPSCR content, so we need to save it first. 13122 Register OldFPSCRReg = MI.getOperand(0).getReg(); 13123 if (MRI.use_empty(OldFPSCRReg)) 13124 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg); 13125 else 13126 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg); 13127 13128 // Put bits in 32:63 to FPSCR. 13129 Register NewFPSCRReg = MI.getOperand(1).getReg(); 13130 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF)) 13131 .addImm(255) 13132 .addReg(NewFPSCRReg) 13133 .addImm(0) 13134 .addImm(0); 13135 } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 || 13136 MI.getOpcode() == PPC::PROBED_ALLOCA_64) { 13137 return emitProbedAlloca(MI, BB); 13138 } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) { 13139 DebugLoc DL = MI.getDebugLoc(); 13140 Register Src = MI.getOperand(2).getReg(); 13141 Register Lo = MI.getOperand(0).getReg(); 13142 Register Hi = MI.getOperand(1).getReg(); 13143 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 13144 .addDef(Lo) 13145 .addUse(Src, 0, PPC::sub_gp8_x1); 13146 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY)) 13147 .addDef(Hi) 13148 .addUse(Src, 0, PPC::sub_gp8_x0); 13149 } else if (MI.getOpcode() == PPC::LQX_PSEUDO || 13150 MI.getOpcode() == PPC::STQX_PSEUDO) { 13151 DebugLoc DL = MI.getDebugLoc(); 13152 // Ptr is used as the ptr_rc_no_r0 part 13153 // of LQ/STQ's memory operand and adding result of RA and RB, 13154 // so it has to be g8rc_and_g8rc_nox0. 13155 Register Ptr = 13156 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 13157 Register Val = MI.getOperand(0).getReg(); 13158 Register RA = MI.getOperand(1).getReg(); 13159 Register RB = MI.getOperand(2).getReg(); 13160 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB); 13161 BuildMI(*BB, MI, DL, 13162 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ) 13163 : TII->get(PPC::STQ)) 13164 .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0) 13165 .addImm(0) 13166 .addReg(Ptr); 13167 } else { 13168 llvm_unreachable("Unexpected instr type to insert"); 13169 } 13170 13171 MI.eraseFromParent(); // The pseudo instruction is gone now. 13172 return BB; 13173 } 13174 13175 //===----------------------------------------------------------------------===// 13176 // Target Optimization Hooks 13177 //===----------------------------------------------------------------------===// 13178 13179 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) { 13180 // For the estimates, convergence is quadratic, so we essentially double the 13181 // number of digits correct after every iteration. For both FRE and FRSQRTE, 13182 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 13183 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 13184 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3; 13185 if (VT.getScalarType() == MVT::f64) 13186 RefinementSteps++; 13187 return RefinementSteps; 13188 } 13189 13190 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG, 13191 const DenormalMode &Mode) const { 13192 // We only have VSX Vector Test for software Square Root. 13193 EVT VT = Op.getValueType(); 13194 if (!isTypeLegal(MVT::i1) || 13195 (VT != MVT::f64 && 13196 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))) 13197 return TargetLowering::getSqrtInputTest(Op, DAG, Mode); 13198 13199 SDLoc DL(Op); 13200 // The output register of FTSQRT is CR field. 13201 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op); 13202 // ftsqrt BF,FRB 13203 // Let e_b be the unbiased exponent of the double-precision 13204 // floating-point operand in register FRB. 13205 // fe_flag is set to 1 if either of the following conditions occurs. 13206 // - The double-precision floating-point operand in register FRB is a zero, 13207 // a NaN, or an infinity, or a negative value. 13208 // - e_b is less than or equal to -970. 13209 // Otherwise fe_flag is set to 0. 13210 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is 13211 // not eligible for iteration. (zero/negative/infinity/nan or unbiased 13212 // exponent is less than -970) 13213 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32); 13214 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1, 13215 FTSQRT, SRIdxVal), 13216 0); 13217 } 13218 13219 SDValue 13220 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op, 13221 SelectionDAG &DAG) const { 13222 // We only have VSX Vector Square Root. 13223 EVT VT = Op.getValueType(); 13224 if (VT != MVT::f64 && 13225 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())) 13226 return TargetLowering::getSqrtResultForDenormInput(Op, DAG); 13227 13228 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op); 13229 } 13230 13231 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, 13232 int Enabled, int &RefinementSteps, 13233 bool &UseOneConstNR, 13234 bool Reciprocal) const { 13235 EVT VT = Operand.getValueType(); 13236 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || 13237 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || 13238 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13239 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13240 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13241 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13242 13243 // The Newton-Raphson computation with a single constant does not provide 13244 // enough accuracy on some CPUs. 13245 UseOneConstNR = !Subtarget.needsTwoConstNR(); 13246 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); 13247 } 13248 return SDValue(); 13249 } 13250 13251 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, 13252 int Enabled, 13253 int &RefinementSteps) const { 13254 EVT VT = Operand.getValueType(); 13255 if ((VT == MVT::f32 && Subtarget.hasFRES()) || 13256 (VT == MVT::f64 && Subtarget.hasFRE()) || 13257 (VT == MVT::v4f32 && Subtarget.hasAltivec()) || 13258 (VT == MVT::v2f64 && Subtarget.hasVSX())) { 13259 if (RefinementSteps == ReciprocalEstimate::Unspecified) 13260 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget); 13261 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); 13262 } 13263 return SDValue(); 13264 } 13265 13266 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { 13267 // Note: This functionality is used only when unsafe-fp-math is enabled, and 13268 // on cores with reciprocal estimates (which are used when unsafe-fp-math is 13269 // enabled for division), this functionality is redundant with the default 13270 // combiner logic (once the division -> reciprocal/multiply transformation 13271 // has taken place). As a result, this matters more for older cores than for 13272 // newer ones. 13273 13274 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13275 // reciprocal if there are two or more FDIVs (for embedded cores with only 13276 // one FP pipeline) for three or more FDIVs (for generic OOO cores). 13277 switch (Subtarget.getCPUDirective()) { 13278 default: 13279 return 3; 13280 case PPC::DIR_440: 13281 case PPC::DIR_A2: 13282 case PPC::DIR_E500: 13283 case PPC::DIR_E500mc: 13284 case PPC::DIR_E5500: 13285 return 2; 13286 } 13287 } 13288 13289 // isConsecutiveLSLoc needs to work even if all adds have not yet been 13290 // collapsed, and so we need to look through chains of them. 13291 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, 13292 int64_t& Offset, SelectionDAG &DAG) { 13293 if (DAG.isBaseWithConstantOffset(Loc)) { 13294 Base = Loc.getOperand(0); 13295 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 13296 13297 // The base might itself be a base plus an offset, and if so, accumulate 13298 // that as well. 13299 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); 13300 } 13301 } 13302 13303 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, 13304 unsigned Bytes, int Dist, 13305 SelectionDAG &DAG) { 13306 if (VT.getSizeInBits() / 8 != Bytes) 13307 return false; 13308 13309 SDValue BaseLoc = Base->getBasePtr(); 13310 if (Loc.getOpcode() == ISD::FrameIndex) { 13311 if (BaseLoc.getOpcode() != ISD::FrameIndex) 13312 return false; 13313 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 13314 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 13315 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 13316 int FS = MFI.getObjectSize(FI); 13317 int BFS = MFI.getObjectSize(BFI); 13318 if (FS != BFS || FS != (int)Bytes) return false; 13319 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes); 13320 } 13321 13322 SDValue Base1 = Loc, Base2 = BaseLoc; 13323 int64_t Offset1 = 0, Offset2 = 0; 13324 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); 13325 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); 13326 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) 13327 return true; 13328 13329 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13330 const GlobalValue *GV1 = nullptr; 13331 const GlobalValue *GV2 = nullptr; 13332 Offset1 = 0; 13333 Offset2 = 0; 13334 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); 13335 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 13336 if (isGA1 && isGA2 && GV1 == GV2) 13337 return Offset1 == (Offset2 + Dist*Bytes); 13338 return false; 13339 } 13340 13341 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does 13342 // not enforce equality of the chain operands. 13343 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, 13344 unsigned Bytes, int Dist, 13345 SelectionDAG &DAG) { 13346 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { 13347 EVT VT = LS->getMemoryVT(); 13348 SDValue Loc = LS->getBasePtr(); 13349 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); 13350 } 13351 13352 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 13353 EVT VT; 13354 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13355 default: return false; 13356 case Intrinsic::ppc_altivec_lvx: 13357 case Intrinsic::ppc_altivec_lvxl: 13358 case Intrinsic::ppc_vsx_lxvw4x: 13359 case Intrinsic::ppc_vsx_lxvw4x_be: 13360 VT = MVT::v4i32; 13361 break; 13362 case Intrinsic::ppc_vsx_lxvd2x: 13363 case Intrinsic::ppc_vsx_lxvd2x_be: 13364 VT = MVT::v2f64; 13365 break; 13366 case Intrinsic::ppc_altivec_lvebx: 13367 VT = MVT::i8; 13368 break; 13369 case Intrinsic::ppc_altivec_lvehx: 13370 VT = MVT::i16; 13371 break; 13372 case Intrinsic::ppc_altivec_lvewx: 13373 VT = MVT::i32; 13374 break; 13375 } 13376 13377 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); 13378 } 13379 13380 if (N->getOpcode() == ISD::INTRINSIC_VOID) { 13381 EVT VT; 13382 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13383 default: return false; 13384 case Intrinsic::ppc_altivec_stvx: 13385 case Intrinsic::ppc_altivec_stvxl: 13386 case Intrinsic::ppc_vsx_stxvw4x: 13387 VT = MVT::v4i32; 13388 break; 13389 case Intrinsic::ppc_vsx_stxvd2x: 13390 VT = MVT::v2f64; 13391 break; 13392 case Intrinsic::ppc_vsx_stxvw4x_be: 13393 VT = MVT::v4i32; 13394 break; 13395 case Intrinsic::ppc_vsx_stxvd2x_be: 13396 VT = MVT::v2f64; 13397 break; 13398 case Intrinsic::ppc_altivec_stvebx: 13399 VT = MVT::i8; 13400 break; 13401 case Intrinsic::ppc_altivec_stvehx: 13402 VT = MVT::i16; 13403 break; 13404 case Intrinsic::ppc_altivec_stvewx: 13405 VT = MVT::i32; 13406 break; 13407 } 13408 13409 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); 13410 } 13411 13412 return false; 13413 } 13414 13415 // Return true is there is a nearyby consecutive load to the one provided 13416 // (regardless of alignment). We search up and down the chain, looking though 13417 // token factors and other loads (but nothing else). As a result, a true result 13418 // indicates that it is safe to create a new consecutive load adjacent to the 13419 // load provided. 13420 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { 13421 SDValue Chain = LD->getChain(); 13422 EVT VT = LD->getMemoryVT(); 13423 13424 SmallSet<SDNode *, 16> LoadRoots; 13425 SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); 13426 SmallSet<SDNode *, 16> Visited; 13427 13428 // First, search up the chain, branching to follow all token-factor operands. 13429 // If we find a consecutive load, then we're done, otherwise, record all 13430 // nodes just above the top-level loads and token factors. 13431 while (!Queue.empty()) { 13432 SDNode *ChainNext = Queue.pop_back_val(); 13433 if (!Visited.insert(ChainNext).second) 13434 continue; 13435 13436 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { 13437 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13438 return true; 13439 13440 if (!Visited.count(ChainLD->getChain().getNode())) 13441 Queue.push_back(ChainLD->getChain().getNode()); 13442 } else if (ChainNext->getOpcode() == ISD::TokenFactor) { 13443 for (const SDUse &O : ChainNext->ops()) 13444 if (!Visited.count(O.getNode())) 13445 Queue.push_back(O.getNode()); 13446 } else 13447 LoadRoots.insert(ChainNext); 13448 } 13449 13450 // Second, search down the chain, starting from the top-level nodes recorded 13451 // in the first phase. These top-level nodes are the nodes just above all 13452 // loads and token factors. Starting with their uses, recursively look though 13453 // all loads (just the chain uses) and token factors to find a consecutive 13454 // load. 13455 Visited.clear(); 13456 Queue.clear(); 13457 13458 for (SDNode *I : LoadRoots) { 13459 Queue.push_back(I); 13460 13461 while (!Queue.empty()) { 13462 SDNode *LoadRoot = Queue.pop_back_val(); 13463 if (!Visited.insert(LoadRoot).second) 13464 continue; 13465 13466 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) 13467 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) 13468 return true; 13469 13470 for (SDNode *U : LoadRoot->uses()) 13471 if (((isa<MemSDNode>(U) && 13472 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) || 13473 U->getOpcode() == ISD::TokenFactor) && 13474 !Visited.count(U)) 13475 Queue.push_back(U); 13476 } 13477 } 13478 13479 return false; 13480 } 13481 13482 /// This function is called when we have proved that a SETCC node can be replaced 13483 /// by subtraction (and other supporting instructions) so that the result of 13484 /// comparison is kept in a GPR instead of CR. This function is purely for 13485 /// codegen purposes and has some flags to guide the codegen process. 13486 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, 13487 bool Swap, SDLoc &DL, SelectionDAG &DAG) { 13488 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13489 13490 // Zero extend the operands to the largest legal integer. Originally, they 13491 // must be of a strictly smaller size. 13492 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0), 13493 DAG.getConstant(Size, DL, MVT::i32)); 13494 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1), 13495 DAG.getConstant(Size, DL, MVT::i32)); 13496 13497 // Swap if needed. Depends on the condition code. 13498 if (Swap) 13499 std::swap(Op0, Op1); 13500 13501 // Subtract extended integers. 13502 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1); 13503 13504 // Move the sign bit to the least significant position and zero out the rest. 13505 // Now the least significant bit carries the result of original comparison. 13506 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode, 13507 DAG.getConstant(Size - 1, DL, MVT::i32)); 13508 auto Final = Shifted; 13509 13510 // Complement the result if needed. Based on the condition code. 13511 if (Complement) 13512 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted, 13513 DAG.getConstant(1, DL, MVT::i64)); 13514 13515 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final); 13516 } 13517 13518 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N, 13519 DAGCombinerInfo &DCI) const { 13520 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected."); 13521 13522 SelectionDAG &DAG = DCI.DAG; 13523 SDLoc DL(N); 13524 13525 // Size of integers being compared has a critical role in the following 13526 // analysis, so we prefer to do this when all types are legal. 13527 if (!DCI.isAfterLegalizeDAG()) 13528 return SDValue(); 13529 13530 // If all users of SETCC extend its value to a legal integer type 13531 // then we replace SETCC with a subtraction 13532 for (const SDNode *U : N->uses()) 13533 if (U->getOpcode() != ISD::ZERO_EXTEND) 13534 return SDValue(); 13535 13536 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 13537 auto OpSize = N->getOperand(0).getValueSizeInBits(); 13538 13539 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits(); 13540 13541 if (OpSize < Size) { 13542 switch (CC) { 13543 default: break; 13544 case ISD::SETULT: 13545 return generateEquivalentSub(N, Size, false, false, DL, DAG); 13546 case ISD::SETULE: 13547 return generateEquivalentSub(N, Size, true, true, DL, DAG); 13548 case ISD::SETUGT: 13549 return generateEquivalentSub(N, Size, false, true, DL, DAG); 13550 case ISD::SETUGE: 13551 return generateEquivalentSub(N, Size, true, false, DL, DAG); 13552 } 13553 } 13554 13555 return SDValue(); 13556 } 13557 13558 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, 13559 DAGCombinerInfo &DCI) const { 13560 SelectionDAG &DAG = DCI.DAG; 13561 SDLoc dl(N); 13562 13563 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); 13564 // If we're tracking CR bits, we need to be careful that we don't have: 13565 // trunc(binary-ops(zext(x), zext(y))) 13566 // or 13567 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) 13568 // such that we're unnecessarily moving things into GPRs when it would be 13569 // better to keep them in CR bits. 13570 13571 // Note that trunc here can be an actual i1 trunc, or can be the effective 13572 // truncation that comes from a setcc or select_cc. 13573 if (N->getOpcode() == ISD::TRUNCATE && 13574 N->getValueType(0) != MVT::i1) 13575 return SDValue(); 13576 13577 if (N->getOperand(0).getValueType() != MVT::i32 && 13578 N->getOperand(0).getValueType() != MVT::i64) 13579 return SDValue(); 13580 13581 if (N->getOpcode() == ISD::SETCC || 13582 N->getOpcode() == ISD::SELECT_CC) { 13583 // If we're looking at a comparison, then we need to make sure that the 13584 // high bits (all except for the first) don't matter the result. 13585 ISD::CondCode CC = 13586 cast<CondCodeSDNode>(N->getOperand( 13587 N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); 13588 unsigned OpBits = N->getOperand(0).getValueSizeInBits(); 13589 13590 if (ISD::isSignedIntSetCC(CC)) { 13591 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || 13592 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) 13593 return SDValue(); 13594 } else if (ISD::isUnsignedIntSetCC(CC)) { 13595 if (!DAG.MaskedValueIsZero(N->getOperand(0), 13596 APInt::getHighBitsSet(OpBits, OpBits-1)) || 13597 !DAG.MaskedValueIsZero(N->getOperand(1), 13598 APInt::getHighBitsSet(OpBits, OpBits-1))) 13599 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI) 13600 : SDValue()); 13601 } else { 13602 // This is neither a signed nor an unsigned comparison, just make sure 13603 // that the high bits are equal. 13604 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0)); 13605 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1)); 13606 13607 // We don't really care about what is known about the first bit (if 13608 // anything), so pretend that it is known zero for both to ensure they can 13609 // be compared as constants. 13610 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0); 13611 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0); 13612 13613 if (!Op1Known.isConstant() || !Op2Known.isConstant() || 13614 Op1Known.getConstant() != Op2Known.getConstant()) 13615 return SDValue(); 13616 } 13617 } 13618 13619 // We now know that the higher-order bits are irrelevant, we just need to 13620 // make sure that all of the intermediate operations are bit operations, and 13621 // all inputs are extensions. 13622 if (N->getOperand(0).getOpcode() != ISD::AND && 13623 N->getOperand(0).getOpcode() != ISD::OR && 13624 N->getOperand(0).getOpcode() != ISD::XOR && 13625 N->getOperand(0).getOpcode() != ISD::SELECT && 13626 N->getOperand(0).getOpcode() != ISD::SELECT_CC && 13627 N->getOperand(0).getOpcode() != ISD::TRUNCATE && 13628 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && 13629 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && 13630 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) 13631 return SDValue(); 13632 13633 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && 13634 N->getOperand(1).getOpcode() != ISD::AND && 13635 N->getOperand(1).getOpcode() != ISD::OR && 13636 N->getOperand(1).getOpcode() != ISD::XOR && 13637 N->getOperand(1).getOpcode() != ISD::SELECT && 13638 N->getOperand(1).getOpcode() != ISD::SELECT_CC && 13639 N->getOperand(1).getOpcode() != ISD::TRUNCATE && 13640 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && 13641 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && 13642 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) 13643 return SDValue(); 13644 13645 SmallVector<SDValue, 4> Inputs; 13646 SmallVector<SDValue, 8> BinOps, PromOps; 13647 SmallPtrSet<SDNode *, 16> Visited; 13648 13649 for (unsigned i = 0; i < 2; ++i) { 13650 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13651 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13652 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13653 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13654 isa<ConstantSDNode>(N->getOperand(i))) 13655 Inputs.push_back(N->getOperand(i)); 13656 else 13657 BinOps.push_back(N->getOperand(i)); 13658 13659 if (N->getOpcode() == ISD::TRUNCATE) 13660 break; 13661 } 13662 13663 // Visit all inputs, collect all binary operations (and, or, xor and 13664 // select) that are all fed by extensions. 13665 while (!BinOps.empty()) { 13666 SDValue BinOp = BinOps.pop_back_val(); 13667 13668 if (!Visited.insert(BinOp.getNode()).second) 13669 continue; 13670 13671 PromOps.push_back(BinOp); 13672 13673 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13674 // The condition of the select is not promoted. 13675 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13676 continue; 13677 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13678 continue; 13679 13680 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13681 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13682 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && 13683 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || 13684 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13685 Inputs.push_back(BinOp.getOperand(i)); 13686 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13687 BinOp.getOperand(i).getOpcode() == ISD::OR || 13688 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13689 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13690 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || 13691 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13692 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || 13693 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || 13694 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { 13695 BinOps.push_back(BinOp.getOperand(i)); 13696 } else { 13697 // We have an input that is not an extension or another binary 13698 // operation; we'll abort this transformation. 13699 return SDValue(); 13700 } 13701 } 13702 } 13703 13704 // Make sure that this is a self-contained cluster of operations (which 13705 // is not quite the same thing as saying that everything has only one 13706 // use). 13707 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13708 if (isa<ConstantSDNode>(Inputs[i])) 13709 continue; 13710 13711 for (const SDNode *User : Inputs[i].getNode()->uses()) { 13712 if (User != N && !Visited.count(User)) 13713 return SDValue(); 13714 13715 // Make sure that we're not going to promote the non-output-value 13716 // operand(s) or SELECT or SELECT_CC. 13717 // FIXME: Although we could sometimes handle this, and it does occur in 13718 // practice that one of the condition inputs to the select is also one of 13719 // the outputs, we currently can't deal with this. 13720 if (User->getOpcode() == ISD::SELECT) { 13721 if (User->getOperand(0) == Inputs[i]) 13722 return SDValue(); 13723 } else if (User->getOpcode() == ISD::SELECT_CC) { 13724 if (User->getOperand(0) == Inputs[i] || 13725 User->getOperand(1) == Inputs[i]) 13726 return SDValue(); 13727 } 13728 } 13729 } 13730 13731 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13732 for (const SDNode *User : PromOps[i].getNode()->uses()) { 13733 if (User != N && !Visited.count(User)) 13734 return SDValue(); 13735 13736 // Make sure that we're not going to promote the non-output-value 13737 // operand(s) or SELECT or SELECT_CC. 13738 // FIXME: Although we could sometimes handle this, and it does occur in 13739 // practice that one of the condition inputs to the select is also one of 13740 // the outputs, we currently can't deal with this. 13741 if (User->getOpcode() == ISD::SELECT) { 13742 if (User->getOperand(0) == PromOps[i]) 13743 return SDValue(); 13744 } else if (User->getOpcode() == ISD::SELECT_CC) { 13745 if (User->getOperand(0) == PromOps[i] || 13746 User->getOperand(1) == PromOps[i]) 13747 return SDValue(); 13748 } 13749 } 13750 } 13751 13752 // Replace all inputs with the extension operand. 13753 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13754 // Constants may have users outside the cluster of to-be-promoted nodes, 13755 // and so we need to replace those as we do the promotions. 13756 if (isa<ConstantSDNode>(Inputs[i])) 13757 continue; 13758 else 13759 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 13760 } 13761 13762 std::list<HandleSDNode> PromOpHandles; 13763 for (auto &PromOp : PromOps) 13764 PromOpHandles.emplace_back(PromOp); 13765 13766 // Replace all operations (these are all the same, but have a different 13767 // (i1) return type). DAG.getNode will validate that the types of 13768 // a binary operator match, so go through the list in reverse so that 13769 // we've likely promoted both operands first. Any intermediate truncations or 13770 // extensions disappear. 13771 while (!PromOpHandles.empty()) { 13772 SDValue PromOp = PromOpHandles.back().getValue(); 13773 PromOpHandles.pop_back(); 13774 13775 if (PromOp.getOpcode() == ISD::TRUNCATE || 13776 PromOp.getOpcode() == ISD::SIGN_EXTEND || 13777 PromOp.getOpcode() == ISD::ZERO_EXTEND || 13778 PromOp.getOpcode() == ISD::ANY_EXTEND) { 13779 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && 13780 PromOp.getOperand(0).getValueType() != MVT::i1) { 13781 // The operand is not yet ready (see comment below). 13782 PromOpHandles.emplace_front(PromOp); 13783 continue; 13784 } 13785 13786 SDValue RepValue = PromOp.getOperand(0); 13787 if (isa<ConstantSDNode>(RepValue)) 13788 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); 13789 13790 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); 13791 continue; 13792 } 13793 13794 unsigned C; 13795 switch (PromOp.getOpcode()) { 13796 default: C = 0; break; 13797 case ISD::SELECT: C = 1; break; 13798 case ISD::SELECT_CC: C = 2; break; 13799 } 13800 13801 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 13802 PromOp.getOperand(C).getValueType() != MVT::i1) || 13803 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 13804 PromOp.getOperand(C+1).getValueType() != MVT::i1)) { 13805 // The to-be-promoted operands of this node have not yet been 13806 // promoted (this should be rare because we're going through the 13807 // list backward, but if one of the operands has several users in 13808 // this cluster of to-be-promoted nodes, it is possible). 13809 PromOpHandles.emplace_front(PromOp); 13810 continue; 13811 } 13812 13813 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 13814 PromOp.getNode()->op_end()); 13815 13816 // If there are any constant inputs, make sure they're replaced now. 13817 for (unsigned i = 0; i < 2; ++i) 13818 if (isa<ConstantSDNode>(Ops[C+i])) 13819 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); 13820 13821 DAG.ReplaceAllUsesOfValueWith(PromOp, 13822 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); 13823 } 13824 13825 // Now we're left with the initial truncation itself. 13826 if (N->getOpcode() == ISD::TRUNCATE) 13827 return N->getOperand(0); 13828 13829 // Otherwise, this is a comparison. The operands to be compared have just 13830 // changed type (to i1), but everything else is the same. 13831 return SDValue(N, 0); 13832 } 13833 13834 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, 13835 DAGCombinerInfo &DCI) const { 13836 SelectionDAG &DAG = DCI.DAG; 13837 SDLoc dl(N); 13838 13839 // If we're tracking CR bits, we need to be careful that we don't have: 13840 // zext(binary-ops(trunc(x), trunc(y))) 13841 // or 13842 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) 13843 // such that we're unnecessarily moving things into CR bits that can more 13844 // efficiently stay in GPRs. Note that if we're not certain that the high 13845 // bits are set as required by the final extension, we still may need to do 13846 // some masking to get the proper behavior. 13847 13848 // This same functionality is important on PPC64 when dealing with 13849 // 32-to-64-bit extensions; these occur often when 32-bit values are used as 13850 // the return values of functions. Because it is so similar, it is handled 13851 // here as well. 13852 13853 if (N->getValueType(0) != MVT::i32 && 13854 N->getValueType(0) != MVT::i64) 13855 return SDValue(); 13856 13857 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || 13858 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) 13859 return SDValue(); 13860 13861 if (N->getOperand(0).getOpcode() != ISD::AND && 13862 N->getOperand(0).getOpcode() != ISD::OR && 13863 N->getOperand(0).getOpcode() != ISD::XOR && 13864 N->getOperand(0).getOpcode() != ISD::SELECT && 13865 N->getOperand(0).getOpcode() != ISD::SELECT_CC) 13866 return SDValue(); 13867 13868 SmallVector<SDValue, 4> Inputs; 13869 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; 13870 SmallPtrSet<SDNode *, 16> Visited; 13871 13872 // Visit all inputs, collect all binary operations (and, or, xor and 13873 // select) that are all fed by truncations. 13874 while (!BinOps.empty()) { 13875 SDValue BinOp = BinOps.pop_back_val(); 13876 13877 if (!Visited.insert(BinOp.getNode()).second) 13878 continue; 13879 13880 PromOps.push_back(BinOp); 13881 13882 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { 13883 // The condition of the select is not promoted. 13884 if (BinOp.getOpcode() == ISD::SELECT && i == 0) 13885 continue; 13886 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) 13887 continue; 13888 13889 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || 13890 isa<ConstantSDNode>(BinOp.getOperand(i))) { 13891 Inputs.push_back(BinOp.getOperand(i)); 13892 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || 13893 BinOp.getOperand(i).getOpcode() == ISD::OR || 13894 BinOp.getOperand(i).getOpcode() == ISD::XOR || 13895 BinOp.getOperand(i).getOpcode() == ISD::SELECT || 13896 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { 13897 BinOps.push_back(BinOp.getOperand(i)); 13898 } else { 13899 // We have an input that is not a truncation or another binary 13900 // operation; we'll abort this transformation. 13901 return SDValue(); 13902 } 13903 } 13904 } 13905 13906 // The operands of a select that must be truncated when the select is 13907 // promoted because the operand is actually part of the to-be-promoted set. 13908 DenseMap<SDNode *, EVT> SelectTruncOp[2]; 13909 13910 // Make sure that this is a self-contained cluster of operations (which 13911 // is not quite the same thing as saying that everything has only one 13912 // use). 13913 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13914 if (isa<ConstantSDNode>(Inputs[i])) 13915 continue; 13916 13917 for (SDNode *User : Inputs[i].getNode()->uses()) { 13918 if (User != N && !Visited.count(User)) 13919 return SDValue(); 13920 13921 // If we're going to promote the non-output-value operand(s) or SELECT or 13922 // SELECT_CC, record them for truncation. 13923 if (User->getOpcode() == ISD::SELECT) { 13924 if (User->getOperand(0) == Inputs[i]) 13925 SelectTruncOp[0].insert(std::make_pair(User, 13926 User->getOperand(0).getValueType())); 13927 } else if (User->getOpcode() == ISD::SELECT_CC) { 13928 if (User->getOperand(0) == Inputs[i]) 13929 SelectTruncOp[0].insert(std::make_pair(User, 13930 User->getOperand(0).getValueType())); 13931 if (User->getOperand(1) == Inputs[i]) 13932 SelectTruncOp[1].insert(std::make_pair(User, 13933 User->getOperand(1).getValueType())); 13934 } 13935 } 13936 } 13937 13938 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { 13939 for (SDNode *User : PromOps[i].getNode()->uses()) { 13940 if (User != N && !Visited.count(User)) 13941 return SDValue(); 13942 13943 // If we're going to promote the non-output-value operand(s) or SELECT or 13944 // SELECT_CC, record them for truncation. 13945 if (User->getOpcode() == ISD::SELECT) { 13946 if (User->getOperand(0) == PromOps[i]) 13947 SelectTruncOp[0].insert(std::make_pair(User, 13948 User->getOperand(0).getValueType())); 13949 } else if (User->getOpcode() == ISD::SELECT_CC) { 13950 if (User->getOperand(0) == PromOps[i]) 13951 SelectTruncOp[0].insert(std::make_pair(User, 13952 User->getOperand(0).getValueType())); 13953 if (User->getOperand(1) == PromOps[i]) 13954 SelectTruncOp[1].insert(std::make_pair(User, 13955 User->getOperand(1).getValueType())); 13956 } 13957 } 13958 } 13959 13960 unsigned PromBits = N->getOperand(0).getValueSizeInBits(); 13961 bool ReallyNeedsExt = false; 13962 if (N->getOpcode() != ISD::ANY_EXTEND) { 13963 // If all of the inputs are not already sign/zero extended, then 13964 // we'll still need to do that at the end. 13965 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13966 if (isa<ConstantSDNode>(Inputs[i])) 13967 continue; 13968 13969 unsigned OpBits = 13970 Inputs[i].getOperand(0).getValueSizeInBits(); 13971 assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); 13972 13973 if ((N->getOpcode() == ISD::ZERO_EXTEND && 13974 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), 13975 APInt::getHighBitsSet(OpBits, 13976 OpBits-PromBits))) || 13977 (N->getOpcode() == ISD::SIGN_EXTEND && 13978 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < 13979 (OpBits-(PromBits-1)))) { 13980 ReallyNeedsExt = true; 13981 break; 13982 } 13983 } 13984 } 13985 13986 // Replace all inputs, either with the truncation operand, or a 13987 // truncation or extension to the final output type. 13988 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { 13989 // Constant inputs need to be replaced with the to-be-promoted nodes that 13990 // use them because they might have users outside of the cluster of 13991 // promoted nodes. 13992 if (isa<ConstantSDNode>(Inputs[i])) 13993 continue; 13994 13995 SDValue InSrc = Inputs[i].getOperand(0); 13996 if (Inputs[i].getValueType() == N->getValueType(0)) 13997 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); 13998 else if (N->getOpcode() == ISD::SIGN_EXTEND) 13999 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 14000 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); 14001 else if (N->getOpcode() == ISD::ZERO_EXTEND) 14002 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 14003 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); 14004 else 14005 DAG.ReplaceAllUsesOfValueWith(Inputs[i], 14006 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); 14007 } 14008 14009 std::list<HandleSDNode> PromOpHandles; 14010 for (auto &PromOp : PromOps) 14011 PromOpHandles.emplace_back(PromOp); 14012 14013 // Replace all operations (these are all the same, but have a different 14014 // (promoted) return type). DAG.getNode will validate that the types of 14015 // a binary operator match, so go through the list in reverse so that 14016 // we've likely promoted both operands first. 14017 while (!PromOpHandles.empty()) { 14018 SDValue PromOp = PromOpHandles.back().getValue(); 14019 PromOpHandles.pop_back(); 14020 14021 unsigned C; 14022 switch (PromOp.getOpcode()) { 14023 default: C = 0; break; 14024 case ISD::SELECT: C = 1; break; 14025 case ISD::SELECT_CC: C = 2; break; 14026 } 14027 14028 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && 14029 PromOp.getOperand(C).getValueType() != N->getValueType(0)) || 14030 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && 14031 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { 14032 // The to-be-promoted operands of this node have not yet been 14033 // promoted (this should be rare because we're going through the 14034 // list backward, but if one of the operands has several users in 14035 // this cluster of to-be-promoted nodes, it is possible). 14036 PromOpHandles.emplace_front(PromOp); 14037 continue; 14038 } 14039 14040 // For SELECT and SELECT_CC nodes, we do a similar check for any 14041 // to-be-promoted comparison inputs. 14042 if (PromOp.getOpcode() == ISD::SELECT || 14043 PromOp.getOpcode() == ISD::SELECT_CC) { 14044 if ((SelectTruncOp[0].count(PromOp.getNode()) && 14045 PromOp.getOperand(0).getValueType() != N->getValueType(0)) || 14046 (SelectTruncOp[1].count(PromOp.getNode()) && 14047 PromOp.getOperand(1).getValueType() != N->getValueType(0))) { 14048 PromOpHandles.emplace_front(PromOp); 14049 continue; 14050 } 14051 } 14052 14053 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), 14054 PromOp.getNode()->op_end()); 14055 14056 // If this node has constant inputs, then they'll need to be promoted here. 14057 for (unsigned i = 0; i < 2; ++i) { 14058 if (!isa<ConstantSDNode>(Ops[C+i])) 14059 continue; 14060 if (Ops[C+i].getValueType() == N->getValueType(0)) 14061 continue; 14062 14063 if (N->getOpcode() == ISD::SIGN_EXTEND) 14064 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14065 else if (N->getOpcode() == ISD::ZERO_EXTEND) 14066 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14067 else 14068 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); 14069 } 14070 14071 // If we've promoted the comparison inputs of a SELECT or SELECT_CC, 14072 // truncate them again to the original value type. 14073 if (PromOp.getOpcode() == ISD::SELECT || 14074 PromOp.getOpcode() == ISD::SELECT_CC) { 14075 auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); 14076 if (SI0 != SelectTruncOp[0].end()) 14077 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); 14078 auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); 14079 if (SI1 != SelectTruncOp[1].end()) 14080 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); 14081 } 14082 14083 DAG.ReplaceAllUsesOfValueWith(PromOp, 14084 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); 14085 } 14086 14087 // Now we're left with the initial extension itself. 14088 if (!ReallyNeedsExt) 14089 return N->getOperand(0); 14090 14091 // To zero extend, just mask off everything except for the first bit (in the 14092 // i1 case). 14093 if (N->getOpcode() == ISD::ZERO_EXTEND) 14094 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), 14095 DAG.getConstant(APInt::getLowBitsSet( 14096 N->getValueSizeInBits(0), PromBits), 14097 dl, N->getValueType(0))); 14098 14099 assert(N->getOpcode() == ISD::SIGN_EXTEND && 14100 "Invalid extension type"); 14101 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); 14102 SDValue ShiftCst = 14103 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); 14104 return DAG.getNode( 14105 ISD::SRA, dl, N->getValueType(0), 14106 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), 14107 ShiftCst); 14108 } 14109 14110 SDValue PPCTargetLowering::combineSetCC(SDNode *N, 14111 DAGCombinerInfo &DCI) const { 14112 assert(N->getOpcode() == ISD::SETCC && 14113 "Should be called with a SETCC node"); 14114 14115 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 14116 if (CC == ISD::SETNE || CC == ISD::SETEQ) { 14117 SDValue LHS = N->getOperand(0); 14118 SDValue RHS = N->getOperand(1); 14119 14120 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS. 14121 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) && 14122 LHS.hasOneUse()) 14123 std::swap(LHS, RHS); 14124 14125 // x == 0-y --> x+y == 0 14126 // x != 0-y --> x+y != 0 14127 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 14128 RHS.hasOneUse()) { 14129 SDLoc DL(N); 14130 SelectionDAG &DAG = DCI.DAG; 14131 EVT VT = N->getValueType(0); 14132 EVT OpVT = LHS.getValueType(); 14133 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1)); 14134 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC); 14135 } 14136 } 14137 14138 return DAGCombineTruncBoolExt(N, DCI); 14139 } 14140 14141 // Is this an extending load from an f32 to an f64? 14142 static bool isFPExtLoad(SDValue Op) { 14143 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode())) 14144 return LD->getExtensionType() == ISD::EXTLOAD && 14145 Op.getValueType() == MVT::f64; 14146 return false; 14147 } 14148 14149 /// Reduces the number of fp-to-int conversion when building a vector. 14150 /// 14151 /// If this vector is built out of floating to integer conversions, 14152 /// transform it to a vector built out of floating point values followed by a 14153 /// single floating to integer conversion of the vector. 14154 /// Namely (build_vector (fptosi $A), (fptosi $B), ...) 14155 /// becomes (fptosi (build_vector ($A, $B, ...))) 14156 SDValue PPCTargetLowering:: 14157 combineElementTruncationToVectorTruncation(SDNode *N, 14158 DAGCombinerInfo &DCI) const { 14159 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14160 "Should be called with a BUILD_VECTOR node"); 14161 14162 SelectionDAG &DAG = DCI.DAG; 14163 SDLoc dl(N); 14164 14165 SDValue FirstInput = N->getOperand(0); 14166 assert(FirstInput.getOpcode() == PPCISD::MFVSR && 14167 "The input operand must be an fp-to-int conversion."); 14168 14169 // This combine happens after legalization so the fp_to_[su]i nodes are 14170 // already converted to PPCSISD nodes. 14171 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode(); 14172 if (FirstConversion == PPCISD::FCTIDZ || 14173 FirstConversion == PPCISD::FCTIDUZ || 14174 FirstConversion == PPCISD::FCTIWZ || 14175 FirstConversion == PPCISD::FCTIWUZ) { 14176 bool IsSplat = true; 14177 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ || 14178 FirstConversion == PPCISD::FCTIWUZ; 14179 EVT SrcVT = FirstInput.getOperand(0).getValueType(); 14180 SmallVector<SDValue, 4> Ops; 14181 EVT TargetVT = N->getValueType(0); 14182 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14183 SDValue NextOp = N->getOperand(i); 14184 if (NextOp.getOpcode() != PPCISD::MFVSR) 14185 return SDValue(); 14186 unsigned NextConversion = NextOp.getOperand(0).getOpcode(); 14187 if (NextConversion != FirstConversion) 14188 return SDValue(); 14189 // If we are converting to 32-bit integers, we need to add an FP_ROUND. 14190 // This is not valid if the input was originally double precision. It is 14191 // also not profitable to do unless this is an extending load in which 14192 // case doing this combine will allow us to combine consecutive loads. 14193 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0))) 14194 return SDValue(); 14195 if (N->getOperand(i) != FirstInput) 14196 IsSplat = false; 14197 } 14198 14199 // If this is a splat, we leave it as-is since there will be only a single 14200 // fp-to-int conversion followed by a splat of the integer. This is better 14201 // for 32-bit and smaller ints and neutral for 64-bit ints. 14202 if (IsSplat) 14203 return SDValue(); 14204 14205 // Now that we know we have the right type of node, get its operands 14206 for (int i = 0, e = N->getNumOperands(); i < e; ++i) { 14207 SDValue In = N->getOperand(i).getOperand(0); 14208 if (Is32Bit) { 14209 // For 32-bit values, we need to add an FP_ROUND node (if we made it 14210 // here, we know that all inputs are extending loads so this is safe). 14211 if (In.isUndef()) 14212 Ops.push_back(DAG.getUNDEF(SrcVT)); 14213 else { 14214 SDValue Trunc = 14215 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0), 14216 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true)); 14217 Ops.push_back(Trunc); 14218 } 14219 } else 14220 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0)); 14221 } 14222 14223 unsigned Opcode; 14224 if (FirstConversion == PPCISD::FCTIDZ || 14225 FirstConversion == PPCISD::FCTIWZ) 14226 Opcode = ISD::FP_TO_SINT; 14227 else 14228 Opcode = ISD::FP_TO_UINT; 14229 14230 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32; 14231 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops); 14232 return DAG.getNode(Opcode, dl, TargetVT, BV); 14233 } 14234 return SDValue(); 14235 } 14236 14237 /// Reduce the number of loads when building a vector. 14238 /// 14239 /// Building a vector out of multiple loads can be converted to a load 14240 /// of the vector type if the loads are consecutive. If the loads are 14241 /// consecutive but in descending order, a shuffle is added at the end 14242 /// to reorder the vector. 14243 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) { 14244 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14245 "Should be called with a BUILD_VECTOR node"); 14246 14247 SDLoc dl(N); 14248 14249 // Return early for non byte-sized type, as they can't be consecutive. 14250 if (!N->getValueType(0).getVectorElementType().isByteSized()) 14251 return SDValue(); 14252 14253 bool InputsAreConsecutiveLoads = true; 14254 bool InputsAreReverseConsecutive = true; 14255 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize(); 14256 SDValue FirstInput = N->getOperand(0); 14257 bool IsRoundOfExtLoad = false; 14258 LoadSDNode *FirstLoad = nullptr; 14259 14260 if (FirstInput.getOpcode() == ISD::FP_ROUND && 14261 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) { 14262 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0)); 14263 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD; 14264 } 14265 // Not a build vector of (possibly fp_rounded) loads. 14266 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) || 14267 N->getNumOperands() == 1) 14268 return SDValue(); 14269 14270 if (!IsRoundOfExtLoad) 14271 FirstLoad = cast<LoadSDNode>(FirstInput); 14272 14273 SmallVector<LoadSDNode *, 4> InputLoads; 14274 InputLoads.push_back(FirstLoad); 14275 for (int i = 1, e = N->getNumOperands(); i < e; ++i) { 14276 // If any inputs are fp_round(extload), they all must be. 14277 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND) 14278 return SDValue(); 14279 14280 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) : 14281 N->getOperand(i); 14282 if (NextInput.getOpcode() != ISD::LOAD) 14283 return SDValue(); 14284 14285 SDValue PreviousInput = 14286 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1); 14287 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput); 14288 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput); 14289 14290 // If any inputs are fp_round(extload), they all must be. 14291 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD) 14292 return SDValue(); 14293 14294 // We only care about regular loads. The PPC-specific load intrinsics 14295 // will not lead to a merge opportunity. 14296 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1)) 14297 InputsAreConsecutiveLoads = false; 14298 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1)) 14299 InputsAreReverseConsecutive = false; 14300 14301 // Exit early if the loads are neither consecutive nor reverse consecutive. 14302 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive) 14303 return SDValue(); 14304 InputLoads.push_back(LD2); 14305 } 14306 14307 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) && 14308 "The loads cannot be both consecutive and reverse consecutive."); 14309 14310 SDValue WideLoad; 14311 SDValue ReturnSDVal; 14312 if (InputsAreConsecutiveLoads) { 14313 assert(FirstLoad && "Input needs to be a LoadSDNode."); 14314 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(), 14315 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 14316 FirstLoad->getAlign()); 14317 ReturnSDVal = WideLoad; 14318 } else if (InputsAreReverseConsecutive) { 14319 LoadSDNode *LastLoad = InputLoads.back(); 14320 assert(LastLoad && "Input needs to be a LoadSDNode."); 14321 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(), 14322 LastLoad->getBasePtr(), LastLoad->getPointerInfo(), 14323 LastLoad->getAlign()); 14324 SmallVector<int, 16> Ops; 14325 for (int i = N->getNumOperands() - 1; i >= 0; i--) 14326 Ops.push_back(i); 14327 14328 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad, 14329 DAG.getUNDEF(N->getValueType(0)), Ops); 14330 } else 14331 return SDValue(); 14332 14333 for (auto *LD : InputLoads) 14334 DAG.makeEquivalentMemoryOrdering(LD, WideLoad); 14335 return ReturnSDVal; 14336 } 14337 14338 // This function adds the required vector_shuffle needed to get 14339 // the elements of the vector extract in the correct position 14340 // as specified by the CorrectElems encoding. 14341 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, 14342 SDValue Input, uint64_t Elems, 14343 uint64_t CorrectElems) { 14344 SDLoc dl(N); 14345 14346 unsigned NumElems = Input.getValueType().getVectorNumElements(); 14347 SmallVector<int, 16> ShuffleMask(NumElems, -1); 14348 14349 // Knowing the element indices being extracted from the original 14350 // vector and the order in which they're being inserted, just put 14351 // them at element indices required for the instruction. 14352 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14353 if (DAG.getDataLayout().isLittleEndian()) 14354 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF; 14355 else 14356 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4; 14357 CorrectElems = CorrectElems >> 8; 14358 Elems = Elems >> 8; 14359 } 14360 14361 SDValue Shuffle = 14362 DAG.getVectorShuffle(Input.getValueType(), dl, Input, 14363 DAG.getUNDEF(Input.getValueType()), ShuffleMask); 14364 14365 EVT VT = N->getValueType(0); 14366 SDValue Conv = DAG.getBitcast(VT, Shuffle); 14367 14368 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), 14369 Input.getValueType().getVectorElementType(), 14370 VT.getVectorNumElements()); 14371 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv, 14372 DAG.getValueType(ExtVT)); 14373 } 14374 14375 // Look for build vector patterns where input operands come from sign 14376 // extended vector_extract elements of specific indices. If the correct indices 14377 // aren't used, add a vector shuffle to fix up the indices and create 14378 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions 14379 // during instruction selection. 14380 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) { 14381 // This array encodes the indices that the vector sign extend instructions 14382 // extract from when extending from one type to another for both BE and LE. 14383 // The right nibble of each byte corresponds to the LE incides. 14384 // and the left nibble of each byte corresponds to the BE incides. 14385 // For example: 0x3074B8FC byte->word 14386 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC 14387 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF 14388 // For example: 0x000070F8 byte->double word 14389 // For LE: the allowed indices are: 0x0,0x8 14390 // For BE: the allowed indices are: 0x7,0xF 14391 uint64_t TargetElems[] = { 14392 0x3074B8FC, // b->w 14393 0x000070F8, // b->d 14394 0x10325476, // h->w 14395 0x00003074, // h->d 14396 0x00001032, // w->d 14397 }; 14398 14399 uint64_t Elems = 0; 14400 int Index; 14401 SDValue Input; 14402 14403 auto isSExtOfVecExtract = [&](SDValue Op) -> bool { 14404 if (!Op) 14405 return false; 14406 if (Op.getOpcode() != ISD::SIGN_EXTEND && 14407 Op.getOpcode() != ISD::SIGN_EXTEND_INREG) 14408 return false; 14409 14410 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value 14411 // of the right width. 14412 SDValue Extract = Op.getOperand(0); 14413 if (Extract.getOpcode() == ISD::ANY_EXTEND) 14414 Extract = Extract.getOperand(0); 14415 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14416 return false; 14417 14418 ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 14419 if (!ExtOp) 14420 return false; 14421 14422 Index = ExtOp->getZExtValue(); 14423 if (Input && Input != Extract.getOperand(0)) 14424 return false; 14425 14426 if (!Input) 14427 Input = Extract.getOperand(0); 14428 14429 Elems = Elems << 8; 14430 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4; 14431 Elems |= Index; 14432 14433 return true; 14434 }; 14435 14436 // If the build vector operands aren't sign extended vector extracts, 14437 // of the same input vector, then return. 14438 for (unsigned i = 0; i < N->getNumOperands(); i++) { 14439 if (!isSExtOfVecExtract(N->getOperand(i))) { 14440 return SDValue(); 14441 } 14442 } 14443 14444 // If the vector extract indicies are not correct, add the appropriate 14445 // vector_shuffle. 14446 int TgtElemArrayIdx; 14447 int InputSize = Input.getValueType().getScalarSizeInBits(); 14448 int OutputSize = N->getValueType(0).getScalarSizeInBits(); 14449 if (InputSize + OutputSize == 40) 14450 TgtElemArrayIdx = 0; 14451 else if (InputSize + OutputSize == 72) 14452 TgtElemArrayIdx = 1; 14453 else if (InputSize + OutputSize == 48) 14454 TgtElemArrayIdx = 2; 14455 else if (InputSize + OutputSize == 80) 14456 TgtElemArrayIdx = 3; 14457 else if (InputSize + OutputSize == 96) 14458 TgtElemArrayIdx = 4; 14459 else 14460 return SDValue(); 14461 14462 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx]; 14463 CorrectElems = DAG.getDataLayout().isLittleEndian() 14464 ? CorrectElems & 0x0F0F0F0F0F0F0F0F 14465 : CorrectElems & 0xF0F0F0F0F0F0F0F0; 14466 if (Elems != CorrectElems) { 14467 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems); 14468 } 14469 14470 // Regular lowering will catch cases where a shuffle is not needed. 14471 return SDValue(); 14472 } 14473 14474 // Look for the pattern of a load from a narrow width to i128, feeding 14475 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node 14476 // (LXVRZX). This node represents a zero extending load that will be matched 14477 // to the Load VSX Vector Rightmost instructions. 14478 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) { 14479 SDLoc DL(N); 14480 14481 // This combine is only eligible for a BUILD_VECTOR of v1i128. 14482 if (N->getValueType(0) != MVT::v1i128) 14483 return SDValue(); 14484 14485 SDValue Operand = N->getOperand(0); 14486 // Proceed with the transformation if the operand to the BUILD_VECTOR 14487 // is a load instruction. 14488 if (Operand.getOpcode() != ISD::LOAD) 14489 return SDValue(); 14490 14491 auto *LD = cast<LoadSDNode>(Operand); 14492 EVT MemoryType = LD->getMemoryVT(); 14493 14494 // This transformation is only valid if the we are loading either a byte, 14495 // halfword, word, or doubleword. 14496 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 || 14497 MemoryType == MVT::i32 || MemoryType == MVT::i64; 14498 14499 // Ensure that the load from the narrow width is being zero extended to i128. 14500 if (!ValidLDType || 14501 (LD->getExtensionType() != ISD::ZEXTLOAD && 14502 LD->getExtensionType() != ISD::EXTLOAD)) 14503 return SDValue(); 14504 14505 SDValue LoadOps[] = { 14506 LD->getChain(), LD->getBasePtr(), 14507 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)}; 14508 14509 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL, 14510 DAG.getVTList(MVT::v1i128, MVT::Other), 14511 LoadOps, MemoryType, LD->getMemOperand()); 14512 } 14513 14514 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N, 14515 DAGCombinerInfo &DCI) const { 14516 assert(N->getOpcode() == ISD::BUILD_VECTOR && 14517 "Should be called with a BUILD_VECTOR node"); 14518 14519 SelectionDAG &DAG = DCI.DAG; 14520 SDLoc dl(N); 14521 14522 if (!Subtarget.hasVSX()) 14523 return SDValue(); 14524 14525 // The target independent DAG combiner will leave a build_vector of 14526 // float-to-int conversions intact. We can generate MUCH better code for 14527 // a float-to-int conversion of a vector of floats. 14528 SDValue FirstInput = N->getOperand(0); 14529 if (FirstInput.getOpcode() == PPCISD::MFVSR) { 14530 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI); 14531 if (Reduced) 14532 return Reduced; 14533 } 14534 14535 // If we're building a vector out of consecutive loads, just load that 14536 // vector type. 14537 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG); 14538 if (Reduced) 14539 return Reduced; 14540 14541 // If we're building a vector out of extended elements from another vector 14542 // we have P9 vector integer extend instructions. The code assumes legal 14543 // input types (i.e. it can't handle things like v4i16) so do not run before 14544 // legalization. 14545 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) { 14546 Reduced = combineBVOfVecSExt(N, DAG); 14547 if (Reduced) 14548 return Reduced; 14549 } 14550 14551 // On Power10, the Load VSX Vector Rightmost instructions can be utilized 14552 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR 14553 // is a load from <valid narrow width> to i128. 14554 if (Subtarget.isISA3_1()) { 14555 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG); 14556 if (BVOfZLoad) 14557 return BVOfZLoad; 14558 } 14559 14560 if (N->getValueType(0) != MVT::v2f64) 14561 return SDValue(); 14562 14563 // Looking for: 14564 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1)) 14565 if (FirstInput.getOpcode() != ISD::SINT_TO_FP && 14566 FirstInput.getOpcode() != ISD::UINT_TO_FP) 14567 return SDValue(); 14568 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP && 14569 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP) 14570 return SDValue(); 14571 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode()) 14572 return SDValue(); 14573 14574 SDValue Ext1 = FirstInput.getOperand(0); 14575 SDValue Ext2 = N->getOperand(1).getOperand(0); 14576 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14577 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 14578 return SDValue(); 14579 14580 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1)); 14581 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1)); 14582 if (!Ext1Op || !Ext2Op) 14583 return SDValue(); 14584 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 || 14585 Ext1.getOperand(0) != Ext2.getOperand(0)) 14586 return SDValue(); 14587 14588 int FirstElem = Ext1Op->getZExtValue(); 14589 int SecondElem = Ext2Op->getZExtValue(); 14590 int SubvecIdx; 14591 if (FirstElem == 0 && SecondElem == 1) 14592 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0; 14593 else if (FirstElem == 2 && SecondElem == 3) 14594 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1; 14595 else 14596 return SDValue(); 14597 14598 SDValue SrcVec = Ext1.getOperand(0); 14599 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ? 14600 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP; 14601 return DAG.getNode(NodeType, dl, MVT::v2f64, 14602 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl)); 14603 } 14604 14605 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, 14606 DAGCombinerInfo &DCI) const { 14607 assert((N->getOpcode() == ISD::SINT_TO_FP || 14608 N->getOpcode() == ISD::UINT_TO_FP) && 14609 "Need an int -> FP conversion node here"); 14610 14611 if (useSoftFloat() || !Subtarget.has64BitSupport()) 14612 return SDValue(); 14613 14614 SelectionDAG &DAG = DCI.DAG; 14615 SDLoc dl(N); 14616 SDValue Op(N, 0); 14617 14618 // Don't handle ppc_fp128 here or conversions that are out-of-range capable 14619 // from the hardware. 14620 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) 14621 return SDValue(); 14622 if (!Op.getOperand(0).getValueType().isSimple()) 14623 return SDValue(); 14624 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) || 14625 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64)) 14626 return SDValue(); 14627 14628 SDValue FirstOperand(Op.getOperand(0)); 14629 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD && 14630 (FirstOperand.getValueType() == MVT::i8 || 14631 FirstOperand.getValueType() == MVT::i16); 14632 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) { 14633 bool Signed = N->getOpcode() == ISD::SINT_TO_FP; 14634 bool DstDouble = Op.getValueType() == MVT::f64; 14635 unsigned ConvOp = Signed ? 14636 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) : 14637 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS); 14638 SDValue WidthConst = 14639 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2, 14640 dl, false); 14641 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode()); 14642 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst }; 14643 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl, 14644 DAG.getVTList(MVT::f64, MVT::Other), 14645 Ops, MVT::i8, LDN->getMemOperand()); 14646 14647 // For signed conversion, we need to sign-extend the value in the VSR 14648 if (Signed) { 14649 SDValue ExtOps[] = { Ld, WidthConst }; 14650 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps); 14651 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext); 14652 } else 14653 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld); 14654 } 14655 14656 14657 // For i32 intermediate values, unfortunately, the conversion functions 14658 // leave the upper 32 bits of the value are undefined. Within the set of 14659 // scalar instructions, we have no method for zero- or sign-extending the 14660 // value. Thus, we cannot handle i32 intermediate values here. 14661 if (Op.getOperand(0).getValueType() == MVT::i32) 14662 return SDValue(); 14663 14664 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && 14665 "UINT_TO_FP is supported only with FPCVT"); 14666 14667 // If we have FCFIDS, then use it when converting to single-precision. 14668 // Otherwise, convert to double-precision and then round. 14669 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14670 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS 14671 : PPCISD::FCFIDS) 14672 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU 14673 : PPCISD::FCFID); 14674 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) 14675 ? MVT::f32 14676 : MVT::f64; 14677 14678 // If we're converting from a float, to an int, and back to a float again, 14679 // then we don't need the store/load pair at all. 14680 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && 14681 Subtarget.hasFPCVT()) || 14682 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { 14683 SDValue Src = Op.getOperand(0).getOperand(0); 14684 if (Src.getValueType() == MVT::f32) { 14685 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); 14686 DCI.AddToWorklist(Src.getNode()); 14687 } else if (Src.getValueType() != MVT::f64) { 14688 // Make sure that we don't pick up a ppc_fp128 source value. 14689 return SDValue(); 14690 } 14691 14692 unsigned FCTOp = 14693 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : 14694 PPCISD::FCTIDUZ; 14695 14696 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); 14697 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); 14698 14699 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { 14700 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, 14701 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)); 14702 DCI.AddToWorklist(FP.getNode()); 14703 } 14704 14705 return FP; 14706 } 14707 14708 return SDValue(); 14709 } 14710 14711 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for 14712 // builtins) into loads with swaps. 14713 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, 14714 DAGCombinerInfo &DCI) const { 14715 // Delay VSX load for LE combine until after LegalizeOps to prioritize other 14716 // load combines. 14717 if (DCI.isBeforeLegalizeOps()) 14718 return SDValue(); 14719 14720 SelectionDAG &DAG = DCI.DAG; 14721 SDLoc dl(N); 14722 SDValue Chain; 14723 SDValue Base; 14724 MachineMemOperand *MMO; 14725 14726 switch (N->getOpcode()) { 14727 default: 14728 llvm_unreachable("Unexpected opcode for little endian VSX load"); 14729 case ISD::LOAD: { 14730 LoadSDNode *LD = cast<LoadSDNode>(N); 14731 Chain = LD->getChain(); 14732 Base = LD->getBasePtr(); 14733 MMO = LD->getMemOperand(); 14734 // If the MMO suggests this isn't a load of a full vector, leave 14735 // things alone. For a built-in, we have to make the change for 14736 // correctness, so if there is a size problem that will be a bug. 14737 if (MMO->getSize() < 16) 14738 return SDValue(); 14739 break; 14740 } 14741 case ISD::INTRINSIC_W_CHAIN: { 14742 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14743 Chain = Intrin->getChain(); 14744 // Similarly to the store case below, Intrin->getBasePtr() doesn't get 14745 // us what we want. Get operand 2 instead. 14746 Base = Intrin->getOperand(2); 14747 MMO = Intrin->getMemOperand(); 14748 break; 14749 } 14750 } 14751 14752 MVT VecTy = N->getValueType(0).getSimpleVT(); 14753 14754 SDValue LoadOps[] = { Chain, Base }; 14755 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, 14756 DAG.getVTList(MVT::v2f64, MVT::Other), 14757 LoadOps, MVT::v2f64, MMO); 14758 14759 DCI.AddToWorklist(Load.getNode()); 14760 Chain = Load.getValue(1); 14761 SDValue Swap = DAG.getNode( 14762 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); 14763 DCI.AddToWorklist(Swap.getNode()); 14764 14765 // Add a bitcast if the resulting load type doesn't match v2f64. 14766 if (VecTy != MVT::v2f64) { 14767 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); 14768 DCI.AddToWorklist(N.getNode()); 14769 // Package {bitcast value, swap's chain} to match Load's shape. 14770 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), 14771 N, Swap.getValue(1)); 14772 } 14773 14774 return Swap; 14775 } 14776 14777 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for 14778 // builtins) into stores with swaps. 14779 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, 14780 DAGCombinerInfo &DCI) const { 14781 // Delay VSX store for LE combine until after LegalizeOps to prioritize other 14782 // store combines. 14783 if (DCI.isBeforeLegalizeOps()) 14784 return SDValue(); 14785 14786 SelectionDAG &DAG = DCI.DAG; 14787 SDLoc dl(N); 14788 SDValue Chain; 14789 SDValue Base; 14790 unsigned SrcOpnd; 14791 MachineMemOperand *MMO; 14792 14793 switch (N->getOpcode()) { 14794 default: 14795 llvm_unreachable("Unexpected opcode for little endian VSX store"); 14796 case ISD::STORE: { 14797 StoreSDNode *ST = cast<StoreSDNode>(N); 14798 Chain = ST->getChain(); 14799 Base = ST->getBasePtr(); 14800 MMO = ST->getMemOperand(); 14801 SrcOpnd = 1; 14802 // If the MMO suggests this isn't a store of a full vector, leave 14803 // things alone. For a built-in, we have to make the change for 14804 // correctness, so if there is a size problem that will be a bug. 14805 if (MMO->getSize() < 16) 14806 return SDValue(); 14807 break; 14808 } 14809 case ISD::INTRINSIC_VOID: { 14810 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); 14811 Chain = Intrin->getChain(); 14812 // Intrin->getBasePtr() oddly does not get what we want. 14813 Base = Intrin->getOperand(3); 14814 MMO = Intrin->getMemOperand(); 14815 SrcOpnd = 2; 14816 break; 14817 } 14818 } 14819 14820 SDValue Src = N->getOperand(SrcOpnd); 14821 MVT VecTy = Src.getValueType().getSimpleVT(); 14822 14823 // All stores are done as v2f64 and possible bit cast. 14824 if (VecTy != MVT::v2f64) { 14825 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); 14826 DCI.AddToWorklist(Src.getNode()); 14827 } 14828 14829 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, 14830 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); 14831 DCI.AddToWorklist(Swap.getNode()); 14832 Chain = Swap.getValue(1); 14833 SDValue StoreOps[] = { Chain, Swap, Base }; 14834 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, 14835 DAG.getVTList(MVT::Other), 14836 StoreOps, VecTy, MMO); 14837 DCI.AddToWorklist(Store.getNode()); 14838 return Store; 14839 } 14840 14841 // Handle DAG combine for STORE (FP_TO_INT F). 14842 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N, 14843 DAGCombinerInfo &DCI) const { 14844 14845 SelectionDAG &DAG = DCI.DAG; 14846 SDLoc dl(N); 14847 unsigned Opcode = N->getOperand(1).getOpcode(); 14848 14849 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) 14850 && "Not a FP_TO_INT Instruction!"); 14851 14852 SDValue Val = N->getOperand(1).getOperand(0); 14853 EVT Op1VT = N->getOperand(1).getValueType(); 14854 EVT ResVT = Val.getValueType(); 14855 14856 if (!isTypeLegal(ResVT)) 14857 return SDValue(); 14858 14859 // Only perform combine for conversion to i64/i32 or power9 i16/i8. 14860 bool ValidTypeForStoreFltAsInt = 14861 (Op1VT == MVT::i32 || Op1VT == MVT::i64 || 14862 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8))); 14863 14864 if (ResVT == MVT::f128 && !Subtarget.hasP9Vector()) 14865 return SDValue(); 14866 14867 if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() || 14868 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt) 14869 return SDValue(); 14870 14871 // Extend f32 values to f64 14872 if (ResVT.getScalarSizeInBits() == 32) { 14873 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); 14874 DCI.AddToWorklist(Val.getNode()); 14875 } 14876 14877 // Set signed or unsigned conversion opcode. 14878 unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ? 14879 PPCISD::FP_TO_SINT_IN_VSR : 14880 PPCISD::FP_TO_UINT_IN_VSR; 14881 14882 Val = DAG.getNode(ConvOpcode, 14883 dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val); 14884 DCI.AddToWorklist(Val.getNode()); 14885 14886 // Set number of bytes being converted. 14887 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8; 14888 SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), 14889 DAG.getIntPtrConstant(ByteSize, dl, false), 14890 DAG.getValueType(Op1VT) }; 14891 14892 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl, 14893 DAG.getVTList(MVT::Other), Ops, 14894 cast<StoreSDNode>(N)->getMemoryVT(), 14895 cast<StoreSDNode>(N)->getMemOperand()); 14896 14897 DCI.AddToWorklist(Val.getNode()); 14898 return Val; 14899 } 14900 14901 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) { 14902 // Check that the source of the element keeps flipping 14903 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts). 14904 bool PrevElemFromFirstVec = Mask[0] < NumElts; 14905 for (int i = 1, e = Mask.size(); i < e; i++) { 14906 if (PrevElemFromFirstVec && Mask[i] < NumElts) 14907 return false; 14908 if (!PrevElemFromFirstVec && Mask[i] >= NumElts) 14909 return false; 14910 PrevElemFromFirstVec = !PrevElemFromFirstVec; 14911 } 14912 return true; 14913 } 14914 14915 static bool isSplatBV(SDValue Op) { 14916 if (Op.getOpcode() != ISD::BUILD_VECTOR) 14917 return false; 14918 SDValue FirstOp; 14919 14920 // Find first non-undef input. 14921 for (int i = 0, e = Op.getNumOperands(); i < e; i++) { 14922 FirstOp = Op.getOperand(i); 14923 if (!FirstOp.isUndef()) 14924 break; 14925 } 14926 14927 // All inputs are undef or the same as the first non-undef input. 14928 for (int i = 1, e = Op.getNumOperands(); i < e; i++) 14929 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef()) 14930 return false; 14931 return true; 14932 } 14933 14934 static SDValue isScalarToVec(SDValue Op) { 14935 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14936 return Op; 14937 if (Op.getOpcode() != ISD::BITCAST) 14938 return SDValue(); 14939 Op = Op.getOperand(0); 14940 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR) 14941 return Op; 14942 return SDValue(); 14943 } 14944 14945 // Fix up the shuffle mask to account for the fact that the result of 14946 // scalar_to_vector is not in lane zero. This just takes all values in 14947 // the ranges specified by the min/max indices and adds the number of 14948 // elements required to ensure each element comes from the respective 14949 // position in the valid lane. 14950 // On little endian, that's just the corresponding element in the other 14951 // half of the vector. On big endian, it is in the same half but right 14952 // justified rather than left justified in that half. 14953 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV, 14954 int LHSMaxIdx, int RHSMinIdx, 14955 int RHSMaxIdx, int HalfVec, 14956 unsigned ValidLaneWidth, 14957 const PPCSubtarget &Subtarget) { 14958 for (int i = 0, e = ShuffV.size(); i < e; i++) { 14959 int Idx = ShuffV[i]; 14960 if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx)) 14961 ShuffV[i] += 14962 Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth; 14963 } 14964 } 14965 14966 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if 14967 // the original is: 14968 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C)))) 14969 // In such a case, just change the shuffle mask to extract the element 14970 // from the permuted index. 14971 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, 14972 const PPCSubtarget &Subtarget) { 14973 SDLoc dl(OrigSToV); 14974 EVT VT = OrigSToV.getValueType(); 14975 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR && 14976 "Expecting a SCALAR_TO_VECTOR here"); 14977 SDValue Input = OrigSToV.getOperand(0); 14978 14979 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 14980 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1)); 14981 SDValue OrigVector = Input.getOperand(0); 14982 14983 // Can't handle non-const element indices or different vector types 14984 // for the input to the extract and the output of the scalar_to_vector. 14985 if (Idx && VT == OrigVector.getValueType()) { 14986 unsigned NumElts = VT.getVectorNumElements(); 14987 assert( 14988 NumElts > 1 && 14989 "Cannot produce a permuted scalar_to_vector for one element vector"); 14990 SmallVector<int, 16> NewMask(NumElts, -1); 14991 unsigned ResultInElt = NumElts / 2; 14992 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1; 14993 NewMask[ResultInElt] = Idx->getZExtValue(); 14994 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask); 14995 } 14996 } 14997 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT, 14998 OrigSToV.getOperand(0)); 14999 } 15000 15001 // On little endian subtargets, combine shuffles such as: 15002 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b 15003 // into: 15004 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b 15005 // because the latter can be matched to a single instruction merge. 15006 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute 15007 // to put the value into element zero. Adjust the shuffle mask so that the 15008 // vector can remain in permuted form (to prevent a swap prior to a shuffle). 15009 // On big endian targets, this is still useful for SCALAR_TO_VECTOR 15010 // nodes with elements smaller than doubleword because all the ways 15011 // of getting scalar data into a vector register put the value in the 15012 // rightmost element of the left half of the vector. 15013 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN, 15014 SelectionDAG &DAG) const { 15015 SDValue LHS = SVN->getOperand(0); 15016 SDValue RHS = SVN->getOperand(1); 15017 auto Mask = SVN->getMask(); 15018 int NumElts = LHS.getValueType().getVectorNumElements(); 15019 SDValue Res(SVN, 0); 15020 SDLoc dl(SVN); 15021 bool IsLittleEndian = Subtarget.isLittleEndian(); 15022 15023 // On big endian targets this is only useful for subtargets with direct moves. 15024 // On little endian targets it would be useful for all subtargets with VSX. 15025 // However adding special handling for LE subtargets without direct moves 15026 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8) 15027 // which includes direct moves. 15028 if (!Subtarget.hasDirectMove()) 15029 return Res; 15030 15031 // If this is not a shuffle of a shuffle and the first element comes from 15032 // the second vector, canonicalize to the commuted form. This will make it 15033 // more likely to match one of the single instruction patterns. 15034 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE && 15035 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) { 15036 std::swap(LHS, RHS); 15037 Res = DAG.getCommutedVectorShuffle(*SVN); 15038 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 15039 } 15040 15041 // Adjust the shuffle mask if either input vector comes from a 15042 // SCALAR_TO_VECTOR and keep the respective input vector in permuted 15043 // form (to prevent the need for a swap). 15044 SmallVector<int, 16> ShuffV(Mask); 15045 SDValue SToVLHS = isScalarToVec(LHS); 15046 SDValue SToVRHS = isScalarToVec(RHS); 15047 if (SToVLHS || SToVRHS) { 15048 // FIXME: If both LHS and RHS are SCALAR_TO_VECTOR, but are not the 15049 // same type and have differing element sizes, then do not perform 15050 // the following transformation. The current transformation for 15051 // SCALAR_TO_VECTOR assumes that both input vectors have the same 15052 // element size. This will be updated in the future to account for 15053 // differing sizes of the LHS and RHS. 15054 if (SToVLHS && SToVRHS && 15055 (SToVLHS.getValueType().getScalarSizeInBits() != 15056 SToVRHS.getValueType().getScalarSizeInBits())) 15057 return Res; 15058 15059 int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements() 15060 : SToVRHS.getValueType().getVectorNumElements(); 15061 int NumEltsOut = ShuffV.size(); 15062 // The width of the "valid lane" (i.e. the lane that contains the value that 15063 // is vectorized) needs to be expressed in terms of the number of elements 15064 // of the shuffle. It is thereby the ratio of the values before and after 15065 // any bitcast. 15066 unsigned ValidLaneWidth = 15067 SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() / 15068 LHS.getValueType().getScalarSizeInBits() 15069 : SToVRHS.getValueType().getScalarSizeInBits() / 15070 RHS.getValueType().getScalarSizeInBits(); 15071 15072 // Initially assume that neither input is permuted. These will be adjusted 15073 // accordingly if either input is. 15074 int LHSMaxIdx = -1; 15075 int RHSMinIdx = -1; 15076 int RHSMaxIdx = -1; 15077 int HalfVec = LHS.getValueType().getVectorNumElements() / 2; 15078 15079 // Get the permuted scalar to vector nodes for the source(s) that come from 15080 // ISD::SCALAR_TO_VECTOR. 15081 // On big endian systems, this only makes sense for element sizes smaller 15082 // than 64 bits since for 64-bit elements, all instructions already put 15083 // the value into element zero. Since scalar size of LHS and RHS may differ 15084 // after isScalarToVec, this should be checked using their own sizes. 15085 if (SToVLHS) { 15086 if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64) 15087 return Res; 15088 // Set up the values for the shuffle vector fixup. 15089 LHSMaxIdx = NumEltsOut / NumEltsIn; 15090 SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget); 15091 if (SToVLHS.getValueType() != LHS.getValueType()) 15092 SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS); 15093 LHS = SToVLHS; 15094 } 15095 if (SToVRHS) { 15096 if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64) 15097 return Res; 15098 RHSMinIdx = NumEltsOut; 15099 RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx; 15100 SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget); 15101 if (SToVRHS.getValueType() != RHS.getValueType()) 15102 SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS); 15103 RHS = SToVRHS; 15104 } 15105 15106 // Fix up the shuffle mask to reflect where the desired element actually is. 15107 // The minimum and maximum indices that correspond to element zero for both 15108 // the LHS and RHS are computed and will control which shuffle mask entries 15109 // are to be changed. For example, if the RHS is permuted, any shuffle mask 15110 // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted. 15111 fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx, 15112 HalfVec, ValidLaneWidth, Subtarget); 15113 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 15114 15115 // We may have simplified away the shuffle. We won't be able to do anything 15116 // further with it here. 15117 if (!isa<ShuffleVectorSDNode>(Res)) 15118 return Res; 15119 Mask = cast<ShuffleVectorSDNode>(Res)->getMask(); 15120 } 15121 15122 SDValue TheSplat = IsLittleEndian ? RHS : LHS; 15123 // The common case after we commuted the shuffle is that the RHS is a splat 15124 // and we have elements coming in from the splat at indices that are not 15125 // conducive to using a merge. 15126 // Example: 15127 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero> 15128 if (!isSplatBV(TheSplat)) 15129 return Res; 15130 15131 // We are looking for a mask such that all even elements are from 15132 // one vector and all odd elements from the other. 15133 if (!isAlternatingShuffMask(Mask, NumElts)) 15134 return Res; 15135 15136 // Adjust the mask so we are pulling in the same index from the splat 15137 // as the index from the interesting vector in consecutive elements. 15138 if (IsLittleEndian) { 15139 // Example (even elements from first vector): 15140 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero> 15141 if (Mask[0] < NumElts) 15142 for (int i = 1, e = Mask.size(); i < e; i += 2) { 15143 if (ShuffV[i] < 0) 15144 continue; 15145 ShuffV[i] = (ShuffV[i - 1] + NumElts); 15146 } 15147 // Example (odd elements from first vector): 15148 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero> 15149 else 15150 for (int i = 0, e = Mask.size(); i < e; i += 2) { 15151 if (ShuffV[i] < 0) 15152 continue; 15153 ShuffV[i] = (ShuffV[i + 1] + NumElts); 15154 } 15155 } else { 15156 // Example (even elements from first vector): 15157 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1 15158 if (Mask[0] < NumElts) 15159 for (int i = 0, e = Mask.size(); i < e; i += 2) { 15160 if (ShuffV[i] < 0) 15161 continue; 15162 ShuffV[i] = ShuffV[i + 1] - NumElts; 15163 } 15164 // Example (odd elements from first vector): 15165 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1 15166 else 15167 for (int i = 1, e = Mask.size(); i < e; i += 2) { 15168 if (ShuffV[i] < 0) 15169 continue; 15170 ShuffV[i] = ShuffV[i - 1] - NumElts; 15171 } 15172 } 15173 15174 // If the RHS has undefs, we need to remove them since we may have created 15175 // a shuffle that adds those instead of the splat value. 15176 SDValue SplatVal = 15177 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue(); 15178 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal); 15179 15180 if (IsLittleEndian) 15181 RHS = TheSplat; 15182 else 15183 LHS = TheSplat; 15184 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV); 15185 } 15186 15187 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN, 15188 LSBaseSDNode *LSBase, 15189 DAGCombinerInfo &DCI) const { 15190 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) && 15191 "Not a reverse memop pattern!"); 15192 15193 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool { 15194 auto Mask = SVN->getMask(); 15195 int i = 0; 15196 auto I = Mask.rbegin(); 15197 auto E = Mask.rend(); 15198 15199 for (; I != E; ++I) { 15200 if (*I != i) 15201 return false; 15202 i++; 15203 } 15204 return true; 15205 }; 15206 15207 SelectionDAG &DAG = DCI.DAG; 15208 EVT VT = SVN->getValueType(0); 15209 15210 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX()) 15211 return SDValue(); 15212 15213 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order. 15214 // See comment in PPCVSXSwapRemoval.cpp. 15215 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it. 15216 if (!Subtarget.hasP9Vector()) 15217 return SDValue(); 15218 15219 if(!IsElementReverse(SVN)) 15220 return SDValue(); 15221 15222 if (LSBase->getOpcode() == ISD::LOAD) { 15223 // If the load return value 0 has more than one user except the 15224 // shufflevector instruction, it is not profitable to replace the 15225 // shufflevector with a reverse load. 15226 for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end(); 15227 UI != UE; ++UI) 15228 if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE) 15229 return SDValue(); 15230 15231 SDLoc dl(LSBase); 15232 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()}; 15233 return DAG.getMemIntrinsicNode( 15234 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps, 15235 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15236 } 15237 15238 if (LSBase->getOpcode() == ISD::STORE) { 15239 // If there are other uses of the shuffle, the swap cannot be avoided. 15240 // Forcing the use of an X-Form (since swapped stores only have 15241 // X-Forms) without removing the swap is unprofitable. 15242 if (!SVN->hasOneUse()) 15243 return SDValue(); 15244 15245 SDLoc dl(LSBase); 15246 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0), 15247 LSBase->getBasePtr()}; 15248 return DAG.getMemIntrinsicNode( 15249 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps, 15250 LSBase->getMemoryVT(), LSBase->getMemOperand()); 15251 } 15252 15253 llvm_unreachable("Expected a load or store node here"); 15254 } 15255 15256 static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) { 15257 unsigned IntrinsicID = 15258 cast<ConstantSDNode>(Intrin.getOperand(1))->getZExtValue(); 15259 if (IntrinsicID == Intrinsic::ppc_stdcx) 15260 StoreWidth = 8; 15261 else if (IntrinsicID == Intrinsic::ppc_stwcx) 15262 StoreWidth = 4; 15263 else if (IntrinsicID == Intrinsic::ppc_sthcx) 15264 StoreWidth = 2; 15265 else if (IntrinsicID == Intrinsic::ppc_stbcx) 15266 StoreWidth = 1; 15267 else 15268 return false; 15269 return true; 15270 } 15271 15272 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, 15273 DAGCombinerInfo &DCI) const { 15274 SelectionDAG &DAG = DCI.DAG; 15275 SDLoc dl(N); 15276 switch (N->getOpcode()) { 15277 default: break; 15278 case ISD::ADD: 15279 return combineADD(N, DCI); 15280 case ISD::SHL: 15281 return combineSHL(N, DCI); 15282 case ISD::SRA: 15283 return combineSRA(N, DCI); 15284 case ISD::SRL: 15285 return combineSRL(N, DCI); 15286 case ISD::MUL: 15287 return combineMUL(N, DCI); 15288 case ISD::FMA: 15289 case PPCISD::FNMSUB: 15290 return combineFMALike(N, DCI); 15291 case PPCISD::SHL: 15292 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. 15293 return N->getOperand(0); 15294 break; 15295 case PPCISD::SRL: 15296 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. 15297 return N->getOperand(0); 15298 break; 15299 case PPCISD::SRA: 15300 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 15301 if (C->isZero() || // 0 >>s V -> 0. 15302 C->isAllOnes()) // -1 >>s V -> -1. 15303 return N->getOperand(0); 15304 } 15305 break; 15306 case ISD::SIGN_EXTEND: 15307 case ISD::ZERO_EXTEND: 15308 case ISD::ANY_EXTEND: 15309 return DAGCombineExtBoolTrunc(N, DCI); 15310 case ISD::TRUNCATE: 15311 return combineTRUNCATE(N, DCI); 15312 case ISD::SETCC: 15313 if (SDValue CSCC = combineSetCC(N, DCI)) 15314 return CSCC; 15315 [[fallthrough]]; 15316 case ISD::SELECT_CC: 15317 return DAGCombineTruncBoolExt(N, DCI); 15318 case ISD::SINT_TO_FP: 15319 case ISD::UINT_TO_FP: 15320 return combineFPToIntToFP(N, DCI); 15321 case ISD::VECTOR_SHUFFLE: 15322 if (ISD::isNormalLoad(N->getOperand(0).getNode())) { 15323 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0)); 15324 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI); 15325 } 15326 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG); 15327 case ISD::STORE: { 15328 15329 EVT Op1VT = N->getOperand(1).getValueType(); 15330 unsigned Opcode = N->getOperand(1).getOpcode(); 15331 15332 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) { 15333 SDValue Val= combineStoreFPToInt(N, DCI); 15334 if (Val) 15335 return Val; 15336 } 15337 15338 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) { 15339 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1)); 15340 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI); 15341 if (Val) 15342 return Val; 15343 } 15344 15345 // Turn STORE (BSWAP) -> sthbrx/stwbrx. 15346 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP && 15347 N->getOperand(1).getNode()->hasOneUse() && 15348 (Op1VT == MVT::i32 || Op1VT == MVT::i16 || 15349 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) { 15350 15351 // STBRX can only handle simple types and it makes no sense to store less 15352 // two bytes in byte-reversed order. 15353 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT(); 15354 if (mVT.isExtended() || mVT.getSizeInBits() < 16) 15355 break; 15356 15357 SDValue BSwapOp = N->getOperand(1).getOperand(0); 15358 // Do an any-extend to 32-bits if this is a half-word input. 15359 if (BSwapOp.getValueType() == MVT::i16) 15360 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); 15361 15362 // If the type of BSWAP operand is wider than stored memory width 15363 // it need to be shifted to the right side before STBRX. 15364 if (Op1VT.bitsGT(mVT)) { 15365 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits(); 15366 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp, 15367 DAG.getConstant(Shift, dl, MVT::i32)); 15368 // Need to truncate if this is a bswap of i64 stored as i32/i16. 15369 if (Op1VT == MVT::i64) 15370 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp); 15371 } 15372 15373 SDValue Ops[] = { 15374 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT) 15375 }; 15376 return 15377 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), 15378 Ops, cast<StoreSDNode>(N)->getMemoryVT(), 15379 cast<StoreSDNode>(N)->getMemOperand()); 15380 } 15381 15382 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0> 15383 // So it can increase the chance of CSE constant construction. 15384 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() && 15385 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) { 15386 // Need to sign-extended to 64-bits to handle negative values. 15387 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT(); 15388 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1), 15389 MemVT.getSizeInBits()); 15390 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64); 15391 15392 // DAG.getTruncStore() can't be used here because it doesn't accept 15393 // the general (base + offset) addressing mode. 15394 // So we use UpdateNodeOperands and setTruncatingStore instead. 15395 DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2), 15396 N->getOperand(3)); 15397 cast<StoreSDNode>(N)->setTruncatingStore(true); 15398 return SDValue(N, 0); 15399 } 15400 15401 // For little endian, VSX stores require generating xxswapd/lxvd2x. 15402 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15403 if (Op1VT.isSimple()) { 15404 MVT StoreVT = Op1VT.getSimpleVT(); 15405 if (Subtarget.needsSwapsForVSXMemOps() && 15406 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || 15407 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) 15408 return expandVSXStoreForLE(N, DCI); 15409 } 15410 break; 15411 } 15412 case ISD::LOAD: { 15413 LoadSDNode *LD = cast<LoadSDNode>(N); 15414 EVT VT = LD->getValueType(0); 15415 15416 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15417 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15418 if (VT.isSimple()) { 15419 MVT LoadVT = VT.getSimpleVT(); 15420 if (Subtarget.needsSwapsForVSXMemOps() && 15421 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || 15422 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) 15423 return expandVSXLoadForLE(N, DCI); 15424 } 15425 15426 // We sometimes end up with a 64-bit integer load, from which we extract 15427 // two single-precision floating-point numbers. This happens with 15428 // std::complex<float>, and other similar structures, because of the way we 15429 // canonicalize structure copies. However, if we lack direct moves, 15430 // then the final bitcasts from the extracted integer values to the 15431 // floating-point numbers turn into store/load pairs. Even with direct moves, 15432 // just loading the two floating-point numbers is likely better. 15433 auto ReplaceTwoFloatLoad = [&]() { 15434 if (VT != MVT::i64) 15435 return false; 15436 15437 if (LD->getExtensionType() != ISD::NON_EXTLOAD || 15438 LD->isVolatile()) 15439 return false; 15440 15441 // We're looking for a sequence like this: 15442 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64 15443 // t16: i64 = srl t13, Constant:i32<32> 15444 // t17: i32 = truncate t16 15445 // t18: f32 = bitcast t17 15446 // t19: i32 = truncate t13 15447 // t20: f32 = bitcast t19 15448 15449 if (!LD->hasNUsesOfValue(2, 0)) 15450 return false; 15451 15452 auto UI = LD->use_begin(); 15453 while (UI.getUse().getResNo() != 0) ++UI; 15454 SDNode *Trunc = *UI++; 15455 while (UI.getUse().getResNo() != 0) ++UI; 15456 SDNode *RightShift = *UI; 15457 if (Trunc->getOpcode() != ISD::TRUNCATE) 15458 std::swap(Trunc, RightShift); 15459 15460 if (Trunc->getOpcode() != ISD::TRUNCATE || 15461 Trunc->getValueType(0) != MVT::i32 || 15462 !Trunc->hasOneUse()) 15463 return false; 15464 if (RightShift->getOpcode() != ISD::SRL || 15465 !isa<ConstantSDNode>(RightShift->getOperand(1)) || 15466 RightShift->getConstantOperandVal(1) != 32 || 15467 !RightShift->hasOneUse()) 15468 return false; 15469 15470 SDNode *Trunc2 = *RightShift->use_begin(); 15471 if (Trunc2->getOpcode() != ISD::TRUNCATE || 15472 Trunc2->getValueType(0) != MVT::i32 || 15473 !Trunc2->hasOneUse()) 15474 return false; 15475 15476 SDNode *Bitcast = *Trunc->use_begin(); 15477 SDNode *Bitcast2 = *Trunc2->use_begin(); 15478 15479 if (Bitcast->getOpcode() != ISD::BITCAST || 15480 Bitcast->getValueType(0) != MVT::f32) 15481 return false; 15482 if (Bitcast2->getOpcode() != ISD::BITCAST || 15483 Bitcast2->getValueType(0) != MVT::f32) 15484 return false; 15485 15486 if (Subtarget.isLittleEndian()) 15487 std::swap(Bitcast, Bitcast2); 15488 15489 // Bitcast has the second float (in memory-layout order) and Bitcast2 15490 // has the first one. 15491 15492 SDValue BasePtr = LD->getBasePtr(); 15493 if (LD->isIndexed()) { 15494 assert(LD->getAddressingMode() == ISD::PRE_INC && 15495 "Non-pre-inc AM on PPC?"); 15496 BasePtr = 15497 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15498 LD->getOffset()); 15499 } 15500 15501 auto MMOFlags = 15502 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile; 15503 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr, 15504 LD->getPointerInfo(), LD->getAlign(), 15505 MMOFlags, LD->getAAInfo()); 15506 SDValue AddPtr = 15507 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), 15508 BasePtr, DAG.getIntPtrConstant(4, dl)); 15509 SDValue FloatLoad2 = DAG.getLoad( 15510 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr, 15511 LD->getPointerInfo().getWithOffset(4), 15512 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo()); 15513 15514 if (LD->isIndexed()) { 15515 // Note that DAGCombine should re-form any pre-increment load(s) from 15516 // what is produced here if that makes sense. 15517 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr); 15518 } 15519 15520 DCI.CombineTo(Bitcast2, FloatLoad); 15521 DCI.CombineTo(Bitcast, FloatLoad2); 15522 15523 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1), 15524 SDValue(FloatLoad2.getNode(), 1)); 15525 return true; 15526 }; 15527 15528 if (ReplaceTwoFloatLoad()) 15529 return SDValue(N, 0); 15530 15531 EVT MemVT = LD->getMemoryVT(); 15532 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 15533 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty); 15534 if (LD->isUnindexed() && VT.isVector() && 15535 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && 15536 // P8 and later hardware should just use LOAD. 15537 !Subtarget.hasP8Vector() && 15538 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 15539 VT == MVT::v4f32))) && 15540 LD->getAlign() < ABIAlignment) { 15541 // This is a type-legal unaligned Altivec load. 15542 SDValue Chain = LD->getChain(); 15543 SDValue Ptr = LD->getBasePtr(); 15544 bool isLittleEndian = Subtarget.isLittleEndian(); 15545 15546 // This implements the loading of unaligned vectors as described in 15547 // the venerable Apple Velocity Engine overview. Specifically: 15548 // https://developer.apple.com/hardwaredrivers/ve/alignment.html 15549 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html 15550 // 15551 // The general idea is to expand a sequence of one or more unaligned 15552 // loads into an alignment-based permutation-control instruction (lvsl 15553 // or lvsr), a series of regular vector loads (which always truncate 15554 // their input address to an aligned address), and a series of 15555 // permutations. The results of these permutations are the requested 15556 // loaded values. The trick is that the last "extra" load is not taken 15557 // from the address you might suspect (sizeof(vector) bytes after the 15558 // last requested load), but rather sizeof(vector) - 1 bytes after the 15559 // last requested vector. The point of this is to avoid a page fault if 15560 // the base address happened to be aligned. This works because if the 15561 // base address is aligned, then adding less than a full vector length 15562 // will cause the last vector in the sequence to be (re)loaded. 15563 // Otherwise, the next vector will be fetched as you might suspect was 15564 // necessary. 15565 15566 // We might be able to reuse the permutation generation from 15567 // a different base address offset from this one by an aligned amount. 15568 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this 15569 // optimization later. 15570 Intrinsic::ID Intr, IntrLD, IntrPerm; 15571 MVT PermCntlTy, PermTy, LDTy; 15572 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15573 : Intrinsic::ppc_altivec_lvsl; 15574 IntrLD = Intrinsic::ppc_altivec_lvx; 15575 IntrPerm = Intrinsic::ppc_altivec_vperm; 15576 PermCntlTy = MVT::v16i8; 15577 PermTy = MVT::v4i32; 15578 LDTy = MVT::v4i32; 15579 15580 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); 15581 15582 // Create the new MMO for the new base load. It is like the original MMO, 15583 // but represents an area in memory almost twice the vector size centered 15584 // on the original address. If the address is unaligned, we might start 15585 // reading up to (sizeof(vector)-1) bytes below the address of the 15586 // original unaligned load. 15587 MachineFunction &MF = DAG.getMachineFunction(); 15588 MachineMemOperand *BaseMMO = 15589 MF.getMachineMemOperand(LD->getMemOperand(), 15590 -(int64_t)MemVT.getStoreSize()+1, 15591 2*MemVT.getStoreSize()-1); 15592 15593 // Create the new base load. 15594 SDValue LDXIntID = 15595 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); 15596 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; 15597 SDValue BaseLoad = 15598 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15599 DAG.getVTList(PermTy, MVT::Other), 15600 BaseLoadOps, LDTy, BaseMMO); 15601 15602 // Note that the value of IncOffset (which is provided to the next 15603 // load's pointer info offset value, and thus used to calculate the 15604 // alignment), and the value of IncValue (which is actually used to 15605 // increment the pointer value) are different! This is because we 15606 // require the next load to appear to be aligned, even though it 15607 // is actually offset from the base pointer by a lesser amount. 15608 int IncOffset = VT.getSizeInBits() / 8; 15609 int IncValue = IncOffset; 15610 15611 // Walk (both up and down) the chain looking for another load at the real 15612 // (aligned) offset (the alignment of the other load does not matter in 15613 // this case). If found, then do not use the offset reduction trick, as 15614 // that will prevent the loads from being later combined (as they would 15615 // otherwise be duplicates). 15616 if (!findConsecutiveLoad(LD, DAG)) 15617 --IncValue; 15618 15619 SDValue Increment = 15620 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); 15621 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); 15622 15623 MachineMemOperand *ExtraMMO = 15624 MF.getMachineMemOperand(LD->getMemOperand(), 15625 1, 2*MemVT.getStoreSize()-1); 15626 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; 15627 SDValue ExtraLoad = 15628 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, 15629 DAG.getVTList(PermTy, MVT::Other), 15630 ExtraLoadOps, LDTy, ExtraMMO); 15631 15632 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15633 BaseLoad.getValue(1), ExtraLoad.getValue(1)); 15634 15635 // Because vperm has a big-endian bias, we must reverse the order 15636 // of the input vectors and complement the permute control vector 15637 // when generating little endian code. We have already handled the 15638 // latter by using lvsr instead of lvsl, so just reverse BaseLoad 15639 // and ExtraLoad here. 15640 SDValue Perm; 15641 if (isLittleEndian) 15642 Perm = BuildIntrinsicOp(IntrPerm, 15643 ExtraLoad, BaseLoad, PermCntl, DAG, dl); 15644 else 15645 Perm = BuildIntrinsicOp(IntrPerm, 15646 BaseLoad, ExtraLoad, PermCntl, DAG, dl); 15647 15648 if (VT != PermTy) 15649 Perm = Subtarget.hasAltivec() 15650 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) 15651 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, 15652 DAG.getTargetConstant(1, dl, MVT::i64)); 15653 // second argument is 1 because this rounding 15654 // is always exact. 15655 15656 // The output of the permutation is our loaded result, the TokenFactor is 15657 // our new chain. 15658 DCI.CombineTo(N, Perm, TF); 15659 return SDValue(N, 0); 15660 } 15661 } 15662 break; 15663 case ISD::INTRINSIC_WO_CHAIN: { 15664 bool isLittleEndian = Subtarget.isLittleEndian(); 15665 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 15666 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr 15667 : Intrinsic::ppc_altivec_lvsl); 15668 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) { 15669 SDValue Add = N->getOperand(1); 15670 15671 int Bits = 4 /* 16 byte alignment */; 15672 15673 if (DAG.MaskedValueIsZero(Add->getOperand(1), 15674 APInt::getAllOnes(Bits /* alignment */) 15675 .zext(Add.getScalarValueSizeInBits()))) { 15676 SDNode *BasePtr = Add->getOperand(0).getNode(); 15677 for (SDNode *U : BasePtr->uses()) { 15678 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15679 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) { 15680 // We've found another LVSL/LVSR, and this address is an aligned 15681 // multiple of that one. The results will be the same, so use the 15682 // one we've just found instead. 15683 15684 return SDValue(U, 0); 15685 } 15686 } 15687 } 15688 15689 if (isa<ConstantSDNode>(Add->getOperand(1))) { 15690 SDNode *BasePtr = Add->getOperand(0).getNode(); 15691 for (SDNode *U : BasePtr->uses()) { 15692 if (U->getOpcode() == ISD::ADD && 15693 isa<ConstantSDNode>(U->getOperand(1)) && 15694 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - 15695 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) % 15696 (1ULL << Bits) == 15697 0) { 15698 SDNode *OtherAdd = U; 15699 for (SDNode *V : OtherAdd->uses()) { 15700 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15701 cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() == 15702 IID) { 15703 return SDValue(V, 0); 15704 } 15705 } 15706 } 15707 } 15708 } 15709 } 15710 15711 // Combine vmaxsw/h/b(a, a's negation) to abs(a) 15712 // Expose the vabsduw/h/b opportunity for down stream 15713 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() && 15714 (IID == Intrinsic::ppc_altivec_vmaxsw || 15715 IID == Intrinsic::ppc_altivec_vmaxsh || 15716 IID == Intrinsic::ppc_altivec_vmaxsb)) { 15717 SDValue V1 = N->getOperand(1); 15718 SDValue V2 = N->getOperand(2); 15719 if ((V1.getSimpleValueType() == MVT::v4i32 || 15720 V1.getSimpleValueType() == MVT::v8i16 || 15721 V1.getSimpleValueType() == MVT::v16i8) && 15722 V1.getSimpleValueType() == V2.getSimpleValueType()) { 15723 // (0-a, a) 15724 if (V1.getOpcode() == ISD::SUB && 15725 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) && 15726 V1.getOperand(1) == V2) { 15727 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2); 15728 } 15729 // (a, 0-a) 15730 if (V2.getOpcode() == ISD::SUB && 15731 ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) && 15732 V2.getOperand(1) == V1) { 15733 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15734 } 15735 // (x-y, y-x) 15736 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB && 15737 V1.getOperand(0) == V2.getOperand(1) && 15738 V1.getOperand(1) == V2.getOperand(0)) { 15739 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1); 15740 } 15741 } 15742 } 15743 } 15744 15745 break; 15746 case ISD::INTRINSIC_W_CHAIN: 15747 // For little endian, VSX loads require generating lxvd2x/xxswapd. 15748 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load. 15749 if (Subtarget.needsSwapsForVSXMemOps()) { 15750 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15751 default: 15752 break; 15753 case Intrinsic::ppc_vsx_lxvw4x: 15754 case Intrinsic::ppc_vsx_lxvd2x: 15755 return expandVSXLoadForLE(N, DCI); 15756 } 15757 } 15758 break; 15759 case ISD::INTRINSIC_VOID: 15760 // For little endian, VSX stores require generating xxswapd/stxvd2x. 15761 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store. 15762 if (Subtarget.needsSwapsForVSXMemOps()) { 15763 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 15764 default: 15765 break; 15766 case Intrinsic::ppc_vsx_stxvw4x: 15767 case Intrinsic::ppc_vsx_stxvd2x: 15768 return expandVSXStoreForLE(N, DCI); 15769 } 15770 } 15771 break; 15772 case ISD::BSWAP: { 15773 // Turn BSWAP (LOAD) -> lhbrx/lwbrx. 15774 // For subtargets without LDBRX, we can still do better than the default 15775 // expansion even for 64-bit BSWAP (LOAD). 15776 bool Is64BitBswapOn64BitTgt = 15777 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64; 15778 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) && 15779 N->getOperand(0).hasOneUse(); 15780 if (IsSingleUseNormalLd && 15781 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || 15782 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) { 15783 SDValue Load = N->getOperand(0); 15784 LoadSDNode *LD = cast<LoadSDNode>(Load); 15785 // Create the byte-swapping load. 15786 SDValue Ops[] = { 15787 LD->getChain(), // Chain 15788 LD->getBasePtr(), // Ptr 15789 DAG.getValueType(N->getValueType(0)) // VT 15790 }; 15791 SDValue BSLoad = 15792 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, 15793 DAG.getVTList(N->getValueType(0) == MVT::i64 ? 15794 MVT::i64 : MVT::i32, MVT::Other), 15795 Ops, LD->getMemoryVT(), LD->getMemOperand()); 15796 15797 // If this is an i16 load, insert the truncate. 15798 SDValue ResVal = BSLoad; 15799 if (N->getValueType(0) == MVT::i16) 15800 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); 15801 15802 // First, combine the bswap away. This makes the value produced by the 15803 // load dead. 15804 DCI.CombineTo(N, ResVal); 15805 15806 // Next, combine the load away, we give it a bogus result value but a real 15807 // chain result. The result value is dead because the bswap is dead. 15808 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); 15809 15810 // Return N so it doesn't get rechecked! 15811 return SDValue(N, 0); 15812 } 15813 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only 15814 // before legalization so that the BUILD_PAIR is handled correctly. 15815 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt || 15816 !IsSingleUseNormalLd) 15817 return SDValue(); 15818 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0)); 15819 15820 // Can't split volatile or atomic loads. 15821 if (!LD->isSimple()) 15822 return SDValue(); 15823 SDValue BasePtr = LD->getBasePtr(); 15824 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, 15825 LD->getPointerInfo(), LD->getAlign()); 15826 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo); 15827 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, 15828 DAG.getIntPtrConstant(4, dl)); 15829 MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand( 15830 LD->getMemOperand(), 4, 4); 15831 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO); 15832 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi); 15833 SDValue Res; 15834 if (Subtarget.isLittleEndian()) 15835 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo); 15836 else 15837 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); 15838 SDValue TF = 15839 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 15840 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1)); 15841 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF); 15842 return Res; 15843 } 15844 case PPCISD::VCMP: 15845 // If a VCMP_rec node already exists with exactly the same operands as this 15846 // node, use its result instead of this node (VCMP_rec computes both a CR6 15847 // and a normal output). 15848 // 15849 if (!N->getOperand(0).hasOneUse() && 15850 !N->getOperand(1).hasOneUse() && 15851 !N->getOperand(2).hasOneUse()) { 15852 15853 // Scan all of the users of the LHS, looking for VCMP_rec's that match. 15854 SDNode *VCMPrecNode = nullptr; 15855 15856 SDNode *LHSN = N->getOperand(0).getNode(); 15857 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); 15858 UI != E; ++UI) 15859 if (UI->getOpcode() == PPCISD::VCMP_rec && 15860 UI->getOperand(1) == N->getOperand(1) && 15861 UI->getOperand(2) == N->getOperand(2) && 15862 UI->getOperand(0) == N->getOperand(0)) { 15863 VCMPrecNode = *UI; 15864 break; 15865 } 15866 15867 // If there is no VCMP_rec node, or if the flag value has a single use, 15868 // don't transform this. 15869 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1)) 15870 break; 15871 15872 // Look at the (necessarily single) use of the flag value. If it has a 15873 // chain, this transformation is more complex. Note that multiple things 15874 // could use the value result, which we should ignore. 15875 SDNode *FlagUser = nullptr; 15876 for (SDNode::use_iterator UI = VCMPrecNode->use_begin(); 15877 FlagUser == nullptr; ++UI) { 15878 assert(UI != VCMPrecNode->use_end() && "Didn't find user!"); 15879 SDNode *User = *UI; 15880 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 15881 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) { 15882 FlagUser = User; 15883 break; 15884 } 15885 } 15886 } 15887 15888 // If the user is a MFOCRF instruction, we know this is safe. 15889 // Otherwise we give up for right now. 15890 if (FlagUser->getOpcode() == PPCISD::MFOCRF) 15891 return SDValue(VCMPrecNode, 0); 15892 } 15893 break; 15894 case ISD::BR_CC: { 15895 // If this is a branch on an altivec predicate comparison, lower this so 15896 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This 15897 // lowering is done pre-legalize, because the legalizer lowers the predicate 15898 // compare down to code that is difficult to reassemble. 15899 // This code also handles branches that depend on the result of a store 15900 // conditional. 15901 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 15902 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); 15903 15904 int CompareOpc; 15905 bool isDot; 15906 15907 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE)) 15908 break; 15909 15910 // Since we are doing this pre-legalize, the RHS can be a constant of 15911 // arbitrary bitwidth which may cause issues when trying to get the value 15912 // from the underlying APInt. 15913 auto RHSAPInt = cast<ConstantSDNode>(RHS)->getAPIntValue(); 15914 if (!RHSAPInt.isIntN(64)) 15915 break; 15916 15917 unsigned Val = RHSAPInt.getZExtValue(); 15918 auto isImpossibleCompare = [&]() { 15919 // If this is a comparison against something other than 0/1, then we know 15920 // that the condition is never/always true. 15921 if (Val != 0 && Val != 1) { 15922 if (CC == ISD::SETEQ) // Cond never true, remove branch. 15923 return N->getOperand(0); 15924 // Always !=, turn it into an unconditional branch. 15925 return DAG.getNode(ISD::BR, dl, MVT::Other, 15926 N->getOperand(0), N->getOperand(4)); 15927 } 15928 return SDValue(); 15929 }; 15930 // Combine branches fed by store conditional instructions (st[bhwd]cx). 15931 unsigned StoreWidth = 0; 15932 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && 15933 isStoreConditional(LHS, StoreWidth)) { 15934 if (SDValue Impossible = isImpossibleCompare()) 15935 return Impossible; 15936 PPC::Predicate CompOpc; 15937 // eq 0 => ne 15938 // ne 0 => eq 15939 // eq 1 => eq 15940 // ne 1 => ne 15941 if (Val == 0) 15942 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ; 15943 else 15944 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE; 15945 15946 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3), 15947 DAG.getConstant(StoreWidth, dl, MVT::i32)}; 15948 auto *MemNode = cast<MemSDNode>(LHS); 15949 SDValue ConstSt = DAG.getMemIntrinsicNode( 15950 PPCISD::STORE_COND, dl, 15951 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops, 15952 MemNode->getMemoryVT(), MemNode->getMemOperand()); 15953 15954 SDValue InChain; 15955 // Unchain the branch from the original store conditional. 15956 if (N->getOperand(0) == LHS.getValue(1)) 15957 InChain = LHS.getOperand(0); 15958 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) { 15959 SmallVector<SDValue, 4> InChains; 15960 SDValue InTF = N->getOperand(0); 15961 for (int i = 0, e = InTF.getNumOperands(); i < e; i++) 15962 if (InTF.getOperand(i) != LHS.getValue(1)) 15963 InChains.push_back(InTF.getOperand(i)); 15964 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains); 15965 } 15966 15967 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain, 15968 DAG.getConstant(CompOpc, dl, MVT::i32), 15969 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4), 15970 ConstSt.getValue(2)); 15971 } 15972 15973 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && 15974 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { 15975 assert(isDot && "Can't compare against a vector result!"); 15976 15977 if (SDValue Impossible = isImpossibleCompare()) 15978 return Impossible; 15979 15980 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); 15981 // Create the PPCISD altivec 'dot' comparison node. 15982 SDValue Ops[] = { 15983 LHS.getOperand(2), // LHS of compare 15984 LHS.getOperand(3), // RHS of compare 15985 DAG.getConstant(CompareOpc, dl, MVT::i32) 15986 }; 15987 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; 15988 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops); 15989 15990 // Unpack the result based on how the target uses it. 15991 PPC::Predicate CompOpc; 15992 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { 15993 default: // Can't happen, don't crash on invalid number though. 15994 case 0: // Branch on the value of the EQ bit of CR6. 15995 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; 15996 break; 15997 case 1: // Branch on the inverted value of the EQ bit of CR6. 15998 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; 15999 break; 16000 case 2: // Branch on the value of the LT bit of CR6. 16001 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; 16002 break; 16003 case 3: // Branch on the inverted value of the LT bit of CR6. 16004 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; 16005 break; 16006 } 16007 16008 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), 16009 DAG.getConstant(CompOpc, dl, MVT::i32), 16010 DAG.getRegister(PPC::CR6, MVT::i32), 16011 N->getOperand(4), CompNode.getValue(1)); 16012 } 16013 break; 16014 } 16015 case ISD::BUILD_VECTOR: 16016 return DAGCombineBuildVector(N, DCI); 16017 case ISD::VSELECT: 16018 return combineVSelect(N, DCI); 16019 } 16020 16021 return SDValue(); 16022 } 16023 16024 SDValue 16025 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 16026 SelectionDAG &DAG, 16027 SmallVectorImpl<SDNode *> &Created) const { 16028 // fold (sdiv X, pow2) 16029 EVT VT = N->getValueType(0); 16030 if (VT == MVT::i64 && !Subtarget.isPPC64()) 16031 return SDValue(); 16032 if ((VT != MVT::i32 && VT != MVT::i64) || 16033 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2())) 16034 return SDValue(); 16035 16036 SDLoc DL(N); 16037 SDValue N0 = N->getOperand(0); 16038 16039 bool IsNegPow2 = Divisor.isNegatedPowerOf2(); 16040 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); 16041 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); 16042 16043 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); 16044 Created.push_back(Op.getNode()); 16045 16046 if (IsNegPow2) { 16047 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); 16048 Created.push_back(Op.getNode()); 16049 } 16050 16051 return Op; 16052 } 16053 16054 //===----------------------------------------------------------------------===// 16055 // Inline Assembly Support 16056 //===----------------------------------------------------------------------===// 16057 16058 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 16059 KnownBits &Known, 16060 const APInt &DemandedElts, 16061 const SelectionDAG &DAG, 16062 unsigned Depth) const { 16063 Known.resetAll(); 16064 switch (Op.getOpcode()) { 16065 default: break; 16066 case PPCISD::LBRX: { 16067 // lhbrx is known to have the top bits cleared out. 16068 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) 16069 Known.Zero = 0xFFFF0000; 16070 break; 16071 } 16072 case ISD::INTRINSIC_WO_CHAIN: { 16073 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { 16074 default: break; 16075 case Intrinsic::ppc_altivec_vcmpbfp_p: 16076 case Intrinsic::ppc_altivec_vcmpeqfp_p: 16077 case Intrinsic::ppc_altivec_vcmpequb_p: 16078 case Intrinsic::ppc_altivec_vcmpequh_p: 16079 case Intrinsic::ppc_altivec_vcmpequw_p: 16080 case Intrinsic::ppc_altivec_vcmpequd_p: 16081 case Intrinsic::ppc_altivec_vcmpequq_p: 16082 case Intrinsic::ppc_altivec_vcmpgefp_p: 16083 case Intrinsic::ppc_altivec_vcmpgtfp_p: 16084 case Intrinsic::ppc_altivec_vcmpgtsb_p: 16085 case Intrinsic::ppc_altivec_vcmpgtsh_p: 16086 case Intrinsic::ppc_altivec_vcmpgtsw_p: 16087 case Intrinsic::ppc_altivec_vcmpgtsd_p: 16088 case Intrinsic::ppc_altivec_vcmpgtsq_p: 16089 case Intrinsic::ppc_altivec_vcmpgtub_p: 16090 case Intrinsic::ppc_altivec_vcmpgtuh_p: 16091 case Intrinsic::ppc_altivec_vcmpgtuw_p: 16092 case Intrinsic::ppc_altivec_vcmpgtud_p: 16093 case Intrinsic::ppc_altivec_vcmpgtuq_p: 16094 Known.Zero = ~1U; // All bits but the low one are known to be zero. 16095 break; 16096 } 16097 break; 16098 } 16099 case ISD::INTRINSIC_W_CHAIN: { 16100 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { 16101 default: 16102 break; 16103 case Intrinsic::ppc_load2r: 16104 // Top bits are cleared for load2r (which is the same as lhbrx). 16105 Known.Zero = 0xFFFF0000; 16106 break; 16107 } 16108 break; 16109 } 16110 } 16111 } 16112 16113 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 16114 switch (Subtarget.getCPUDirective()) { 16115 default: break; 16116 case PPC::DIR_970: 16117 case PPC::DIR_PWR4: 16118 case PPC::DIR_PWR5: 16119 case PPC::DIR_PWR5X: 16120 case PPC::DIR_PWR6: 16121 case PPC::DIR_PWR6X: 16122 case PPC::DIR_PWR7: 16123 case PPC::DIR_PWR8: 16124 case PPC::DIR_PWR9: 16125 case PPC::DIR_PWR10: 16126 case PPC::DIR_PWR_FUTURE: { 16127 if (!ML) 16128 break; 16129 16130 if (!DisableInnermostLoopAlign32) { 16131 // If the nested loop is an innermost loop, prefer to a 32-byte alignment, 16132 // so that we can decrease cache misses and branch-prediction misses. 16133 // Actual alignment of the loop will depend on the hotness check and other 16134 // logic in alignBlocks. 16135 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty()) 16136 return Align(32); 16137 } 16138 16139 const PPCInstrInfo *TII = Subtarget.getInstrInfo(); 16140 16141 // For small loops (between 5 and 8 instructions), align to a 32-byte 16142 // boundary so that the entire loop fits in one instruction-cache line. 16143 uint64_t LoopSize = 0; 16144 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) 16145 for (const MachineInstr &J : **I) { 16146 LoopSize += TII->getInstSizeInBytes(J); 16147 if (LoopSize > 32) 16148 break; 16149 } 16150 16151 if (LoopSize > 16 && LoopSize <= 32) 16152 return Align(32); 16153 16154 break; 16155 } 16156 } 16157 16158 return TargetLowering::getPrefLoopAlignment(ML); 16159 } 16160 16161 /// getConstraintType - Given a constraint, return the type of 16162 /// constraint it is for this target. 16163 PPCTargetLowering::ConstraintType 16164 PPCTargetLowering::getConstraintType(StringRef Constraint) const { 16165 if (Constraint.size() == 1) { 16166 switch (Constraint[0]) { 16167 default: break; 16168 case 'b': 16169 case 'r': 16170 case 'f': 16171 case 'd': 16172 case 'v': 16173 case 'y': 16174 return C_RegisterClass; 16175 case 'Z': 16176 // FIXME: While Z does indicate a memory constraint, it specifically 16177 // indicates an r+r address (used in conjunction with the 'y' modifier 16178 // in the replacement string). Currently, we're forcing the base 16179 // register to be r0 in the asm printer (which is interpreted as zero) 16180 // and forming the complete address in the second register. This is 16181 // suboptimal. 16182 return C_Memory; 16183 } 16184 } else if (Constraint == "wc") { // individual CR bits. 16185 return C_RegisterClass; 16186 } else if (Constraint == "wa" || Constraint == "wd" || 16187 Constraint == "wf" || Constraint == "ws" || 16188 Constraint == "wi" || Constraint == "ww") { 16189 return C_RegisterClass; // VSX registers. 16190 } 16191 return TargetLowering::getConstraintType(Constraint); 16192 } 16193 16194 /// Examine constraint type and operand type and determine a weight value. 16195 /// This object must already have been set up with the operand type 16196 /// and the current alternative constraint selected. 16197 TargetLowering::ConstraintWeight 16198 PPCTargetLowering::getSingleConstraintMatchWeight( 16199 AsmOperandInfo &info, const char *constraint) const { 16200 ConstraintWeight weight = CW_Invalid; 16201 Value *CallOperandVal = info.CallOperandVal; 16202 // If we don't have a value, we can't do a match, 16203 // but allow it at the lowest weight. 16204 if (!CallOperandVal) 16205 return CW_Default; 16206 Type *type = CallOperandVal->getType(); 16207 16208 // Look at the constraint type. 16209 if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) 16210 return CW_Register; // an individual CR bit. 16211 else if ((StringRef(constraint) == "wa" || 16212 StringRef(constraint) == "wd" || 16213 StringRef(constraint) == "wf") && 16214 type->isVectorTy()) 16215 return CW_Register; 16216 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64)) 16217 return CW_Register; // just hold 64-bit integers data. 16218 else if (StringRef(constraint) == "ws" && type->isDoubleTy()) 16219 return CW_Register; 16220 else if (StringRef(constraint) == "ww" && type->isFloatTy()) 16221 return CW_Register; 16222 16223 switch (*constraint) { 16224 default: 16225 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 16226 break; 16227 case 'b': 16228 if (type->isIntegerTy()) 16229 weight = CW_Register; 16230 break; 16231 case 'f': 16232 if (type->isFloatTy()) 16233 weight = CW_Register; 16234 break; 16235 case 'd': 16236 if (type->isDoubleTy()) 16237 weight = CW_Register; 16238 break; 16239 case 'v': 16240 if (type->isVectorTy()) 16241 weight = CW_Register; 16242 break; 16243 case 'y': 16244 weight = CW_Register; 16245 break; 16246 case 'Z': 16247 weight = CW_Memory; 16248 break; 16249 } 16250 return weight; 16251 } 16252 16253 std::pair<unsigned, const TargetRegisterClass *> 16254 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 16255 StringRef Constraint, 16256 MVT VT) const { 16257 if (Constraint.size() == 1) { 16258 // GCC RS6000 Constraint Letters 16259 switch (Constraint[0]) { 16260 case 'b': // R1-R31 16261 if (VT == MVT::i64 && Subtarget.isPPC64()) 16262 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); 16263 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); 16264 case 'r': // R0-R31 16265 if (VT == MVT::i64 && Subtarget.isPPC64()) 16266 return std::make_pair(0U, &PPC::G8RCRegClass); 16267 return std::make_pair(0U, &PPC::GPRCRegClass); 16268 // 'd' and 'f' constraints are both defined to be "the floating point 16269 // registers", where one is for 32-bit and the other for 64-bit. We don't 16270 // really care overly much here so just give them all the same reg classes. 16271 case 'd': 16272 case 'f': 16273 if (Subtarget.hasSPE()) { 16274 if (VT == MVT::f32 || VT == MVT::i32) 16275 return std::make_pair(0U, &PPC::GPRCRegClass); 16276 if (VT == MVT::f64 || VT == MVT::i64) 16277 return std::make_pair(0U, &PPC::SPERCRegClass); 16278 } else { 16279 if (VT == MVT::f32 || VT == MVT::i32) 16280 return std::make_pair(0U, &PPC::F4RCRegClass); 16281 if (VT == MVT::f64 || VT == MVT::i64) 16282 return std::make_pair(0U, &PPC::F8RCRegClass); 16283 } 16284 break; 16285 case 'v': 16286 if (Subtarget.hasAltivec() && VT.isVector()) 16287 return std::make_pair(0U, &PPC::VRRCRegClass); 16288 else if (Subtarget.hasVSX()) 16289 // Scalars in Altivec registers only make sense with VSX. 16290 return std::make_pair(0U, &PPC::VFRCRegClass); 16291 break; 16292 case 'y': // crrc 16293 return std::make_pair(0U, &PPC::CRRCRegClass); 16294 } 16295 } else if (Constraint == "wc" && Subtarget.useCRBits()) { 16296 // An individual CR bit. 16297 return std::make_pair(0U, &PPC::CRBITRCRegClass); 16298 } else if ((Constraint == "wa" || Constraint == "wd" || 16299 Constraint == "wf" || Constraint == "wi") && 16300 Subtarget.hasVSX()) { 16301 // A VSX register for either a scalar (FP) or vector. There is no 16302 // support for single precision scalars on subtargets prior to Power8. 16303 if (VT.isVector()) 16304 return std::make_pair(0U, &PPC::VSRCRegClass); 16305 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16306 return std::make_pair(0U, &PPC::VSSRCRegClass); 16307 return std::make_pair(0U, &PPC::VSFRCRegClass); 16308 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) { 16309 if (VT == MVT::f32 && Subtarget.hasP8Vector()) 16310 return std::make_pair(0U, &PPC::VSSRCRegClass); 16311 else 16312 return std::make_pair(0U, &PPC::VSFRCRegClass); 16313 } else if (Constraint == "lr") { 16314 if (VT == MVT::i64) 16315 return std::make_pair(0U, &PPC::LR8RCRegClass); 16316 else 16317 return std::make_pair(0U, &PPC::LRRCRegClass); 16318 } 16319 16320 // Handle special cases of physical registers that are not properly handled 16321 // by the base class. 16322 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') { 16323 // If we name a VSX register, we can't defer to the base class because it 16324 // will not recognize the correct register (their names will be VSL{0-31} 16325 // and V{0-31} so they won't match). So we match them here. 16326 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') { 16327 int VSNum = atoi(Constraint.data() + 3); 16328 assert(VSNum >= 0 && VSNum <= 63 && 16329 "Attempted to access a vsr out of range"); 16330 if (VSNum < 32) 16331 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass); 16332 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass); 16333 } 16334 16335 // For float registers, we can't defer to the base class as it will match 16336 // the SPILLTOVSRRC class. 16337 if (Constraint.size() > 3 && Constraint[1] == 'f') { 16338 int RegNum = atoi(Constraint.data() + 2); 16339 if (RegNum > 31 || RegNum < 0) 16340 report_fatal_error("Invalid floating point register number"); 16341 if (VT == MVT::f32 || VT == MVT::i32) 16342 return Subtarget.hasSPE() 16343 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass) 16344 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass); 16345 if (VT == MVT::f64 || VT == MVT::i64) 16346 return Subtarget.hasSPE() 16347 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass) 16348 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass); 16349 } 16350 } 16351 16352 std::pair<unsigned, const TargetRegisterClass *> R = 16353 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 16354 16355 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers 16356 // (which we call X[0-9]+). If a 64-bit value has been requested, and a 16357 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent 16358 // register. 16359 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use 16360 // the AsmName field from *RegisterInfo.td, then this would not be necessary. 16361 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && 16362 PPC::GPRCRegClass.contains(R.first)) 16363 return std::make_pair(TRI->getMatchingSuperReg(R.first, 16364 PPC::sub_32, &PPC::G8RCRegClass), 16365 &PPC::G8RCRegClass); 16366 16367 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. 16368 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) { 16369 R.first = PPC::CR0; 16370 R.second = &PPC::CRRCRegClass; 16371 } 16372 // FIXME: This warning should ideally be emitted in the front end. 16373 const auto &TM = getTargetMachine(); 16374 if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) { 16375 if (((R.first >= PPC::V20 && R.first <= PPC::V31) || 16376 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) && 16377 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass)) 16378 errs() << "warning: vector registers 20 to 32 are reserved in the " 16379 "default AIX AltiVec ABI and cannot be used\n"; 16380 } 16381 16382 return R; 16383 } 16384 16385 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 16386 /// vector. If it is invalid, don't add anything to Ops. 16387 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, 16388 std::string &Constraint, 16389 std::vector<SDValue>&Ops, 16390 SelectionDAG &DAG) const { 16391 SDValue Result; 16392 16393 // Only support length 1 constraints. 16394 if (Constraint.length() > 1) return; 16395 16396 char Letter = Constraint[0]; 16397 switch (Letter) { 16398 default: break; 16399 case 'I': 16400 case 'J': 16401 case 'K': 16402 case 'L': 16403 case 'M': 16404 case 'N': 16405 case 'O': 16406 case 'P': { 16407 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); 16408 if (!CST) return; // Must be an immediate to match. 16409 SDLoc dl(Op); 16410 int64_t Value = CST->getSExtValue(); 16411 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative 16412 // numbers are printed as such. 16413 switch (Letter) { 16414 default: llvm_unreachable("Unknown constraint letter!"); 16415 case 'I': // "I" is a signed 16-bit constant. 16416 if (isInt<16>(Value)) 16417 Result = DAG.getTargetConstant(Value, dl, TCVT); 16418 break; 16419 case 'J': // "J" is a constant with only the high-order 16 bits nonzero. 16420 if (isShiftedUInt<16, 16>(Value)) 16421 Result = DAG.getTargetConstant(Value, dl, TCVT); 16422 break; 16423 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. 16424 if (isShiftedInt<16, 16>(Value)) 16425 Result = DAG.getTargetConstant(Value, dl, TCVT); 16426 break; 16427 case 'K': // "K" is a constant with only the low-order 16 bits nonzero. 16428 if (isUInt<16>(Value)) 16429 Result = DAG.getTargetConstant(Value, dl, TCVT); 16430 break; 16431 case 'M': // "M" is a constant that is greater than 31. 16432 if (Value > 31) 16433 Result = DAG.getTargetConstant(Value, dl, TCVT); 16434 break; 16435 case 'N': // "N" is a positive constant that is an exact power of two. 16436 if (Value > 0 && isPowerOf2_64(Value)) 16437 Result = DAG.getTargetConstant(Value, dl, TCVT); 16438 break; 16439 case 'O': // "O" is the constant zero. 16440 if (Value == 0) 16441 Result = DAG.getTargetConstant(Value, dl, TCVT); 16442 break; 16443 case 'P': // "P" is a constant whose negation is a signed 16-bit constant. 16444 if (isInt<16>(-Value)) 16445 Result = DAG.getTargetConstant(Value, dl, TCVT); 16446 break; 16447 } 16448 break; 16449 } 16450 } 16451 16452 if (Result.getNode()) { 16453 Ops.push_back(Result); 16454 return; 16455 } 16456 16457 // Handle standard constraint letters. 16458 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 16459 } 16460 16461 void PPCTargetLowering::CollectTargetIntrinsicOperands(const CallInst &I, 16462 SmallVectorImpl<SDValue> &Ops, 16463 SelectionDAG &DAG) const { 16464 if (I.getNumOperands() <= 1) 16465 return; 16466 if (!isa<ConstantSDNode>(Ops[1].getNode())) 16467 return; 16468 auto IntrinsicID = cast<ConstantSDNode>(Ops[1].getNode())->getZExtValue(); 16469 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw && 16470 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap) 16471 return; 16472 16473 if (I.hasMetadata("annotation")) { 16474 MDNode *MDN = I.getMetadata("annotation"); 16475 Ops.push_back(DAG.getMDNode(MDN)); 16476 } 16477 } 16478 16479 // isLegalAddressingMode - Return true if the addressing mode represented 16480 // by AM is legal for this target, for a load/store of the specified type. 16481 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, 16482 const AddrMode &AM, Type *Ty, 16483 unsigned AS, 16484 Instruction *I) const { 16485 // Vector type r+i form is supported since power9 as DQ form. We don't check 16486 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC, 16487 // imm form is preferred and the offset can be adjusted to use imm form later 16488 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and 16489 // max offset to check legal addressing mode, we should be a little aggressive 16490 // to contain other offsets for that LSRUse. 16491 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector()) 16492 return false; 16493 16494 // PPC allows a sign-extended 16-bit immediate field. 16495 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) 16496 return false; 16497 16498 // No global is ever allowed as a base. 16499 if (AM.BaseGV) 16500 return false; 16501 16502 // PPC only support r+r, 16503 switch (AM.Scale) { 16504 case 0: // "r+i" or just "i", depending on HasBaseReg. 16505 break; 16506 case 1: 16507 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. 16508 return false; 16509 // Otherwise we have r+r or r+i. 16510 break; 16511 case 2: 16512 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. 16513 return false; 16514 // Allow 2*r as r+r. 16515 break; 16516 default: 16517 // No other scales are supported. 16518 return false; 16519 } 16520 16521 return true; 16522 } 16523 16524 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, 16525 SelectionDAG &DAG) const { 16526 MachineFunction &MF = DAG.getMachineFunction(); 16527 MachineFrameInfo &MFI = MF.getFrameInfo(); 16528 MFI.setReturnAddressIsTaken(true); 16529 16530 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 16531 return SDValue(); 16532 16533 SDLoc dl(Op); 16534 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16535 16536 // Make sure the function does not optimize away the store of the RA to 16537 // the stack. 16538 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 16539 FuncInfo->setLRStoreRequired(); 16540 bool isPPC64 = Subtarget.isPPC64(); 16541 auto PtrVT = getPointerTy(MF.getDataLayout()); 16542 16543 if (Depth > 0) { 16544 // The link register (return address) is saved in the caller's frame 16545 // not the callee's stack frame. So we must get the caller's frame 16546 // address and load the return address at the LR offset from there. 16547 SDValue FrameAddr = 16548 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16549 LowerFRAMEADDR(Op, DAG), MachinePointerInfo()); 16550 SDValue Offset = 16551 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, 16552 isPPC64 ? MVT::i64 : MVT::i32); 16553 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), 16554 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), 16555 MachinePointerInfo()); 16556 } 16557 16558 // Just load the return address off the stack. 16559 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); 16560 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, 16561 MachinePointerInfo()); 16562 } 16563 16564 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, 16565 SelectionDAG &DAG) const { 16566 SDLoc dl(Op); 16567 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 16568 16569 MachineFunction &MF = DAG.getMachineFunction(); 16570 MachineFrameInfo &MFI = MF.getFrameInfo(); 16571 MFI.setFrameAddressIsTaken(true); 16572 16573 EVT PtrVT = getPointerTy(MF.getDataLayout()); 16574 bool isPPC64 = PtrVT == MVT::i64; 16575 16576 // Naked functions never have a frame pointer, and so we use r1. For all 16577 // other functions, this decision must be delayed until during PEI. 16578 unsigned FrameReg; 16579 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 16580 FrameReg = isPPC64 ? PPC::X1 : PPC::R1; 16581 else 16582 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; 16583 16584 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, 16585 PtrVT); 16586 while (Depth--) 16587 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), 16588 FrameAddr, MachinePointerInfo()); 16589 return FrameAddr; 16590 } 16591 16592 // FIXME? Maybe this could be a TableGen attribute on some registers and 16593 // this table could be generated automatically from RegInfo. 16594 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT, 16595 const MachineFunction &MF) const { 16596 bool isPPC64 = Subtarget.isPPC64(); 16597 16598 bool is64Bit = isPPC64 && VT == LLT::scalar(64); 16599 if (!is64Bit && VT != LLT::scalar(32)) 16600 report_fatal_error("Invalid register global variable type"); 16601 16602 Register Reg = StringSwitch<Register>(RegName) 16603 .Case("r1", is64Bit ? PPC::X1 : PPC::R1) 16604 .Case("r2", isPPC64 ? Register() : PPC::R2) 16605 .Case("r13", (is64Bit ? PPC::X13 : PPC::R13)) 16606 .Default(Register()); 16607 16608 if (Reg) 16609 return Reg; 16610 report_fatal_error("Invalid register name global variable"); 16611 } 16612 16613 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const { 16614 // 32-bit SVR4 ABI access everything as got-indirect. 16615 if (Subtarget.is32BitELFABI()) 16616 return true; 16617 16618 // AIX accesses everything indirectly through the TOC, which is similar to 16619 // the GOT. 16620 if (Subtarget.isAIXABI()) 16621 return true; 16622 16623 CodeModel::Model CModel = getTargetMachine().getCodeModel(); 16624 // If it is small or large code model, module locals are accessed 16625 // indirectly by loading their address from .toc/.got. 16626 if (CModel == CodeModel::Small || CModel == CodeModel::Large) 16627 return true; 16628 16629 // JumpTable and BlockAddress are accessed as got-indirect. 16630 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA)) 16631 return true; 16632 16633 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) 16634 return Subtarget.isGVIndirectSymbol(G->getGlobal()); 16635 16636 return false; 16637 } 16638 16639 bool 16640 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 16641 // The PowerPC target isn't yet aware of offsets. 16642 return false; 16643 } 16644 16645 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 16646 const CallInst &I, 16647 MachineFunction &MF, 16648 unsigned Intrinsic) const { 16649 switch (Intrinsic) { 16650 case Intrinsic::ppc_atomicrmw_xchg_i128: 16651 case Intrinsic::ppc_atomicrmw_add_i128: 16652 case Intrinsic::ppc_atomicrmw_sub_i128: 16653 case Intrinsic::ppc_atomicrmw_nand_i128: 16654 case Intrinsic::ppc_atomicrmw_and_i128: 16655 case Intrinsic::ppc_atomicrmw_or_i128: 16656 case Intrinsic::ppc_atomicrmw_xor_i128: 16657 case Intrinsic::ppc_cmpxchg_i128: 16658 Info.opc = ISD::INTRINSIC_W_CHAIN; 16659 Info.memVT = MVT::i128; 16660 Info.ptrVal = I.getArgOperand(0); 16661 Info.offset = 0; 16662 Info.align = Align(16); 16663 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 16664 MachineMemOperand::MOVolatile; 16665 return true; 16666 case Intrinsic::ppc_atomic_load_i128: 16667 Info.opc = ISD::INTRINSIC_W_CHAIN; 16668 Info.memVT = MVT::i128; 16669 Info.ptrVal = I.getArgOperand(0); 16670 Info.offset = 0; 16671 Info.align = Align(16); 16672 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 16673 return true; 16674 case Intrinsic::ppc_atomic_store_i128: 16675 Info.opc = ISD::INTRINSIC_VOID; 16676 Info.memVT = MVT::i128; 16677 Info.ptrVal = I.getArgOperand(2); 16678 Info.offset = 0; 16679 Info.align = Align(16); 16680 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16681 return true; 16682 case Intrinsic::ppc_altivec_lvx: 16683 case Intrinsic::ppc_altivec_lvxl: 16684 case Intrinsic::ppc_altivec_lvebx: 16685 case Intrinsic::ppc_altivec_lvehx: 16686 case Intrinsic::ppc_altivec_lvewx: 16687 case Intrinsic::ppc_vsx_lxvd2x: 16688 case Intrinsic::ppc_vsx_lxvw4x: 16689 case Intrinsic::ppc_vsx_lxvd2x_be: 16690 case Intrinsic::ppc_vsx_lxvw4x_be: 16691 case Intrinsic::ppc_vsx_lxvl: 16692 case Intrinsic::ppc_vsx_lxvll: { 16693 EVT VT; 16694 switch (Intrinsic) { 16695 case Intrinsic::ppc_altivec_lvebx: 16696 VT = MVT::i8; 16697 break; 16698 case Intrinsic::ppc_altivec_lvehx: 16699 VT = MVT::i16; 16700 break; 16701 case Intrinsic::ppc_altivec_lvewx: 16702 VT = MVT::i32; 16703 break; 16704 case Intrinsic::ppc_vsx_lxvd2x: 16705 case Intrinsic::ppc_vsx_lxvd2x_be: 16706 VT = MVT::v2f64; 16707 break; 16708 default: 16709 VT = MVT::v4i32; 16710 break; 16711 } 16712 16713 Info.opc = ISD::INTRINSIC_W_CHAIN; 16714 Info.memVT = VT; 16715 Info.ptrVal = I.getArgOperand(0); 16716 Info.offset = -VT.getStoreSize()+1; 16717 Info.size = 2*VT.getStoreSize()-1; 16718 Info.align = Align(1); 16719 Info.flags = MachineMemOperand::MOLoad; 16720 return true; 16721 } 16722 case Intrinsic::ppc_altivec_stvx: 16723 case Intrinsic::ppc_altivec_stvxl: 16724 case Intrinsic::ppc_altivec_stvebx: 16725 case Intrinsic::ppc_altivec_stvehx: 16726 case Intrinsic::ppc_altivec_stvewx: 16727 case Intrinsic::ppc_vsx_stxvd2x: 16728 case Intrinsic::ppc_vsx_stxvw4x: 16729 case Intrinsic::ppc_vsx_stxvd2x_be: 16730 case Intrinsic::ppc_vsx_stxvw4x_be: 16731 case Intrinsic::ppc_vsx_stxvl: 16732 case Intrinsic::ppc_vsx_stxvll: { 16733 EVT VT; 16734 switch (Intrinsic) { 16735 case Intrinsic::ppc_altivec_stvebx: 16736 VT = MVT::i8; 16737 break; 16738 case Intrinsic::ppc_altivec_stvehx: 16739 VT = MVT::i16; 16740 break; 16741 case Intrinsic::ppc_altivec_stvewx: 16742 VT = MVT::i32; 16743 break; 16744 case Intrinsic::ppc_vsx_stxvd2x: 16745 case Intrinsic::ppc_vsx_stxvd2x_be: 16746 VT = MVT::v2f64; 16747 break; 16748 default: 16749 VT = MVT::v4i32; 16750 break; 16751 } 16752 16753 Info.opc = ISD::INTRINSIC_VOID; 16754 Info.memVT = VT; 16755 Info.ptrVal = I.getArgOperand(1); 16756 Info.offset = -VT.getStoreSize()+1; 16757 Info.size = 2*VT.getStoreSize()-1; 16758 Info.align = Align(1); 16759 Info.flags = MachineMemOperand::MOStore; 16760 return true; 16761 } 16762 case Intrinsic::ppc_stdcx: 16763 case Intrinsic::ppc_stwcx: 16764 case Intrinsic::ppc_sthcx: 16765 case Intrinsic::ppc_stbcx: { 16766 EVT VT; 16767 auto Alignment = Align(8); 16768 switch (Intrinsic) { 16769 case Intrinsic::ppc_stdcx: 16770 VT = MVT::i64; 16771 break; 16772 case Intrinsic::ppc_stwcx: 16773 VT = MVT::i32; 16774 Alignment = Align(4); 16775 break; 16776 case Intrinsic::ppc_sthcx: 16777 VT = MVT::i16; 16778 Alignment = Align(2); 16779 break; 16780 case Intrinsic::ppc_stbcx: 16781 VT = MVT::i8; 16782 Alignment = Align(1); 16783 break; 16784 } 16785 Info.opc = ISD::INTRINSIC_W_CHAIN; 16786 Info.memVT = VT; 16787 Info.ptrVal = I.getArgOperand(0); 16788 Info.offset = 0; 16789 Info.align = Alignment; 16790 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 16791 return true; 16792 } 16793 default: 16794 break; 16795 } 16796 16797 return false; 16798 } 16799 16800 /// It returns EVT::Other if the type should be determined using generic 16801 /// target-independent logic. 16802 EVT PPCTargetLowering::getOptimalMemOpType( 16803 const MemOp &Op, const AttributeList &FuncAttributes) const { 16804 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { 16805 // We should use Altivec/VSX loads and stores when available. For unaligned 16806 // addresses, unaligned VSX loads are only fast starting with the P8. 16807 if (Subtarget.hasAltivec() && Op.size() >= 16 && 16808 (Op.isAligned(Align(16)) || 16809 ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) 16810 return MVT::v4i32; 16811 } 16812 16813 if (Subtarget.isPPC64()) { 16814 return MVT::i64; 16815 } 16816 16817 return MVT::i32; 16818 } 16819 16820 /// Returns true if it is beneficial to convert a load of a constant 16821 /// to just the constant itself. 16822 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 16823 Type *Ty) const { 16824 assert(Ty->isIntegerTy()); 16825 16826 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 16827 return !(BitSize == 0 || BitSize > 64); 16828 } 16829 16830 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 16831 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 16832 return false; 16833 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 16834 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 16835 return NumBits1 == 64 && NumBits2 == 32; 16836 } 16837 16838 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 16839 if (!VT1.isInteger() || !VT2.isInteger()) 16840 return false; 16841 unsigned NumBits1 = VT1.getSizeInBits(); 16842 unsigned NumBits2 = VT2.getSizeInBits(); 16843 return NumBits1 == 64 && NumBits2 == 32; 16844 } 16845 16846 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 16847 // Generally speaking, zexts are not free, but they are free when they can be 16848 // folded with other operations. 16849 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { 16850 EVT MemVT = LD->getMemoryVT(); 16851 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || 16852 (Subtarget.isPPC64() && MemVT == MVT::i32)) && 16853 (LD->getExtensionType() == ISD::NON_EXTLOAD || 16854 LD->getExtensionType() == ISD::ZEXTLOAD)) 16855 return true; 16856 } 16857 16858 // FIXME: Add other cases... 16859 // - 32-bit shifts with a zext to i64 16860 // - zext after ctlz, bswap, etc. 16861 // - zext after and by a constant mask 16862 16863 return TargetLowering::isZExtFree(Val, VT2); 16864 } 16865 16866 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const { 16867 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() && 16868 "invalid fpext types"); 16869 // Extending to float128 is not free. 16870 if (DestVT == MVT::f128) 16871 return false; 16872 return true; 16873 } 16874 16875 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 16876 return isInt<16>(Imm) || isUInt<16>(Imm); 16877 } 16878 16879 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { 16880 return isInt<16>(Imm) || isUInt<16>(Imm); 16881 } 16882 16883 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align, 16884 MachineMemOperand::Flags, 16885 unsigned *Fast) const { 16886 if (DisablePPCUnaligned) 16887 return false; 16888 16889 // PowerPC supports unaligned memory access for simple non-vector types. 16890 // Although accessing unaligned addresses is not as efficient as accessing 16891 // aligned addresses, it is generally more efficient than manual expansion, 16892 // and generally only traps for software emulation when crossing page 16893 // boundaries. 16894 16895 if (!VT.isSimple()) 16896 return false; 16897 16898 if (VT.isFloatingPoint() && !VT.isVector() && 16899 !Subtarget.allowsUnalignedFPAccess()) 16900 return false; 16901 16902 if (VT.getSimpleVT().isVector()) { 16903 if (Subtarget.hasVSX()) { 16904 if (VT != MVT::v2f64 && VT != MVT::v2i64 && 16905 VT != MVT::v4f32 && VT != MVT::v4i32) 16906 return false; 16907 } else { 16908 return false; 16909 } 16910 } 16911 16912 if (VT == MVT::ppcf128) 16913 return false; 16914 16915 if (Fast) 16916 *Fast = 1; 16917 16918 return true; 16919 } 16920 16921 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 16922 SDValue C) const { 16923 // Check integral scalar types. 16924 if (!VT.isScalarInteger()) 16925 return false; 16926 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 16927 if (!ConstNode->getAPIntValue().isSignedIntN(64)) 16928 return false; 16929 // This transformation will generate >= 2 operations. But the following 16930 // cases will generate <= 2 instructions during ISEL. So exclude them. 16931 // 1. If the constant multiplier fits 16 bits, it can be handled by one 16932 // HW instruction, ie. MULLI 16933 // 2. If the multiplier after shifted fits 16 bits, an extra shift 16934 // instruction is needed than case 1, ie. MULLI and RLDICR 16935 int64_t Imm = ConstNode->getSExtValue(); 16936 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 16937 Imm >>= Shift; 16938 if (isInt<16>(Imm)) 16939 return false; 16940 uint64_t UImm = static_cast<uint64_t>(Imm); 16941 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) || 16942 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm)) 16943 return true; 16944 } 16945 return false; 16946 } 16947 16948 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 16949 EVT VT) const { 16950 return isFMAFasterThanFMulAndFAdd( 16951 MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext())); 16952 } 16953 16954 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 16955 Type *Ty) const { 16956 if (Subtarget.hasSPE()) 16957 return false; 16958 switch (Ty->getScalarType()->getTypeID()) { 16959 case Type::FloatTyID: 16960 case Type::DoubleTyID: 16961 return true; 16962 case Type::FP128TyID: 16963 return Subtarget.hasP9Vector(); 16964 default: 16965 return false; 16966 } 16967 } 16968 16969 // FIXME: add more patterns which are not profitable to hoist. 16970 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const { 16971 if (!I->hasOneUse()) 16972 return true; 16973 16974 Instruction *User = I->user_back(); 16975 assert(User && "A single use instruction with no uses."); 16976 16977 switch (I->getOpcode()) { 16978 case Instruction::FMul: { 16979 // Don't break FMA, PowerPC prefers FMA. 16980 if (User->getOpcode() != Instruction::FSub && 16981 User->getOpcode() != Instruction::FAdd) 16982 return true; 16983 16984 const TargetOptions &Options = getTargetMachine().Options; 16985 const Function *F = I->getFunction(); 16986 const DataLayout &DL = F->getParent()->getDataLayout(); 16987 Type *Ty = User->getOperand(0)->getType(); 16988 16989 return !( 16990 isFMAFasterThanFMulAndFAdd(*F, Ty) && 16991 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 16992 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); 16993 } 16994 case Instruction::Load: { 16995 // Don't break "store (load float*)" pattern, this pattern will be combined 16996 // to "store (load int32)" in later InstCombine pass. See function 16997 // combineLoadToOperationType. On PowerPC, loading a float point takes more 16998 // cycles than loading a 32 bit integer. 16999 LoadInst *LI = cast<LoadInst>(I); 17000 // For the loads that combineLoadToOperationType does nothing, like 17001 // ordered load, it should be profitable to hoist them. 17002 // For swifterror load, it can only be used for pointer to pointer type, so 17003 // later type check should get rid of this case. 17004 if (!LI->isUnordered()) 17005 return true; 17006 17007 if (User->getOpcode() != Instruction::Store) 17008 return true; 17009 17010 if (I->getType()->getTypeID() != Type::FloatTyID) 17011 return true; 17012 17013 return false; 17014 } 17015 default: 17016 return true; 17017 } 17018 return true; 17019 } 17020 17021 const MCPhysReg * 17022 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { 17023 // LR is a callee-save register, but we must treat it as clobbered by any call 17024 // site. Hence we include LR in the scratch registers, which are in turn added 17025 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies 17026 // to CTR, which is used by any indirect call. 17027 static const MCPhysReg ScratchRegs[] = { 17028 PPC::X12, PPC::LR8, PPC::CTR8, 0 17029 }; 17030 17031 return ScratchRegs; 17032 } 17033 17034 Register PPCTargetLowering::getExceptionPointerRegister( 17035 const Constant *PersonalityFn) const { 17036 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; 17037 } 17038 17039 Register PPCTargetLowering::getExceptionSelectorRegister( 17040 const Constant *PersonalityFn) const { 17041 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; 17042 } 17043 17044 bool 17045 PPCTargetLowering::shouldExpandBuildVectorWithShuffles( 17046 EVT VT , unsigned DefinedValues) const { 17047 if (VT == MVT::v2i64) 17048 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves 17049 17050 if (Subtarget.hasVSX()) 17051 return true; 17052 17053 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); 17054 } 17055 17056 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { 17057 if (DisableILPPref || Subtarget.enableMachineScheduler()) 17058 return TargetLowering::getSchedulingPreference(N); 17059 17060 return Sched::ILP; 17061 } 17062 17063 // Create a fast isel object. 17064 FastISel * 17065 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, 17066 const TargetLibraryInfo *LibInfo) const { 17067 return PPC::createFastISel(FuncInfo, LibInfo); 17068 } 17069 17070 // 'Inverted' means the FMA opcode after negating one multiplicand. 17071 // For example, (fma -a b c) = (fnmsub a b c) 17072 static unsigned invertFMAOpcode(unsigned Opc) { 17073 switch (Opc) { 17074 default: 17075 llvm_unreachable("Invalid FMA opcode for PowerPC!"); 17076 case ISD::FMA: 17077 return PPCISD::FNMSUB; 17078 case PPCISD::FNMSUB: 17079 return ISD::FMA; 17080 } 17081 } 17082 17083 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG, 17084 bool LegalOps, bool OptForSize, 17085 NegatibleCost &Cost, 17086 unsigned Depth) const { 17087 if (Depth > SelectionDAG::MaxRecursionDepth) 17088 return SDValue(); 17089 17090 unsigned Opc = Op.getOpcode(); 17091 EVT VT = Op.getValueType(); 17092 SDNodeFlags Flags = Op.getNode()->getFlags(); 17093 17094 switch (Opc) { 17095 case PPCISD::FNMSUB: 17096 if (!Op.hasOneUse() || !isTypeLegal(VT)) 17097 break; 17098 17099 const TargetOptions &Options = getTargetMachine().Options; 17100 SDValue N0 = Op.getOperand(0); 17101 SDValue N1 = Op.getOperand(1); 17102 SDValue N2 = Op.getOperand(2); 17103 SDLoc Loc(Op); 17104 17105 NegatibleCost N2Cost = NegatibleCost::Expensive; 17106 SDValue NegN2 = 17107 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1); 17108 17109 if (!NegN2) 17110 return SDValue(); 17111 17112 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c)) 17113 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c)) 17114 // These transformations may change sign of zeroes. For example, 17115 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1. 17116 if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) { 17117 // Try and choose the cheaper one to negate. 17118 NegatibleCost N0Cost = NegatibleCost::Expensive; 17119 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize, 17120 N0Cost, Depth + 1); 17121 17122 NegatibleCost N1Cost = NegatibleCost::Expensive; 17123 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize, 17124 N1Cost, Depth + 1); 17125 17126 if (NegN0 && N0Cost <= N1Cost) { 17127 Cost = std::min(N0Cost, N2Cost); 17128 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags); 17129 } else if (NegN1) { 17130 Cost = std::min(N1Cost, N2Cost); 17131 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags); 17132 } 17133 } 17134 17135 // (fneg (fnmsub a b c)) => (fma a b (fneg c)) 17136 if (isOperationLegal(ISD::FMA, VT)) { 17137 Cost = N2Cost; 17138 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags); 17139 } 17140 17141 break; 17142 } 17143 17144 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize, 17145 Cost, Depth); 17146 } 17147 17148 // Override to enable LOAD_STACK_GUARD lowering on Linux. 17149 bool PPCTargetLowering::useLoadStackGuardNode() const { 17150 if (!Subtarget.isTargetLinux()) 17151 return TargetLowering::useLoadStackGuardNode(); 17152 return true; 17153 } 17154 17155 // Override to disable global variable loading on Linux and insert AIX canary 17156 // word declaration. 17157 void PPCTargetLowering::insertSSPDeclarations(Module &M) const { 17158 if (Subtarget.isAIXABI()) { 17159 M.getOrInsertGlobal(AIXSSPCanaryWordName, 17160 Type::getInt8PtrTy(M.getContext())); 17161 return; 17162 } 17163 if (!Subtarget.isTargetLinux()) 17164 return TargetLowering::insertSSPDeclarations(M); 17165 } 17166 17167 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const { 17168 if (Subtarget.isAIXABI()) 17169 return M.getGlobalVariable(AIXSSPCanaryWordName); 17170 return TargetLowering::getSDagStackGuard(M); 17171 } 17172 17173 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 17174 bool ForCodeSize) const { 17175 if (!VT.isSimple() || !Subtarget.hasVSX()) 17176 return false; 17177 17178 switch(VT.getSimpleVT().SimpleTy) { 17179 default: 17180 // For FP types that are currently not supported by PPC backend, return 17181 // false. Examples: f16, f80. 17182 return false; 17183 case MVT::f32: 17184 case MVT::f64: { 17185 if (Subtarget.hasPrefixInstrs()) { 17186 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP. 17187 return true; 17188 } 17189 bool IsExact; 17190 APSInt IntResult(16, false); 17191 // The rounding mode doesn't really matter because we only care about floats 17192 // that can be converted to integers exactly. 17193 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact); 17194 // For exact values in the range [-16, 15] we can materialize the float. 17195 if (IsExact && IntResult <= 15 && IntResult >= -16) 17196 return true; 17197 return Imm.isZero(); 17198 } 17199 case MVT::ppcf128: 17200 return Imm.isPosZero(); 17201 } 17202 } 17203 17204 // For vector shift operation op, fold 17205 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y) 17206 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, 17207 SelectionDAG &DAG) { 17208 SDValue N0 = N->getOperand(0); 17209 SDValue N1 = N->getOperand(1); 17210 EVT VT = N0.getValueType(); 17211 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 17212 unsigned Opcode = N->getOpcode(); 17213 unsigned TargetOpcode; 17214 17215 switch (Opcode) { 17216 default: 17217 llvm_unreachable("Unexpected shift operation"); 17218 case ISD::SHL: 17219 TargetOpcode = PPCISD::SHL; 17220 break; 17221 case ISD::SRL: 17222 TargetOpcode = PPCISD::SRL; 17223 break; 17224 case ISD::SRA: 17225 TargetOpcode = PPCISD::SRA; 17226 break; 17227 } 17228 17229 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) && 17230 N1->getOpcode() == ISD::AND) 17231 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) 17232 if (Mask->getZExtValue() == OpSizeInBits - 1) 17233 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0)); 17234 17235 return SDValue(); 17236 } 17237 17238 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const { 17239 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17240 return Value; 17241 17242 SDValue N0 = N->getOperand(0); 17243 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 17244 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() || 17245 N0.getOpcode() != ISD::SIGN_EXTEND || 17246 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr || 17247 N->getValueType(0) != MVT::i64) 17248 return SDValue(); 17249 17250 // We can't save an operation here if the value is already extended, and 17251 // the existing shift is easier to combine. 17252 SDValue ExtsSrc = N0.getOperand(0); 17253 if (ExtsSrc.getOpcode() == ISD::TRUNCATE && 17254 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext) 17255 return SDValue(); 17256 17257 SDLoc DL(N0); 17258 SDValue ShiftBy = SDValue(CN1, 0); 17259 // We want the shift amount to be i32 on the extswli, but the shift could 17260 // have an i64. 17261 if (ShiftBy.getValueType() == MVT::i64) 17262 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32); 17263 17264 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0), 17265 ShiftBy); 17266 } 17267 17268 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const { 17269 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17270 return Value; 17271 17272 return SDValue(); 17273 } 17274 17275 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const { 17276 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG)) 17277 return Value; 17278 17279 return SDValue(); 17280 } 17281 17282 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1)) 17283 // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0)) 17284 // When C is zero, the equation (addi Z, -C) can be simplified to Z 17285 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types 17286 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, 17287 const PPCSubtarget &Subtarget) { 17288 if (!Subtarget.isPPC64()) 17289 return SDValue(); 17290 17291 SDValue LHS = N->getOperand(0); 17292 SDValue RHS = N->getOperand(1); 17293 17294 auto isZextOfCompareWithConstant = [](SDValue Op) { 17295 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() || 17296 Op.getValueType() != MVT::i64) 17297 return false; 17298 17299 SDValue Cmp = Op.getOperand(0); 17300 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() || 17301 Cmp.getOperand(0).getValueType() != MVT::i64) 17302 return false; 17303 17304 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) { 17305 int64_t NegConstant = 0 - Constant->getSExtValue(); 17306 // Due to the limitations of the addi instruction, 17307 // -C is required to be [-32768, 32767]. 17308 return isInt<16>(NegConstant); 17309 } 17310 17311 return false; 17312 }; 17313 17314 bool LHSHasPattern = isZextOfCompareWithConstant(LHS); 17315 bool RHSHasPattern = isZextOfCompareWithConstant(RHS); 17316 17317 // If there is a pattern, canonicalize a zext operand to the RHS. 17318 if (LHSHasPattern && !RHSHasPattern) 17319 std::swap(LHS, RHS); 17320 else if (!LHSHasPattern && !RHSHasPattern) 17321 return SDValue(); 17322 17323 SDLoc DL(N); 17324 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue); 17325 SDValue Cmp = RHS.getOperand(0); 17326 SDValue Z = Cmp.getOperand(0); 17327 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1)); 17328 int64_t NegConstant = 0 - Constant->getSExtValue(); 17329 17330 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) { 17331 default: break; 17332 case ISD::SETNE: { 17333 // when C == 0 17334 // --> addze X, (addic Z, -1).carry 17335 // / 17336 // add X, (zext(setne Z, C))-- 17337 // \ when -32768 <= -C <= 32767 && C != 0 17338 // --> addze X, (addic (addi Z, -C), -1).carry 17339 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17340 DAG.getConstant(NegConstant, DL, MVT::i64)); 17341 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17342 SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17343 AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64)); 17344 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17345 SDValue(Addc.getNode(), 1)); 17346 } 17347 case ISD::SETEQ: { 17348 // when C == 0 17349 // --> addze X, (subfic Z, 0).carry 17350 // / 17351 // add X, (zext(sete Z, C))-- 17352 // \ when -32768 <= -C <= 32767 && C != 0 17353 // --> addze X, (subfic (addi Z, -C), 0).carry 17354 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z, 17355 DAG.getConstant(NegConstant, DL, MVT::i64)); 17356 SDValue AddOrZ = NegConstant != 0 ? Add : Z; 17357 SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue), 17358 DAG.getConstant(0, DL, MVT::i64), AddOrZ); 17359 return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64), 17360 SDValue(Subc.getNode(), 1)); 17361 } 17362 } 17363 17364 return SDValue(); 17365 } 17366 17367 // Transform 17368 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to 17369 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2)) 17370 // In this case both C1 and C2 must be known constants. 17371 // C1+C2 must fit into a 34 bit signed integer. 17372 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, 17373 const PPCSubtarget &Subtarget) { 17374 if (!Subtarget.isUsingPCRelativeCalls()) 17375 return SDValue(); 17376 17377 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node. 17378 // If we find that node try to cast the Global Address and the Constant. 17379 SDValue LHS = N->getOperand(0); 17380 SDValue RHS = N->getOperand(1); 17381 17382 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17383 std::swap(LHS, RHS); 17384 17385 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR) 17386 return SDValue(); 17387 17388 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node. 17389 GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0)); 17390 ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS); 17391 17392 // Check that both casts succeeded. 17393 if (!GSDN || !ConstNode) 17394 return SDValue(); 17395 17396 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue(); 17397 SDLoc DL(GSDN); 17398 17399 // The signed int offset needs to fit in 34 bits. 17400 if (!isInt<34>(NewOffset)) 17401 return SDValue(); 17402 17403 // The new global address is a copy of the old global address except 17404 // that it has the updated Offset. 17405 SDValue GA = 17406 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0), 17407 NewOffset, GSDN->getTargetFlags()); 17408 SDValue MatPCRel = 17409 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA); 17410 return MatPCRel; 17411 } 17412 17413 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const { 17414 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget)) 17415 return Value; 17416 17417 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget)) 17418 return Value; 17419 17420 return SDValue(); 17421 } 17422 17423 // Detect TRUNCATE operations on bitcasts of float128 values. 17424 // What we are looking for here is the situtation where we extract a subset 17425 // of bits from a 128 bit float. 17426 // This can be of two forms: 17427 // 1) BITCAST of f128 feeding TRUNCATE 17428 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE 17429 // The reason this is required is because we do not have a legal i128 type 17430 // and so we want to prevent having to store the f128 and then reload part 17431 // of it. 17432 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N, 17433 DAGCombinerInfo &DCI) const { 17434 // If we are using CRBits then try that first. 17435 if (Subtarget.useCRBits()) { 17436 // Check if CRBits did anything and return that if it did. 17437 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI)) 17438 return CRTruncValue; 17439 } 17440 17441 SDLoc dl(N); 17442 SDValue Op0 = N->getOperand(0); 17443 17444 // Looking for a truncate of i128 to i64. 17445 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64) 17446 return SDValue(); 17447 17448 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0; 17449 17450 // SRL feeding TRUNCATE. 17451 if (Op0.getOpcode() == ISD::SRL) { 17452 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 17453 // The right shift has to be by 64 bits. 17454 if (!ConstNode || ConstNode->getZExtValue() != 64) 17455 return SDValue(); 17456 17457 // Switch the element number to extract. 17458 EltToExtract = EltToExtract ? 0 : 1; 17459 // Update Op0 past the SRL. 17460 Op0 = Op0.getOperand(0); 17461 } 17462 17463 // BITCAST feeding a TRUNCATE possibly via SRL. 17464 if (Op0.getOpcode() == ISD::BITCAST && 17465 Op0.getValueType() == MVT::i128 && 17466 Op0.getOperand(0).getValueType() == MVT::f128) { 17467 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0)); 17468 return DCI.DAG.getNode( 17469 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast, 17470 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32)); 17471 } 17472 return SDValue(); 17473 } 17474 17475 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const { 17476 SelectionDAG &DAG = DCI.DAG; 17477 17478 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1)); 17479 if (!ConstOpOrElement) 17480 return SDValue(); 17481 17482 // An imul is usually smaller than the alternative sequence for legal type. 17483 if (DAG.getMachineFunction().getFunction().hasMinSize() && 17484 isOperationLegal(ISD::MUL, N->getValueType(0))) 17485 return SDValue(); 17486 17487 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool { 17488 switch (this->Subtarget.getCPUDirective()) { 17489 default: 17490 // TODO: enhance the condition for subtarget before pwr8 17491 return false; 17492 case PPC::DIR_PWR8: 17493 // type mul add shl 17494 // scalar 4 1 1 17495 // vector 7 2 2 17496 return true; 17497 case PPC::DIR_PWR9: 17498 case PPC::DIR_PWR10: 17499 case PPC::DIR_PWR_FUTURE: 17500 // type mul add shl 17501 // scalar 5 2 2 17502 // vector 7 2 2 17503 17504 // The cycle RATIO of related operations are showed as a table above. 17505 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both 17506 // scalar and vector type. For 2 instrs patterns, add/sub + shl 17507 // are 4, it is always profitable; but for 3 instrs patterns 17508 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6. 17509 // So we should only do it for vector type. 17510 return IsAddOne && IsNeg ? VT.isVector() : true; 17511 } 17512 }; 17513 17514 EVT VT = N->getValueType(0); 17515 SDLoc DL(N); 17516 17517 const APInt &MulAmt = ConstOpOrElement->getAPIntValue(); 17518 bool IsNeg = MulAmt.isNegative(); 17519 APInt MulAmtAbs = MulAmt.abs(); 17520 17521 if ((MulAmtAbs - 1).isPowerOf2()) { 17522 // (mul x, 2^N + 1) => (add (shl x, N), x) 17523 // (mul x, -(2^N + 1)) => -(add (shl x, N), x) 17524 17525 if (!IsProfitable(IsNeg, true, VT)) 17526 return SDValue(); 17527 17528 SDValue Op0 = N->getOperand(0); 17529 SDValue Op1 = 17530 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17531 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT)); 17532 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1); 17533 17534 if (!IsNeg) 17535 return Res; 17536 17537 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 17538 } else if ((MulAmtAbs + 1).isPowerOf2()) { 17539 // (mul x, 2^N - 1) => (sub (shl x, N), x) 17540 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 17541 17542 if (!IsProfitable(IsNeg, false, VT)) 17543 return SDValue(); 17544 17545 SDValue Op0 = N->getOperand(0); 17546 SDValue Op1 = 17547 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0), 17548 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT)); 17549 17550 if (!IsNeg) 17551 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0); 17552 else 17553 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1); 17554 17555 } else { 17556 return SDValue(); 17557 } 17558 } 17559 17560 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this 17561 // in combiner since we need to check SD flags and other subtarget features. 17562 SDValue PPCTargetLowering::combineFMALike(SDNode *N, 17563 DAGCombinerInfo &DCI) const { 17564 SDValue N0 = N->getOperand(0); 17565 SDValue N1 = N->getOperand(1); 17566 SDValue N2 = N->getOperand(2); 17567 SDNodeFlags Flags = N->getFlags(); 17568 EVT VT = N->getValueType(0); 17569 SelectionDAG &DAG = DCI.DAG; 17570 const TargetOptions &Options = getTargetMachine().Options; 17571 unsigned Opc = N->getOpcode(); 17572 bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 17573 bool LegalOps = !DCI.isBeforeLegalizeOps(); 17574 SDLoc Loc(N); 17575 17576 if (!isOperationLegal(ISD::FMA, VT)) 17577 return SDValue(); 17578 17579 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0 17580 // since (fnmsub a b c)=-0 while c-ab=+0. 17581 if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath) 17582 return SDValue(); 17583 17584 // (fma (fneg a) b c) => (fnmsub a b c) 17585 // (fnmsub (fneg a) b c) => (fma a b c) 17586 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize)) 17587 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags); 17588 17589 // (fma a (fneg b) c) => (fnmsub a b c) 17590 // (fnmsub a (fneg b) c) => (fma a b c) 17591 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize)) 17592 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags); 17593 17594 return SDValue(); 17595 } 17596 17597 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 17598 // Only duplicate to increase tail-calls for the 64bit SysV ABIs. 17599 if (!Subtarget.is64BitELFABI()) 17600 return false; 17601 17602 // If not a tail call then no need to proceed. 17603 if (!CI->isTailCall()) 17604 return false; 17605 17606 // If sibling calls have been disabled and tail-calls aren't guaranteed 17607 // there is no reason to duplicate. 17608 auto &TM = getTargetMachine(); 17609 if (!TM.Options.GuaranteedTailCallOpt && DisableSCO) 17610 return false; 17611 17612 // Can't tail call a function called indirectly, or if it has variadic args. 17613 const Function *Callee = CI->getCalledFunction(); 17614 if (!Callee || Callee->isVarArg()) 17615 return false; 17616 17617 // Make sure the callee and caller calling conventions are eligible for tco. 17618 const Function *Caller = CI->getParent()->getParent(); 17619 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(), 17620 CI->getCallingConv())) 17621 return false; 17622 17623 // If the function is local then we have a good chance at tail-calling it 17624 return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee); 17625 } 17626 17627 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 17628 if (!Subtarget.hasVSX()) 17629 return false; 17630 if (Subtarget.hasP9Vector() && VT == MVT::f128) 17631 return true; 17632 return VT == MVT::f32 || VT == MVT::f64 || 17633 VT == MVT::v4f32 || VT == MVT::v2f64; 17634 } 17635 17636 bool PPCTargetLowering:: 17637 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const { 17638 const Value *Mask = AndI.getOperand(1); 17639 // If the mask is suitable for andi. or andis. we should sink the and. 17640 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) { 17641 // Can't handle constants wider than 64-bits. 17642 if (CI->getBitWidth() > 64) 17643 return false; 17644 int64_t ConstVal = CI->getZExtValue(); 17645 return isUInt<16>(ConstVal) || 17646 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF)); 17647 } 17648 17649 // For non-constant masks, we can always use the record-form and. 17650 return true; 17651 } 17652 17653 // For type v4i32/v8ii16/v16i8, transform 17654 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (abdu a, b) 17655 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (abdu a, b) 17656 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (abdu a, b) 17657 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (abdu a, b) 17658 // TODO: Move this to DAGCombiner? 17659 SDValue PPCTargetLowering::combineVSelect(SDNode *N, 17660 DAGCombinerInfo &DCI) const { 17661 assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here"); 17662 assert(Subtarget.hasP9Altivec() && 17663 "Only combine this when P9 altivec supported!"); 17664 17665 SelectionDAG &DAG = DCI.DAG; 17666 SDLoc dl(N); 17667 SDValue Cond = N->getOperand(0); 17668 SDValue TrueOpnd = N->getOperand(1); 17669 SDValue FalseOpnd = N->getOperand(2); 17670 EVT VT = N->getOperand(1).getValueType(); 17671 17672 if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB || 17673 FalseOpnd.getOpcode() != ISD::SUB) 17674 return SDValue(); 17675 17676 // ABSD only available for type v4i32/v8i16/v16i8 17677 if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8) 17678 return SDValue(); 17679 17680 // At least to save one more dependent computation 17681 if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse())) 17682 return SDValue(); 17683 17684 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 17685 17686 // Can only handle unsigned comparison here 17687 switch (CC) { 17688 default: 17689 return SDValue(); 17690 case ISD::SETUGT: 17691 case ISD::SETUGE: 17692 break; 17693 case ISD::SETULT: 17694 case ISD::SETULE: 17695 std::swap(TrueOpnd, FalseOpnd); 17696 break; 17697 } 17698 17699 SDValue CmpOpnd1 = Cond.getOperand(0); 17700 SDValue CmpOpnd2 = Cond.getOperand(1); 17701 17702 // SETCC CmpOpnd1 CmpOpnd2 cond 17703 // TrueOpnd = CmpOpnd1 - CmpOpnd2 17704 // FalseOpnd = CmpOpnd2 - CmpOpnd1 17705 if (TrueOpnd.getOperand(0) == CmpOpnd1 && 17706 TrueOpnd.getOperand(1) == CmpOpnd2 && 17707 FalseOpnd.getOperand(0) == CmpOpnd2 && 17708 FalseOpnd.getOperand(1) == CmpOpnd1) { 17709 return DAG.getNode(ISD::ABDU, dl, N->getOperand(1).getValueType(), CmpOpnd1, 17710 CmpOpnd2, DAG.getTargetConstant(0, dl, MVT::i32)); 17711 } 17712 17713 return SDValue(); 17714 } 17715 17716 /// getAddrModeForFlags - Based on the set of address flags, select the most 17717 /// optimal instruction format to match by. 17718 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const { 17719 // This is not a node we should be handling here. 17720 if (Flags == PPC::MOF_None) 17721 return PPC::AM_None; 17722 // Unaligned D-Forms are tried first, followed by the aligned D-Forms. 17723 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm)) 17724 if ((Flags & FlagSet) == FlagSet) 17725 return PPC::AM_DForm; 17726 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm)) 17727 if ((Flags & FlagSet) == FlagSet) 17728 return PPC::AM_DSForm; 17729 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm)) 17730 if ((Flags & FlagSet) == FlagSet) 17731 return PPC::AM_DQForm; 17732 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm)) 17733 if ((Flags & FlagSet) == FlagSet) 17734 return PPC::AM_PrefixDForm; 17735 // If no other forms are selected, return an X-Form as it is the most 17736 // general addressing mode. 17737 return PPC::AM_XForm; 17738 } 17739 17740 /// Set alignment flags based on whether or not the Frame Index is aligned. 17741 /// Utilized when computing flags for address computation when selecting 17742 /// load and store instructions. 17743 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, 17744 SelectionDAG &DAG) { 17745 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR)); 17746 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N); 17747 if (!FI) 17748 return; 17749 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 17750 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value(); 17751 // If this is (add $FI, $S16Imm), the alignment flags are already set 17752 // based on the immediate. We just need to clear the alignment flags 17753 // if the FI alignment is weaker. 17754 if ((FrameIndexAlign % 4) != 0) 17755 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4; 17756 if ((FrameIndexAlign % 16) != 0) 17757 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16; 17758 // If the address is a plain FrameIndex, set alignment flags based on 17759 // FI alignment. 17760 if (!IsAdd) { 17761 if ((FrameIndexAlign % 4) == 0) 17762 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17763 if ((FrameIndexAlign % 16) == 0) 17764 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17765 } 17766 } 17767 17768 /// Given a node, compute flags that are used for address computation when 17769 /// selecting load and store instructions. The flags computed are stored in 17770 /// FlagSet. This function takes into account whether the node is a constant, 17771 /// an ADD, OR, or a constant, and computes the address flags accordingly. 17772 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, 17773 SelectionDAG &DAG) { 17774 // Set the alignment flags for the node depending on if the node is 17775 // 4-byte or 16-byte aligned. 17776 auto SetAlignFlagsForImm = [&](uint64_t Imm) { 17777 if ((Imm & 0x3) == 0) 17778 FlagSet |= PPC::MOF_RPlusSImm16Mult4; 17779 if ((Imm & 0xf) == 0) 17780 FlagSet |= PPC::MOF_RPlusSImm16Mult16; 17781 }; 17782 17783 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { 17784 // All 32-bit constants can be computed as LIS + Disp. 17785 const APInt &ConstImm = CN->getAPIntValue(); 17786 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants. 17787 FlagSet |= PPC::MOF_AddrIsSImm32; 17788 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17789 setAlignFlagsForFI(N, FlagSet, DAG); 17790 } 17791 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants. 17792 FlagSet |= PPC::MOF_RPlusSImm34; 17793 else // Let constant materialization handle large constants. 17794 FlagSet |= PPC::MOF_NotAddNorCst; 17795 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) { 17796 // This address can be represented as an addition of: 17797 // - Register + Imm16 (possibly a multiple of 4/16) 17798 // - Register + Imm34 17799 // - Register + PPCISD::Lo 17800 // - Register + Register 17801 // In any case, we won't have to match this as Base + Zero. 17802 SDValue RHS = N.getOperand(1); 17803 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) { 17804 const APInt &ConstImm = CN->getAPIntValue(); 17805 if (ConstImm.isSignedIntN(16)) { 17806 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates. 17807 SetAlignFlagsForImm(ConstImm.getZExtValue()); 17808 setAlignFlagsForFI(N, FlagSet, DAG); 17809 } 17810 if (ConstImm.isSignedIntN(34)) 17811 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates. 17812 else 17813 FlagSet |= PPC::MOF_RPlusR; // Register. 17814 } else if (RHS.getOpcode() == PPCISD::Lo && 17815 !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue()) 17816 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo. 17817 else 17818 FlagSet |= PPC::MOF_RPlusR; 17819 } else { // The address computation is not a constant or an addition. 17820 setAlignFlagsForFI(N, FlagSet, DAG); 17821 FlagSet |= PPC::MOF_NotAddNorCst; 17822 } 17823 } 17824 17825 static bool isPCRelNode(SDValue N) { 17826 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR || 17827 isValidPCRelNode<ConstantPoolSDNode>(N) || 17828 isValidPCRelNode<GlobalAddressSDNode>(N) || 17829 isValidPCRelNode<JumpTableSDNode>(N) || 17830 isValidPCRelNode<BlockAddressSDNode>(N)); 17831 } 17832 17833 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute 17834 /// the address flags of the load/store instruction that is to be matched. 17835 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N, 17836 SelectionDAG &DAG) const { 17837 unsigned FlagSet = PPC::MOF_None; 17838 17839 // Compute subtarget flags. 17840 if (!Subtarget.hasP9Vector()) 17841 FlagSet |= PPC::MOF_SubtargetBeforeP9; 17842 else { 17843 FlagSet |= PPC::MOF_SubtargetP9; 17844 if (Subtarget.hasPrefixInstrs()) 17845 FlagSet |= PPC::MOF_SubtargetP10; 17846 } 17847 if (Subtarget.hasSPE()) 17848 FlagSet |= PPC::MOF_SubtargetSPE; 17849 17850 // Check if we have a PCRel node and return early. 17851 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N)) 17852 return FlagSet; 17853 17854 // If the node is the paired load/store intrinsics, compute flags for 17855 // address computation and return early. 17856 unsigned ParentOp = Parent->getOpcode(); 17857 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) || 17858 (ParentOp == ISD::INTRINSIC_VOID))) { 17859 unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue(); 17860 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) { 17861 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp) 17862 ? Parent->getOperand(2) 17863 : Parent->getOperand(3); 17864 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG); 17865 FlagSet |= PPC::MOF_Vector; 17866 return FlagSet; 17867 } 17868 } 17869 17870 // Mark this as something we don't want to handle here if it is atomic 17871 // or pre-increment instruction. 17872 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent)) 17873 if (LSB->isIndexed()) 17874 return PPC::MOF_None; 17875 17876 // Compute in-memory type flags. This is based on if there are scalars, 17877 // floats or vectors. 17878 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent); 17879 assert(MN && "Parent should be a MemSDNode!"); 17880 EVT MemVT = MN->getMemoryVT(); 17881 unsigned Size = MemVT.getSizeInBits(); 17882 if (MemVT.isScalarInteger()) { 17883 assert(Size <= 128 && 17884 "Not expecting scalar integers larger than 16 bytes!"); 17885 if (Size < 32) 17886 FlagSet |= PPC::MOF_SubWordInt; 17887 else if (Size == 32) 17888 FlagSet |= PPC::MOF_WordInt; 17889 else 17890 FlagSet |= PPC::MOF_DoubleWordInt; 17891 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors. 17892 if (Size == 128) 17893 FlagSet |= PPC::MOF_Vector; 17894 else if (Size == 256) { 17895 assert(Subtarget.pairedVectorMemops() && 17896 "256-bit vectors are only available when paired vector memops is " 17897 "enabled!"); 17898 FlagSet |= PPC::MOF_Vector; 17899 } else 17900 llvm_unreachable("Not expecting illegal vectors!"); 17901 } else { // Floating point type: can be scalar, f128 or vector types. 17902 if (Size == 32 || Size == 64) 17903 FlagSet |= PPC::MOF_ScalarFloat; 17904 else if (MemVT == MVT::f128 || MemVT.isVector()) 17905 FlagSet |= PPC::MOF_Vector; 17906 else 17907 llvm_unreachable("Not expecting illegal scalar floats!"); 17908 } 17909 17910 // Compute flags for address computation. 17911 computeFlagsForAddressComputation(N, FlagSet, DAG); 17912 17913 // Compute type extension flags. 17914 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) { 17915 switch (LN->getExtensionType()) { 17916 case ISD::SEXTLOAD: 17917 FlagSet |= PPC::MOF_SExt; 17918 break; 17919 case ISD::EXTLOAD: 17920 case ISD::ZEXTLOAD: 17921 FlagSet |= PPC::MOF_ZExt; 17922 break; 17923 case ISD::NON_EXTLOAD: 17924 FlagSet |= PPC::MOF_NoExt; 17925 break; 17926 } 17927 } else 17928 FlagSet |= PPC::MOF_NoExt; 17929 17930 // For integers, no extension is the same as zero extension. 17931 // We set the extension mode to zero extension so we don't have 17932 // to add separate entries in AddrModesMap for loads and stores. 17933 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) { 17934 FlagSet |= PPC::MOF_ZExt; 17935 FlagSet &= ~PPC::MOF_NoExt; 17936 } 17937 17938 // If we don't have prefixed instructions, 34-bit constants should be 17939 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms. 17940 bool IsNonP1034BitConst = 17941 ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) & 17942 FlagSet) == PPC::MOF_RPlusSImm34; 17943 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR && 17944 IsNonP1034BitConst) 17945 FlagSet |= PPC::MOF_NotAddNorCst; 17946 17947 return FlagSet; 17948 } 17949 17950 /// SelectForceXFormMode - Given the specified address, force it to be 17951 /// represented as an indexed [r+r] operation (an XForm instruction). 17952 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp, 17953 SDValue &Base, 17954 SelectionDAG &DAG) const { 17955 17956 PPC::AddrMode Mode = PPC::AM_XForm; 17957 int16_t ForceXFormImm = 0; 17958 if (provablyDisjointOr(DAG, N) && 17959 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) { 17960 Disp = N.getOperand(0); 17961 Base = N.getOperand(1); 17962 return Mode; 17963 } 17964 17965 // If the address is the result of an add, we will utilize the fact that the 17966 // address calculation includes an implicit add. However, we can reduce 17967 // register pressure if we do not materialize a constant just for use as the 17968 // index register. We only get rid of the add if it is not an add of a 17969 // value and a 16-bit signed constant and both have a single use. 17970 if (N.getOpcode() == ISD::ADD && 17971 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) || 17972 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) { 17973 Disp = N.getOperand(0); 17974 Base = N.getOperand(1); 17975 return Mode; 17976 } 17977 17978 // Otherwise, use R0 as the base register. 17979 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 17980 N.getValueType()); 17981 Base = N; 17982 17983 return Mode; 17984 } 17985 17986 bool PPCTargetLowering::splitValueIntoRegisterParts( 17987 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 17988 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const { 17989 EVT ValVT = Val.getValueType(); 17990 // If we are splitting a scalar integer into f64 parts (i.e. so they 17991 // can be placed into VFRC registers), we need to zero extend and 17992 // bitcast the values. This will ensure the value is placed into a 17993 // VSR using direct moves or stack operations as needed. 17994 if (PartVT == MVT::f64 && 17995 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) { 17996 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 17997 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val); 17998 Parts[0] = Val; 17999 return true; 18000 } 18001 return false; 18002 } 18003 18004 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op, 18005 SelectionDAG &DAG) const { 18006 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 18007 TargetLowering::CallLoweringInfo CLI(DAG); 18008 EVT RetVT = Op.getValueType(); 18009 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 18010 SDValue Callee = 18011 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout())); 18012 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false); 18013 TargetLowering::ArgListTy Args; 18014 TargetLowering::ArgListEntry Entry; 18015 for (const SDValue &N : Op->op_values()) { 18016 EVT ArgVT = N.getValueType(); 18017 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 18018 Entry.Node = N; 18019 Entry.Ty = ArgTy; 18020 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend); 18021 Entry.IsZExt = !Entry.IsSExt; 18022 Args.push_back(Entry); 18023 } 18024 18025 SDValue InChain = DAG.getEntryNode(); 18026 SDValue TCChain = InChain; 18027 const Function &F = DAG.getMachineFunction().getFunction(); 18028 bool isTailCall = 18029 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) && 18030 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy()); 18031 if (isTailCall) 18032 InChain = TCChain; 18033 CLI.setDebugLoc(SDLoc(Op)) 18034 .setChain(InChain) 18035 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args)) 18036 .setTailCall(isTailCall) 18037 .setSExtResult(SignExtend) 18038 .setZExtResult(!SignExtend) 18039 .setIsPostTypeLegalization(true); 18040 return TLI.LowerCallTo(CLI).first; 18041 } 18042 18043 SDValue PPCTargetLowering::lowerLibCallBasedOnType( 18044 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op, 18045 SelectionDAG &DAG) const { 18046 if (Op.getValueType() == MVT::f32) 18047 return lowerToLibCall(LibCallFloatName, Op, DAG); 18048 18049 if (Op.getValueType() == MVT::f64) 18050 return lowerToLibCall(LibCallDoubleName, Op, DAG); 18051 18052 return SDValue(); 18053 } 18054 18055 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const { 18056 SDNodeFlags Flags = Op.getNode()->getFlags(); 18057 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() && 18058 Flags.hasNoNaNs() && Flags.hasNoInfs(); 18059 } 18060 18061 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const { 18062 return Op.getNode()->getFlags().hasApproximateFuncs(); 18063 } 18064 18065 bool PPCTargetLowering::isScalarMASSConversionEnabled() const { 18066 return getTargetMachine().Options.PPCGenScalarMASSEntries; 18067 } 18068 18069 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName, 18070 const char *LibCallFloatName, 18071 const char *LibCallDoubleNameFinite, 18072 const char *LibCallFloatNameFinite, 18073 SDValue Op, 18074 SelectionDAG &DAG) const { 18075 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op)) 18076 return SDValue(); 18077 18078 if (!isLowringToMASSFiniteSafe(Op)) 18079 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op, 18080 DAG); 18081 18082 return lowerLibCallBasedOnType(LibCallFloatNameFinite, 18083 LibCallDoubleNameFinite, Op, DAG); 18084 } 18085 18086 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const { 18087 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite", 18088 "__xl_powf_finite", Op, DAG); 18089 } 18090 18091 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const { 18092 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite", 18093 "__xl_sinf_finite", Op, DAG); 18094 } 18095 18096 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const { 18097 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite", 18098 "__xl_cosf_finite", Op, DAG); 18099 } 18100 18101 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const { 18102 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite", 18103 "__xl_logf_finite", Op, DAG); 18104 } 18105 18106 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const { 18107 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite", 18108 "__xl_log10f_finite", Op, DAG); 18109 } 18110 18111 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const { 18112 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite", 18113 "__xl_expf_finite", Op, DAG); 18114 } 18115 18116 // If we happen to match to an aligned D-Form, check if the Frame Index is 18117 // adequately aligned. If it is not, reset the mode to match to X-Form. 18118 static void setXFormForUnalignedFI(SDValue N, unsigned Flags, 18119 PPC::AddrMode &Mode) { 18120 if (!isa<FrameIndexSDNode>(N)) 18121 return; 18122 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) || 18123 (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16))) 18124 Mode = PPC::AM_XForm; 18125 } 18126 18127 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), 18128 /// compute the address flags of the node, get the optimal address mode based 18129 /// on the flags, and set the Base and Disp based on the address mode. 18130 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent, 18131 SDValue N, SDValue &Disp, 18132 SDValue &Base, 18133 SelectionDAG &DAG, 18134 MaybeAlign Align) const { 18135 SDLoc DL(Parent); 18136 18137 // Compute the address flags. 18138 unsigned Flags = computeMOFlags(Parent, N, DAG); 18139 18140 // Get the optimal address mode based on the Flags. 18141 PPC::AddrMode Mode = getAddrModeForFlags(Flags); 18142 18143 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned. 18144 // Select an X-Form load if it is not. 18145 setXFormForUnalignedFI(N, Flags, Mode); 18146 18147 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node. 18148 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) { 18149 assert(Subtarget.isUsingPCRelativeCalls() && 18150 "Must be using PC-Relative calls when a valid PC-Relative node is " 18151 "present!"); 18152 Mode = PPC::AM_PCRel; 18153 } 18154 18155 // Set Base and Disp accordingly depending on the address mode. 18156 switch (Mode) { 18157 case PPC::AM_DForm: 18158 case PPC::AM_DSForm: 18159 case PPC::AM_DQForm: { 18160 // This is a register plus a 16-bit immediate. The base will be the 18161 // register and the displacement will be the immediate unless it 18162 // isn't sufficiently aligned. 18163 if (Flags & PPC::MOF_RPlusSImm16) { 18164 SDValue Op0 = N.getOperand(0); 18165 SDValue Op1 = N.getOperand(1); 18166 int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue(); 18167 if (!Align || isAligned(*Align, Imm)) { 18168 Disp = DAG.getTargetConstant(Imm, DL, N.getValueType()); 18169 Base = Op0; 18170 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) { 18171 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18172 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 18173 } 18174 break; 18175 } 18176 } 18177 // This is a register plus the @lo relocation. The base is the register 18178 // and the displacement is the global address. 18179 else if (Flags & PPC::MOF_RPlusLo) { 18180 Disp = N.getOperand(1).getOperand(0); // The global address. 18181 assert(Disp.getOpcode() == ISD::TargetGlobalAddress || 18182 Disp.getOpcode() == ISD::TargetGlobalTLSAddress || 18183 Disp.getOpcode() == ISD::TargetConstantPool || 18184 Disp.getOpcode() == ISD::TargetJumpTable); 18185 Base = N.getOperand(0); 18186 break; 18187 } 18188 // This is a constant address at most 32 bits. The base will be 18189 // zero or load-immediate-shifted and the displacement will be 18190 // the low 16 bits of the address. 18191 else if (Flags & PPC::MOF_AddrIsSImm32) { 18192 auto *CN = cast<ConstantSDNode>(N); 18193 EVT CNType = CN->getValueType(0); 18194 uint64_t CNImm = CN->getZExtValue(); 18195 // If this address fits entirely in a 16-bit sext immediate field, codegen 18196 // this as "d, 0". 18197 int16_t Imm; 18198 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) { 18199 Disp = DAG.getTargetConstant(Imm, DL, CNType); 18200 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 18201 CNType); 18202 break; 18203 } 18204 // Handle 32-bit sext immediate with LIS + Addr mode. 18205 if ((CNType == MVT::i32 || isInt<32>(CNImm)) && 18206 (!Align || isAligned(*Align, CNImm))) { 18207 int32_t Addr = (int32_t)CNImm; 18208 // Otherwise, break this down into LIS + Disp. 18209 Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32); 18210 Base = 18211 DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32); 18212 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8; 18213 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0); 18214 break; 18215 } 18216 } 18217 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable. 18218 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout())); 18219 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { 18220 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18221 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); 18222 } else 18223 Base = N; 18224 break; 18225 } 18226 case PPC::AM_PrefixDForm: { 18227 int64_t Imm34 = 0; 18228 unsigned Opcode = N.getOpcode(); 18229 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) && 18230 (isIntS34Immediate(N.getOperand(1), Imm34))) { 18231 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate. 18232 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18233 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) 18234 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); 18235 else 18236 Base = N.getOperand(0); 18237 } else if (isIntS34Immediate(N, Imm34)) { 18238 // The address is a 34-bit signed immediate. 18239 Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType()); 18240 Base = DAG.getRegister(PPC::ZERO8, N.getValueType()); 18241 } 18242 break; 18243 } 18244 case PPC::AM_PCRel: { 18245 // When selecting PC-Relative instructions, "Base" is not utilized as 18246 // we select the address as [PC+imm]. 18247 Disp = N; 18248 break; 18249 } 18250 case PPC::AM_None: 18251 break; 18252 default: { // By default, X-Form is always available to be selected. 18253 // When a frame index is not aligned, we also match by XForm. 18254 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N); 18255 Base = FI ? N : N.getOperand(1); 18256 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, 18257 N.getValueType()) 18258 : N.getOperand(0); 18259 break; 18260 } 18261 } 18262 return Mode; 18263 } 18264 18265 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC, 18266 bool Return, 18267 bool IsVarArg) const { 18268 switch (CC) { 18269 case CallingConv::Cold: 18270 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS); 18271 default: 18272 return CC_PPC64_ELF_FIS; 18273 } 18274 } 18275 18276 bool PPCTargetLowering::shouldInlineQuadwordAtomics() const { 18277 // TODO: 16-byte atomic type support for AIX is in progress; we should be able 18278 // to inline 16-byte atomic ops on AIX too in the future. 18279 return Subtarget.isPPC64() && 18280 (EnableQuadwordAtomics || !Subtarget.getTargetTriple().isOSAIX()) && 18281 Subtarget.hasQuadwordAtomics(); 18282 } 18283 18284 TargetLowering::AtomicExpansionKind 18285 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 18286 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 18287 if (shouldInlineQuadwordAtomics() && Size == 128) 18288 return AtomicExpansionKind::MaskedIntrinsic; 18289 18290 switch (AI->getOperation()) { 18291 case AtomicRMWInst::UIncWrap: 18292 case AtomicRMWInst::UDecWrap: 18293 return AtomicExpansionKind::CmpXChg; 18294 default: 18295 return TargetLowering::shouldExpandAtomicRMWInIR(AI); 18296 } 18297 18298 llvm_unreachable("unreachable atomicrmw operation"); 18299 } 18300 18301 TargetLowering::AtomicExpansionKind 18302 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const { 18303 unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits(); 18304 if (shouldInlineQuadwordAtomics() && Size == 128) 18305 return AtomicExpansionKind::MaskedIntrinsic; 18306 return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI); 18307 } 18308 18309 static Intrinsic::ID 18310 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) { 18311 switch (BinOp) { 18312 default: 18313 llvm_unreachable("Unexpected AtomicRMW BinOp"); 18314 case AtomicRMWInst::Xchg: 18315 return Intrinsic::ppc_atomicrmw_xchg_i128; 18316 case AtomicRMWInst::Add: 18317 return Intrinsic::ppc_atomicrmw_add_i128; 18318 case AtomicRMWInst::Sub: 18319 return Intrinsic::ppc_atomicrmw_sub_i128; 18320 case AtomicRMWInst::And: 18321 return Intrinsic::ppc_atomicrmw_and_i128; 18322 case AtomicRMWInst::Or: 18323 return Intrinsic::ppc_atomicrmw_or_i128; 18324 case AtomicRMWInst::Xor: 18325 return Intrinsic::ppc_atomicrmw_xor_i128; 18326 case AtomicRMWInst::Nand: 18327 return Intrinsic::ppc_atomicrmw_nand_i128; 18328 } 18329 } 18330 18331 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic( 18332 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 18333 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 18334 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18335 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18336 Type *ValTy = Incr->getType(); 18337 assert(ValTy->getPrimitiveSizeInBits() == 128); 18338 Function *RMW = Intrinsic::getDeclaration( 18339 M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation())); 18340 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18341 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo"); 18342 Value *IncrHi = 18343 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi"); 18344 Value *Addr = 18345 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18346 Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi}); 18347 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18348 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18349 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18350 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18351 return Builder.CreateOr( 18352 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18353 } 18354 18355 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 18356 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 18357 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 18358 assert(shouldInlineQuadwordAtomics() && "Only support quadword now"); 18359 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 18360 Type *ValTy = CmpVal->getType(); 18361 assert(ValTy->getPrimitiveSizeInBits() == 128); 18362 Function *IntCmpXchg = 18363 Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128); 18364 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 18365 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo"); 18366 Value *CmpHi = 18367 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi"); 18368 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo"); 18369 Value *NewHi = 18370 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi"); 18371 Value *Addr = 18372 Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext())); 18373 emitLeadingFence(Builder, CI, Ord); 18374 Value *LoHi = 18375 Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi}); 18376 emitTrailingFence(Builder, CI, Ord); 18377 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 18378 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 18379 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 18380 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 18381 return Builder.CreateOr( 18382 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 18383 } 18384